repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
Horizon-Engineering/Android_application_ILS | Horizon/app/src/main/java/com/homa/hls/socketconn/CommonsNet.java | 2831 | package com.homa.hls.socketconn;
import com.allin.activity.action.SysApplication;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class CommonsNet {
byte[] MacAddress;
byte mConnWay;
DatagramPacket mDatagramPacket;
private String mIP;
private int mPort;
byte[] password;
public CommonsNet() {
this.mPort = 0;
this.mDatagramPacket = null;
this.mConnWay = (byte) 0;
this.MacAddress = null;
this.password = null;
this.mIP = "";
this.mPort = 0;
}
public DatagramSocket getmDatagramSocket() {
SysApplication.getInstance();
return SysApplication.mDatagramSocket;
}
public void init(String ip, int port, byte[] macaddress, byte[] password) {
this.mIP = ip;
this.mPort = port;
this.MacAddress = macaddress;
this.password = password;
}
public void send(DatagramPacket packet) throws IOException {
SysApplication.getInstance();
if (SysApplication.mDatagramSocket != null) {
SysApplication.getInstance();
SysApplication.mDatagramSocket.send(packet);
}
}
public void receive(DatagramPacket packet) throws IOException {
if (packet != null) {
SysApplication.getInstance();
if (SysApplication.mDatagramSocket != null) {
SysApplication.getInstance();
SysApplication.mDatagramSocket.receive(packet);
}
}
}
public int getmPort() {
return this.mPort;
}
public String getmIP() {
return this.mIP;
}
public void setmIP(String mIP) {
this.mIP = mIP;
}
public void setmPort(int mPort) {
this.mPort = mPort;
}
public DatagramPacket getmDatagramPacket() {
return this.mDatagramPacket;
}
public void setmDatagramPacket(DatagramPacket mDatagramPacket) {
this.mDatagramPacket = mDatagramPacket;
}
public byte getmConnWay() {
return this.mConnWay;
}
public void setmConnWay(byte mConnWay) {
this.mConnWay = mConnWay;
}
public byte[] getMacAddress() {
return this.MacAddress;
}
public void setMacAddress(byte[] macAddress) {
this.MacAddress = macAddress;
}
public byte[] getPassword() {
return this.password;
}
public void setPassword(byte[] password) {
this.password = password;
}
public DatagramPacket CreateDatagramPacket(byte[] data) throws UnknownHostException {
this.mDatagramPacket = new DatagramPacket(data, data.length, InetAddress.getByName(this.mIP), getmPort());
return this.mDatagramPacket;
}
}
| apache-2.0 |
JNOSQL/artemis-extension | couchbase-extension/src/test/java/org/eclipse/jnosql/mapping/couchbase/document/CouchbaseDocumentRepositoryProxyTest.java | 3037 | /*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*/
package org.eclipse.jnosql.mapping.couchbase.document;
import com.couchbase.client.java.document.json.JsonObject;
import jakarta.nosql.mapping.document.DocumentRepositoryProducer;
import org.eclipse.jnosql.mapping.test.CDIExtension;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import javax.inject.Inject;
import java.lang.reflect.Proxy;
import java.time.Duration;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@CDIExtension
public class CouchbaseDocumentRepositoryProxyTest {
private CouchbaseTemplate template;
@Inject
private DocumentRepositoryProducer producer;
private PersonRepository personRepository;
@BeforeEach
public void setUp() {
this.template = Mockito.mock(CouchbaseTemplate.class);
CouchbaseDocumentRepositoryProxy handler = new CouchbaseDocumentRepositoryProxy(template,
PersonRepository.class, producer.get(PersonRepository.class, template));
when(template.insert(any(Person.class))).thenReturn(new Person());
when(template.insert(any(Person.class), any(Duration.class))).thenReturn(new Person());
when(template.update(any(Person.class))).thenReturn(new Person());
personRepository = (PersonRepository) Proxy.newProxyInstance(PersonRepository.class.getClassLoader(),
new Class[]{PersonRepository.class},
handler);
}
@Test
public void shouldFindAll() {
personRepository.findAll();
verify(template).n1qlQuery("select * from Person");
}
@Test
public void shouldFindByNameN1ql() {
ArgumentCaptor<JsonObject> captor = ArgumentCaptor.forClass(JsonObject.class);
personRepository.findByName("Ada");
verify(template).n1qlQuery(Mockito.eq("select * from Person where name = $name"), captor.capture());
JsonObject value = captor.getValue();
assertEquals("Ada", value.getString("name"));
}
interface PersonRepository extends CouchbaseRepository<Person, String> {
@N1QL("select * from Person")
List<Person> findAll();
@N1QL("select * from Person where name = $name")
List<Person> findByName(@Param("name") String name);
}
} | apache-2.0 |
nafae/developer | modules/dfa_axis/src/main/java/com/google/api/ads/dfa/axis/v1_19/RichMediaExitWindowProperties.java | 12070 | /**
* RichMediaExitWindowProperties.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfa.axis.v1_19;
public class RichMediaExitWindowProperties implements java.io.Serializable {
private int height;
private int left;
private boolean locationBar;
private boolean menuBar;
private boolean resizable;
private boolean scrollBars;
private boolean statusBar;
private boolean toolBar;
private int top;
private int width;
public RichMediaExitWindowProperties() {
}
public RichMediaExitWindowProperties(
int height,
int left,
boolean locationBar,
boolean menuBar,
boolean resizable,
boolean scrollBars,
boolean statusBar,
boolean toolBar,
int top,
int width) {
this.height = height;
this.left = left;
this.locationBar = locationBar;
this.menuBar = menuBar;
this.resizable = resizable;
this.scrollBars = scrollBars;
this.statusBar = statusBar;
this.toolBar = toolBar;
this.top = top;
this.width = width;
}
/**
* Gets the height value for this RichMediaExitWindowProperties.
*
* @return height
*/
public int getHeight() {
return height;
}
/**
* Sets the height value for this RichMediaExitWindowProperties.
*
* @param height
*/
public void setHeight(int height) {
this.height = height;
}
/**
* Gets the left value for this RichMediaExitWindowProperties.
*
* @return left
*/
public int getLeft() {
return left;
}
/**
* Sets the left value for this RichMediaExitWindowProperties.
*
* @param left
*/
public void setLeft(int left) {
this.left = left;
}
/**
* Gets the locationBar value for this RichMediaExitWindowProperties.
*
* @return locationBar
*/
public boolean isLocationBar() {
return locationBar;
}
/**
* Sets the locationBar value for this RichMediaExitWindowProperties.
*
* @param locationBar
*/
public void setLocationBar(boolean locationBar) {
this.locationBar = locationBar;
}
/**
* Gets the menuBar value for this RichMediaExitWindowProperties.
*
* @return menuBar
*/
public boolean isMenuBar() {
return menuBar;
}
/**
* Sets the menuBar value for this RichMediaExitWindowProperties.
*
* @param menuBar
*/
public void setMenuBar(boolean menuBar) {
this.menuBar = menuBar;
}
/**
* Gets the resizable value for this RichMediaExitWindowProperties.
*
* @return resizable
*/
public boolean isResizable() {
return resizable;
}
/**
* Sets the resizable value for this RichMediaExitWindowProperties.
*
* @param resizable
*/
public void setResizable(boolean resizable) {
this.resizable = resizable;
}
/**
* Gets the scrollBars value for this RichMediaExitWindowProperties.
*
* @return scrollBars
*/
public boolean isScrollBars() {
return scrollBars;
}
/**
* Sets the scrollBars value for this RichMediaExitWindowProperties.
*
* @param scrollBars
*/
public void setScrollBars(boolean scrollBars) {
this.scrollBars = scrollBars;
}
/**
* Gets the statusBar value for this RichMediaExitWindowProperties.
*
* @return statusBar
*/
public boolean isStatusBar() {
return statusBar;
}
/**
* Sets the statusBar value for this RichMediaExitWindowProperties.
*
* @param statusBar
*/
public void setStatusBar(boolean statusBar) {
this.statusBar = statusBar;
}
/**
* Gets the toolBar value for this RichMediaExitWindowProperties.
*
* @return toolBar
*/
public boolean isToolBar() {
return toolBar;
}
/**
* Sets the toolBar value for this RichMediaExitWindowProperties.
*
* @param toolBar
*/
public void setToolBar(boolean toolBar) {
this.toolBar = toolBar;
}
/**
* Gets the top value for this RichMediaExitWindowProperties.
*
* @return top
*/
public int getTop() {
return top;
}
/**
* Sets the top value for this RichMediaExitWindowProperties.
*
* @param top
*/
public void setTop(int top) {
this.top = top;
}
/**
* Gets the width value for this RichMediaExitWindowProperties.
*
* @return width
*/
public int getWidth() {
return width;
}
/**
* Sets the width value for this RichMediaExitWindowProperties.
*
* @param width
*/
public void setWidth(int width) {
this.width = width;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof RichMediaExitWindowProperties)) return false;
RichMediaExitWindowProperties other = (RichMediaExitWindowProperties) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
this.height == other.getHeight() &&
this.left == other.getLeft() &&
this.locationBar == other.isLocationBar() &&
this.menuBar == other.isMenuBar() &&
this.resizable == other.isResizable() &&
this.scrollBars == other.isScrollBars() &&
this.statusBar == other.isStatusBar() &&
this.toolBar == other.isToolBar() &&
this.top == other.getTop() &&
this.width == other.getWidth();
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
_hashCode += getHeight();
_hashCode += getLeft();
_hashCode += (isLocationBar() ? Boolean.TRUE : Boolean.FALSE).hashCode();
_hashCode += (isMenuBar() ? Boolean.TRUE : Boolean.FALSE).hashCode();
_hashCode += (isResizable() ? Boolean.TRUE : Boolean.FALSE).hashCode();
_hashCode += (isScrollBars() ? Boolean.TRUE : Boolean.FALSE).hashCode();
_hashCode += (isStatusBar() ? Boolean.TRUE : Boolean.FALSE).hashCode();
_hashCode += (isToolBar() ? Boolean.TRUE : Boolean.FALSE).hashCode();
_hashCode += getTop();
_hashCode += getWidth();
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(RichMediaExitWindowProperties.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://www.doubleclick.net/dfa-api/v1.19", "RichMediaExitWindowProperties"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("height");
elemField.setXmlName(new javax.xml.namespace.QName("", "height"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("left");
elemField.setXmlName(new javax.xml.namespace.QName("", "left"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("locationBar");
elemField.setXmlName(new javax.xml.namespace.QName("", "locationBar"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("menuBar");
elemField.setXmlName(new javax.xml.namespace.QName("", "menuBar"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("resizable");
elemField.setXmlName(new javax.xml.namespace.QName("", "resizable"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("scrollBars");
elemField.setXmlName(new javax.xml.namespace.QName("", "scrollBars"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("statusBar");
elemField.setXmlName(new javax.xml.namespace.QName("", "statusBar"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("toolBar");
elemField.setXmlName(new javax.xml.namespace.QName("", "toolBar"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("top");
elemField.setXmlName(new javax.xml.namespace.QName("", "top"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("width");
elemField.setXmlName(new javax.xml.namespace.QName("", "width"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
prashantc29/bulletin-board-consistency | common/src/main/java/edu/umn/bulletinboard/common/locks/ServerLock.java | 417 | package edu.umn.bulletinboard.common.locks;
/**
*
* Contains lock objects for different operations performed by servers and
* coordinator.
*
* Created by Abhijeet on 3/30/2014.
*/
public class ServerLock {
public static final Boolean register = new Boolean(true);
public static final Boolean getID = new Boolean(true);
/**
* No instantiation allowed.
*/
private ServerLock() {}
}
| apache-2.0 |
DenverM80/ds3_java_sdk | ds3-sdk/src/main/java/com/spectralogic/ds3client/utils/hashing/CRC32Hasher.java | 1009 | /*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.ds3client.utils.hashing;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
public class CRC32Hasher extends ChecksumHasher {
@Override
protected Checksum getChecksum() {
return new CRC32();
}
}
| apache-2.0 |
hanyahui88/swifts | src/main/java/com/swifts/frame/modules/cms/entity/Comment.java | 2706 | /**
* Copyright © 2015-2016 <a href="https://github.com/hanyahui88/swifts">swifts</a> All rights reserved.
*/
package com.swifts.frame.modules.cms.entity;
import java.util.Date;
import javax.validation.constraints.NotNull;
import com.swifts.frame.common.persistence.DataEntity;
import com.swifts.frame.modules.sys.entity.User;
import org.hibernate.validator.constraints.Length;
/**
* 评论Entity
* @author ThinkGem
* @version 2013-05-15
*/
public class Comment extends DataEntity<Comment> {
private static final long serialVersionUID = 1L;
private Category category;// 分类编号
private String contentId; // 归属分类内容的编号(Article.id、Photo.id、Download.id)
private String title; // 归属分类内容的标题(Article.title、Photo.title、Download.title)
private String content; // 评论内容
private String name; // 评论姓名
private String ip; // 评论IP
private Date createDate;// 评论时间
private User auditUser; // 审核人
private Date auditDate; // 审核时间
private String delFlag; // 删除标记删除标记(0:正常;1:删除;2:审核)
public Comment() {
super();
this.delFlag = DEL_FLAG_AUDIT;
}
public Comment(String id){
this();
this.id = id;
}
public Comment(Category category){
this();
this.category = category;
}
@NotNull
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
@NotNull
public String getContentId() {
return contentId;
}
public void setContentId(String contentId) {
this.contentId = contentId;
}
@Length(min=1, max=255)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Length(min=1, max=255)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Length(min=1, max=100)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getAuditUser() {
return auditUser;
}
public void setAuditUser(User auditUser) {
this.auditUser = auditUser;
}
public Date getAuditDate() {
return auditDate;
}
public void setAuditDate(Date auditDate) {
this.auditDate = auditDate;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
@NotNull
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
@Length(min=1, max=1)
public String getDelFlag() {
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
} | apache-2.0 |
paplorinc/intellij-community | java/java-impl/src/com/intellij/refactoring/JavaRefactoringSettings.java | 5521 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
@State(name = "RefactoringSettings", storages = {
@Storage("baseRefactoring.xml"),
@Storage(value = "other.xml", deprecated = true),
})
public class JavaRefactoringSettings implements PersistentStateComponent<JavaRefactoringSettings> {
// properties should be public in order to get saved by DefaultExternalizable implementation
//public boolean RENAME_PREVIEW_USAGES = true;
public boolean RENAME_SEARCH_IN_COMMENTS_FOR_PACKAGE = true;
public boolean RENAME_SEARCH_IN_COMMENTS_FOR_CLASS = true;
public boolean RENAME_SEARCH_IN_COMMENTS_FOR_METHOD = true;
public boolean RENAME_SEARCH_IN_COMMENTS_FOR_FIELD = true;
public boolean RENAME_SEARCH_IN_COMMENTS_FOR_VARIABLE = true;
public boolean RENAME_SEARCH_FOR_TEXT_FOR_PACKAGE = true;
public boolean RENAME_SEARCH_FOR_TEXT_FOR_CLASS = true;
public boolean RENAME_SEARCH_FOR_TEXT_FOR_METHOD = true;
public boolean RENAME_SEARCH_FOR_TEXT_FOR_FIELD = true;
public boolean RENAME_SEARCH_FOR_TEXT_FOR_VARIABLE = true;
//public boolean ENCAPSULATE_FIELDS_PREVIEW_USAGES = true;
public boolean ENCAPSULATE_FIELDS_USE_ACCESSORS_WHEN_ACCESSIBLE = true;
public boolean EXTRACT_INTERFACE_PREVIEW_USAGES = true;
public boolean MOVE_PREVIEW_USAGES = true;
public boolean MOVE_SEARCH_IN_COMMENTS = true;
public boolean MOVE_SEARCH_FOR_TEXT = true;
//public boolean INLINE_METHOD_PREVIEW_USAGES = true;
//public boolean INLINE_FIELD_PREVIEW_USAGES = true;
//public boolean CHANGE_SIGNATURE_PREVIEW_USAGES = true;
public boolean CHANGE_CLASS_SIGNATURE_PREVIEW_USAGES = true;
public boolean MOVE_INNER_PREVIEW_USAGES = true;
//public boolean TYPE_COOK_PREVIEW_USAGES = true;
public boolean TYPE_COOK_DROP_CASTS = true;
public boolean TYPE_COOK_PRESERVE_RAW_ARRAYS = true;
public boolean TYPE_COOK_LEAVE_OBJECT_PARAMETERIZED_TYPES_RAW = true;
public boolean TYPE_COOK_EXHAUSTIVE;
public boolean TYPE_COOK_COOK_OBJECTS;
public boolean TYPE_COOK_PRODUCE_WILDCARDS;
public boolean TYPE_MIGRATION_PREVIEW_USAGES = true;
//public boolean MAKE_METHOD_STATIC_PREVIEW_USAGES;
//public boolean INTRODUCE_PARAMETER_PREVIEW_USAGES;
public int INTRODUCE_PARAMETER_REPLACE_FIELDS_WITH_GETTERS;
public int EXTRACT_INTERFACE_JAVADOC;
public int EXTRACT_SUPERCLASS_JAVADOC;
public boolean TURN_REFS_TO_SUPER_PREVIEW_USAGES;
public boolean INTRODUCE_PARAMETER_DELETE_LOCAL_VARIABLE;
public boolean INTRODUCE_PARAMETER_USE_INITIALIZER;
public String INTRODUCE_FIELD_VISIBILITY;
public int PULL_UP_MEMBERS_JAVADOC;
public boolean PUSH_DOWN_PREVIEW_USAGES;
public boolean INLINE_METHOD_THIS;
public boolean INLINE_SUPER_CLASS_THIS;
public boolean INLINE_FIELD_THIS;
public boolean INLINE_LOCAL_THIS;
//public boolean INHERITANCE_TO_DELEGATION_PREVIEW_USAGES;
public boolean INHERITANCE_TO_DELEGATION_DELEGATE_OTHER;
//public boolean REPLACE_CONSTRUCTOR_WITH_FACTORY_PREVIEW_USAGES;
public String INTRODUCE_CONSTANT_VISIBILITY;
public boolean INTRODUCE_CONSTANT_MOVE_TO_ANOTHER_CLASS;
public boolean CONVERT_TO_INSTANCE_METHOD_PREVIEW_USAGES = true;
public Boolean INTRODUCE_LOCAL_CREATE_FINALS;
public Boolean INTRODUCE_LOCAL_CREATE_VAR_TYPE = false;
public Boolean INTRODUCE_PARAMETER_CREATE_FINALS;
public boolean INLINE_CLASS_SEARCH_IN_COMMENTS = true;
public boolean INLINE_CLASS_SEARCH_IN_NON_JAVA = true;
@SuppressWarnings({"WeakerAccess"}) public boolean RENAME_INHERITORS = true;
@SuppressWarnings({"WeakerAccess"}) public boolean RENAME_PARAMETER_IN_HIERARCHY = true;
@SuppressWarnings({"WeakerAccess"}) public boolean RENAME_VARIABLES = true;
@SuppressWarnings({"WeakerAccess"}) public boolean RENAME_TESTS = true;
@SuppressWarnings({"WeakerAccess"}) public boolean RENAME_OVERLOADS = true;
public static JavaRefactoringSettings getInstance() {
return ServiceManager.getService(JavaRefactoringSettings.class);
}
public boolean isToRenameInheritors() {
return RENAME_INHERITORS;
}
public boolean isToRenameVariables() {
return RENAME_VARIABLES;
}
public void setRenameInheritors(final boolean RENAME_INHERITORS) {
this.RENAME_INHERITORS = RENAME_INHERITORS;
}
public void setRenameVariables(final boolean RENAME_VARIABLES) {
this.RENAME_VARIABLES = RENAME_VARIABLES;
}
public boolean isRenameParameterInHierarchy() {
return RENAME_PARAMETER_IN_HIERARCHY;
}
public void setRenameParameterInHierarchy(boolean rename) {
this.RENAME_PARAMETER_IN_HIERARCHY = rename;
}
@Override
public JavaRefactoringSettings getState() {
return this;
}
@Override
public void loadState(@NotNull JavaRefactoringSettings state) {
XmlSerializerUtil.copyBean(state, this);
}
public boolean isToRenameTests() {
return RENAME_TESTS;
}
public void setRenameTests(boolean renameTests) {
this.RENAME_TESTS = renameTests;
}
public void setRenameOverloads(boolean renameOverloads) {
RENAME_OVERLOADS = renameOverloads;
}
public boolean isRenameOverloads() {
return RENAME_OVERLOADS;
}
} | apache-2.0 |
asfeixue/mBridge | mBridge-proxy/src/main/java/com/feixue/mbridge/proxy/ClientProxy.java | 332 | package com.feixue.mbridge.proxy;
/**
* client endpoint proxy
* Created by zxxiao on 2017/7/12.
*/
public interface ClientProxy extends Proxy {
/**
* 和指定服务器地址建立链接
* @param host
* @param port
* @throws Exception
*/
void connect(String host, int port) throws Exception;
}
| artistic-2.0 |
aucd29/airbnb | Airbnb/app/src/main/java/net/sarangnamu/cloneairbnb/page/sub/main/MainListDetailFrgmt.java | 1432 | /*
* Copyright 2016. Burke Choi All rights reserved.
* http://www.sarangnamu.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.sarangnamu.cloneairbnb.page.sub.main;
import android.support.annotation.LayoutRes;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import net.sarangnamu.common.BkApp;
import net.sarangnamu.common.InflateFrgmtBase;
import net.sarangnamu.common.ui.LpInst;
/**
* Created by <a href="mailto:aucd29@gmail.com">Burke Choi</a> on 2016. 5. 3.. <p/>
*/
public class MainListDetailFrgmt extends InflateFrgmtBase {
private static final org.slf4j.Logger mLog = org.slf4j.LoggerFactory.getLogger(MainListDetailFrgmt.class);
@Override
protected void initLayout() {
mBaseView.setLayoutParams(LpInst.frame(BkApp.screenX(), BkApp.screenY()));
}
@Override
protected String getPrefixForPage() {
return "";
}
}
| artistic-2.0 |
netpork/bokalce | java/tk/netpork/bokalce/Preload.java | 2635 | package tk.netpork.bokalce;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.util.Log;
/**
* Created by netpork on 10/20/14.
*/
public class Preload extends AsyncTask <Integer, Void, Integer>{
private static final String TAG = "Preload";
private MainPanel mPanel;
public Preload(MainPanel panel) {
mPanel = panel;
}
@Override
protected Integer doInBackground(Integer... something) {
Video.djidji = BitmapFactory.decodeResource(mPanel.getResources(), R.drawable.djidji, Video.optionsNoScale);
Video.nana = BitmapFactory.decodeResource(mPanel.getResources(), R.drawable.nana, Video.optionsNoScale);
Video.ahmad = BitmapFactory.decodeResource(mPanel.getResources(), R.drawable.ahmad, Video.optionsNoScale);
Video.ilkke = BitmapFactory.decodeResource(mPanel.getResources(), R.drawable.ilkke, Video.optionsNoScale);
Video.sprite = BitmapFactory.decodeResource(mPanel.getResources(), R.drawable.sprite_128x128, Video.optionsNoScale);
Video.sprite.getPixels(Video.spritePixels, 0, Video.spriteWidth, 0, 0, Video.spriteWidth, Video.spriteHeight);
// Log.i(TAG, "--------x" + Video.sprite.getWidth() + " ------y" + Video.sprite.getHeight());
Video.bubbles[0] = BitmapFactory.decodeResource(mPanel.getResources(), R.drawable.boobles1, Video.optionsNoScale);
Video.bubbles[1] = BitmapFactory.decodeResource(mPanel.getResources(), R.drawable.boobles2, Video.optionsNoScale);
Video.bubbles[2] = BitmapFactory.decodeResource(mPanel.getResources(), R.drawable.boobles3, Video.optionsNoScale);
Video.bubbles[3] = BitmapFactory.decodeResource(mPanel.getResources(), R.drawable.boobles4, Video.optionsNoScale);
Video.bubbles[4] = BitmapFactory.decodeResource(mPanel.getResources(), R.drawable.boobles5, Video.optionsNoScale);
Video.bubbles[5] = BitmapFactory.decodeResource(mPanel.getResources(), R.drawable.boobles6, Video.optionsNoScale);
MainPanel.plopSound1 = MediaPlayer.create(MainPanel.context, R.raw.plop0);
MainPanel.plopSound2 = MediaPlayer.create(MainPanel.context, R.raw.plop1);
MainPanel.plopSound3 = MediaPlayer.create(MainPanel.context, R.raw.plop2);
MainPanel.modPlayer = new ModMusic(MainPanel.context, R.raw.xality);
// Log.i(TAG, "preload finished!");
return 1;
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
// Log.i(TAG, "finished from postexecute");
mPanel.startMusicAndThread();
}
}
| artistic-2.0 |
douhao4648/Test | src/pattern/p16_observer/HanFeiZi.java | 537 | package pattern.p16_observer;
import java.util.Observable;
public class HanFeiZi extends Observable {
public void haveBreakfast() {
System.out.println("----------------------" + "吃饭ing" + "----------------------");
super.setChanged();
super.notifyObservers("韩非子在吃饭");
}
public void haveFun() {
System.out.println("----------------------" + "玩耍ing" + "----------------------");
super.setChanged();
super.notifyObservers("韩非子在玩耍");
}
}
| artistic-2.0 |
Pushjet/Pushjet-Android | gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/src/platform-native/org/gradle/nativeplatform/plugins/NativeComponentModelPlugin.java | 13506 | /*
* Copyright 2011 the original author or 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 org.gradle.nativeplatform.plugins;
import org.gradle.api.*;
import org.gradle.api.artifacts.repositories.ArtifactRepository;
import org.gradle.api.file.SourceDirectorySet;
import org.gradle.api.internal.DefaultPolymorphicDomainObjectContainer;
import org.gradle.api.internal.file.FileResolver;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.plugins.ExtensionContainer;
import org.gradle.internal.Actions;
import org.gradle.internal.reflect.Instantiator;
import org.gradle.internal.service.ServiceRegistry;
import org.gradle.language.base.FunctionalSourceSet;
import org.gradle.language.base.ProjectSourceSet;
import org.gradle.language.base.internal.LanguageRegistry;
import org.gradle.language.base.internal.LanguageSourceSetInternal;
import org.gradle.language.base.plugins.ComponentModelBasePlugin;
import org.gradle.language.nativeplatform.HeaderExportingSourceSet;
import org.gradle.model.*;
import org.gradle.nativeplatform.*;
import org.gradle.nativeplatform.internal.*;
import org.gradle.nativeplatform.internal.configure.*;
import org.gradle.nativeplatform.internal.prebuilt.DefaultPrebuiltLibraries;
import org.gradle.nativeplatform.internal.prebuilt.PrebuiltLibraryInitializer;
import org.gradle.nativeplatform.internal.resolve.NativeDependencyResolver;
import org.gradle.nativeplatform.platform.NativePlatform;
import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform;
import org.gradle.nativeplatform.platform.internal.NativePlatformInternal;
import org.gradle.nativeplatform.toolchain.internal.DefaultNativeToolChainRegistry;
import org.gradle.nativeplatform.toolchain.internal.NativeToolChainInternal;
import org.gradle.nativeplatform.toolchain.internal.NativeToolChainRegistryInternal;
import org.gradle.platform.base.BinaryContainer;
import org.gradle.platform.base.ComponentSpecContainer;
import org.gradle.platform.base.PlatformContainer;
import org.gradle.platform.base.internal.BinaryNamingSchemeBuilder;
import org.gradle.platform.base.internal.DefaultBinaryNamingSchemeBuilder;
import org.gradle.platform.base.internal.DefaultPlatformContainer;
import javax.inject.Inject;
import java.io.File;
/**
* A plugin that sets up the infrastructure for defining native binaries.
*/
@Incubating
public class NativeComponentModelPlugin implements Plugin<ProjectInternal> {
private final Instantiator instantiator;
@Inject
public NativeComponentModelPlugin(Instantiator instantiator) {
this.instantiator = instantiator;
}
public void apply(final ProjectInternal project) {
project.getPlugins().apply(ComponentModelBasePlugin.class);
ProjectSourceSet sources = project.getExtensions().getByType(ProjectSourceSet.class);
ComponentSpecContainer components = project.getExtensions().getByType(ComponentSpecContainer.class);
components.registerFactory(NativeExecutableSpec.class, new NativeExecutableSpecFactory(instantiator, sources, project));
NamedDomainObjectContainer<NativeExecutableSpec> nativeExecutables = components.containerWithType(NativeExecutableSpec.class);
components.registerFactory(NativeLibrarySpec.class, new NativeLibrarySpecFactory(instantiator, sources, project));
NamedDomainObjectContainer<NativeLibrarySpec> nativeLibraries = components.containerWithType(NativeLibrarySpec.class);
project.getExtensions().create("nativeRuntime", DefaultNativeComponentExtension.class, nativeExecutables, nativeLibraries);
// TODO:DAZ Remove these: should not pollute the global namespace
project.getExtensions().add("nativeComponents", components.withType(NativeComponentSpec.class));
project.getExtensions().add("executables", nativeExecutables);
project.getExtensions().add("libraries", nativeLibraries);
}
/**
* Model rules.
*/
@SuppressWarnings("UnusedDeclaration")
@RuleSource
public static class Rules {
@Model
Repositories repositories(ServiceRegistry serviceRegistry, FlavorContainer flavors, PlatformContainer platforms, BuildTypeContainer buildTypes) {
Instantiator instantiator = serviceRegistry.get(Instantiator.class);
FileResolver fileResolver = serviceRegistry.get(FileResolver.class);
Action<PrebuiltLibrary> initializer = new PrebuiltLibraryInitializer(instantiator, platforms.withType(NativePlatform.class), buildTypes, flavors);
return new DefaultRepositories(instantiator, fileResolver, initializer);
}
@Model
NativeToolChainRegistryInternal toolChains(ServiceRegistry serviceRegistry) {
Instantiator instantiator = serviceRegistry.get(Instantiator.class);
return instantiator.newInstance(DefaultNativeToolChainRegistry.class, instantiator);
}
@Model
BuildTypeContainer buildTypes(ServiceRegistry serviceRegistry) {
Instantiator instantiator = serviceRegistry.get(Instantiator.class);
return instantiator.newInstance(DefaultBuildTypeContainer.class, instantiator);
}
@Model
FlavorContainer flavors(ServiceRegistry serviceRegistry) {
Instantiator instantiator = serviceRegistry.get(Instantiator.class);
return instantiator.newInstance(DefaultFlavorContainer.class, instantiator);
}
@Model
NamedDomainObjectSet<NativeComponentSpec> nativeComponents(ComponentSpecContainer components) {
return components.withType(NativeComponentSpec.class);
}
@Mutate
public void registerExtensions(ExtensionContainer extensions, BuildTypeContainer buildTypes, FlavorContainer flavors) {
extensions.add("buildTypes", buildTypes);
extensions.add("flavors", flavors);
}
@Mutate
public void registerNativePlatformFactory(PlatformContainer platforms, ServiceRegistry serviceRegistry) {
final Instantiator instantiator = serviceRegistry.get(Instantiator.class);
NamedDomainObjectFactory<NativePlatform> nativePlatformFactory = new NamedDomainObjectFactory<NativePlatform>() {
public NativePlatform create(String name) {
return instantiator.newInstance(DefaultNativePlatform.class, name);
}
};
//TODO freekh: remove cast/this comment when registerDefault exists on interface
((DefaultPlatformContainer) platforms).registerDefaultFactory(nativePlatformFactory);
platforms.registerFactory(NativePlatform.class, nativePlatformFactory);
}
@Mutate
public void createNativeBinaries(BinaryContainer binaries, NamedDomainObjectSet<NativeComponentSpec> nativeComponents,
LanguageRegistry languages, NativeToolChainRegistryInternal toolChains,
PlatformContainer platforms, BuildTypeContainer buildTypes, FlavorContainer flavors,
ServiceRegistry serviceRegistry, @Path("buildDir") File buildDir) {
Instantiator instantiator = serviceRegistry.get(Instantiator.class);
NativeDependencyResolver resolver = serviceRegistry.get(NativeDependencyResolver.class);
Action<NativeBinarySpec> configureBinaryAction = new NativeBinarySpecInitializer(buildDir);
Action<NativeBinarySpec> setToolsAction = new ToolSettingNativeBinaryInitializer(languages);
Action<NativeBinarySpec> setDefaultTargetsAction = new ToolSettingNativeBinaryInitializer(languages);
@SuppressWarnings("unchecked") Action<NativeBinarySpec> initAction = Actions.composite(configureBinaryAction, setToolsAction, new MarkBinariesBuildable());
NativeBinariesFactory factory = new DefaultNativeBinariesFactory(instantiator, initAction, resolver);
BinaryNamingSchemeBuilder namingSchemeBuilder = new DefaultBinaryNamingSchemeBuilder();
Action<NativeComponentSpec> createBinariesAction =
new NativeComponentSpecInitializer(factory, namingSchemeBuilder, toolChains, platforms, buildTypes, flavors);
for (NativeComponentSpec component : nativeComponents) {
createBinariesAction.execute(component);
binaries.addAll(component.getBinaries());
}
}
@Finalize
public void createDefaultPlatforms(PlatformContainer platforms) {
if (platforms.withType(NativePlatform.class).isEmpty()) {
// TODO:DAZ Create a set of known platforms, rather than a single 'default'
NativePlatform defaultPlatform = platforms.create(NativePlatform.DEFAULT_NAME, NativePlatform.class);
}
}
@Finalize
public void createDefaultToolChain(NativeToolChainRegistryInternal toolChains) {
if (toolChains.isEmpty()) {
toolChains.addDefaultToolChains();
}
}
@Finalize
public void createDefaultBuildTypes(BuildTypeContainer buildTypes) {
if (buildTypes.isEmpty()) {
buildTypes.create("debug");
}
}
@Finalize
public void createDefaultFlavor(FlavorContainer flavors) {
if (flavors.isEmpty()) {
flavors.create(DefaultFlavor.DEFAULT);
}
}
@Mutate
void configureGeneratedSourceSets(ProjectSourceSet sources) {
for (FunctionalSourceSet functionalSourceSet : sources) {
for (LanguageSourceSetInternal languageSourceSet : functionalSourceSet.withType(LanguageSourceSetInternal.class)) {
Task generatorTask = languageSourceSet.getGeneratorTask();
if (generatorTask != null) {
languageSourceSet.builtBy(generatorTask);
maybeSetSourceDir(languageSourceSet.getSource(), generatorTask, "sourceDir");
if (languageSourceSet instanceof HeaderExportingSourceSet) {
maybeSetSourceDir(((HeaderExportingSourceSet) languageSourceSet).getExportedHeaders(), generatorTask, "headerDir");
}
}
}
}
}
@Finalize
public void applyHeaderSourceSetConventions(ProjectSourceSet sources) {
for (FunctionalSourceSet functionalSourceSet : sources) {
for (HeaderExportingSourceSet headerSourceSet : functionalSourceSet.withType(HeaderExportingSourceSet.class)) {
// Only apply default locations when none explicitly configured
if (headerSourceSet.getExportedHeaders().getSrcDirs().isEmpty()) {
headerSourceSet.getExportedHeaders().srcDir(String.format("src/%s/headers", functionalSourceSet.getName()));
}
headerSourceSet.getImplicitHeaders().setSrcDirs(headerSourceSet.getSource().getSrcDirs());
headerSourceSet.getImplicitHeaders().include("**/*.h");
}
}
}
private void maybeSetSourceDir(SourceDirectorySet sourceSet, Task task, String propertyName) {
Object value = task.property(propertyName);
if (value != null) {
sourceSet.srcDir(value);
}
}
}
private static class MarkBinariesBuildable implements Action<NativeBinarySpec> {
public void execute(NativeBinarySpec nativeBinarySpec) {
NativeToolChainInternal toolChainInternal = (NativeToolChainInternal) nativeBinarySpec.getToolChain();
boolean canBuild = toolChainInternal.select((NativePlatformInternal) nativeBinarySpec.getTargetPlatform()).isAvailable();
((NativeBinarySpecInternal) nativeBinarySpec).setBuildable(canBuild);
}
}
private static class DefaultRepositories extends DefaultPolymorphicDomainObjectContainer<ArtifactRepository> implements Repositories {
private DefaultRepositories(final Instantiator instantiator, final FileResolver fileResolver, final Action<PrebuiltLibrary> binaryFactory) {
super(ArtifactRepository.class, instantiator, new ArtifactRepositoryNamer());
registerFactory(PrebuiltLibraries.class, new NamedDomainObjectFactory<PrebuiltLibraries>() {
public PrebuiltLibraries create(String name) {
return instantiator.newInstance(DefaultPrebuiltLibraries.class, name, instantiator, fileResolver, binaryFactory);
}
});
}
}
private static class ArtifactRepositoryNamer implements Namer<ArtifactRepository> {
public String determineName(ArtifactRepository object) {
return object.getName();
}
}
} | bsd-2-clause |
nvdb-vegdata/nvdb-api-client | src/main/java/no/vegvesen/nvdbapi/client/model/datakatalog/AssociationType.java | 4128 | /*
* Copyright (c) 2015-2017, Statens vegvesen
* 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 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 no.vegvesen.nvdbapi.client.model.datakatalog;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Arrays;
public class AssociationType implements Serializable {
private final Integer id;
private final Integer featureTypeId;
private final InsideParent insideParent;
private final Affiliation affiliation;
private final LocalDate validFrom;
// List associations
private Integer listId;
private Integer maxNumber;
private Integer minNumber;
public AssociationType(Integer id, Integer featureTypeId, InsideParent insideParent, Affiliation affiliation,
LocalDate validFrom, Integer listId, Integer maxNumber, Integer minNumber) {
this.id = id;
this.featureTypeId = featureTypeId;
this.insideParent = insideParent;
this.affiliation = affiliation;
this.validFrom = validFrom;
// List associations
this.listId = listId;
this.maxNumber = maxNumber;
this.minNumber = minNumber;
}
public Integer getId() {
return id;
}
public LocalDate getValidFrom() {
return validFrom;
}
public Integer getFeatureTypeId() {
return featureTypeId;
}
public InsideParent getInsideParent() {
return insideParent;
}
public Integer getListId() { return listId; }
public Integer getMaxNumber() { return maxNumber; }
public Integer getMinNumber() { return minNumber; }
public Affiliation getAffiliation() {
return affiliation;
}
public enum Affiliation {
ASSOCIATION("ASSOSIASJON"),
AGGREGATION("AGGREGERING"),
COMPOSITION("KOMPOSISJON"),
TOPOLOGY("TOPOLOGI");
private final String name;
Affiliation(String name) {
this.name = name;
}
public static Affiliation from(String text) {
return Arrays.stream(values()).filter(v -> v.name.equalsIgnoreCase(text)).findAny().orElse(null);
}
}
public enum InsideParent {
NO,
YES,
/**
* Ja, men sidepos/feltkode/høydepos kan avvike
*/
YES_WITH_DEVIATIONS;
public static InsideParent from(String text) {
switch (text.toLowerCase()) {
case "ja":
return AssociationType.InsideParent.YES;
case "nei":
return AssociationType.InsideParent.NO;
case "med_avvik":
return AssociationType.InsideParent.YES_WITH_DEVIATIONS;
default:
throw new UnsupportedOperationException("Unrecognized inside parent value: "+ text);
}
}
}
}
| bsd-2-clause |
UniquePassive/runelite | runescape-client/src/main/java/class33.java | 3111 | import net.runelite.mapping.Export;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("af")
public final class class33 {
@ObfuscatedName("i")
@ObfuscatedSignature(
signature = "Lll;"
)
@Export("logoSprite")
static IndexedSprite logoSprite;
@ObfuscatedName("k")
final int[] field464;
class33() {
this.field464 = new int[4096];
}
@ObfuscatedName("o")
@ObfuscatedSignature(
signature = "(Lar;B)V",
garbageValue = "5"
)
final void method407(class44 var1) {
for(int var2 = 0; var2 < 64; ++var2) {
for(int var3 = 0; var3 < 64; ++var3) {
this.field464[var2 * 64 + var3] = var1.method655(var2, var3) | -16777216;
}
}
}
@ObfuscatedName("k")
@ObfuscatedSignature(
signature = "(IIB)I",
garbageValue = "-47"
)
final int method402(int var1, int var2) {
return this.field464[var1 * 64 + var2];
}
@ObfuscatedName("o")
@ObfuscatedSignature(
signature = "(Ljf;B)V",
garbageValue = "-3"
)
public static void method409(IndexDataBase var0) {
Enum.EnumDefinition_indexCache = var0;
}
@ObfuscatedName("d")
@ObfuscatedSignature(
signature = "(B)V",
garbageValue = "53"
)
static final void method408() {
if(!class132.Viewport_false0) {
int var0 = Region.pitchSin;
int var1 = Region.pitchCos;
int var2 = Region.yawSin;
int var3 = Region.yawCos;
byte var4 = 50;
short var5 = 3500;
int var6 = (class132.Viewport_mouseX - Graphics3D.centerX) * var4 / Graphics3D.Rasterizer3D_zoom;
int var7 = (class132.Viewport_mouseY - Graphics3D.centerY) * var4 / Graphics3D.Rasterizer3D_zoom;
int var8 = (class132.Viewport_mouseX - Graphics3D.centerX) * var5 / Graphics3D.Rasterizer3D_zoom;
int var9 = (class132.Viewport_mouseY - Graphics3D.centerY) * var5 / Graphics3D.Rasterizer3D_zoom;
int var10 = Graphics3D.method2779(var7, var4, var1, var0);
int var11 = Graphics3D.method2803(var7, var4, var1, var0);
var7 = var10;
var10 = Graphics3D.method2779(var9, var5, var1, var0);
int var12 = Graphics3D.method2803(var9, var5, var1, var0);
var9 = var10;
var10 = Graphics3D.method2800(var6, var11, var3, var2);
var11 = Graphics3D.method2812(var6, var11, var3, var2);
var6 = var10;
var10 = Graphics3D.method2800(var8, var12, var3, var2);
var12 = Graphics3D.method2812(var8, var12, var3, var2);
class132.field1919 = (var6 + var10) / 2;
class132.field1923 = (var7 + var9) / 2;
class132.field1924 = (var11 + var12) / 2;
class132.field1925 = (var10 - var6) / 2;
class37.field502 = (var9 - var7) / 2;
Resampler.field1629 = (var12 - var11) / 2;
class20.field336 = Math.abs(class132.field1925);
class132.field1926 = Math.abs(class37.field502);
IndexStoreActionHandler.field3399 = Math.abs(Resampler.field1629);
}
}
}
| bsd-2-clause |
chototsu/MikuMikuStudio | engine/src/blender/com/jme3/scene/plugins/blender/textures/GeneratedTexture.java | 6281 | package com.jme3.scene.plugins.blender.textures;
import com.jme3.bounding.BoundingBox;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.plugins.blender.BlenderContext;
import com.jme3.scene.plugins.blender.BlenderContext.LoadedFeatureDataType;
import com.jme3.scene.plugins.blender.file.Structure;
import com.jme3.scene.plugins.blender.textures.TriangulatedTexture.TriangleTextureElement;
import com.jme3.scene.plugins.blender.textures.UVCoordinatesGenerator.UVCoordinatesType;
import com.jme3.scene.plugins.blender.textures.generating.TextureGenerator;
import com.jme3.texture.Image;
import com.jme3.texture.Texture;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* The generated texture loaded from blender file. The texture is not generated
* after being read. This class rather stores all required data and can compute
* a pixel in the required 3D space position.
*
* @author Marcin Roguski (Kaelthas)
*/
/* package */class GeneratedTexture extends Texture {
// flag values
public static final int TEX_COLORBAND = 1;
public static final int TEX_FLIPBLEND = 2;
public static final int TEX_NEGALPHA = 4;
public static final int TEX_CHECKER_ODD = 8;
public static final int TEX_CHECKER_EVEN = 16;
public static final int TEX_PRV_ALPHA = 32;
public static final int TEX_PRV_NOR = 64;
public static final int TEX_REPEAT_XMIR = 128;
public static final int TEX_REPEAT_YMIR = 256;
public static final int TEX_FLAG_MASK = TEX_COLORBAND | TEX_FLIPBLEND | TEX_NEGALPHA | TEX_CHECKER_ODD | TEX_CHECKER_EVEN | TEX_PRV_ALPHA | TEX_PRV_NOR | TEX_REPEAT_XMIR | TEX_REPEAT_YMIR;
/** Material-texture link structure. */
private final Structure mTex;
/** Texture generateo for the specified texture type. */
private final TextureGenerator textureGenerator;
/**
* Constructor. Reads the required data from the 'tex' structure.
*
* @param tex
* the texture structure
* @param mTex
* the material-texture link data structure
* @param textureGenerator
* the generator for the required texture type
* @param blenderContext
* the blender context
*/
public GeneratedTexture(Structure tex, Structure mTex, TextureGenerator textureGenerator, BlenderContext blenderContext) {
this.mTex = mTex;
this.textureGenerator = textureGenerator;
this.textureGenerator.readData(tex, blenderContext);
super.setImage(new GeneratedTextureImage(textureGenerator.getImageFormat()));
}
/**
* This method computes the textyre color/intensity at the specified (u, v,
* s) position in 3D space.
*
* @param pixel
* the pixel where the result is stored
* @param u
* the U factor
* @param v
* the V factor
* @param s
* the S factor
*/
public void getPixel(TexturePixel pixel, float u, float v, float s) {
textureGenerator.getPixel(pixel, u, v, s);
}
/**
* This method triangulates the texture. In the result we get a set of small
* flat textures for each face of the given mesh. This can be later merged
* into one flat texture.
*
* @param mesh
* the mesh we create the texture for
* @param geometriesOMA
* the old memory address of the geometries group that the given
* mesh belongs to (required for bounding box calculations)
* @param coordinatesType
* the types of UV coordinates
* @param blenderContext
* the blender context
* @return triangulated texture
*/
@SuppressWarnings("unchecked")
public TriangulatedTexture triangulate(Mesh mesh, Long geometriesOMA, UVCoordinatesType coordinatesType, BlenderContext blenderContext) {
List<Geometry> geometries = (List<Geometry>) blenderContext.getLoadedFeature(geometriesOMA, LoadedFeatureDataType.LOADED_FEATURE);
int[] coordinatesSwappingIndexes = new int[] { ((Number) mTex.getFieldValue("projx")).intValue(), ((Number) mTex.getFieldValue("projy")).intValue(), ((Number) mTex.getFieldValue("projz")).intValue() };
List<Vector3f> uvs = UVCoordinatesGenerator.generateUVCoordinatesFor3DTexture(mesh, coordinatesType, coordinatesSwappingIndexes, geometries);
Vector3f[] uvsArray = uvs.toArray(new Vector3f[uvs.size()]);
BoundingBox boundingBox = UVCoordinatesGenerator.getBoundingBox(geometries);
Set<TriangleTextureElement> triangleTextureElements = new TreeSet<TriangleTextureElement>(new Comparator<TriangleTextureElement>() {
public int compare(TriangleTextureElement o1, TriangleTextureElement o2) {
return o1.faceIndex - o2.faceIndex;
}
});
int[] indices = new int[3];
for (int i = 0; i < mesh.getTriangleCount(); ++i) {
mesh.getTriangle(i, indices);
triangleTextureElements.add(new TriangleTextureElement(i, boundingBox, this, uvsArray, indices, blenderContext));
}
return new TriangulatedTexture(triangleTextureElements, blenderContext);
}
@Override
public void setWrap(WrapAxis axis, WrapMode mode) {
}
@Override
public void setWrap(WrapMode mode) {
}
@Override
public WrapMode getWrap(WrapAxis axis) {
return null;
}
@Override
public Type getType() {
return Type.ThreeDimensional;
}
@Override
public Texture createSimpleClone() {
return null;
}
/**
* Private class to give the format of the 'virtual' 3D texture image.
*
* @author Marcin Roguski (Kaelthas)
*/
private static class GeneratedTextureImage extends Image {
public GeneratedTextureImage(Format imageFormat) {
super.format = imageFormat;
}
}
}
| bsd-2-clause |
imagej/imagej-ops | src/main/java/net/imagej/ops/imagemoments/centralmoments/DefaultCentralMoment10.java | 2418 | /*
* #%L
* ImageJ2 software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2014 - 2021 ImageJ2 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%
*/
package net.imagej.ops.imagemoments.centralmoments;
import net.imagej.ops.Op;
import net.imagej.ops.Ops;
import net.imagej.ops.imagemoments.AbstractImageMomentOp;
import net.imglib2.IterableInterval;
import net.imglib2.type.numeric.RealType;
import org.scijava.Priority;
import org.scijava.plugin.Plugin;
/**
* {@link Op} to calculate the {@code imageMoments.centralMoment10} directly.
*
* @author Daniel Seebacher (University of Konstanz)
* @author Christian Dietz (University of Konstanz)
* @param <I> input type
* @param <O> output type
*/
@Plugin(type = Ops.ImageMoments.CentralMoment10.class, label = "Image Moment: CentralMoment10",
priority = Priority.VERY_HIGH)
public class DefaultCentralMoment10<I extends RealType<I>, O extends RealType<O>>
extends AbstractImageMomentOp<I, O> implements Ops.ImageMoments.CentralMoment10
{
@Override
public void compute(final IterableInterval<I> input, final O output) {
output.setReal(0d);
}
}
| bsd-2-clause |
stavamichal/perun | perun-web-gui/src/main/java/cz/metacentrum/perun/webgui/tabs/groupstabs/MoveGroupsTabItem.java | 9927 | package cz.metacentrum.perun.webgui.tabs.groupstabs;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import cz.metacentrum.perun.webgui.client.PerunWebSession;
import cz.metacentrum.perun.webgui.client.localization.ButtonTranslation;
import cz.metacentrum.perun.webgui.client.resources.ButtonType;
import cz.metacentrum.perun.webgui.client.resources.SmallIcons;
import cz.metacentrum.perun.webgui.client.resources.TableSorter;
import cz.metacentrum.perun.webgui.json.JsonCallbackEvents;
import cz.metacentrum.perun.webgui.json.JsonUtils;
import cz.metacentrum.perun.webgui.json.groupsManager.GetAllGroups;
import cz.metacentrum.perun.webgui.json.groupsManager.MoveGroup;
import cz.metacentrum.perun.webgui.model.Group;
import cz.metacentrum.perun.webgui.model.PerunError;
import cz.metacentrum.perun.webgui.model.VirtualOrganization;
import cz.metacentrum.perun.webgui.tabs.TabItem;
import cz.metacentrum.perun.webgui.widgets.CustomButton;
import cz.metacentrum.perun.webgui.widgets.ListBoxWithObjects;
import cz.metacentrum.perun.webgui.widgets.TabMenu;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Move groups under another or as top-level.
* !! USE AS INNER TAB ONLY !!
*
* @author Pavel Zlamal <256627@mail.muni.cz>
*/
public class MoveGroupsTabItem implements TabItem {
/**
* Perun web session
*/
private PerunWebSession session = PerunWebSession.getInstance();
/**
* Content widget - should be simple panel
*/
private SimplePanel contentWidget = new SimplePanel();
/**
* Title widget
*/
private Label titleWidget = new Label("Move groups");
private ButtonTranslation buttonTranslation = ButtonTranslation.INSTANCE;
private VirtualOrganization vo = null;
private Group group = null;
private ArrayList<? extends Group> groups = null;
/**
* Creates a tab instance
*/
public MoveGroupsTabItem(VirtualOrganization vo, ArrayList<? extends Group> groups){
this.vo = vo;
this.groups = new TableSorter<Group>().sortByName((ArrayList<Group>)groups);
}
/**
* Creates a tab instance
*/
public MoveGroupsTabItem(Group group, ArrayList<? extends Group> groups){
this.group = group;
this.groups = new TableSorter<Group>().sortByName((ArrayList<Group>)groups);
}
public boolean isPrepared(){
return ((this.vo != null) || (this.group != null)) && (this.groups != null) && (!this.groups.isEmpty());
}
@Override
public boolean isRefreshParentOnClose() {
return false;
}
@Override
public void onClose() {
}
public Widget draw() {
VerticalPanel vp = new VerticalPanel();
int voId = (vo != null) ? vo.getId() : group.getVoId();
List<Group> backupGroups = new ArrayList<>();
backupGroups.addAll(groups);
// remove any subgroups of parent groups in a list of MOVED groups
for (Group bg : backupGroups) {
Iterator<? extends Group> iterator = groups.iterator();
while (iterator.hasNext()) {
// check if is subgroup
Group moveGroup = iterator.next();
if (moveGroup.getName().startsWith(bg.getName()+":")) {
iterator.remove();
}
}
}
// textboxes which set the class data when updated
final ListBoxWithObjects<Group> vosGroups = new ListBoxWithObjects<Group>();
// prepares layout
FlexTable layout = new FlexTable();
layout.setStyleName("inputFormFlexTable");
FlexCellFormatter cellFormatter = layout.getFlexCellFormatter();
// close tab events
final TabItem tab = this;
TabMenu menu = new TabMenu();
// send button
final CustomButton moveButton = TabMenu.getPredefinedButton(ButtonType.MOVE, buttonTranslation.moveGroup());
moveButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
final Group destinationGroup = vosGroups.getSelectedObject();
final MoveGroup request = new MoveGroup();
final JsonCallbackEvents nextEvent = JsonCallbackEvents.disableButtonEvents(moveButton, new JsonCallbackEvents() {
int groupsCounter = 0;
@Override
public void onFinished(JavaScriptObject jso) {
if (groups.size() - 1 == groupsCounter) {
// there is another group to move
request.setEvents(JsonCallbackEvents.closeTabDisableButtonEvents(moveButton, tab));
request.moveGroup(groups.get(groupsCounter),destinationGroup);
} else if (groups.size() - 1 > groupsCounter) {
request.moveGroup(groups.get(groupsCounter), destinationGroup);
}
// done
}
@Override
public void onError(PerunError error) {
// close tab if failed
moveButton.setProcessing(false);
session.getTabManager().closeTab(tab);
}
@Override
public void onLoadingStart() {
groupsCounter++;
}
});
if (groups.size() == 1) {
// single group
request.setEvents(JsonCallbackEvents.closeTabDisableButtonEvents(moveButton, tab));
} else {
// iterate over more groups
request.setEvents(nextEvent);
}
request.moveGroup(groups.get(0), destinationGroup);
}
});
final GetAllGroups groupsCall = new GetAllGroups(voId, new JsonCallbackEvents(){
public void onFinished(JavaScriptObject jso){
vosGroups.clear();
ArrayList<Group> retGroups = JsonUtils.jsoAsList(jso);
retGroups = new TableSorter<Group>().sortByName(retGroups);
// skip groups which are moving and their sub-groups and direct parents (since they would stayed at the same place)
Iterator<Group> iterator = retGroups.iterator();
while (iterator.hasNext()) {
Group retGroup = iterator.next();
for (Group g : groups) {
if (g.getId() == retGroup.getId() ||
retGroup.getName().startsWith(g.getName()+":") ||
retGroup.getName().equals(g.getName()) ||
g.getParentGroupId() == retGroup.getId()) {
iterator.remove();
break;
}
}
}
for (Group g : retGroups) {
if (!g.isCoreGroup()) {
// SKIP CORE GROUPS !!
vosGroups.addItem(g);
}
}
if (vosGroups.getAllObjects().isEmpty()) {
for (Group g : groups) {
// at lease one of moving groups is a sub group, so we can offer move to top-level
if (g.getName().contains(":")) {
vosGroups.addNotSelectedOption();
moveButton.setEnabled(true);
return;
}
}
// can't move group anywhere
vosGroups.addItem("No possible destination group was found or group is already top-level.");
} else {
vosGroups.addNotSelectedOption();
moveButton.setEnabled(true);
}
}
public void onLoadingStart(){
vosGroups.clear();
vosGroups.addItem("Loading...");
moveButton.setEnabled(false);
}
public void onError(PerunError error) {
vosGroups.clear();
vosGroups.addItem("Error while loading");
}
});
groupsCall.retrieveData();
// cancel button
final CustomButton cancelButton = TabMenu.getPredefinedButton(ButtonType.CANCEL, "");
cancelButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent clickEvent) {
session.getTabManager().closeTab(tab, isRefreshParentOnClose());
}
});
layout.setHTML(0, 0, "Following groups will be moved (including all their sub-groups):");
layout.getFlexCellFormatter().setColSpan(0, 0, 2);
String items = "<ul>";
for (Group g : groups) {
items = items.concat("<li>" + g.getName() + "</li>");
}
items = items.concat("</ul>");
ScrollPanel sp = new ScrollPanel();
sp.setStyleName("border");
sp.setSize("100%", "100px");
sp.add(new HTML(items));
layout.setWidget(1, 0, sp);
layout.getFlexCellFormatter().setColSpan(1, 0, 2);
// Add some standard form options
layout.setHTML(2, 0, "Destination group:");
layout.setWidget(2, 1, vosGroups);
for (int i=2; i<layout.getRowCount(); i++) {
cellFormatter.addStyleName(i, 0, "itemName");
}
layout.setHTML(3, 0, "Group(s) will be moved (including all their sub-groups) under destination group! If no destination group is selected, group will be moved to top-level.<p>We strongly recommend to move groups one by one.");
layout.getFlexCellFormatter().setStyleName(3, 0, "inputFormInlineComment");
layout.getFlexCellFormatter().setColSpan(3, 0, 2);
vp.setWidth("400px");
menu.addWidget(moveButton);
menu.addWidget(cancelButton);
vp.add(layout);
vp.add(menu);
vp.setCellHorizontalAlignment(menu, HasHorizontalAlignment.ALIGN_RIGHT);
this.contentWidget.setWidget(vp);
return getWidget();
}
public Widget getWidget() {
return this.contentWidget;
}
public Widget getTitle() {
return this.titleWidget;
}
public ImageResource getIcon() {
return SmallIcons.INSTANCE.addIcon();
}
@Override
public int hashCode() {
final int prime = 2719;
int result = 1;
result = prime * result + 6786786;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
return true;
}
public boolean multipleInstancesEnabled() {
return false;
}
public void open()
{
}
public boolean isAuthorized() {
// FIXME - temporary only for perun admin
if (session.isPerunAdmin()){
return true;
}/*
else if (session.isVoAdmin((vo != null) ? vo.getId() : group.getVoId())) {
return true;
}*/ else {
return false;
}
}
}
| bsd-2-clause |
abelbriggs1/runelite | runelite-client/src/main/java/net/runelite/client/game/UntradeableItemMapping.java | 3002 | /*
* Copyright (c) 2018, TheStonedTurtle <https://github.com/TheStonedTurtle>
* 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 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 net.runelite.client.game;
import com.google.common.collect.ImmutableMap;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import net.runelite.api.ItemID;
@Getter
@RequiredArgsConstructor
public enum UntradeableItemMapping
{
MARK_OF_GRACE(ItemID.MARK_OF_GRACE, 10, ItemID.AMYLASE_CRYSTAL),
GRACEFUL_HOOD(ItemID.GRACEFUL_HOOD, 28, ItemID.MARK_OF_GRACE),
GRACEFUL_TOP(ItemID.GRACEFUL_TOP, 44, ItemID.MARK_OF_GRACE),
GRACEFUL_LEGS(ItemID.GRACEFUL_LEGS, 48, ItemID.MARK_OF_GRACE),
GRACEFUL_GLOVES(ItemID.GRACEFUL_GLOVES, 24, ItemID.MARK_OF_GRACE),
GRACEFUL_BOOTS(ItemID.GRACEFUL_BOOTS, 32, ItemID.MARK_OF_GRACE),
GRACEFUL_CAPE(ItemID.GRACEFUL_CAPE, 32, ItemID.MARK_OF_GRACE),
// 10 golden nuggets = 100 soft clay
GOLDEN_NUGGET(ItemID.GOLDEN_NUGGET, 10, ItemID.SOFT_CLAY),
PROSPECTOR_HELMET(ItemID.PROSPECTOR_HELMET, 32, ItemID.GOLDEN_NUGGET),
PROSPECTOR_JACKET(ItemID.PROSPECTOR_JACKET, 48, ItemID.GOLDEN_NUGGET),
PROSPECTOR_LEGS(ItemID.PROSPECTOR_LEGS, 40, ItemID.GOLDEN_NUGGET),
PROSPECTOR_BOOTS(ItemID.PROSPECTOR_BOOTS, 24, ItemID.GOLDEN_NUGGET);
private static final ImmutableMap<Integer, UntradeableItemMapping> UNTRADEABLE_RECLAIM_MAP;
private final int itemID;
private final int quantity;
private final int priceID;
static
{
ImmutableMap.Builder<Integer, UntradeableItemMapping> map = ImmutableMap.builder();
for (UntradeableItemMapping p : values())
{
map.put(p.getItemID(), p);
}
UNTRADEABLE_RECLAIM_MAP = map.build();
}
public static UntradeableItemMapping map(int itemId)
{
return UNTRADEABLE_RECLAIM_MAP.get(itemId);
}
}
| bsd-2-clause |
vilmospapp/jodd | jodd-joy/src/testInt/java/jodd/joy/JoySuite.java | 2718 | // Copyright (c) 2003-present, Jodd Team (http://jodd.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:
//
// 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 jodd.joy;
import jodd.exception.UncheckedException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
})
public class JoySuite {
public static boolean isSuite;
/**
* Starts Tomcat after the suite.
*/
@BeforeClass
public static void beforeClass() {
isSuite = true;
startTomcat();
}
/**
* Stop Tomcat after the suite.
*/
@AfterClass
public static void afterSuite() {
isSuite = false;
stopTomcat();
}
// ---------------------------------------------------------------- tomcat
private static JoyTomcatTestServer server;
/**
* Starts Tomcat.
*/
public static void startTomcat() {
if (server != null) {
return;
}
server = new JoyTomcatTestServer();
try {
server.start();
System.out.println("Tomcat test server started");
} catch (Exception e) {
throw new UncheckedException(e);
}
}
/**
* Stops Tomcat if not in the suite.
*/
public static void stopTomcat() {
if (server == null) {
return;
}
if (isSuite) { // dont stop tomcat if it we are still running in the suite!
return;
}
try {
server.stop();
} catch (Exception ignore) {
} finally {
System.out.println("Tomcat test server stopped");
server = null;
}
}
} | bsd-2-clause |
RAttab/not-battlecode-2014 | coarsenserPlayer/MapAssessment.java | 1711 | package coarsenserPlayer;
import battlecode.common.*;
public class MapAssessment{
public static int[][] coarseMap;
public static int bigBoxSize;
public static void assessMap(int bigBoxSizeIn,RobotController rc){
bigBoxSize=bigBoxSizeIn;
int coarseWidth = rc.getMapWidth()/bigBoxSize;
int coarseHeight = rc.getMapHeight()/bigBoxSize;
coarseMap = new int[coarseWidth][coarseHeight];
for(int x=0;x<coarseWidth*bigBoxSize;x++){
for(int y=0;y<coarseHeight*bigBoxSize;y++){
coarseMap[x/bigBoxSize][y/bigBoxSize]+=countObstacles(x,y,rc);
}
}
}
public static int countObstacles(int x, int y,RobotController rc){//returns a 0 or a 1
int terrainOrdinal = rc.senseTerrainTile(new MapLocation(x,y)).ordinal();//0 NORMAL, 1 ROAD, 2 VOID, 3 OFF_MAP
return (terrainOrdinal<2?0:1);
}
public static void printCoarseMap(){
System.out.println("Coarse map:");
for(int x=0;x<coarseMap[0].length;x++){
for(int y=0;y<coarseMap.length;y++){
int numberOfObstacles = coarseMap[x][y];
System.out.print(Math.min(numberOfObstacles, 9));
}
System.out.println();
}
}
public static void printBigCoarseMap(RobotController rc){
System.out.println("Fine map:");
for(int x=0;x<coarseMap[0].length*bigBoxSize;x++){
for(int y=0;y<coarseMap.length*bigBoxSize;y++){
if(countObstacles(x,y,rc)==0){//there's no obstacle, so print the box's obstacle count
int numberOfObstacles = coarseMap[x/bigBoxSize][y/bigBoxSize];
System.out.print(Math.min(numberOfObstacles, 9));
}else{//there's an obstacle, so print an X
System.out.print("X");
}
System.out.print(" ");
}
System.out.println();
}
}
} | bsd-2-clause |
hyperfiction/HypPlay_services | dependencies/hyp-play-services/src/fr/hyperfiction/playservices/Plus.java | 1931 | package fr.hyperfiction.playservices;
import android.content.Intent;
import android.net.Uri;
import com.google.android.gms.plus.PlusShare;
import com.google.android.gms.plus.PlusShare.Builder;
import com.google.android.gms.plus.PlusClient;
import fr.hyperfiction.googleplayservices.HypPlayServices;
import fr.hyperfiction.playservices.PlayHelper;
/**
* ...
* @author shoe[box]
*/
public class Plus{
// -------o constructor
/**
* constructor
*
* @param
* @return void
*/
private Plus( ){
}
// -------o public
/**
*
*
* @public
* @return void
*/
static public void basicSharing( String sText , String sURL ){
Intent i = new PlusShare.Builder( HypPlayServices.mainActivity )
.setType("text/plain")
.setText( sText )
.setContentUrl(Uri.parse( sURL ))
.getIntent();
HypPlayServices.mainActivity.startActivityForResult( i , 0 );
}
/**
*
*
* @public
* @return void
*/
static public String getFamily_name( ){
return getPlusClient( ).getCurrentPerson( ).getName( ).getFamilyName( );
}
/**
*
*
* @public
* @return void
*/
static public String getFirst_name( ){
return getPlusClient( ).getCurrentPerson( ).getName( ).getGivenName( );
}
/**
*
*
* @public
* @return void
*/
static public String getAccount_name( ){
return getPlusClient( ).getAccountName( );
}
/**
*
*
* @public
* @return void
*/
static public String getDisplay_name( ){
return getPlusClient( ).getCurrentPerson( ).getDisplayName( );
}
/**
*
*
* @public
* @return void
*/
static public String getNick_name( ){
return getPlusClient( ).getCurrentPerson( ).getNickname( );
}
// -------o protected
/**
*
*
* @private
* @return void
*/
static private PlusClient getPlusClient( ){
return PlayHelper.getInstance( ).getPlusClient( );
}
// -------o misc
} | bsd-2-clause |
christandiono/pipelineconverter | src/Galaxy/Tree/Tool/Tool.java | 987 | package Galaxy.Tree.Tool;
import Galaxy.Tree.GalaxyNode;
public class Tool extends GalaxyNode{
String description;
String id;
String fullName;
String version;
Inputs toolInputs;
Outputs toolOutputs;
Command toolCommand;
String help;
public Tool(String id, String fullName, String description,
String version, Inputs toolInputs, Command toolCommand,
String help){
this.id = id;
this.fullName = fullName;
this.description = description;
this.version = version;
this.toolInputs = toolInputs;
this.toolCommand = toolCommand;
this.help = help;
}
public String getID(){
return id;
}
public String getDescription() {
return description;
}
public String getId() {
return id;
}
public String getFullName() {
return fullName;
}
public String getVersion() {
return version;
}
public Inputs getToolInputs() {
return toolInputs;
}
public Command getToolCommand() {
return toolCommand;
}
public String getHelp() {
return help;
}
}
| bsd-2-clause |
klangner/cta | src/main/java/com/github/cta/Main.java | 1729 | package com.github.cta;
import com.github.cta.extractor.EcogScoreExtractor;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author Krzysztof Langner on 16.05.15.
*/
public class Main {
private static final String TEST_DATA_PATH = "datasets/adenoma";
public static void main(String[] args){
String dataPath = (args.length > 0) ? args[0] : TEST_DATA_PATH;
List<String> files = scanDirectory(dataPath);
for(String file : files){
processFile(file);
}
}
private static List<String> scanDirectory(String dataPath) {
List<String> files = new ArrayList<String>();
File folder = new File(dataPath);
if(folder.isDirectory()) {
//noinspection ConstantConditions
for (File file : folder.listFiles()) {
if (file.getName().endsWith(".xml")) {
files.add(file.getAbsolutePath());
}
}
}
else{
System.out.println("Not directory: " + dataPath);
}
return files;
}
public static void processFile(String fileName) {
XMLTrialFile trailFile = new XMLTrialFile(fileName);
List<Integer> scores = EcogScoreExtractor.findScore(trailFile.getEligibilityCriteria());
if(scores.size() > 0) {
System.out.println("CTA: " + trailFile.getStudyId());
System.out.print("Labels: ");
for(int i = 0; i < scores.size(); i++){
if(i+1 < scores.size()) System.out.print("ECOG " + scores.get(i) + ",");
else System.out.println("ECOG " + scores.get(i));
}
System.out.println();
}
}
}
| bsd-2-clause |
gregorias/dfuntest | core/src/main/java/me/gregorias/dfuntest/util/FileUtils.java | 2450 | package me.gregorias.dfuntest.util;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
// This interface was created for testing purposes.
/**
* Interface for local file utilities.
*/
public interface FileUtils {
/**
* {@link org.apache.commons.io.FileUtils#copyDirectoryToDirectory(java.io.File, java.io.File)}
*
* @param from Source path
* @param to Target directory path
*/
void copyDirectoryToDirectory(File from, File to) throws IOException;
/**
* {@link org.apache.commons.io.FileUtils#copyFileToDirectory(java.io.File, java.io.File)}
*
* @param from Source path
* @param to Target directory path
*/
void copyFileToDirectory(File from, File to) throws IOException;
/**
* {@link java.nio.file.Files#createDirectories(java.nio.file.Path,
* java.nio.file.attribute.FileAttribute[])}
*
* @param path Path to create
*/
void createDirectories(Path path) throws IOException;
/**
* {@link java.nio.file.Files#createTempDirectory(
* String, java.nio.file.attribute.FileAttribute[])}
*
* @param dirPrefix prefix of temporary directory
* @return Path to created directory
*/
Path createTempDirectory(String dirPrefix) throws IOException;
/**
* {@link org.apache.commons.io.FileUtils#deleteQuietly(java.io.File)}
*
* @param file File to delete
* @return true iff directory was deleted
*/
boolean deleteQuietly(File file);
/**
* {@link java.nio.file.Files#exists(java.nio.file.Path, java.nio.file.LinkOption...)}
*
* @param path path to check
* @return true iff exists
*/
boolean exists(Path path);
/**
* {@link java.nio.file.Files#isDirectory(java.nio.file.Path, java.nio.file.LinkOption...)}
*
* @param path path to check
* @return true iff path is a directory
*/
boolean isDirectory(Path path);
/**
* {@link java.lang.ProcessBuilder}
*
* @param command command to run
* @param pwdFile working directory of the process
* @return process running the command
*/
Process runCommand(List<String> command, File pwdFile) throws IOException;
/**
* {@link java.nio.file.Files#write(java.nio.file.Path, Iterable, java.nio.charset.Charset,
* java.nio.file.OpenOption...)}
*
* @param path Path of file to write to.
* @param content String to be written to file.
*/
void write(Path path, String content) throws IOException;
} | bsd-2-clause |
UCSFMemoryAndAging/lava-uds | lava-crms-nacc/src/edu/ucsf/lava/crms/assessment/controller/NaccNpExtractComponentHandler.java | 9732 | package edu.ucsf.lava.crms.assessment.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.validation.BindingResult;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.definition.StateDefinition;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
import edu.ucsf.lava.core.action.ActionUtils;
import edu.ucsf.lava.core.calendar.CalendarDaoUtils;
import edu.ucsf.lava.core.calendar.controller.CalendarHandlerUtils;
import edu.ucsf.lava.core.controller.ComponentCommand;
import edu.ucsf.lava.core.controller.LavaComponentFormAction;
import edu.ucsf.lava.core.dao.LavaDaoFilter;
import edu.ucsf.lava.core.reporting.model.ReportSetup;
import edu.ucsf.lava.crms.assessment.dto.UdsExtractReportDto;
import edu.ucsf.lava.crms.assessment.model.NaccPathology;
import edu.ucsf.lava.crms.assessment.model.UdsUploadUtils;
import edu.ucsf.lava.crms.assessment.model.UdsUploadable;
import edu.ucsf.lava.crms.reporting.controller.CrmsReportComponentHandler;
import edu.ucsf.lava.crms.session.CrmsSessionUtils;
/*
* Used to extract NACC's NP data set only (not including any other NACC datasets, like UDS)
*
* @author trobbie (EMORY)
*/
public class NaccNpExtractComponentHandler extends CrmsReportComponentHandler {
public NaccNpExtractComponentHandler() {
super();
}
// subclasses can override/enhance this to add additional criteria filter fields
protected LavaDaoFilter setupReportFilter(RequestContext context, LavaDaoFilter filter) {
HttpServletRequest request = ((ServletExternalContext)context.getExternalContext()).getRequest();
super.setupReportFilter(context, filter);
// selection (unlike for lists, where they are mutually exclusive), want to initialize them here so
// they default to the defaultDisplayRange
// ultimately, dateEnd is ignored because it is not a criteria for the UDSExtract. it is
// not displayed on the report setup parameters view, and is set to the extreme value
// when the report is to be generated. but does not hurt to handle it here because it is
// handled in unison with dateStart, which is used
// initializes the query date range to defaults based on the defaultDisplayRange
CalendarHandlerUtils.setDateFilterParams(context, filter, this.defaultDisplayRange, this.startDateParam, this.endDateParam);
// transfer the default date range to the custom date params used as filter fields in the view. this
// must be done separately from the above call because the Calendar handler does not want this to happen
// (see updateCustomParamsFromDateParams comments)
CalendarDaoUtils.updateCustomParamsFromDateParams(filter, this.startDateParam, this.endDateParam, Boolean.TRUE);
// initialize the patientId filter field to the current patient
if (CrmsSessionUtils.getCurrentPatient(sessionManager,request) != null) {
filter.setParam("patientId", CrmsSessionUtils.getCurrentPatient(sessionManager,request).getId());
}
return filter;
}
public Map getBackingObjects(RequestContext context, Map components) {
Map backingObjects = super.getBackingObjects(context, components);
ReportSetup reportSetup = (ReportSetup) backingObjects.get(this.getDefaultObjectName());
reportSetup.setFormat("csv");
return backingObjects;
}
// override and do not set any required fields because EITHER the startDate or
// patientId must be input (or both), so either startDate or patientId could be null
protected String[] defineRequiredFields(RequestContext context, Object command) {
String[] required = new String[0];
setRequiredFields(required);
return getRequiredFields();
}
public Map addReferenceData(RequestContext context, Object command, BindingResult errors, Map model)
{
HttpServletRequest request = ((ServletExternalContext)context.getExternalContext()).getRequest();
String flowMode = ActionUtils.getFlowMode(context.getActiveFlow().getId());
StateDefinition state = context.getCurrentState();
ReportSetup reportSetup = (ReportSetup) ((ComponentCommand)command).getComponents().get(this.getDefaultObjectName());
model = super.addReferenceData(context, command, errors, model);
if (state.getId().equals("reportSetup")) {
// override the setting of dateCriteria for the purpose of the model so that the view
// will not display the dateCriteria, because only using the startDate, not the endDate, so
// the display of the startDate criteria is done in the udsExtract.jsp
// note that the dateCriteria is set true otherwise to take advantage of this handler and the
// superclass handler's handling of the dateStart property, w.r.t. quick date selection, etc.
model.put("dateCriteria", false);
}
if (state.getId().equals("reportGen")) {
model.put("naccNpExtractRecords", (List)((ComponentCommand)command).getComponents().get("naccNpExtractRecords"));
}
return model;
}
// override because startDate is a datetime so have CalendarHandlerUtils format quick date selections with a time portion
protected Event handleCustomEvent(RequestContext context, Object command, BindingResult errors) throws Exception {
// handle filter events for quick date range selection
HttpServletRequest request = ((ServletExternalContext)context.getExternalContext()).getRequest();
ReportSetup reportSetup = (ReportSetup) ((ComponentCommand)command).getComponents().get(this.getDefaultObjectName());
CalendarHandlerUtils.setDateFilterParams(context,(LavaDaoFilter)reportSetup.getFilter(), this.defaultDisplayRange, this.startDateParam, this.endDateParam);
// reflect the new date param values in the view by updating the custom date params
CalendarDaoUtils.updateCustomParamsFromDateParams(reportSetup.getFilter(), this.startDateParam, this.endDateParam, Boolean.TRUE);
return new Event(this,SUCCESS_FLOW_EVENT_ID);
}
// the "generate" event is handled when the user submits parameters to generate the report. the
// actual generation is done by the reporting engine (Jasper Reports) but this handler can be used
// to validate that the parameters have been correctly set
protected Event doGenerate(RequestContext context, Object command, BindingResult errors) throws Exception {
HttpServletRequest request = ((ServletExternalContext)context.getExternalContext()).getRequest();
ReportSetup reportSetup = (ReportSetup) ((ComponentCommand)command).getComponents().get(this.getDefaultObjectName());
LavaDaoFilter reportFilter = reportSetup.getFilter();
// transfer the customStartDate param used by the view to the startParam used in the query
CalendarHandlerUtils.handleCustomDateFilter(reportFilter, this.startDateParam, this.endDateParam);
// conditionally check required fields here, i.e. since only one of the startDate and
// patientId report parameters are required, but it does not matter which one, can not
// enforce required fields via the binder, so do it here after the report params have
// been bound
if (reportFilter.getParam(this.startDateParam) == null && reportFilter.getParam("patientId") == null) {
LavaComponentFormAction.createCommandError(errors, "naccNpExtract.reportSetup.required", null);
return new Event(this,ERROR_FLOW_EVENT_ID);
}
//do query for records here
LavaDaoFilter naccNpFilter = NaccPathology.MANAGER.newFilterInstance(this.getCurrentUser(request));
//NACC NP sorted by patient and data collection date.
naccNpFilter.setAlias("patient", "patient");
naccNpFilter.addSort("patient.id",true);
naccNpFilter.addSort("dcDate",true);
//set completion status and submission status filters
naccNpFilter.addDaoParam(naccNpFilter.daoOr(naccNpFilter.daoNull("submissionstatus"),naccNpFilter.daoNot(naccNpFilter.daoEqualityParam("submissionstatus", "DO NOT SUBMIT"))));
naccNpFilter.addDaoParam(naccNpFilter.daoEqualityParam("deStatus", "Complete"));
naccNpFilter.addDaoParam(naccNpFilter.daoEqualityParam("dcStatus", "Complete"));
Date startDate = (Date)reportFilter.getParam(this.startDateParam);
//if start date supplied, then get all records modified after the date supplied
if(startDate!=null){
naccNpFilter.addDaoParam(naccNpFilter.daoGreaterThanOrEqualParam("modified", startDate));
}
//if a specific patient is specified, then limit results to that patient
Object idParam = reportFilter.getParam("patientId");
if(idParam!=null){
Long patientId = null;
if(idParam instanceof Long){
patientId = (Long)idParam;
}else if(idParam instanceof String){
try{
patientId = Long.valueOf((String)idParam);
}catch(NumberFormatException nfe){};
}
if(patientId!=null){
naccNpFilter.addDaoParam(naccNpFilter.daoEqualityParam("patient.id",patientId));
}
}
List naccNpExtractInstruments = NaccPathology.MANAGER.get(naccNpFilter);
Collections.sort(naccNpExtractInstruments, UdsUploadUtils.udsExtractComparator);
List naccNpExtractRecords = new ArrayList(naccNpExtractInstruments.size());
for(Object o : naccNpExtractInstruments){
if(UdsUploadable.class.isAssignableFrom(o.getClass())){
List<String> records = ((UdsUploadable)o).getUdsUploadCsvRecords();
for(String record : records){
naccNpExtractRecords.add(new UdsExtractReportDto(record));
}
}
}
((ComponentCommand)command).getComponents().put("naccNpExtractRecords",naccNpExtractRecords);
return new Event(this,SUCCESS_FLOW_EVENT_ID);
}
}
| bsd-2-clause |
jackstraw66/web | livescribe/lsadmin/src/main/java/com/livescribe/admin/dao/CustomAuthorizationDao.java | 2367 | /**
*
*/
package com.livescribe.admin.dao;
import java.util.List;
import org.hibernate.Query;
import com.livescribe.framework.orm.consumer.Authorization;
import com.livescribe.framework.orm.consumer.AuthorizationDao;
/**
* @author mnaqvi
*
*/
public class CustomAuthorizationDao extends AuthorizationDao {
/**
* <p>Default class constructor.</p>
*
*/
public CustomAuthorizationDao() {
super();
}
/**
* <p>Returns a list of EN authorizations by the given userId.</p>
*
* @param userId the user Id (surrogate key of the User table)
* @return a <code>List</code> of <code>Authorization</code>s.
*/
public List<Authorization> findByUserId(Long userId) {
Query q = this.sessionFactoryConsumer.getCurrentSession().createQuery("from Authorization a where a.user.userId = :userId and a.provider = :provider");
q.setLong("userId", userId);
q.setString("provider", "EN");
@SuppressWarnings("unchecked")
List<Authorization> list = q.list();
return list;
}
/**
* <p>Returns the primary EN authorization for the given userId.</p>
*
* @param userId the user Id (surrogate key of the User table)
* @return the <bold>primary</bold> <code>Authorization</code>.
*/
public Authorization findPrimaryENAuthByUserId(Long userId) {
Query q = this.sessionFactoryConsumer.getCurrentSession().createQuery("from Authorization a where a.user.userId = :userId and a.provider = :provider and a.isPrimary = 1");
q.setLong("userId", userId);
q.setString("provider", "EN");
@SuppressWarnings("unchecked")
List<Authorization> list = q.list();
if (null == list || list.isEmpty()) {
return null;
}
return list.get(0); // There cannot be more than 1 EN authorizations for a user.
}
/**
* <p>Returns a list of EN authorizations by the given userId.</p>
*
* @param userId the user Id (surrogate key of the User table)
* @return a <code>List</code> of <code>Authorization</code>s.
*/
public List<Authorization> findNonPrimaryENAuthsByUserId(Long userId) {
Query q = this.sessionFactoryConsumer.getCurrentSession().createQuery("from Authorization a where a.user.userId = :userId and a.provider = :provider and a.isPrimary = 0");
q.setLong("userId", userId);
q.setString("provider", "EN");
@SuppressWarnings("unchecked")
List<Authorization> list = q.list();
return list;
}
}
| bsd-2-clause |
joshng/papaya | papaya/src/main/java/com/joshng/util/collect/PersistentSet.java | 7181 | package com.joshng.util.collect;
import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import com.joshng.util.blocks.F2;
import javax.annotation.concurrent.Immutable;
import java.util.*;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* A persistent immutable single linked set class.
*
* NOTE: this is not an efficient structure for large sets: insertion is O(N)
*/
@Immutable
public class PersistentSet<T> extends AbstractSequentialList<T> implements Set<T> {
private static final F2 WITH = new F2<Object, PersistentSet<Object>, PersistentSet<Object>>() {
@Override
public PersistentSet<Object> apply(Object input1, PersistentSet<Object> input2) {
return input2.with(input1);
}
};
private final T value;
// logically final, but Builder uses mutable private copies
private PersistentSet<T> next;
@SuppressWarnings("unchecked")
public static <T> F2<T, PersistentSet<T>, PersistentSet<T>> with() {
return WITH;
}
private PersistentSet(T value, PersistentSet<T> next) {
this.value = value;
this.next = next;
}
@SuppressWarnings({"rawtypes"})
private final static PersistentSet Nil = makeNil();
@SuppressWarnings({"rawtypes", "unchecked"})
private static PersistentSet makeNil() {
PersistentSet nil = new PersistentSet(null, null);
nil.next = nil;
return nil;
}
/**
* @return The empty set
*/
@SuppressWarnings("unchecked")
public static <T> PersistentSet<T> nil() {
return Nil;
}
/**
* @return A set containing the specified value
*/
@SuppressWarnings("unchecked")
public static <T> PersistentSet<T> of(T value) {
return new PersistentSet<T>(value, Nil);
}
/**
* @return A set containing the specified values
*/
@SuppressWarnings("unchecked")
public static <T> PersistentSet<T> of(T v1, T v2) {
return Nil.with(v2).with(v1);
}
/**
* @return A set containing the specified values
*/
@SuppressWarnings("unchecked")
public static <T> PersistentSet<T> of(T v1, T v2, T v3) {
return Nil.with(v3).with(v2).with(v1);
}
/**
* @return A set containing the specified values
*/
@SuppressWarnings("unchecked")
public static <T> PersistentSet<T> of(T... values) {
PersistentSet<T> set = Nil;
for (int i = values.length - 1; i >= 0; --i)
set = set.with(values[i]);
return set;
}
/**
* @return A new set with the values from the Iterable
*/
public static <T> PersistentSet<T> copyOf(Iterable<T> values) {
if (values instanceof PersistentSet) return (PersistentSet<T>) values;
return new Builder<T>().addAll(values).build();
}
public static <T> Builder<T> builder() {
return new Builder<T>();
}
/**
* @return The value at the start of the set
*/
public T head() {
return value;
}
/**
* @return The remainder of the set without the first element
*/
public PersistentSet<T> tail() {
return next;
}
/**
* @return A new set with value as the head and the old set as the tail
*/
public PersistentSet<T> with(T value) {
checkNotNull(value);
return contains(value) ? this : new PersistentSet<>(value, this);
}
@Override
public T get(int i) {
if (i >= 0)
for (PersistentSet<T> set = this; set != Nil; set = set.tail())
if (i-- == 0)
return set.head();
throw new IndexOutOfBoundsException();
}
/**
* Note: O(N)
*
* @return A new set omitting the specified value
*/
public PersistentSet<T> without(T x) {
if (x == null) return this;
PersistentSet<T> match = this;
while (!x.equals(match.head())) {
if (match.isEmpty()) return this;
match = match.tail();
}
Builder<T> prefix = new Builder<>();
PersistentSet<T> p = this;
while (p != match) {
prefix.add(p.head());
}
return prefix.buildOnto(match.tail());
}
public PersistentSet<T> union(Iterable<? extends T> items) {
return PersistentSet.<T>builder().addAll(items).buildOnto(this);
}
/**
* Note: O(N)
*/
@Override
public boolean contains(Object value) {
for (PersistentSet<T> set = this; set != Nil; set = set.next)
if (value.equals(set.head()))
return true;
return false;
}
@Override
@SuppressWarnings("unchecked")
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof PersistentSet))
return false;
PersistentSet<?> x = this;
PersistentSet<Object> y = (PersistentSet<Object>) other;
for (; x != Nil && y != Nil; x = x.tail(), y = y.tail())
if (!x.head().equals(y.head()))
return false;
return x == Nil && y == Nil;
}
public static final Joiner commaJoiner = Joiner.on(",");
@Override
public String toString() {
return "(" + commaJoiner.join(this) + ")";
}
/**
* Note: O(N)
*
* @return The number of elements in the set
*/
@Override
public int size() {
int size = 0;
for (PersistentSet<T> set = this; set != Nil; set = set.next)
++size;
return size;
}
@Override
public boolean isEmpty() {
return this == Nil;
}
/**
* @return A new set with the elements in the reverse order
*/
public PersistentSet<T> reversed() {
PersistentSet<T> set = nil();
for (PersistentSet<T> p = this; p != Nil; p = p.next) {
set = new PersistentSet<>(p.value, set);
}
return set;
}
public static class Builder<T> {
private PersistentSet<T> set = nil();
public Builder<T> add(T value) {
set = set.with(value);
return this;
}
public Builder<T> addAll(Iterable<? extends T> values) {
for (T value : values)
add(value);
return this;
}
/**
* The Builder cannot be used after calling build()
*
* @return The set
*/
@SuppressWarnings("unchecked")
public PersistentSet<T> build() {
return buildOnto(nil());
}
public PersistentSet<T> buildOnto(PersistentSet<T> tail) {
// reverse in place by changing pointers (no allocation)
Set<T> contents = Sets.newHashSet(tail);
for (PersistentSet<T> p = set; p != Nil; ) {
PersistentSet<T> next = p.next;
if (!contents.contains(p.value)) {
p.next = tail;
tail = p;
}
p = next;
}
set = null;
return tail;
}
}
@Override
public Iterator<T> iterator() {
return new Iter<T>(this);
}
private static class Iter<T> implements Iterator<T> {
private PersistentSet<T> set;
private Iter(PersistentSet<T> set) {
this.set = new PersistentSet<T>(null, set);
}
public boolean hasNext() {
return set.tail() != Nil;
}
public T next() {
set = set.tail();
return set.head();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
@Override
public ListIterator<T> listIterator(int index) {
throw new UnsupportedOperationException();
}
@Override public Spliterator<T> spliterator() {
return Spliterators.spliterator(this, Spliterator.ORDERED | Spliterator.DISTINCT);
}
}
| bsd-2-clause |
mianli/Dobelity | dobe/src/main/java/com/study/mli/dobe/customview/loader/PullableListView.java | 1583 | package com.study.mli.dobe.customview.loader;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
/**
* Created by limian on 2016/9/18.
*/
public class PullableListView extends ListView implements Pullable {
public PullableListView(Context context) {
super(context);
}
public PullableListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PullableListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean canPullDown()
{
if (getCount() == 0)
{
// 没有item的时候也可以下拉刷新
return true;
} else if (getFirstVisiblePosition() == 0
&& getChildAt(0).getTop() >= 0)
{
// 滑到ListView的顶部了
return true;
} else
return false;
}
@Override
public boolean canPullUp()
{
if (getCount() == 0)
{
// 没有item的时候也可以上拉加载
return true;
} else if (getLastVisiblePosition() == (getCount() - 1))
{
// 滑到底部了
if (getChildAt(getLastVisiblePosition() - getFirstVisiblePosition()) != null
&& getChildAt(
getLastVisiblePosition()
- getFirstVisiblePosition()).getBottom() <= getMeasuredHeight())
return true;
}
return false;
}
}
| bsd-2-clause |
UniquePassive/runelite | runelite-client/src/main/java/net/runelite/client/plugins/teamcapes/TeamCapesOverlay.java | 2854 | /*
* Copyright (c) 2017, Devin French <https://github.com/devinfrench>
* 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 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 net.runelite.client.plugins.teamcapes;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.util.Map;
import javax.inject.Inject;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayPriority;
import net.runelite.client.ui.overlay.components.PanelComponent;
public class TeamCapesOverlay extends Overlay
{
private final TeamCapesPlugin plugin;
private final TeamCapesConfig config;
private final PanelComponent panelComponent = new PanelComponent();
@Inject
TeamCapesOverlay(TeamCapesPlugin plugin, TeamCapesConfig config)
{
setPosition(OverlayPosition.TOP_LEFT);
setPriority(OverlayPriority.LOW);
this.plugin = plugin;
this.config = config;
}
@Override
public Dimension render(Graphics2D graphics)
{
Map<Integer, Integer> teams = plugin.getTeams();
if (teams.isEmpty())
{
return null;
}
panelComponent.getLines().clear();
for (Map.Entry<Integer, Integer> team : teams.entrySet())
{
// Only display team capes that have a count greater than the configured minimum.
if (team.getValue() >= config.getMinimumCapeCount())
{
panelComponent.getLines().add(new PanelComponent.Line(
"Team-" + Integer.toString(team.getKey()),
Color.WHITE,
Integer.toString(team.getValue()),
Color.WHITE
));
}
}
return panelComponent.render(graphics);
}
}
| bsd-2-clause |
EPapadopoulou/PersoNIS | api/android/archive/external/src/main/java/org/societies/android/api/privacytrust/trust/model/ATrustedEntityId.java | 5802 | /**
* Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET
* (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije
* informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE
* COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp.,
* INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM
* ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC))
* 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 org.societies.android.api.privacytrust.trust.model;
import org.societies.api.privacytrust.trust.model.MalformedTrustedEntityIdException;
import org.societies.api.privacytrust.trust.model.TrustedEntityId;
import android.os.Parcel;
import android.os.Parcelable;
/**
* This class is a <code>Parcelable</code> wrapper around {@link TrustedEntityId}
* which is used to uniquely identify trusted CSSs, CISs or services.
*
* @author <a href="mailto:nicolas.liampotis@cn.ntua.gr">Nicolas Liampotis</a> (ICCS)
* @since 0.4
*/
public final class ATrustedEntityId implements Parcelable {
/** The {@link TrustedEntityId} wrapped in this <code>ATrustedEntityId</code>. */
private final TrustedEntityId teid;
public static final Parcelable.Creator<ATrustedEntityId> CREATOR =
new Parcelable.Creator<ATrustedEntityId>() {
/**
* Creates a <code>ATrustedEntityId</code> from the given
* {@link Parcel}.
*
* @throws IllegalArgumentException
* if a <code>ATrustedEntityId</code> cannot be
* created from <code>source</code>.
* @see ATrustedEntityId#writeToParcel(Parcel, int)
*/
public ATrustedEntityId createFromParcel(Parcel source) {
final String str = source.readString();
TrustedEntityId teid = null;
try {
teid = new TrustedEntityId(str);
} catch (MalformedTrustedEntityIdException mteie) {
throw new IllegalArgumentException(
mteie.getLocalizedMessage(), mteie);
}
return new ATrustedEntityId(teid);
}
public ATrustedEntityId[] newArray(int size) {
return new ATrustedEntityId[size];
}
};
/**
* Creates a <code>ATrustedEntityId</code> instance from the given
* {@link TrustedEntityId}.
*
* @throws NullPointerException
* if <code>teid</code> is <code>null</code>.
*/
public ATrustedEntityId(final TrustedEntityId teid) {
if (teid == null)
throw new NullPointerException("teid can't be null");
this.teid = teid;
}
/**
* Creates a <code>ATrustedEntityId</code> instance from the given
* {@link TrustedEntityId} String representation.
*
* @throws NullPointerException
* if <code>str</code> is <code>null</code>.
* @throws MalformedTrustedEntityIdException
* if <code>str</code> is not formatted correctly.
*/
public ATrustedEntityId(final String str) throws MalformedTrustedEntityIdException {
this(new TrustedEntityId(str));
}
/**
* Returns the {@link TrustedEntityId} wrapped in this
* <code>ATrustedEntityId</code>.
*
* @return the {@link TrustedEntityId} wrapped in this
* <code>ATrustedEntityId</code>.
*/
public TrustedEntityId getTeid() {
return this.teid;
}
/*
* @see android.os.Parcelable#describeContents()
*/
public int describeContents() {
return 0;
}
/*
* @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
*/
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.teid.toString());
}
/**
* Returns a String representation of this <code>ATrustedEntityId</code>.
*
* @return a String representation of this <code>ATrustedEntityId</code>.
*/
@Override
public String toString() {
return this.teid.toString();
}
/*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.teid.hashCode();
}
/*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object that) {
if (this == that)
return true;
if (that == null)
return false;
if (this.getClass() != that.getClass())
return false;
ATrustedEntityId other = (ATrustedEntityId) that;
return (this.teid.equals(other.teid));
}
} | bsd-2-clause |
geronimo-iia/ferox | ferox-renderer-lwjgl/src/test/java/com/ferox/renderer/impl/lwjgl/LwjglFixedFunctionTest.java | 6716 | /*
* Ferox, a graphics and game library in Java
*
* Copyright (c) 2012, Michael Ludwig
* 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 com.ferox.renderer.impl.lwjgl;
import com.ferox.math.Matrix4;
import com.ferox.math.Vector3;
import com.ferox.math.Vector4;
import com.ferox.math.bounds.Frustum;
import com.ferox.renderer.*;
import com.ferox.renderer.builder.Texture2DBuilder;
import com.ferox.renderer.geom.Geometry;
import com.ferox.renderer.geom.Shapes;
/**
*
*/
public class LwjglFixedFunctionTest {
static double x = 0;
public static void main(String[] args) throws Exception {
Framework.Factory.enableDebugMode();
final Framework framework = Framework.Factory.create();
System.out.println(framework.getCapabilities().getMajorVersion() + "." + framework.getCapabilities().getMinorVersion());
final OnscreenSurface s = framework.createSurface(new OnscreenSurfaceOptions().withDepthBuffer(24).fixedSize());
s.setTitle("Hello World");
s.setVSyncEnabled(true);
// final Geometry box = Sphere.create(framework, 1.5, 16);
final Geometry box = Shapes.createBox(framework, 3.0);
float[] texData = new float[256 * 256 * 3];
for (int y = 0; y < 256; y++) {
for (int x = 0; x < 256; x++) {
texData[y * 256 * 3 + x * 3] = x / 255f;
texData[y * 256 * 3 + x * 3 + 1] = y / 255f;
}
}
Texture2DBuilder tb = framework.newTexture2D().width(256).height(256);
tb.rgb().mipmap(0).from(texData);
final Texture2D tex = tb.build();
int frames = 0;
long now = System.currentTimeMillis();
try {
while (!s.isDestroyed()) {
framework.invoke(new Task<Void>() {
@Override
public Void run(HardwareAccessLayer access) {
Context c = access.setActiveSurface(s);
if (c == null)
return null;
FixedFunctionRenderer r = c.getFixedFunctionRenderer();
r.clear(true, true, true, new Vector4(.3, .2, .5, 1), 1.0, 0);
Frustum view = new Frustum(60.0, 1.0, 1.0, 70.0);
view.setOrientation(new Vector3(10, 0, 45), new Vector3(0, 0, -1),
new Vector3(0, 1, 0));
r.setProjectionMatrix(view.getProjectionMatrix());
r.setTextureEyePlanes(1, new Matrix4().setIdentity());
r.setModelViewMatrix(view.getViewMatrix());
// r.setLightingEnabled(true);
r.setLightEnabled(0, true);
// r.setGlobalAmbientLight(new Vector4(.3, .3, .3, 1.0));
r.setLightColor(0, new Vector4(1, 1, 1, 1), new Vector4(1, 1, 1, 1),
new Vector4(1, 1, 1, 1));
r.setLightPosition(0, new Vector4(0, 0, 25, 1));
// r.setSpotlight(0, new Vector3(0, 0, -1), 15, 40);
r.setMaterialDiffuse(new Vector4(1.0, 1.0, 1.0, 1));
r.setMaterialAmbient(new Vector4(.2, .2, .2, 1));
r.setMaterialSpecular(new Vector4(.2, .9, .2, 1));
r.setMaterialShininess(10.0);
r.setTexture(1, tex);
r.setTextureCoordinateSource(1, FixedFunctionRenderer.TexCoordSource.EYE);
r.setNormals(box.getNormals());
r.setVertices(box.getVertices());
// r.setTextureCoordinates(1, box.getTextureCoordinates());
r.setIndices(box.getIndices());
r.setDrawStyle(Renderer.DrawStyle.SOLID, Renderer.DrawStyle.LINE);
Matrix4 m = new Matrix4().setIdentity();
Vector4 t = new Vector4();
for (int z = 0; z < 5; z++) {
for (int y = 0; y < 5; y++) {
for (int x = 0; x < 5; x++) {
t.set(LwjglFixedFunctionTest.x + 3.5 * (x - 2), 3.5 * (y - 2),
3.5 * (z - 2), 1);
m.setCol(3, t);
r.setModelViewMatrix(m.mul(view.getViewMatrix(), m));
r.render(box.getPolygonType(), box.getIndexOffset(), box.getIndexCount());
}
}
}
x += 0.03;
if (x > 20) {
x = -20;
}
c.flush();
return null;
}
}).get();
frames++;
}
} finally {
double time = (System.currentTimeMillis() - now) / 1e3;
System.out.printf("Total frames: %d Total time: %.2f sec Average fps: %.2f\n", frames, time,
frames / time);
framework.destroy();
}
}
}
| bsd-2-clause |
0359xiaodong/WaniKani-for-Android | WaniKani/src/tr/xip/wanikani/dialogs/LevelPickerDialogFragment.java | 7272 | package tr.xip.wanikani.dialogs;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashSet;
import tr.xip.wanikani.R;
import tr.xip.wanikani.adapters.LevelPickerCheckBoxAdapter;
public class LevelPickerDialogFragment extends DialogFragment implements LevelPickerCheckBoxAdapter.LevelPickerCheckBoxAdapterListener {
private static final String ARG_USER_LEVEL = "user_level";
private static final String ARG_FRAGMENT_ID = "fragment_id";
private static final String ARG_SELECTED_ITEMS_STORAGE = "selected_items_storage";
private static final String ARG_SELECTION_STORAGE = "selection_storage";
Context context;
LevelDialogListener mListener;
String userLevel;
int fragmentId;
String selectedLevel = "0";
int wanikaniLevelsNumber;
private HashSet<Integer> mSelectedItems;
private ArrayList<Integer> mSelectedItemsStorage;
private boolean[] mSelection;
private boolean[] mSelectionStorage;
public void init(int fragmentId, String userLevel) {
this.userLevel = userLevel;
this.fragmentId = fragmentId;
}
@Override
public Dialog onCreateDialog(Bundle bundle) {
context = getActivity();
wanikaniLevelsNumber = context.getResources().getInteger(R.integer.wanikani_levels_number);
Dialog dialog = super.onCreateDialog(bundle);
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
if (bundle != null) {
userLevel = bundle.getString(ARG_USER_LEVEL);
fragmentId = bundle.getInt(ARG_FRAGMENT_ID);
mSelectedItemsStorage = bundle.getIntegerArrayList(ARG_SELECTED_ITEMS_STORAGE);
mSelectionStorage = bundle.getBooleanArray(ARG_SELECTION_STORAGE);
}
mListener = (LevelDialogListener) getFragmentManager().findFragmentById(fragmentId);
mSelectedItems = new HashSet<Integer>();
mSelection = new boolean[wanikaniLevelsNumber];
if (mSelectedItemsStorage == null && mSelectionStorage == null) {
mSelectedItems.add(Integer.parseInt(userLevel));
mSelection[Integer.parseInt(userLevel) - 1] = true;
}
if (mSelectedItemsStorage != null) {
mSelectedItems.clear();
for (int i = 0; i < mSelectedItemsStorage.size(); ++i) {
mSelectedItems.add(mSelectedItemsStorage.get(i));
}
}
if (mSelectionStorage != null) {
for (int i = 0; i < mSelectionStorage.length; ++i) {
mSelection[i] = mSelectionStorage[i];
}
}
return dialog;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_level_picker, null);
Button mOk = (Button) view.findViewById(R.id.button1);
Button mReset = (Button) view.findViewById(R.id.button2);
Button mCancel = (Button) view.findViewById(R.id.button3);
final ListView mCheckList = (ListView) view.findViewById(R.id.listView);
ArrayList<LevelPickerCheckBoxAdapter.LevelCheckBox> mListItems = new ArrayList<LevelPickerCheckBoxAdapter.LevelCheckBox>();
for (int i = 0; i < wanikaniLevelsNumber; i++) {
LevelPickerCheckBoxAdapter.LevelCheckBox checkBox =
new LevelPickerCheckBoxAdapter.LevelCheckBox(i + 1 + "", mSelection[i]);
mListItems.add(checkBox);
}
mCheckList.setAdapter(new LevelPickerCheckBoxAdapter(context,
R.layout.item_level_picker_checkbox, mListItems, this));
mOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectedLevel = "0";
for (Integer item : mSelectedItems) {
if (selectedLevel.equals("0")) {
selectedLevel = (item + 1) + "";
} else {
selectedLevel += "," + (item + 1);
}
}
if (!selectedLevel.equals("0")) {
mListener.onLevelDialogPositiveClick(LevelPickerDialogFragment.this, selectedLevel);
if (mSelectedItemsStorage == null) {
mSelectedItemsStorage = new ArrayList<Integer>();
}
if (mSelectionStorage == null) {
mSelectionStorage = new boolean[wanikaniLevelsNumber];
}
mSelectedItemsStorage.clear();
for (int item : mSelectedItems) {
mSelectedItemsStorage.add(item);
}
for (int i = 0; i < mSelection.length; i++) {
mSelectionStorage[i] = mSelection[i];
}
dismiss();
} else
Toast.makeText(context, R.string.error_no_levels_selected, Toast.LENGTH_LONG).show();
}
});
mReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mSelectedItems != null)
mSelectedItems.clear();
if (mSelection != null)
mSelection = new boolean[wanikaniLevelsNumber];
if (mSelectedItemsStorage != null)
mSelectedItemsStorage.clear();
if (mSelectionStorage != null)
mSelectionStorage = new boolean[wanikaniLevelsNumber];
mListener.onLevelDialogResetClick(LevelPickerDialogFragment.this, userLevel);
dismiss();
}
});
mCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
return view;
}
@Override
public void onLevelPickerCheckBoxAdapterItemClickListener(int which, boolean isChecked) {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
mSelectedItems.remove(Integer.valueOf(which));
}
mSelection[which] = isChecked;
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(ARG_USER_LEVEL, userLevel);
outState.putInt(ARG_FRAGMENT_ID, fragmentId);
outState.putIntegerArrayList(ARG_SELECTED_ITEMS_STORAGE, mSelectedItemsStorage);
outState.putBooleanArray(ARG_SELECTION_STORAGE, mSelectionStorage);
super.onSaveInstanceState(outState);
}
public interface LevelDialogListener {
public void onLevelDialogPositiveClick(DialogFragment dialog, String level);
public void onLevelDialogResetClick(DialogFragment dialog, String level);
}
}
| bsd-2-clause |
cv/htmlcheck | src/com/github/cv/htmlcheck/HtmlCheckError.java | 748 | /*
* See LICENSE file in distribution for copyright and licensing information.
*/
package com.github.cv.htmlcheck;
import org.jdom.Element;
public class HtmlCheckError extends AssertionError {
private static final long serialVersionUID = 1L;
private Element element;
public HtmlCheckError(String message) {
super(message);
}
public HtmlCheckError(String message, Element element) {
super(message);
this.element = element;
}
@Override
public boolean equals(Object that) {
return toString().equals(that.toString());
}
public Element getElement() {
return element;
}
@Override
public String toString() {
return "\n" + getMessage();
}
}
| bsd-2-clause |
iotoasis/SDA | src/main/java/com/pineone/icbms/sda/kb/model/OneM2MJenaModelFactory.java | 1366 | package com.pineone.icbms.sda.kb.model;
import org.apache.jena.graph.Triple;
import org.apache.jena.rdf.model.Statement;
import com.pineone.icbms.sda.kb.dto.OneM2MAEDTO;
import com.pineone.icbms.sda.kb.dto.OneM2MCSEBaseDTO;
import com.pineone.icbms.sda.kb.dto.OneM2MContainerDTO;
import com.pineone.icbms.sda.kb.dto.OneM2MContentInstanceDTO;
import com.pineone.icbms.sda.kb.dto.OneM2MRemoteCSEDTO;
public class OneM2MJenaModelFactory {
TripleMap<Statement> triples ;
public OneM2MJenaModelFactory(OneM2MContainerDTO dto){
triples = dto.getTriples();
}
public OneM2MJenaModelFactory(OneM2MContentInstanceDTO dto){
triples = dto.getTriples();
}
public OneM2MJenaModelFactory(OneM2MAEDTO dto){
triples = dto.getTriples();
}
public OneM2MJenaModelFactory(OneM2MCSEBaseDTO dto){
triples = dto.getTriples();
}
public OneM2MJenaModelFactory(OneM2MRemoteCSEDTO dto){
triples = dto.getTriples();
}
public String makeTriple(){
return "http://somewhere/JohnSmith http://www.w3.org/2001/vcard-rdf/3.0#FN \"John Smith\" ";
}
/**
* 트리플 생성
* @return
*/
public static Triple createDefaultTriple() {
return null;
}
public static void main(String[] args) {
Triple triple = OneM2MJenaModelFactory.createDefaultTriple();
String a = null;
}
}
| bsd-2-clause |
warriordog/acomputerbot_extlib | src/net/acomputerdog/ircbot/ext/command/CommandWhoAmI.java | 1313 | package net.acomputerdog.ircbot.ext.command;
import com.sorcix.sirc.structure.Channel;
import com.sorcix.sirc.structure.User;
import com.sorcix.sirc.util.Chattable;
import net.acomputerdog.ircbot.command.Command;
import net.acomputerdog.ircbot.command.util.CommandLine;
import net.acomputerdog.ircbot.main.IrcBot;
public class CommandWhoAmI extends Command {
public CommandWhoAmI(IrcBot bot) {
super(bot, "WhoAmI", "whoami", "who-am-i", "who_am_i");
}
@Override
public String getDescription() {
return "Returns information about the caller.";
}
@Override
public boolean processCommand(Channel channel, User sender, Chattable target, CommandLine command) {
User user;
if (channel != null) {
user = bot.getConnection().createUser(sender.getNickLower(), channel.getName());
} else {
user = sender;
}
bot.getConnection().sendRaw("/WHO " + user.getNick());
target.send("Nick: " + user.getNick() + " (" + user.getNickLower() + ")"); //String.valueOf(user.getPrefix() == '0' ? "@" : user.getPrefix()) +
target.send("RealName: " + user.getRealName());
target.send("Username: " + user.getUserName());
target.send("Hostname: " + user.getHostName());
return true;
}
}
| bsd-2-clause |
monnetproject/bliss | clesa/src/main/java/eu/monnetproject/bliss/clesa/ONETATrain.java | 4834 | /**
* *******************************************************************************
* Copyright (c) 2011, Monnet 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. * Neither the name of the Monnet Project 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 MONNET PROJECT 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.monnetproject.bliss.clesa;
import eu.monnetproject.bliss.CLIOpts;
import eu.monnetproject.bliss.ParallelBinarizedReader;
import eu.monnetproject.bliss.SimilarityMetric;
import eu.monnetproject.bliss.WordMap;
import eu.monnetproject.math.sparse.DiskBackedRealVector;
import eu.monnetproject.math.sparse.SparseIntArray;
import eu.monnetproject.math.sparse.SparseMatrix;
import eu.monnetproject.math.sparse.Vector;
import eu.monnetproject.math.sparse.eigen.CholeskyDecomposition;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
/**
*
* @author John McCrae
*/
public class ONETATrain {
public static void main(String[] args) throws Exception {
final CLIOpts opts = new CLIOpts(args);
final File corpus = opts.roFile("corpus[.gz|.bz2]", "The corpus");
final File wordMap = opts.roFile("wordMap", "The word map");
final File outFile1 = opts.woFile("outFile", "The file to write the source L-matrix to");
final File outFile2 = opts.woFile("outFile", "The file to write the target L-matrix to");
opts.restAsSystemProperties();
if (!opts.verify(ONETATrain.class)) {
return;
}
final int W = WordMap.calcW(wordMap);
train(corpus, W, outFile1, outFile2);
}
public static void train(final File corpus, final int W, final File kernelFile1, final File kernelFile2) throws IOException {
final ParallelBinarizedReader pbr = new ParallelBinarizedReader(CLIOpts.openInputAsMaybeZipped(corpus));
System.err.println("Creating CL-ESA metric");
final SimilarityMetric metric = new CLESAFactory().makeMetric(pbr, W);
final int J = metric.K();
pbr.close();
final ParallelBinarizedReader pbr2 = new ParallelBinarizedReader(CLIOpts.openInputAsMaybeZipped(corpus));
SparseIntArray[] s;
final DataOutputStream kOut1 = new DataOutputStream(CLIOpts.openOutputAsMaybeZipped(kernelFile1));
final DataOutputStream kOut2 = new DataOutputStream(CLIOpts.openOutputAsMaybeZipped(kernelFile2));
int j = 0;
System.err.print("Calculating kernel");
while ((s = pbr2.nextFreqPair(W)) != null) {
final Vector<Double> v0 = metric.simVecSource(s[0]);
for(int i = 0; i < v0.length(); i++) {
kOut1.writeDouble(v0.doubleValue(i));
}
final Vector<Double> v1 = metric.simVecTarget(s[1]);
for(int i = 0; i < v1.length(); i++) {
kOut2.writeDouble(v1.doubleValue(i));
}
if (++j % 10 == 0) {
System.err.print(".");
}
}
System.err.println();
kOut1.flush();
kOut1.close();
kOut2.flush();
kOut2.close();
System.err.print("Cholesky decomp source kernel");
CholeskyDecomposition.denseOnDiskDecomp(kernelFile1, J);
System.err.println();
System.err.print("Cholesky decomp target kernel");
CholeskyDecomposition.denseOnDiskDecomp(kernelFile2, J);
System.err.println();
}
}
| bsd-3-clause |
al3xandru/testng-jmock | core/src/org/jmock/core/constraint/IsGreaterThan.java | 694 | /* Copyright (c) 2000-2004 jMock.org
*/
package org.jmock.core.constraint;
import org.jmock.core.Constraint;
import org.jmock.core.Formatting;
/**
* Is the value greater than another {@link java.lang.Comparable} value?
*/
public class IsGreaterThan implements Constraint
{
private Comparable lowerLimit;
public IsGreaterThan( Comparable lowerLimit ) {
this.lowerLimit = lowerLimit;
}
public boolean eval( Object arg ) {
return lowerLimit.compareTo(arg) < 0;
}
public StringBuffer describeTo( StringBuffer buffer ) {
return buffer.append("a value greater than ")
.append(Formatting.toReadableString(lowerLimit));
}
}
| bsd-3-clause |
stuhacking/SGEngine | src/main/java/sge/renderer/gl/GLOrthographicProjection.java | 1184 | package sge.renderer.gl;
import sge.math.Matrix4;
public class GLOrthographicProjection implements GLProjection {
public float nearPlane = 1.0f;
public float farPlane = 100.0f;
public GLOrthographicProjection () {
this(1.0f, 100.0f);
}
public GLOrthographicProjection (float near, float far) {
this.nearPlane = near;
this.farPlane = far;
}
/* (non-javadoc)
* @see sge.renderer.gl.GLProjection#getProjectionMatrix(int, int)
*/
@Override
public Matrix4 getProjectionMatrix (final int width, final int height) {
float f_ = farPlane;
float n_ = nearPlane;
float aspectRatio = (float) width / (float) height;
float size = Math.min(width / 2.0f, height / 2.0f);
float left = -size, right = size, top = size / aspectRatio, bottom = -size / aspectRatio;
return new Matrix4(
2 / (right - left), 0.0f, 0.0f, 0.0f,
0.0f, 2 / (top - bottom), 0.0f, 0.0f,
0.0f, 0.0f, -2 / (f_ - n_), 0.0f,
-(right + left) / (right - left), -(top + bottom) / (top - bottom), -(f_ + n_) / (f_ - n_), 1.0f
);
}
}
| bsd-3-clause |
exponent/exponent | android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/components/datetimepicker/RNDatePickerDialogFragment.java | 6054 | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package versioned.host.exp.exponent.modules.api.components.datetimepicker;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.DialogInterface.OnClickListener;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import android.widget.DatePicker;
import java.util.Calendar;
import java.util.Locale;
@SuppressLint("ValidFragment")
public class RNDatePickerDialogFragment extends DialogFragment {
private DatePickerDialog instance;
@Nullable
private OnDateSetListener mOnDateSetListener;
@Nullable
private OnDismissListener mOnDismissListener;
@Nullable
private static OnClickListener mOnNeutralButtonActionListener;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args = getArguments();
instance = createDialog(args, getActivity(), mOnDateSetListener);
return instance;
}
public void update(Bundle args) {
final RNDate date = new RNDate(args);
instance.updateDate(date.year(), date.month(), date.day());
}
static @NonNull
DatePickerDialog getDialog(
Bundle args,
Context activityContext,
@Nullable OnDateSetListener onDateSetListener) {
final RNDate date = new RNDate(args);
final int year = date.year();
final int month = date.month();
final int day = date.day();
RNDatePickerDisplay display = RNDatePickerDisplay.DEFAULT;
if (args != null && args.getString(RNConstants.ARG_DISPLAY, null) != null) {
display = RNDatePickerDisplay.valueOf(args.getString(RNConstants.ARG_DISPLAY).toUpperCase(Locale.US));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
switch (display) {
case CALENDAR:
case SPINNER:
String resourceName = display == RNDatePickerDisplay.CALENDAR
? "CalendarDatePickerDialog"
: "SpinnerDatePickerDialog";
return new RNDismissableDatePickerDialog(
activityContext,
activityContext.getResources().getIdentifier(
resourceName,
"style",
activityContext.getPackageName()),
onDateSetListener,
year,
month,
day,
display
);
default:
return new RNDismissableDatePickerDialog(
activityContext,
onDateSetListener,
year,
month,
day,
display
);
}
} else {
DatePickerDialog dialog = new RNDismissableDatePickerDialog(activityContext, onDateSetListener, year, month, day, display);
switch (display) {
case CALENDAR:
dialog.getDatePicker().setCalendarViewShown(true);
dialog.getDatePicker().setSpinnersShown(false);
break;
case SPINNER:
dialog.getDatePicker().setCalendarViewShown(false);
break;
}
return dialog;
}
}
static DatePickerDialog createDialog(
Bundle args,
Context activityContext,
@Nullable OnDateSetListener onDateSetListener) {
final Calendar c = Calendar.getInstance();
DatePickerDialog dialog = getDialog(args, activityContext, onDateSetListener);
if (args != null && args.containsKey(RNConstants.ARG_NEUTRAL_BUTTON_LABEL)) {
dialog.setButton(DialogInterface.BUTTON_NEUTRAL, args.getString(RNConstants.ARG_NEUTRAL_BUTTON_LABEL), mOnNeutralButtonActionListener);
}
final DatePicker datePicker = dialog.getDatePicker();
if (args != null && args.containsKey(RNConstants.ARG_MINDATE)) {
// Set minDate to the beginning of the day. We need this because of clowniness in datepicker
// that causes it to throw an exception if minDate is greater than the internal timestamp
// that it generates from the y/m/d passed in the constructor.
c.setTimeInMillis(args.getLong(RNConstants.ARG_MINDATE));
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
datePicker.setMinDate(c.getTimeInMillis());
} else {
// This is to work around a bug in DatePickerDialog where it doesn't display a title showing
// the date under certain conditions.
datePicker.setMinDate(RNConstants.DEFAULT_MIN_DATE);
}
if (args != null && args.containsKey(RNConstants.ARG_MAXDATE)) {
// Set maxDate to the end of the day, same reason as for minDate.
c.setTimeInMillis(args.getLong(RNConstants.ARG_MAXDATE));
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MILLISECOND, 999);
datePicker.setMaxDate(c.getTimeInMillis());
}
return dialog;
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (mOnDismissListener != null) {
mOnDismissListener.onDismiss(dialog);
}
}
/*package*/ void setOnDateSetListener(@Nullable OnDateSetListener onDateSetListener) {
mOnDateSetListener = onDateSetListener;
}
/*package*/ void setOnDismissListener(@Nullable OnDismissListener onDismissListener) {
mOnDismissListener = onDismissListener;
}
/*package*/ void setOnNeutralButtonActionListener(@Nullable OnClickListener onNeutralButtonActionListener) {
mOnNeutralButtonActionListener = onNeutralButtonActionListener;
}
}
| bsd-3-clause |
BaseXdb/basex | basex-core/src/main/java/org/basex/query/util/ft/FTMatches.java | 2366 | package org.basex.query.util.ft;
import org.basex.util.list.*;
/**
* AllMatches full-text container, referencing several {@link FTMatch} instances.
*
* @author BaseX Team 2005-22, BSD License
* @author Christian Gruen
*/
public final class FTMatches extends ObjectList<FTMatch, FTMatches> {
/** Position of a token in the query. */
public int pos;
/**
* Constructor.
*/
public FTMatches() {
}
/**
* Constructor.
* @param pos query position
*/
public FTMatches(final int pos) {
this();
this.pos = pos;
}
/**
* Resets the match container.
* @param ps query position
*/
public void reset(final int ps) {
pos = ps;
size = 0;
}
/**
* Adds a match entry.
* @param ps position
*/
public void or(final int ps) {
or(ps, ps);
}
/**
* Adds a match entry.
* @param start start position
* @param end end position
*/
public void or(final int start, final int end) {
add(new FTMatch(1).add(new FTStringMatch(start, end, pos)));
}
/**
* Adds a match entry.
* @param start start position
* @param end end position
*/
public void and(final int start, final int end) {
final FTStringMatch sm = new FTStringMatch(start, end, pos);
for(final FTMatch m : this) m.add(sm);
}
/**
* Checks if at least one of the matches contains only includes.
* @return result of check
*/
public boolean matches() {
for(final FTMatch m : this) {
if(m.match()) return true;
}
return false;
}
/**
* Combines two matches as phrase.
* @param all second match list
* @param distance word distance
* @return true if matches are left
*/
public boolean phrase(final FTMatches all, final int distance) {
int a = 0, b = 0, c = 0;
while(a < size && b < all.size) {
final int e = all.list[b].list[0].start;
final int d = e - list[a].list[0].end - distance;
if(d == 0) {
list[c] = list[a];
list[c++].list[0].end = e;
}
if(d >= 0) ++a;
if(d <= 0) ++b;
}
size = c;
return size != 0;
}
@Override
protected FTMatch[] newArray(final int s) {
return new FTMatch[s];
}
@Override
public boolean equals(final Object obj) {
return this == obj || obj instanceof FTMatches &&
pos == ((FTMatches) obj).pos && super.equals(obj);
}
}
| bsd-3-clause |
ksclarke/vertx-pairtree | src/test/java/info/freelibrary/pairtree/InvalidPathExceptionTest.java | 1231 |
package info.freelibrary.pairtree;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class InvalidPathExceptionTest {
private static final String MESSAGE = "A Pairtree path may not be null";
private static final String DETAILED_MESSAGE = "Response code: 403 [Not found]";
private static final String CODE = "403";
private static final String REASON = "Not found";
private static final Exception EXC = new Exception();
@Test
public final void testInvalidPathExceptionString() {
assertEquals(MESSAGE, new InvalidPathException(MessageCodes.PT_003).getMessage());
}
@Test
public final void testInvalidPathExceptionStringObjectArray() {
assertEquals(DETAILED_MESSAGE, new InvalidPathException(MessageCodes.PT_018, CODE, REASON).getMessage());
}
@Test
public final void testInvalidPathExceptionStringException() {
assertEquals(MESSAGE, new InvalidPathException(EXC, MessageCodes.PT_003).getMessage());
}
@Test
public final void testInvalidPathExceptionStringExceptionStringArray() {
assertEquals(DETAILED_MESSAGE, new InvalidPathException(EXC, MessageCodes.PT_018, CODE, REASON).getMessage());
}
}
| bsd-3-clause |
kakada/dhis2 | dhis-api/src/main/java/org/hisp/dhis/minmax/MinMaxDataElementService.java | 3087 | package org.hisp.dhis.minmax;
/*
* Copyright (c) 2004-2015, University of Oslo
* 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 HISP project 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.
*/
import java.util.Collection;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;
import org.hisp.dhis.organisationunit.OrganisationUnit;
/**
* @author Lars Helge Overland
* @version $Id$
*/
public interface MinMaxDataElementService
{
String ID = MinMaxDataElementService.class.getName();
int addMinMaxDataElement( MinMaxDataElement minMaxDataElement );
void deleteMinMaxDataElement( MinMaxDataElement minMaxDataElement );
void updateMinMaxDataElement( MinMaxDataElement minMaxDataElement );
MinMaxDataElement getMinMaxDataElement( int id );
MinMaxDataElement getMinMaxDataElement( OrganisationUnit source, DataElement dataElement, DataElementCategoryOptionCombo optionCombo );
Collection<MinMaxDataElement> getMinMaxDataElements( OrganisationUnit source, DataElement dataElement );
Collection<MinMaxDataElement> getMinMaxDataElements( OrganisationUnit source, Collection<DataElement> dataElements );
Collection<MinMaxDataElement> getAllMinMaxDataElements();
void removeMinMaxDataElements( OrganisationUnit organisationUnit );
void removeMinMaxDataElements( DataElement dataElement );
void removeMinMaxDataElements( DataElementCategoryOptionCombo optionCombo );
void removeMinMaxDataElements( Collection<DataElement> dataElements, Collection<OrganisationUnit> organisationUnits );
}
| bsd-3-clause |
ComsewogueRobotics/2014 | src/edu/wpi/first/wpilibj/templates/commands/LEDRingOff.java | 1141 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.templates.Robot;
/**
*
* @author Andrew
*/
public class LEDRingOff extends Command {
public LEDRingOff() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
requires(Robot.Lights);
}
// Called just before this Command runs the first time
protected void initialize() {
Robot.Lights.setOff();
}
// 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 true;
}
// 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 |
cameronbraid/rox | src/main/java/com/flat502/rox/server/ServerEncodingMap.java | 482 | package com.flat502.rox.server;
import java.util.HashMap;
import java.util.Map;
import com.flat502.rox.encoding.Encoding;
import com.flat502.rox.encoding.EncodingMap;
class ServerEncodingMap implements EncodingMap {
private Map map = new HashMap();
public Encoding addEncoding(Encoding encoding) {
return (Encoding) this.map.put(encoding.getName(), encoding);
}
public Encoding getEncoding(String name) {
return (Encoding) this.map.get(name);
}
}
| bsd-3-clause |
NCIP/cacis | nav/src/test/java/gov/nih/nci/cacis/nav/SendSignedMailTest.java | 10910 | /**
* Copyright 5AM Solutions Inc
* Copyright SemanticBits LLC
* Copyright AgileX Technologies, Inc
* Copyright Ekagra Software Technologies Ltd
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cacis/LICENSE.txt for details.
*/
package gov.nih.nci.cacis.nav;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
import javax.activation.DataHandler;
import javax.activation.URLDataSource;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.icegreen.greenmail.user.GreenMailUser;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetupTest;
/**
* Tests sending/receiving mail
*
* @author joshua.phillips@semanticbits.com
* @author vinodh.rc@semanticbits.com
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:/applicationContext-nav-test.xml" })
public class SendSignedMailTest {
private static final String INBOX = "INBOX";
private static final String POP3_TYPE = "pop3";
private static final String MAIL_POP3_PORT_KEY = "mail.pop3.port";
private static final String UNEXPECTED_EXCEPTION = "Unexpected exception: ";
private static final Logger LOG = Logger.getLogger(TestMail.class);
private static final String LOCALHOST = "localhost";
private static final int SMTP_PORT = 3025;
private static final int POP3_PORT = 3110;
private GreenMail server;
@Value("${sec.email.keystore.location}")
private String secEmailKeyStoreLocation;
@Value("${sec.email.keystore.password}")
private String secEmailKeyStorePassword;
// Using the from email address to get the matching key
@Value("${sec.email.message.from}")
private String secEmailKeyStoreKey;
@Value("${sec.email.truststore.location}")
private String secEmailTrustStoreLocation;
@Value("${sec.email.truststore.password}")
private String secEmailTrustStorePassword;
@Value("${sec.email.message.from}")
private String secEmailFrom;
// Using the same email address for from and to
// as the test truststore has key for the from address only
@Value("${sec.email.message.from}")
private String secEmailTo;
@Value("${sec.email.sender.user}")
private String secEmailUser;
@Value("${sec.email.sender.pass}")
private String secEmailPass;
@Autowired
private SendSignedMail sender;
@Autowired
private SendEncryptedMail encSender;
/**
* starts GreenMain server for testing
*/
@Before
public void setUp() {
server = new GreenMail(ServerSetupTest.ALL);
// for some reason, the greenmail server doesnt start in time
// will attempt max times to ensure all service gets startedup
int i = 0;
final int max = 2;
while (i < max) {
try {
server.start();
// CHECKSTYLE:OFF
} catch (RuntimeException e) { // NOPMD
// CHECKSTYLE:ON
i++;
continue;
}
i = max;
}
}
/**
* stops GreenMain server after testing
*/
@After
public void tearDown() {
server.stop();
}
/**
* tests error on invalid keystore
*
* @throws MessagingException - exception thrown
*/
@Test(expected = MessagingException.class)
public void supplyInvalidKeystore() throws MessagingException {
final SendSignedMail ssem = new SendSignedMail(new Properties(), secEmailFrom, "invalid keystore",
secEmailKeyStorePassword, secEmailKeyStoreKey);
// shouldnt reach this line
ssem.signMail(null);
}
/**
* send to gmail
* @throws MessagingException exception thrown
*/
@Test
public void sendSignedAndEncryptedMailToGmail() throws MessagingException {
final MimeMessage msg = sender.createMessage(secEmailTo, "Clinical Note", "subj", "inst", "content", "metadata", "title", "indexBodyToken", "readmeToken");
final MimeMessage signedMsg = sender.signMail(msg);
final MimeMessage encMsg = encSender.encryptMail(signedMsg, secEmailTo);
sender.sendMail(encMsg);
}
/**
* tests receiving signed mail
*
* @throws IOException - io exception thrown
*/
@Test
public void receiveSignedMessage() throws IOException {
try {
final MimeMessage msg = createMessage();
// TODO:fix sample certificate for email address
msg.setFrom(new InternetAddress(secEmailFrom));
final Properties smtpprops = new Properties();
smtpprops.put("mail.smtp.auth", "true");
smtpprops.put("mail.smtp.starttls.enable", "true");
final SendSignedMail ssem = new SendSignedMail(smtpprops, secEmailFrom, secEmailKeyStoreLocation,
secEmailKeyStorePassword, secEmailKeyStoreKey);
final MimeMessage signedMsg = ssem.signMail(msg);
final GreenMailUser user = server.setUser(secEmailTo, secEmailUser, secEmailPass);
user.deliver(signedMsg);
assertEquals(1, server.getReceivedMessages().length);
final Properties props = new Properties();
props.setProperty(MAIL_POP3_PORT_KEY, String.valueOf(POP3_PORT));
final Session session = Session.getInstance(props, null);
session.setDebug(true);
final Store store = session.getStore(POP3_TYPE);
store.connect("localhost", secEmailUser, secEmailPass);
final Folder folder = store.getFolder(INBOX);
folder.open(Folder.READ_ONLY);
final Message[] messages = folder.getMessages();
assertTrue(messages != null);
assertTrue(messages.length == 1);
final MimeMessage retMsg = (MimeMessage) messages[0];
final ValidateSignedMail vsm = new ValidateSignedMail(false);
// TO email public key is tied to the email address itself, so using it as keyalias
vsm.validate(retMsg, secEmailTrustStoreLocation, secEmailTrustStorePassword, secEmailTo);
final Multipart mp = (Multipart) retMsg.getContent();
assertTrue(mp.getCount() == 2);
final Multipart origMsgMp = (Multipart) msg.getContent();
final Part actualMsgPart = mp.getBodyPart(0);
final Multipart actualMsgMp = (Multipart) actualMsgPart.getContent();
validateMsgParts(origMsgMp, actualMsgMp);
// CHECKSTYLE:OFF
} catch (Exception e) { // NOPMD
// CHECKSTYLE:ON
fail(UNEXPECTED_EXCEPTION + e);
}
}
private void validateMsgParts(Multipart origMsgMp, Multipart actualMsgMp) {
try {
final String textpart = (String) actualMsgMp.getBodyPart(0).getContent();
assertNotNull(textpart);
assertEquals((String) origMsgMp.getBodyPart(0).getContent(), textpart);
final String attachPart = getPartContent(actualMsgMp.getBodyPart(1));
assertNotNull(attachPart);
assertEquals(getPartContent(origMsgMp.getBodyPart(1)), attachPart);
} catch (IOException e) {
fail(UNEXPECTED_EXCEPTION + e);
} catch (MessagingException e) {
fail(UNEXPECTED_EXCEPTION + e);
}
}
private String getPartContent(Part part) {
BufferedReader reader = null;
String partMsg = null;
try {
final Writer writer = new StringWriter();
final char[] buffer = new char[1024];
reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
int n = -1;
while ((n = reader.read(buffer)) != -1) { // NOPMD
writer.write(buffer, 0, n);
}
partMsg = writer.toString();
// CHECKSTYLE:OFF
} catch (Exception e) { // NOPMD
// CHECKSTYLE:ON
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
LOG.error("Error closing BufferedReader!");
}
}
}
return partMsg;
}
private MimeMessage createMessage() throws Exception { // NOPMD
final String subject = "Notification of Document Availability";
final Properties mailProps = new Properties();
final Session session = Session.getInstance(mailProps, null);
mailProps.setProperty("mail.smtp.host", LOCALHOST);
mailProps.setProperty("mail.smtp.port", String.valueOf(SMTP_PORT));
mailProps.setProperty("mail.smtp.sendpartial", "true");
session.setDebug(true);
final MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(secEmailFrom));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(secEmailTo));
final MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText("Instructions to the user.");
mbp1.setHeader("Content-Type", "text/plain");
final MimeBodyPart mbp2 = new MimeBodyPart();
final ClassLoader cl = TestMail.class.getClassLoader();
final URLDataSource ds = new URLDataSource(cl.getResource("purchase_order.xml"));
mbp2.setDataHandler(new DataHandler(ds));
mbp2.setFileName("IHEXDSNAV-" + UUID.randomUUID() + ".xml");
mbp2.setHeader("Content-Type", "application/xml; charset=UTF-8");
final Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
msg.setContent(mp);
msg.setSentDate(new Date());
return msg;
}
}
| bsd-3-clause |
CalSPEED/CalSPEED-Android | CalSPEED/src/main/java/gov/ca/cpuc/calspeed/android/TabSwipeActivity.java | 8118 | /*
Copyright (c) 2020, California State University Monterey Bay (CSUMB).
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 CPUC, CSU Monterey Bay, 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 gov.ca.cpuc.calspeed.android;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public abstract class TabSwipeActivity extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
/*
* Create the ViewPager and our custom adapter
*/
Log.v(this.getClass().getName(), "start of onCreate()");
mViewPager = new ViewPager(this);
Log.v(this.getClass().getName(), "calling new TabsAdapter object");
adapter = new TabsAdapter( this, mViewPager );
mViewPager.setAdapter( adapter );
mViewPager.setOnPageChangeListener( adapter );
/*
* We need to provide an ID for the ViewPager, otherwise we will get an exception like:
*
* java.lang.IllegalArgumentException: No view found for id 0xffffffff for fragment TestFragment{40de5b90 #0 id=0xffffffff android:switcher:-1:0}
* at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:864)
*
* The ID 0x7F04FFF0 is large enough to probably never be used for anything else
*/
mViewPager.setId( R.id.viewpager );
super.onCreate(savedInstanceState);
/*
* Set the ViewPager as the content view
*/
Log.v(this.getClass().getName(), "calling setContentView()");
setContentView(mViewPager);
}
protected void addTab(int titleRes, Class<? extends Fragment> fragmentClass, Bundle args ) {
adapter.addTab( getString( titleRes ), fragmentClass, args );
}
protected void addTab(CharSequence title, Class<? extends Fragment> fragmentClass, Bundle args ) {
adapter.addTab( title, fragmentClass, args );
}
protected void removeTab(int index ) {
adapter.removeTab( index );
}
protected void removeTabs(int index, int index2) {
adapter.removeTabs(index, index2);
}
protected boolean isCurrentTab(int position) {
return adapter.isCurrentTab(position);
}
protected void selectPage(int position) {
adapter.onPageSelected(position);
}
private static class TabsAdapter extends FragmentPagerAdapter implements TabListener, ViewPager.OnPageChangeListener {
private final SherlockFragmentActivity mActivity;
private final ActionBar mActionBar;
private final ViewPager mPager;
public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
this.mActivity = activity;
this.mActionBar = activity.getSupportActionBar();
this.mPager = pager;
mActionBar.setNavigationMode( ActionBar.NAVIGATION_MODE_TABS );
Log.v(this.getClass().getName(), "calling new TabsAdapter()");
}
private static class TabInfo {
public final Class<? extends Fragment> fragmentClass;
public final Bundle args;
public TabInfo(Class<? extends Fragment> fragmentClass,
Bundle args) {
this.fragmentClass = fragmentClass;
this.args = args;
}
}
private final List<TabInfo> mTabs = new ArrayList<TabInfo>();
public void addTab( CharSequence title, Class<? extends Fragment> fragmentClass, Bundle args ) {
TabInfo tabInfo = new TabInfo( fragmentClass, args );
Tab tab = mActionBar.newTab();
tab.setText( title );
tab.setTabListener( this );
tab.setTag( tabInfo );
mTabs.add( tabInfo );
mActionBar.addTab( tab );
notifyDataSetChanged();
}
public void removeTab( int index ) {
mTabs.remove( index );
mActionBar.removeTab( mActionBar.getTabAt(index) );
notifyDataSetChanged();
}
public void removeTabs(int index, int index2) {
mTabs.remove(index2);
mTabs.remove(index);
mActionBar.removeTab(mActionBar.getTabAt(index2));
mActionBar.removeTab(mActionBar.getTabAt(index));
notifyDataSetChanged();
}
public boolean isCurrentTab(int position) {
return mPager.getCurrentItem() == position;
}
@Override
public Fragment getItem(int position) {
final TabInfo tabInfo = mTabs.get( position );
return Fragment.instantiate( mActivity, tabInfo.fragmentClass.getName(), tabInfo.args );
}
@Override
public int getCount() {
return mTabs.size();
}
public void onPageScrollStateChanged(int arg0) {
Utils.hideKeyboard(mActivity);
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
Utils.hideKeyboard(mActivity);
}
public void onPageSelected(int position) {
/*
* Select tab when user swiped
*/
Utils.hideKeyboard(mActivity);
mActionBar.setSelectedNavigationItem( position );
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
/*
* Slide to selected fragment when user selected tab
*/
Log.v(this.getClass().getName(), "onTabSelected() called");
Utils.hideKeyboard(mActivity);
final TabInfo tabInfo = (TabInfo) tab.getTag();
for ( int i = 0; i < mTabs.size(); i++ ) {
if ( mTabs.get( i ) == tabInfo ) {
mPager.setCurrentItem( i );
Log.d(this.getClass().getName(), String.format("Swapping to tab: %d", i));
getItem(i);
}
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Utils.hideKeyboard(mActivity);
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Utils.hideKeyboard(mActivity);
}
}
} | bsd-3-clause |
petablox-project/petablox | src/petablox/project/analyses/rhs/IWrappedSE.java | 171 | package petablox.project.analyses.rhs;
public interface IWrappedSE<PE extends IEdge, SE extends IEdge> {
public SE getSE();
public IWrappedPE<PE,SE> getWPE();
}
| bsd-3-clause |
madongfly/grpc-java | grpclb/src/generated/main/grpc/io/grpc/grpclb/LoadBalancerGrpc.java | 5163 | package io.grpc.grpclb;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
@javax.annotation.Generated("by gRPC proto compiler")
public class LoadBalancerGrpc {
private LoadBalancerGrpc() {}
public static final String SERVICE_NAME = "grpc.lb.v1.LoadBalancer";
// Static method descriptors that strictly reflect the proto.
@io.grpc.ExperimentalApi
public static final io.grpc.MethodDescriptor<io.grpc.grpclb.LoadBalanceRequest,
io.grpc.grpclb.LoadBalanceResponse> METHOD_BALANCE_LOAD =
io.grpc.MethodDescriptor.create(
io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING,
generateFullMethodName(
"grpc.lb.v1.LoadBalancer", "BalanceLoad"),
io.grpc.protobuf.ProtoUtils.marshaller(io.grpc.grpclb.LoadBalanceRequest.getDefaultInstance()),
io.grpc.protobuf.ProtoUtils.marshaller(io.grpc.grpclb.LoadBalanceResponse.getDefaultInstance()));
public static LoadBalancerStub newStub(io.grpc.Channel channel) {
return new LoadBalancerStub(channel);
}
public static LoadBalancerBlockingStub newBlockingStub(
io.grpc.Channel channel) {
return new LoadBalancerBlockingStub(channel);
}
public static LoadBalancerFutureStub newFutureStub(
io.grpc.Channel channel) {
return new LoadBalancerFutureStub(channel);
}
public static interface LoadBalancer {
public io.grpc.stub.StreamObserver<io.grpc.grpclb.LoadBalanceRequest> balanceLoad(
io.grpc.stub.StreamObserver<io.grpc.grpclb.LoadBalanceResponse> responseObserver);
}
public static interface LoadBalancerBlockingClient {
}
public static interface LoadBalancerFutureClient {
}
public static class LoadBalancerStub extends io.grpc.stub.AbstractStub<LoadBalancerStub>
implements LoadBalancer {
private LoadBalancerStub(io.grpc.Channel channel) {
super(channel);
}
private LoadBalancerStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected LoadBalancerStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new LoadBalancerStub(channel, callOptions);
}
@java.lang.Override
public io.grpc.stub.StreamObserver<io.grpc.grpclb.LoadBalanceRequest> balanceLoad(
io.grpc.stub.StreamObserver<io.grpc.grpclb.LoadBalanceResponse> responseObserver) {
return asyncBidiStreamingCall(
getChannel().newCall(METHOD_BALANCE_LOAD, getCallOptions()), responseObserver);
}
}
public static class LoadBalancerBlockingStub extends io.grpc.stub.AbstractStub<LoadBalancerBlockingStub>
implements LoadBalancerBlockingClient {
private LoadBalancerBlockingStub(io.grpc.Channel channel) {
super(channel);
}
private LoadBalancerBlockingStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected LoadBalancerBlockingStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new LoadBalancerBlockingStub(channel, callOptions);
}
}
public static class LoadBalancerFutureStub extends io.grpc.stub.AbstractStub<LoadBalancerFutureStub>
implements LoadBalancerFutureClient {
private LoadBalancerFutureStub(io.grpc.Channel channel) {
super(channel);
}
private LoadBalancerFutureStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected LoadBalancerFutureStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new LoadBalancerFutureStub(channel, callOptions);
}
}
public static io.grpc.ServerServiceDefinition bindService(
final LoadBalancer serviceImpl) {
return io.grpc.ServerServiceDefinition.builder(SERVICE_NAME)
.addMethod(
METHOD_BALANCE_LOAD,
asyncBidiStreamingCall(
new io.grpc.stub.ServerCalls.BidiStreamingMethod<
io.grpc.grpclb.LoadBalanceRequest,
io.grpc.grpclb.LoadBalanceResponse>() {
@java.lang.Override
public io.grpc.stub.StreamObserver<io.grpc.grpclb.LoadBalanceRequest> invoke(
io.grpc.stub.StreamObserver<io.grpc.grpclb.LoadBalanceResponse> responseObserver) {
return serviceImpl.balanceLoad(responseObserver);
}
})).build();
}
}
| bsd-3-clause |
krishagni/openspecimen | WEB-INF/src/com/krishagni/catissueplus/core/biospecimen/domain/factory/impl/ParticipantLookupFactoryImpl.java | 3211 | package com.krishagni.catissueplus.core.biospecimen.domain.factory.impl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import com.krishagni.catissueplus.core.biospecimen.ConfigParams;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.ParticipantErrorCode;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.ParticipantLookupFactory;
import com.krishagni.catissueplus.core.biospecimen.matching.ParticipantLookupLogic;
import com.krishagni.catissueplus.core.common.OpenSpecimenAppCtxProvider;
import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException;
import com.krishagni.catissueplus.core.common.service.ConfigurationService;
import com.krishagni.catissueplus.core.common.util.ConfigUtil;
import com.krishagni.catissueplus.core.common.util.LogUtil;
public class ParticipantLookupFactoryImpl implements ParticipantLookupFactory, InitializingBean {
private static final LogUtil logger = LogUtil.getLogger(ParticipantLookupFactoryImpl.class);
private ParticipantLookupLogic defaultParticipantLookupFlow;
private ParticipantLookupLogic participantLookupLogic;
private ConfigurationService cfgSvc;
public void setDefaultParticipantLookupFlow(ParticipantLookupLogic defaultParticipantLookupFlow) {
this.defaultParticipantLookupFlow = defaultParticipantLookupFlow;
}
public void setParticipantLookupLogic(ParticipantLookupLogic participantLookupLogic) {
this.participantLookupLogic = participantLookupLogic;
}
public void setCfgSvc(ConfigurationService cfgSvc) {
this.cfgSvc = cfgSvc;
}
@Override
public ParticipantLookupLogic getLookupLogic() {
if (participantLookupLogic == null) {
initParticipantLookupFlow(ConfigUtil.getInstance().getStrSetting(ConfigParams.MODULE, ConfigParams.PARTICIPANT_LOOKUP_FLOW));
}
return participantLookupLogic;
}
@Override
public void afterPropertiesSet() throws Exception {
cfgSvc.registerChangeListener(
ConfigParams.MODULE,
(name, value) -> {
if (StringUtils.isBlank(name) || ConfigParams.PARTICIPANT_LOOKUP_FLOW.equals(name)) {
participantLookupLogic = null;
}
}
);
}
private void initParticipantLookupFlow(String lookupFlow) {
if (StringUtils.isBlank(lookupFlow)) {
participantLookupLogic = defaultParticipantLookupFlow;
return;
}
ParticipantLookupLogic result = null;
try {
lookupFlow = lookupFlow.trim();
if (lookupFlow.startsWith("bean:")) {
result = OpenSpecimenAppCtxProvider.getBean(lookupFlow.substring("bean:".length()).trim());
} else {
String className = lookupFlow;
if (lookupFlow.startsWith("class:")) {
className = lookupFlow.substring("class:".length()).trim();
}
Class<ParticipantLookupLogic> klass = (Class<ParticipantLookupLogic>) Class.forName(className);
result = BeanUtils.instantiate(klass);
}
} catch (Exception e) {
logger.info("Invalid participant lookup flow configuration setting: " + lookupFlow, e);
}
if (result == null) {
throw OpenSpecimenException.userError(ParticipantErrorCode.INVALID_LOOKUP_FLOW, lookupFlow);
}
participantLookupLogic = result;
}
}
| bsd-3-clause |
holisticon/annotation-processor-toolkit | annotationprocessor/src/test/java/io/toolisticon/annotationprocessortoolkit/tools/matcher/impl/ByQualifiedNameMatcherTest.java | 5094 | package io.toolisticon.annotationprocessortoolkit.tools.matcher.impl;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.mockito.Mockito;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Name;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
/**
* Unit test for {@link ByQualifiedNameMatcher}.
*/
public class ByQualifiedNameMatcherTest {
private final static String NAME = "NAME";
private ByQualifiedNameMatcher unit = new ByQualifiedNameMatcher();
@Test
public void test_getStringRepresentationOfPassedCharacteristic_happyPath() {
MatcherAssert.assertThat("Should return enum name", unit.getStringRepresentationOfPassedCharacteristic(NAME).equals(NAME));
}
@Test
public void test_getStringRepresentationOfPassedCharacteristic_passedNullValue() {
MatcherAssert.assertThat("Should return null for null valued parameter", unit.getStringRepresentationOfPassedCharacteristic(null) == null);
}
@Test
public void test_checkForMatchingCharacteristic_match_class() {
TypeElement element = Mockito.mock(TypeElement.class);
Name nameOfElement = Mockito.mock(Name.class);
Mockito.when(nameOfElement.toString()).thenReturn(NAME);
Mockito.when(element.getKind()).thenReturn(ElementKind.CLASS);
Mockito.when(element.getQualifiedName()).thenReturn(nameOfElement);
MatcherAssert.assertThat("Should find match correctly", unit.checkForMatchingCharacteristic(element, NAME));
}
@Test
public void test_checkForMatchingCharacteristic_match_package() {
PackageElement element = Mockito.mock(PackageElement.class);
Name nameOfElement = Mockito.mock(Name.class);
Mockito.when(nameOfElement.toString()).thenReturn(NAME);
Mockito.when(element.getKind()).thenReturn(ElementKind.PACKAGE);
Mockito.when(element.getQualifiedName()).thenReturn(nameOfElement);
MatcherAssert.assertThat("Should find match correctly", unit.checkForMatchingCharacteristic(element, NAME));
}
@Test
public void test_checkForMatchingCharacteristic_match_method() {
Element element = Mockito.mock(Element.class);
Name nameOfElement = Mockito.mock(Name.class);
Mockito.when(nameOfElement.toString()).thenReturn(NAME);
Mockito.when(element.getKind()).thenReturn(ElementKind.METHOD);
Mockito.when(element.getSimpleName()).thenReturn(nameOfElement);
MatcherAssert.assertThat("Should find match correctly", unit.checkForMatchingCharacteristic(element, NAME));
}
@Test
public void test_checkForMatchingCharacteristic_mismatch_class() {
TypeElement element = Mockito.mock(TypeElement.class);
Name nameOfElement = Mockito.mock(Name.class);
Mockito.when(nameOfElement.toString()).thenReturn("XXX");
Mockito.when(element.getKind()).thenReturn(ElementKind.CLASS);
Mockito.when(element.getQualifiedName()).thenReturn(nameOfElement);
MatcherAssert.assertThat("Should find mismatch correctly", !unit.checkForMatchingCharacteristic(element, NAME));
}
@Test
public void test_checkForMatchingCharacteristic_mismatch_package() {
PackageElement element = Mockito.mock(PackageElement.class);
Name nameOfElement = Mockito.mock(Name.class);
Mockito.when(nameOfElement.toString()).thenReturn("XXX");
Mockito.when(element.getKind()).thenReturn(ElementKind.PACKAGE);
Mockito.when(element.getQualifiedName()).thenReturn(nameOfElement);
MatcherAssert.assertThat("Should find mismatch correctly", !unit.checkForMatchingCharacteristic(element, NAME));
}
@Test
public void test_checkForMatchingCharacteristic_mismatch_method() {
Element element = Mockito.mock(Element.class);
Name nameOfElement = Mockito.mock(Name.class);
Mockito.when(nameOfElement.toString()).thenReturn("XXX");
Mockito.when(element.getKind()).thenReturn(ElementKind.METHOD);
Mockito.when(element.getSimpleName()).thenReturn(nameOfElement);
MatcherAssert.assertThat("Should find mismatch correctly", !unit.checkForMatchingCharacteristic(element, NAME));
}
@Test
public void test_checkForMatchingCharacteristic_nullValuedElement() {
MatcherAssert.assertThat("Should return false in case of null valued element", !unit.checkForMatchingCharacteristic(null, NAME));
}
@Test
public void test_checkForMatchingCharacteristic_nullValuedAnnotationType() {
Element element = Mockito.mock(Element.class);
MatcherAssert.assertThat("Should retrun false in case of null valued annotation", !unit.checkForMatchingCharacteristic(element, null));
}
@Test
public void test_checkForMatchingCharacteristic_nullValuedParameters() {
MatcherAssert.assertThat("Should return false in case of null valued parameters", !unit.checkForMatchingCharacteristic(null, null));
}
}
| bsd-3-clause |
rsmudge/armitage | src/cortana/CortanaPipe.java | 1366 | package cortana;
import java.io.*;
import java.util.*;
/* a pipe to receive output from Cortana and make it available in an event driven way to the user */
public class CortanaPipe implements Runnable {
protected PipedInputStream readme;
protected PipedOutputStream writeme;
public OutputStream getOutput() {
return writeme;
}
public CortanaPipe() {
try {
readme = new PipedInputStream(1024 * 1024 * 1);
writeme = new PipedOutputStream(readme);
}
catch (IOException ioex) {
ioex.printStackTrace();
}
}
public interface CortanaPipeListener {
public void read(String text);
}
protected List listeners = new LinkedList();
public void addCortanaPipeListener(CortanaPipeListener l) {
synchronized (this) {
listeners.add(l);
}
if (listeners.size() == 1) {
new Thread(this).start();
}
}
public void run() {
BufferedReader in = new BufferedReader(new InputStreamReader(readme));
while (true) {
try {
String entry = in.readLine();
if (entry != null) {
synchronized (this) {
Iterator i = listeners.iterator();
while (i.hasNext()) {
CortanaPipeListener l = (CortanaPipeListener)i.next();
l.read(entry);
}
}
}
}
catch (IOException ioex) {
try {
Thread.sleep(500);
}
catch (Exception ex) { }
//ioex.printStackTrace();
}
}
}
}
| bsd-3-clause |
bartdag/py4j-benchmark | java/src/Py4JBenchmarkUtility.java | 1506 | import py4j.GatewayServer;
import java.util.Random;
public class Py4JBenchmarkUtility {
public final int seed;
private final Random random;
public static final int DEFAULT_SEED = 17;
public Py4JBenchmarkUtility(int seed) {
this.seed = seed;
random = new Random(seed);
}
public byte[] getBytes(int length) {
byte[] bytes = new byte[length];
random.nextBytes(bytes);
return bytes;
}
public Object callEcho(Echo echo, Object param) {
return echo.echo(param);
}
public static int startCountdown(int count, Countdown pythonCountdown) {
Countdown javaCountdown = new CountdownImpl();
return pythonCountdown.countdown(count, javaCountdown);
}
public static byte[] echoBytes(byte[] bytes) {
// Change first and last byte
bytes[0] = 1;
bytes[bytes.length - 1] = 2;
return bytes;
}
public static void main(String[] args) {
int seed = DEFAULT_SEED;
if (args.length > 0) {
seed = Integer.parseInt(args[0]);
}
Py4JBenchmarkUtility utility = new Py4JBenchmarkUtility(seed);
GatewayServer server = new GatewayServer(utility);
server.start(true);
}
public static interface Echo {
Object echo(Object param);
}
public static interface Countdown {
int countdown(int count, Countdown countdownObject);
}
public static class CountdownImpl implements Countdown {
@Override public int countdown(int count, Countdown countdownObject) {
if (count == 0) {
return 0;
} else {
return countdownObject.countdown(count - 1, this);
}
}
}
}
| bsd-3-clause |
dmitrykolesnikovich/dyn4j | sandbox/src/org/dyn4j/sandbox/tests/Conveyor.java | 4175 | /*
* Copyright (c) 2010-2015 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.sandbox.tests;
import org.dyn4j.dynamics.CollisionAdapter;
import org.dyn4j.dynamics.contact.ContactConstraint;
import org.dyn4j.geometry.Geometry;
import org.dyn4j.geometry.MassType;
import org.dyn4j.sandbox.SandboxBody;
import com.jogamp.opengl.GL2;
/**
* Compiled test for the contact tangent speed feature.
* @author William Bittle
* @version 1.0.6
* @since 1.0.2
*/
public class Conveyor extends CompiledSimulation {
/** The collision listener */
private CustomCollisionListener listener;
/**
* A custom collision listener to set the tangent speed of contacts with the floor body.
* @author William Bittle
* @version 1.0.2
* @since 1.0.2
*/
private class CustomCollisionListener extends CollisionAdapter {
/* (non-Javadoc)
* @see org.dyn4j.dynamics.CollisionAdapter#collision(org.dyn4j.dynamics.contact.ContactConstraint)
*/
@Override
public boolean collision(ContactConstraint contactConstraint) {
if (contactConstraint.getBody1() == floor) {
contactConstraint.setTangentSpeed(-5.0);
} else if (contactConstraint.getBody2() == floor) {
contactConstraint.setTangentSpeed(5.0);
}
// allow all collisions
return true;
}
}
/** The floor body */
private SandboxBody floor;
/* (non-Javadoc)
* @see org.dyn4j.sandbox.tests.CompiledSimulation#initialize()
*/
@Override
public void initialize() {
this.world.setUserData("Conveyor");
this.floor = new SandboxBody();
this.floor.addFixture(Geometry.createRectangle(15.0, 1.0));
this.floor.setMass(MassType.INFINITE);
this.floor.setUserData("Floor");
SandboxBody box = new SandboxBody();
box.addFixture(Geometry.createSquare(1.0));
box.setMass(MassType.NORMAL);
box.translate(0.0, 2.0);
box.setUserData("Box");
this.listener = new CustomCollisionListener();
this.world.addBody(this.floor);
this.world.addBody(box);
this.world.addListener(this.listener);
}
/* (non-Javadoc)
* @see org.dyn4j.sandbox.tests.CompiledSimulation#update(double, boolean)
*/
@Override
public void update(double elapsedTime, boolean stepped) {}
/* (non-Javadoc)
* @see org.dyn4j.sandbox.tests.CompiledSimulation#render(com.jogamp.opengl.GL2)
*/
@Override
public void render(GL2 gl) {}
/* (non-Javadoc)
* @see org.dyn4j.sandbox.tests.CompiledSimulation#reset()
*/
@Override
public void reset() {
// remove everything from the world
this.world.removeAllBodiesAndJoints();
// remove all the listeners
this.world.removeListener(this.listener);
// add it all back
this.initialize();
}
}
| bsd-3-clause |
Pluto-tv/chromium-crosswalk | chromecast/browser/android/apk/src/org/chromium/chromecast/shell/CastWindowAndroid.java | 6644 | // Copyright 2014 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.chromecast.shell;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.content.browser.ContentView;
import org.chromium.content.browser.ContentViewCore;
import org.chromium.content.browser.ContentViewRenderView;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.NavigationController;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.WebContentsObserver;
import org.chromium.ui.base.WindowAndroid;
/**
* Container for the various UI components that make up a shell window.
*/
@JNINamespace("chromecast::shell")
public class CastWindowAndroid extends LinearLayout {
public static final String TAG = "CastWindowAndroid";
public static final String ACTION_PAGE_LOADED = "castPageLoaded";
public static final String ACTION_ENABLE_DEV_TOOLS = "castEnableDevTools";
public static final String ACTION_DISABLE_DEV_TOOLS = "castDisableDevTools";
private ContentViewCore mContentViewCore;
private ContentViewRenderView mContentViewRenderView;
private NavigationController mNavigationController;
private int mRenderProcessId;
private WebContents mWebContents;
private WebContentsObserver mWebContentsObserver;
private WindowAndroid mWindow;
/**
* Constructor for inflating via XML.
*/
public CastWindowAndroid(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Set the SurfaceView being renderered to as soon as it is available.
*/
public void setContentViewRenderView(ContentViewRenderView contentViewRenderView) {
FrameLayout contentViewHolder = (FrameLayout) findViewById(R.id.contentview_holder);
if (contentViewRenderView == null) {
if (mContentViewRenderView != null) {
contentViewHolder.removeView(mContentViewRenderView);
}
} else {
contentViewHolder.addView(contentViewRenderView,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
}
mContentViewRenderView = contentViewRenderView;
}
/**
* @param window The owning window for this shell.
*/
public void setWindow(WindowAndroid window) {
mWindow = window;
}
/**
* Loads an URL. This will perform minimal amounts of sanitizing of the URL to attempt to
* make it valid.
*
* @param url The URL to be loaded by the shell.
*/
public void loadUrl(String url) {
if (url == null) return;
if (TextUtils.equals(url, mWebContents.getUrl())) {
mNavigationController.reload(true);
} else {
mNavigationController.loadUrl(new LoadUrlParams(normalizeUrl(url)));
}
// TODO(aurimas): Remove this when crbug.com/174541 is fixed.
mContentViewCore.getContainerView().clearFocus();
mContentViewCore.getContainerView().requestFocus();
}
/**
* Returns the render_process_id for the associated web contents
*/
public int getRenderProcessId() {
return mRenderProcessId;
}
/**
* Given a URI String, performs minimal normalization to attempt to build a usable URL from it.
* @param uriString The passed-in path to be normalized.
* @return The normalized URL, as a string.
*/
private static String normalizeUrl(String uriString) {
if (uriString == null) return uriString;
Uri uri = Uri.parse(uriString);
if (uri.getScheme() == null) {
uri = Uri.parse("http://" + uriString);
}
return uri.toString();
}
/**
* Initializes the ContentView based on the native tab contents pointer passed in.
* @param nativeWebContents The pointer to the native tab contents object.
*/
@SuppressWarnings("unused")
@CalledByNative
private void initFromNativeWebContents(WebContents webContents, int renderProcessId) {
Context context = getContext();
mContentViewCore = new ContentViewCore(context);
ContentView view = ContentView.newInstance(context, mContentViewCore);
mContentViewCore.initialize(view, view, webContents, mWindow);
mWebContents = mContentViewCore.getWebContents();
mNavigationController = mWebContents.getNavigationController();
mRenderProcessId = renderProcessId;
if (getParent() != null) mContentViewCore.onShow();
((FrameLayout) findViewById(R.id.contentview_holder)).addView(view,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
view.requestFocus();
mContentViewRenderView.setCurrentContentViewCore(mContentViewCore);
mWebContentsObserver = new WebContentsObserver(mWebContents) {
@Override
public void didStopLoading(String url) {
Uri intentUri = Uri.parse(mNavigationController
.getOriginalUrlForVisibleNavigationEntry());
Log.v(TAG, "Broadcast ACTION_PAGE_LOADED: scheme=" + intentUri.getScheme()
+ ", host=" + intentUri.getHost());
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(
new Intent(ACTION_PAGE_LOADED, intentUri));
}
};
}
/**
* @return The {@link ViewGroup} currently shown by this Shell.
*/
public ViewGroup getContentView() {
return mContentViewCore.getContainerView();
}
/**
* @return The {@link ContentViewCore} currently managing the view shown by this Shell.
*/
public ContentViewCore getContentViewCore() {
return mContentViewCore;
}
/**
* @return The {@link WebContents} managed by this class.
*/
public WebContents getWebContents() {
return mWebContents;
}
}
| bsd-3-clause |
adlange/IN2SEC | src/main/dependencies/alice/tuprolog/Number.java | 6543 | /*
* tuProlog - Copyright (C) 2001-2002 aliCE team at deis.unibo.it
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package alice.tuprolog;
import java.util.*;
/**
*
* Number abstract class represents numbers prolog data type
*
* @see Int
* @see Long
* @see Float
* @see Double
*
* Reviewed by Paolo Contessi: implements Comparable<Number>
*/
public abstract class Number extends Term implements Comparable<Number> {
private static final long serialVersionUID = 1L;
/**
* Returns the value of the number as int
*
* @return
*/
public abstract int intValue();
/**
* Returns the value of the number as float
*
* @return
*/
public abstract float floatValue();
/**
* Returns the value of the number as long
*
* @return
*/
public abstract long longValue();
/**
* Returns the value of the number as double
*/
public abstract double doubleValue();
/**
* is this term a prolog integer term?
*/
public abstract boolean isInteger();
/**
* is this term a prolog real term?
*/
public abstract boolean isReal();
//
/**
* is an int Integer number?
*
* @deprecated Use <tt>instanceof Int</tt> instead.
*/
public abstract boolean isTypeInt();
/**
* is an int Integer number?
*
* @deprecated Use <tt>instanceof Int</tt> instead.
*/
public abstract boolean isInt();
/**
* is a float Real number?
*
* @deprecated Use <tt>instanceof alice.tuprolog.Float</tt> instead.
*/
public abstract boolean isTypeFloat();
/**
* is a float Real number?
*
* @deprecated Use <tt>instanceof alice.tuprolog.Float</tt> instead.
*/
public abstract boolean isFloat();
/**
* is a double Real number?
*
* @deprecated Use <tt>instanceof alice.tuprolog.Double</tt> instead.
*/
public abstract boolean isTypeDouble();
/**
* is a double Real number?
*
* @deprecated Use <tt>instanceof alice.tuprolog.Double</tt> instead.
*/
public abstract boolean isDouble();
/**
* is a long Integer number?
*
* @deprecated Use <tt>instanceof alice.tuprolog.Long</tt> instead.
*/
public abstract boolean isTypeLong();
/**
* is a long Integer number?
*
* @deprecated Use <tt>instanceof alice.tuprolog.Long</tt> instead.
*/
public abstract boolean isLong();
public static Number createNumber(String s) {
Term t = Term.createTerm(s);
if (t instanceof Number) {
return (Number) t;
}
throw new InvalidTermException("Term " + t + " is not a number.");
}
/**
* Gets the actual term referred by this Term.
*/
public Term getTerm() {
return this;
}
// checking type and properties of the Term
/**
* is this term a prolog numeric term?
*/
final public boolean isNumber() {
return true;
}
/**
* is this term a struct
*/
final public boolean isStruct() {
return false;
}
/**
* is this term a variable
*/
final public boolean isVar() {
return false;
}
final public boolean isEmptyList() {
return false;
}
//
/**
* is this term a constant prolog term?
*/
final public boolean isAtomic() {
return true;
}
/**
* is this term a prolog compound term?
*/
final public boolean isCompound() {
return false;
}
/**
* is this term a prolog (alphanumeric) atom?
*/
final public boolean isAtom() {
return false;
}
/**
* is this term a prolog list?
*/
final public boolean isList() {
return false;
}
/**
* is this term a ground term?
*/
final public boolean isGround() {
return true;
}
//
/**
* gets a copy of this term.
*/
public Term copy(int idExecCtx) {
return this;
}
/**
* gets a copy (with renamed variables) of the term.
* <p>
* the list argument passed contains the list of variables to be renamed
* (if empty list then no renaming)
*/
Term copy(AbstractMap<Var, Var> vMap, int idExecCtx) {
return this;
}
/**
* gets a copy of the term.
*/
Term copy(AbstractMap<Var, Var> vMap, AbstractMap<Term, Var> substMap) {
return this;
}
long resolveTerm(long count) {
return count;
}
/**
*
*/
public void free() {
}
void restoreVariables() {
}
/*Castagna 06/2011*/
@Override
public void accept(TermVisitor tv) {
tv.visit(this);
}
/**/
}
| bsd-3-clause |
adamretter/jenkins-scala-plugin | jenkins-scala-plugin/src/main/java/hudson/plugins/scala/ScriptSource.java | 3108 | /**
* Copyright (c) 2014, Adam Retter <adam.retter@googlemail.com>
* All rights reserved.
*
* This software includes code from: groovy-plugin https://github.com/jenkinsci/groovy-plugin,
* Copyright (c) <2007> <Red Hat, Inc.>.
*
* 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 {organization} 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 hudson.plugins.scala;
import hudson.FilePath;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.Describable;
import hudson.util.DescriptorList;
import java.io.IOException;
public interface ScriptSource extends Describable<ScriptSource> {
/**
* In the end, every script is a file...
*
* @param projectWorkspace Project workspace (useful when the source has to create temporary file)
* @return Path to the executed script file
* @throws java.io.IOException
* @throws java.lang.InterruptedException
*/
public FilePath getScriptFile(final FilePath projectWorkspace) throws IOException, InterruptedException;
/**
* Able to load script when script path contains parameters
*
* @param projectWorkspace Project workspace to create tmp file
* @param build needed to obtain environment variables
* @param listener The build listener needed by Environment
* @return Path to the executed script file
* @throws IOException
* @throws InterruptedException
*/
public FilePath getScriptFile(final FilePath projectWorkspace, AbstractBuild<?, ?> build, BuildListener listener) throws IOException, InterruptedException;
public static final DescriptorList<ScriptSource> SOURCES = new DescriptorList<ScriptSource>(ScriptSource.class);
}
| bsd-3-clause |
WhitmoreLakeTroBots/2016-Stronghold | src/org/usfirst/frc3668/Stronghold/commands/CMDturtleTailUP.java | 1524 | package org.usfirst.frc3668.Stronghold.commands;
import org.usfirst.frc3668.Stronghold.Robot;
import org.usfirst.frc3668.Stronghold.RobotMap;
import org.usfirst.frc3668.Stronghold.Settings;
import edu.wpi.first.wpilibj.command.Command;
/**
*
*/
public class CMDturtleTailUP extends Command {
public CMDturtleTailUP() {
// Use requires() here to declare subsystem dependencies
requires(Robot.TurtleTail);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
// Robot.TurtleTail.autoRaise();
if (Robot.TurtleTail.getTurtleTailEconder() > (Settings.TT_slowDownBand + Settings.TT_upPosition)) {
Robot.TurtleTail.Move(Settings.TT_motorSpeed);
} else {
Robot.TurtleTail.Move(Settings.TT_slowSpeed);
}
System.out.println("Upper Switch: " + Robot.TurtleTail.isUP() + "\t Turtle Tail encoder: "
+ Robot.TurtleTail.getTurtleTailEconder());
// System.out.println("RU Turtle Tail Encoder = " +
// Robot.TurtleTail.getTurtleTailEconder());
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return Robot.TurtleTail.isUP();
}
// Called once after isFinished returns true
protected void end() {
Robot.TurtleTail.Move(0);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
Robot.TurtleTail.Move(0);
}
}
| bsd-3-clause |
nesl/FieldStream-AntRadio | src/org/fieldstream/service/logger/DatabaseLogger.java | 38834 | //Copyright (c) 2010, University of Memphis, Carnegie Mellon University
//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 names of the University of Memphis and Carnegie Mellon University 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.
//
// @author Andrew Raij
package org.fieldstream.service.logger;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Map.Entry;
import org.fieldstream.Constants;
import org.fieldstream.gui.ema.EMALogConstants;
import org.fieldstream.gui.ema.IContent;
import org.fieldstream.gui.ema.InterviewScheduler;
import org.fieldstream.incentives.AbstractIncentivesManager;
import org.fieldstream.service.StateManager;
import org.fieldstream.service.context.model.ModelCalculation;
import org.fieldstream.service.logger.Log;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
//NOTES for new logger
//--------------------
//TODO Maybe add a dbHelper to handle auto-creation and upgrades of db.
//Can't use SQLiteOpenHelper as is. It requires db be in data dir rather than sdcard.
//see http://www.anddev.org/custom_content_providers_and_files-t9272.html for one solution.
//
//TODO VERIFY chestband hours incentive logging
/**
* A class that handles all data logging from sensors, features, and models (contexts)
*
* All data should be timestamped in terms of milliseconds from the epoch (January 1, 1970 00:00:00 GMT).
*
* Will NOT log any sensor/feature/model listed in Constants.DATALOG_FILTER
*/
public class DatabaseLogger extends AbstractLogger {
private String dbFilename;
private String dbDirectory;
private SQLiteDatabase db;
private HashMap<String, Boolean> tableExistsCache;
private static final String TAG = "DataLoggerService";
private HandlerThread mythread;
private Handler myhandel;
private static DatabaseLogger INSTANCE = null;
private static HashSet<Object> refHolders;
public static DatabaseLogger getInstance(Object holder) {
if (INSTANCE == null) {
INSTANCE = new DatabaseLogger();
refHolders = new HashSet<Object>();
}
refHolders.add(holder);
return INSTANCE;
}
public static void releaseInstance(Object holder) {
refHolders.remove(holder);
if (refHolders.isEmpty()) {
// time to shut down the db
INSTANCE.close();
INSTANCE = null;
refHolders = null;
}
}
/**
* Constructor for DataLogger.
* @param dbDirectory path to database
*/
protected DatabaseLogger() {
super(true);
mythread = new HandlerThread("DataLogService");
mythread.start();
myhandel = new Handler(mythread.getLooper());
this.dbFilename = Constants.DATALOG_FILENAME;
File root = Environment.getExternalStorageDirectory();
this.dbDirectory = root + "/" + Constants.LOG_DIR;
db = null;
initDB();
}
/**
* Constructor for DataLogger.
* @param dbDirectory path to database
*/
protected DatabaseLogger(String dbDirectory, boolean automaticLogging) {
super(automaticLogging);
mythread = new HandlerThread("DataLogService");
mythread.start();
myhandel = new Handler(mythread.getLooper());
this.dbFilename = Constants.DATALOG_FILENAME;
this.dbDirectory = dbDirectory;
db = null;
initDB();
}
/**
*
* Opens the database if it exists. Otherwise, it creates a new
* database and sets up the metadata tables
*/
protected void initDB() {
String pathToFile = dbDirectory +"/" + dbFilename;
tableExistsCache = new HashMap<String, Boolean>();
try {
File dir = new File(dbDirectory);
if (!dir.exists()) {
dir.mkdirs();
}
db = SQLiteDatabase.openDatabase(pathToFile, null, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY);
if (!tableExists("sensor_metadata")) {
// create sensors metadata table
String create = "CREATE TABLE " + "sensor_metadata" +
" (_id INTEGER PRIMARY KEY, table_name TEXT, sensor_desc TEXT);";
db.execSQL(create);
tableExistsCache.put("sensor_metadata", true);
}
if (!tableExists("feature_metadata")) {
// create features metadata table
String create = "CREATE TABLE " + "feature_metadata" +
" (_id INTEGER PRIMARY KEY, table_name TEXT, sensor_desc TEXT, feature_desc TEXT);";
db.execSQL(create);
tableExistsCache.put("feature_metadata", true);
}
if (!tableExists("model_metadata")) {
// create models metadata table
String create = "CREATE TABLE " + "model_metadata" +
" (_id INTEGER PRIMARY KEY, table_name TEXT, model_desc TEXT, model_outputs TEXT);";
db.execSQL(create);
tableExistsCache.put("model_metadata", true);
}
if (!tableExists("EMA_metadata")) {
// create EMA metadata table
String create = "CREATE TABLE " + "EMA_metadata" +
" (_id INTEGER PRIMARY KEY, table_name TEXT, trigger_types TEXT, status_types TEXT, delay_questions_desc, delay_responses_desc TEXT, questions_desc TEXT, responses_desc TEXT);";
db.execSQL(create);
tableExistsCache.put("EMA_metadata", true);
}
if (!tableExists("incentives_metadata")) {
// create incentives metadata table
String create = "CREATE TABLE " + "incentives_metadata" +
" (_id INTEGER PRIMARY KEY, table_name TEXT, incentive_desc TEXT, total_earned DOUBLE);";
db.execSQL(create);
tableExistsCache.put("incentives_metadata", true);
}
} catch (SQLiteException ex) {
Log.e(TAG, "Problem initializing DB: " + ex.getLocalizedMessage());
}
if (Log.DEBUG) Log.d(TAG, "DB ready");
}
/**
* Checks if the specified table exists
* @param tableName The unique id of the table.
*/
protected Boolean tableExists(String tableName) {
if (db == null)
return false;
Boolean exists = tableExistsCache.get(tableName);
// this table is not cached yet
if (exists == null) {
// SELECT name FROM sqlite_master WHERE name='table_name'
String[] columns = {"name"};
Cursor c = db.query("sqlite_master", columns, "name='" + tableName + "'", null, null, null, null);
exists = c.getCount() > 0;
c.close();
tableExistsCache.put(tableName, exists);
}
return exists;
}
// SENSOR LOGGING
// --------------
/**
* Creates a table for the specified sensor. This should only get called if the table does not exist already.
* @param tableName The unique id of the sensor (from Constants).
*/
protected Boolean createSensorTable(int sensorID) {
if (db == null)
return null;
String tableName = "sensor" + sensorID;
try {
// add the table to metadata
ContentValues values = new ContentValues();
//values.put("_id", p.getId());
values.put("table_name", tableName);
values.put("sensor_desc", Constants.getSensorDescription(Constants.parseSensorId(sensorID)));
db.insertOrThrow("sensor_metadata", null, values);
// create the table
String create = "CREATE TABLE " + tableName +
" (_id INTEGER PRIMARY KEY, start_timestamp INTEGER, end_timestamp INTEGER, num_samples INTEGER, timestamps BLOB, samples BLOB);";
db.execSQL(create);
tableExistsCache.put(tableName, true);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not create sensor table " + tableName + ": " + e.getMessage());
}
return null;
}
/**
* Reads data in the DB from the specified sensor. This enables context inferencing algorithms
* to use older data no longer available in the feature/sensor/context buffers.
* @param sensorID The unique id of the sensor (from Constants).
* @param startTime, endTime The returned cursor will contain data in between (and including) startTime and endTime.
*/
public Cursor readSensorData(int sensorID, long startTime, long endTime) {
if (db == null)
return null;
String tableName = "sensor" + sensorID;
if (!tableExists(tableName))
return null;
String[] columns = {"start_timestamp", "end_timestamp", "samples"};
String where = "start_timestamp BETWEEN '" + Long.toString(startTime) + "' AND '" + Long.toString(endTime) + "'";
where += " OR end_timestamp BETWEEN '" + Long.toString(startTime) + "' AND '" + Long.toString(endTime) + "'";
Cursor c = db.query(tableName, columns, where, null, null, null, null);
return c;
}
/* (non-Javadoc)
* @see edu.cmu.ices.stress.phone.service.logger.ILogger#logSensorData(int, long[], int[])
*/
public void logSensorData(int sensorID, long[] timestamps, int[] buffer, int startNewData, int endNewData){
if (timestamps.length <=0 || buffer.length <= 0)
return;
if (Constants.DATALOG_FILTER.contains(sensorID))
return;
if (db == null)
return;
String tableName = "sensor" + sensorID;
// check if the table for this data exists
if (!tableExists(tableName)) {
// if not, create the table
createSensorTable(sensorID);
}
SensorLogRunner sensorLogRunner = new SensorLogRunner(tableName, timestamps, buffer, startNewData, endNewData);
myhandel.post(sensorLogRunner);
}
/**
* A class that makes sensor logging occur in a new thread
*/
class SensorLogRunner implements Runnable {
private String tableName;
private long[] timestamps;
private int[] buffer;
private int startNewData;
private int endNewData;
/**
* Constructor
*/
public SensorLogRunner(String tableName, long[] timestamps, int[] buffer, int startNewData, int endNewData) {
this.tableName = tableName;
this.timestamps = timestamps;
this.buffer = buffer;
this.startNewData = startNewData;
this.endNewData = endNewData;
}
/**
* Handles logging
*/
public void run() {
long id = -1;
try{
int start, end;
if (startNewData == endNewData) {
start = 0;
end = buffer.length;
}
else {
start = startNewData;
end = endNewData;
}
ContentValues values = new ContentValues();
values.put("num_samples", end - start);
values.put("start_timestamp", timestamps[start]);
values.put("end_timestamp", timestamps[end-1]);
byte [] bytes = longSubArrayToByteArray(timestamps, start, end);
values.put("timestamps", bytes);
bytes = intSubArrayToByteArray(buffer, start, end);
values.put("samples", bytes);
if (db.isOpen()) {
id = db.insertOrThrow(tableName, null, values);
}
}
catch (SQLiteException e) {
Log.e(TAG, "Could not write sensor sample to table " + tableName + ": " + e.getMessage());
}
}
}
private static final byte[] intSubArrayToByteArray(int[] input, int start, int end) {
byte[] output = new byte[(end-start) * 4];
int j = 0;
for (int i=start; i < end; i++, j++) {
output[4*j] = (byte)(input[i] >>> 24);
output[4*j + 1] = (byte)(input[i] >>> 16);
output[4*j + 2] =(byte)(input[i] >>> 8);
output[4*j + 3] = (byte)input[i];
}
return output;
}
private static final byte[] longSubArrayToByteArray(long[] input, int start, int end) {
byte[] output = new byte[(end-start) * 8];
int j = 0;
for (int i=start; i < end; i++, j++) {
output[8*j] = (byte)(input[i] >>> 56);
output[8*j + 1] = (byte)(input[i] >>> 48);
output[8*j + 2] =(byte)(input[i] >>> 40);
output[8*j + 3] = (byte)(input[i] >>> 32);
output[8*j + 4] = (byte)(input[i] >>> 24);
output[8*j + 5] = (byte)(input[i] >>> 16);
output[8*j + 6] =(byte)(input[i] >>> 8);
output[8*j + 7] = (byte)input[i];
}
return output;
}
public static final int byteArrayToInt(byte [] b) {
return (b[0] << 24)
+ ((b[1] & 0xFF) << 16)
+ ((b[2] & 0xFF) << 8)
+ (b[3] & 0xFF);
}
public static final long byteArrayToLong(byte [] b) {
return (b[0] << 56) + ((b[1] & 0xFF) << 48) + ((b[2] & 0xFF) << 40) + (b[3] & 0xFF << 32) + (b[4] & 0xFF << 24) + (b[5] & 0xFF << 16) + (b[6] & 0xFF << 8) + (b[7] & 0xFF);
}
// FEATURE LOGGING
// ---------------
/**
* Creates a table for the specified sensor-feature pair. This should only get called if the table does not exist already.
* @param featureID The unique id of the feature-sensor (from Constants).
*/
protected Boolean createFeatureTable(int featureID) {
if (db == null)
return null;
String tableName = "feature" + featureID;
try {
// add the table to metadata
ContentValues values = new ContentValues();
values.put("table_name", tableName);
values.put("sensor_desc", Constants.getSensorDescription(Constants.parseSensorId(featureID)));
values.put("feature_desc", Constants.getFeatureDescription(Constants.parseFeatureId(featureID)));
db.insertOrThrow("feature_metadata", null, values);
// create the table
String create = "CREATE TABLE " + tableName +
" (_id INTEGER PRIMARY KEY, start_timestamp INTEGER, end_timestamp INTEGER, value DOUBLE);";
db.execSQL(create);
tableExistsCache.put(tableName, true);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not create feature table " + tableName + ": " + e.getMessage());
}
return null;
}
/**
* Reads data in the DB from the specified sensor-feature pair. This enables context inferencing algorithms
* to use older data no longer available in the feature/sensor/context buffers.
* @param featureID The unique id of the sensor-feature pair (from Constants).
* @param startTime, endTime The returned cursor will contain data in between (and including) startTime and endTime.
*/
public Cursor readFeatureData(int featureID, long startTime, long endTime) {
if (db == null)
return null;
String tableName = "feature" + featureID;
if (!tableExists(tableName))
return null;
String[] columns = {"start_timestamp", "end_timestamp", "value"};
String where = "start_timestamp BETWEEN '" + Long.toString(startTime) + "' AND '" + Long.toString(endTime) + "'";
where += " OR end_timestamp BETWEEN '" + Long.toString(startTime) + "' AND '" + Long.toString(endTime) + "'";
Cursor c = db.query(tableName, columns, where, null, null, null, null);
return c;
}
/* (non-Javadoc)
* @see edu.cmu.ices.stress.phone.service.logger.ILogger#logFeatureData(int, long, double)
*/
public void logFeatureData(int featureID, long timeBegin, long timeEnd, double value){
if (Constants.DATALOG_FILTER.contains(featureID))
return;
if (db == null)
return;
String tableName = "feature" + featureID;
// check if the table for this data exists
if (!tableExists(tableName)) {
// if not, create the table
createFeatureTable(featureID);
}
// write to DB
try{
ContentValues values = new ContentValues();
values.put("start_timestamp", timeBegin);
values.put("end_timestamp", timeEnd);
values.put("value", value);
db.insertOrThrow(tableName, null, values);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not write feature value to table " + tableName + ": " + e.getMessage());
}
// FeatureLogRunner featureLogRunner = new FeatureLogRunner(tableName, timestamp, value);
// myhandel.post(featureLogRunner);
}
// /**
// * A class that makes feature logging occur in a new thread
// */
// class FeatureLogRunner implements Runnable {
// private String tableName;
// private long timestamp;
// private double value;
//
// /**
// * Constructor
// */
// public FeatureLogRunner(String tableName, long timestamp, double value) {
// this.tableName = tableName;
// this.timestamp = timestamp;
// this.value = value;
// }
//
// /**
// * Handles logging
// */
// public void run() {
// try{
// ContentValues values = new ContentValues();
// values.put("timestamp", timestamp);
// values.put("value", value);
//
// db.insertOrThrow(tableName, null, values);
// }
// catch (SQLiteException e) {
// Log.e(TAG, "Could not write feature value to table " + tableName + ": " + e.getMessage());
// }
// }
// }
// CONTEXT/MODEL LOGGING
// ---------------------
/**
* Creates a table for the specified model. This should only get called if the table does not exist already.
* @param modelID The unique id of the model (from Constants).
*/
protected Boolean createModelTable(int modelID) {
if (db == null)
return null;
String tableName = "model" + modelID;
try {
// add the table to metadata
ContentValues values = new ContentValues();
values.put("table_name", tableName);
values.put("model_desc", Constants.getModelDescription(modelID));
ModelCalculation model = StateManager.models.get(modelID);
Iterator<Entry<Integer,String>> itr = model.getOutputDescription().entrySet().iterator();
String outputs = "";
while(itr.hasNext()) {
Entry<Integer,String> entry = itr.next();
outputs += entry.getKey() + ":" + entry.getValue();
if (itr.hasNext()) {
outputs+="\n";
}
}
values.put("model_outputs", outputs);
db.insertOrThrow("model_metadata", null, values);
// create the table
String create = "CREATE TABLE " + tableName +
" (_id INTEGER PRIMARY KEY, start_timestamp INTEGER, end_timestamp INTEGER, label INTEGER);";
db.execSQL(create);
tableExistsCache.put(tableName, true);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not create model table " + tableName + ": " + e.getMessage());
}
return null;
}
/**
* Reads data in the DB from the specified model. This enables context inferencing algorithms
* to use older data no longer available in the feature/sensor/context buffers.
* @param modelID The unique id of the model (from Constants).
* @param startTime, endTime The returned cursor will contain data in between (and including) startTime and endTime.
*/
public Cursor readModelData(int modelID, long startTime, long endTime) {
if (db == null)
return null;
String tableName = "model" + modelID;
if (!tableExists(tableName))
return null;
String[] columns = {"start_timestamp", "end_timestamp", "label"};
String where = "start_timestamp BETWEEN '" + Long.toString(startTime) + "' AND '" + Long.toString(endTime) + "'";
where += " OR end_timestamp BETWEEN '" + Long.toString(startTime) + "' AND '" + Long.toString(endTime) + "'";
Cursor c = db.query(tableName, columns, where, null, null, null, null);
return c;
}
/* (non-Javadoc)
* @see edu.cmu.ices.stress.phone.service.logger.ILogger#logModelData(int, long, int)
*/
public void logModelData(int modelID, int label, long startTime, long endTime){
if (Constants.DATALOG_FILTER.contains(modelID))
return;
if (db == null)
return;
String tableName = "model" + modelID;
// check if the table for this data exists
if (!tableExists(tableName)) {
// if not, create the table
createModelTable(modelID);
}
// write to the db
try{
ContentValues values = new ContentValues();
values.put("start_timestamp", startTime);
values.put("end_timestamp", endTime);
values.put("label", label);
db.insertOrThrow(tableName, null, values);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not write model label to table " + tableName + ": " + e.getMessage());
}
// ModelLogRunner modelLogRunner = new ModelLogRunner(tableName, timestamp, label);
// myhandel.post(modelLogRunner);
}
// /**
// * A class that makes feature logging occur in a new thread
// */
// class ModelLogRunner implements Runnable {
// private String tableName;
// private long timestamp;
// private int label;
//
// /**
// * Constructor
// */
// public ModelLogRunner(String tableName, long timestamp, int label) {
// this.tableName = tableName;
// this.timestamp = timestamp;
// this.label = label;
// }
//
// /**
// * Handles logging
// */
// public void run() {
// try{
// ContentValues values = new ContentValues();
// values.put("timestamp", timestamp);
// values.put("label", Integer.toString(label));
//
// db.insertOrThrow(tableName, null, values);
// }
// catch (SQLiteException e) {
// Log.e(TAG, "Could not write model label to table " + tableName + ": " + e.getMessage());
// }
// }
// }
// EMA LOGGING
// -----------
/**
* Creates a table for logging EMA data (labels, timing, etc.).
* This should only get called if the table does not exist already.
* This is tied very closely to the InterviewContent class.
*/
protected Boolean createEMATable(String tableName) {
if (db == null)
return null;
// add the table to metadata
ContentValues values = new ContentValues();
values.put("table_name", tableName);
// trigger types
Iterator<Entry<Integer,String>> itr = EMALogConstants.emaTriggerDescriptions.entrySet().iterator();
String triggerTypes = "";
while(itr.hasNext()) {
Entry<Integer,String> entry = itr.next();
triggerTypes += entry.getKey() + ":" + entry.getValue();
if (itr.hasNext()) {
triggerTypes+="\n";
}
}
values.put("trigger_types", triggerTypes);
// status types
itr = EMALogConstants.emaStatusDescriptions.entrySet().iterator();
String statusTypes = "";
while(itr.hasNext()) {
Entry<Integer,String> entry = itr.next();
statusTypes += entry.getKey() + ":" + entry.getValue();
if (itr.hasNext()) {
statusTypes+="\n";
}
}
values.put("status_types", statusTypes);
IContent content = InterviewScheduler.getContent();
// delay questions
int len = content.getNumberDelayQuestions();
String questions = "";
for (int i = 0; i < len; i++) {
questions += i + ":" + content.getDelayQuestion(i);
if (i < len - 1) {
questions += "\n";
}
}
values.put("delay_questions_desc", questions);
// delay responses
String responses = "";
for (int i = 0; i < len; i++) {
responses += i + ":[";
String[] temp = content.getDelayResponses(i);
for (int j=0; j < temp.length; j++) {
responses += temp[j];
if (j < temp.length -1) {
responses += ", ";
}
}
responses += "]\n";
}
values.put("delay_responses_desc", responses);
// questions
len = content.getNumberQuestions(false);
questions = "";
for (int i = 0; i < len; i++) {
questions += i + ":" + content.getQuestion(i);
if (i < len - 1) {
questions += "\n";
}
}
values.put("questions_desc", questions);
// responses
responses = "";
for (int i = 0; i < len; i++) {
responses += i + ":[";
String[] temp = content.getResponses(i);
if (temp != null) {
for (int j=0; j < temp.length; j++) {
responses += temp[j];
if (j < temp.length -1) {
responses += ", ";
}
}
}
responses += "]\n";
}
values.put("responses_desc", responses);
try {
db.insertOrThrow("ema_metadata", null, values);
// create the table
String create = "CREATE TABLE " + tableName +
" (_id INTEGER PRIMARY KEY, trigger_type INTEGER, context TEXT, status INTEGER, " +
" prompt_timestamp INTEGER, delay_duration INTEGER, start_timestamp INTEGER";
len = content.getNumberDelayQuestions();
for (int i=0; i < len; i++) {
create += ", delay_response" + i + " TEXT, delay_response_time" + i + " INTEGER";
}
len = content.getNumberQuestions(false);
for (int i=0; i < len; i++) {
create += ", response" + i + " TEXT, response_time" + i + " INTEGER";
}
create += ");";
db.execSQL(create);
tableExistsCache.put(tableName, true);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not create EMA table " + tableName + ": " + e.getMessage());
}
return null;
}
public void logEMA(int triggerType, String emaContext, int status, long prompt,
long delayDuration, String[] delayResponses, long[] delayResponseTimes, long start,
String[] responses, long[] responseTimes) {
if (db == null)
return;
String tableName = "ema";
// check if the table for this data exists
if (!tableExists(tableName)) {
// if not, create the table
createEMATable(tableName);
}
EMALogRunner emaLogRunner = new EMALogRunner(tableName, triggerType, emaContext, status,
prompt, delayDuration, delayResponses, delayResponseTimes,
start, responses, responseTimes);
myhandel.post(emaLogRunner);
}
/**
* A class that makes sensor logging occur in a new thread
*/
class EMALogRunner implements Runnable {
String tableName;
int triggerType;
int status;
long prompt;
long delayDuration;
String[] delayResponses;
long[] delayResponseTimes;
long start;
String[] responses;
long[] responseTimes;
String emaContext;
/**
* Constructor
*/
public EMALogRunner(String tableName, int triggerType, String emaContext, int status, long prompt,
long delayDuration, String[] delayResponses, long[] delayResponseTimes, long start,
String[] responses, long[] responseTimes) {
this.tableName = tableName;
this.triggerType = triggerType;
this.status = status;
this.prompt = prompt;
this.delayDuration = delayDuration;
this.delayResponses = delayResponses;
this.delayResponseTimes = delayResponseTimes;
this.start = start;
this.responses = responses;
this.responseTimes = responseTimes;
this.emaContext = emaContext;
}
/**
* Handles logging
*/
public void run() {
// write to the db
try{
ContentValues values = new ContentValues();
values.put("trigger_type", triggerType);
values.put("context", emaContext);
values.put("status", status);
values.put("prompt_timestamp", prompt);
values.put("start_timestamp", start);
values.put("delay_duration", delayDuration);
IContent content = InterviewScheduler.getContent();
int len = content.getNumberDelayQuestions();
for (int i=0; i < len; i++) {
values.put("delay_response" + i, delayResponses[i]);
values.put("delay_response_time" + i, delayResponseTimes[i]);
}
len = content.getNumberQuestions(false);
for (int i=0; i < len; i++) {
values.put("response" + i, responses[i]);
values.put("response_time" + i, responseTimes[i]);
}
db.insertOrThrow(tableName, null, values);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not write EMA data to table " + tableName + ": " + e.getMessage());
}
}
}
public Cursor readEMA(long startTime, long endTime) {
if (db == null)
return null;
String tableName = "ema";
if (!tableExists(tableName))
return null;
IContent content = InterviewScheduler.getContent();
String[] columns = new String[5 + 2 * content.getNumberDelayQuestions() + 2 * content.getNumberQuestions(false)];
columns[0] = "trigger_type";
columns[1] = "context";
columns[2] = "status";
columns[3] = "prompt_timestamp";
columns[4] = "start_timestamp";
int len = content.getNumberDelayQuestions();
int index = 5;
for (int i=0; i < len; i++) {
columns[index++] = "delay_response" + i;
columns[index++] = "delay_response_time" + i;
}
len = content.getNumberQuestions(false);
for (int i=0; i < len; i++) {
columns[index++] = "response" + i;
columns[index++] = "response_time" + i;
}
Cursor c = db.query(tableName, columns, "prompt_timestamp BETWEEN'" + Long.toString(startTime) + "' AND '" + Long.toString(endTime) +"'", null, null, null, null);
return c;
}
@Override
public void logUIData(String data) {
// TODO Auto-generated method stub
}
// INCENTIVES LOGGING
// ------------------
/**
* Creates a table for logging earned incentives. This should only get called if the table does not exist already.
*/
protected Boolean createIncentivesTable(int incentiveID) {
if (db == null) {
Log.d("db", "createIncentiveTable - db is null");
return null;
}
String tableName = "incentives" + incentiveID;
Log.d("db", "trying to create incentives table");
try {
// add the table to metadata
ContentValues values = new ContentValues();
values.put("table_name", tableName);
String incentiveDesc = AbstractIncentivesManager.getIncentiveDesc(incentiveID);
values.put("incentive_desc",incentiveDesc);
values.put("total_earned", 0.00);
db.insertOrThrow("incentives_metadata", null, values);
// create the table
String create = "CREATE TABLE " + tableName +
" (_id INTEGER PRIMARY KEY, timestamp INTEGER, comment TEXT, amount DOUBLE);";
db.execSQL(create);
tableExistsCache.put(tableName, true);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not create incentives table " + tableName + ": " + e.getMessage());
}
return null;
}
public void logIncentiveEarned(int incentiveID, String comment, long timestamp, float amount, float total) {
if (db == null) {
Log.d("db", "logincentive - db is null");
return;
}
Log.d("db", "trying to log incentives");
String tableName = "incentives" + incentiveID;
// check if the table for this data exists
if (!tableExists(tableName)) {
// if not, create the table
createIncentivesTable(incentiveID);
}
// write to the db
try{
ContentValues values = new ContentValues();
if (amount != 0) {
values.put("timestamp", timestamp);
values.put("comment", comment);
values.put("amount", amount);
db.insertOrThrow(tableName, null, values);
}
values.clear();
values.put("total_earned", total);
db.update("incentives_metadata", values, "table_name='" + tableName + "'", null);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not write incentive to table " + tableName + ": " + e.getMessage());
}
}
/**
* Reads incentives data in the DB. This enables reloading incentives data.
*/
public Cursor readIncentivesData(int incentiveID) {
if (db == null) {
Log.d("db", "db is null");
return null;
}
String tableName = "incentives" + incentiveID;
if (!tableExists(tableName)) {
Log.d("db", "table " + tableName + "does not exist");
return null;
}
String[] columns = {"amount", "timestamp", "comment"};
Cursor c = db.query(tableName, columns, null, null, null, null, null);
return c;
}
// /**
// * Reads incentives data in the DB. This enables reloading incentives data.
// */
// public long readIncentivesTimeWearingBand() {
// if (db == null)
// return 0;
//
// String tableName = "incentives_metadata";
// if (!tableExists(tableName))
// return 0;
//
// String[] columns = {"ms_wearing_band"};
// Cursor c = db.query(tableName, columns, null, null, null, null, null);
// if (c.moveToFirst()) {
// return c.getLong(0);
// }
//
// return 0;
// }
// PERFORMANCE/DEBUG LOGGING
// -------------------------
/**
* Creates a table for logging performance values. This should only get called if the table does not exist already.
*/
protected Boolean createPerformanceTable() {
if (db == null)
return null;
String tableName = "performance";
// create the table
String create = "CREATE TABLE " + tableName +
" (_id INTEGER PRIMARY KEY, timestamp INTEGER, location INTEGER, report TEXT);";
try {
db.execSQL(create);
tableExistsCache.put(tableName, true);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not create performance table " + tableName + ": " + e.getMessage());
}
return null;
}
@Override
public void logPerformance(int location, long timestamp, String logString) {
if (db == null)
return;
String tableName = "performance";
// check if the table for this data exists
if (!tableExists(tableName)) {
// if not, create the table
createPerformanceTable();
}
// write to the db
try{
ContentValues values = new ContentValues();
values.put("location", location);
values.put("timestamp", timestamp);
values.put("report", logString);
db.insertOrThrow(tableName, null, values);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not write performance string to table " + tableName + ": " + e.getMessage());
}
}
public double getTotalIncentivesEarned() {
double total = 0.0;
String columns[] = {"total_earned"};
Cursor c = db.query("incentives_metadata", columns, null, null, null, null, null);
int index = c.getColumnIndex(columns[0]);
if (c.moveToFirst()) {
do {
total += c.getDouble(index);
} while (c.moveToNext());
}
c.close();
return total;
}
/**
* Creates a table for logging dead periods. This should only get called if the table does not exist already.
*/
protected Boolean createDeadPeriodTable() {
if (db == null)
return null;
String tableName = "deadperiod";
// create the table
String create = "CREATE TABLE " + tableName +
" (_id INTEGER PRIMARY KEY, start INTEGER, end INTEGER);";
try {
db.execSQL(create);
tableExistsCache.put(tableName, true);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not create dead period table " + tableName + ": " + e.getMessage());
}
return null;
}
public void logDeadPeriod(long start, long end) {
if (db == null)
return;
String tableName = "deadperiod";
// check if the table for this data exists
if (!tableExists(tableName)) {
// if not, create the table
createDeadPeriodTable();
}
// write to the db
try{
String[] columns = {"start", "end"};
String where = "start= '" + start + "' AND end= '" + end + "'";
Cursor c = db.query(tableName, columns, where, null, null, null, null);
if (c.getCount() == 0) {
ContentValues values = new ContentValues();
values.put("start", start);
values.put("end", end);
db.insertOrThrow(tableName, null, values);
}
c.close();
}
catch (SQLiteException e) {
Log.e(TAG, "Could not write performance string to table " + tableName + ": " + e.getMessage());
}
}
@Override
public void close() {
if (db != null && db.isOpen())
db.close();
db = null;
myhandel.removeCallbacks(mythread);
myhandel.getLooper().quit();
myhandel = null;
mythread = null;
super.close();
if (Log.DEBUG) Log.d("DatabaseLogger","closing db");
}
protected Boolean createResumeTable() {
if (db == null)
return null;
String tableName = "resume";
// create the table
String create = "CREATE TABLE " + tableName +
" (_id INTEGER PRIMARY KEY, timestamp INTEGER);";
try {
db.execSQL(create);
tableExistsCache.put(tableName, true);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not create resume table " + tableName + ": " + e.getMessage());
}
return null;
}
public void logResume(long timestamp) {
if (db == null)
return;
String tableName = "resume";
// check if the table for this data exists
if (!tableExists(tableName)) {
// if not, create the table
createResumeTable();
}
// write to the db
ContentValues values = new ContentValues();
values.put("timestamp", timestamp);
try{
db.insertOrThrow(tableName, null, values);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not write performance string to table " + tableName + ": " + e.getMessage());
}
}
@Override
public void logAnything(String tableName, String entry, long timestamp) {
if (db == null)
return;
// check if the table for this data exists
if (!tableExists(tableName)) {
// if not, create the table
createAnythingTable(tableName);
}
// write to the db
ContentValues values = new ContentValues();
values.put("timestamp", timestamp);
values.put("entry", entry);
try{
db.insertOrThrow(tableName, null, values);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not write generic entry to table " + tableName + ": " + e.getMessage());
}
}
protected Boolean createAnythingTable(String tableName) {
if (db == null)
return null;
// create the table
String create = "CREATE TABLE " + tableName +
" (_id INTEGER PRIMARY KEY, timestamp INTEGER, entry TEXT);";
try {
db.execSQL(create);
tableExistsCache.put(tableName, true);
}
catch (SQLiteException e) {
Log.e(TAG, "Could not create anything table " + tableName + ": " + e.getMessage());
}
return null;
}
};
| bsd-3-clause |
callumhay/biffbamblammogame | LevelEditor/BBBLevelEditor/src/bbbleveleditor/LevelPiece.java | 1627 | package bbbleveleditor;
import java.util.HashMap;
import javax.swing.ImageIcon;
public class LevelPiece {
public static final String PORTAL_PIECE_NAME = "Portal";
public static final String PORTAL_PIECE_SYMBOL = "X";
public static final String TESLA_PIECE_NAME = "Tesla";
public static final String TESLA_PIECE_SYMBOL = "A";
public static final String ITEM_DROP_PIECE_SYMBOL = "D";
public static final String ALWAYS_DROP_PIECE_SYMBOL = "K";
public static final String CANNON_PIECE_SYMBOL = "C";
public static final String ONE_SHOT_CANNON_PIECE_SYMBOL = "C1";
public static final String SWITCH_PIECE_SYMBOL = "W";
public static final String WARP_PORTAL_PIECE_SYMBOL = "V";
public static final String ITEM_DROP_PIECE_NAME = "Item Drop";
public static final int NO_TRIGGER_ID = -1;
public static LevelPiece DefaultPiece;
// Hash mapping of the symbols to level pieces
public static HashMap<String, LevelPiece> LevelPieceCache = new HashMap<String, LevelPiece>();
public static final int LEVEL_PIECE_WIDTH = 40;
public static final int LEVEL_PIECE_HEIGHT = 20;
private String name;
private String fileSymbol;
private ImageIcon pieceImage;
public LevelPiece(String name, String symbol, String fileName) {
this.name = name;
this.fileSymbol = symbol;
this.pieceImage = new ImageIcon(BBBLevelEditorMain.class.getResource("resources/" + fileName));
}
public String getName() {
return this.name;
}
public ImageIcon getImageIcon() {
return this.pieceImage;
}
public String getSymbol() {
return this.fileSymbol;
}
}
| bsd-3-clause |
diorcety/jcabi-mysql-maven-plugin | src/it/parallel/src/test/java/com/jcabi/ParallelITCase.java | 3115 | /**
* Copyright (c) 2012-2013, JCabi.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. 3) Neither the name of the jcabi.com 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.jcabi;
import com.jcabi.jdbc.JdbcSession;
import java.sql.Connection;
import java.sql.DriverManager;
import org.junit.Test;
/**
* Test case for {@link Parallel}.
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
*/
public final class ParallelITCase {
/**
* First MySQL port.
*/
private static final String FIRST =
System.getProperty("failsafe.mysql.first");
/**
* Second MySQL port.
*/
private static final String SECOND =
System.getProperty("failsafe.mysql.second");
/**
* MySQL works.
* @throws Exception If something is wrong
*/
@Test
public void basicMySqlManipulations() throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
this.process(Integer.parseInt(ParallelITCase.FIRST));
}
/**
* Process on this port.
* @param port Port to process
* @throws Exception If fails
*/
private void process(final int port) throws Exception {
final Connection conn = DriverManager.getConnection(
String.format(
"jdbc:mysql://localhost:%d/root?user=root&password=root",
port
)
);
new JdbcSession(conn)
.autocommit(false)
.sql("CREATE TABLE foo (id INT)")
.execute()
.sql("INSERT INTO foo VALUES (1)")
.execute()
.sql("SELECT COUNT(*) FROM foo")
.execute()
.sql("DROP TABLE foo")
.execute();
}
}
| bsd-3-clause |
oliverlietz/bd-j | AuthoringTools/com.hdcookbook.grin/com.hdcookbook.grin-me/src/main/java/com/hdcookbook/grin/Show.java | 40097 |
/*
* Copyright (c) 2007, Sun Microsystems, 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 Sun Microsystems 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.
*
* Note: In order to comply with the binary form redistribution
* requirement in the above license, the licensee may include
* a URL reference to a copy of the required copyright notice,
* the list of conditions and the disclaimer in a human readable
* file with the binary form of the code that is subject to the
* above license. For example, such file could be put on a
* Blu-ray disc containing the binary form of the code or could
* be put in a JAR file that is broadcast via a digital television
* broadcast medium. In any event, you must include in any end
* user licenses governing any code that includes the code subject
* to the above license (in source and/or binary form) a disclaimer
* that is at least as protective of Sun as the disclaimers in the
* above license.
*
* A copy of the required copyright notice, the list of conditions and
* the disclaimer will be maintained at
* https://hdcookbook.dev.java.net/misc/license.html .
* Thus, licensees may comply with the binary form redistribution
* requirement with a text file that contains the following text:
*
* A copy of the license(s) governing this code is located
* at https://hdcookbook.dev.java.net/misc/license.html
*/
package com.hdcookbook.grin;
import com.hdcookbook.grin.animator.AnimationClient;
import com.hdcookbook.grin.animator.RenderContext;
import com.hdcookbook.grin.commands.ActivateSegmentCommand;
import com.hdcookbook.grin.commands.Command;
import com.hdcookbook.grin.features.Group;
import com.hdcookbook.grin.features.SetTarget;
import com.hdcookbook.grin.util.AssetFinder;
import com.hdcookbook.grin.util.ImageManager;
import com.hdcookbook.grin.util.ManagedImage;
import com.hdcookbook.grin.util.SetupManager;
import com.hdcookbook.grin.util.SetupClient;
import com.hdcookbook.grin.util.Debug;
import com.hdcookbook.grin.util.Queue;
import com.hdcookbook.grin.input.RCHandler;
import com.hdcookbook.grin.input.RCKeyEvent;
import java.util.Hashtable;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.io.IOException;
/**
* Represents a show. A show is the top-level node in a scene graph.
* It is composed of a number of segments. A show progresses by moving
* through segments; a show has exactly one active segment while it is
* running. A segment is composed of a number of visual features, plus
* a set of remote control handlers.
*
* @author Bill Foote (http://jovial.com)
**/
public class Show implements AnimationClient {
private Director director;
// Never null
/**
* Our helper that calls into us to load images and such. This is
* for internal use only, and is public so that GRIN features in
* other packages can access it efficiently.
**/
public SetupManager setupManager;
/**
* The component we're presented within. This can be needed
* for things like loading images via Component.prepareImage().
* It should only be used on an initialized, non-destroyed show.
**/
public Component component;
/**
* An object used to hold state during initializaition of a show.
* This is nulled out after the show is initialized.
* This is for internal use only, and is public so that GRIN
* classes in other packages can access it efficiently.
**/
public ShowInitializer initializer = new ShowInitializer();
protected Segment[] segments;
protected Feature[] features;
protected RCHandler[] rcHandlers;
protected Hashtable publicSegments;
protected Hashtable publicFeatures;
protected Hashtable publicRCHandlers;
protected Hashtable publicNamedCommands;
/**
* This is the set of images that are "sticky". Sticky images get
* loaded as normal (that is, by a feature that uses the image being
* included in the setup clause of a segment), but they are never
* unloaded. Thus, features that use sticky images will be
* prepared instantly if subsequently re-used.
* <p>
* This array may be null.
**/
protected ManagedImage[] stickyImages = null;
/**
* This is a dummy segment which contains one feature
* in its activated feature array, which represents the top of
* the rendering tree.
**/
protected Segment showTop = null;
/**
* A group representing a set of activated features in the
* currently activated Segment.
* This data member is accessed from Segment.activate(Segment)
* and Segment.runFeatureSetup().
*/
protected Group showTopGroup = null;
private Segment currentSegment = null;
private Segment[] segmentStack = new Segment[0]; // For push/pop
private int segmentStackPos = 0;
private String[] drawTargets;
private int defaultDrawTarget = 0;
private ActivateSegmentCommand popSegmentCommand = null;
private GrinXHelper syncDisplayCommand = null;
private GrinXHelper segmentDoneCommand = null;
private boolean initialized = false;
private boolean destroyed = false;
private Queue pendingCommands = new Queue(32);
private boolean deferringPendingCommands = false;
private int numTargets = 1; // number of RenderContext targets needed
// by this show
protected String fontName[];
protected int fontStyleSize[]; // style in lower two bits, >> 2 for size
private Font font[]; // Populated on demand by getFont(int).
/**
* Scale factor for use by a director's java code
*
* @see #getXScale()
**/
private int xScale = 1000; // in mills
/**
* Scale factor for use by a director's java code
*
* @see #getYScale()
**/
private int yScale = 1000; // in mills
/**
* Offset factor for use by a director's java code
*
* @see #getXOffset();
**/
private int xOffset = 0;
/**
* Offset factor for use by a director's java code
*
* @see #getYOffset();
**/
private int yOffset = 0;
/**
* Create a new show.
*
* @param director A Director helper class the xlet can use to control
* the show. May be null, in which case a default
* direct instance of Director will be assigned.
**/
public Show(Director director) {
if (director == null) {
director = new Director();
}
this.director = director;
director.setShow(this);
}
/**
* Get this show's director. If the show was created without a director,
* a default one is created, and this will be returned.
*
* @return our Director
**/
public Director getDirector() {
return director;
}
/**
* This is called to build the show. This needs to be done before
* initialize is called. Normally, clients of the GRIN framework
* shouldn't call this.
*
* @throws IOException if anything goes wrong.
**/
public void buildShow(Segment[] segments, Feature[] features,
RCHandler[] rcHandlers, String[] stickyImages,
Segment showTop, Group showTopGroup,
Hashtable publicSegments, Hashtable publicFeatures,
Hashtable publicRCHandlers,
Hashtable publicNamedCommands,
String[] fontName, int[] fontStyleSize)
throws IOException
{
this.segments = segments;
this.features = features;
this.rcHandlers = rcHandlers;
if (stickyImages != null) {
this.stickyImages = new ManagedImage[stickyImages.length];
for (int i = 0; i < stickyImages.length; i++) {
this.stickyImages[i] = ImageManager.getImage(stickyImages[i]);
// This will never be null, even if the path doesn't refer
// to a real image. The library doesn't try to load images
// until a feature that uses the image is prepared, so the
// framework has no way of knowing if the image exists or
// not at this time.
}
}
this.showTopGroup = showTopGroup;
this.showTop = showTop;
this.showTop.setShow(this);
this.publicSegments = publicSegments;
this.publicFeatures = publicFeatures;
this.publicRCHandlers = publicRCHandlers;
this.publicNamedCommands = publicNamedCommands;
for (int i = 0; i < rcHandlers.length; i++) {
rcHandlers[i].setShow(this);
}
for (int i = 0; i < segments.length; i++) {
segments[i].setShow(this);
}
this.fontName = fontName;
this.fontStyleSize = fontStyleSize;
font = new Font[fontName.length];
}
/**
* Sets the scale and offset values for a show.
**/
public void setScale(int xScale, int yScale, int xOffset, int yOffset) {
this.xScale = xScale;
this.yScale = yScale;
this.xOffset = xOffset;
this.yOffset = yOffset;
}
/**
* Get one of the fonts recorded for this show. This is an internal
* method for use by the text feature, or by other extension features
* that use show fonts. It should only be called from the setup thread,
* or from the animation thread after setup.
**/
public Font getFont(int index) {
// We're not synchronized, because we're called in well defined
// places with no possibility of conflict.
if (font[index] == null) {
int style = fontStyleSize[index] & 0x03;
int size = fontStyleSize[index] >> 2;
font[index] = AssetFinder.getFont(fontName[index], style, size);
}
return font[index];
}
/**
* {@inheritDoc}
* <p>
* This will be called by the animation framework; clients of the GRIN
* framework should ensure a show has been built before handing it off
* to the animation framework.
*
* @param component The component this show will eventually be displayed
* in. It's used for things like
* Component.prepareImage().
**/
public void initialize(Component component) {
if (Debug.ASSERT && initialized) {
Debug.assertFail("Initizlize called twice");
}
initialized = true;
this.component = component;
if (stickyImages != null) {
for (int i = 0; i < stickyImages.length; i++) {
this.stickyImages[i].makeSticky();
// This always succeeds, even if the actual image
// file doesn't exist, because no attempt is made to
// load the image here.
}
}
popSegmentCommand = new ActivateSegmentCommand(this, false, true);
{
int num = 0;
for (int i = 0; i < features.length; i++) {
if (features[i] instanceof SetupClient) {
num++;
}
}
setupManager = new SetupManager(num);
}
setupManager.start();
for (int i = 0; i < segments.length; i++) {
segments[i].initialize();
}
for (int i = 0; i < features.length; i++) {
features[i].initialize();
}
showTop.initialize();
showTop.activate(null);
initializer = null;
}
/**
* {@inheritDoc}
* <p>
* Destroy a show. This will be called by the animation framework
* when the animation engine is destroyed, or when this show is removed
* from the engine's list of shows.
**/
public synchronized void destroy() {
if (Debug.ASSERT && !initialized) {
Debug.assertFail("Destroy of uninitialized show");
}
if (currentSegment != null) {
currentSegment.deactivate();
currentSegment = null;
}
showTop.deactivate();
showTop = null;
for (int i = 0; i < features.length; i++) {
features[i].destroy();
}
if (stickyImages != null) {
for (int i = 0; i < stickyImages.length; i++) {
this.stickyImages[i].unmakeSticky();
}
}
destroyed = true;
setupManager.stop();
director.notifyDestroyed();
notifyAll();
}
/**
* Used to build the show. Clients of the GRIN framework should not
* call this method directly.
**/
public void setSegmentStackDepth(int depth) {
segmentStack = new Segment[depth];
}
/**
* Used to build the show, or to reinitialize it.
**/
public void setDrawTargets(String[] drawTargets) {
this.drawTargets = drawTargets;
}
/**
* Get the set of draw target names. The numerical draw targets
* in features (e.g. the SetTarget feature) don't necessarily correspond
* to indicies in this array, because when AnimationClient instances
* are set up in an AnimationEngine, a master list of all of the unique
* draw targets is built.
*
* @see com.hdcookbook.grin.animator.RenderContext#setTarget(int)
* @see #mapDrawTargets(Hashtable)
* @see com.hdcookbook.grin.features.SetTarget
**/
public String[] getDrawTargets() {
return drawTargets;
}
/**
* {@inheritDoc}
**/
public void mapDrawTargets(Hashtable targetMap) {
defaultDrawTarget
= ((Integer) targetMap.get(drawTargets[0])).intValue();
for (int i = 0; i < features.length; i++) {
Feature f = features[i];
if (f instanceof SetTarget) {
((SetTarget) f).mapDrawTarget(targetMap);
}
}
}
/**
* Look up the given public feature.
*
* @return feature, or null if not found
**/
public Feature getFeature(String name) {
return (Feature) publicFeatures.get(name);
}
/**
* Look up the given public named command or command list. This Command
* object can be used in a call to runCommand(Command) on the show
* from whene it came. If you send a named command to a different
* show, the results are undefined.
*
* @return the Command, or null
**/
public Command getNamedCommand(String name) {
return (Command) publicNamedCommands.get(name);
}
/**
* Get a public RC handler by name.
*
* @return rc handler, or null if not found
**/
public RCHandler getRCHandler(String name) {
return (RCHandler) publicRCHandlers.get(name);
}
/**
* Look up a public segment. This is done without taking out the show lock.
* It's OK to call this before the show is initialized.
*
* @return segment, or null if not found.
*
**/
public Segment getSegment(String name) {
return (Segment) publicSegments.get(name);
}
/**
* Get the depth of the segment stack. This is how many times you can
* push a segment without an old value falling off the end of the stack.
* It's set in the show file.
**/
public int getSegmentStackDepth() {
return segmentStack.length;
}
/**
* Set the current segment. This is the main way an application
* controls what is being displayed on the screen. The new segment
* will become current when we advance to the next frame.
* <p>
* This can be called from any thread; it does not take out the show
* lock or any other global locks. If the show has been destroyed,
* calling this method has no effect. It's OK to call this before the
* show has been initialized.
* <p>
* The current segment is not pushed onto the segment activation stack.
*
* @param seg The segment to activate, or null to pop the
* segment activation stack;
**/
public void activateSegment(Segment seg) {
activateSegment(seg, false);
}
/**
* Set the current segment. This is the main way an application
* controls what is being displayed on the screen. The new segment
* will become current when we advance to the next frame.
* <p>
* This can be called from any thread; it does not take out the show
* lock or any other global locks. If the show has been destroyed,
* calling this method has no effect.
*
* @param seg The segment to activate, or null to pop the
* segment activation stack.
*
* @param push When true and when the segment is non-null, the
* current segment will be pushed onto the
* segment activation stack as the show transitions to
* the new segment.
**/
public void activateSegment(Segment seg, boolean push) {
if (Debug.ASSERT && seg != null && seg.show != this) {
Debug.assertFail();
}
if (seg == null) {
runCommand(popSegmentCommand);
} else {
runCommand(seg.getCommandToActivate(push));
}
}
/**
* Used by the activate segment command. Clients of the GRIN framework
* should never call this method directly.
**/
public synchronized void pushCurrentSegment() {
segmentStack[segmentStackPos] = currentSegment;
segmentStackPos = (segmentStackPos + 1) % segmentStack.length;
}
/**
* Used by the activate segment command. Clients of the GRIN framework
* should never call this method directly.
**/
public synchronized Segment popSegmentStack() {
segmentStackPos--;
if (segmentStackPos < 0) {
segmentStackPos = segmentStack.length - 1;
}
Segment result = segmentStack[segmentStackPos];
segmentStack[segmentStackPos] = null;
return result;
}
/**
* Synchronize the display to the current show state. This works by
* queueing a show command. When executed, this command will prevent
* the execution of any other show commands, until the display has
* caught up to the internal program state. This is a good thing
* to do before a command that is potentially time-consuming, like
* selecting a playlist. To flesh out this example,
* on some players, while a playlist is being
* selected, the Java runtime does not get a chance to run and update
* the screen, so it's good to make sure the screen is up-to-date before
* starting the playlist selection.
* <p>
* Note carefully the difference between syncDisplay() and
* deferNextCommands(). If you're about to queue a command that does
* something time-consuming, then you should call syncDisplay() first,
* so the display is guaranteed to be updated. If, however, you're
* executing within the body of the command and you want to make sure the
* display gets synchronized before the next command in the queue (which
* was already there), then you want to call deferNextCommands().
* <p>
* This is equivalent to the <code>sync_display</code> GRIN command.
*
* @see #deferNextCommands()
**/
public void syncDisplay() {
if (syncDisplayCommand == null) {
GrinXHelper cmd = new GrinXHelper(this);
cmd.setCommandNumber(GrinXHelper.SYNC_DISPLAY);
syncDisplayCommand = cmd;
}
runCommand(syncDisplayCommand);
}
/**
* Signal to the show that the current segment is done. This causes
* the segment to execute its "next" command block, which in most
* shows should contain a command to move to a different segment.
* <p>
* This is equivalent to the <code>segment_done</code> GRIN command.
**/
public void segmentDone() {
if (segmentDoneCommand == null) {
GrinXHelper cmd = new GrinXHelper(this);
cmd.setCommandNumber(GrinXHelper.SEGMENT_DONE);
segmentDoneCommand = cmd;
}
runCommand(segmentDoneCommand);
}
/**
* Run the given command when we advance to the next frame.
* If the show has been destroyed, this has no effect.
* <p>
* This can be called from any thread; it does not take out the show
* lock or any other global locks. If the show has been destroyed,
* calling this method has no effect. It's OK to call this before
* the show has been initialized.
*
* @see #runCommands(Command[])
**/
public void runCommand(Command cmd) {
pendingCommands.add(cmd);
}
/**
* Run the given commands when we advance to the next frame.
* If the show has been destroyed, this has no effect.
* <p>
* This can be called from any thread; it does not take out the show
* lock or any other global locks. If the show has been destroyed,
* calling this method has no effect. It's OK to call this before
* the show has been initialized.
*
* @see #runCommand(Command)
**/
public void runCommands(Command[] cmds) {
if (cmds == null || cmds.length == 0) {
return;
}
synchronized(pendingCommands) {
for (int i = 0; i < cmds.length; i++) {
pendingCommands.add(cmds[i]);
}
}
}
/**
* {@inheritDoc}
* <p>
* The animation framework calls this method just before calling
* nextFrame() if
* the animation loop is caught up. From time to time, pending commands
* will be deferred until animation has caught up - this is done by the
* sync_display command. GRIN knows we've
* caught up when we paint a frame, but calling this method can let
* it know one frame earlier.
*
* @see #nextFrame()
**/
public synchronized void setCaughtUp() {
deferringPendingCommands = false;
}
/**
* {@inheritDoc}
*
* @throws InterruptedException if the show has been destroyed
*
* @see #setCaughtUp()
**/
public synchronized void nextFrame() throws InterruptedException {
if (currentSegment != null) {
showTop.nextFrameForActiveFeatures();
currentSegment.nextFrameForRCHandlers();
}
director.notifyNextFrame();
// It's in Director's contract that this be called with the
// show lock held.
}
//
// Called from Director.notifyNextFrame()
//
synchronized void runPendingCommands() {
while (!deferringPendingCommands && !pendingCommands.isEmpty()) {
Command c = (Command) pendingCommands.remove();
if (c != null) {
c.execute(this); // Can call deferNextCommands()
}
}
}
/**
* This method, which should ONLY be called from the execute() method
* of a command, suspends processing of further queued commands until
* the display of the show has caught up with the screen. This is done
* from the sync_display command, but can be done from any other command
* too. It causes an effect like Toolkit.sync() or the old X-Windows
* XSync() command, whereby the screen is guaranteed to be up-to-date
* before further commands are processed.
* <p>
* Doing this can be useful, for example, just before an operation that
* is time-consuming and CPU-bound on some players, like JMF selection.
*
* @see #syncDisplay()
**/
public synchronized void deferNextCommands() {
deferringPendingCommands = true;
}
/**
* This is called from ActivateSegmentCommand, and should not be
* called from anywhere else.
**/
public synchronized void doActivateSegment(Segment newS) {
// We know the lock is being held, and a command is being executed
Segment old = currentSegment;
synchronized(pendingCommands) {
currentSegment = newS;
// Needed for RC key processing, since we don't want to
// take out the show lock when receiving an RC event.
}
currentSegment.activate(old);
director.notifySegmentActivated(newS, old);
}
/**
* This is called from GrinXHelper(SEGMENT_DONE), and should not be
* called from anywhere else.
**/
// We know the lock is being held, and a command is being executed
public void doSegmentDone() {
currentSegment.doSegmentDone();
}
/**
* Get the current segment. The caller may wish to
* synchronize on the show when using this, so that the
* current segment doesn't change right after the call.
**/
public synchronized Segment getCurrentSegment() {
return currentSegment;
}
/**
* {@inheritDoc}
**/
public synchronized void addDisplayAreas(RenderContext context)
throws InterruptedException
{
if (currentSegment != null) {
int old = context.setTarget(defaultDrawTarget);
showTop.addDisplayAreas(context);
context.setTarget(old);
}
}
/**
* {@inheritDoc}
* <p>
* Paint the current state of the enhancement. This should be
* called by the xlet, usually via the animation framework.
**/
public synchronized void paintFrame(Graphics2D gr)
throws InterruptedException
{
if (Thread.interrupted() || destroyed) {
throw new InterruptedException();
}
if (currentSegment != null) {
showTop.paintFrame(gr);
}
}
/**
* {@inheritDoc}
**/
public void paintDone() {
}
/**
* Called by the xlet when a key press is received.
* <p>
* A key pressis queued and true is returned only if the current
* segment uses that key press It is possible that the show will have
* a different current segment by the time the key press is processed, so
* there's some chance that a key press won't be queued, even if it is of
* interest to the state the show's about to be in. This should almost
* always be harmless, but if you wish to capture all key presses in your
* show, you can populate the needed segments with a key_pressed
* rc_handler with an empty body that captures all keys.
*
* @return true If the key press is enqueued, and thus is expected to
* be used.
**/
public boolean handleKeyPressed(int vkCode) {
synchronized(pendingCommands) {
if (currentSegment == null) {
return false;
}
RCKeyEvent re = RCKeyEvent.getKeyByEventCode(vkCode);
if (re == null) {
return false;
}
if ((currentSegment.rcPressedInterest & re.getBitMask()) == 0) {
return false;
}
pendingCommands.add(re);
}
return true;
}
/**
* This is an implementation method, called by RCKeyEvent
**/
public synchronized void
internalHandleKeyPressed(RCKeyEvent re, Show caller) {
if (currentSegment != null) {
currentSegment.handleKeyPressed(re, caller);
}
}
/**
* Called by the xlet when a key release is received. Note that not
* all devices generate a key released.
* <p>
* A key release is queued and true is returned only if the current
* segment uses that key release. It is possible that the show will have
* a different current segment by the time the key release is processed, so
* there's some chance that a key release won't be queued, even if it is of
* interest to the state the show's about to be in. This should almost
* always be harmless, but if you wish to capture all key releases in your
* show, you can populate the needed segments with a key_released
* rc_handler with an empty body that captures all keys.
*
* @return true If the key release is enqueued, and thus is expected to
* be used.
**/
public boolean handleKeyReleased(int vkCode) {
synchronized(pendingCommands) {
if (currentSegment == null) {
return false;
}
RCKeyEvent re = RCKeyEvent.getKeyByEventCode(vkCode);
if (re == null) {
return false;
}
if ((currentSegment.rcReleasedInterest & re.getBitMask()) == 0) {
return false;
}
pendingCommands.add(re.getKeyReleased());
}
return true;
}
/**
* This is an implementation method, called by RCKeyEvent
**/
public synchronized void
internalHandleKeyReleased(RCKeyEvent re, Show caller) {
if (currentSegment != null) {
currentSegment.handleKeyReleased(re, caller);
}
}
/**
* Called by the xlet when a key typed event is received, or generated
* (e.g. from a virtual keyboard). Note that not
* all devices generate a key typed. In order to extend GRIN to
* support key typed events, a subclass of RCKeyEvent will be required;
* see the protected RCKeyEvent constructor for details.
* <p>
* A key typed event is queued and true is returned only if the current
* segment uses that key typed event.
*
* @return true If the key typed is enqueued, and thus is expected to
* be used.
**/
public boolean handleKeyTyped(RCKeyEvent typed) {
synchronized(pendingCommands) {
if ((currentSegment.keyTypedInterest & typed.getBitMask()) == 0) {
return false;
}
pendingCommands.add(typed);
}
return true;
}
/**
* Called by an xlet when a key typed event is received, or generated
* (e.g. from a virtual keyboard). Note that not all devices generate
* a key typed.
* <p>
* This director-based event delivery mechanism is implemented in the
* core GRIN library, e.g. it is called by GrinXlet. The mechanism
* exposed through handleKeyTyped() was not. Frameworks extending GRIN
* that call handleKeyTyped() should also call the present method, so
* that the director-based key typed event delivery mechanism will work.
**/
public void handleKeyTypedToDirector(char key) {
if (director.wantsKeyTyped()) {
synchronized(pendingCommands) {
GrinXHelper h = new GrinXHelper(this);
h.setCommandNumber(GrinXHelper.HANDLE_KEY_TYPED_FOR_DIRECTOR);
h.setCommandObject(new Character(key));
pendingCommands.add(h);
}
}
}
/**
* Called by GrinXHelper for a HANDLE_KEY_TYPED
*/
void internalHandleKeyTypedToDirector(char key) {
director.notifyKeyTyped(key);
}
/**
* This method is to be called by a subclass of RCKeyEvent that is created
* by someone extending GRIN to support key typed events.
**/
public synchronized void
internalHandleKeyTyped(RCKeyEvent re, Show caller) {
if (currentSegment != null) {
currentSegment.handleKeyTyped(re, caller);
}
}
/**
* Called by the xlet when the mouse moves. This should be called
* when a mouse moved event or a mouse dragged event is received.
* <p>
* Mouse events are delivered in the animation thread, just like remote
* control keypresses, except in the "bookmenu" demo xlet.
**/
/**
* Called by the xlet when the mouse is moved.
* <p>
* In Dec. 2011, this method was changed to make it consistent with the
* way remote control keypresses are handled. Now, the Show checks
* if the current segment is interested in the mouse event, by consulting
* its handlers. This happens in the AWT event delivery thread. If it
* is interested, the event is queued on the command list, for eventual
* processing on the animation thread. Note that it is possible that
* the show's state might change between computation of interest, and
* eventual delivery.
* <p>
* Previously, the re-dispatch was handled at the GrinXlet level, and
* mouse events were not "consumed" at all.
* <p>
* For code-based mouse handling, the Director event delivery mechanism
* might be more appropriate. There, mouse events are not consumed; it is
* left to application code to coordinate event usage among different
* shows.
*
* @param consumed true if the event was consumed by a show before us,
* and thus should only be delivered to the director.
*
* @return true If the mouse move is enqueued for an RC handler, and
* thus is expected to be used.
*
* @see #handleMousePressed(int, int, boolean)
* @see #handleKeyPressed(int)
* @see Director#notifyMouseMoved(int, int)
**/
public boolean handleMouseMoved(int x, int y, boolean consumed) {
boolean wants = !consumed && wantsMouseEvent(x, y);
GrinXHelper event = new GrinXHelper(this);
if (wants) {
event.setCommandNumber(GrinXHelper.MOUSE_MOVE);
} else {
event.setCommandNumber(GrinXHelper.MOUSE_MOVE_DIRECTOR_ONLY);
}
event.setCommandObject(new Point(x, y));
pendingCommands.add(event);
return wants;
}
synchronized void internalHandleMouseMoved(int x, int y) {
Cursor c;
if (currentSegment == null) {
c = Cursor.getDefaultCursor();
} else {
currentSegment.handleMouse(x, y, false);
c = Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
}
if (component != null && c != component.getCursor()) {
component.setCursor(c);
}
}
void directorHandleMouseMoved(int x, int y) {
director.notifyMouseMoved(x, y);
}
/**
* Called by the xlet when the mouse is pressed.
* <p>
* In Dec. 2011, this method was changed to make it consistent with the
* way remote control keypresses are handled. Now, the Show checks
* if the current segment is interested in the mouse event, by consulting
* its handlers. This happens in the AWT event delivery thread. If it
* is interested, the event is queued on the command list, for eventual
* processing on the animation thread. Note that it is possible that
* the show's state might change between computation of interest, and
* eventual delivery.
* <p>
* Previously, the re-dispatch was handled at the GrinXlet level, and
* mouse events were not "consumed" at all.
* <p>
* For code-based mouse handling, the Director event delivery mechanism
* might be more appropriate. There, mouse events are not consumed; it is
* left to application code to coordinate event usage among different
* shows.
*
* @param consumed true if the event was consumed by a show before us,
* and thus should only be delivered to the director.
*
* @return true If the mouse move is enqueued for an RC handler, and
* thus is expected to be used.
*
* @see #handleMouseMoved(int, int, boolean)
* @see #handleKeyPressed(int)
* @see Director#notifyMousePressed(int, int)
**/
public boolean handleMousePressed(int x, int y, boolean consumed) {
boolean wants = !consumed && wantsMouseEvent(x, y);
GrinXHelper event = new GrinXHelper(this);
if (wants) {
event.setCommandNumber(GrinXHelper.MOUSE_PRESS);
} else {
event.setCommandNumber(GrinXHelper.MOUSE_PRESS_DIRECTOR_ONLY);
}
event.setCommandObject(new Point(x, y));
pendingCommands.add(event);
return wants;
}
synchronized void internalHandleMousePressed(int x, int y) {
if (currentSegment != null) {
currentSegment.handleMouse(x, y, true);
}
}
void directorHandleMousePressed(int x, int y) {
director.notifyMousePressed(x, y);
}
//
// Is a mouse event is wanted by the show in its current state?
//
private synchronized boolean wantsMouseEvent(int x, int y) {
if (currentSegment != null) {
Rectangle[] rects = currentSegment.getMouseRects();
for (int i = 0; i < rects.length; i++) {
if (rects[i].contains(x, y)) {
return true;
}
}
}
return false;
}
/**
* Scale a value by a scale factor in mills. This is equivalent to
* <pre>
* (value * mills + 500) / 1000
* </pre>
* No function is provided to recover the original value from the
* scaled value (and such a function would suffer from loss of
* precision). In a scaled show, we recommend only setting
* translation values, and never getting them.
*
* @see #getXScale()
* @see #getYScale()
**/
public static int scale(int value, int mills) {
return (value * mills + 500) / 1000;
}
/**
* Get the x scale factor, in mills. To scale, use scale(int, int)
*
* @see #scale(int, int)
**/
public int getXScale() {
return xScale;
}
/**
* Get the y scale factor, in mills. To scale, use scale(int, int)
*
* @see #scale(int, int)
**/
public int getYScale() {
return yScale;
}
/**
* Get the x offset that this show was built with. This might be useful
* in directors designed to work with scaled shows, but usually they
* act relative to the fixed coordinates within the show that will
* have already been adjusted.
**/
public int getXOffset() {
return xOffset;
}
/**
* Get the y offset that this show was built with. This might be useful
* in directors designed to work with scaled shows, but usually they
* act relative to the fixed coordinates within the show that will
* have already been adjusted.
**/
public int getYOffset() {
return yOffset;
}
}
| bsd-3-clause |
vivo-project/VIVO | selenium/src/test/java/org/vivoweb/vivo/selenium/tests/CreateLocation.java | 4116 | package org.vivoweb.vivo.selenium.tests;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import static org.vivoweb.vivo.selenium.VIVOAppTester.*;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CreateLocation {
@BeforeClass
public static void setUp() {
startTests();
vivoLogIn("testAdmin@cornell.edu", "Password");
}
@AfterClass
public static void tearDown() {
vivoLogOut();
endTests();
}
@Test
public void createLocation() {
clickAndWait(By.linkText("Site Admin"));
assertTitle("VIVO Site Administration");
verifyTextPresent("Data Input");
selectByLabel(By.id("VClassURI"), "Building (vivo)");
clickAndWait(By.xpath("//input[@value='Add individual of this class']"));
assertTitle("Edit");
verifyTextPresent("Create a new Building");
clickAndWait(By.linkText("Cancel"));
assertTitle("VIVO Site Administration");
selectByLabel(By.id("VClassURI"), "Building (vivo)");
clickAndWait(By.xpath("//input[@value='Add individual of this class']"));
assertTitle("Edit");
verifyTextPresent("Create a new Building");
clickAndWait(By.id("submit"));
assertTitle("Edit");
verifyTextPresent("Please enter a value in the Name field.");
type(By.id("label"), "Jane Memorial Building");
clickAndWait(By.id("submit"));
assertTitle("Jane Memorial Building");
clickAndWait(By.cssSelector("a.add-BFO_0000051 > img.add-individual"));
assertTitle("Edit");
verifyTextPresent("There are no entries in the system from which to select.");
clickAndWait(By.id("offerCreate"));
assertTitle("Edit");
verifyTextPresent("Create \"rooms\" entry for Jane Memorial Building");
type(By.id("label"), "Lab Admin Office");
clickAndWait(By.id("submit"));
assertTitle("Jane Memorial Building");
clickAndWait(By.cssSelector("a.add-BFO_0000050 > img.add-individual"));
assertTitle("Edit");
verifyTextPresent("If you don't find the appropriate entry on the selection list above:");
selectByLabel(By.id("typeOfNew"), "Geographic Location (vivo)");
clickAndWait(By.id("offerCreate"));
assertTitle("Edit");
type(By.id("label"), "Primate Quad");
clickAndWait(By.id("submit"));
assertTitle("Jane Memorial Building");
clickAndWait(By.cssSelector("a.add-RO_0001015 > img.add-individual"));
assertTitle("Edit");
verifyTextPresent("If you don't find the appropriate entry on the selection list above:");
clickAndWait(By.id("submit"));
assertTitle("Jane Memorial Building");
clickAndWait(By.xpath("(//img[@alt='add'])[3]"));
assertTitle("Edit");
selectByLabel(By.id("objectVar"), "Primate Heart Health (Service)");
clickAndWait(By.id("submit"));
assertTitle("Jane Memorial Building");
clickAndWait(By.xpath("(//h3[@id='RO_0001015']/a)[3]"));
assertTitle("Edit");
selectByLabel(By.id("objectVar"), "Primate University of America (University)");
clickAndWait(By.id("submit"));
assertTitle("Jane Memorial Building");
clickAndWait(By.xpath("(//img[@alt='add'])[5]"));
assertTitle("Edit");
selectByLabel(By.id("objectVar"), "Primate Health Check (Event)");
clickAndWait(By.id("submit"));
assertTitle("Jane Memorial Building");
verifyElementPresent(By.linkText("Portable Primate Habitat"));
verifyElementPresent(By.linkText("Primate Heart Health"));
verifyElementPresent(By.linkText("Primate University of America"));
verifyElementPresent(By.linkText("Primate Health Check"));
verifyElementPresent(By.linkText("Lab Admin Office"));
verifyElementPresent(By.linkText("Primate Quad"));
}
}
| bsd-3-clause |
exponent/exponent | android/versioned-abis/expoview-abi40_0_0/src/main/java/abi40_0_0/host/exp/exponent/modules/api/components/datetimepicker/ReflectionHelper.java | 846 | package abi40_0_0.host.exp.exponent.modules.api.components.datetimepicker;
import androidx.annotation.Nullable;
import java.lang.reflect.Field;
public class ReflectionHelper {
@Nullable
public static Field findField(Class objectClass, Class fieldClass, String expectedName) {
try {
Field field = objectClass.getDeclaredField(expectedName);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
// ignore
}
// search for it if it wasn't found under the expected ivar name
for (Field searchField : objectClass.getDeclaredFields()) {
if (searchField.getType() == fieldClass) {
searchField.setAccessible(true);
return searchField;
}
}
return null;
}
}
| bsd-3-clause |
mikekab/RESOLVE | src/main/java/edu/clemson/cs/r2jt/absyn/ConceptBodyModuleDec.java | 8156 | /**
* ConceptBodyModuleDec.java
* ---------------------------------
* Copyright (c) 2016
* RESOLVE Software Research Group
* School of Computing
* Clemson University
* All rights reserved.
* ---------------------------------
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package edu.clemson.cs.r2jt.absyn;
import edu.clemson.cs.r2jt.collections.Iterator;
import edu.clemson.cs.r2jt.collections.List;
import edu.clemson.cs.r2jt.data.PosSymbol;
import edu.clemson.cs.r2jt.data.Symbol;
public class ConceptBodyModuleDec extends AbstractParameterizedModuleDec {
// ===========================================================
// Variables
// ===========================================================
/** The name member. */
private PosSymbol name;
/** The performance profile name member. */
private PosSymbol profileName;
/** The conceptName member. */
private PosSymbol conceptName;
/** The enhancementNames member. */
private List<PosSymbol> enhancementNames;
/** The requires member. */
private Exp requires;
/** The conventions member. */
private List<Exp> conventions;
/** The corrs member. */
private List<Exp> corrs;
/** The facilityInit member. */
private InitItem facilityInit;
/** The facilityFinal member. */
private FinalItem facilityFinal;
/** The decs member. */
private List<Dec> decs;
// ===========================================================
// Constructors
// ===========================================================
public ConceptBodyModuleDec() {};
public ConceptBodyModuleDec(PosSymbol name, PosSymbol profileName,
List<ModuleParameterDec> parameters, PosSymbol conceptName,
List<PosSymbol> enhancementNames, List<UsesItem> usesItems,
Exp requires, List<Exp> conventions, List<Exp> corrs,
InitItem facilityInit, FinalItem facilityFinal, List<Dec> decs) {
this.name = name;
this.profileName = profileName;
this.parameters = parameters;
this.conceptName = conceptName;
this.enhancementNames = enhancementNames;
this.usesItems = usesItems;
this.requires = requires;
this.conventions = conventions;
this.corrs = corrs;
this.facilityInit = facilityInit;
this.facilityFinal = facilityFinal;
this.decs = decs;
}
// ===========================================================
// Accessor Methods
// ===========================================================
// -----------------------------------------------------------
// Get Methods
// -----------------------------------------------------------
/** Returns the value of the name variable. */
public PosSymbol getName() {
return name;
}
/** Returns the value of the profileName variable. */
public PosSymbol getProfileName() {
return profileName;
}
/** Returns the value of the conceptName variable. */
public PosSymbol getConceptName() {
return conceptName;
}
/** Returns the value of the enhancementNames variable. */
public List<PosSymbol> getEnhancementNames() {
return enhancementNames;
}
/** Returns the value of the requires variable. */
public Exp getRequires() {
return requires;
}
/** Returns the value of the conventions variable. */
public List<Exp> getConventions() {
return conventions;
}
/** Returns the value of the corrs variable. */
public List<Exp> getCorrs() {
return corrs;
}
/** Returns the value of the facilityInit variable. */
public InitItem getFacilityInit() {
return facilityInit;
}
/** Returns the value of the facilityFinal variable. */
public FinalItem getFacilityFinal() {
return facilityFinal;
}
/** Returns the value of the decs variable. */
public List<Dec> getDecs() {
return decs;
}
/** Returns a list of procedures in this realization. */
public List<Symbol> getLocalProcedureNames() {
List<Symbol> retval = new List<Symbol>();
Iterator<Dec> it = decs.iterator();
while (it.hasNext()) {
Dec d = it.next();
if (d instanceof ProcedureDec) {
retval.add(d.getName().getSymbol());
}
}
return retval;
}
// -----------------------------------------------------------
// Set Methods
// -----------------------------------------------------------
/** Sets the name variable to the specified value. */
public void setName(PosSymbol name) {
this.name = name;
}
/** Sets the profileName variable to the specified value. */
public void setProfileName(PosSymbol name) {
this.profileName = name;
}
/** Sets the conceptName variable to the specified value. */
public void setConceptName(PosSymbol conceptName) {
this.conceptName = conceptName;
}
/** Sets the enhancementNames variable to the specified value. */
public void setEnhancementNames(List<PosSymbol> enhancementNames) {
this.enhancementNames = enhancementNames;
}
/** Sets the requires variable to the specified value. */
public void setRequires(Exp requires) {
this.requires = requires;
}
/** Sets the conventions variable to the specified value. */
public void setConventions(List<Exp> conventions) {
this.conventions = conventions;
}
/** Sets the corrs variable to the specified value. */
public void setCorrs(List<Exp> corrs) {
this.corrs = corrs;
}
/** Sets the facilityInit variable to the specified value. */
public void setFacilityInit(InitItem facilityInit) {
this.facilityInit = facilityInit;
}
/** Sets the facilityFinal variable to the specified value. */
public void setFacilityFinal(FinalItem facilityFinal) {
this.facilityFinal = facilityFinal;
}
/** Sets the decs variable to the specified value. */
public void setDecs(List<Dec> decs) {
this.decs = decs;
}
// ===========================================================
// Public Methods
// ===========================================================
/** Accepts a ResolveConceptualVisitor. */
public void accept(ResolveConceptualVisitor v) {
v.visitConceptBodyModuleDec(this);
}
/** Returns a formatted text string of this class. */
public String asString(int indent, int increment) {
StringBuffer sb = new StringBuffer();
printSpace(indent, sb);
sb.append("ConceptBodyModuleDec\n");
if (name != null) {
sb.append(name.asString(indent + increment, increment));
}
if (parameters != null) {
sb.append(parameters.asString(indent + increment, increment));
}
if (conceptName != null) {
sb.append(conceptName.asString(indent + increment, increment));
}
if (enhancementNames != null) {
sb.append(enhancementNames.asString(indent + increment, increment));
}
if (usesItems != null) {
sb.append(usesItems.asString(indent + increment, increment));
}
if (requires != null) {
sb.append(requires.asString(indent + increment, increment));
}
if (conventions != null) {
sb.append(conventions.asString(indent + increment, increment));
}
if (corrs != null) {
sb.append(corrs.asString(indent + increment, increment));
}
if (facilityInit != null) {
sb.append(facilityInit.asString(indent + increment, increment));
}
if (facilityFinal != null) {
sb.append(facilityFinal.asString(indent + increment, increment));
}
if (decs != null) {
sb.append(decs.asString(indent + increment, increment));
}
return sb.toString();
}
}
| bsd-3-clause |
the-AjK/P3-P2P | server/ServerModel.java | 23197 | /****************************************************************************************\
|
| Project: P3-P2P
| Author: Alberto Garbui - Mat.: 561226
|
| File: ServerModel.java
| Description: componente model del pattern MVC
| Package: server
| Version: 0.1 - creazione struttura scheletro
| 1.0 - aggiunti campi dati e relativi metodi set/get
| 1.1 - aggiunto logo iniziale
|
\****************************************************************************************/
package server;
import java.util.Vector;
import java.awt.Color;
import client.IClient;
import common.DeviceClient;
import common.DeviceServer;
import common.Resource;
public class ServerModel extends java.util.Observable
{
//campi dati
private DeviceServer me; //contiene nome del server e riferimento
private Vector<DeviceClient> clients; //clients connessi
private Vector<DeviceServer> servers; //server connessi
private Vector<String> log; //log di sistema
private Color coloreLog; //colore testo della casella log
private String animationIcon; //piccola icona di animazione per visualizzare lo stato del client
private Vector<ResearchRequest> researchRequest; //lista di richieste di ricerca
//lock
private Object log_lock;
private Object clients_lock;
private Object servers_lock;
private Object requests_lock;
/****************************************************************************************\
| private class ResearchRequest
| description: classe interna per gestire la coda di richieste
\****************************************************************************************/
private class ResearchRequest
{
public DeviceClient client;
public Resource risorsa;
public Vector<DeviceClient> clientList = new Vector<DeviceClient>();
public int numberOfRequests;
public ResearchRequest(DeviceClient _client, Resource _risorsa)
{
client = _client;
risorsa = _risorsa;
numberOfRequests = 0;
Vector<DeviceClient> clientList = new Vector<DeviceClient>();
}
}
/****************************************************************************************\
| public ServerModel()
| description: costruttore del model
\****************************************************************************************/
public ServerModel()
{
//inizializzo i campi dati
me = new DeviceServer("",null); //creo me stesso :)
clients = new Vector<DeviceClient>();
servers = new Vector<DeviceServer>();
researchRequest = new Vector<ResearchRequest>();
log = new Vector<String>();
log_lock = new Object();
clients_lock = new Object();
servers_lock = new Object();
requests_lock = new Object();
log.add(" ______ ______ ______ ______ ______ ");
log.add(" | __ \\|__ | ______ | __ \\|__ || __ \\");
log.add(" | __/|__ ||______|| __/| __|| __/");
log.add(" |___| |______| |___| |______||___| ");
log.add(" P3-P2P Server (C) JK ");
log.add("--------------------------------------------------");
animationIcon = "P2P";
}
/****************************************************************************************\
| public void viewRefresh()
| description: notifica la parte view in modalita' "model-pull"
\****************************************************************************************/
private void viewRefresh()
{
setChanged();
notifyObservers();
}
/****************************************************************************************\
| public String getAnimIcon()
| description: restituisce l'icona
\****************************************************************************************/
public String getAnimIcon(){return animationIcon;}
/****************************************************************************************\
| public void setAnimIcon(String _s)
| description: setta l'icona
\****************************************************************************************/
public void setAnimIcon(String _s)
{
animationIcon = _s;
viewRefresh();
}
/****************************************************************************************\
| public DeviceServer me()
| description: restituisce me stesso
\****************************************************************************************/
public DeviceServer me(){return me;}
/****************************************************************************************\
| public String getServerName()
| description: restituisce il nome del server
\****************************************************************************************/
public String getServerName(){return me.getName();}
/****************************************************************************************\
| public IServer getServerRef()
| description: restituisce il riferimento del server
\****************************************************************************************/
public IServer getServerRef(){return me.getRef();}
/****************************************************************************************\
| public void setServerRef(IServer _ref)
| description: setta il riferimento del server
\****************************************************************************************/
public void setServerRef(IServer _ref){me.setRef(_ref);}
/****************************************************************************************\
| public int getNclients()
| description: restituisce il numero di client connessi al server
\****************************************************************************************/
public int getNclients()
{
synchronized(clients_lock)
{
return clients.size();
}
}
/****************************************************************************************\
| public int getNservers()
| description: restituisce il numero di server connessi
\****************************************************************************************/
public int getNservers()
{
synchronized(servers_lock)
{
return servers.size();
}
}
/****************************************************************************************\
| public Vector<DeviceServer> getServerList()
| description: restituisce la lista dei server connessi
\****************************************************************************************/
public Vector<DeviceServer> getServerList(){return servers;}
/****************************************************************************************\
| public Vector<DeviceClient> getClientList()
| description: restituisce la lista dei clients connessi al server
\****************************************************************************************/
public Vector<DeviceClient> getClientList(){return clients;}
/****************************************************************************************\
| public void incrementNumberOfRequests(DeviceClient _client, Resource _risorsa)
| description: incrementa il numero di richieste
\****************************************************************************************/
public void incrementNumberOfRequests(DeviceClient _client, Resource _risorsa)
{
synchronized(requests_lock)
{
for(int i=0; i<researchRequest.size(); i++)
{
if(researchRequest.get(i).client.getName().equals(_client.getName()) &&
researchRequest.get(i).risorsa.getName().equals(_risorsa.getName()) &&
researchRequest.get(i).risorsa.getNparts() == _risorsa.getNparts()
){
researchRequest.get(i).numberOfRequests++;
break;
}
}
}
}
/****************************************************************************************\
| public void decrementNumberOfRequests(DeviceClient _client, Resource _risorsa)
| description: decrementa il numero di richieste
\****************************************************************************************/
public void decrementNumberOfRequests(DeviceClient _client, Resource _risorsa)
{
synchronized(requests_lock)
{
for(int i=0; i<researchRequest.size(); i++)
{
if(researchRequest.get(i).client.getName().equals(_client.getName()) &&
researchRequest.get(i).risorsa.getName().equals(_risorsa.getName()) &&
researchRequest.get(i).risorsa.getNparts() == _risorsa.getNparts()
){
researchRequest.get(i).numberOfRequests--;
break;
}
}
}
}
/****************************************************************************************\
| public int getNumberOfRequests(DeviceClient _client, Resource _risorsa)
| description: restituisce il numero di richieste
\****************************************************************************************/
public int getNumberOfRequests(DeviceClient _client, Resource _risorsa)
{
int result = 0;
synchronized(requests_lock)
{
for(int i=0; i<researchRequest.size(); i++)
{
if(researchRequest.get(i).client.getName().equals(_client.getName()) &&
researchRequest.get(i).risorsa.getName().equals(_risorsa.getName()) &&
researchRequest.get(i).risorsa.getNparts() == _risorsa.getNparts()
){
result = researchRequest.get(i).numberOfRequests;
break;
}
}
}
return result;
}
/****************************************************************************************\
| public void addResearchRequest(DeviceClient _client, Resource _risorsa)
| description: aggiunge una richiesta in coda richieste risorse
\****************************************************************************************/
public void addResearchRequest(DeviceClient _client, Resource _risorsa)
{
synchronized(requests_lock)
{
int count = 0;
for(int i=0; i<researchRequest.size(); i++)
{
if(researchRequest.get(i).client.getName().equals(_client.getName()) &&
researchRequest.get(i).risorsa.getName().equals(_risorsa.getName()) &&
researchRequest.get(i).risorsa.getNparts() == _risorsa.getNparts()
){
count++;
}
}
if(count == 0)
researchRequest.add(new ResearchRequest(_client,_risorsa));
}
}
/****************************************************************************************\
| public void removeResearchRequest(DeviceClient _client, Resource _risorsa)
| description: rimuove una richiesta dalla lista
\****************************************************************************************/
public void removeResearchRequest(DeviceClient _client, Resource _risorsa)
{
synchronized(requests_lock)
{
for(int i=0; i<researchRequest.size(); i++)
{
if(researchRequest.get(i).client.getName().equals(_client.getName()) &&
researchRequest.get(i).risorsa.getName().equals(_risorsa.getName()) &&
researchRequest.get(i).risorsa.getNparts() == _risorsa.getNparts()
){
researchRequest.get(i).clientList.remove(i);
break;
}
}
}
}
/****************************************************************************************\
| public Vector<DeviceClient> getResearchClientList(DeviceClient _client, Resource _risorsa)
| description: restituisce la lista dei client che possiedono una determinata risorsa
\****************************************************************************************/
public Vector<DeviceClient> getResearchClientList(DeviceClient _client, Resource _risorsa)
{
Vector<DeviceClient> clients = new Vector<DeviceClient>();
synchronized(requests_lock)
{
for(int i=0; i<researchRequest.size(); i++)
{
if(researchRequest.get(i).client.getName().equals(_client.getName()) &&
researchRequest.get(i).risorsa.getName().equals(_risorsa.getName()) &&
researchRequest.get(i).risorsa.getNparts() == _risorsa.getNparts()
){
clients = researchRequest.get(i).clientList;
break;
}
}
}
return clients;
}
/****************************************************************************************\
| public void addResearchClientList(DeviceClient _client, Resource _risorsa, Vector<DeviceClient> _clients2add)
| description: restituisce la lista dei client che possiedono una determinata risorsa
\****************************************************************************************/
public void addResearchClientList(DeviceClient _client, Resource _risorsa, Vector<DeviceClient> _clients2add)
{
synchronized(requests_lock)
{
for(int i=0; i<researchRequest.size(); i++)
{
if(researchRequest.get(i).client.getName().equals(_client.getName()) &&
researchRequest.get(i).risorsa.getName().equals(_risorsa.getName()) &&
researchRequest.get(i).risorsa.getNparts() == _risorsa.getNparts()
){
for(int j=0; j<_clients2add.size(); j++)
{
Vector<DeviceClient> lista = researchRequest.get(i).clientList;
int count = 0;
for(int k=0; k<lista.size(); k++)
{
if(_clients2add.get(j).getName().equals(lista.get(k).getName()))
{
count++;
}
}
if(count == 0)
researchRequest.get(i).clientList.add(_clients2add.get(j));
}
break;
}
}
}
}
/****************************************************************************************\
| public void removeServer(String _server2remove)
| description: rimuove il server specificato dalla lista di servers
\****************************************************************************************/
public void removeServer(String _server2remove)
{
synchronized(servers_lock)
{
for(int i=0; i<servers.size(); i++)
{
if(servers.get(i).getName().equals(_server2remove))
{
servers.remove(i);
break;
}
}
}
viewRefresh();
}
/****************************************************************************************\
| public void removeClient(String _client2remove)
| description: rimuove il client specificato dalla lista di clients
\****************************************************************************************/
public void removeClient(String _client2remove)
{
synchronized(clients_lock)
{
for(int i=0; i<clients.size(); i++)
{
if(clients.get(i).getName().equals(_client2remove))
{
clients.remove(i);
break;
}
}
}
viewRefresh();
}
/****************************************************************************************\
| public Vector<DeviceClient> getClientsOwnResourceList(Resource _risorsa)
| description: restituisce una lista di client che possiedono una determinata risorsa
\****************************************************************************************/
public Vector<DeviceClient> getClientsOwnResourceList(Resource _risorsa)
{
Vector<DeviceClient> res = new Vector<DeviceClient>();
Resource risorsa;
DeviceClient client;
synchronized(clients_lock)
{
for(int i=0; i<clients.size(); i++) //scorro la lista di clients
{
client = clients.get(i);
for(int j=0; j<client.getNresource(); j++) //scorro la lista delle risorse
{
risorsa = client.getResource(j);
if(risorsa.getName().equals(_risorsa.getName()) &&
risorsa.getNparts() == _risorsa.getNparts() )
{
res.add(client); //aggiungo il client che possiede la risorsa
break;
}
}
}
}
return res;
}
/****************************************************************************************\
| public DeviceServer getServer(int _n)
| description: restituisce il DeviceServer specificato
\****************************************************************************************/
public DeviceServer getServer(int _n)
{
synchronized(servers_lock)
{
return servers.get(_n);
}
}
/****************************************************************************************\
| public boolean serverIsHere(String _serverName)
| description: restituisce true se il server specificato e' nella lista servers
\****************************************************************************************/
public boolean serverIsHere(String _serverName)
{
synchronized(servers_lock)
{
for(int i=0; i<servers.size(); i++)
{
if(servers.get(i).getName().equals(_serverName))return true;
}
}
return false;
}
/****************************************************************************************\
| public DeviceClient getClient(int _n)
| description: restituisce il DeviceClient specificato
\****************************************************************************************/
public DeviceClient getClient(int _n)
{
synchronized(clients_lock)
{
return clients.get(_n);
}
}
/****************************************************************************************\
| public boolean clientIsHere(String _clientName)
| description: restituisce true se il client specificato e' nella lista clients
\****************************************************************************************/
public boolean clientIsHere(String _clientName)
{
synchronized(clients_lock)
{
for(int i=0; i<clients.size(); i++)
{
if(clients.get(i).getName().equals(_clientName))return true;
}
}
return false;
}
/****************************************************************************************\
| public void setServerName(String _nome)
| description: setta il nome del server
\****************************************************************************************/
public void setServerName(String _nome)
{
me.setName(_nome);
viewRefresh();
}
/****************************************************************************************\
| private String vector2String(Vector<String> v)
| description: converte un vector di stringhe in un'unica stringa
\****************************************************************************************/
private String vector2String(Vector<String> v)
{
String res = "";
for(int i=0; i<v.size(); i++)
{
res = res + v.get(i) + "\n";
}
return res;
}
/****************************************************************************************\
| public String getClientsText()
| description: restituisce la lista di clients sottoforma di stringa per la GUI
\****************************************************************************************/
public String getClientsText()
{
String res = "";
synchronized(clients_lock)
{
for(int i=0; i<clients.size(); i++)
{
res = res + clients.get(i).getName() + " - [ R: {";
for(int j=0; j<clients.get(i).getNresource(); j++)
{
if(j!=0)res = res + ",";
res = res + clients.get(i).getResource(j).getName() + clients.get(i).getResource(j).getNparts();
}
res = res + "} ]\n";
}
}
return res;
}
/****************************************************************************************\
| public String getServersText()
| description: restituisce la lista di servers sottoforma di stringa per la GUI
\****************************************************************************************/
public String getServersText()
{
String res = "";
synchronized(servers_lock)
{
for(int i=0; i<servers.size(); i++)
{
res = res + servers.get(i).getName() + "\n";
}
}
return res;
}
/****************************************************************************************\
| public String getLogText()
| description: restituisce la lista dei log sottoforma di stringa per la GUI
\****************************************************************************************/
public String getLogText(){return vector2String(log);}
/****************************************************************************************\
| public void addServer(DeviceServer _server)
| description: aggiunge un server alla lista di servers
\****************************************************************************************/
public void addServer(DeviceServer _server)
{
synchronized(servers_lock)
{
if(!serverIsHere(_server.getName()))
servers.add(_server);
}
viewRefresh();
}
/****************************************************************************************\
| public void addClient(DeviceClient _client)
| description: aggiunge un client alla lista dei clients
\****************************************************************************************/
public void addClient(DeviceClient _client)
{
synchronized(clients_lock)
{
clients.add(_client);
}
viewRefresh();
}
/****************************************************************************************\
| public void addClientResourceList(String _nomeClient, Vector<Resource> _listaRisorse)
| description: aggiorna la lista risorse di un client
\****************************************************************************************/
public void addClientResourceList(String _nomeClient, Vector<Resource> _listaRisorse)
{
boolean trovato = false;
int i;
synchronized(clients_lock)
{
for(i=0; i<clients.size(); i++)
{
if(clients.get(i).getName().equals(_nomeClient))
{
trovato = true;
break;
}
}
if(trovato)
{
clients.get(i).setResourceList(_listaRisorse);
}
}
if(trovato)viewRefresh();
}
/****************************************************************************************\
| public int addLogText(String _logLine)
| description: aggiunge una riga di testo ai log e ritorna la posizione
\****************************************************************************************/
public int addLogText(String _logLine)
{
synchronized(log_lock)
{
log.add(_logLine);
}
viewRefresh();
return log.size() - 1;
}
/****************************************************************************************\
| public void addLogTextToLine(int pos, String _logText)
| description: aggiunge del testo nella riga dei log indicata
\****************************************************************************************/
public void addLogTextToLine(int pos, String _logText)
{
synchronized(log_lock)
{
log.setElementAt(log.get(pos) + _logText, pos);
}
viewRefresh();
}
/****************************************************************************************\
| public void setLogText(int pos, String _logLine)
| description: sovrascrive un log precedente nella posizione indicata
\****************************************************************************************/
public void setLogText(int pos, String _logLine)
{
synchronized(log_lock)
{
log.setElementAt(_logLine, pos);
}
viewRefresh();
}
/****************************************************************************************\
| public Color getLogColor()
| description: restituisce il colore del testo dei log
\****************************************************************************************/
public Color getLogColor(){return coloreLog;}
/****************************************************************************************\
| public Color setLogColor()
| description: setta il colore del testo dei log
\****************************************************************************************/
public void setLogColor(Color _color)
{
coloreLog = _color;
viewRefresh();
}
}//end class ServerModel()
| bsd-3-clause |
bruceMacLeod/motech-server-pillreminder-0.18 | modules/rules/api-bundle/src/main/java/org/motechproject/rules/osgi/Activator.java | 536 | package org.motechproject.rules.osgi;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private RuleBundleLoader ruleBundleLoader;
@Override
public void start(BundleContext context) {
ruleBundleLoader = new RuleBundleLoader(context, Bundle.STARTING, null);
ruleBundleLoader.open();
}
public void stop(BundleContext context) {
this.ruleBundleLoader.close();
}
}
| bsd-3-clause |
IAS-ZHAW/DistanceToolCore | src/ch/zhaw/ias/dito/GenerateTagMatrix.java | 4739 | /* released under bsd licence
* see LICENCE file or http://www.opensource.org/licenses/bsd-license.php for details
* Institute of Applied Simulation (ZHAW)
* Author Thomas Niederberger
*/
package ch.zhaw.ias.dito;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Pattern;
public class GenerateTagMatrix {
public static int MIN_COUNT = 3;
public static int PROJECT_ID = 14;
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String filename = "C:/Daten/atizo/tag-file-pro-" + PROJECT_ID + ".csv";
BufferedReader reader = new BufferedReader(new FileReader(filename));
Pattern pattern = Pattern.compile("[,]\\s*");
String line;
Map<String, Pair> tagList = new HashMap<String, Pair>();
List<List<Integer>> vectors = new ArrayList<List<Integer>>();
Map<Integer, List<String>> tagStopContainer = new HashMap<Integer, List<String>>();
// Project 128
tagStopContainer.put(128, new ArrayList<String>());
//Collections.addAll(tagStopContainer.get(128), "nicht", "zu", "mit", "fuer", "bade", "bad", "spiegel");
// Project 638
tagStopContainer.put(638, new ArrayList<String>());
Collections.addAll(tagStopContainer.get(638), "konfituere", "konfitüre", "konfi", "marmelade", "confiture");
// Project 804
tagStopContainer.put(804, new ArrayList<String>());
Collections.addAll(tagStopContainer.get(804), "mit", "fuer");
// Project 810
tagStopContainer.put(810, new ArrayList<String>());
tagStopContainer.put(14, new ArrayList<String>());
List<String> tagStopList = tagStopContainer.get(PROJECT_ID);
int lineCounter = 0;
int tagCounter = 0;
while ((line = reader.readLine()) != null) {
Scanner s = new Scanner(line);
s.useDelimiter(pattern);
int rowCounter = 0;
ArrayList<Integer> values = new ArrayList<Integer>();
while (s.hasNext()) {
String tag = s.next();
tag = standardsizeTag(tag, tagStopList);
//ignore tags from stop-list
if (tag.length() == 0) {
continue;
}
if (! tagList.containsKey(tag)) {
tagList.put(tag, new Pair(tagCounter++));
}
Pair p = tagList.get(tag);
p.count = p.count + 1;
values.add(p.index);
rowCounter++;
}
lineCounter++;
vectors.add(values);
}
filename = "C:/Daten/atizo/tag-file-out-pro-" + PROJECT_ID + ".csv";
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
int countedTags = 0;
//write headers
for (Iterator<String> it = tagList.keySet().iterator(); it.hasNext(); ) {
String key = it.next();
if (tagList.get(key).count < MIN_COUNT) {
continue;
}
System.out.println(key + ": " + tagList.get(key).count);
writer.write(key + ";");
countedTags++;
}
writer.newLine();
System.out.println("records: " + lineCounter);
System.out.println("tagCounter: " + tagCounter);
System.out.println("Tags with " + MIN_COUNT + " mentions at least: " + countedTags);
for (int i = 0; i < vectors.size(); i++) {
List<Integer> matrixLine = vectors.get(i);
for (Iterator<String> it = tagList.keySet().iterator(); it.hasNext(); ) {
//for (int j = 0; j < tagCounter; j++) {
String key = it.next();
if (tagList.get(key).count < MIN_COUNT) {
continue;
}
if (matrixLine.contains(tagList.get(key).index)) {
writer.write("1;");
} else {
writer.write("0;");
}
}
writer.newLine();
}
writer.close();
}
private static String standardsizeTag(String tag, List<String> tagStopList) {
/*String[][] replacements = {{"ß", "ä", "ö", "ü", "é", "è", "à"}, {"ss", "ae", "oe", "ue", "e", "e", "a"}};
for (int i = 0; i < replacements[0].length; i++) {
tag = tag.replace(replacements[0][i], replacements[1][i]);
}*/
for (int i = 0; i < tagStopList.size(); i++) {
tag = tag.replace(tagStopList.get(i), "");
}
return tag;
}
static class Pair {
int index = 0;
int count = 0;
public Pair(int index) {
this.index = index;
}
}
}
| bsd-3-clause |
shushiej/KinectVisualizerProject | modules/ui/src/main/java/com/illposed/osc/ui/OscUI.java | 45431 | /*
* Copyright (C) 2001-2014, C. Ramakrishnan / Illposed Software.
* All rights reserved.
*
* This code is licensed under the BSD 3-Clause license.
* See file LICENSE (or LICENSE.html) for more information
* .
*/
// this is the package we are in
package com.illposed.osc.ui;
import com.illposed.osc.OSCBundle;
import com.illposed.osc.OSCListener;
import com.illposed.osc.OSCMessage;
import com.illposed.osc.OSCPacket;
import com.illposed.osc.OSCPort;
import com.illposed.osc.OSCPortIn;
import com.illposed.osc.OSCPortOut;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* have added effectlisteners to components. Need to set name of buttons, and
* deal with the resulting messages in pd
*/
/**
* OscUI is a subClass of JPanel.
*
* @author Chandrasekhar Ramakrishnan
* @author JT
*/
public class OscUI extends JPanel {
// declare some variables
private JFrame parent;
private JTextField addressWidget;
private JLabel portWidget;
private JTextField textBox;
private JTextField textBox2;
private JTextField textBox3;
private JTextField textBox4 = new JTextField(String.valueOf(1000), 8);
private JLabel delayLabel;
public static final Color OSK_PINK = new Color(249, 197, 201);
public static final Color OSK_MEDPINK = new Color(253, 235, 236);
public static final Color OSK_PALEPINK = new Color(253, 235, 236);
public static final Color OSK_PALEGREY = new Color(232, 233, 232);
public static final Color OSK_MEDGREY = new Color(197, 201, 202);
public static final Color OSK_DARKGREY = new Color(109, 110, 115);
public static final Color OSK_RED = new Color(235, 89, 114);
public static final Color OSK_BLUE = new Color(46, 151, 216);
public enum EFFECT {LUMA, BLUR, FRAME, REFRACT, KALEI, CUBISM, OSKWAVE, EMPTY };
// fonts
public static final Font font11 = new Font("Helvetica Neue", Font.PLAIN, 11);
public static final Font font11b = new Font("Helvetica Neue", Font.BOLD, 11);
public static final Font font16 = new Font("Helvetica Neue", Font.PLAIN, 16);
public static final Font font16b = new Font("Helvetica Neue", Font.BOLD, 16);
public static final Font font22 = new Font("Helvetica Neue", Font.PLAIN, 22);
public static final Font font22b = new Font("Helvetica Neue", Font.BOLD, 22);
public static final Font font30 = new Font("Helvetica Neue", Font.PLAIN, 30);
public static final Font font30b = new Font("Helvetica Neue", Font.BOLD, 30);
//borders
public static final Border lineBorder = new LineBorder(Color.BLACK, 2);
public static final Border emptyBorder = new EmptyBorder(5, 5, 5, 5);
private JButton firstSynthButtonOn, secondSynthButtonOn, thirdSynthButtonOn, fourthSynthButtonOn;
private JButton firstSynthButtonOff, secondSynthButtonOff, thirdSynthButtonOff,fourthSynthButtonOff;
private JSlider slider, slider2, slider3;
private OSCPortOut oscPortOut;
private OSCPortIn oscPortIn;
private JPanel livePanel;
private JPanel averagePanel;
private JButton addButton;
private JButton renderButton;
private boolean videoChosen;
// create a constructor
// OscUI takes an argument of myParent which is a JFrame
public OscUI(JFrame myParent) {
super();
parent = myParent;
makeDisplay();
try {
oscPortOut = new OSCPortOut();
oscPortIn = new OSCPortIn(OSCPort.defaultSCOSCPort());
oscPortIn.addListener("/livelevel", new OSCListener() {
private List<Integer> samples = new ArrayList<Integer>();
private int count = 10;
@Override
public void acceptMessage(Date time, OSCMessage message) {
System.out.println("ACCEPTED MESAGE");
List<Object> messageArgs = message.getArguments();
// args should have length 1 and have a float value
if (messageArgs != null && !messageArgs.isEmpty())
{
Object level = messageArgs.get(0);
if (level instanceof Float)
{
samples.add(Math.round((Float)level));
System.out.println("as int: "+Math.round((Float)level));
}
if (samples.size() == count)
{
int total = 0;
for (Integer i : samples)
{
total += i;
}
fillLevels(total / count);
samples.clear();
}
System.out.println(level.getClass().getName());
}
printArgs(messageArgs); // for debugging
// message.addArgument("$1");
// List<Object> args = message.getArguments();
// for(Object a : args){
// System.out.println("RECEIVED ARGS: " + a);
// }
}
});
oscPortIn.startListening();
} catch (Exception ex) {
// this is just a demo program, so this is acceptable behavior
ex.printStackTrace();
}
}
// tries to conver Object to int, returns null f it can't
private int toInt(Object obj){
// if (obj instanceof Float)
return 6;
}
/** Prints list of objects */
protected void printArgs(List<Object> args) {
if (args == null || args.isEmpty()) {
System.out.println("Argument list is null or empty");
return;
}
for (int i = 0; i < args.size(); i++){
Object o = args.get(i);
if (o instanceof String){
System.out.println("Arg "+i+": (String)"+o);
}
else if (o instanceof Integer){
System.out.println("Arg "+i+": (Integer)"+Integer.valueOf((Integer)o));
}
else if (o instanceof Float){
System.out.println("Arg "+i+": (Float)"+Float.valueOf((Float)o));
}
else
System.out.println("Arg "+i+": not String, Integer or FLoat");
}
}
// create a method for widget building
private final void makeDisplay() {
// setLayout to be a BoxLayout
setLayout(new BorderLayout());
setBackground(OSK_PINK);
setOpaque(true);
// call these methods ???? to be defined later
addTopPanel();
addMainPanel();
// addOscServerAddressPanel();
// addGlobalControlPanel();
// addFirstSynthPanel();
// addSecondSynthPanel();
// addThirdSynthPanel();
// addFourthSynthPanel();
}
/****** ADD PANEL METHODS ******/
/****** LOOK THE DIAGRAM BELOW **/
/****** GRIDBAGLAYOUT BRAH, GOOGLE IT
/**|_____1______|
/**| 2 | 3 | 4 |
/**|___|____|___|
/**| 5 | 6 | 7 |
/**|___|____|___|
/** 1 **/
private void addTopPanel() {
JPanel topPanel = new JPanel();
topPanel.setBackground(OSK_PINK);
topPanel.setOpaque(true);
add(topPanel, BorderLayout.NORTH);
// topPanel.add(loadImage("oskImg.png"), BorderLayout.EAST);
JPanel titlePanel = new JPanel();
titlePanel.add(makeLabel("[", font30));
titlePanel.add(makeLabel("OSKELATE ", font30b));
titlePanel.add(makeLabel("VISUALISER", font30));
titlePanel.add(makeLabel("]", font30));
titlePanel.setBackground(OSK_PINK);
titlePanel.setOpaque(true);
JButton exitButton = new JButton("Exit", loadImageAsIcon("close.png"));
exitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
oscPortOut.close();
oscPortIn.close();
}
catch (Exception e1)
{
// uwot
}
}
});
topPanel.add(exitButton, BorderLayout.EAST);
topPanel.add(titlePanel, BorderLayout.CENTER);
// JTextArea textArea = new JTextArea();
// topPanel.add(textArea, BorderLayout.WEST);
}
/** 2, 3, 4, 5, 6, 7 **/
private void addMainPanel() {
JPanel mainPanel = new JPanel();
GridBagLayout gridBag = new GridBagLayout();
mainPanel.setLayout(gridBag);
GridBagConstraints cons = new GridBagConstraints();
cons.weightx = 0.5;
add(mainPanel, BorderLayout.AFTER_LAST_LINE);
cons.fill = GridBagConstraints.BOTH;
cons.gridx = 0;
cons.gridy = 0;
cons.weightx = 0.5;
addLevelsPanel(mainPanel, cons);
cons.fill = GridBagConstraints.BOTH;
cons.gridx = 1;
cons.gridy = 0;
cons.gridwidth = 3;
cons.gridheight = 2;
cons.weightx = 1;
addTabbedPane(mainPanel, cons);
cons.fill = GridBagConstraints.BOTH;
cons.gridx = 0;
cons.gridy = 1;
cons.gridwidth = 1;
cons.weightx = 0.5;
addGemPanel(mainPanel, cons);
// cons.fill = GridBagConstraints.BOTH;
// cons.gridx = 1;
// cons.gridy = 1;
// cons.gridwidth = 1;
// cons.weightx = 1;
// addAudioPanel(mainPanel, cons);
}
/** 4
* @param cons **/
private void addLevelsPanel(JPanel mainPanel, GridBagConstraints cons) {
JPanel levelsPanel = new JPanel();
levelsPanel.setBackground(OSK_PALEPINK);
levelsPanel.setOpaque(true);
levelsPanel.setLayout(new BorderLayout());
levelsPanel.add(makeLabel("SOUND LEVEL", font22), BorderLayout.NORTH);
levelsPanel.add(makeLevels(), BorderLayout.CENTER);
mainPanel.add(levelsPanel, cons);
}
/** 3
* @param cons **/
private void addTabbedPane(JPanel mainPanel, GridBagConstraints cons) {
JPanel skeletalPanel = new JPanel();
JTabbedPane tabbedPane = new JTabbedPane();
//skeletalScroll.setPreferredSize(new Dimension(ScreenRes.getScaledWidth(0.55), ScreenRes.getScaledHeight(0.4630)));//700 500
skeletalPanel.setPreferredSize(new Dimension(ScreenRes.getScaledWidth(0.55), ScreenRes.getScaledHeight(0.9)));//700 500
skeletalPanel.setBackground(OSK_PALEPINK);
skeletalPanel.setOpaque(true);
//skeletalPanel.setLayout(new GridLayout(3, 1, 5, 5));
//skeletalPanel.setLayout(new FlowLayout());
skeletalPanel.setBorder(new EmptyBorder(ScreenRes.getScaledHeight(0.1204),ScreenRes.getScaledWidth(0.0260),ScreenRes.getScaledHeight(0.0463),ScreenRes.getScaledWidth(0.0260)));
//skeletalPanel.add(makeLabel("SKELETAL RESPONSE", font22));
skeletalPanel.add(new FXLuma("FX:_L_U_M_A", this));
skeletalPanel.add(new FXMBlur("FX:_M_B_L_U_R", this));
skeletalPanel.add(new FXFrame("FX:_F_R_A_M_E", this));
skeletalPanel.add(new FXRefract("FX:_R_E_F_R_A_C_T", this));
skeletalPanel.add(new FXKalei("FX:_K_A_L_E_I", this));
skeletalPanel.add(new TXCubism("TX:_C_U_B_I_S_M", this));
skeletalPanel.add(new FXOskwave("TX:_O_S_K_W_A_V_E", this));
/// audio
JPanel audioPanel = new JPanel();
audioPanel.setPreferredSize(new Dimension(ScreenRes.getScaledWidth(0.2083), ScreenRes.getScaledHeight(0.4630)));//400 500
audioPanel.setBackground(OSK_PALEGREY);
audioPanel.setOpaque(true);
audioPanel.setLayout(new GridLayout(3, 1, 5, 5));
audioPanel.setBorder(emptyBorder);
audioPanel.add(makeLabel("<html><h1 style=\"color:white\"><span style=\"font-weight: bold\">AUDIO</span> RESPONSE</h><html>", font22));
// FX and TX
JPanel auFXPanel = new JPanel();
auFXPanel.setBackground(OSK_PALEGREY);
auFXPanel.add(new EmptyPanel("FX:LUMA",0.1, 0.1, 13, 18, 0.0078, this));
auFXPanel.add(new SliderPanel("FX:FRAME",0.1, 0.1, 13, 18, 0.0078, this));
auFXPanel.add(new EmptyPanel("FX:MBLUR",0.1, 0.1, 13, 18, 0.0078, this));
auFXPanel.add(new EmptyPanel("FX:REFRACT",0.1, 0.1, 13, 18, 0.0078, this));
auFXPanel.add(new EmptyPanel("FX:KALEI",0.1, 0.1, 13, 18, 0.0078, this));//0.0678 0.0833
audioPanel.add(auFXPanel);
JPanel auTXPanel = new JPanel();
auTXPanel.setBackground(OSK_PALEGREY);
auTXPanel.add(new EmptyPanel("NORMAL TX",0.1, 0.1, 13,18, 0.0078, this));//0.0130 18,35
auTXPanel.add(new EmptyPanel("TX:CUBISM",0.1, 0.1, 13,18, 0.0078, this));
auTXPanel.add(new EmptyPanel("TX:OSKWAVE",0.1, 0.1, 13,18, 0.0078, this));
audioPanel.add(auTXPanel);
for (int i = 0; i < 8; i++){
// audioPanel.add(new EmptyPanel());
}
audioPanel.setVisible(true);
audioPanel.setOpaque(true);
tabbedPane.add("Skeletal", skeletalPanel);
tabbedPane.addTab("Audio", audioPanel);
tabbedPane.setVisible(true);
mainPanel.add(tabbedPane, cons);
}
/** 2
* @param cons **/
private void addLogoPanel(JPanel mainPanel, GridBagConstraints cons) {
BufferedImage image = null;
try {
image = ImageIO.read(new File("src/main/java/com/illposed/osc/ui/Oskelate.PNG"));
} catch (IOException ex) {
System.out.println("Where is the image?");
}
cons.weightx = 2;
JPanel title = new JPanel();
title.setBackground(new Color(255,238,239));
JLabel imgP = new JLabel(new ImageIcon(image));
title.setPreferredSize(new Dimension(ScreenRes.getScaledWidth(0.2), ScreenRes.getScaledHeight(0.2778)));//250 500
title.setBorder(lineBorder);
title.setLayout(new GridLayout(1, 2, 0,0));
title.add(imgP);
mainPanel.add(title, cons);
}
private Image getScaledImage(Image srcImg, int w, int h){
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}
/** 6
* @param cons **/
private void addAudioPanel(JPanel mainPanel, GridBagConstraints cons) {
JPanel audioPanel = new JPanel();
audioPanel.setPreferredSize(new Dimension(ScreenRes.getScaledWidth(0.2083), ScreenRes.getScaledHeight(0.4630)));//400 500
audioPanel.setBackground(OSK_PALEGREY);
audioPanel.setOpaque(true);
audioPanel.setLayout(new GridLayout(3, 1, 5, 5));
audioPanel.setBorder(emptyBorder);
audioPanel.add(makeLabel("<html><h1 style=\"color:white\"><span style=\"font-weight: bold\">AUDIO</span> RESPONSE</h><html>", font22));
// FX and TX
JPanel auFXPanel = new JPanel();
auFXPanel.setBackground(OSK_PALEGREY);
auFXPanel.add(new EmptyPanel("FX:LUMA",0.1, 0.1, 13, 18, 0.0078, this));
auFXPanel.add(new SliderPanel("FX:FRAME",0.1, 0.1, 13, 18, 0.0078, this));
auFXPanel.add(new EmptyPanel("FX:MBLUR",0.1, 0.1, 13, 18, 0.0078, this));
auFXPanel.add(new EmptyPanel("FX:REFRACT",0.1, 0.1, 13, 18, 0.0078, this));
auFXPanel.add(new EmptyPanel("FX:KALEI",0.1, 0.1, 13, 18, 0.0078, this));//0.0678 0.0833
audioPanel.add(auFXPanel);
JPanel auTXPanel = new JPanel();
auTXPanel.setBackground(OSK_PALEGREY);
auTXPanel.add(new EmptyPanel("NORMAL TX",0.1, 0.1, 13,18, 0.0078, this));//0.0130 18,35
auTXPanel.add(new EmptyPanel("TX:CUBISM",0.1, 0.1, 13,18, 0.0078, this));
auTXPanel.add(new EmptyPanel("TX:OSKWAVE",0.1, 0.1, 13,18, 0.0078, this));
audioPanel.add(auTXPanel);
for (int i = 0; i < 8; i++){
// audioPanel.add(new EmptyPanel());
}
audioPanel.setVisible(true);
audioPanel.setOpaque(true);
mainPanel.add(audioPanel, cons);
}
/** 5
* @param cons **/
private void addGemPanel(JPanel mainPanel, GridBagConstraints cons) {
JPanel gemPanel = new JPanel();
gemPanel.setLayout(new BoxLayout(gemPanel, BoxLayout.PAGE_AXIS));
JPanel btnPanel = new JPanel();
addButton = new JButton("Create GEM", loadImageAsIcon("plus.png"));
addButton.setVerticalTextPosition(SwingConstants.BOTTOM);
addButton.setHorizontalTextPosition(SwingConstants.CENTER);
renderButton = new JButton("Render", loadImageAsIcon("play.png"));
renderButton.setVerticalTextPosition(SwingConstants.BOTTOM);
renderButton.setHorizontalTextPosition(SwingConstants.CENTER);
// JButton closeButton = new JButton("Destroy GEM", loadImageAsIcon("close.png"));
// closeButton.setVerticalTextPosition(SwingConstants.BOTTOM);
// closeButton.setHorizontalTextPosition(SwingConstants.CENTER);
btnPanel.add(addButton);
btnPanel.add(renderButton);
// btnPanel.add(closeButton);
JPanel optionPanel = new JPanel();
optionPanel.setLayout(new BoxLayout(optionPanel,BoxLayout.PAGE_AXIS));
ButtonGroup bgroup = new ButtonGroup();
final JRadioButton internalScreen = new JRadioButton("Internal Screen");
final JRadioButton externalScreen = new JRadioButton("External Screen");
internalScreen.setFont(font22b);
externalScreen.setFont(font22b);
internalScreen.setAlignmentX(JComponent.CENTER_ALIGNMENT);
externalScreen.setAlignmentX(JComponent.CENTER_ALIGNMENT);
bgroup.add(internalScreen);
bgroup.add(externalScreen);
optionPanel.add(internalScreen);
optionPanel.add(externalScreen);
addButton.addActionListener(new ActionListener() {
boolean isCreate = true;
@Override
public void actionPerformed(ActionEvent e) {
if(isCreate){
// TODO Auto-generated method stub
if(!internalScreen.isSelected() && !externalScreen.isSelected()){
JOptionPane.showMessageDialog(null, "Must select Screen Type", "WARNING!", JOptionPane.ERROR_MESSAGE);
}
else if(internalScreen.isSelected()){
doSendMessage("/internal", null);
doSendMessage("/create", null);
changeButton(addButton, "Destroy Gem", "close.png");
isCreate = false;
}
else if(externalScreen.isSelected()){
doSendMessage("/external",null);
doSendMessage("/create", null);
changeButton(addButton, "Destroy Gem", "close.png");
isCreate = false;
}
}
else{
doSendMessage("/destroy", null);
isCreate = true;
changeButton(addButton,"Create Gem","plus.png");
}
}
});
renderButton.addActionListener(new ActionListener() {
boolean isPlay = true;
List<Object> args = new ArrayList<Object>();
@Override
public void actionPerformed(ActionEvent e) {
if (isPlay)
{
changeButton(renderButton,"Stop Render", "stop.png");
isPlay = false;
args.clear();
args.add(new Integer(1));
doSendMessage("/rendergem", args);
}
else {
changeButton(renderButton, "Render", "play.png");
isPlay = false;
args.clear();
args.add(new Integer(0));
doSendMessage("/rendergem", args);
}
}
});
gemPanel.add(btnPanel);
gemPanel.add(optionPanel);
JPanel videoPanel= new JPanel();
videoPanel.setPreferredSize(new Dimension(ScreenRes.getScaledWidth(0.2), ScreenRes.getScaledHeight(0.3472)));//250 500
videoPanel.setBackground(OSK_PALEPINK);
videoPanel.setOpaque(true);
JButton videoButton = new JButton("Choose video file");
final JButton playButton = new JButton("Play Video", loadImageAsIcon("play.png"));
final JButton renderButton = new JButton("Render Video", loadImageAsIcon("gear.png"));
playButton.addActionListener(new ActionListener() {
boolean isPlay = true;
List<Object> args = new ArrayList<Object>();
@Override
public void actionPerformed(ActionEvent e) {
if(!videoChosen){
JOptionPane.showMessageDialog(null, "Must Choose WIDEO", "ERROR FGT", JOptionPane.ERROR_MESSAGE);
}
else if(isPlay){
changeButton(playButton, "Stop Video", "stop.png");
isPlay = false;
args.clear();
args.add(new Integer(1));
doSendMessage("/play", args);
}
else{
changeButton(playButton, "Play Video", "play.png");
args.clear();
args.add(new Integer(0));
doSendMessage("/play", args);
isPlay = true;
}
}
});
renderButton.addActionListener(new ActionListener() {
List<Object> args = new ArrayList<Object>();
boolean isRender = true;
@Override
public void actionPerformed(ActionEvent e) {
if(!videoChosen){
JOptionPane.showMessageDialog(null, "Cannot Render an Empty Video...CMON!!", "ERROR FGT", JOptionPane.ERROR_MESSAGE);
}
else if(isRender){
changeButton(renderButton,"Stop Render",null);
args.clear();
args.add(new Integer(1));
doSendMessage("/render",args);
isRender = false;
}
else{
changeButton(renderButton,"Start Render", null);
args.clear();
args.add(new Integer(0));
doSendMessage("/render",args);
isRender = true;
}
}
});
videoPanel.add(playButton);
videoPanel.add(renderButton);
videoButton.addActionListener(new ActionListener() {
List<Object> args = new ArrayList<Object>();
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Please select a video file");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
String path = "";
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
// System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
path = (chooser.getSelectedFile()).getPath();
makeVideoChosen();
} else {
System.out.println("No Selection");
}
// doSendSlider((float)1000.00, 1000);
args.clear();
args.add("open:");
args.add(path);
doSendMessage("/open", args);
}
});
videoPanel.add(videoButton);
//mainPanel.add(videoPanel, cons);
gemPanel.add(videoPanel);
mainPanel.add(gemPanel, cons);
}
protected void changeButton(JButton b, String name, String path){
b.setText(name);
b.setVerticalTextPosition(SwingConstants.BOTTOM);
b.setHorizontalTextPosition(SwingConstants.CENTER);
if(path != null){
b.setIcon(loadImageAsIcon(path));
}
}
protected void makeVideoChosen() {
videoChosen = true;
}
/** THAT'S ALL THE MAIN PANELS **/
// /javaosc-ui/src/main/java/res/oskImg.png
private Component loadImage(String path){
try
{
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = getClass().getResourceAsStream(path);
Image logo = ImageIO.read(input);
JLabel label = new JLabel( new ImageIcon( logo ) );
return label;
}
catch ( Exception e ) { return new JLabel("image load failed"); }
}
private ImageIcon loadImageAsIcon(String path){
try
{
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = getClass().getResourceAsStream(path);
Image logo = ImageIO.read(input);
ImageIcon i = new ImageIcon(logo);
return i;
}
catch ( Exception e ) { return null; }
}
/****** MAKE COMPONENT METHODS ******/
/* returns JLabel with text*/
public static Component makeLabel(String name, Font font) {
JLabel temp = new JLabel();
temp.setHorizontalAlignment(JLabel.CENTER);
temp.setFont(font);
temp.setText(name);
temp.setBorder(emptyBorder);
return temp;
}
private Component makeLevels() {
JPanel levelsPanel = new JPanel();
levelsPanel.setLayout(new GridLayout(1, 2, 20, 1));
livePanel= new JPanel();
livePanel.setLayout(new GridLayout(15, 1, 0, 1));
levelsPanel.add(livePanel);
averagePanel = new JPanel();
averagePanel.setLayout(new GridLayout(15, 1, 0, 1));
/** make sure you only call fillLevels once both livePanel and
* average panel have been created
*/
fillLevels(5);
// fillLevels(8);
levelsPanel.add(averagePanel);
return levelsPanel;
}
private void fillLevels(int num) {
livePanel.removeAll();
averagePanel.removeAll();
if (num < 0) num = 0;
num = num / 4;
if (num > 15) num = 15; // SRIRAM DID THIS THANKS BRAH
for (int i = 0; i < (15 - num); i++)
{
livePanel.add(new JLabel(" "));
averagePanel.add(new JLabel(" "));
}
for (int i = 0; i < num; i++)
{
JLabel square = new JLabel(" ");
square.setOpaque(true);
square.setBackground(Color.GREEN);
averagePanel.add(square);
livePanel.add(square);
}
averagePanel.repaint();
averagePanel.revalidate();
livePanel.repaint();
livePanel.revalidate();
}
protected void addFourthSynthPanel() {
// TODO Auto-generated method stub
JPanel fourthSynthPanel = makeNewJPanel();
fourthSynthPanel.setBackground(new Color(13, 23, 0));
fourthSynthButtonOn = new JButton("On");
fourthSynthButtonOff = new JButton("Off");
fourthSynthButtonOff.setEnabled(false);
fourthSynthPanel.add(fourthSynthButtonOn);
// add firstSendButtonOff to the firstSynthPanel
fourthSynthPanel.add(fourthSynthButtonOff);
// add the firstSynthpanel to the OscUI Panel
add(fourthSynthPanel);
}
// create a method for adding ServerAddress Panel to the OscUI Panel
protected void addOscServerAddressPanel() {
// variable addressPanel holds an instance of JPanel.
// instance of JPanel received from makeNewJPanel method
JPanel addressPanel = makeNewJPanel1();
addressPanel.setBackground(new Color(123, 150, 123));
// variable addressWidget holds an instance of JTextField
addressWidget = new JTextField("localhost");
// variable setAddressButton holds an insatnce of JButton with
// a "Set Address" argument for its screen name
JButton setAddressButton = new JButton("Set Address");
setAddressButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// perform the addressChanged method when action is received
addressChanged();
}
});
// variable portWidget holds an instance of JLabel with the OSCPortOut
// as the text it looks like OSCPortOut has a method to get the default
// SuperCollider port
portWidget = new JLabel(Integer.toString(OSCPort.defaultSCOSCPort()));
portWidget.setForeground(new Color(255, 255, 255));
JLabel portLabel = new JLabel("Port");
portLabel.setForeground(new Color(255, 255, 255));
// add the setAddressButton to the addressPanel
addressPanel.add(setAddressButton);
// portWidget = new JTextField("57110");
// add the addressWidget to the addressPanel
addressPanel.add(addressWidget);
// add the JLabel "Port" to the addressPanel
addressPanel.add(portLabel);
// add te portWidget tot eh addressPanel
addressPanel.add(portWidget);
//??? add address panel to the JPanel OscUI
add(addressPanel);
}
public void addGlobalControlPanel() {
JPanel globalControlPanel = makeNewJPanel();
JButton globalOffButton = new JButton("All Off");
JButton globalOnButton = new JButton("All On");
textBox4 = new JTextField(String.valueOf(1000), 8);
delayLabel = new JLabel("All Off delay in ms");
delayLabel.setForeground(new Color(255, 255, 255));
globalControlPanel.setBackground(new Color(13, 53, 0));
globalOnButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doSendGlobalOn(1000, 1001, 1002);
firstSynthButtonOn.setEnabled(false);
firstSynthButtonOff.setEnabled(true);
slider.setEnabled(true);
slider.setValue(2050);
textBox.setEnabled(true);
textBox.setText("440.0");
secondSynthButtonOn.setEnabled(false);
secondSynthButtonOff.setEnabled(true);
slider2.setEnabled(true);
slider2.setValue(2048);
textBox2.setEnabled(true);
textBox2.setText("440.0");
thirdSynthButtonOn.setEnabled(false);
thirdSynthButtonOff.setEnabled(true);
slider3.setEnabled(true);
slider3.setValue(2052);
fourthSynthButtonOn.setEnabled(false);
fourthSynthButtonOff.setEnabled(true);
textBox3.setEnabled(true);
textBox3.setText("440.0");
}
});
// ??? have an anonymous class listen to the setAddressButton action
globalOffButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doSendGlobalOff(1000, 1001, 1002);
firstSynthButtonOn.setEnabled(true);
firstSynthButtonOff.setEnabled(false);
slider.setEnabled(false);
slider.setValue(0);
textBox.setEnabled(false);
textBox.setText("0");
secondSynthButtonOn.setEnabled(true);
secondSynthButtonOff.setEnabled(false);
slider2.setEnabled(false);
slider2.setValue(0);
textBox2.setEnabled(false);
textBox2.setText("0");
thirdSynthButtonOn.setEnabled(true);
thirdSynthButtonOff.setEnabled(false);
slider3.setEnabled(false);
slider3.setValue(0);
textBox3.setEnabled(false);
textBox3.setText("0");
}
});
globalControlPanel.add(globalOnButton);
globalControlPanel.add(globalOffButton);
globalControlPanel.add(textBox4);
globalControlPanel.add(delayLabel);
add(globalControlPanel);
}
// create method for adding a the buttons and synths of the
// first synth on one panel
public void addFirstSynthPanel() {
// the variable firstSynthPanel holds an instance of Jpanel
// created by the makeNewJPanel method
JPanel firstSynthPanel = makeNewJPanel();
// the variable firstSynthButytonOn holds an instance of JButton labeled
// "On"
firstSynthPanel.setBackground(new Color(13, 23, 0));
firstSynthButtonOn = new JButton("On");
//firstSynthButtonOn.setBackground(new Color(123, 150, 123));
// the variable firstSynthButtonOff holds an instance of JButton labeled
// "Off"
firstSynthButtonOff = new JButton("Off");
firstSynthButtonOff.setEnabled(false);
// the variable slider holds an instance of JSlider which is
// set to be a Horizontal slider
slider = new JSlider(JSlider.HORIZONTAL);
// set the minimum value of the slider to 20
slider.setMinimum(0);
slider.setMaximum(10000);
// set the inital value of the slider to 400
//slider.setValue(1 / 5);
slider.setEnabled(false);
textBox = new JTextField(String.valueOf((1 / 5) * 10000), 8);
textBox.setEnabled(false);
firstSynthButtonOn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// when the on button is pushed, doSendOn method is invoked
// send the arguments for frequency and node
doSendOn(440, 1000);
firstSynthButtonOn.setEnabled(false);
firstSynthButtonOff.setEnabled(true);
textBox.setText("440.0");
textBox.setEnabled(true);
slider.setValue(2050);
slider.setEnabled(true);
}
});
// when the on button is pushed, doSendOff method is invoked
// send the argument for node
firstSynthButtonOff.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// when the action occurs the doSend1 method is invoked
doSendOff(1000);
firstSynthButtonOn.setEnabled(true);
firstSynthButtonOff.setEnabled(false);
slider.setEnabled(false);
slider.setValue(0);
textBox.setEnabled(false);
textBox.setText("0");
}
});
// when the slider is moved, doSendSlider method is invoked
// send the argument for freq and node
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JSlider mySlider = (JSlider) e.getSource();
if (mySlider.getValueIsAdjusting()) {
float freq = (float) mySlider.getValue();
freq = (freq / 10000) * (freq / 10000);
freq = freq * 10000;
freq = freq + 20;
doPrintValue(freq);
doSendSlider(freq, 1000);
}
}
});
// when the value in the textbox is changed, doSendSlider method is
// invoked; send the argument for freq and node
textBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTextField field = (JTextField) e.getSource();
float freq = (Float.valueOf(field.getText())).floatValue();
if (freq > 10020) { freq = 10020; doPrintValue(freq); }
if (freq < 20) { freq = 20; doPrintValue(freq); }
slider.setValue((int)(10000*Math.sqrt(((freq - 20) / 10000))));
doSendSlider(freq, 1000);
}
});
// add firstSynthButtonOn to the firstSynthPanel
firstSynthPanel.add(firstSynthButtonOn);
// add firstSendButtonOff to the firstSynthPanel
firstSynthPanel.add(firstSynthButtonOff);
// add slider to the firstSynthPanel
firstSynthPanel.add(slider);
firstSynthPanel.add(textBox);
// add the firstSynthpanel to the OscUI Panel
add(firstSynthPanel);
}
///********************
// create method for adding a the Second Synth Panel
protected void addSecondSynthPanel() {
// make a new JPanel called secondSynthPanel
JPanel secondSynthPanel = makeNewJPanel();
secondSynthPanel.setBackground(new Color(13, 23, 0));
// the variable secondSynthButtonOn holds an instance of JButton
secondSynthButtonOn = new JButton("On");
// the variable secondSynthButtonOff holds an instance of JButton
secondSynthButtonOff = new JButton("Off");
secondSynthButtonOff.setEnabled(false);
// the variable slider2 holds an instance of JSlider positioned
// horizontally
slider2 = new JSlider(JSlider.HORIZONTAL);
slider2.setMinimum(0);
slider2.setMaximum(10000);
slider2.setEnabled(false);
textBox2 = new JTextField(String.valueOf((2 / 5) * 10000), 8);
textBox2.setEnabled(false);
secondSynthButtonOn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// when the action occurs the doSendOn method is invoked
// with the arguments for freq and node
doSendOn(440, 1001);
secondSynthButtonOn.setEnabled(false);
secondSynthButtonOff.setEnabled(true);
slider2.setEnabled(true);
slider2.setValue(2050);
textBox2.setEnabled(true);
textBox2.setText("440.0");
}
});
// add the action for the Off button
secondSynthButtonOff.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// when the action occurs the doSendOff method is invoked
// with the argument for node
doSendOff(1001);
secondSynthButtonOn.setEnabled(true);
secondSynthButtonOff.setEnabled(false);
slider2.setEnabled(false);
slider2.setValue(0);
textBox2.setEnabled(false);
textBox2.setText("0");
}
});
// add the action for the slider
slider2.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JSlider mySlider2 = (JSlider) e.getSource();
if (mySlider2.getValueIsAdjusting()) {
float freq = (float) mySlider2.getValue();
freq = (freq / 10000) * (freq / 10000);
freq = freq * 10000;
freq = freq + 20;
doPrintValue2(freq);
// arguments for freq and node
doSendSlider(freq, 1001);
}
}
});
// when the value in the textbox is changed, doSendSlider method is
// invoked; send the argument for freq and node
textBox2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTextField field = (JTextField) e.getSource();
float freq = (Float.valueOf(field.getText())).floatValue();
if (freq > 10020) { freq = 10020; doPrintValue2(freq); }
if (freq < 20) { freq = 20; doPrintValue2(freq); }
slider2.setValue((int)(10000*Math.sqrt(((freq - 20) / 10000))));
doSendSlider(freq, 1001);
}
});
// ******************
// add Buttons and Slider to secondSynthPanel
secondSynthPanel.add(secondSynthButtonOn);
secondSynthPanel.add(secondSynthButtonOff);
secondSynthPanel.add(slider2);
secondSynthPanel.add(textBox2);
// add the secondSynthPanel2 to the OscUI Panel
add(secondSynthPanel);
}
protected void addThirdSynthPanel() {
JPanel thirdSynthPanel = makeNewJPanel();
thirdSynthPanel.setBackground(new Color(13, 23, 0));
thirdSynthButtonOn = new JButton("On");
thirdSynthButtonOff = new JButton("Off");
thirdSynthButtonOff.setEnabled(false);
slider3 = new JSlider(JSlider.HORIZONTAL);
slider3.setMinimum(0);
slider3.setMaximum(10000);
slider3.setEnabled(false);
textBox3 = new JTextField(String.valueOf((1 / 25) * 10000), 8);
textBox3.setEnabled(false);
thirdSynthButtonOn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// when the action occurs the doSendOn method is invoked
// with arguments for freq and node
doSendOn(440, 1002);
thirdSynthButtonOn.setEnabled(false);
thirdSynthButtonOff.setEnabled(true);
slider3.setEnabled(true);
slider3.setValue(2050);
textBox3.setEnabled(true);
textBox3.setText("440.0");
}
});
thirdSynthButtonOff.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// when the action occurs the doSendOff method is invoked
// with argument for node
doSendOff(1002);
thirdSynthButtonOn.setEnabled(true);
thirdSynthButtonOff.setEnabled(false);
slider3.setEnabled(false);
slider3.setValue(0);
textBox3.setEnabled(false);
textBox3.setText("0");
}
});
slider3.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
// JSlider source = (JSlider) e.getSource();
JSlider mySlider3 = (JSlider) e.getSource();
//if (source.getValueIsAdjusting()) {
if (mySlider3.getValueIsAdjusting()) {
// int freq = (int)source.getValue();
float freq = (float) mySlider3.getValue();
freq = (freq / 10000) * (freq / 10000);
freq = freq * 10000;
freq = freq + 20;
doPrintValue3(freq);
// when the action occurs the doSendSlider method is invoked
// with arguments for freq and node
doSendSlider(freq, 1002);
}
}
});
// when the value in the textbox is changed, doSendSlider method is
// invoked; send the argument for freq and node
textBox3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTextField field = (JTextField) e.getSource();
float freq = (Float.valueOf(field.getText())).floatValue();
if (freq > 10020) { freq = 10020; doPrintValue3(freq); }
if (freq < 20) { freq = 20; doPrintValue3(freq); }
slider3.setValue((int)(10000*Math.sqrt(((freq - 20) / 10000))));
doSendSlider(freq, 1002);
}
});
// ******************
// add thirdSynthButtons and slider to the thirdSynthPanel
thirdSynthPanel.add(thirdSynthButtonOn);
thirdSynthPanel.add(thirdSynthButtonOff);
thirdSynthPanel.add(slider3);
thirdSynthPanel.add(textBox3);
// add the sendButtonPanel2 to the OscUI Panel
add(thirdSynthPanel);
}
// here is the make new JPanel method
protected JPanel makeNewJPanel() {
// a variable tempPanel holds an instance of JPanel
JPanel tempPanel = new JPanel();
// set the Layout of tempPanel to be a FlowLayout aligned left
tempPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
// function returns the tempPanel
return tempPanel;
}
// here is the make new JPanel method
protected JPanel makeNewJPanel1() {
// a variable tempPanel holds an instance of JPanel
JPanel tempPanel1 = new JPanel();
// set the Layout of tempPanel to be a FlowLayout aligned left
tempPanel1.setLayout(new FlowLayout(FlowLayout.RIGHT));
// function returns the tempPanel
return tempPanel1;
}
// actions
// create a method for the addressChanged action (Set Address)
public void addressChanged() {
// the variable OSCPortOut tries to get an instance of OSCPortOut
// at the address indicated by the addressWidget
try {
oscPortOut =
new OSCPortOut(InetAddress.getByName(addressWidget.getText()));
// if the oscPort variable fails to be instantiated then sent
// the error message
} catch (Exception e) {
showError("Couldn't set address");
}
}
// create a method for the doSend action (Send)
public void doSendOn(float freq, int node) {
// if "Set Address" has not been performed then give the message to set
// it first
if (null == oscPortOut) {
showError("Please set an address first");
}
// send an OSC message to start the synth "pink" on node 1000.
List<Object> args = new ArrayList<Object>(6);
args.add("javaosc-example");
args.add(new Integer(node));
args.add(new Integer(1));
args.add(new Integer(0));
args.add("freq");
args.add(new Float(freq));
// a comma is placed after /s_new in the code
OSCMessage msg = new OSCMessage("/s_new", args);
// Object[] args2 = {new Symbol("amp"), new Float(0.5)};
// OscMessage msg2 = new OscMessage("/n_set", args2);
//oscPort.send(msg);
// try to use the send method of oscPort using the msg in nodeWidget
// send an error message if this doesn't happen
try {
oscPortOut.send(msg);
} catch (Exception ex) {
showError("Couldn't send");
}
}
// create a method for the doSend1 action (Send)
public void doSendOff(int node) {
// if "Set Address" has not been performed then give the message to set
// it first
if (null == oscPortOut) {
showError("Please set an address first");
}
// send an OSC message to free the node 1000
List<Object> args = new ArrayList<Object>(1);
args.add(new Integer(node));
OSCMessage msg = new OSCMessage("/n_free", args);
// try to use the send method of oscPort using the msg in nodeWidget
// send an error message if this doesn't happen
try {
oscPortOut.send(msg);
} catch (Exception e) {
showError("Couldn't send");
}
}
public void doPrintValue(float freq) {
textBox.setText(String.valueOf(freq));
}
public void doPrintValue2(float freq) {
textBox2.setText(String.valueOf(freq));
}
public void doPrintValue3(float freq) {
textBox3.setText(String.valueOf(freq));
}
/** SEND METHODS */
// create a method for the doSend3 action (Send)
public void doSendSlider(float freq, int node) {
// if "Set Address" has not been performed then give the message to set
// it first
if (null == oscPortOut) {
showError("Please set an address first");
}
// send an OSC message to set the node 1000
List<Object> args = new ArrayList<Object>(3);
args.add(new Integer(node));
args.add("freq");
args.add(new Float(freq));
OSCMessage msg = new OSCMessage("/n_set", args);
// try to use the send method of oscPort using the msg in nodeWidget
// send an error message if this doesn't happen
try {
oscPortOut.send(msg);
} catch (Exception e) {
showError("Couldn't send");
}
}
public void doSendMessage(String msg_name, List<Object> args){
if(null == oscPortOut){
showError("Please set an Address first");
}
OSCMessage msg = new OSCMessage();
if (args == null || args.isEmpty())
{
msg = new OSCMessage(msg_name);
}
else
{
msg = new OSCMessage(msg_name, args);
}
try {
oscPortOut.send(msg);
for(Object a : args){
System.out.println(msg_name + " " + a);
}
System.out.println("MSG SENT: " + msg_name);
} catch (Exception e) {
showError("Couldn't send");
}
}
public void doSendGlobalOff(int node1, int node2, int node3) {
if (null == oscPortOut) {
showError("Please set an address first");
}
List<Object> args1 = new ArrayList<Object>(1);
args1.add(new Integer(node1));
OSCMessage msg1 = new OSCMessage("/n_free", args1);
List<Object> args2 = new ArrayList<Object>(1);
args2.add(new Integer(node2));
OSCMessage msg2 = new OSCMessage("/n_free", args2);
List<Object> args3 = new ArrayList<Object>(1);
args3.add(new Integer(node3));
OSCMessage msg3 = new OSCMessage("/n_free", args3);
// create a timeStamped bundle of the messages
List<OSCPacket> packets = new ArrayList<OSCPacket>(3);
packets.add(msg1);
packets.add(msg2);
packets.add(msg3);
Date newDate = new Date();
long time = newDate.getTime();
Integer delayTime = Integer.valueOf(textBox4.getText());
time = time + delayTime.longValue();
newDate.setTime(time);
OSCBundle bundle = new OSCBundle(packets, newDate);
try {
oscPortOut.send(bundle);
} catch (Exception e) {
showError("Couldn't send");
}
}
public void doSendGlobalOn(int node1, int node2, int node3) {
if (null == oscPortOut) {
showError("Please set an address first");
}
List<Object> args1 = new ArrayList<Object>(4);
args1.add("javaosc-example");
args1.add(new Integer(node1));
args1.add(new Integer(1));
args1.add(new Integer(0));
OSCMessage msg1 = new OSCMessage("/s_new", args1);
List<Object> args2 = new ArrayList<Object>(4);
args2.add("javaosc-example");
args2.add(new Integer(node2));
args2.add(new Integer(1));
args2.add(new Integer(0));
OSCMessage msg2 = new OSCMessage("/s_new", args2);
List<Object> args3 = new ArrayList<Object>(4);
args3.add("javaosc-example");
args3.add(new Integer(node3));
args3.add(new Integer(1));
args3.add(new Integer(0));
OSCMessage msg3 = new OSCMessage("/s_new", args3);
try {
oscPortOut.send(msg1);
} catch (Exception e) {
showError("Couldn't send");
}
try {
oscPortOut.send(msg2);
} catch (Exception e) {
showError("Couldn't send");
}
try {
oscPortOut.send(msg3);
} catch (Exception e) {
showError("Couldn't send");
}
}
// create a showError method
protected void showError(String anErrorMessage) {
// tell the JOptionPane to showMessageDialog
System.out.println(anErrorMessage);
}
}
| bsd-3-clause |
AlexanderJohr/Java-ImageJ-Map-Digester-Locator | src/ij/gui/PointRoi.java | 6195 | package ij.gui;
import java.awt.*;
import java.awt.image.*;
import ij.*;
import ij.process.*;
import ij.measure.*;
import ij.plugin.filter.Analyzer;
import java.awt.event.KeyEvent;
import ij.plugin.frame.Recorder;
import ij.util.Java2;
/** This class represents a collection of points. */
public class PointRoi extends PolygonRoi {
private static Font font;
private static int fontSize = 9;
private double saveMag;
private boolean hideLabels;
/** Creates a new PointRoi using the specified int arrays of offscreen coordinates. */
public PointRoi(int[] ox, int[] oy, int points) {
super(itof(ox), itof(oy), points, POINT);
width+=1; height+=1;
}
/** Creates a new PointRoi using the specified float arrays of offscreen coordinates. */
public PointRoi(float[] ox, float[] oy, int points) {
super(ox, oy, points, POINT);
width+=1; height+=1;
}
/** Creates a new PointRoi using the specified float arrays of offscreen coordinates. */
public PointRoi(float[] ox, float[] oy) {
this(ox, oy, ox.length);
}
/** Creates a new PointRoi from a FloatPolygon. */
public PointRoi(FloatPolygon poly) {
this(poly.xpoints, poly.ypoints, poly.npoints);
}
/** Creates a new PointRoi from a Polygon. */
public PointRoi(Polygon poly) {
this(itof(poly.xpoints), itof(poly.ypoints), poly.npoints);
}
/** Creates a new PointRoi using the specified offscreen int coordinates. */
public PointRoi(int ox, int oy) {
super(makeXArray(ox, null), makeYArray(oy, null), 1, POINT);
width=1; height=1;
}
/** Creates a new PointRoi using the specified offscreen double coordinates. */
public PointRoi(double ox, double oy) {
super(makeXArray(ox, null), makeYArray(oy, null), 1, POINT);
width=1; height=1;
}
/** Creates a new PointRoi using the specified screen coordinates. */
public PointRoi(int sx, int sy, ImagePlus imp) {
super(makeXArray(sx, imp), makeYArray(sy, imp), 1, POINT);
setImage(imp);
width=1; height=1;
if (imp!=null) imp.draw(x-5, y-5, width+10, height+10);
if (Recorder.record && !Recorder.scriptMode())
Recorder.record("makePoint", x, y);
}
static float[] itof(int[] arr) {
if (arr==null)
return null;
int n = arr.length;
float[] temp = new float[n];
for (int i=0; i<n; i++)
temp[i] = arr[i];
return temp;
}
static float[] makeXArray(double value, ImagePlus imp) {
float[] array = new float[1];
array[0] = (float)(imp!=null?imp.getCanvas().offScreenXD((int)value):value);
return array;
}
static float[] makeYArray(double value, ImagePlus imp) {
float[] array = new float[1];
array[0] = (float)(imp!=null?imp.getCanvas().offScreenYD((int)value):value);
return array;
}
void handleMouseMove(int ox, int oy) {
//IJ.log("handleMouseMove");
}
protected void handleMouseUp(int sx, int sy) {
super.handleMouseUp(sx, sy);
modifyRoi(); //adds this point to previous points if shift key down
}
/** Draws the points on the image. */
public void draw(Graphics g) {
//IJ.log("draw: " + nPoints+" "+width+" "+height);
updatePolygon();
//IJ.log("draw: "+ xpf[0]+" "+ypf[0]+" "+xp2[0]+" "+yp2[0]);
if (ic!=null) mag = ic.getMagnification();
int size2 = HANDLE_SIZE/2;
if (!Prefs.noPointLabels && !hideLabels && nPoints>1) {
fontSize = 9;
if (mag>1.0)
fontSize = (int)(((mag-1.0)/3.0+1.0)*9.0);
if (fontSize>18) fontSize = 18;
if (font==null || mag!=saveMag)
font = new Font("SansSerif", Font.PLAIN, fontSize);
g.setFont(font);
if (fontSize>9)
Java2.setAntialiasedText(g, true);
saveMag = mag;
}
for (int i=0; i<nPoints; i++)
drawPoint(g, xp2[i]-size2, yp2[i]-size2, i+1);
//showStatus();
if (updateFullWindow)
{updateFullWindow = false; imp.draw();}
}
void drawPoint(Graphics g, int x, int y, int n) {
g.setColor(fillColor!=null?fillColor:Color.white);
g.drawLine(x-4, y+2, x+8, y+2);
g.drawLine(x+2, y-4, x+2, y+8);
g.setColor(strokeColor!=null?strokeColor:ROIColor);
g.fillRect(x+1,y+1,3,3);
if (!Prefs.noPointLabels && !hideLabels && nPoints>1)
g.drawString(""+n, x+6, y+fontSize+4);
g.setColor(Color.black);
g.drawRect(x, y, 4, 4);
}
public void drawPixels(ImageProcessor ip) {
ip.setLineWidth(Analyzer.markWidth);
for (int i=0; i<nPoints; i++) {
ip.moveTo(x+(int)xpf[i], y+(int)ypf[i]);
ip.lineTo(x+(int)xpf[i], y+(int)ypf[i]);
}
}
/** Returns a copy of this PointRoi with a point at (x,y) added. */
public PointRoi addPoint(double x, double y) {
FloatPolygon poly = getFloatPolygon();
poly.addPoint(x, y);
PointRoi p = new PointRoi(poly.xpoints, poly.ypoints, poly.npoints);
p.setHideLabels(hideLabels);
IJ.showStatus("count="+poly.npoints);
return p;
}
public PointRoi addPoint(int x, int y) {
return addPoint((double)x, (double)y);
}
/** Subtract the points that intersect the specified ROI and return
the result. Returns null if there are no resulting points. */
public PointRoi subtractPoints(Roi roi) {
Polygon points = getPolygon();
Polygon poly = roi.getPolygon();
Polygon points2 = new Polygon();
for (int i=0; i<points.npoints; i++) {
if (!poly.contains(points.xpoints[i], points.ypoints[i]))
points2.addPoint(points.xpoints[i], points.ypoints[i]);
}
if (points2.npoints==0)
return null;
else
return new PointRoi(points2.xpoints, points2.ypoints, points2.npoints);
}
public ImageProcessor getMask() {
if (cachedMask!=null && cachedMask.getPixels()!=null)
return cachedMask;
ImageProcessor mask = new ByteProcessor(width, height);
for (int i=0; i<nPoints; i++) {
mask.putPixel((int)xpf[i], (int)ypf[i], 255);
}
cachedMask = mask;
return mask;
}
/** Returns true if (x,y) is one of the points in this collection. */
public boolean contains(int x, int y) {
for (int i=0; i<nPoints; i++) {
if (x==this.x+xpf[i] && y==this.y+ypf[i]) return true;
}
return false;
}
public void setHideLabels(boolean hideLabels) {
this.hideLabels = hideLabels;
}
/** Always returns true. */
public boolean subPixelResolution() {
return true;
}
public String toString() {
if (nPoints>1)
return ("Roi[Points, count="+nPoints+"]");
else
return ("Roi[Point, x="+x+", y="+y+"]");
}
}
| bsd-3-clause |
NCIP/caarray | software/caarray-ejb.jar/src/main/java/gov/nih/nci/caarray/application/file/JobQueueSubmitter.java | 957 | //======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package gov.nih.nci.caarray.application.file;
import gov.nih.nci.caarray.jobqueue.JobQueue;
import com.google.inject.Inject;
/**
* Submits jobs via the job queue.
*/
public class JobQueueSubmitter implements FileManagementJobSubmitter {
private final JobQueue jobQueue;
/**
* @param jobQueue the Provider<JobQueue> dependency
*/
@Inject
public JobQueueSubmitter(JobQueue jobQueue) {
this.jobQueue = jobQueue;
}
/**
* {@inheritDoc}
*/
public void submitJob(AbstractFileManagementJob job) {
jobQueue.enqueue(job);
}
}
| bsd-3-clause |
jbobnar/TwelveMonkeys | imageio/imageio-tiff/src/test/java/com/twelvemonkeys/imageio/plugins/tiff/TIFFImageMetadataTest.java | 31657 | /*
* Copyright (c) 2015, Harald Kuhr
* 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 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 com.twelvemonkeys.imageio.plugins.tiff;
import com.twelvemonkeys.imageio.metadata.Directory;
import com.twelvemonkeys.imageio.metadata.Entry;
import com.twelvemonkeys.imageio.metadata.tiff.Rational;
import com.twelvemonkeys.imageio.metadata.tiff.TIFF;
import com.twelvemonkeys.imageio.metadata.tiff.TIFFEntry;
import com.twelvemonkeys.imageio.metadata.tiff.TIFFReader;
import com.twelvemonkeys.imageio.stream.URLImageInputStreamSpi;
import com.twelvemonkeys.lang.StringUtil;
import org.junit.Test;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.imageio.ImageIO;
import javax.imageio.metadata.IIOInvalidTreeException;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataFormatImpl;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.spi.IIORegistry;
import javax.imageio.stream.ImageInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.*;
/**
* TIFFImageMetadataTest.
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: harald.kuhr$
* @version $Id: TIFFImageMetadataTest.java,v 1.0 30/07/15 harald.kuhr Exp$
*/
public class TIFFImageMetadataTest {
static {
IIORegistry.getDefaultInstance().registerServiceProvider(new URLImageInputStreamSpi());
ImageIO.setUseCache(false);
}
// TODO: Candidate super method
private URL getClassLoaderResource(final String resource) {
return getClass().getResource(resource);
}
// TODO: Candidate abstract super method
private IIOMetadata createMetadata(final String resource) throws IOException {
try (ImageInputStream input = ImageIO.createImageInputStream(getClassLoaderResource(resource))) {
Directory ifd = new TIFFReader().read(input);
// System.err.println("ifd: " + ifd);
return new TIFFImageMetadata(ifd);
}
}
@Test
public void testMetadataStandardFormat() throws IOException {
IIOMetadata metadata = createMetadata("/tiff/smallliz.tif");
Node root = metadata.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
// Root: "javax_imageio_1.0"
assertNotNull(root);
assertEquals(IIOMetadataFormatImpl.standardMetadataFormatName, root.getNodeName());
assertEquals(6, root.getChildNodes().getLength());
// "Chroma"
Node chroma = root.getFirstChild();
assertEquals("Chroma", chroma.getNodeName());
assertEquals(3, chroma.getChildNodes().getLength());
Node colorSpaceType = chroma.getFirstChild();
assertEquals("ColorSpaceType", colorSpaceType.getNodeName());
assertEquals("YCbCr", ((Element) colorSpaceType).getAttribute("name"));
Node numChannels = colorSpaceType.getNextSibling();
assertEquals("NumChannels", numChannels.getNodeName());
assertEquals("3", ((Element) numChannels).getAttribute("value"));
Node blackIsZero = numChannels.getNextSibling();
assertEquals("BlackIsZero", blackIsZero.getNodeName());
assertEquals(0, blackIsZero.getAttributes().getLength());
// "Compression"
Node compression = chroma.getNextSibling();
assertEquals("Compression", compression.getNodeName());
assertEquals(2, compression.getChildNodes().getLength());
Node compressionTypeName = compression.getFirstChild();
assertEquals("CompressionTypeName", compressionTypeName.getNodeName());
assertEquals("Old JPEG", ((Element) compressionTypeName).getAttribute("value"));
Node lossless = compressionTypeName.getNextSibling();
assertEquals("Lossless", lossless.getNodeName());
assertEquals("FALSE", ((Element) lossless).getAttribute("value"));
// "Data"
Node data = compression.getNextSibling();
assertEquals("Data", data.getNodeName());
assertEquals(4, data.getChildNodes().getLength());
Node planarConfiguration = data.getFirstChild();
assertEquals("PlanarConfiguration", planarConfiguration.getNodeName());
assertEquals("PixelInterleaved", ((Element) planarConfiguration).getAttribute("value"));
Node sampleFormat = planarConfiguration.getNextSibling();
assertEquals("SampleFormat", sampleFormat.getNodeName());
assertEquals("UnsignedIntegral", ((Element) sampleFormat).getAttribute("value"));
Node bitsPerSample = sampleFormat.getNextSibling();
assertEquals("BitsPerSample", bitsPerSample.getNodeName());
assertEquals("8 8 8", ((Element) bitsPerSample).getAttribute("value"));
Node sampleMSB = bitsPerSample.getNextSibling();
assertEquals("SampleMSB", sampleMSB.getNodeName());
assertEquals("0 0 0", ((Element) sampleMSB).getAttribute("value"));
// "Dimension"
Node dimension = data.getNextSibling();
assertEquals("Dimension", dimension.getNodeName());
assertEquals(3, dimension.getChildNodes().getLength());
Node pixelAspectRatio = dimension.getFirstChild();
assertEquals("PixelAspectRatio", pixelAspectRatio.getNodeName());
assertEquals("1.0", ((Element) pixelAspectRatio).getAttribute("value"));
Node horizontalPixelSize = pixelAspectRatio.getNextSibling();
assertEquals("HorizontalPixelSize", horizontalPixelSize.getNodeName());
assertEquals("0.254", ((Element) horizontalPixelSize).getAttribute("value"));
Node verticalPixelSize = horizontalPixelSize.getNextSibling();
assertEquals("VerticalPixelSize", verticalPixelSize.getNodeName());
assertEquals("0.254", ((Element) verticalPixelSize).getAttribute("value"));
// "Document"
Node document = dimension.getNextSibling();
assertEquals("Document", document.getNodeName());
assertEquals(1, document.getChildNodes().getLength());
Node formatVersion = document.getFirstChild();
assertEquals("FormatVersion", formatVersion.getNodeName());
assertEquals("6.0", ((Element) formatVersion).getAttribute("value"));
// "Text"
Node text = document.getNextSibling();
assertEquals("Text", text.getNodeName());
assertEquals(1, text.getChildNodes().getLength());
// NOTE: Could be multiple "TextEntry" elements, with different "keyword" attributes
Node textEntry = text.getFirstChild();
assertEquals("TextEntry", textEntry.getNodeName());
assertEquals("Software", ((Element) textEntry).getAttribute("keyword"));
assertEquals("HP IL v1.1", ((Element) textEntry).getAttribute("value"));
}
@Test
public void testMetadataNativeFormat() throws IOException {
IIOMetadata metadata = createMetadata("/tiff/quad-lzw.tif");
Node root = metadata.getAsTree(TIFFMedataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME);
// Root: "com_sun_media_imageio_plugins_tiff_image_1.0"
assertNotNull(root);
assertEquals(TIFFMedataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME, root.getNodeName());
assertEquals(1, root.getChildNodes().getLength());
// IFD: "TIFFIFD"
Node ifd = root.getFirstChild();
assertEquals("TIFFIFD", ifd.getNodeName());
NodeList entries = ifd.getChildNodes();
assertEquals(13, entries.getLength());
String[] stripOffsets = {
"8", "150", "292", "434", "576", "718", "860", "1002", "1144", "1286",
"1793", "3823", "7580", "12225", "17737", "23978", "30534", "36863", "42975", "49180",
"55361", "61470", "67022", "71646", "74255", "75241", "75411", "75553", "75695", "75837",
"75979", "76316", "77899", "80466", "84068", "88471", "93623", "99105", "104483", "109663",
"114969", "120472", "126083", "131289", "135545", "138810", "140808", "141840", "141982", "142124",
"142266", "142408", "142615", "144074", "146327", "149721", "154066", "158927", "164022", "169217",
"174409", "179657", "185166", "190684", "196236", "201560", "206064", "209497", "211612", "212419",
"212561", "212703", "212845", "212987", "213129", "213271", "213413"
};
String[] stripByteCounts = {
"142", "142", "142", "142", "142", "142", "142", "142", "142", "507",
"2030", "3757", "4645", "5512", "6241", "6556", "6329", "6112", "6205", "6181",
"6109", "5552", "4624", "2609", "986", "170", "142", "142", "142", "142",
"337", "1583", "2567", "3602", "4403", "5152", "5482", "5378", "5180", "5306",
"5503", "5611", "5206", "4256", "3265", "1998", "1032", "142", "142", "142",
"142", "207", "1459", "2253", "3394", "4345", "4861", "5095", "5195", "5192",
"5248", "5509", "5518", "5552", "5324", "4504", "3433", "2115", "807", "142",
"142", "142", "142", "142", "142", "142", "128"
};
// The 13 entries
assertSingleNodeWithValue(entries, TIFF.TAG_IMAGE_WIDTH, TIFF.TYPE_SHORT, "512");
assertSingleNodeWithValue(entries, TIFF.TAG_IMAGE_HEIGHT, TIFF.TYPE_SHORT, "384");
assertSingleNodeWithValue(entries, TIFF.TAG_BITS_PER_SAMPLE, TIFF.TYPE_SHORT, "8", "8", "8");
assertSingleNodeWithValue(entries, TIFF.TAG_COMPRESSION, TIFF.TYPE_SHORT, "5");
assertSingleNodeWithValue(entries, TIFF.TAG_PHOTOMETRIC_INTERPRETATION, TIFF.TYPE_SHORT, "2");
assertSingleNodeWithValue(entries, TIFF.TAG_STRIP_OFFSETS, TIFF.TYPE_LONG, stripOffsets);
assertSingleNodeWithValue(entries, TIFF.TAG_SAMPLES_PER_PIXEL, TIFF.TYPE_SHORT, "3");
assertSingleNodeWithValue(entries, TIFF.TAG_ROWS_PER_STRIP, TIFF.TYPE_LONG, "5");
assertSingleNodeWithValue(entries, TIFF.TAG_STRIP_BYTE_COUNTS, TIFF.TYPE_LONG, stripByteCounts);
assertSingleNodeWithValue(entries, TIFF.TAG_PLANAR_CONFIGURATION, TIFF.TYPE_SHORT, "1");
assertSingleNodeWithValue(entries, TIFF.TAG_X_POSITION, TIFF.TYPE_RATIONAL, "0");
assertSingleNodeWithValue(entries, TIFF.TAG_Y_POSITION, TIFF.TYPE_RATIONAL, "0");
assertSingleNodeWithValue(entries, 32995, TIFF.TYPE_SHORT, "0"); // Matteing tag, obsoleted by ExtraSamples tag in TIFF 6.0
}
@Test
public void testTreeDetached() throws IOException {
IIOMetadata metadata = createMetadata("/tiff/sm_colors_tile.tif");
Node nativeTree = metadata.getAsTree(TIFFMedataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME);
assertNotNull(nativeTree);
Node nativeTree2 = metadata.getAsTree(TIFFMedataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME);
assertNotNull(nativeTree2);
assertNotSame(nativeTree, nativeTree2);
assertNodeEquals("Unmodified trees differs", nativeTree, nativeTree2); // Both not modified
// Modify one of the trees
Node ifdNode = nativeTree2.getFirstChild();
ifdNode.removeChild(ifdNode.getFirstChild());
IIOMetadataNode tiffField = new IIOMetadataNode("TIFFField");
ifdNode.appendChild(tiffField);
assertNodeNotEquals("Modified tree does not differ", nativeTree, nativeTree2);
}
@Test
public void testMergeTree() throws IOException {
TIFFImageMetadata metadata = (TIFFImageMetadata) createMetadata("/tiff/sm_colors_tile.tif");
String nativeFormat = TIFFMedataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME;
Node nativeTree = metadata.getAsTree(nativeFormat);
assertNotNull(nativeTree);
IIOMetadataNode newTree = new IIOMetadataNode("com_sun_media_imageio_plugins_tiff_image_1.0");
IIOMetadataNode ifdNode = new IIOMetadataNode("TIFFIFD");
newTree.appendChild(ifdNode);
createTIFFFieldNode(ifdNode, TIFF.TAG_RESOLUTION_UNIT, TIFF.TYPE_SHORT, TIFFBaseline.RESOLUTION_UNIT_DPI);
createTIFFFieldNode(ifdNode, TIFF.TAG_X_RESOLUTION, TIFF.TYPE_RATIONAL, new Rational(300));
createTIFFFieldNode(ifdNode, TIFF.TAG_Y_RESOLUTION, TIFF.TYPE_RATIONAL, new Rational(30001, 100));
metadata.mergeTree(nativeFormat, newTree);
Directory ifd = metadata.getIFD();
assertNotNull(ifd.getEntryById(TIFF.TAG_X_RESOLUTION));
assertEquals(new Rational(300), ifd.getEntryById(TIFF.TAG_X_RESOLUTION).getValue());
assertNotNull(ifd.getEntryById(TIFF.TAG_Y_RESOLUTION));
assertEquals(new Rational(30001, 100), ifd.getEntryById(TIFF.TAG_Y_RESOLUTION).getValue());
assertNotNull(ifd.getEntryById(TIFF.TAG_RESOLUTION_UNIT));
assertEquals(TIFFBaseline.RESOLUTION_UNIT_DPI, ((Number) ifd.getEntryById(TIFF.TAG_RESOLUTION_UNIT).getValue()).intValue());
Node mergedTree = metadata.getAsTree(nativeFormat);
NodeList fields = mergedTree.getFirstChild().getChildNodes();
// Validate there's one and only one resolution unit, x res and y res
// Validate resolution unit == 1, x res & y res
assertSingleNodeWithValue(fields, TIFF.TAG_RESOLUTION_UNIT, TIFF.TYPE_SHORT, String.valueOf(TIFFBaseline.RESOLUTION_UNIT_DPI));
assertSingleNodeWithValue(fields, TIFF.TAG_X_RESOLUTION, TIFF.TYPE_RATIONAL, "300");
assertSingleNodeWithValue(fields, TIFF.TAG_Y_RESOLUTION, TIFF.TYPE_RATIONAL, "30001/100");
}
@Test
public void testMergeTreeStandardFormat() throws IOException {
TIFFImageMetadata metadata = (TIFFImageMetadata) createMetadata("/tiff/zackthecat.tif");
String standardFormat = IIOMetadataFormatImpl.standardMetadataFormatName;
Node standardTree = metadata.getAsTree(standardFormat);
assertNotNull(standardTree);
IIOMetadataNode newTree = new IIOMetadataNode(standardFormat);
IIOMetadataNode dimensionNode = new IIOMetadataNode("Dimension");
newTree.appendChild(dimensionNode);
IIOMetadataNode horizontalPixelSize = new IIOMetadataNode("HorizontalPixelSize");
dimensionNode.appendChild(horizontalPixelSize);
horizontalPixelSize.setAttribute("value", String.valueOf(300 / 25.4));
IIOMetadataNode verticalPixelSize = new IIOMetadataNode("VerticalPixelSize");
dimensionNode.appendChild(verticalPixelSize);
verticalPixelSize.setAttribute("value", String.valueOf(300 / 25.4));
metadata.mergeTree(standardFormat, newTree);
Directory ifd = metadata.getIFD();
assertNotNull(ifd.getEntryById(TIFF.TAG_X_RESOLUTION));
assertEquals(new Rational(300), ifd.getEntryById(TIFF.TAG_X_RESOLUTION).getValue());
assertNotNull(ifd.getEntryById(TIFF.TAG_Y_RESOLUTION));
assertEquals(new Rational(300), ifd.getEntryById(TIFF.TAG_Y_RESOLUTION).getValue());
// Should keep DPI as unit
assertNotNull(ifd.getEntryById(TIFF.TAG_RESOLUTION_UNIT));
assertEquals(TIFFBaseline.RESOLUTION_UNIT_DPI, ((Number) ifd.getEntryById(TIFF.TAG_RESOLUTION_UNIT).getValue()).intValue());
}
@Test
public void testMergeTreeStandardFormatAspectOnly() throws IOException {
TIFFImageMetadata metadata = (TIFFImageMetadata) createMetadata("/tiff/sm_colors_tile.tif");
String standardFormat = IIOMetadataFormatImpl.standardMetadataFormatName;
Node standardTree = metadata.getAsTree(standardFormat);
assertNotNull(standardTree);
IIOMetadataNode newTree = new IIOMetadataNode(standardFormat);
IIOMetadataNode dimensionNode = new IIOMetadataNode("Dimension");
newTree.appendChild(dimensionNode);
IIOMetadataNode aspectRatio = new IIOMetadataNode("PixelAspectRatio");
dimensionNode.appendChild(aspectRatio);
aspectRatio.setAttribute("value", String.valueOf(3f / 2f));
metadata.mergeTree(standardFormat, newTree);
Directory ifd = metadata.getIFD();
assertNotNull(ifd.getEntryById(TIFF.TAG_X_RESOLUTION));
assertEquals(new Rational(3, 2), ifd.getEntryById(TIFF.TAG_X_RESOLUTION).getValue());
assertNotNull(ifd.getEntryById(TIFF.TAG_Y_RESOLUTION));
assertEquals(new Rational(1), ifd.getEntryById(TIFF.TAG_Y_RESOLUTION).getValue());
assertNotNull(ifd.getEntryById(TIFF.TAG_RESOLUTION_UNIT));
assertEquals(TIFFBaseline.RESOLUTION_UNIT_NONE, ((Number) ifd.getEntryById(TIFF.TAG_RESOLUTION_UNIT).getValue()).intValue());
}
@Test(expected = IllegalArgumentException.class)
public void testMergeTreeUnsupportedFormat() throws IOException {
IIOMetadata metadata = createMetadata("/tiff/sm_colors_tile.tif");
String nativeFormat = "com_foo_bar_tiff_42";
metadata.mergeTree(nativeFormat, new IIOMetadataNode(nativeFormat));
}
@Test(expected = IIOInvalidTreeException.class)
public void testMergeTreeFormatMisMatch() throws IOException {
IIOMetadata metadata = createMetadata("/tiff/sm_colors_tile.tif");
String nativeFormat = TIFFMedataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME;
metadata.mergeTree(nativeFormat, new IIOMetadataNode("com_foo_bar_tiff_42"));
}
@Test(expected = IIOInvalidTreeException.class)
public void testMergeTreeInvalid() throws IOException {
IIOMetadata metadata = createMetadata("/tiff/sm_colors_tile.tif");
String nativeFormat = TIFFMedataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME;
metadata.mergeTree(nativeFormat, new IIOMetadataNode(nativeFormat)); // Requires at least one child node
}
// TODO: Test that failed merge leaves metadata unchanged
@Test
public void testSetFromTreeEmpty() throws IOException {
// Read from file, set empty to see that all is cleared
TIFFImageMetadata metadata = (TIFFImageMetadata) createMetadata("/tiff/sm_colors_tile.tif");
String nativeFormat = TIFFMedataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME;
IIOMetadataNode root = new IIOMetadataNode(nativeFormat);
root.appendChild(new IIOMetadataNode("TIFFIFD"));
metadata.setFromTree(nativeFormat, root);
Directory ifd = metadata.getIFD();
assertNotNull(ifd);
assertEquals(0, ifd.size());
Node tree = metadata.getAsTree(nativeFormat);
assertNotNull(tree);
assertNotNull(tree.getFirstChild());
assertEquals(1, tree.getChildNodes().getLength());
}
@Test
public void testSetFromTree() throws IOException {
String softwareString = "12M UberTIFF 1.0";
TIFFImageMetadata metadata = new TIFFImageMetadata(Collections.<Entry>emptySet());
String nativeFormat = TIFFMedataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME;
IIOMetadataNode root = new IIOMetadataNode(nativeFormat);
IIOMetadataNode ifdNode = new IIOMetadataNode("TIFFIFD");
root.appendChild(ifdNode);
createTIFFFieldNode(ifdNode, TIFF.TAG_SOFTWARE, TIFF.TYPE_ASCII, softwareString);
metadata.setFromTree(nativeFormat, root);
Directory ifd = metadata.getIFD();
assertNotNull(ifd);
assertEquals(1, ifd.size());
assertNotNull(ifd.getEntryById(TIFF.TAG_SOFTWARE));
assertEquals(softwareString, ifd.getEntryById(TIFF.TAG_SOFTWARE).getValue());
Node tree = metadata.getAsTree(nativeFormat);
assertNotNull(tree);
assertNotNull(tree.getFirstChild());
assertEquals(1, tree.getChildNodes().getLength());
}
@Test
public void testSetFromTreeStandardFormat() throws IOException {
String softwareString = "12M UberTIFF 1.0";
String copyrightString = "Copyright (C) TwelveMonkeys, 2015";
TIFFImageMetadata metadata = new TIFFImageMetadata(Collections.<Entry>emptySet());
String standardFormat = IIOMetadataFormatImpl.standardMetadataFormatName;
IIOMetadataNode root = new IIOMetadataNode(standardFormat);
IIOMetadataNode textNode = new IIOMetadataNode("Text");
root.appendChild(textNode);
IIOMetadataNode textEntry = new IIOMetadataNode("TextEntry");
textNode.appendChild(textEntry);
textEntry.setAttribute("keyword", "SOFTWARE"); // Spelling should not matter
textEntry.setAttribute("value", softwareString);
textEntry = new IIOMetadataNode("TextEntry");
textNode.appendChild(textEntry);
textEntry.setAttribute("keyword", "copyright"); // Spelling should not matter
textEntry.setAttribute("value", copyrightString);
metadata.setFromTree(standardFormat, root);
Directory ifd = metadata.getIFD();
assertNotNull(ifd);
assertEquals(2, ifd.size());
assertNotNull(ifd.getEntryById(TIFF.TAG_SOFTWARE));
assertEquals(softwareString, ifd.getEntryById(TIFF.TAG_SOFTWARE).getValue());
assertNotNull(ifd.getEntryById(TIFF.TAG_COPYRIGHT));
assertEquals(copyrightString, ifd.getEntryById(TIFF.TAG_COPYRIGHT).getValue());
}
@Test(expected = IllegalArgumentException.class)
public void testSetFromTreeUnsupportedFormat() throws IOException {
IIOMetadata metadata = createMetadata("/tiff/sm_colors_tile.tif");
String nativeFormat = "com_foo_bar_tiff_42";
metadata.setFromTree(nativeFormat, new IIOMetadataNode(nativeFormat));
}
@Test(expected = IIOInvalidTreeException.class)
public void testSetFromTreeFormatMisMatch() throws IOException {
IIOMetadata metadata = createMetadata("/tiff/sm_colors_tile.tif");
String nativeFormat = TIFFMedataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME;
metadata.setFromTree(nativeFormat, new IIOMetadataNode("com_foo_bar_tiff_42"));
}
@Test(expected = IIOInvalidTreeException.class)
public void testSetFromTreeInvalid() throws IOException {
IIOMetadata metadata = createMetadata("/tiff/sm_colors_tile.tif");
String nativeFormat = TIFFMedataFormat.SUN_NATIVE_IMAGE_METADATA_FORMAT_NAME;
metadata.setFromTree(nativeFormat, new IIOMetadataNode(nativeFormat)); // Requires at least one child node
}
@Test
public void testStandardChromaSamplesPerPixel() {
Set<Entry> entries = new HashSet<>();
entries.add(new TIFFEntry(TIFF.TAG_PHOTOMETRIC_INTERPRETATION, TIFFBaseline.PHOTOMETRIC_RGB));
entries.add(new TIFFEntry(TIFF.TAG_SAMPLES_PER_PIXEL, 4));
entries.add(new TIFFEntry(TIFF.TAG_BITS_PER_SAMPLE, new int[] {8, 8, 8})); // This is incorrect, just making sure the correct value is selected
IIOMetadataNode chromaNode = new TIFFImageMetadata(entries).getStandardChromaNode();
assertNotNull(chromaNode);
IIOMetadataNode numChannels = (IIOMetadataNode) chromaNode.getElementsByTagName("NumChannels").item(0);
assertEquals("4", numChannels.getAttribute("value"));
}
@Test
public void testStandardChromaSamplesPerPixelFallbackBitsPerSample() {
Set<Entry> entries = new HashSet<>();
entries.add(new TIFFEntry(TIFF.TAG_PHOTOMETRIC_INTERPRETATION, TIFFBaseline.PHOTOMETRIC_RGB));
entries.add(new TIFFEntry(TIFF.TAG_BITS_PER_SAMPLE, new int[] {8, 8, 8}));
IIOMetadataNode chromaNode = new TIFFImageMetadata(entries).getStandardChromaNode();
assertNotNull(chromaNode);
IIOMetadataNode numChannels = (IIOMetadataNode) chromaNode.getElementsByTagName("NumChannels").item(0);
assertEquals("3", numChannels.getAttribute("value"));
}
@Test
public void testStandardChromaSamplesPerPixelFallbackDefault() {
Set<Entry> entries = new HashSet<>();
entries.add(new TIFFEntry(TIFF.TAG_PHOTOMETRIC_INTERPRETATION, TIFFBaseline.PHOTOMETRIC_BLACK_IS_ZERO));
IIOMetadataNode chromaNode = new TIFFImageMetadata(entries).getStandardChromaNode();
assertNotNull(chromaNode);
IIOMetadataNode numChannels = (IIOMetadataNode) chromaNode.getElementsByTagName("NumChannels").item(0);
assertEquals("1", numChannels.getAttribute("value"));
}
@Test
public void testStandardDataBitsPerSampleFallbackDefault() {
Set<Entry> entries = new HashSet<>();
entries.add(new TIFFEntry(TIFF.TAG_PHOTOMETRIC_INTERPRETATION, TIFFBaseline.PHOTOMETRIC_BLACK_IS_ZERO));
IIOMetadataNode dataNode = new TIFFImageMetadata(entries).getStandardDataNode();
assertNotNull(dataNode);
IIOMetadataNode numChannels = (IIOMetadataNode) dataNode.getElementsByTagName("BitsPerSample").item(0);
assertEquals("1", numChannels.getAttribute("value"));
}
@Test
public void testStandardNodeSamplesPerPixelFallbackDefault() {
Set<Entry> entries = new HashSet<>();
entries.add(new TIFFEntry(TIFF.TAG_PHOTOMETRIC_INTERPRETATION, TIFFBaseline.PHOTOMETRIC_RGB));
// Just to make sure we haven't accidentally missed something
IIOMetadataNode standardTree = (IIOMetadataNode) new TIFFImageMetadata(entries).getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
assertNotNull(standardTree);
}
// TODO: Test that failed set leaves metadata unchanged
private void assertSingleNodeWithValue(final NodeList fields, final int tag, int type, final String... expectedValue) {
String tagNumber = String.valueOf(tag);
String typeName = StringUtil.capitalize(TIFF.TYPE_NAMES[type].toLowerCase());
boolean foundTag = false;
for (int i = 0; i < fields.getLength(); i++) {
Element field = (Element) fields.item(i);
if (tagNumber.equals(field.getAttribute("number"))) {
assertFalse("Duplicate tag " + tagNumber + " found", foundTag);
assertEquals(1, field.getChildNodes().getLength());
Node containerNode = field.getFirstChild();
assertEquals("TIFF" + typeName + "s", containerNode.getNodeName());
NodeList valueNodes = containerNode.getChildNodes();
assertEquals("Unexpected number of values for tag " + tagNumber, expectedValue.length, valueNodes.getLength());
for (int j = 0; j < expectedValue.length; j++) {
Element valueNode = (Element) valueNodes.item(j);
assertEquals("TIFF" + typeName, valueNode.getNodeName());
assertEquals("Unexpected tag " + tagNumber + " value", expectedValue[j], valueNode.getAttribute("value"));
}
foundTag = true;
}
}
assertTrue("No tag " + tagNumber + " found", foundTag);
}
static void createTIFFFieldNode(final IIOMetadataNode parentIFDNode, int tag, short type, Object value) {
IIOMetadataNode fieldNode = new IIOMetadataNode("TIFFField");
parentIFDNode.appendChild(fieldNode);
fieldNode.setAttribute("number", String.valueOf(tag));
switch (type) {
case TIFF.TYPE_ASCII:
createTIFFFieldContainerNode(fieldNode, "Ascii", value);
break;
case TIFF.TYPE_BYTE:
createTIFFFieldContainerNode(fieldNode, "Byte", value);
break;
case TIFF.TYPE_SHORT:
createTIFFFieldContainerNode(fieldNode, "Short", value);
break;
case TIFF.TYPE_RATIONAL:
createTIFFFieldContainerNode(fieldNode, "Rational", value);
break;
default:
throw new IllegalArgumentException("Unsupported type: " + type);
}
}
static void createTIFFFieldContainerNode(final IIOMetadataNode fieldNode, final String type, final Object value) {
IIOMetadataNode containerNode = new IIOMetadataNode("TIFF" + type + "s");
fieldNode.appendChild(containerNode);
IIOMetadataNode valueNode = new IIOMetadataNode("TIFF" + type);
valueNode.setAttribute("value", String.valueOf(value));
containerNode.appendChild(valueNode);
}
private void assertNodeNotEquals(final String message, final Node expected, final Node actual) {
// Lame, lazy implementation...
try {
assertNodeEquals(message, expected, actual);
}
catch (AssertionError ignore) {
return;
}
fail(message);
}
private void assertNodeEquals(final String message, final Node expected, final Node actual) {
assertEquals(message + " class differs", expected.getClass(), actual.getClass());
assertEquals(message, expected.getNodeValue(), actual.getNodeValue());
if (expected instanceof IIOMetadataNode) {
IIOMetadataNode expectedIIO = (IIOMetadataNode) expected;
IIOMetadataNode actualIIO = (IIOMetadataNode) actual;
assertEquals(message, expectedIIO.getUserObject(), actualIIO.getUserObject());
}
NodeList expectedChildNodes = expected.getChildNodes();
NodeList actualChildNodes = actual.getChildNodes();
assertEquals(message + " child length differs: " + toString(expectedChildNodes) + " != " + toString(actualChildNodes),
expectedChildNodes.getLength(), actualChildNodes.getLength());
for (int i = 0; i < expectedChildNodes.getLength(); i++) {
Node expectedChild = expectedChildNodes.item(i);
Node actualChild = actualChildNodes.item(i);
assertEquals(message + " node name differs", expectedChild.getLocalName(), actualChild.getLocalName());
assertNodeEquals(message + "/" + expectedChild.getLocalName(), expectedChild, actualChild);
}
}
private String toString(final NodeList list) {
if (list.getLength() == 0) {
return "[]";
}
StringBuilder builder = new StringBuilder("[");
for (int i = 0; i < list.getLength(); i++) {
if (i > 0) {
builder.append(", ");
}
Node node = list.item(i);
builder.append(node.getLocalName());
}
builder.append("]");
return builder.toString();
}
}
| bsd-3-clause |
xnlogic/pacer | ext/src/test/java/com/xnlogic/pacer/pipes/BlackboxPipelineTest.java | 1047 | package com.xnlogic.pacer.pipes;
import static org.junit.Assert.*;
import org.junit.Test;
import com.tinkerpop.pipes.Pipe;
import com.tinkerpop.pipes.IdentityPipe;
import java.util.Arrays;
import java.util.List;
import com.xnlogic.pacer.pipes.BlackboxPipeline;
public class BlackboxPipelineTest {
@Test
public void resetTest() {
List<String> data = Arrays.asList("Pacer", "Pipes", "Test");
Pipe<String, String> pipe1 = new IdentityPipe<String>();
Pipe<String, String> pipe2 = new IdentityPipe<String>();
BlackboxPipeline<String, String> blackboxPipeline = new BlackboxPipeline<String, String>(pipe1, pipe2);
blackboxPipeline.setStarts(data);
pipe2.setStarts(data);
int count = 0;
while (blackboxPipeline.hasNext()) {
assertEquals(blackboxPipeline.next(), data.get(count));
blackboxPipeline.reset();
count++;
}
assertEquals(count, data.size());
assertFalse(blackboxPipeline.hasNext());
}
}
| bsd-3-clause |
NCIP/camod | software/camod/test/unit/web/search/SearchPopulateTransIntTest.java | 6761 | /*L
* Copyright SAIC
* Copyright SAIC-Frederick
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/camod/LICENSE.txt for details.
*/
package unit.web.search;
import gov.nih.nci.camod.webapp.form.TransientInterferenceForm;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.naming.NamingException;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebResponse;
import junit.framework.Test;
import junit.framework.TestSuite;
import unit.web.base.BaseModelNeededTest;
import unit.web.util.TestUtil;
public class SearchPopulateTransIntTest extends BaseModelNeededTest
{
public SearchPopulateTransIntTest(String arg0)
{
super(arg0);
}
protected void setUp() throws Exception
{
try {
setupJNDIdatasource();
} catch (NamingException ex) {
System.out.println("NamingException in datasouuce binding: " + SearchPopulateTransIntTest.class.getName());
}
ResourceBundle theBundle = ResourceBundle.getBundle("test");
String theUsername = theBundle.getString("username");
String thePassword = theBundle.getString("password");
loginToApplication(theUsername, thePassword);
createModel();
}
protected void tearDown() throws Exception
{
deleteModel();
logoutOfApplication();
}
public static Test suite()
{
TestSuite suite = new TestSuite(SearchPopulateTransIntTest.class);
return suite;
}
public void testPopulateMorpholino() throws Exception
{
navigateToModelForEditing(myModelName);
System.out.println("myModelName: " + myModelName);
// Adding a Morpholino
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "Enter Morpholino");
System.out.println("theLink: " + theLink);
assertNotNull("Unable to find link to enter a Morpholino", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("if source is not listed");
System.out.println("here: " );
WebForm theWebForm = theCurrentPage.getFormWithName("transientInterferenceForm");
TransientInterferenceForm theForm = new TransientInterferenceForm();
theForm.setSource("Gene Tool");
theForm.setTargetedRegion("TESTINGTARGETEDREGION");
List<String> theParamsToIgnore = new ArrayList<String>();
/* Add parameters found on submit screen but not displayed on search screen */
List<String> theParamsToSkip = new ArrayList<String>();
TestUtil.setRandomValues(theForm, theWebForm, false, theParamsToIgnore);
TestUtil.setValuesOnForm(theForm, theWebForm);
theCurrentPage = theWebForm.submit();
assertCurrentPageContains("You have successfully added a Transient Interference to this model!");
// Verify that populate method returns complete and correct data
navigateToModelForEditing(myModelName);
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "TESTINGTARGETEDREGION");
assertNotNull("Unable to find link to verify Morpholino", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("if source is not listed");
theWebForm = theCurrentPage.getFormWithName("transientInterferenceForm");
//Add parameters found behind but not populate screen
theParamsToSkip = new ArrayList<String>();
theParamsToSkip.add("aTransIntID");
theParamsToSkip.add("aConceptCode");
theParamsToSkip.add("otherDeliveryMethod");
// shows up as a match but maybe font is not read
theParamsToSkip.add("sequenceDirection");
theParamsToSkip.add("otherSource");
theParamsToSkip.add("submitAction");
theParamsToSkip.add("otherVisualLigand");
verifyValuesOnPopulatePage(theWebForm, theParamsToSkip);
}
public void testPopulateSirna() throws Exception
{
navigateToModelForEditing(myModelName);
System.out.println("myModelName: " + myModelName);
// Adding a Morpholino
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "Enter SiRNA");
System.out.println("theLink: " + theLink);
assertNotNull("Unable to find link to enter a SiRNA", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("if source is not listed");
System.out.println("here: " );
WebForm theWebForm = theCurrentPage.getFormWithName("transientInterferenceForm");
TransientInterferenceForm theForm = new TransientInterferenceForm();
theForm.setSource("Amaxa");
theForm.setTargetedRegion("TESTINGTARGETEDREGION");
List<String> theParamsToIgnore = new ArrayList<String>();
// Add parameters found on submit screen but not displayed on search screen
List<String> theParamsToSkip = new ArrayList<String>();
TestUtil.setRandomValues(theForm, theWebForm, false, theParamsToIgnore);
TestUtil.setValuesOnForm(theForm, theWebForm);
theCurrentPage = theWebForm.submit();
assertCurrentPageContains("You have successfully added a Transient Interference to this model! ");
// Verify that populate method returns complete and correct data
navigateToModelForEditing(myModelName);
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "TESTINGTARGETEDREGION");
assertNotNull("Unable to find link to verify SiRNA", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("if source is not listed");
theWebForm = theCurrentPage.getFormWithName("transientInterferenceForm");
//Add parameters found behind but not populate screen
theParamsToSkip = new ArrayList<String>();
theParamsToSkip.add("aTransIntID");
theParamsToSkip.add("aConceptCode");
theParamsToSkip.add("otherDeliveryMethod");
// shows up as a match but maybe font is not read
theParamsToSkip.add("sequenceDirection");
theParamsToSkip.add("otherSource");
theParamsToSkip.add("submitAction");
theParamsToSkip.add("otherVisualLigand");
verifyValuesOnPopulatePage(theWebForm, theParamsToSkip);
}
public void testSearchForMorpholino() throws Exception {
}
public void testSearchForSirna() throws Exception {
}
}
| bsd-3-clause |
AurionProject/Aurion | Product/Production/Services/DocumentSubmissionCore/src/test/java/gov/hhs/fha/nhinc/docsubmission/outbound/deferred/response/StandardOutboundDocSubmissionDeferredResponseTest.java | 13143 | /*
* Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services.
* 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 United States Government 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 UNITED STATES GOVERNMENT 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 gov.hhs.fha.nhinc.docsubmission.outbound.deferred.response;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import gov.hhs.fha.nhinc.aspect.OutboundProcessingEvent;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.HomeCommunityType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetCommunitiesType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetCommunityType;
import gov.hhs.fha.nhinc.common.nhinccommonentity.RespondingGatewayProvideAndRegisterDocumentSetSecuredResponseRequestType;
import gov.hhs.fha.nhinc.docsubmission.XDRAuditLogger;
import gov.hhs.fha.nhinc.docsubmission.XDRPolicyChecker;
import gov.hhs.fha.nhinc.docsubmission.aspect.DeferredResponseDescriptionBuilder;
import gov.hhs.fha.nhinc.docsubmission.aspect.DocSubmissionArgTransformerBuilder;
import gov.hhs.fha.nhinc.docsubmission.entity.deferred.response.OutboundDocSubmissionDeferredResponseDelegate;
import gov.hhs.fha.nhinc.docsubmission.entity.deferred.response.OutboundDocSubmissionDeferredResponseOrchestratable;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.transform.policy.SubjectHelper;
import gov.hhs.healthit.nhin.XDRAcknowledgementType;
import java.lang.reflect.Method;
import oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Test;
/**
* @author akong
*
*/
public class StandardOutboundDocSubmissionDeferredResponseTest {
protected Mockery context = new JUnit4Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
final XDRAuditLogger mockXDRLog = context.mock(XDRAuditLogger.class);
final XDRPolicyChecker mockPolicyCheck = context.mock(XDRPolicyChecker.class);
final SubjectHelper mockSubjectHelper = context.mock(SubjectHelper.class);
final OutboundDocSubmissionDeferredResponseDelegate mockDelegate = context
.mock(OutboundDocSubmissionDeferredResponseDelegate.class);
@Test
public void testProvideAndRegisterDocumentSetB() {
expect2MockAudits();
setMockPolicyCheck(true);
setMockSubjectHelperToReturnValidHcid();
setMockDelegateToReturnValidResponse();
XDRAcknowledgementType response = runProvideAndRegisterDocumentSetBAsyncRequest();
context.assertIsSatisfied();
assertNotNull(response);
assertEquals(NhincConstants.XDR_RESP_ACK_STATUS_MSG, response.getMessage().getStatus());
}
@Test
public void testProvideAndRegisterDocumentSetB_policyFailure() {
expect2MockAudits();
setMockPolicyCheck(false);
setMockSubjectHelperToReturnValidHcid();
XDRAcknowledgementType response = runProvideAndRegisterDocumentSetBAsyncRequest();
context.assertIsSatisfied();
assertNotNull(response);
assertEquals(NhincConstants.XDR_ACK_FAILURE_STATUS_MSG, response.getMessage().getStatus());
}
@Test
public void testProvideAndRegisterDocumentSetB_emptyTargets() {
expect2MockAudits();
XDRAcknowledgementType response = runProvideAndRegisterDocumentSetBAsyncRequest_emptyTargets();
context.assertIsSatisfied();
assertNotNull(response);
assertEquals(NhincConstants.XDR_ACK_FAILURE_STATUS_MSG, response.getMessage().getStatus());
}
@Test
public void testHasNhinTargetHomeCommunityId() {
StandardOutboundDocSubmissionDeferredResponse entityOrch = createEntityDocSubmissionDeferredResponseOrchImpl();
boolean hasTargets = entityOrch.hasNhinTargetHomeCommunityId(null);
assertFalse(hasTargets);
RespondingGatewayProvideAndRegisterDocumentSetSecuredResponseRequestType request = new RespondingGatewayProvideAndRegisterDocumentSetSecuredResponseRequestType();
hasTargets = entityOrch.hasNhinTargetHomeCommunityId(request);
assertFalse(hasTargets);
NhinTargetCommunitiesType targetCommunities = new NhinTargetCommunitiesType();
request.setNhinTargetCommunities(targetCommunities);
hasTargets = entityOrch.hasNhinTargetHomeCommunityId(request);
assertFalse(hasTargets);
request.getNhinTargetCommunities().getNhinTargetCommunity().add(null);
request.setNhinTargetCommunities(targetCommunities);
hasTargets = entityOrch.hasNhinTargetHomeCommunityId(request);
assertFalse(hasTargets);
targetCommunities = createNhinTargetCommunitiesType();
request.setNhinTargetCommunities(targetCommunities);
hasTargets = entityOrch.hasNhinTargetHomeCommunityId(request);
assertTrue(hasTargets);
request.getNhinTargetCommunities().getNhinTargetCommunity().get(0).getHomeCommunity().setHomeCommunityId(null);
hasTargets = entityOrch.hasNhinTargetHomeCommunityId(request);
assertFalse(hasTargets);
request.getNhinTargetCommunities().getNhinTargetCommunity().get(0).setHomeCommunity(null);
hasTargets = entityOrch.hasNhinTargetHomeCommunityId(request);
assertFalse(hasTargets);
}
@Test
public void testGetters() {
StandardOutboundDocSubmissionDeferredResponse entityOrch = new StandardOutboundDocSubmissionDeferredResponse();
assertNotNull(entityOrch.getSubjectHelper());
assertNotNull(entityOrch.getXDRAuditLogger());
assertNotNull(entityOrch.getXDRPolicyChecker());
}
private XDRAcknowledgementType runProvideAndRegisterDocumentSetBAsyncRequest() {
RegistryResponseType request = new RegistryResponseType();
AssertionType assertion = new AssertionType();
NhinTargetCommunitiesType targets = createNhinTargetCommunitiesType();
StandardOutboundDocSubmissionDeferredResponse entityOrch = createEntityDocSubmissionDeferredResponseOrchImpl();
return entityOrch.provideAndRegisterDocumentSetBAsyncResponse(request, assertion, targets);
}
private XDRAcknowledgementType runProvideAndRegisterDocumentSetBAsyncRequest_emptyTargets() {
RegistryResponseType request = new RegistryResponseType();
AssertionType assertion = new AssertionType();
NhinTargetCommunitiesType targets = new NhinTargetCommunitiesType();
StandardOutboundDocSubmissionDeferredResponse entityOrch = createEntityDocSubmissionDeferredResponseOrchImpl();
return entityOrch.provideAndRegisterDocumentSetBAsyncResponse(request, assertion, targets);
}
private NhinTargetCommunitiesType createNhinTargetCommunitiesType() {
NhinTargetCommunityType target = new NhinTargetCommunityType();
HomeCommunityType homeCommunity = new HomeCommunityType();
homeCommunity.setHomeCommunityId("1.1");
target.setHomeCommunity(homeCommunity);
NhinTargetCommunitiesType targets = new NhinTargetCommunitiesType();
targets.getNhinTargetCommunity().add(target);
return targets;
}
private void expect2MockAudits() {
context.checking(new Expectations() {
{
oneOf(mockXDRLog).auditEntityXDRResponseRequest(
with(any(RespondingGatewayProvideAndRegisterDocumentSetSecuredResponseRequestType.class)),
with(any(AssertionType.class)), with(equal(NhincConstants.AUDIT_LOG_INBOUND_DIRECTION)));
oneOf(mockXDRLog).auditEntityAcknowledgement(with(any(XDRAcknowledgementType.class)),
with(any(AssertionType.class)), with(equal(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION)),
with(equal(NhincConstants.XDR_RESPONSE_ACTION)));
}
});
}
private void setMockPolicyCheck(final boolean allow) {
context.checking(new Expectations() {
{
oneOf(mockPolicyCheck).checkXDRResponsePolicy(with(any(RegistryResponseType.class)),
with(any(AssertionType.class)), with(any(String.class)), with(any(String.class)),
with(equal(NhincConstants.POLICYENGINE_OUTBOUND_DIRECTION)));
will(returnValue(allow));
}
});
}
private void setMockSubjectHelperToReturnValidHcid() {
context.checking(new Expectations() {
{
oneOf(mockSubjectHelper).determineSendingHomeCommunityId(with(any(HomeCommunityType.class)),
with(any(AssertionType.class)));
will(returnValue("2.2"));
}
});
}
private void setMockDelegateToReturnValidResponse() {
context.checking(new Expectations() {
{
oneOf(mockDelegate).process(with(any(OutboundDocSubmissionDeferredResponseOrchestratable.class)));
will(returnValue(createOutboundDocSubmissionDeferredResponseOrchestratable()));
}
});
}
private OutboundDocSubmissionDeferredResponseOrchestratable createOutboundDocSubmissionDeferredResponseOrchestratable() {
RegistryResponseType regResponse = new RegistryResponseType();
regResponse.setStatus(NhincConstants.XDR_RESP_ACK_STATUS_MSG);
XDRAcknowledgementType response = new XDRAcknowledgementType();
response.setMessage(regResponse);
OutboundDocSubmissionDeferredResponseOrchestratable orchestratable = new OutboundDocSubmissionDeferredResponseOrchestratable(
null);
orchestratable.setResponse(response);
return orchestratable;
}
private StandardOutboundDocSubmissionDeferredResponse createEntityDocSubmissionDeferredResponseOrchImpl() {
return new StandardOutboundDocSubmissionDeferredResponse() {
protected XDRAuditLogger getXDRAuditLogger() {
return mockXDRLog;
}
protected XDRPolicyChecker getXDRPolicyChecker() {
return mockPolicyCheck;
}
protected SubjectHelper getSubjectHelper() {
return mockSubjectHelper;
}
protected OutboundDocSubmissionDeferredResponseDelegate getOutboundDocSubmissionDeferredResponseDelegate() {
return mockDelegate;
}
protected boolean isAuditEnabled(String propertyFile, String propertyName) {
return true;
}
};
}
@Test
public void hasOutboundProcessingEvent() throws Exception {
Class<StandardOutboundDocSubmissionDeferredResponse> clazz = StandardOutboundDocSubmissionDeferredResponse.class;
Method method = clazz.getMethod("provideAndRegisterDocumentSetBAsyncResponse", RegistryResponseType.class,
AssertionType.class, NhinTargetCommunitiesType.class);
OutboundProcessingEvent annotation = method.getAnnotation(OutboundProcessingEvent.class);
assertNotNull(annotation);
assertEquals(DeferredResponseDescriptionBuilder.class, annotation.beforeBuilder());
assertEquals(DocSubmissionArgTransformerBuilder.class, annotation.afterReturningBuilder());
assertEquals("Document Submission Deferred Response", annotation.serviceType());
assertEquals("", annotation.version());
}
}
| bsd-3-clause |
NCIP/calims | calims2-api/test/unit/java/gov/nih/nci/calims2/business/administration/role/RoleValidatorMockup.java | 1799 | /*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.business.administration.role;
import java.util.HashSet;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.metadata.BeanDescriptor;
import gov.nih.nci.calims2.business.util.validation.ConstraintViolationImpl;
import gov.nih.nci.calims2.domain.administration.Role;
/**
* @author katariap
*
*/
public class RoleValidatorMockup implements Validator {
private Role testEntity;
/**
* @return testEntity The entity to return.
*/
public Role getEntity() {
return testEntity;
}
/**
* {@inheritDoc}
*/
public BeanDescriptor getConstraintsForClass(Class<?> clazz) {
return null;
}
/**
* {@inheritDoc}
*/
public <T> T unwrap(Class<T> word) {
return null;
}
/**
* {@inheritDoc}
*/
public <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) {
testEntity = (Role) object;
Set<ConstraintViolation<T>> violations = new HashSet<ConstraintViolation<T>>();
if (testEntity.getName() == null) {
ConstraintViolationImpl<T> violation = new ConstraintViolationImpl<T>();
violation.setMessage("Name required.");
violations.add(violation);
}
return violations;
}
/**
* {@inheritDoc}
*/
public <T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyName, Class<?>... groups) {
return null;
}
/**
* {@inheritDoc}
*/
public <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) {
return null;
}
}
| bsd-3-clause |
FIRSTTeam0322/FRCTeam0322JavaCBR2015 | src/org/usfirst/frc322/FRCTeam0322JavaCBR2015/commands/LeftArmRotator.java | 1731 | // RobotBuilder Version: 1.5
//
// 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 the future.
package org.usfirst.frc322.FRCTeam0322JavaCBR2015.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc322.FRCTeam0322JavaCBR2015.Robot;
/**
*
*/
public class LeftArmRotator extends Command {
public LeftArmRotator() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
requires(Robot.leftArm);
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
Robot.leftArm.leftArmControl(Robot.oi.getManipulatorStick().getRawAxis(0));
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
Robot.leftArm.leftArmControl(0.0);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
end();
}
}
| bsd-3-clause |
levans/Open-Quark | src/CAL_Platform/src/org/openquark/cal/services/StringModuleSourceDefinition.java | 3276 | /*
* Copyright (c) 2007 BUSINESS OBJECTS SOFTWARE LIMITED
* 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 Business Objects 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.
*/
/*
* StringModuleSourceDefinition.java
* Created: Nov 24, 2005
* By: dmosimann
*/
package org.openquark.cal.services;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.openquark.cal.compiler.ModuleName;
import org.openquark.cal.compiler.ModuleSourceDefinition;
import org.openquark.util.TextEncodingUtilities;
/**
* A ModuleSourceDefinition that provides source from a string.
* @author David Mosimann
*/
public class StringModuleSourceDefinition extends ModuleSourceDefinition {
/** The text defining the module (includes imports, functions, data declarations, ...) */
private final String moduleDefinition;
/**
* Constructor for StringModuleSourceDefinition
* @param moduleName the name of the module which is defined in the given file.
* @param moduleDefinition The string from which the ModuleSourceDefinition will be read.
*/
public StringModuleSourceDefinition(ModuleName moduleName, String moduleDefinition) {
super(moduleName);
this.moduleDefinition = moduleDefinition;
}
/**
* {@inheritDoc}
*/
@Override
public InputStream getInputStream(Status status) {
return new ByteArrayInputStream(TextEncodingUtilities.getUTF8Bytes(moduleDefinition));
}
/**
* {@inheritDoc}
*/
@Override
public long getTimeStamp() {
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public String getDebugInfo() {
return "constructed prorgammatically via a source string";
}
}
| bsd-3-clause |
tivv/davepgjdbc | org/postgresql/core/v2/QueryExecutorImpl.java | 23752 | /*-------------------------------------------------------------------------
*
* Copyright (c) 2003-2011, PostgreSQL Global Development Group
* Copyright (c) 2004, Open Cloud Limited.
*
* IDENTIFICATION
* $PostgreSQL: pgjdbc/org/postgresql/core/v2/QueryExecutorImpl.java,v 1.23 2009/12/04 19:53:20 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core.v2;
import java.util.Vector;
import java.io.IOException;
import java.io.Writer;
import java.sql.*;
import org.postgresql.core.*;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.GT;
import org.postgresql.copy.CopyOperation;
/**
* QueryExecutor implementation for the V2 protocol.
*/
public class QueryExecutorImpl implements QueryExecutor {
public QueryExecutorImpl(ProtocolConnectionImpl protoConnection, PGStream pgStream, Logger logger) {
this.protoConnection = protoConnection;
this.pgStream = pgStream;
this.logger = logger;
}
//
// Query parsing
//
public Query createSimpleQuery(String sql) {
return new V2Query(sql, false, protoConnection);
}
public Query createParameterizedQuery(String sql) {
return new V2Query(sql, true, protoConnection);
}
//
// Fastpath
//
public ParameterList createFastpathParameters(int count) {
return new FastpathParameterList(count);
}
public synchronized byte[]
fastpathCall(int fnid, ParameterList parameters, boolean suppressBegin) throws SQLException {
if (protoConnection.getTransactionState() == ProtocolConnection.TRANSACTION_IDLE && !suppressBegin)
{
if (logger.logDebug())
logger.debug("Issuing BEGIN before fastpath call.");
ResultHandler handler = new ResultHandler() {
private boolean sawBegin = false;
private SQLException sqle = null;
public void handleResultRows(Query fromQuery, Field[] fields, Vector tuples, ResultCursor cursor) {
}
public void handleCommandStatus(String status, int updateCount, long insertOID) {
if (!sawBegin)
{
if (!status.equals("BEGIN"))
handleError(new PSQLException(GT.tr("Expected command status BEGIN, got {0}.", status),
PSQLState.PROTOCOL_VIOLATION));
sawBegin = true;
}
else
{
handleError(new PSQLException(GT.tr("Unexpected command status: {0}.", status),
PSQLState.PROTOCOL_VIOLATION));
}
}
public void handleWarning(SQLWarning warning) {
// we don't want to ignore warnings and it would be tricky
// to chain them back to the connection, so since we don't
// expect to get them in the first place, we just consider
// them errors.
handleError(warning);
}
public void handleError(SQLException error) {
if (sqle == null)
{
sqle = error;
}
else
{
sqle.setNextException(error);
}
}
public void handleCompletion() throws SQLException{
if (sqle != null)
throw sqle;
}
};
try
{
// Create and issue a dummy query to use the existing prefix infrastructure
V2Query query = (V2Query)createSimpleQuery("");
SimpleParameterList params = (SimpleParameterList)query.createParameterList();
sendQuery(query, params, "BEGIN");
processResults(query, handler, 0, 0);
}
catch (IOException ioe)
{
throw new PSQLException(GT.tr("An I/O error occured while sending to the backend."), PSQLState.CONNECTION_FAILURE, ioe);
}
}
try
{
sendFastpathCall(fnid, (FastpathParameterList)parameters);
return receiveFastpathResult();
}
catch (IOException ioe)
{
throw new PSQLException(GT.tr("An I/O error occured while sending to the backend."), PSQLState.CONNECTION_FAILURE, ioe);
}
}
private void sendFastpathCall(int fnid, FastpathParameterList params) throws IOException {
// Send call.
int count = params.getParameterCount();
if (logger.logDebug())
logger.debug(" FE=> FastpathCall(fnid=" + fnid + ",paramCount=" + count + ")");
pgStream.SendChar('F');
pgStream.SendChar(0);
pgStream.SendInteger4(fnid);
pgStream.SendInteger4(count);
for (int i = 1; i <= count; ++i)
params.writeV2FastpathValue(i, pgStream);
pgStream.flush();
}
public synchronized void processNotifies() throws SQLException {
// Asynchronous notifies only arrive when we are not in a transaction
if (protoConnection.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
return;
try {
while (pgStream.hasMessagePending()) {
int c = pgStream.ReceiveChar();
switch (c) {
case 'A': // Asynchronous Notify
receiveAsyncNotify();
break;
case 'E': // Error Message
throw receiveErrorMessage();
// break;
case 'N': // Error Notification
protoConnection.addWarning(receiveNotification());
break;
default:
throw new PSQLException(GT.tr("Unknown Response Type {0}.", new Character((char) c)), PSQLState.CONNECTION_FAILURE);
}
}
} catch (IOException ioe) {
throw new PSQLException(GT.tr("An I/O error occured while sending to the backend."), PSQLState.CONNECTION_FAILURE, ioe);
}
}
private byte[] receiveFastpathResult() throws IOException, SQLException {
SQLException error = null;
boolean endQuery = false;
byte[] result = null;
while (!endQuery)
{
int c = pgStream.ReceiveChar();
switch (c)
{
case 'A': // Asynchronous Notify
receiveAsyncNotify();
break;
case 'E': // Error Message
SQLException newError = receiveErrorMessage();
if (error == null)
error = newError;
else
error.setNextException(newError);
// keep processing
break;
case 'N': // Error Notification
protoConnection.addWarning(receiveNotification());
break;
case 'V': // Fastpath result
c = pgStream.ReceiveChar();
if (c == 'G')
{
if (logger.logDebug())
logger.debug(" <=BE FastpathResult");
// Result.
int len = pgStream.ReceiveInteger4();
result = pgStream.Receive(len);
c = pgStream.ReceiveChar();
}
else
{
if (logger.logDebug())
logger.debug(" <=BE FastpathVoidResult");
}
if (c != '0')
throw new PSQLException(GT.tr("Unknown Response Type {0}.", new Character((char) c)), PSQLState.CONNECTION_FAILURE);
break;
case 'Z':
if (logger.logDebug())
logger.debug(" <=BE ReadyForQuery");
endQuery = true;
break;
default:
throw new PSQLException(GT.tr("Unknown Response Type {0}.", new Character((char) c)), PSQLState.CONNECTION_FAILURE);
}
}
// did we get an error during this query?
if (error != null)
throw error;
return result;
}
//
// Query execution
//
public synchronized void execute(Query query,
ParameterList parameters,
ResultHandler handler,
int maxRows, int fetchSize, int flags)
throws SQLException
{
execute((V2Query)query, (SimpleParameterList)parameters, handler, maxRows, flags);
}
// Nothing special yet, just run the queries one at a time.
public synchronized void execute(Query[] queries,
ParameterList[] parameters,
ResultHandler handler,
int maxRows, int fetchSize, int flags)
throws SQLException
{
final ResultHandler delegateHandler = handler;
handler = new ResultHandler() {
public void handleResultRows(Query fromQuery, Field[] fields, Vector tuples, ResultCursor cursor) {
delegateHandler.handleResultRows(fromQuery, fields, tuples, cursor);
}
public void handleCommandStatus(String status, int updateCount, long insertOID) {
delegateHandler.handleCommandStatus(status, updateCount, insertOID);
}
public void handleWarning(SQLWarning warning) {
delegateHandler.handleWarning(warning);
}
public void handleError(SQLException error) {
delegateHandler.handleError(error);
}
public void handleCompletion() throws SQLException {
}
};
for (int i = 0; i < queries.length; ++i)
execute((V2Query)queries[i], (SimpleParameterList)parameters[i], handler, maxRows, flags);
delegateHandler.handleCompletion();
}
public void fetch(ResultCursor cursor, ResultHandler handler, int rows) throws SQLException {
throw org.postgresql.Driver.notImplemented(this.getClass(), "fetch(ResultCursor,ResultHandler,int)");
}
private void execute(V2Query query,
SimpleParameterList parameters,
ResultHandler handler,
int maxRows, int flags) throws SQLException
{
// The V2 protocol has no support for retrieving metadata
// without executing the whole query.
if ((flags & QueryExecutor.QUERY_DESCRIBE_ONLY) != 0)
return;
if (parameters == null)
parameters = (SimpleParameterList)query.createParameterList();
parameters.checkAllParametersSet();
String queryPrefix = null;
if (protoConnection.getTransactionState() == ProtocolConnection.TRANSACTION_IDLE &&
(flags & QueryExecutor.QUERY_SUPPRESS_BEGIN) == 0)
{
queryPrefix = "BEGIN;";
// Insert a handler that intercepts the BEGIN.
final ResultHandler delegateHandler = handler;
handler = new ResultHandler() {
private boolean sawBegin = false;
public void handleResultRows(Query fromQuery, Field[] fields, Vector tuples, ResultCursor cursor) {
if (sawBegin)
delegateHandler.handleResultRows(fromQuery, fields, tuples, cursor);
}
public void handleCommandStatus(String status, int updateCount, long insertOID) {
if (!sawBegin)
{
if (!status.equals("BEGIN"))
handleError(new PSQLException(GT.tr("Expected command status BEGIN, got {0}.", status),
PSQLState.PROTOCOL_VIOLATION));
sawBegin = true;
}
else
{
delegateHandler.handleCommandStatus(status, updateCount, insertOID);
}
}
public void handleWarning(SQLWarning warning) {
delegateHandler.handleWarning(warning);
}
public void handleError(SQLException error) {
delegateHandler.handleError(error);
}
public void handleCompletion() throws SQLException{
delegateHandler.handleCompletion();
}
};
}
try
{
sendQuery(query, parameters, queryPrefix);
processResults(query, handler, maxRows, flags);
}
catch (IOException e)
{
protoConnection.close();
handler.handleError(new PSQLException(GT.tr("An I/O error occured while sending to the backend."), PSQLState.CONNECTION_FAILURE, e));
}
handler.handleCompletion();
}
/*
* Send a query to the backend.
*/
protected void sendQuery(V2Query query, SimpleParameterList params, String queryPrefix) throws IOException {
if (logger.logDebug())
logger.debug(" FE=> Query(\"" + (queryPrefix == null ? "" : queryPrefix) + query.toString(params) + "\")");
pgStream.SendChar('Q');
Writer encodingWriter = pgStream.getEncodingWriter();
if (queryPrefix != null)
encodingWriter.write(queryPrefix);
String[] fragments = query.getFragments();
for (int i = 0 ; i < fragments.length; ++i)
{
encodingWriter.write(fragments[i]);
if (i < params.getParameterCount())
params.writeV2Value(i + 1, encodingWriter);
}
encodingWriter.write(0);
pgStream.flush();
}
protected void processResults(Query originalQuery, ResultHandler handler, int maxRows, int flags) throws IOException {
boolean bothRowsAndStatus = (flags & QueryExecutor.QUERY_BOTH_ROWS_AND_STATUS) != 0;
Field[] fields = null;
Vector tuples = null;
boolean endQuery = false;
while (!endQuery)
{
int c = pgStream.ReceiveChar();
switch (c)
{
case 'A': // Asynchronous Notify
receiveAsyncNotify();
break;
case 'B': // Binary Data Transfer
{
if (fields == null)
throw new IOException("Data transfer before field metadata");
if (logger.logDebug())
logger.debug(" <=BE BinaryRow");
Object tuple = null;
try {
tuple = pgStream.ReceiveTupleV2(fields.length, true);
} catch(OutOfMemoryError oome) {
if (maxRows == 0 || tuples.size() < maxRows) {
handler.handleError(new PSQLException(GT.tr("Ran out of memory retrieving query results."), PSQLState.OUT_OF_MEMORY, oome));
}
}
for (int i = 0; i < fields.length; i++)
fields[i].setFormat(Field.BINARY_FORMAT); //Set the field to binary format
if (maxRows == 0 || tuples.size() < maxRows)
tuples.addElement(tuple);
}
break;
case 'C': // Command Status
String status = pgStream.ReceiveString();
if (logger.logDebug())
logger.debug(" <=BE CommandStatus(" + status + ")");
if (fields != null)
{
handler.handleResultRows(originalQuery, fields, tuples, null);
fields = null;
if (bothRowsAndStatus)
interpretCommandStatus(status, handler);
}
else
{
interpretCommandStatus(status, handler);
}
break;
case 'D': // Text Data Transfer
{
if (fields == null)
throw new IOException("Data transfer before field metadata");
if (logger.logDebug())
logger.debug(" <=BE DataRow");
Object tuple = null;
try {
tuple = pgStream.ReceiveTupleV2(fields.length, false);
} catch(OutOfMemoryError oome) {
if (maxRows == 0 || tuples.size() < maxRows)
handler.handleError(new PSQLException(GT.tr("Ran out of memory retrieving query results."), PSQLState.OUT_OF_MEMORY, oome));
}
if (maxRows == 0 || tuples.size() < maxRows)
tuples.addElement(tuple);
}
break;
case 'E': // Error Message
handler.handleError(receiveErrorMessage());
// keep processing
break;
case 'I': // Empty Query
if (logger.logDebug())
logger.debug(" <=BE EmptyQuery");
c = pgStream.ReceiveChar();
if (c != 0)
throw new IOException("Expected \\0 after EmptyQuery, got: " + c);
break;
case 'N': // Error Notification
handler.handleWarning(receiveNotification());
break;
case 'P': // Portal Name
String portalName = pgStream.ReceiveString();
if (logger.logDebug())
logger.debug(" <=BE PortalName(" + portalName + ")");
break;
case 'T': // MetaData Field Description
fields = receiveFields();
tuples = new Vector();
break;
case 'Z':
if (logger.logDebug())
logger.debug(" <=BE ReadyForQuery");
endQuery = true;
break;
default:
throw new IOException("Unexpected packet type: " + c);
}
}
}
/*
* Receive the field descriptions from the back end.
*/
private Field[] receiveFields() throws IOException
{
int size = pgStream.ReceiveInteger2();
Field[] fields = new Field[size];
if (logger.logDebug())
logger.debug(" <=BE RowDescription(" + fields.length + ")");
for (int i = 0; i < fields.length; i++)
{
String columnLabel = pgStream.ReceiveString();
int typeOid = pgStream.ReceiveInteger4();
int typeLength = pgStream.ReceiveInteger2();
int typeModifier = pgStream.ReceiveInteger4();
fields[i] = new Field(columnLabel, columnLabel, typeOid, typeLength, typeModifier, 0, 0);
}
return fields;
}
private void receiveAsyncNotify() throws IOException {
int pid = pgStream.ReceiveInteger4();
String msg = pgStream.ReceiveString();
if (logger.logDebug())
logger.debug(" <=BE AsyncNotify(pid=" + pid + ",msg=" + msg + ")");
protoConnection.addNotification(new org.postgresql.core.Notification(msg, pid));
}
private SQLException receiveErrorMessage() throws IOException {
String errorMsg = pgStream.ReceiveString().trim();
if (logger.logDebug())
logger.debug(" <=BE ErrorResponse(" + errorMsg + ")");
return new PSQLException(errorMsg, PSQLState.UNKNOWN_STATE);
}
private SQLWarning receiveNotification() throws IOException {
String warnMsg = pgStream.ReceiveString();
// Strip out the severity field so we have consistency with
// the V3 protocol. SQLWarning.getMessage should return just
// the actual message.
//
int severityMark = warnMsg.indexOf(":");
warnMsg = warnMsg.substring(severityMark+1).trim();
if (logger.logDebug())
logger.debug(" <=BE NoticeResponse(" + warnMsg + ")");
return new SQLWarning(warnMsg);
}
private void interpretCommandStatus(String status, ResultHandler handler) throws IOException {
int update_count = 0;
long insert_oid = 0;
if (status.equals("BEGIN"))
protoConnection.setTransactionState(ProtocolConnection.TRANSACTION_OPEN);
else if (status.equals("COMMIT") || status.equals("ROLLBACK"))
protoConnection.setTransactionState(ProtocolConnection.TRANSACTION_IDLE);
else if (status.startsWith("INSERT") || status.startsWith("UPDATE") || status.startsWith("DELETE") || status.startsWith("MOVE"))
{
try
{
update_count = Integer.parseInt(status.substring(1 + status.lastIndexOf(' ')));
if (status.startsWith("INSERT"))
insert_oid = Long.parseLong(status.substring(1 + status.indexOf(' '),
status.lastIndexOf(' ')));
}
catch (NumberFormatException nfe)
{
handler.handleError(new PSQLException(GT.tr("Unable to interpret the update count in command completion tag: {0}.", status), PSQLState.CONNECTION_FAILURE));
return ;
}
}
handler.handleCommandStatus(status, update_count, insert_oid);
}
private final ProtocolConnectionImpl protoConnection;
private final PGStream pgStream;
private final Logger logger;
public CopyOperation startCopy(String sql, boolean suppressBegin) throws SQLException {
throw new PSQLException(GT.tr("Copy not implemented for protocol version 2"), PSQLState.NOT_IMPLEMENTED);
}
}
| bsd-3-clause |
xebialabs/vijava | src/com/vmware/vim25/NotADirectory.java | 1814 | /*================================================================================
Copyright (c) 2012 Steve Jin. 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 (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class NotADirectory extends FileFault {
} | bsd-3-clause |
seanogden/wtf | bindings/java/org/wtf/client/Iterator.java | 2844 | /* Copyright (c) 2013, Cornell University
* 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 WTF 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.wtf.client;
import java.util.LinkedList;
import java.util.Queue;
public class Iterator implements Operation
{
private long ptr = 0;
private long reqid = 0;
private Client c;
private Queue<Object> backlogged;
public Iterator(Client c)
{
this.c = c;
this.backlogged = new LinkedList<Object>();
_create();
}
protected void finalize() throws Throwable
{
try
{
destroy();
}
finally
{
super.finalize();
}
}
public synchronized void destroy()
{
if (ptr != 0)
{
_destroy();
ptr = 0;
}
}
/* ctor/dtor */
private native void _create();
private native void _destroy();
/* Other calls */
public Boolean hasNext()
{
while (!finished() && backlogged.isEmpty())
{
this.c.waitFor(this.reqid);
}
return !backlogged.isEmpty();
}
public Object next()
{
return backlogged.poll();
}
private native boolean finished();
public native void callback();
/* Utilities */
private void appendBacklogged(Object ret)
{
backlogged.add(ret);
}
}
| bsd-3-clause |
aic-sri-international/aic-expresso | src/test/java/com/sri/ai/test/grinder/theory/base/AbstractTheoryTest.java | 1291 | package com.sri.ai.test.grinder.theory.base;
import static java.lang.Math.ceil;
import static java.lang.Math.round;
import java.util.Random;
import com.sri.ai.grinder.tester.TheoryTestingSupport;
public abstract class AbstractTheoryTest {
public AbstractTheoryTest() {
super();
}
/**
* Provides a way to regulate which seed to use (or none) for all tests at once.
* Default is none.
*/
protected Random makeRandom() {
return new Random();
}
/**
* Provides a way to regulate which theory to use.
* @return
*/
abstract protected TheoryTestingSupport makeTheoryTestingSupport();
/**
* Indicates whether correctness should be checked against brute-force methods when possible.
* Default is true.
* @return
*/
protected boolean getTestAgainstBruteForce() {
return true;
}
/**
* Provides a double to scale (up or down) an integer, rounding up.
* This is useful for scaling up or down the number of tests inherited from a super class,
* which need to go through {@link #scale(int)} for this to have an effect.
* Default is 1.
* @return
*/
protected double getScaleFactor() {
return 1;
}
/** Scales i according to {@link #getScaleFactor()}, rounding up. */
protected long scale(int i) {
return round(ceil(i*getScaleFactor()));
}
} | bsd-3-clause |
jdfekete/obvious | obvious-example/src/main/java/obvious/demo/scatterplotapp/ScatterplotApp.java | 6904 | /*
* Copyright (c) 2010, INRIA
* 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 INRIA 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 REGENTS 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 REGENTS AND 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 obvious.demo.scatterplotapp;
import java.awt.Dimension;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
import obvious.ObviousException;
import obvious.data.Schema;
import obvious.data.Table;
import obvious.impl.TupleImpl;
import obvious.ivtk.view.IvtkObviousView;
import obvious.prefuse.data.PrefuseObviousSchema;
import obvious.prefuse.data.PrefuseObviousTable;
import obvious.prefuse.view.PrefuseObviousControl;
import obvious.prefuse.view.PrefuseObviousView;
import obvious.prefuse.viz.PrefuseVisualizationFactory;
import obvious.prefuse.viz.util.PrefuseScatterPlotViz;
import obvious.viz.Visualization;
import obvious.viz.VisualizationFactory;
import prefuse.controls.DragControl;
import prefuse.controls.PanControl;
import prefuse.controls.ZoomControl;
/**
* A demo application for obvious.
* @author Hemery
*
*/
public final class ScatterplotApp {
/**
* Constructor.
*/
private ScatterplotApp() {
}
/**
* Main method.
* @param args arguments of the main
* @throws ObviousException if something bad happens
*/
public static void main(final String[] args) throws ObviousException {
final Schema schema = new PrefuseObviousSchema();
schema.addColumn("id", Integer.class, 0);
schema.addColumn("age", Integer.class, 0);
schema.addColumn("category", String.class, "unemployed");
final Table table = new PrefuseObviousTable(schema);
table.addRow(new TupleImpl(schema, new Object[] {1, 22, "worker"}));
table.addRow(new TupleImpl(schema, new Object[] {2, 60, "unemployed"}));
table.addRow(new TupleImpl(schema, new Object[] {3, 32, "worker"}));
table.addRow(new TupleImpl(schema, new Object[] {4, 20, "unemployed"}));
table.addRow(new TupleImpl(schema, new Object[] {5, 72, "worker"}));
table.addRow(new TupleImpl(schema, new Object[] {6, 40, "unemployed"}));
table.addRow(new TupleImpl(schema, new Object[] {7, 52, "worker"}));
table.addRow(new TupleImpl(schema, new Object[] {8, 35, "unemployed"}));
table.addRow(new TupleImpl(schema, new Object[] {9, 32, "worker"}));
table.addRow(new TupleImpl(schema, new Object[] {10, 44, "unemployed"}));
table.addRow(new TupleImpl(schema, new Object[] {11, 27, "worker"}));
table.addRow(new TupleImpl(schema, new Object[] {12, 38, "unemployed"}));
table.addRow(new TupleImpl(schema, new Object[] {13, 53, "worker"}));
table.addRow(new TupleImpl(schema, new Object[] {14, 49, "unemployed"}));
table.addRow(new TupleImpl(schema, new Object[] {15, 21, "worker"}));
table.addRow(new TupleImpl(schema, new Object[] {16, 36, "unemployed"}));
// Creating the parameter map for the monolithic object.
Map<String, Object> param = new HashMap<String, Object>();
param.put(PrefuseScatterPlotViz.X_AXIS, "id"); // name of the xfield
param.put(PrefuseScatterPlotViz.Y_AXIS, "age"); // name of the yfield
param.put(PrefuseScatterPlotViz.SHAPE, "category"); // category field
// Creating the parameter map for the monolithic object.
Map<String, Object> paramIvtk = new HashMap<String, Object>();
paramIvtk.put(PrefuseScatterPlotViz.X_AXIS, "id"); // name of the xfield
paramIvtk.put(PrefuseScatterPlotViz.Y_AXIS, "age"); // name of the yfield
paramIvtk.put(PrefuseScatterPlotViz.SHAPE, "category"); // category field
// Using the factory to build the visualization
System.setProperty("obvious.VisualizationFactory",
"obvious.prefuse.viz.PrefuseVisualizationFactory");
VisualizationFactory factory = PrefuseVisualizationFactory.getInstance();
Visualization vis =
factory.createVisualization(table, null, "scatterplot", param);
// In order to display, we have to call the underlying prefuse
// visualization.
// In a complete version of obvious, we don't need that step.
final prefuse.Visualization prefViz = (prefuse.Visualization)
vis.getUnderlyingImpl(prefuse.Visualization.class);
// Building the prefuse display.
PrefuseObviousView view = new PrefuseObviousView(
vis, null, "scatterplot", null);
view.addListener(new PrefuseObviousControl(new ZoomControl()));
view.addListener(new PrefuseObviousControl(new PanControl()));
view.addListener(new PrefuseObviousControl(new DragControl()));
IvtkObviousView view2 = new IvtkObviousView(
vis, null, "scatterplot", null);
Dimension minimumSize = new Dimension(0, 0);
view.getViewJComponent().setMinimumSize(minimumSize);
view2.getViewJComponent().setMinimumSize(minimumSize);
JFrame frame = new JFrame("Obvious : scatterplot demonstrator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSplitPane mainPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
JSplitPane scatterplotViews = new ScatterPlotViewsPanel(
view.getViewJComponent(), view2.getViewJComponent());
JSplitPane configurationPanel = new ConfigurationPanel(
table, frame, prefViz, view2.getViewJComponent());
mainPane.add(scatterplotViews, 0);
mainPane.add(configurationPanel, 1);
frame.add(mainPane);
frame.pack();
frame.setVisible(true);
prefViz.run("draw");
}
}
| bsd-3-clause |
wsldl123292/jodd | jodd-db/src/main/java/jodd/db/oom/sqlgen/chunks/ReferenceChunk.java | 2621 | // Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved.
package jodd.db.oom.sqlgen.chunks;
import jodd.db.oom.DbEntityColumnDescriptor;
import jodd.db.oom.DbEntityDescriptor;
import jodd.db.oom.sqlgen.DbSqlBuilderException;
import jodd.util.StringPool;
/**
* Resolves column and table references. Reference is given in format: <code>tableRef.propertyName</code>.
* The <code>propertyName</code> may be '+' (e.g. <code>tableRef.+</code>), indicating the identity columns.
* If property name is omitted (e.g. <code>tableRef</code>), only table name will be rendered.
* If table reference is omitted (e.g. <code>.propertyName</code>), only property i.e. column name
* will be rendered.
*/
public class ReferenceChunk extends SqlChunk {
protected final String tableRef;
protected final String columnRef;
protected final boolean onlyId;
public ReferenceChunk(String tableRef, String columnRef) {
this(tableRef, columnRef, false);
}
public ReferenceChunk(String tableRef, String columnRef, boolean onlyId) {
super(CHUNK_REFERENCE);
this.tableRef = tableRef;
this.columnRef = columnRef;
this.onlyId = onlyId;
}
public ReferenceChunk(String reference) {
super(CHUNK_REFERENCE);
int dotNdx = reference.indexOf('.');
if (dotNdx == -1) {
this.tableRef = reference;
this.columnRef = null;
this.onlyId = false;
} else {
String ref = reference.substring(0, dotNdx);
if (ref.length() == 0) {
ref = null;
}
this.tableRef = ref;
ref = reference.substring(dotNdx + 1);
if (ref.length() == 0) {
ref = null;
}
this.columnRef = ref;
onlyId = columnRef != null && columnRef.equals(StringPool.PLUS);
}
}
// ---------------------------------------------------------------- process
@Override
public void process(StringBuilder out) {
DbEntityDescriptor ded;
if (tableRef != null) {
ded = lookupTableRef(tableRef);
String tableName = resolveTable(tableRef, ded);
out.append(tableName);
} else {
ded = findColumnRef(columnRef);
}
if (onlyId == true) {
if (tableRef != null) {
out.append('.');
}
out.append(ded.getIdColumnName());
} else if (columnRef != null) {
DbEntityColumnDescriptor dec = ded.findByPropertyName(columnRef);
templateData.lastColumnDec = dec;
String column = dec == null ? null : dec.getColumnName();
//String column = ded.getColumnName(columnRef);
if (column == null) {
throw new DbSqlBuilderException("Invalid column reference: " + tableRef + '.' + columnRef);
}
if (tableRef != null) {
out.append('.');
}
out.append(column);
}
}
} | bsd-3-clause |
GalCohen/Chess | src/Chess.java | 12907 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
//TODO: check
//TODO: check mate
/**
*
* @author Gal Cohen
*
*/
public class Chess {
public static Board gameboard;
public static String currentLoc = null;
public static String newLoc = null;
public static String thirdArgument = null;
public static boolean askForDraw = false;
public static boolean whiteTurn = true;
public static boolean enPassant = false;
public static int enPassantX;
public static int enPassantY;
public static int enPassantToEliminateX;
public static int enPassantToEliminateY;
public static int enPassantCapturer1X;
public static int enPassantCapturer1Y;
public static int enPassantCapturer2X;
public static int enPassantCapturer2Y;
public static void main(String[] args) {
//initialize game
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = null;
initializeGame();
drawBoard();
//game loop
while (true){
//read the player's move
input = null;
try {
if (whiteTurn){
System.out.println("White player's turn:");
}else{
System.out.println("Black player's turn:");
}
boolean check = gameboard.detectCheck(whiteTurn);
if (check == true) {
if (whiteTurn) {
System.out.println("white king in check");
}else {
System.out.println("black king in check");
}
}
input = br.readLine();
parseInput(input);
drawBoard();
check = gameboard.detectCheck(!whiteTurn);
if (check == true) {
if (!whiteTurn) {
System.out.println("Checkmate");
System.out.println("Black wins");
}else {
System.out.println("Checkmate");
System.out.println("White wins");
}
System.exit(1);
}
if ( gameboard.checkStalemate( whiteTurn)){
System.out.println("Stalemate");
System.exit(1);
}
} catch (IOException e) {
System.out.println("Invalid input. Try again.");
}
}
//exit
}
public static void initializeGame(){
gameboard = new Board();
}
public static void resignGame(){
}
public static void gameDraw(){
}
public static void drawBoard(){
String[][] result = new String[8][8];
//make the tiles white or black
boolean white = true;
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
if (white){
result[i][j] = " |";
white = false;
}else{
result[i][j] = "##|";
white = true;
}
}
white = !(white);
}
// draw the pieces in the right locations
for (int y = 0; y < 8; y++){
for (int x = 0; x < 8; x++){
if ( gameboard.board[x][y] != null){
result[x][y] = gameboard.board[x][y].drawPiece() + "|";
}
}
}
//print out the whole board
System.out.println("_________________________");
for (int y = 0; y < 8; y++){
System.out.print("|");
for (int x = 0; x < 8; x++){
System.out.print(result[x][y]);
}
System.out.print(" " + (8-y));
System.out.println();
}
System.out.println("\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'\'");
System.out.println(" a b c d e f g h");
}
public static int fileToCoordinate(String file){
int result = (int) file.toLowerCase().charAt(0) - (int)('a');
return result;
}
public static int rankToCoordinate(String file){
int result = 7 - ((int) file.toLowerCase().charAt(1) - (int)('1'));
return result;
}
/* public static boolean parseMove(String input){
if (input.contains(" ") == false){
return false;
}
currentLoc = input.substring(0, 2);
newLoc = input.substring(3, 5);
return true;
}
*/
public static boolean legalInput(int x1, int x2, int x3, int x4){
if ((x1 >= 0 && x1 <= 7) && (x2 >= 0 && x2 <= 7) && (x3 >= 0 && x3 <= 7) && (x4 >= 0 && x4 <= 7)){
return true;
}
return false;
}
public static void parseInput(String input){
StringTokenizer st = null;
int count = 0;
input = input.toLowerCase();
input = input.trim();
String[] array = new String[100];
st = new StringTokenizer(input);
while (st.hasMoreTokens()) {
array[count] = st.nextToken();
count++;
}
if (count > 0 && count < 4){
if (count == 1){
if (array[0].equals("resign")){
if (whiteTurn){
System.out.println("Black wins");
System.exit(1);
}else{
System.out.println("White wins");
System.exit(1);
}
}else if (array[0].equals("draw")){
if (askForDraw == true){
System.out.println("Draw");
System.exit(1);
}else{
System.out.println("You must ask the opponent if they are willing to call the game a draw first.");
}
}else{
System.out.println("Invalid input. Please try again. ");
}
}else if (count == 2) {
currentLoc = array[0];
newLoc = array[1];
if (currentLoc.length() == 2 && newLoc.length() == 2 ){
executeMove();
}else{
System.out.println("Invalid input. Please try again.");
}
}else if (count == 3){
currentLoc = array[0];
newLoc = array[1];
if (currentLoc.length() == 2 && newLoc.length() == 2 ){
if (array[2].equals("draw?")){
executeMove();
askForDraw = true;
}else if (array[2].equals("q") || array[2].equals("r") || array[2].equals("b") || array[2].equals("n")) {
thirdArgument = array[2];
executeMove();
}else{
System.out.println("Invalid input. Please try again.");
}
}else{
System.out.println("Invalid input. Please try again.");
}
}
}else{
System.out.println("Invalid input.Please try again.");
}
currentLoc = null;
newLoc = null;
thirdArgument = null;
}
public static void executeMoveOld(){
int oldx = fileToCoordinate(currentLoc);
int oldy =rankToCoordinate(currentLoc);
int newx = fileToCoordinate(newLoc);
int newy =rankToCoordinate(newLoc);
System.out.println(currentLoc +" "+ newLoc);
if (legalInput(oldx, oldy, newx, newy) == true){ //are the coordinates entered legal?
if (gameboard.board[oldx][oldy] != null){ // is there a piece in the chosen spot?
//if (gameboard.board[oldx][oldy].canMove(oldx, oldy, newx, newy, false)){
if ((whiteTurn && gameboard.board[oldx][oldy].isWhite()) || (!whiteTurn && !gameboard.board[oldx][oldy].isWhite())){ //does the piece being moved belong to the player whos turn it is?
if (gameboard.board[newx][newy] == null){ // is the new location empty?
if (gameboard.testCastling(oldx, oldy, newx, newy)) {
return;
}
if (gameboard.board[oldx][oldy].canMove(oldx, oldy, newx, newy, true) && gameboard.isPathClear(oldx, oldy, newx, newx) ){
gameboard.board[newx][newy] = gameboard.board[oldx][oldy];
if ( gameboard.board[newx][newy].drawPiece().equalsIgnoreCase("wp") || gameboard.board[newx][newy].drawPiece().equalsIgnoreCase("bp") ) {
pawnPromotion(newx, newy);
}
gameboard.board[oldx][oldy] = null;
whiteTurn = !whiteTurn;
}else{
System.out.println("Illegal move: This piece cannot move this way.");
}
}else if ((whiteTurn && !gameboard.board[newx][newy].isWhite()) ||
(!whiteTurn && gameboard.board[newx][newy].isWhite())){ // is it the correct colored piece in the old spot, and the opposite colored in the new spot?
if (gameboard.board[oldx][oldy].canMove(oldx, oldy, newx, newy, false) && gameboard.isPathClear(oldx, oldy, newx, newx)){
gameboard.board[newx][newy] = gameboard.board[oldx][oldy];
if ( gameboard.board[newx][newy].drawPiece().equalsIgnoreCase("wp") || gameboard.board[newx][newy].drawPiece().equalsIgnoreCase("bp") ) {
pawnPromotion(newx, newy);
}
gameboard.board[oldx][oldy] = null;
whiteTurn = !whiteTurn;
}else{
System.out.println("Illegal move: This piece cannot move this way.");
}
}else{
System.out.println("Illegal move. Please try again..??");
}
//}else{
// System.out.println("Illegal move: This piece does not belong to the player whos turn it is.");
//}
}else{
System.out.println("Illegal move: This piece cannot be moved this way. Please try again.");
}
}else{
System.out.println("Invalid move: There are no pieces at the chosen location. Please try again.");
}
}else{
System.out.println("Invalid move: The chosen location is not on the board. Please try again.");
}
}
public static void pawnPromotion(int newx, int newy) {
if (gameboard.board[newx][newy].drawPiece().equalsIgnoreCase("wp") && newy == 0) {
if (thirdArgument == null) {
gameboard.board[newx][newy] = new Queen(true);
}else if (thirdArgument.equals("q")) {
gameboard.board[newx][newy] = new Queen(true);
}else if (thirdArgument.equals("r")) {
gameboard.board[newx][newy] = new Rook(true);
}else if (thirdArgument.equals("b")) {
gameboard.board[newx][newy] = new Bishop(true);
}else if (thirdArgument.equals("n")) {
gameboard.board[newx][newy] = new Knight(true);
}
}else if (gameboard.board[newx][newy].drawPiece().equalsIgnoreCase("bp") && newy == 7) {
if (thirdArgument == null) {
gameboard.board[newx][newy] = new Queen(false);
}else if (thirdArgument.equals("q")) {
gameboard.board[newx][newy] = new Queen(false);
}else if (thirdArgument.equals("r")) {
gameboard.board[newx][newy] = new Rook(false);
}else if (thirdArgument.equals("b")) {
gameboard.board[newx][newy] = new Bishop(false);
}else if (thirdArgument.equals("n")) {
gameboard.board[newx][newy] = new Knight(false);
}
}
}
public static void executeMove(){
int oldx = fileToCoordinate(currentLoc);
int oldy =rankToCoordinate(currentLoc);
int newx = fileToCoordinate(newLoc);
int newy =rankToCoordinate(newLoc);
//System.out.println(currentLoc +" "+ newLoc);
if (legalInput(oldx, oldy, newx, newy) == false){ //are the coordinates entered legal?
System.out.println("Invalid file and rank. Please try again.");
return;
}
if (gameboard.board[oldx][oldy] == null){ // is there a piece in the chosen spot?
System.out.println("A piece does not exist in this spot. Please try again.");
return;
}
if (whiteTurn != gameboard.board[oldx][oldy].isWhite()) {
System.out.println("The piece you are attempting to move does not belong to you. Please try again.");
return;
}
boolean isNewSpotEmpty = true;
if (gameboard.board[newx][newy] != null) {
if (gameboard.board[newx][newy].isWhite() == whiteTurn) {
System.out.println("Cannot advance to a location taken by a piece of the same color. Please Try again.");
return;
}
isNewSpotEmpty = false;
}
if (gameboard.testCastling(oldx, oldy, newx, newy)) {
//gameboard.detectCheckMate();
//no longer the first move of the piece
gameboard.board[newx][newy].firstMove = false;
whiteTurn = !whiteTurn;
return;
}
if (enPassant == true) {
enPassant = false;
if (gameboard.testEnPassant(oldx, oldy, newx, newy) == true) {
//gameboard.detectCheckMate();
//no longer the first move of the piece
gameboard.board[newx][newy].firstMove = false;
whiteTurn = !whiteTurn;
return;
}
}
if (gameboard.isPathClear(oldx, oldy, newx, newy) == false) {
System.out.println("Cannot move to that location because there are pieces on the way.");
return;
}
if (gameboard.board[oldx][oldy].canMove(oldx, oldy, newx, newy, isNewSpotEmpty) == false) {
System.out.println("Illegal move. This piece cannot move this way.");
return;
}
gameboard.board[newx][newy] = gameboard.board[oldx][oldy];//move the piece to the new location
//no longer the first move of the piece
gameboard.board[newx][newy].firstMove = false;
if ( gameboard.board[newx][newy].drawPiece().equalsIgnoreCase("wp") || gameboard.board[newx][newy].drawPiece().equalsIgnoreCase("bp") ) {
pawnPromotion(newx, newy);
}
gameboard.board[oldx][oldy] = null;
//detect enpassant scenario for the next turn
if (gameboard.detectEnPassant(oldx, oldy, newx, newy)){
System.out.println("en passant");
// System.out.println("enPassantx:"+enPassantX);
// System.out.println("enPassanty:"+enPassantY);
}
//gameboard.detectCheckMate();
whiteTurn = !whiteTurn;
return;
}
}
| bsd-3-clause |
FRCTeam1073-TheForceTeam/robot17 | src/org/usfirst/frc1073/robot17/commands/increaseLauncherSpeed.java | 2163 | // RobotBuilder Version: 2.0
//
// 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 the future.
package org.usfirst.frc1073.robot17.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc1073.robot17.OI;
import org.usfirst.frc1073.robot17.Robot;
/**
*
*/
public class increaseLauncherSpeed extends Command {
double offset;
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
public increaseLauncherSpeed(double offSet) {
offset = offSet;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
}
// Called just before this Command runs the first time
protected void initialize() {
OI.speed += offset;
if (OI.speed >= 5000)
OI.speed = 5000;
if (OI.speed <= 1000)
OI.speed = 1000;
}
// 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 true;
}
// 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 |
cheminfo/openchemlib-js | src/com/actelion/research/gwt/gui/editor/ACTMouseEvent.java | 2159 | /*
Copyright (c) 2015-2017, cheminfo
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 {{ project }} 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.actelion.research.gwt.gui.editor;
import com.actelion.research.share.gui.editor.io.IMouseEvent;
import com.google.gwt.event.dom.client.MouseEvent;
public class ACTMouseEvent<T extends MouseEvent> implements IMouseEvent {
T _evt;
public ACTMouseEvent(T evt) {
_evt = evt;
}
public double getX() {
return _evt.getX();
}
public double getY() {
return _evt.getY();
}
public boolean isShiftDown() {
return _evt.isShiftKeyDown();
}
public boolean isControlDown() {
return _evt.isControlKeyDown();
}
@Override
public boolean isAltDown() {
return _evt.isAltKeyDown();
}
}
| bsd-3-clause |
luttero/Maud | ImageJ/ij/plugin/FFT.java | 15604 | package ij.plugin;
import ij.*;
import ij.process.*;
import ij.gui.*;
import ij.measure.*;
import ij.plugin.ContrastEnhancer;
import ij.measure.Calibration;
import ij.util.Tools;
import java.awt.*;
import java.util.*;
/**
This class implements the FFT, Inverse FFT and Redisplay Power Spectrum commands
in the Process/FFT submenu. It is based on Arlo Reeves'
Pascal implementation of the Fast Hartley Transform from NIH Image
(http://imagej.nih.gov/ij/docs/ImageFFT/).
The Fast Hartley Transform was restricted by U.S. Patent No. 4,646,256, but was placed
in the public domain by Stanford University in 1995 and is now freely available.
Version 2008-08-25 inverse transform: mask is always symmetrized
*/
public class FFT implements PlugIn, Measurements {
static boolean displayFFT = true;
public static boolean displayRawPS;
public static boolean displayFHT;
public static boolean displayComplex;
public static String fileName;
private ImagePlus imp;
private boolean padded;
private int originalWidth;
private int originalHeight;
private int stackSize = 1;
private int slice = 1;
private boolean doFFT;
public void run(String arg) {
if (arg.equals("options")) {
showDialog();
if (doFFT)
arg="fft";
else
return;
}
imp = IJ.getImage();
if (arg.equals("fft") && imp.isComposite()) {
if (!GUI.showCompositeAdvisory(imp,"FFT"))
return;
}
if (arg.equals("redisplay"))
{redisplayPowerSpectrum(); return;}
if (arg.equals("swap"))
{swapQuadrants(imp.getStack()); imp.updateAndDraw(); return;}
if (arg.equals("inverse")) {
if (imp.getTitle().startsWith("FHT of"))
{doFHTInverseTransform(); return;}
if (imp.getStackSize()==2)
{doComplexInverseTransform(); return;}
}
ImageProcessor ip = imp.getProcessor();
Object obj = imp.getProperty("FHT");
FHT fht = (obj instanceof FHT)?(FHT)obj:null;
stackSize = imp.getStackSize();
boolean inverse;
if (fht==null && arg.equals("inverse")) {
IJ.error("FFT", "Frequency domain image required");
return;
}
if (fht!=null) {
inverse = true;
imp.deleteRoi();
} else {
if (imp.getRoi()!=null)
ip = ip.crop();
fht = newFHT(ip);
inverse = false;
}
if (inverse)
doInverseTransform(fht);
else {
fileName = imp.getTitle();
doForwardTransform(fht);
}
IJ.showProgress(1.0);
}
void doInverseTransform(FHT fht) {
fht = fht.getCopy();
doMasking(fht);
showStatus("Inverse transform");
fht.inverseTransform();
if (fht.quadrantSwapNeeded)
fht.swapQuadrants();
fht.resetMinAndMax();
ImageProcessor ip2 = fht;
if (fht.originalWidth>0) {
fht.setRoi(0, 0, fht.originalWidth, fht.originalHeight);
ip2 = fht.crop();
}
int bitDepth = fht.originalBitDepth>0?fht.originalBitDepth:imp.getBitDepth();
switch (bitDepth) {
case 8: ip2 = ip2.convertToByte(false); break;
case 16: ip2 = ip2.convertToShort(false); break;
case 24:
showStatus("Setting brightness");
if (fht.rgb==null || ip2==null) {
IJ.error("FFT", "Unable to set brightness");
return;
}
ColorProcessor rgb = (ColorProcessor)fht.rgb.duplicate();
rgb.setBrightness((FloatProcessor)ip2);
ip2 = rgb;
fht.rgb = null;
break;
case 32: break;
}
if (bitDepth!=24 && fht.originalColorModel!=null)
ip2.setColorModel(fht.originalColorModel);
String title = imp.getTitle();
if (title.startsWith("FFT of "))
title = title.substring(7, title.length());
ImagePlus imp2 = new ImagePlus("Inverse FFT of "+title, ip2);
imp2.setCalibration(imp.getCalibration());
imp2.show();
}
void doForwardTransform(FHT fht) {
showStatus("Forward transform");
fht.transform();
showStatus("Calculating power spectrum");
long t0 = System.currentTimeMillis();
ImageProcessor ps = fht.getPowerSpectrum();
if (!(displayFHT||displayComplex||displayRawPS))
displayFFT = true;
if (displayFFT) {
ImagePlus imp2 = new ImagePlus("FFT of "+imp.getTitle(), ps);
imp2.show((System.currentTimeMillis()-t0)+" ms");
imp2.setProperty("FHT", fht);
imp2.setCalibration(imp.getCalibration());
String properties = "Fast Hartley Transform\n";
properties += "width: "+fht.originalWidth + "\n";
properties += "height: "+fht.originalHeight + "\n";
properties += "bitdepth: "+fht.originalBitDepth + "\n";
imp2.setProperty("Info", properties);
}
}
FHT newFHT(ImageProcessor ip) {
FHT fht;
if (ip instanceof ColorProcessor) {
showStatus("Extracting brightness");
ImageProcessor ip2 = ((ColorProcessor)ip).getBrightness();
fht = new FHT(pad(ip2));
fht.rgb = (ColorProcessor)ip.duplicate(); // save so we can later update the brightness
} else
fht = new FHT(pad(ip));
if (padded) {
fht.originalWidth = originalWidth;
fht.originalHeight = originalHeight;
}
int bitDepth = imp.getBitDepth();
fht.originalBitDepth = bitDepth;
if (bitDepth!=24)
fht.originalColorModel = ip.getColorModel();
return fht;
}
ImageProcessor pad(ImageProcessor ip) {
originalWidth = ip.getWidth();
originalHeight = ip.getHeight();
int maxN = Math.max(originalWidth, originalHeight);
int i = 2;
while(i<maxN) i *= 2;
if (i==maxN && originalWidth==originalHeight) {
padded = false;
return ip;
}
maxN = i;
showStatus("Padding to "+ maxN + "x" + maxN);
ImageStatistics stats = ImageStatistics.getStatistics(ip, MEAN, null);
ImageProcessor ip2 = ip.createProcessor(maxN, maxN);
ip2.setValue(stats.mean);
ip2.fill();
ip2.insert(ip, 0, 0);
padded = true;
Undo.reset();
//new ImagePlus("padded", ip2.duplicate()).show();
return ip2;
}
void showStatus(String msg) {
if (stackSize>1)
IJ.showStatus("FFT: " + slice+"/"+stackSize);
else
IJ.showStatus(msg);
}
void doMasking(FHT ip) {
if (stackSize>1)
return;
float[] fht = (float[])ip.getPixels();
ImageProcessor mask = imp.getProcessor();
mask = mask.convertToByte(false);
if (mask.getWidth()!=ip.getWidth() || mask.getHeight()!=ip.getHeight())
return;
ImageStatistics stats = ImageStatistics.getStatistics(mask, MIN_MAX, null);
if (stats.histogram[0]==0 && stats.histogram[255]==0)
return;
boolean passMode = stats.histogram[255]!=0;
IJ.showStatus("Masking: "+(passMode?"pass":"filter"));
mask = mask.duplicate();
if (passMode)
changeValuesAndSymmetrize(mask, (byte)255, (byte)0); //0-254 become 0
else
changeValuesAndSymmetrize(mask, (byte)0, (byte)255); //1-255 become 255
//long t0=System.currentTimeMillis();
for (int i=0; i<3; i++)
smooth(mask);
//IJ.log("smoothing time:"+(System.currentTimeMillis()-t0));
if (IJ.debugMode || IJ.altKeyDown())
new ImagePlus("mask", mask.duplicate()).show();
ip.swapQuadrants(mask);
byte[] maskPixels = (byte[])mask.getPixels();
for (int i=0; i<fht.length; i++) {
fht[i] = (float)(fht[i]*(maskPixels[i]&255)/255.0);
}
//FloatProcessor fht2 = new FloatProcessor(mask.getWidth(),mask.getHeight(),fht,null);
//new ImagePlus("fht", fht2.duplicate()).show();
}
// Change pixels not equal to v1 to the new value v2.
// For pixels equal to v1, also the symmetry-equivalent pixel is set to v1
// Requires a quadratic 8-bit image.
void changeValuesAndSymmetrize(ImageProcessor ip, byte v1, byte v2) {
byte[] pixels = (byte[])ip.getPixels();
int n = ip.getWidth();
for (int i=0; i<pixels.length; i++) {
if (pixels[i] == v1) { //pixel has been edited for pass or filter, set symmetry-equivalent
if (i%n==0) { //left edge
if (i>0) pixels[n*n-i] = v1;
} else if (i<n) //top edge
pixels[n-i] = v1;
else //no edge
pixels[n*(n+1)-i] = v1;
} else
pixels[i] = v2; //reset all other pixel values
}
}
// Smooth an 8-bit square image with periodic boundary conditions
// by averaging over 3x3 pixels
// Requires a quadratic 8-bit image.
static void smooth(ImageProcessor ip) {
byte[] pixels = (byte[])ip.getPixels();
byte[] pixels2 = (byte[])pixels.clone();
int n = ip.getWidth();
int[] iMinus = new int[n]; //table of previous index modulo n
int[] iPlus = new int[n]; //table of next index modulo n
for (int i=0; i<n; i++) { //creating the tables in advance is faster calculating each time
iMinus[i] = (i-1+n)%n;
iPlus[i] = (i+1)%n;
}
for (int y=0; y<n; y++) {
int offset1 = n*iMinus[y];
int offset2 = n*y;
int offset3 = n*iPlus[y];
for (int x=0; x<n; x++) {
int sum = (pixels2[offset1+iMinus[x]]&255)
+ (pixels2[offset1+x]&255)
+ (pixels2[offset1+iPlus[x]]&255)
+ (pixels2[offset2+iMinus[x]]&255)
+ (pixels2[offset2+x]&255)
+ (pixels2[offset2+iPlus[x]]&255)
+ (pixels2[offset3+iMinus[x]]&255)
+ (pixels2[offset3+x]&255)
+ (pixels2[offset3+iPlus[x]]&255);
pixels[offset2 + x] = (byte)((sum+4)/9);
}
}
}
void redisplayPowerSpectrum() {
FHT fht = (FHT)imp.getProperty("FHT");
if (fht==null)
{IJ.error("FFT", "Frequency domain image required"); return;}
ImageProcessor ps = fht.getPowerSpectrum();
imp.setProcessor(null, ps);
}
void swapQuadrants(ImageStack stack) {
FHT fht = new FHT(new FloatProcessor(1, 1));
for (int i=1; i<=stack.getSize(); i++)
fht.swapQuadrants(stack.getProcessor(i));
}
void showDialog() {
GenericDialog gd = new GenericDialog("FFT Options");
gd.setInsets(0, 20, 0);
gd.addMessage("Display:");
gd.setInsets(5, 35, 0);
gd.addCheckbox("FFT window", displayFFT);
gd.setInsets(0, 35, 0);
gd.addCheckbox("Raw power spectrum", displayRawPS);
gd.setInsets(0, 35, 0);
gd.addCheckbox("Fast Hartley Transform", displayFHT);
gd.setInsets(0, 35, 0);
gd.addCheckbox("Complex Fourier Transform", displayComplex);
gd.setInsets(8, 20, 0);
gd.addCheckbox("Do forward transform", false);
gd.addHelp(IJ.URL+"/docs/menus/process.html#fft-options");
gd.showDialog();
if (gd.wasCanceled())
return;
displayFFT = gd.getNextBoolean();
displayRawPS = gd.getNextBoolean();
displayFHT = gd.getNextBoolean();
displayComplex = gd.getNextBoolean();
doFFT = gd.getNextBoolean();
}
void doFHTInverseTransform() {
FHT fht = new FHT(imp.getProcessor().duplicate());
fht.inverseTransform();
fht.resetMinAndMax();
String name = WindowManager.getUniqueName(imp.getTitle().substring(7));
new ImagePlus(name, fht).show();
}
void doComplexInverseTransform() {
ImageStack stack = imp.getStack();
if (!stack.getSliceLabel(1).equals("Real"))
return;
int maxN = imp.getWidth();
swapQuadrants(stack);
float[] rein = (float[])stack.getPixels(1);
float[] imin = (float[])stack.getPixels(2);
float[] reout= new float[maxN*maxN];
float[] imout = new float[maxN*maxN];
c2c2DFFT(rein, imin, maxN, reout, imout);
ImageStack stack2 = new ImageStack(maxN, maxN);
swapQuadrants(stack);
stack2.addSlice("Real", reout);
stack2.addSlice("Imaginary", imout);
stack2 = unpad(stack2);
String name = WindowManager.getUniqueName(imp.getTitle().substring(10));
ImagePlus imp2 = new ImagePlus(name, stack2);
imp2.getProcessor().resetMinAndMax();
imp2.show();
}
ImageStack unpad(ImageStack stack) {
Object w = imp.getProperty("FFT width");
Object h = imp.getProperty("FFT height");
if (w==null || h==null) return stack;
int width = (int)Tools.parseDouble((String)w, 0.0);
int height = (int)Tools.parseDouble((String)h, 0.0);
if (width==0 || height==0 || (width==stack.getWidth()&&height==stack.getHeight()))
return stack;
StackProcessor sp = new StackProcessor(stack, null);
ImageStack stack2 = sp.crop(0, 0, width, height);
return stack2;
}
/** Complex to Complex Inverse Fourier Transform
* Author: Joachim Wesner
*/
void c2c2DFFT(float[] rein, float[] imin, int maxN, float[] reout, float[] imout) {
FHT fht = new FHT(new FloatProcessor(maxN,maxN));
float[] fhtpixels = (float[])fht.getPixels();
// Real part of inverse transform
for (int iy = 0; iy < maxN; iy++)
cplxFHT(iy, maxN, rein, imin, false, fhtpixels);
fht.inverseTransform();
// Save intermediate result, so we can do a "in-place" transform
float[] hlp = new float[maxN*maxN];
System.arraycopy(fhtpixels, 0, hlp, 0, maxN*maxN);
// Imaginary part of inverse transform
for (int iy = 0; iy < maxN; iy++)
cplxFHT(iy, maxN, rein, imin, true, fhtpixels);
fht.inverseTransform();
System.arraycopy(hlp, 0, reout, 0, maxN*maxN);
System.arraycopy(fhtpixels, 0, imout, 0, maxN*maxN);
}
/** Build FHT input for equivalent inverse FFT
* Author: Joachim Wesner
*/
void cplxFHT(int row, int maxN, float[] re, float[] im, boolean reim, float[] fht) {
int base = row*maxN;
int offs = ((maxN-row)%maxN) * maxN;
if (!reim) {
for (int c=0; c<maxN; c++) {
int l = offs + (maxN-c)%maxN;
fht[base+c] = ((re[base+c]+re[l]) - (im[base+c]-im[l]))*0.5f;
}
} else {
for (int c=0; c<maxN; c++) {
int l = offs + (maxN-c)%maxN;
fht[base+c] = ((im[base+c]+im[l]) + (re[base+c]-re[l]))*0.5f;
}
}
}
}
| bsd-3-clause |
ThomasDaheim/ownNoteEditor | ownNoteEditor/src/main/java/tf/ownnote/ui/tags/TagDataEditor.java | 13457 | /*
* Copyright (c) 2014ff Thomas Feuster
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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 tf.ownnote.ui.tags;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import java.util.Optional;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.RowConstraints;
import javafx.scene.paint.Color;
import javafx.util.StringConverter;
import static tf.helper.javafx.AbstractStage.INSET_TOP;
import static tf.helper.javafx.AbstractStage.INSET_TOP_BOTTOM;
import tf.helper.javafx.ColorConverter;
import tf.helper.javafx.GridComboBox;
import tf.helper.javafx.TooltipHelper;
import tf.ownnote.ui.main.OwnNoteEditor;
/**
* Show & edit tag data as a GridPane.
*
* - name
* - icon
* - color
* - group tag?
*
* @author thomas
*/
public class TagDataEditor extends GridPane {
private final static TagDataEditor INSTANCE = new TagDataEditor();
private final static int SYMBOL_SIZE = 36;
private final static int COLS_PER_ROW = 5;
private TagData myTag = null;
private OwnNoteEditor myEditor = null;
private final TextField tagName = new TextField();
private final GridComboBox<Label> tagIcon = new GridComboBox<>();
private final ColorPicker tagColor = new ColorPicker();
private final CheckBox groupTag = new CheckBox("");
private TagDataEditor() {
initCard();
}
public static TagDataEditor getInstance() {
return INSTANCE;
}
private void initCard() {
// needs to be done in case it becomes a stage...
// (new JMetro(Style.LIGHT)).setScene(getScene());
// getScene().getStylesheets().add(EditGPXWaypoint.class.getResource("/GPXEditor.css").toExternalForm());
getStyleClass().add("tagEditor");
final ColumnConstraints col1 = new ColumnConstraints();
final ColumnConstraints col2 = new ColumnConstraints();
col2.setMinWidth(100.0);
col2.setMaxWidth(260.0);
col2.setHgrow(Priority.ALWAYS);
getGridPane().getColumnConstraints().addAll(col1,col2);
int rowNum = 0;
// description
Tooltip t = new Tooltip("Tag name");
final Label lblName = new Label("Name:");
lblName.setTooltip(t);
getGridPane().add(lblName, 0, rowNum, 1, 1);
GridPane.setValignment(lblName, VPos.CENTER);
GridPane.setMargin(lblName, INSET_TOP);
getGridPane().add(tagName, 1, rowNum, 1, 1);
GridPane.setMargin(tagName, INSET_TOP);
rowNum++;
// icon
t = new Tooltip("Icon");
final Label lblstatus = new Label("Icon:");
lblstatus.setTooltip(t);
getGridPane().add(lblstatus, 0, rowNum, 1, 1);
GridPane.setValignment(lblstatus, VPos.CENTER);
GridPane.setMargin(lblstatus, INSET_TOP);
tagIcon.setEditable(false);
tagIcon.setVisibleRowCount(8);
tagIcon.setHgap(0.0);
tagIcon.setVgap(0.0);
tagIcon.setResizeContentColumn(false);
tagIcon.setResizeContentRow(false);
// handle non-string combobox content properly
// https://stackoverflow.com/a/58286816
tagIcon.setGridConverter(new StringConverter<Label>() {
@Override
public String toString(Label label) {
if (label == null) {
return "";
} else {
// icon
return label.getTooltip().getText();
}
}
@Override
public Label fromString(String string) {
return iconLabelForText(string);
}
});
// add icons and group labels
int gridRowNum = 0;
int gridColNum = 0;
for (FontAwesomeIcon icon : FontAwesomeIcon.values()) {
final Label label = TagManager.getIconForName(icon.name(), TagManager.IconSize.LARGE);
label.getStyleClass().add("icon-label");
label.setGraphicTextGap(0.0);
final Tooltip tooltip = new Tooltip(icon.name());
tooltip.getStyleClass().add("nametooltip");
TooltipHelper.updateTooltipBehavior(tooltip, 0, 10000, 0, true);
label.setTooltip(tooltip);
tagIcon.add(label, gridColNum, gridRowNum, 1, 1);
if (gridColNum + 1 < COLS_PER_ROW) {
gridColNum++;
} else {
gridRowNum++;
gridColNum = 0;
}
}
// make sure things are laid out properly
addColRowConstraints();
// TFE, 20190721: filter while typing
// TFE; 20200510: minor modification since we now show labels with images
tagIcon.getEditor().textProperty().addListener((ov, oldValue, newValue) -> {
if (newValue != null && !newValue.equals(oldValue)) {
setTagIcon(newValue);
}
});
getGridPane().add(tagIcon, 1, rowNum);
GridPane.setMargin(tagIcon, INSET_TOP);
final Label symbolValue = new Label("");
getGridPane().add(symbolValue, 2, rowNum);
GridPane.setMargin(symbolValue, INSET_TOP);
// update label for any changes of combobox selection
tagIcon.valueProperty().addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
if (newValue != null && !newValue.equals(oldValue)) {
symbolValue.setGraphic(TagManager.getIconForName(newValue, TagManager.IconSize.LARGE));
}
});
// focus dropdown on selected item - hacking needed
tagIcon.showingProperty().addListener((obs, wasShowing, isNowShowing) -> {
if (isNowShowing) {
// set focus on selected item
if (tagIcon.getSelectionModel().getSelectedIndex() > -1) {
tagIcon.scrollTo(iconLabelForText(tagIcon.getSelectionModel().getSelectedItem()));
// https://stackoverflow.com/a/36548310
// https://stackoverflow.com/a/47933342
// final ListView<Label> lv = ObjectsHelper.uncheckedCast(((ComboBoxListViewSkin) waypointSymTxt.getSkin()).getPopupContent());
// lv.scrollTo(waypointSymTxt.getSelectionModel().getSelectedIndex());
}
}
});
rowNum++;
// color
t = new Tooltip("Color");
final Label lblCol = new Label("Color:");
lblCol.setTooltip(t);
getGridPane().add(lblCol, 0, rowNum, 1, 1);
GridPane.setValignment(lblCol, VPos.CENTER);
GridPane.setMargin(lblCol, INSET_TOP);
getGridPane().add(tagColor, 1, rowNum, 1, 1);
GridPane.setMargin(tagColor, INSET_TOP);
rowNum++;
// tag type
t = new Tooltip("Group tag");
final Label lbltype = new Label("Group tag:");
lbltype.setTooltip(t);
getGridPane().add(lbltype, 0, rowNum, 1, 1);
GridPane.setValignment(lbltype, VPos.CENTER);
GridPane.setMargin(lbltype, INSET_TOP);
groupTag.setDisable(true);
getGridPane().add(groupTag, 1, rowNum, 1, 1);
GridPane.setMargin(groupTag, INSET_TOP);
rowNum++;
// save + cancel buttons
final Button saveButton = new Button("Save");
saveButton.setOnAction((ActionEvent event) -> {
saveValues();
// give parent node the oportunity to close
fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED, KeyCode.ACCEPT.toString(), KeyCode.ACCEPT.toString(), KeyCode.ACCEPT, false, false, false, false));
});
// not working since no scene yet...
// getScene().getAccelerators().put(UsefulKeyCodes.CNTRL_S.getKeyCodeCombination(), () -> {
// saveButton.fire();
// });
getGridPane().add(saveButton, 0, rowNum, 1, 1);
GridPane.setHalignment(saveButton, HPos.CENTER);
GridPane.setMargin(saveButton, INSET_TOP_BOTTOM);
final Button cancelBtn = new Button("Cancel");
cancelBtn.setOnAction((ActionEvent event) -> {
initValues();
// give parent node the oportunity to close
fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED, KeyCode.ESCAPE.toString(), KeyCode.ESCAPE.toString(), KeyCode.ESCAPE, false, false, false, false));
});
// not working since no scene yet...
// getScene().getAccelerators().put(UsefulKeyCodes.ESCAPE.getKeyCodeCombination(), () -> {
// cancelBtn.fire();
// });
getGridPane().add(cancelBtn, 1, rowNum, 1, 1);
GridPane.setHalignment(cancelBtn, HPos.CENTER);
GridPane.setMargin(cancelBtn, INSET_TOP_BOTTOM);
}
private void addColRowConstraints() {
for (int i = 0; i < tagIcon.getColumnCount(); i++) {
final ColumnConstraints column = new ColumnConstraints(SYMBOL_SIZE);
column.setFillWidth(true);
column.setHgrow(Priority.ALWAYS);
tagIcon.getColumnConstraints().add(column);
}
for (int i = 0; i < tagIcon.getRowCount(); i++) {
final RowConstraints row = new RowConstraints(SYMBOL_SIZE);
row.setFillHeight(true);
tagIcon.getRowConstraints().add(row);
}
}
private Label iconLabelForText(final String iconName) {
if (iconName == null) {
// default label is a BUG
return iconLabelForText(FontAwesomeIcon.BUG.name());
}
final Optional<Label> label = tagIcon.getGridItems().stream().filter((t) -> {
if (t.getTooltip() == null) {
return false;
} else {
return t.getTooltip().getText().equals(iconName);
}
}).findFirst();
if (label.isPresent()) {
return label.get();
} else {
return null;
}
}
private void setTagIcon(final String labelText) {
final Label label = iconLabelForText(labelText);
if (label != null) {
tagIcon.getSelectionModel().select(label.getTooltip().getText());
tagIcon.scrollTo(iconLabelForText(tagIcon.getSelectionModel().getSelectedItem()));
}
}
public TagDataEditor editTag(final TagData tag, final OwnNoteEditor editor) {
myTag = tag;
myEditor = editor;
initValues();
return this;
}
private void initValues() {
tagName.setText(myTag.getName());
setTagIcon(myTag.getIconName());
tagColor.setValue(Color.valueOf(myTag.getColorName()));
groupTag.setSelected(TagManager.isGroupsChildTag(myTag));
}
public void saveValues() {
// in case of group name change we need to inform the rest of the world
TagManager.getInstance().renameTag(myTag, tagName.getText());
myTag.setIconName(tagIcon.getValue());
myTag.setColorName(ColorConverter.JavaFXtoCSS(tagColor.getValue()));
}
// provision for future conversion into an AbstractStage - not very YAGNI
private GridPane getGridPane() {
return this;
}
public static boolean isCompleteCode(final KeyCode code) {
return isSaveCode(code) || isCancelCode(code);
}
public static boolean isSaveCode(final KeyCode code) {
return KeyCode.ACCEPT.equals(code);
}
public static boolean isCancelCode(final KeyCode code) {
return KeyCode.ESCAPE.equals(code);
}
}
| bsd-3-clause |
lockss/lockss-daemon | plugins/src/org/lockss/plugin/clockss/SourceXmlParserHelperUtilities.java | 5480 | /*
Copyright (c) 2000-2021, Board of Trustees of Leland Stanford Jr. University
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.lockss.plugin.clockss;
import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public final class SourceXmlParserHelperUtilities {
/**
* This function return string representation of publication date from particular xpath selected xml node
* @param node
* <PubDate>
* <Year>2019</Year>
* <Month>01</Month>
* <Day>01</Day>
* </PubDate>
* @return a string representation of pubdate "mm-dd-Year"
*/
public static String getPubDateFromPubDateXpathNodeValue(Node node) {
NodeList nameChildren = node.getChildNodes();
if (nameChildren == null) return null;
String year = null;
String month = null;
String day = null;
if (nameChildren == null) return null;
for (int p = 0; p < nameChildren.getLength(); p++) {
Node partNode = nameChildren.item(p);
String partName = partNode.getNodeName();
if ("Year".equalsIgnoreCase(partName)) {
year = partNode.getTextContent();
} else if ("Month".equalsIgnoreCase(partName)) {
month = partNode.getTextContent();
} else if ("Day".equalsIgnoreCase(partName)) {
day = partNode.getTextContent();
}
}
StringBuilder valbuilder = new StringBuilder();
if (!StringUtils.isBlank(month)) {
valbuilder.append(month);
if (!StringUtils.isBlank(day)) {
valbuilder.append("-" + day);
}
if (!StringUtils.isBlank(year)) {
valbuilder.append("-" + year);
}
return valbuilder.toString();
}
return null;
}
/**
* This function return string representation of author name from particular xpath selected xml node
* @param node
* <Author ValidYN="Y">
* <LastName>Artzi</LastName>
* <ForeName>Ofir</ForeName>
* <Initials>O</Initials>
* <AffiliationInfo>
* <Affiliation>Department of Dermatology, Tel Aviv Medical Center, Tel Aviv, 6423906, Israel. benofir@gmail.com.</Affiliation>
* </AffiliationInfo>
* </Author>
* @return a string representation of author's name "firstname lastname"
*/
public static String getAuthorNameFromAuthorNameXpathNodeValue(Node node) {
NodeList nameChildren = node.getChildNodes();
if (nameChildren == null) return null;
String surname = null;
String firstname = null;
if (nameChildren == null) return null;
for (int p = 0; p < nameChildren.getLength(); p++) {
Node partNode = nameChildren.item(p);
String partName = partNode.getNodeName();
if ("LastName".equalsIgnoreCase(partName)) {
surname = partNode.getTextContent();
} else if ("SurName".equalsIgnoreCase(partName)) {
surname = partNode.getTextContent();
} else if ("SurName".equalsIgnoreCase(partName)) {
surname = partNode.getTextContent();
} else if ("ForeName".equalsIgnoreCase(partName)) {
firstname = partNode.getTextContent();
} else if ("FirstName".equalsIgnoreCase(partName)) {
firstname = partNode.getTextContent();
} else if ("given_name".equalsIgnoreCase(partName)) {
firstname = partNode.getTextContent();
}
}
StringBuilder valbuilder = new StringBuilder();
if (!StringUtils.isBlank(firstname)) {
valbuilder.append(firstname);
if (!StringUtils.isBlank(surname)) {
valbuilder.append(" " + surname);
}
return valbuilder.toString();
}
return null;
}
}
| bsd-3-clause |
NCIP/national-biomedical-image-archive | software/nbia-dao/src/gov/nih/nci/nbia/dicomapi/LogLine.java | 1786 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gov.nih.nci.nbia.dicomapi;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author Luís A. Bastião Silva <bastiao@ua.pt>
*/
public class LogLine implements Serializable
{
static final long serialVersionUID = 1L;
private String type;
private String date;
private String ae;
private String add;
public LogLine(String type, String date, String ae, String add)
{
this.type = type ;
this.date = date ;
this.ae = ae ;
this.add = add ;
}
public static String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
/**
* @return the type
*/
public String getType()
{
return type;
}
/**
* @param type the type to set
*/
public void setType(String type)
{
this.type = type;
}
/**
* @return the date
*/
public String getDate()
{
return date;
}
/**
* @param date the date to set
*/
public void setDate(String date)
{
this.date = date;
}
/**
* @return the ae
*/
public String getAe()
{
return ae;
}
/**
* @param ae the ae to set
*/
public void setAe(String ae)
{
this.ae = ae;
}
/**
* @return the add
*/
public String getAdd()
{
return add;
}
/**
* @param add the add to set
*/
public void setAdd(String add)
{
this.add = add;
}
}
| bsd-3-clause |
LowResourceLanguages/InuktitutComputing | Inuktitut-Java/data/Affix.java | 14622 | //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//
// -----------------------------------------------------------------------
// (c) Conseil national de recherches Canada, 2002
// (c) National Research Council of Canada, 2002
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// Document/File: Affix.java
//
// Type/File type: code Java / Java code
//
// Auteur/Author: Benoit Farley
//
// Organisation/Organization: Conseil national de recherches du Canada/
// National Research Council Canada
//
// Date de cr�ation/Date of creation:
//
// Description: Classe Affix
//
// -----------------------------------------------------------------------
package data;
import java.lang.String;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import data.constraints.Condition;
import data.constraints.Conditions;
public abstract class Affix extends Morpheme {
//
String function = null;
String position = null;
String[] vform = null;
Action[] vaction1 = null;
Action[] vaction2 = null;
String[] tform = null;
Action[] taction1 = null;
Action[] taction2 = null;
String[] kform = null;
Action[] kaction1 = null;
Action[] kaction2 = null;
String[] qform = null;
Action[] qaction1 = null;
Action[] qaction2 = null;
//
//---------------------------------------------------------------------------------------------------------
public abstract String getTransitivityConstraint(); //
public abstract void addToHash(String key, Object obj); //
//---------------------------------------------------------------------------------------------------------
abstract boolean agreeWithTransitivity(String trans); //
//---------------------------------------------------------------------------------------------------------
public String getOriginalMorpheme() {
return morpheme;
}
public boolean isNonMobileSuffix() {
if (getClass() == Suffix.class && ((Suffix) this).mobility != null
&& ((Suffix) this).mobility.equals("nm"))
return true;
else
return false;
}
public void addPrecConstraint(Condition cond) {
if (preCondition==null)
preCondition = (Conditions)cond;
else {
preCondition = new Condition.And((Condition)preCondition,cond);
}
}
//---------------------------------------------------------------------------------------------------------
void setAttributes(HashMap attrs) {
HashMap affAttrs = new HashMap();
affAttrs.put("function",function);
affAttrs.put("position",position);
affAttrs.put("vform",vform);
affAttrs.put("vaction1",vaction1);
affAttrs.put("vaction2",vaction2);
affAttrs.put("tform",tform);
affAttrs.put("taction1",taction1);
affAttrs.put("taction2",taction2);
affAttrs.put("kform",kform);
affAttrs.put("kaction1",kaction1);
affAttrs.put("kaction2",kaction2);
affAttrs.put("qform",qform);
affAttrs.put("qaction1",qaction1);
affAttrs.put("qaction2",qaction2);
affAttrs.putAll(attrs);
super.setAttributes(affAttrs);
}
String[] getForm(char context) {
if (context=='V' || context=='a' || context=='i' || context=='u')
return vform;
else if (context=='t')
return tform;
else if (context=='k')
return kform;
else if (context=='q')
return qform;
else
return null;
}
Action[] getAction1(char context) {
if (context=='V' || context=='a' || context=='i' || context=='u')
return vaction1;
else if (context=='t')
return taction1;
else if (context=='k')
return kaction1;
else if (context=='q')
return qaction1;
else
return null;
}
Action[] getAction2(char context) {
if (context=='V' || context=='a' || context=='i' || context=='u')
return vaction2;
else if (context=='t')
return taction2;
else if (context=='k')
return kaction2;
else if (context=='q')
return qaction2;
else
return null;
}
// Les cha�nes 'alternateForms', 'actions1' et 'action2'
// contiennent le contenu des champs X-form, X-action1 et X-action2
// des enregistrements dans la base de donn�es. Ces champs/cha�nes
// peuvent identifier plus d'une forme+action.
//
// En fait, les possibilit�s sont les suivantes:
// nb. actions1 < nb. surfaceFormsOfAffixes >>> (nb. actions1 = 1) l'action est appliqu�e � chaque forme
// nb. actions1 = nb. surfaceFormsOfAffixes >>> une action par forme
// nb. actions1 > nb. surfaceFormsOfAffixes >>> (nb. surfaceFormsOfAffixes = 1) chaque action est appliqu�e � la forme
//
// nb. surfaceFormsOfAffixes = 0 >>> la forme est la m�me que la forme de 'morpheme'
//
// Si form = '-' et action1 = '-', cela signifie qu'il n'y a pas de forme dans ce context.
//
// Quant � action2, elle doit soit �tre nulle, soit correspondre en nombre � action1.
// Dans ce cas, la valeur '-' signifie une action nulle, i.e. aucune action.
//
// Une forme peut prendre les valeurs suivantes:
// identificateur
// "*" : m�me valeur que la forme du champ 'morpheme'.
// "-" : la forme n'existe pas dans ce context
//
// Cette fonction construit un objet de classe SurfaceFormOfAffix pour
// chaque groupe form+action1+action2 identifi�e.
void makeFormsAndActions(
String context,
String morpheme,
String alternateForms,
String action1,
String action2) {
String[] forms;
Action[] a1;
Action[] a2;
String allForms = null;
if (action1.equals("-")) {
// Si le champ 'X-action1' est vide,
// cela signifie qu'il n'y a pas de forme dans le context X.
allForms = "";
action1 = "";
action2 = "";
} else if (alternateForms==null)
// Si le champ 'X-form' est vide,
// cela signifie que la forme est celle du champ 'morpheme'.
allForms = new String(morpheme);
else {
// Transformer les * en la valeur de 'morpheme'
alternateForms = alternateForms.replaceAll("\\x2a",morpheme);
if (context.equals("V"))
// Dans la table des suffixes, nous avons adopt� la convention selon
// laquelle la valeur du champ 'morpheme' est la forme du suffixe dans
// le context de voyelle, et donc, le champ 'V-form' ne le contient pas:
// il faut l'ajouter ici dans la liste.
allForms = morpheme + " " + alternateForms;
else
allForms = new String(alternateForms);
}
StringTokenizer stf = new StringTokenizer(allForms);
// nb. de surfaceFormsOfAffixes
int nbf = stf.countTokens();
StringTokenizer st1 = new StringTokenizer(action1);
// nb. d'actions1
int nba1 = st1.countTokens();
if (action2==null)
action2 = new String("");
StringTokenizer st2 = new StringTokenizer(action2);
int nba2 = st2.countTokens();
if (nba1 > nbf && nbf==1) {
/*
* S'il y a plus d'action1 que de formes, le nb. de formes devrait �tre �gal � 1
* et on ajoute dans la liste de formes la valeur initiale autant de fois qu'il le
* faut pour �galiser le nombre d'actions.
*/
String initialValue = new String(allForms);
for (int j = nbf; j < nba1; j++)
allForms = allForms + " " + initialValue;
stf = new StringTokenizer(allForms);
nbf = stf.countTokens();
} else if (nbf > nba1 && nba1==1) {
/*
* S'il y a plus de formes que d'action1, le nb. d'action1 devrait �tre �gal �
* 1 et on ajoute dans la liste d'action1 la valeur initiale autant de fois qu'
* il le faut pour �galiser le nombre de formes.
*/
String act1 = new String(action1);
for (int j = nba1; j < nbf; j++)
action1 = action1 + " " + act1;
st1 = new StringTokenizer(action1);
nba1 = st1.countTokens();
/*
* Si le nombre d'action2 est aussi �gal � 1 (il devrait �tre �gal � 0 ou � 1),
* on multiplie aussi.
*/
if (nba2==1) {
String act2 = new String(action2);
for (int j = nba2; j < nbf; j++)
action2 = action2 + " " + act2;
st2 = new StringTokenizer(action2);
nba2 = st2.countTokens();
}
}
// En principe, ici, allForms, action1 et action2 devraient
// �tre en phase et contenir un nombre �gal d'�l�ments.
Vector VForms = new Vector();
Vector a1V = new Vector();
Vector a2V = new Vector();
while (stf.hasMoreTokens()) {
String f = stf.nextToken();
VForms.add(f);
// La premi�re fois, st1.hasMoreTokens() est vrai, puisque
// action1 doit absolument avoir une valeur dans la base de
// donn�es: act1 y trouve sa valeur...
String act1 = st1.nextToken();
// ...sinon, act1 conserve la valeur pr�c�dente, obtenue
// au premier tour.
Pattern pif1 = Pattern.compile("^if\\((.+),([a-z]+),([a-z]+)\\)$");
Matcher mif1 = pif1.matcher(act1);
Pattern pif2 = Pattern.compile("^if\\((.+),([a-z]+)\\)$");
Matcher mif2 = pif2.matcher(act1);
if (mif1.matches()) {
String condition = mif1.group(1).replaceAll("\\x7c"," "); // '|'
String actPos = mif1.group(2);
String actNeg = null;
actNeg = mif1.group(3);
a1V.add(Action.makeAction(actPos+"si("+condition+")"));
if (actNeg != null) {
VForms.add(f);
a1V.add(Action.makeAction(actNeg+"si(!("+condition+"))"));
}
if (!action2.equals("")) {
String ac2 = st2.nextToken();
a2V.add(Action.makeAction(ac2));
a2V.add(Action.makeAction(ac2));
} else {
a2V.add(Action.makeAction(null));
a2V.add(Action.makeAction(null));
}
} else if (mif2.matches()) {
String condition = mif2.group(1).replaceAll("\\x7c"," "); // '|'
String actPos = mif2.group(2);
a1V.add(Action.makeAction(actPos+"si("+condition+")"));
if (!action2.equals("")) {
String ac2 = st2.nextToken();
a2V.add(Action.makeAction(ac2));
a2V.add(Action.makeAction(ac2));
} else {
a2V.add(Action.makeAction(null));
a2V.add(Action.makeAction(null));
}
} else {
a1V.add(Action.makeAction(act1));
if (!action2.equals(""))
a2V.add(Action.makeAction(st2.nextToken()));
else
a2V.add(Action.makeAction(null));
}
}
forms = (String[])VForms.toArray(new String []{});
a1 = (Action[])a1V.toArray(new Action[]{Action.makeAction()});
a2 = (Action[])a2V.toArray(new Action[]{Action.makeAction()});
// Enregistrer dans l'object affixe
if (context.equals("V")) {
vform = forms;
vaction1 = a1;
vaction2 = a2;
} else if (context.equals("t")) {
tform = forms;
taction1 = a1;
taction2 = a2;
} else if (context.equals("k")) {
kform = forms;
kaction1 = a1;
kaction2 = a2;
} else if (context.equals("q")) {
qform = forms;
qaction1 = a1;
qaction2 = a2;
}
/*
* Mis hors-compilation parce pas utile, mais conserv� pour usage futur
*/
// for (int j=0; j<forms.length; j++) {
// fillFinalRadInitAffHashSet(context,forms[j],a1[j],a2[j]);
// }
}
// void fillFinalRadInitAffHashSet(String context, String form, Action a1, Action a2) {
// String f = Orthography.simplifiedOrthographyLat(form);
// String finalRadInitAff[] = a1.finalRadInitAff(context,f);
// for (int i=0; i<finalRadInitAff.length; i++)
// Donnees.finalRadInitAffHashSet.add(finalRadInitAff[i]);
// }
// ----------------------------
public String showData() {
StringBuffer sb = new StringBuffer();
sb.append("vform= [");
int i;
for (i = 0; i < vform.length - 1; i++)
sb.append(vform[i] + ",");
sb.append(vform[i] + "]\n");
sb.append("vaction1= [");
for (i = 0; i < vaction1.length - 1; i++)
sb.append(vaction1[i] + ",");
sb.append(vaction1[i] + "]\n");
sb.append("vaction2= [");
for (i = 0; i < vaction2.length - 1; i++)
sb.append(vaction2[i] + ",");
sb.append(vaction2[i] + "]\n");
sb.append("tform= [");
for (i = 0; i < tform.length - 1; i++)
sb.append(tform[i] + ",");
sb.append(tform[i] + "]\n");
sb.append("taction1= [");
for (i = 0; i < taction1.length - 1; i++)
sb.append(taction1[i] + ",");
sb.append(taction1[i] + "]\n");
sb.append("taction2= [");
for (i = 0; i < taction2.length - 1; i++)
sb.append(taction2[i] + ",");
sb.append(taction2[i] + "]\n");
sb.append("kform= [");
for (i = 0; i < kform.length - 1; i++)
sb.append(kform[i] + ",");
sb.append(kform[i] + "]\n");
sb.append("kaction1= [");
for (i = 0; i < kaction1.length - 1; i++)
sb.append(kaction1[i] + ",");
sb.append(kaction1[i] + "]\n");
sb.append("kaction2= [");
for (i = 0; i < kaction2.length - 1; i++)
sb.append(kaction2[i] + ",");
sb.append(kaction2[i] + "]\n");
sb.append("qform= [");
for (i = 0; i < qform.length - 1; i++)
sb.append(qform[i] + ",");
sb.append(qform[i] + "]\n");
sb.append("qaction1= [");
for (i = 0; i < qaction1.length - 1; i++)
sb.append(qaction1[i] + ",");
sb.append(qaction1[i] + "]\n");
sb.append("qaction2= [");
for (i = 0; i < qaction2.length - 1; i++)
sb.append(qaction2[i] + ",");
sb.append(qaction2[i] + "]\n");
return sb.toString();
}
}
| bsd-3-clause |
leriomaggio/code-coherence-evaluation-tool | code_comments_coherence/media/jhotdraw/7.4.1/jhotdraw7zip/extracted/jhotdraw7/src/main/java/org/jhotdraw/util/Images.java | 8238 | /*
* @(#)Images.java
*
* Copyright (c) 1996-2010 by the original authors of JHotDraw
* and all its contributors.
* All rights reserved.
*
* The copyright of this software is owned by the authors and
* contributors of the JHotDraw project ("the copyright holders").
* You may not use, copy or modify this software, except in
* accordance with the license agreement you entered into with
* the copyright holders. For details see accompanying license terms.
*/
package org.jhotdraw.util;
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import javax.swing.*;
/**
* Image processing methods.
*
* @author Werner Randelshofer
* @version $Id: Images.java 600 2010-01-06 16:08:44Z rawcoder $
*/
public class Images {
/** Prevent instance creation. */
private Images() {
}
public static Image createImage(Class baseClass, String resourceName) {
URL resource = baseClass.getResource(resourceName);
if (resource == null) {
throw new InternalError("Ressource \"" + resourceName + "\" not found for class " + baseClass);
}
Image image = Toolkit.getDefaultToolkit().createImage(resource);
return image;
}
public static Image createImage(URL resource) {
Image image = Toolkit.getDefaultToolkit().createImage(resource);
return image;
}
/**
* Converts an Image to BufferedImage. If the Image is already a
* BufferedImage, the same image is returned.
*
* @param rImg An Image.
* @return A BufferedImage.
*/
public static BufferedImage toBufferedImage(RenderedImage rImg) {
BufferedImage image;
if (rImg instanceof BufferedImage) {
image = (BufferedImage) rImg;
} else {
Raster r = rImg.getData();
WritableRaster wr = WritableRaster.createWritableRaster(
r.getSampleModel(), null);
rImg.copyData(wr);
image = new BufferedImage(
rImg.getColorModel(),
wr,
rImg.getColorModel().isAlphaPremultiplied(),
null);
}
return image;
}
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
// Create a buffered image with a format that's compatible with the screen
BufferedImage bimage = null;
if (System.getProperty("java.version").startsWith("1.4.1_")) {
// Workaround for Java 1.4.1 on Mac OS X.
// For this JVM, we always create an ARGB image to prevent a class
// cast exception in
// sun.awt.image.BufImgSurfaceData.createData(BufImgSurfaceData.java:434)
// when we attempt to draw the buffered image.
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
} else {
// Determine if the image has transparent pixels; for this method's
// implementation, see e661 Determining If an Image Has Transparent Pixels
boolean hasAlpha;
try {
hasAlpha = hasAlpha(image);
} catch (IllegalAccessError e) {
// If we can't determine this, we assume that we have an alpha,
// in order not to loose data.
hasAlpha = true;
}
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
// Determine the type of transparency of the new buffered image
int transparency = Transparency.OPAQUE;
if (hasAlpha) {
transparency = Transparency.TRANSLUCENT;
}
// Create the buffered image
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(
image.getWidth(null), image.getHeight(null), transparency);
} catch (Exception e) {
//} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
if (hasAlpha) {
type = BufferedImage.TYPE_INT_ARGB;
}
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
/**
* This method returns true if the specified image has transparent pixels
*
* Code taken from the Java Developers Almanac 1.4
* http://javaalmanac.com/egs/java.awt.image/HasAlpha.html
*/
public static boolean hasAlpha(Image image) {
// If buffered image, the color model is readily available
if (image instanceof BufferedImage) {
BufferedImage bimage = (BufferedImage) image;
return bimage.getColorModel().hasAlpha();
}
// Use a pixel grabber to retrieve the image's color model;
// grabbing a single pixel is usually sufficient
PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
try {
pg.grabPixels();
} catch (InterruptedException e) {
}
// Get the image's color model
ColorModel cm = pg.getColorModel();
return cm.hasAlpha();
}
/**
* Splits an image into count subimages.
*/
public static BufferedImage[] split(Image image, int count, boolean isHorizontal) {
BufferedImage src = Images.toBufferedImage(image);
if (count == 1) {
return new BufferedImage[]{src};
}
BufferedImage[] parts = new BufferedImage[count];
for (int i = 0; i < count; i++) {
if (isHorizontal) {
parts[i] = src.getSubimage(
src.getWidth() / count * i, 0,
src.getWidth() / count, src.getHeight());
} else {
parts[i] = src.getSubimage(
0, src.getHeight() / count * i,
src.getWidth(), src.getHeight() / count);
}
}
return parts;
}
/** Creates a scaled instanceof the image.
* <p>
* If either width or height is a negative number then a value is s
* ubstituted to maintain the aspect ratio of the original image dimensions.
* If both width and height are negative, then the original image dimensions
* are used.
* <p>
* On Mac OS X 10.6, this method has a much better performance than
* BufferedImage.getScaledInstance.
*
*
* @param image the image.
* @param width the width to which to scale the image.
* @param height the height to which to scale the image.
*/
public static BufferedImage getScaledInstance(Image image, int width, int height) {
int w, h;
if (width<0&&height<0) {
w=image.getWidth(null);
h=image.getHeight(null);
} else if (width<0) {
w=image.getWidth(null)*height/image.getHeight(null);
h=height;
} else if (height<0) {
w=width;
h=image.getHeight(null)*width/image.getWidth(null);
} else {
w=width;
h=height;
}
BufferedImage scaled = new BufferedImage(w,h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = scaled.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.drawImage(image, 0, 0, w, h, null);
g.dispose();
return scaled;
}
}
| bsd-3-clause |
KingBowser/hatter-source-code | commons/main/java/me/hatter/tools/commons/color/Position.java | 415 | package me.hatter.tools.commons.color;
public class Position {
private int row;
private int col;
public int getRow() {
return row;
}
public int getCol() {
return col;
}
public Position(int row, int col) {
this.row = row;
this.col = col;
}
public static Position getPosition(int row, int col) {
return new Position(row, col);
}
}
| bsd-3-clause |
pickerweng/Lifecycle4Android | lifecycle4android/src/main/java/com/meowmau/lifecycle4android/app/AppLifecycleApplication.java | 2978 | /*
* Copyright (c) 2015, Picker Weng
* 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 Lifecycle4Android 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.
*
* Project:
* Lifecycle4Android
*
* File:
* AppLifecycleApplication.java
*
* Author:
* Picker Weng (pickerweng@gmail.com)
*/
package com.meowmau.lifecycle4android.app;
import android.app.Application;
import com.meowmau.lifecycle4android.core.AppLifecycleManager;
/**
* This class implements the {@link Application} to create the application lifecycle manager easily.
* Developer needs to use this class that could retrieve the application lifecycle manager via the
* {@link AppLifecycleApplication#getAppLifecycleManager()}.
*
* @author Picker Weng (pickerweng@gmail.com)
* @since 2015/11/06
*/
public class AppLifecycleApplication extends Application {
private AppLifecycle _appLifecycle;
/**
* Retrieve the application lifecycle instance.
*
* @return the application lifecycle instance
*/
AppLifecycle getAppLifecycle() {
return _appLifecycle;
}
/**
* Retrieve the application lifecycle manager.
*
* @return the application lifecycle manager.
*/
public AppLifecycleManager getAppLifecycleManager() {
return _appLifecycle;
}
@Override
public void onCreate() {
_appLifecycle = new AppLifecycle(this);
_appLifecycle.start();
super.onCreate();
}
@Override
public void onTerminate() {
super.onTerminate();
_appLifecycle.stop();
}
}
| bsd-3-clause |
jonhare/COMP6208 | app/src/main/java/uk/ac/soton/ecs/comp6208/utils/annotations/Demonstration.java | 695 | package uk.ac.soton.ecs.comp6208.utils.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation describing a demonstration within a lecture. Should be applied to
* the each demonstration class.
*
* @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Demonstration {
/**
* The title of the lecture
*
* @return the title
*/
String title();
/**
* The author
*
* @return the author's name
*/
String author() default "Jonathon Hare <jsh2@ecs.soton.ac.uk>";
}
| bsd-3-clause |
justin-hayes/motech | platform/server-config/src/test/java/org/motechproject/config/monitor/ConfigFileMonitorTest.java | 6559 | package org.motechproject.config.monitor;
import org.apache.commons.vfs2.FileChangeEvent;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.impl.DefaultFileMonitor;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.motechproject.config.core.exception.MotechConfigurationException;
import org.motechproject.config.core.domain.BootstrapConfig;
import org.motechproject.config.core.domain.ConfigLocation;
import org.motechproject.config.core.domain.ConfigSource;
import org.motechproject.config.core.service.CoreConfigurationService;
import org.motechproject.config.service.ConfigurationService;
import org.motechproject.server.config.service.ConfigLoader;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyList;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ConfigFileMonitorTest {
@Mock
private ConfigurationService configurationService;
@Mock
private DefaultFileMonitor fileMonitor;
@Mock
private ConfigLoader configLoader;
@Mock
private CoreConfigurationService coreConfigurationService;
@Mock
private BootstrapConfig bootstrapConfig;
@InjectMocks
private ConfigFileMonitor configFileMonitor = new ConfigFileMonitor();
@Before
public void setUp() {
configFileMonitor.setFileMonitor(fileMonitor);
when(configurationService.loadBootstrapConfig()).thenReturn(bootstrapConfig);
}
@Test
public void shouldProcessExistingFilesAndStartFileMonitorWhileInitializing() throws IOException, URISyntaxException {
final Path tempDirectory = Files.createTempDirectory("motech-config-");
String configLocation = tempDirectory.toString();
when(coreConfigurationService.getConfigLocation()).thenReturn(new ConfigLocation(configLocation));
when(bootstrapConfig.getConfigSource()).thenReturn(ConfigSource.FILE);
configFileMonitor.init();
InOrder inOrder = inOrder(configLoader, configurationService, fileMonitor);
inOrder.verify(configLoader).findExistingConfigs();
inOrder.verify(configurationService).processExistingConfigs((List<File>) any());
final ArgumentCaptor<FileObject> fileObjArgCaptor = ArgumentCaptor.forClass(FileObject.class);
inOrder.verify(fileMonitor).addFile(fileObjArgCaptor.capture());
final FileObject monitoredLocation = fileObjArgCaptor.getValue();
assertEquals(configLocation, new File(monitoredLocation.getURL().toURI()).getAbsolutePath());
inOrder.verify(fileMonitor).start();
}
@Test
public void shouldSaveConfigWhenNewFileCreated() throws IOException {
final String fileName = "res:config/org.motechproject.motech-module1/somemodule.properties";
FileObject fileObject = VFS.getManager().resolveFile(fileName);
configFileMonitor.fileCreated(new FileChangeEvent(fileObject));
verify(configurationService).addOrUpdate(new File(fileObject.getName().getPath()));
}
@Test
public void shouldNotSaveConfigWhenNewFileCreatedIsNotSupported() throws IOException {
final String fileName = "res:config/motech-settings.conf";
FileObject fileObject = VFS.getManager().resolveFile(fileName);
configFileMonitor.fileCreated(new FileChangeEvent(fileObject));
verifyZeroInteractions(configurationService);
}
@Test
public void shouldSaveConfigWhenFileIsChanged() throws IOException {
final String fileName = "res:config/org.motechproject.motech-module1/somemodule.properties";
FileObject fileObject = VFS.getManager().resolveFile(fileName);
configFileMonitor.fileChanged(new FileChangeEvent(fileObject));
verify(configurationService).addOrUpdate(new File(fileObject.getName().getPath()));
}
@Test
public void shouldUpdateFileMonitoringLocation() throws FileSystemException {
final String fileName = "res:config/motech-settings.properties";
ConfigLocation configLocation = new ConfigLocation(fileName);
FileObject newLocation = VFS.getManager().resolveFile(fileName);
when(coreConfigurationService.getConfigLocation()).thenReturn(configLocation);
configFileMonitor.updateFileMonitor();
InOrder inOrder = inOrder(coreConfigurationService, fileMonitor);
inOrder.verify(fileMonitor).stop();
inOrder.verify(fileMonitor).removeFile(any(FileObject.class));
inOrder.verify(coreConfigurationService).getConfigLocation();
inOrder.verify(fileMonitor).addFile(newLocation);
inOrder.verify(fileMonitor).start();
}
@Test
public void shouldDeleteConfigWhenFileIsDeleted() throws FileSystemException {
final String fileName = "res:config/org.motechproject.motech-module1/somemodule.properties";
FileObject fileObject = VFS.getManager().resolveFile(fileName);
configFileMonitor.fileDeleted(new FileChangeEvent(fileObject));
verify(configurationService).deleteByBundle(new File(fileObject.getName().getPath()).getParentFile().getName());
}
@Test
public void shouldNotStartFileMonitorIfConfigLoaderThrowsException() throws IOException {
doThrow(new MotechConfigurationException("file could not be read")).when(configLoader).findExistingConfigs();
configFileMonitor.init();
verify(configurationService, never()).processExistingConfigs(anyList());
verify(fileMonitor, never()).run();
}
@Test
public void shouldNotStartWhenFileSourceIsUI() throws IOException {
when(configurationService.getConfigSource()).thenReturn(ConfigSource.UI);
configFileMonitor.init();
verify(configurationService, never()).processExistingConfigs(anyList());
verify(fileMonitor, never()).run();
}
}
| bsd-3-clause |
vitthal26/IpTweet | src/ip/tweet/util/TrayUtil.java | 3280 | /*
* Copyright (c) 2016, Vitthal Kavitake
*
* 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 IpTweet 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 ip.tweet.util;
import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import ip.tweet.client.IpTweet;
import ip.tweet.constant.ChatConstant;
/**
*
* @author Vitthal Kavitake
*
*/
public class TrayUtil {
static TrayIcon trayIcon = null;
public static void addToTray(final JFrame frame) {
try {
if (SystemTray.isSupported()) {
SystemTray tray = SystemTray.getSystemTray();
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// System.out.println(e.getActionCommand());
if (e.getActionCommand() == null
|| e.getActionCommand().equals("Open"))
frame.setVisible(true);
else if (e.getActionCommand().equals("Exit")) {
IpTweet.exit();
}
}
};
PopupMenu popup = new PopupMenu();
// create menu item for the default action
MenuItem item1 = new MenuItem("Open");
item1.addActionListener(listener);
MenuItem item2 = new MenuItem("Exit");
item2.addActionListener(listener);
popup.add(item1);
popup.add(item2);
trayIcon = new TrayIcon(ImageUtil.getChatIconImage(16,16), SharedData.getInstance().getLoggedInUser()
.getDisplayName() + " on " + ChatConstant.APP_NAME,
popup);
trayIcon.addActionListener(listener);
tray.add(trayIcon);
}
} catch (AWTException e) {
System.err.println(e);
}
}
public static void removeTrayIcon() {
if (trayIcon != null)
SystemTray.getSystemTray().remove(trayIcon);
}
}
| bsd-3-clause |
lvdbor/JavaOSC | modules/core/src/test/java/com/illposed/osc/OSCMessageTest.java | 22629 | /*
* Copyright (C) 2003, C. Ramakrishnan / Illposed Software.
* All rights reserved.
*
* This code is licensed under the BSD 3-Clause license.
* See file LICENSE (or LICENSE.html) for more information.
*/
package com.illposed.osc;
import com.illposed.osc.utility.OSCByteArrayToJavaConverter;
import com.illposed.osc.utility.OSCJavaToByteArrayConverter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* @author Chandrasekhar Ramakrishnan
* @see OSCMessage
*/
public class OSCMessageTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
/**
* @param result received from OSC
* @param answer what should have been received
*/
public static void checkResultEqualsAnswer(byte[] result, byte[] answer) {
if (result.length != answer.length) {
Assert.fail(createErrorString("Result and answer aren't the same length, "
+ result.length + " vs " + answer.length + ".", result, answer));
}
for (int i = 0; i < result.length; i++) {
if (result[i] != answer[i]) {
Assert.fail(createErrorString("Failed to convert correctly at position: " + i, result, answer));
}
}
}
public static String createErrorString(final String description, final byte[] result, final byte[] answer) {
return description
+ "\n result (str): \"" + new String(result) + "\""
+ "\n answer (str): \"" + new String(answer) + "\""
+ "\n result (raw): \"" + convertByteArrayToJavaCode(result) + "\""
+ "\n answer (raw): \"" + convertByteArrayToJavaCode(answer) + "\"";
}
/**
* Can be used when creating new test cases.
* @param data to be converted to java code that (re-)creates this same byte array
* @return one line of code that creates the given data in Java
*/
private static String convertByteArrayToJavaCode(final byte[] data) {
StringBuilder javaCode = new StringBuilder();
javaCode.append("{ ");
for (byte b : data) {
javaCode.append((int) b).append(", ");
}
javaCode.delete(javaCode.length() - 2, javaCode.length());
javaCode.append(" };");
return javaCode.toString();
}
@Test
public void testEmpty() {
List<Object> args = new ArrayList<Object>(0);
OSCMessage message = new OSCMessage("/empty", args);
byte[] answer = { 47, 101, 109, 112, 116, 121, 0, 0, 44, 0, 0, 0 };
byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testFillerBeforeCommaNone() {
final List<Object> args = new ArrayList<Object>(0);
final OSCMessage message = new OSCMessage("/abcdef", args);
// here we only have the addresses string terminator (0) before the ',' (44),
// so the comma is 4 byte aligned
final byte[] answer = { 47, 97, 98, 99, 100, 101, 102, 0, 44, 0, 0, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testFillerBeforeCommaOne() {
final List<Object> args = new ArrayList<Object>(0);
final OSCMessage message = new OSCMessage("/abcde", args);
// here we have one padding 0 after the addresses string terminator (also 0)
// and before the ',' (44), so the comma is 4 byte aligned
final byte[] answer = { 47, 97, 98, 99, 100, 101, 0, 0, 44, 0, 0, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testFillerBeforeCommaTwo() {
final List<Object> args = new ArrayList<Object>(0);
final OSCMessage message = new OSCMessage("/abcd", args);
// here we have two padding 0's after the addresses string terminator (also 0)
// and before the ',' (44), so the comma is 4 byte aligned
final byte[] answer = { 47, 97, 98, 99, 100, 0, 0, 0, 44, 0, 0, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testFillerBeforeCommaThree() {
final List<Object> args = new ArrayList<Object>(0);
final OSCMessage message = new OSCMessage("/abcdefg", args);
// here we have three padding 0's after the addresses string terminator (also 0)
// and before the ',' (44), so the comma is 4 byte aligned
final byte[] answer = { 47, 97, 98, 99, 100, 101, 102, 103, 0, 0, 0, 0, 44, 0, 0, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentInteger() {
final List<Object> args = new ArrayList<Object>(1);
args.add(99);
final OSCMessage message = new OSCMessage("/int", args);
final byte[] answer = { 47, 105, 110, 116, 0, 0, 0, 0, 44, 105, 0, 0, 0, 0, 0, 99 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentFloat() {
final List<Object> args = new ArrayList<Object>(1);
args.add(999.9f);
final OSCMessage message = new OSCMessage("/float", args);
final byte[] answer = { 47, 102, 108, 111, 97, 116, 0, 0, 44, 102, 0, 0, 68, 121, -7, -102 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentDouble() {
final List<Object> args = new ArrayList<Object>(1);
args.add(777777.777);
final OSCMessage message = new OSCMessage("/double", args);
final byte[] answer = {
47, 100, 111, 117, 98, 108, 101, 0, 44, 100, 0, 0, 65, 39, -68, 99, -115, -46, -15, -86
};
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentCharacter() {
final List<Object> args = new ArrayList<Object>(1);
args.add('x');
final OSCMessage message = new OSCMessage("/char", args);
final byte[] answer = { 47, 99, 104, 97, 114, 0, 0, 0, 44, 99, 0, 0, 120, 0, 0, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentBlob() {
final List<Object> args = new ArrayList<Object>(1);
args.add(new byte[] { -1, 0, 1 });
final OSCMessage message = new OSCMessage("/blob", args);
final byte[] answer = { 47, 98, 108, 111, 98, 0, 0, 0, 44, 98, 0, 0, 0, 0, 0, 3, -1, 0, 1, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentImpulse() {
final List<Object> args = new ArrayList<Object>(1);
args.add(OSCImpulse.INSTANCE);
final OSCMessage message = new OSCMessage("/impulse", args);
final byte[] answer = { 47, 105, 109, 112, 117, 108, 115, 101, 0, 0, 0, 0, 44, 73, 0, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentLong() {
final List<Object> args = new ArrayList<Object>(1);
args.add(Long.MAX_VALUE);
final OSCMessage message = new OSCMessage("/long", args);
final byte[] answer = {
47, 108, 111, 110, 103, 0, 0, 0, 44, 104, 0, 0, 127, -1, -1, -1, -1, -1, -1, -1 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentTimestamp0() {
final List<Object> args = new ArrayList<Object>(1);
args.add(new Date(0L));
final OSCMessage message = new OSCMessage("/timestamp0", args);
final byte[] answer = { 47, 116, 105, 109, 101, 115, 116, 97, 109, 112, 48, 0, 44, 116, 0, 0, -125, -86, 126, -128, 0, 0, 0, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentTimestamp2000() {
final List<Object> args = new ArrayList<Object>(1);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(2000, 0, 0);
args.add(calendar.getTime());
final OSCMessage message = new OSCMessage("/timestamp2000", args);
final byte[] answer = { 47, 116, 105, 109, 101, 115, 116, 97, 109, 112, 50, 48, 48, 48, 0, 0, 44, 116, 0, 0, -68, 22, 98, 112, 0, 0, 0, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentTimestampAfterFeb2036() {
final List<Object> args = new ArrayList<Object>(1);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(2037, 0, 0);
args.add(calendar.getTime());
final OSCMessage message = new OSCMessage("/timestampAfterFeb2036", args);
final byte[] answer = { 47, 116, 105, 109, 101, 115, 116, 97, 109, 112, 65, 102, 116, 101, 114, 70, 101, 98, 50, 48, 51, 54, 0, 0, 44, 116, 0, 0, 1, -80, 2, -16, 0, 0, 0, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testAtLeastOneZeroAfterAddressAndTypesAndArgumentStrings() {
final List<Object> args = new ArrayList<Object>(3);
// We add 3 arguments.
// Together with the comma before the types,
// this creates a 4 byte aligned stream again (",sii").
// In order to separate the types from the argument data,
// an other four zeros have to appear on the stream.
// This is what we check for here.
//
// We also test for at least one zero after argument strings here (8 % 4 = 0)
args.add("iiffsstt"); // This would be interpreted as a continuation of the types if they were not zero terminated.
args.add(-2);
args.add(-3);
// We do the same with the address.
final OSCMessage message = new OSCMessage("/ZAT", args);
final byte[] answer = {
47, 90, 65, 84, 0, 0, 0, 0,
44, 115, 105, 105, 0, 0, 0, 0,
105, 105, 102, 102, 115, 115, 116, 116, 0, 0, 0, 0,
-1, -1, -1, -2,
-1, -1, -1, -3 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentTrue() {
final List<Object> args = new ArrayList<Object>(1);
args.add(true);
final OSCMessage message = new OSCMessage("/true", args);
final byte[] answer = { 47, 116, 114, 117, 101, 0, 0, 0, 44, 84, 0, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentFalse() {
final List<Object> args = new ArrayList<Object>(1);
args.add(false);
final OSCMessage message = new OSCMessage("/false", args);
final byte[] answer = { 47, 102, 97, 108, 115, 101, 0, 0, 44, 70, 0, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentNull() {
final List<Object> args = new ArrayList<Object>(1);
args.add(null);
final OSCMessage message = new OSCMessage("/null", args);
final byte[] answer = { 47, 110, 117, 108, 108, 0, 0, 0, 44, 78, 0, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testDecreaseVolume() {
List<Object> args = new ArrayList<Object>(2);
args.add(1);
args.add(0.2f);
OSCMessage message = new OSCMessage("/sc/mixer/volume", args);
byte[] answer = {
47, 115, 99, 47, 109, 105, 120, 101, 114, 47, 118, 111,
108, 117, 109, 101, 0, 0, 0, 0, 44, 105, 102, 0, 0, 0, 0,
1, 62, 76, -52, -51 };
byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
/**
* See the comment in
* {@link com.illposed.osc.utility.OSCJavaToByteArrayConverterTest#testPrintFloat2OnStream}.
*/
@Test
public void testIncreaseVolume() {
List<Object> args = new ArrayList<Object>(2);
args.add(1);
args.add(1.0f);
OSCMessage message = new OSCMessage("/sc/mixer/volume", args);
byte[] answer = {
47, 115, 99, 47, 109, 105, 120, 101, 114, 47, 118, 111, 108,
117, 109, 101, 0, 0, 0, 0, 44, 105, 102, 0, 0, 0, 0, 1, 63,
(byte) 128, 0, 0};
byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testPrintStringOnStream() {
OSCJavaToByteArrayConverter stream = new OSCJavaToByteArrayConverter();
stream.write("/example1");
stream.write(100);
byte[] answer =
{47, 101, 120, 97, 109, 112, 108, 101, 49, 0, 0, 0, 0, 0, 0, 100};
byte[] result = stream.toByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testRun() {
OSCMessage message = new OSCMessage("/sc/run");
byte[] answer = {47, 115, 99, 47, 114, 117, 110, 0, 44, 0, 0, 0};
byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testStop() {
OSCMessage message = new OSCMessage("/sc/stop");
byte[] answer = {47, 115, 99, 47, 115, 116, 111, 112, 0, 0, 0, 0, 44, 0, 0, 0};
byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testCreateSynth() {
OSCMessage message = new OSCMessage("/s_new");
message.addArgument(1001);
message.addArgument("freq");
message.addArgument(440.0f);
byte[] answer = {0x2F, 0x73, 0x5F, 0x6E, 0x65, 0x77, 0, 0, 0x2C, 0x69, 0x73, 0x66, 0, 0, 0, 0, 0, 0, 0x3, (byte) 0xE9, 0x66, 0x72, 0x65, 0x71, 0, 0, 0, 0, 0x43, (byte) 0xDC, 0, 0};
byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentCollectionsMixed() {
final List<Object> args = new ArrayList<Object>(5);
final Collection<Integer> singleType = new HashSet<Integer>();
singleType.add(-1);
singleType.add(0);
singleType.add(1);
singleType.add(2);
singleType.add(-1); // double entry; discarded becasue we have a Set
singleType.add(99);
final Collection<Object> allTypes = new LinkedList<Object>();
allTypes.add(null);
allTypes.add(Boolean.TRUE);
allTypes.add(Boolean.FALSE);
allTypes.add(OSCImpulse.INSTANCE);
allTypes.add(1);
allTypes.add(1.0f);
allTypes.add(1.0);
allTypes.add(new byte[] { -99, -1, 0, 1, 99 });
allTypes.add(1L);
allTypes.add('h');
allTypes.add("hello world!");
allTypes.add(new Date(0L));
args.add("firstArg");
args.add(singleType);
args.add("middleArg");
args.add(allTypes);
args.add("lastArg");
final OSCMessage message = new OSCMessage("/collectionsMixed", args);
final byte[] answer = { 47, 99, 111, 108, 108, 101, 99, 116, 105, 111, 110, 115, 77, 105, 120, 101, 100, 0, 0, 0, 44, 115, 91, 105, 105, 105, 105, 105, 93, 115, 91, 78, 84, 70, 73, 105, 102, 100, 98, 104, 99, 115, 116, 93, 115, 0, 0, 0, 102, 105, 114, 115, 116, 65, 114, 103, 0, 0, 0, 0, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 99, 109, 105, 100, 100, 108, 101, 65, 114, 103, 0, 0, 0, 0, 0, 0, 1, 63, -128, 0, 0, 63, -16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, -99, -1, 0, 1, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 104, 0, 0, 0, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33, 0, 0, 0, 0, -125, -86, 126, -128, 0, 0, 0, 0, 108, 97, 115, 116, 65, 114, 103, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testArgumentCollectionsRecursiveMixed() {
final List<Object> args = new ArrayList<Object>(5);
final Collection<Object> fourthLevel = new LinkedList<Object>();
fourthLevel.add(null);
fourthLevel.add(Boolean.TRUE);
fourthLevel.add(Boolean.FALSE);
fourthLevel.add(OSCImpulse.INSTANCE);
fourthLevel.add(1);
fourthLevel.add(1.0f);
fourthLevel.add(1.0);
fourthLevel.add(new byte[] { -99, -1, 0, 1, 99 });
fourthLevel.add(1L);
fourthLevel.add('h');
fourthLevel.add("hello world!");
fourthLevel.add(new Date(0L));
final Collection<Object> thirdLevel = new LinkedList<Object>();
thirdLevel.add(fourthLevel);
thirdLevel.add(-1);
thirdLevel.add('h');
thirdLevel.add(9.9);
final Collection<Object> secondLevel = new LinkedList<Object>();
secondLevel.add(0);
secondLevel.add(thirdLevel);
secondLevel.add('e');
secondLevel.add(8.8);
final Collection<Object> firstLevel = new LinkedList<Object>();
firstLevel.add(1);
firstLevel.add('l');
firstLevel.add(secondLevel);
firstLevel.add(7.7);
args.add("firstArg");
args.add(firstLevel);
args.add("lastArg");
final OSCMessage message = new OSCMessage("/collectionsRecursive", args);
final byte[] answer = { 47, 99, 111, 108, 108, 101, 99, 116, 105, 111, 110, 115, 82, 101, 99, 117, 114, 115, 105, 118, 101, 0, 0, 0, 44, 115, 91, 105, 99, 91, 105, 91, 91, 78, 84, 70, 73, 105, 102, 100, 98, 104, 99, 115, 116, 93, 105, 99, 100, 93, 99, 100, 93, 100, 93, 115, 0, 0, 0, 0, 102, 105, 114, 115, 116, 65, 114, 103, 0, 0, 0, 0, 0, 0, 0, 1, 108, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 63, -128, 0, 0, 63, -16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, -99, -1, 0, 1, 99, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 104, 0, 0, 0, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33, 0, 0, 0, 0, -125, -86, 126, -128, 0, 0, 0, 0, -1, -1, -1, -1, 104, 0, 0, 0, 64, 35, -52, -52, -52, -52, -52, -51, 101, 0, 0, 0, 64, 33, -103, -103, -103, -103, -103, -102, 64, 30, -52, -52, -52, -52, -52, -51, 108, 97, 115, 116, 65, 114, 103, 0 };
final byte[] result = message.getByteArray();
checkResultEqualsAnswer(result, answer);
}
@Test
public void testEncodeLong() {
OSCMessage message = new OSCMessage("/dummy");
Long one001 = 1001L;
message.addArgument(one001);
byte[] byteArray = message.getByteArray();
OSCByteArrayToJavaConverter converter = new OSCByteArrayToJavaConverter();
OSCMessage packet = (OSCMessage) converter.convert(byteArray, byteArray.length);
if (!packet.getAddress().equals("/dummy")) {
Assert.fail("Send Big Integer did not receive the correct address");
}
List<Object> arguments = packet.getArguments();
if (arguments.size() != 1) {
Assert.fail("Send Big Integer should have 1 argument, not " + arguments.size());
}
if (!(arguments.get(0) instanceof Long)) {
Assert.fail("arguments.get(0) should be a Long, not " + arguments.get(0).getClass());
}
if (!(new Long(1001L).equals(arguments.get(0)))) {
Assert.fail("Instead of Long(1001), received " + arguments.get(0));
}
}
@Test
public void testEncodeArray() {
OSCMessage message = new OSCMessage("/dummy");
List<Float> floats = new ArrayList<Float>(2);
floats.add(10.0f);
floats.add(100.0f);
message.addArgument(floats);
byte[] byteArray = message.getByteArray();
OSCByteArrayToJavaConverter converter = new OSCByteArrayToJavaConverter();
OSCMessage packet = (OSCMessage) converter.convert(byteArray, byteArray.length);
if (!packet.getAddress().equals("/dummy")) {
Assert.fail("Send Array did not receive the correct address");
}
List<Object> arguments = packet.getArguments();
if (arguments.size() != 1) {
Assert.fail("Send Array should have 1 argument, not " + arguments.size());
}
if (!(arguments.get(0) instanceof List)) {
Assert.fail("arguments.get(0) should be a Object array, not " + arguments.get(0));
}
for (int i = 0; i < 2; ++i) {
List<Object> theArray = (List<Object>) arguments.get(0);
if (!floats.get(i).equals(theArray.get(i))) {
Assert.fail("Array element " + i + " should be " + floats.get(i) + " not " + theArray.get(i));
}
}
}
@Test
public void testAddressValidationFrontendCtorNull() {
// expect no exception, as we could still set a valid address later on
OSCMessage oscMessage = new OSCMessage(null);
}
@Test
public void testAddressValidationFrontendSetterNull() {
OSCMessage oscMessage = new OSCMessage();
// expect no exception, as we could still set a valid address later on
oscMessage.setAddress(null);
}
@Test
public void testAddressValidationFrontendCtorValid() {
// expect no exception, as the address is valid
OSCMessage oscMessage = new OSCMessage("/hello/world");
}
@Test
public void testAddressValidationFrontendSetterValid() {
OSCMessage oscMessage = new OSCMessage();
// expect no exception, as the address is valid
oscMessage.setAddress("/hello/world");
}
@Test
public void testAddressValidationFrontendCtorInvalid() {
expectedException.expect(IllegalArgumentException.class);
OSCMessage oscMessage = new OSCMessage("/ hello/world");
}
@Test
public void testAddressValidationFrontendSetterInvalid() {
OSCMessage oscMessage = new OSCMessage();
expectedException.expect(IllegalArgumentException.class);
oscMessage.setAddress("/ hello/world");
}
@Test
public void testAddressValidation() {
Assert.assertFalse(OSCMessage.isValidAddress(null));
Assert.assertFalse(OSCMessage.isValidAddress("hello/world"));
Assert.assertFalse(OSCMessage.isValidAddress("/ hello/world"));
Assert.assertFalse(OSCMessage.isValidAddress("/#hello/world"));
Assert.assertFalse(OSCMessage.isValidAddress("/*hello/world"));
Assert.assertFalse(OSCMessage.isValidAddress("/,hello/world"));
Assert.assertFalse(OSCMessage.isValidAddress("/?hello/world"));
Assert.assertFalse(OSCMessage.isValidAddress("/[hello/world"));
Assert.assertFalse(OSCMessage.isValidAddress("/]hello/world"));
Assert.assertFalse(OSCMessage.isValidAddress("/{hello/world"));
Assert.assertFalse(OSCMessage.isValidAddress("/}hello/world"));
Assert.assertFalse(OSCMessage.isValidAddress("//hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/hello"));
Assert.assertTrue( OSCMessage.isValidAddress("/hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/hello/world/two"));
Assert.assertTrue( OSCMessage.isValidAddress("/123/world/two"));
Assert.assertTrue( OSCMessage.isValidAddress("/!hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/~hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/`hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/@hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/$hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/%hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/€hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/^hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/&hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/(hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/)hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/-hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/_hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/+hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/=hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/.hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/<hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/>hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/;hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/:hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/'hello/world"));
Assert.assertTrue( OSCMessage.isValidAddress("/\"hello/world"));
}
}
| bsd-3-clause |
flixel-gdx/flixel-gdx-box2d | flixel-gdx-box2d-core/src/org/flxbox2d/dynamics/joints/B2FlxWeldJoint.java | 2769 | package org.flxbox2d.dynamics.joints;
import org.flxbox2d.B2FlxB;
import org.flxbox2d.collision.shapes.B2FlxShape;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.JointDef;
import com.badlogic.gdx.physics.box2d.joints.WeldJoint;
import com.badlogic.gdx.physics.box2d.joints.WeldJointDef;
/**
* A weld joint essentially glues two bodies together. A weld joint may
* distort somewhat because the island constraint solver is approximate.
*
* @author Ka Wing Chin
*/
public class B2FlxWeldJoint extends B2FlxJoint
{
/**
* Creates a weld joint.
* @param spriteA
* @param spriteB
* @param jointDef
*/
public B2FlxWeldJoint(B2FlxShape spriteA, B2FlxShape spriteB, WeldJointDef jointDef)
{
super(spriteA, spriteB, jointDef);
}
/**
* Creates a weld joint.
* @param spriteA
* @param spriteB
*/
public B2FlxWeldJoint(B2FlxShape spriteA, B2FlxShape spriteB)
{
this(spriteA, spriteB, null);
}
/**
* Create the jointDef.
*/
@Override
protected void setupJointDef()
{
if(jointDef == null)
jointDef = new WeldJointDef();
}
@Override
protected void setDefaults()
{
anchorA = bodyA.getWorldCenter();
super.setDefaults();
}
/**
* Creates the joint.
* @return This joint. Handy for chaining stuff together.
*/
@Override
public B2FlxWeldJoint create()
{
((WeldJointDef)jointDef).initialize(bodyA, bodyB, anchorA);
joint = B2FlxB.world.createJoint(jointDef);
return this;
}
@Override
public WeldJoint getJoint(){return (WeldJoint)joint;}
@Override
public B2FlxWeldJoint setJointDef(JointDef jointDef){super.setJointDef(jointDef);return this;}
@Override
public B2FlxWeldJoint setBodyA(Body bodyA){super.setBodyA(bodyA);return this;}
@Override
public B2FlxWeldJoint setBodyB(Body bodyB){super.setBodyB(bodyB);return this;}
@Override
public B2FlxWeldJoint setAnchorA(Vector2 anchorA){super.setAnchorA(anchorA);return this;}
@Override
public B2FlxWeldJoint setAnchorB(Vector2 anchorB){super.setAnchorB(anchorB);return this;}
@Override
public B2FlxWeldJoint setCollideConnected(boolean collideConnected){super.setCollideConnected(collideConnected);return this;}
@Override
public B2FlxWeldJoint setShowLine(boolean showLine){super.setShowLine(showLine);return this;}
@Override
public B2FlxWeldJoint setLineThickness(float lineThickness){super.setLineThickness(lineThickness);return this;}
@Override
public B2FlxWeldJoint setLineColor(int lineColor){super.setLineColor(lineColor);return this;}
@Override
public B2FlxWeldJoint setLineAlpha(float lineAlpha){super.setLineAlpha(lineAlpha);return this;}
@Override
public B2FlxWeldJoint setSurvive(boolean survive){super.setSurvive(survive);return this;}
}
| bsd-3-clause |
cdegroot/sgame | src/main/java/jgame/platform/JGCanvas.java | 6534 | package jgame.platform;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Toolkit;
import javax.swing.ListCellRenderer;
import jgame.JGObject;
import jgame.impl.JGameError;
/** JGCanvas is internally used by JGEngine for updating and drawing objects
* and tiles, and handling keyboard/mouse events.
*/
class JGCanvas extends Canvas {
/**
*
*/
private final JGEngine jgEngine;
// part of the "official" method of handling keyboard focus
public boolean isFocusTraversable() { return true; }
/*====== init stuff ======*/
public JGCanvas (JGEngine jgEngine, int winwidth, int winheight) {
super();
this.jgEngine = jgEngine;
setSize(winwidth,winheight);
}
/** Determines whether repaint will show the game graphics or do
* nothing. */
boolean is_initialised=false;
/** paint interface that is used when the canvas is not initialised (for
* displaying status info while starting up, loading files, etc. */
private ListCellRenderer initpainter=null;
String progress_message="Please wait, loading files .....";
String author_message="JGame 3.4";
/** for displaying progress bar, value between 0.0 - 1.0 */
double progress_bar=0.0;
void setInitialised() {
is_initialised=true;
initpainter=null;
}
void setInitPainter(ListCellRenderer painter) {
initpainter=painter;
}
void setProgressBar(double pos) {
progress_bar=pos;
if (!is_initialised && initpainter!=null) repaint(100);
}
void setProgressMessage(String msg) {
progress_message=msg;
if (!is_initialised && initpainter!=null) repaint(100);
}
void setAuthorMessage(String msg) {
author_message=msg;
if (!is_initialised && initpainter!=null) repaint(100);
}
/*====== paint ======*/
/** Don't call directly. Use repaint().
*/
public void update(Graphics g) { paint(g); }
/** Don't call directly. Use repaint().
*/
public void paint(Graphics g) { try {
if (this.jgEngine.el.is_exited) {
this.jgEngine.paintExitMessage(g);
return;
}
if (!is_initialised) {
if (initpainter!=null) {
//if (buffer==null) {
// buffer=createImage(width,height);
//}
//if (incremental_repaint) {
//initpainter.getListCellRendererComponent(null,
// buffer.getGraphics(),0,true,false);
// g.drawImage(buffer,0,0,this);
//} else {
initpainter.getListCellRendererComponent(null,
getGraphics(),0,false,false);
//}
}
return;
}
/* Each frame before the paint operation, we check if our possibly
* volatile bg and buffer are still ok. If so, we don't re-validate
* every time, but leave them as persistent images until their
* contents are eventually destroyed. Then we always recreate them
* even if their status is RESTORED. Note that bg is indeed
* persistent, and things are incrementally drawn on it during the
* course of doFrames and paints. If the buffer to be rendered to
* screen is invalid when we render it to screen, we give up for this
* frame and don't retry until the next frame. */
if (this.jgEngine.background==null||!JREImage.isScratchImageValid(this.jgEngine.background)) {
this.jgEngine.background=JREImage.createScratchImage(
this.jgEngine.el.width+3*this.jgEngine.el.scaledtilex,this.jgEngine.el.height+3*this.jgEngine.el.scaledtiley );
this.jgEngine.el.invalidateBGTiles();
}
if (this.jgEngine.buffer==null||!JREImage.isScratchImageValid(this.jgEngine.buffer)) {
this.jgEngine.buffer=JREImage.createScratchImage(this.jgEngine.el.width,this.jgEngine.el.height);
}
if (this.jgEngine.buffer!=null && this.jgEngine.background!=null) {
// block update thread
synchronized (this.jgEngine.objects.objects) {
// paint any part of bg which is not yet defined
this.jgEngine.el.repaintBG(this.jgEngine);
/* clear buffer */
Graphics bufg = this.jgEngine.buffer.getGraphics();
this.jgEngine.buf_gfx = bufg; // enable objects to draw on buffer gfx.
//bufg.setColor(getBackground());
//draw background to buffer
//bufg.drawImage(background,-scaledtilex,-scaledtiley,this);
int tilexshift=this.jgEngine.el.moduloFloor(this.jgEngine.el.tilexofs+1,this.jgEngine.el.viewnrtilesx+3);
int tileyshift=this.jgEngine.el.moduloFloor(this.jgEngine.el.tileyofs+1,this.jgEngine.el.viewnrtilesy+3);
int sx1 = tilexshift+1;
int sy1 = tileyshift+1;
int sx2 = this.jgEngine.el.viewnrtilesx+3;
int sy2 = this.jgEngine.el.viewnrtilesy+3;
if (sx2-sx1 > this.jgEngine.el.viewnrtilesx) sx2 = sx1 + this.jgEngine.el.viewnrtilesx;
if (sy2-sy1 > this.jgEngine.el.viewnrtilesy) sy2 = sy1 + this.jgEngine.el.viewnrtilesy;
int bufmidx = sx2-sx1;
int bufmidy = sy2-sy1;
this.jgEngine.copyBGToBuf(bufg,sx1,sy1, sx2,sy2, 0,0);
sx1 = 0;
sy1 = 0;
sx2 = tilexshift-1;
sy2 = tileyshift-1;
this.jgEngine.copyBGToBuf(bufg,sx1,sy1, sx2,sy2, bufmidx,bufmidy);
sx1 = 0;
sy1 = tileyshift+1;
sx2 = tilexshift-1;
sy2 = this.jgEngine.el.viewnrtilesy+3;
if (sy2-sy1 > this.jgEngine.el.viewnrtilesy) sy2 = sy1 + this.jgEngine.el.viewnrtilesy;
this.jgEngine.copyBGToBuf(bufg,sx1,sy1, sx2,sy2, bufmidx,0);
sx1 = tilexshift+1;
sy1 = 0;
sx2 = this.jgEngine.el.viewnrtilesx+3;
sy2 = tileyshift-1;
if (sx2-sx1 > this.jgEngine.el.viewnrtilesx) sx2 = sx1 + this.jgEngine.el.viewnrtilesx;
this.jgEngine.copyBGToBuf(bufg,sx1,sy1, sx2,sy2, 0,bufmidy);
//Color defaultcolour=g.getColor();
///* sort objects */
//ArrayList sortedkeys = new ArrayList(objects.keySet());
//Collections.sort(sortedkeys);
//for (Iterator i=sortedkeys.iterator(); i.hasNext(); ) {
for (int i=0; i<this.jgEngine.objects.objects.size(); i++) {
this.jgEngine.drawObject(bufg, (JGObject)this.jgEngine.objects.objects.valueAt(i));
}
this.jgEngine.buf_gfx = null; // we're finished with the object drawing
/* draw status */
if (bufg!=null) this.jgEngine.paintFrame(bufg);
//}/*synchronized */
/* draw buffer */
g.drawImage(this.jgEngine.buffer,0,0,this);
//g.setColor(defaultcolour);
}
// don't block the update thread while waiting for sync
Toolkit.getDefaultToolkit().sync();
}
} catch (JGameError e) {
this.jgEngine.exitEngine("Error during paint:\n"
+this.jgEngine.dbgExceptionToString(e) );
} }
public void dbgShowFullStackTrace(JGEngine jgEngine, boolean enabled) {
if (enabled) jgEngine.debugFrame.debugflags |= DebugFrame.FULLSTACKTRACE_DEBUG;
else jgEngine.debugFrame.debugflags &= ~DebugFrame.FULLSTACKTRACE_DEBUG;
}
} | bsd-3-clause |