repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
Shalashalska/Melior-Metallum | metallum_common/metallum/item/crafting/MetallumCrafting.java | 2705 | package metallum.item.crafting;
import metallum.item.ModItems;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
public class MetallumCrafting {
private static ItemStack vanadiumIngotStack = new ItemStack(ModItems.vanadiumIngot);
private static ItemStack stickStack = new ItemStack(Item.stick);
private static ItemStack thoriumIngotStack = new ItemStack(ModItems.thoriumIngot);
public static void init(){
GameRegistry.addRecipe(new ItemStack(ModItems.vanadiumSword), "v", "v", "s", 'v', vanadiumIngotStack, 's', stickStack);
GameRegistry.addRecipe(new ItemStack(ModItems.vanadiumPick), "vvv", " s ", " s ", 'v', vanadiumIngotStack, 's', stickStack);
GameRegistry.addRecipe(new ItemStack(ModItems.vanadiumShovel), "v", "s", "s", 'v', vanadiumIngotStack, 's', stickStack);
GameRegistry.addRecipe(new ItemStack(ModItems.vanadiumHoe), "vv", "s ", "s ", 'v', vanadiumIngotStack, 's', stickStack);
GameRegistry.addRecipe(new ItemStack(ModItems.vanadiumAxe), "vv", "sv", "s ", 'v', vanadiumIngotStack, 's', stickStack);
GameRegistry.addRecipe(new ItemStack(ModItems.vanadiumHelmet), "vvv", "v v", 'v', vanadiumIngotStack);
GameRegistry.addRecipe(new ItemStack(ModItems.vanadiumChestplate), "v v", "vvv", "vvv", 'v', vanadiumIngotStack);
GameRegistry.addRecipe(new ItemStack(ModItems.vanadiumLeggings), "vvv", "v v", "v v", 'v', vanadiumIngotStack);
GameRegistry.addRecipe(new ItemStack(ModItems.vanadiumBoots), "v v", "v v", 'v', vanadiumIngotStack);
GameRegistry.addRecipe(new ItemStack(ModItems.thoriumSword), "t", "t", "s", 't', thoriumIngotStack, 's', stickStack);
GameRegistry.addRecipe(new ItemStack(ModItems.thoriumPick), "ttt", " s ", " s ", 't', thoriumIngotStack, 's', stickStack);
GameRegistry.addRecipe(new ItemStack(ModItems.thoriumAxe), "tt", "st", "s ", 't', thoriumIngotStack, 's', stickStack);
GameRegistry.addRecipe(new ItemStack(ModItems.thoriumHoe), "tt", "s ", "s ", 't', thoriumIngotStack, 's', stickStack);
GameRegistry.addRecipe(new ItemStack(ModItems.thoriumShovel), "t", "s", "s", 't', thoriumIngotStack, 's', stickStack);
GameRegistry.addRecipe(new ItemStack(ModItems.thoriumHelmet), "ttt", "t t", 't', thoriumIngotStack);
GameRegistry.addRecipe(new ItemStack(ModItems.thoriumChestplate), "t t", "ttt", "ttt", 't', thoriumIngotStack);
GameRegistry.addRecipe(new ItemStack(ModItems.thoriumLeggings), "ttt", "t t", "t t", 't', thoriumIngotStack);
GameRegistry.addRecipe(new ItemStack(ModItems.thoriumBoots), "t t", "t t", 't', thoriumIngotStack);
}
}
| gpl-3.0 |
kungeplay/Java_SimpleDemo | Amq_Producer/src/main/java/AmqProducerTopic.java | 3011 | import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.util.concurrent.TimeUnit;
/**
* Created by jiakun on 17-1-23.
*/
public class AmqProducerTopic {
private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;
private static final int SENDNUM = 20;
public static void main(String[] args) {
//连接工厂
ConnectionFactory connectionFactory;
//连接实例
Connection connection = null;
//收发的线程实例
Session session;
//消息发送目标地址
Destination destination;
//实例化连接工厂
connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);
try {
//获取连接实例
connection = connectionFactory.createConnection();
//启动连接
connection.start();
//创建接收或发送的线程实例(创建session的时候定义是否要启用事务,且事务类型是AUTO_ACKNOWLEDGE也就是消费者成功在Listen中获得消息返回时,会话自动确定用户收到消息)
session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
//创建队列(返回一个消息目的地)
destination = session.createTopic("FirstTop");
//创建消息发布者
MessageProducer messageProducer = session.createProducer(destination);
//设置不持久化,此处学习,实际根据项目决定,默认PERSISTENT
messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
sendMessage(session,messageProducer);
} catch (JMSException e) {
e.printStackTrace();
}finally {
if (connection!=null){
try {
connection.close();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
}
public static void sendMessage(Session session, MessageProducer messageProducer) throws JMSException {
for (int i = 0; i < SENDNUM; i++) {
//创建一条文本消息
TextMessage message = session.createTextMessage("ActiveMQ 发布者订阅模型发送消息" + i);
System.out.println("发送消息:amq发送消息" + i);
//通过消息生产者发出消息
messageProducer.send(message);
session.commit();//注意如果session是以开启事务的方式创建必须session.commit()才能提交消息到服务器队列,session.close()服务器将收不到消息
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| gpl-3.0 |
sandulachedumitru/BasicTopography | src/main/java/com/miticorp/topography/basic/model/DistanceTypeMetricMillimeter.java | 889 | package com.miticorp.topography.basic.model;
public class DistanceTypeMetricMillimeter extends DistanceTypeMetric {
private final Double conversionToMeter = 1D / 1000;
@Override
public Double getConversionToMeter() {
return conversionToMeter;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((conversionToMeter == null) ? 0 : conversionToMeter.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DistanceTypeMetricMillimeter other = (DistanceTypeMetricMillimeter) obj;
if (conversionToMeter == null) {
if (other.conversionToMeter != null)
return false;
} else if (!conversionToMeter.equals(other.conversionToMeter))
return false;
return true;
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | frameworks/base/core/java/android/util/ArraySet.java | 22315 | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.util;
import libcore.util.EmptyArray;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* ArraySet is a generic set data structure that is designed to be more memory efficient than a
* traditional {@link java.util.HashSet}. The design is very similar to
* {@link ArrayMap}, with all of the caveats described there. This implementation is
* separate from ArrayMap, however, so the Object array contains only one item for each
* entry in the set (instead of a pair for a mapping).
*
* <p>Note that this implementation is not intended to be appropriate for data structures
* that may contain large numbers of items. It is generally slower than a traditional
* HashSet, since lookups require a binary search and adds and removes require inserting
* and deleting entries in the array. For containers holding up to hundreds of items,
* the performance difference is not significant, less than 50%.</p>
*
* <p>Because this container is intended to better balance memory use, unlike most other
* standard Java containers it will shrink its array as items are removed from it. Currently
* you have no control over this shrinking -- if you set a capacity and then remove an
* item, it may reduce the capacity to better match the current size. In the future an
* explicit call to set the capacity should turn off this aggressive shrinking behavior.</p>
*
* @hide
*/
public final class ArraySet<E> implements Collection<E>, Set<E> {
private static final boolean DEBUG = false;
private static final String TAG = "ArraySet";
/**
* The minimum amount by which the capacity of a ArraySet will increase.
* This is tuned to be relatively space-efficient.
*/
private static final int BASE_SIZE = 4;
/**
* Maximum number of entries to have in array caches.
*/
private static final int CACHE_SIZE = 10;
/**
* Caches of small array objects to avoid spamming garbage. The cache
* Object[] variable is a pointer to a linked list of array objects.
* The first entry in the array is a pointer to the next array in the
* list; the second entry is a pointer to the int[] hash code array for it.
*/
static Object[] mBaseCache;
static int mBaseCacheSize;
static Object[] mTwiceBaseCache;
static int mTwiceBaseCacheSize;
int[] mHashes;
Object[] mArray;
int mSize;
MapCollections<E, E> mCollections;
private int indexOf(Object key, int hash) {
final int N = mSize;
// Important fast case: if nothing is in here, nothing to look for.
if (N == 0) {
return ~0;
}
int index = ContainerHelpers.binarySearch(mHashes, N, hash);
// If the hash code wasn't found, then we have no entry for this key.
if (index < 0) {
return index;
}
// If the key at the returned index matches, that's what we want.
if (key.equals(mArray[index])) {
return index;
}
// Search for a matching key after the index.
int end;
for (end = index + 1; end < N && mHashes[end] == hash; end++) {
if (key.equals(mArray[end])) return end;
}
// Search for a matching key before the index.
for (int i = index - 1; i >= 0 && mHashes[i] == hash; i--) {
if (key.equals(mArray[i])) return i;
}
// Key not found -- return negative value indicating where a
// new entry for this key should go. We use the end of the
// hash chain to reduce the number of array entries that will
// need to be copied when inserting.
return ~end;
}
private int indexOfNull() {
final int N = mSize;
// Important fast case: if nothing is in here, nothing to look for.
if (N == 0) {
return ~0;
}
int index = ContainerHelpers.binarySearch(mHashes, N, 0);
// If the hash code wasn't found, then we have no entry for this key.
if (index < 0) {
return index;
}
// If the key at the returned index matches, that's what we want.
if (null == mArray[index]) {
return index;
}
// Search for a matching key after the index.
int end;
for (end = index + 1; end < N && mHashes[end] == 0; end++) {
if (null == mArray[end]) return end;
}
// Search for a matching key before the index.
for (int i = index - 1; i >= 0 && mHashes[i] == 0; i--) {
if (null == mArray[i]) return i;
}
// Key not found -- return negative value indicating where a
// new entry for this key should go. We use the end of the
// hash chain to reduce the number of array entries that will
// need to be copied when inserting.
return ~end;
}
private void allocArrays(final int size) {
if (size == (BASE_SIZE*2)) {
synchronized (ArraySet.class) {
if (mTwiceBaseCache != null) {
final Object[] array = mTwiceBaseCache;
mArray = array;
mTwiceBaseCache = (Object[])array[0];
mHashes = (int[])array[1];
array[0] = array[1] = null;
mTwiceBaseCacheSize--;
if (DEBUG) Log.d(TAG, "Retrieving 2x cache " + mHashes
+ " now have " + mTwiceBaseCacheSize + " entries");
return;
}
}
} else if (size == BASE_SIZE) {
synchronized (ArraySet.class) {
if (mBaseCache != null) {
final Object[] array = mBaseCache;
mArray = array;
mBaseCache = (Object[])array[0];
mHashes = (int[])array[1];
array[0] = array[1] = null;
mBaseCacheSize--;
if (DEBUG) Log.d(TAG, "Retrieving 1x cache " + mHashes
+ " now have " + mBaseCacheSize + " entries");
return;
}
}
}
mHashes = new int[size];
mArray = new Object[size];
}
private static void freeArrays(final int[] hashes, final Object[] array, final int size) {
if (hashes.length == (BASE_SIZE*2)) {
synchronized (ArraySet.class) {
if (mTwiceBaseCacheSize < CACHE_SIZE) {
array[0] = mTwiceBaseCache;
array[1] = hashes;
for (int i=size-1; i>=2; i--) {
array[i] = null;
}
mTwiceBaseCache = array;
mTwiceBaseCacheSize++;
if (DEBUG) Log.d(TAG, "Storing 2x cache " + array
+ " now have " + mTwiceBaseCacheSize + " entries");
}
}
} else if (hashes.length == BASE_SIZE) {
synchronized (ArraySet.class) {
if (mBaseCacheSize < CACHE_SIZE) {
array[0] = mBaseCache;
array[1] = hashes;
for (int i=size-1; i>=2; i--) {
array[i] = null;
}
mBaseCache = array;
mBaseCacheSize++;
if (DEBUG) Log.d(TAG, "Storing 1x cache " + array
+ " now have " + mBaseCacheSize + " entries");
}
}
}
}
/**
* Create a new empty ArraySet. The default capacity of an array map is 0, and
* will grow once items are added to it.
*/
public ArraySet() {
mHashes = EmptyArray.INT;
mArray = EmptyArray.OBJECT;
mSize = 0;
}
/**
* Create a new ArraySet with a given initial capacity.
*/
public ArraySet(int capacity) {
if (capacity == 0) {
mHashes = EmptyArray.INT;
mArray = EmptyArray.OBJECT;
} else {
allocArrays(capacity);
}
mSize = 0;
}
/**
* Create a new ArraySet with the mappings from the given ArraySet.
*/
public ArraySet(ArraySet<E> set) {
this();
if (set != null) {
addAll(set);
}
}
/** {@hide} */
public ArraySet(Collection<E> set) {
this();
if (set != null) {
addAll(set);
}
}
/**
* Make the array map empty. All storage is released.
*/
@Override
public void clear() {
if (mSize != 0) {
freeArrays(mHashes, mArray, mSize);
mHashes = EmptyArray.INT;
mArray = EmptyArray.OBJECT;
mSize = 0;
}
}
/**
* Ensure the array map can hold at least <var>minimumCapacity</var>
* items.
*/
public void ensureCapacity(int minimumCapacity) {
if (mHashes.length < minimumCapacity) {
final int[] ohashes = mHashes;
final Object[] oarray = mArray;
allocArrays(minimumCapacity);
if (mSize > 0) {
System.arraycopy(ohashes, 0, mHashes, 0, mSize);
System.arraycopy(oarray, 0, mArray, 0, mSize);
}
freeArrays(ohashes, oarray, mSize);
}
}
/**
* Check whether a value exists in the set.
*
* @param key The value to search for.
* @return Returns true if the value exists, else false.
*/
@Override
public boolean contains(Object key) {
return indexOf(key) >= 0;
}
/**
* Returns the index of a value in the set.
*
* @param key The value to search for.
* @return Returns the index of the value if it exists, else a negative integer.
*/
public int indexOf(Object key) {
return key == null ? indexOfNull() : indexOf(key, key.hashCode());
}
/**
* Return the value at the given index in the array.
* @param index The desired index, must be between 0 and {@link #size()}-1.
* @return Returns the value stored at the given index.
*/
public E valueAt(int index) {
return (E)mArray[index];
}
/**
* Return true if the array map contains no items.
*/
@Override
public boolean isEmpty() {
return mSize <= 0;
}
/**
* Adds the specified object to this set. The set is not modified if it
* already contains the object.
*
* @param value the object to add.
* @return {@code true} if this set is modified, {@code false} otherwise.
* @throws ClassCastException
* when the class of the object is inappropriate for this set.
*/
@Override
public boolean add(E value) {
final int hash;
int index;
if (value == null) {
hash = 0;
index = indexOfNull();
} else {
hash = value.hashCode();
index = indexOf(value, hash);
}
if (index >= 0) {
return false;
}
index = ~index;
if (mSize >= mHashes.length) {
final int n = mSize >= (BASE_SIZE*2) ? (mSize+(mSize>>1))
: (mSize >= BASE_SIZE ? (BASE_SIZE*2) : BASE_SIZE);
if (DEBUG) Log.d(TAG, "add: grow from " + mHashes.length + " to " + n);
final int[] ohashes = mHashes;
final Object[] oarray = mArray;
allocArrays(n);
if (mHashes.length > 0) {
if (DEBUG) Log.d(TAG, "add: copy 0-" + mSize + " to 0");
System.arraycopy(ohashes, 0, mHashes, 0, ohashes.length);
System.arraycopy(oarray, 0, mArray, 0, oarray.length);
}
freeArrays(ohashes, oarray, mSize);
}
if (index < mSize) {
if (DEBUG) Log.d(TAG, "add: move " + index + "-" + (mSize-index)
+ " to " + (index+1));
System.arraycopy(mHashes, index, mHashes, index + 1, mSize - index);
System.arraycopy(mArray, index, mArray, index + 1, mSize - index);
}
mHashes[index] = hash;
mArray[index] = value;
mSize++;
return true;
}
/**
* Perform a {@link #add(Object)} of all values in <var>array</var>
* @param array The array whose contents are to be retrieved.
*/
public void addAll(ArraySet<? extends E> array) {
final int N = array.mSize;
ensureCapacity(mSize + N);
if (mSize == 0) {
if (N > 0) {
System.arraycopy(array.mHashes, 0, mHashes, 0, N);
System.arraycopy(array.mArray, 0, mArray, 0, N);
mSize = N;
}
} else {
for (int i=0; i<N; i++) {
add(array.valueAt(i));
}
}
}
/**
* Removes the specified object from this set.
*
* @param object the object to remove.
* @return {@code true} if this set was modified, {@code false} otherwise.
*/
@Override
public boolean remove(Object object) {
final int index = indexOf(object);
if (index >= 0) {
removeAt(index);
return true;
}
return false;
}
/**
* Remove the key/value mapping at the given index.
* @param index The desired index, must be between 0 and {@link #size()}-1.
* @return Returns the value that was stored at this index.
*/
public E removeAt(int index) {
final Object old = mArray[index];
if (mSize <= 1) {
// Now empty.
if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to 0");
freeArrays(mHashes, mArray, mSize);
mHashes = EmptyArray.INT;
mArray = EmptyArray.OBJECT;
mSize = 0;
} else {
if (mHashes.length > (BASE_SIZE*2) && mSize < mHashes.length/3) {
// Shrunk enough to reduce size of arrays. We don't allow it to
// shrink smaller than (BASE_SIZE*2) to avoid flapping between
// that and BASE_SIZE.
final int n = mSize > (BASE_SIZE*2) ? (mSize + (mSize>>1)) : (BASE_SIZE*2);
if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to " + n);
final int[] ohashes = mHashes;
final Object[] oarray = mArray;
allocArrays(n);
mSize--;
if (index > 0) {
if (DEBUG) Log.d(TAG, "remove: copy from 0-" + index + " to 0");
System.arraycopy(ohashes, 0, mHashes, 0, index);
System.arraycopy(oarray, 0, mArray, 0, index);
}
if (index < mSize) {
if (DEBUG) Log.d(TAG, "remove: copy from " + (index+1) + "-" + mSize
+ " to " + index);
System.arraycopy(ohashes, index + 1, mHashes, index, mSize - index);
System.arraycopy(oarray, index + 1, mArray, index, mSize - index);
}
} else {
mSize--;
if (index < mSize) {
if (DEBUG) Log.d(TAG, "remove: move " + (index+1) + "-" + mSize
+ " to " + index);
System.arraycopy(mHashes, index + 1, mHashes, index, mSize - index);
System.arraycopy(mArray, index + 1, mArray, index, mSize - index);
}
mArray[mSize] = null;
}
}
return (E)old;
}
/**
* Return the number of items in this array map.
*/
@Override
public int size() {
return mSize;
}
@Override
public Object[] toArray() {
Object[] result = new Object[mSize];
System.arraycopy(mArray, 0, result, 0, mSize);
return result;
}
@Override
public <T> T[] toArray(T[] array) {
if (array.length < mSize) {
@SuppressWarnings("unchecked") T[] newArray
= (T[]) Array.newInstance(array.getClass().getComponentType(), mSize);
array = newArray;
}
System.arraycopy(mArray, 0, array, 0, mSize);
if (array.length > mSize) {
array[mSize] = null;
}
return array;
}
/**
* {@inheritDoc}
*
* <p>This implementation returns false if the object is not a set, or
* if the sets have different sizes. Otherwise, for each value in this
* set, it checks to make sure the value also exists in the other set.
* If any value doesn't exist, the method returns false; otherwise, it
* returns true.
*/
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object instanceof Set) {
Set<?> set = (Set<?>) object;
if (size() != set.size()) {
return false;
}
try {
for (int i=0; i<mSize; i++) {
E mine = valueAt(i);
if (!set.contains(mine)) {
return false;
}
}
} catch (NullPointerException ignored) {
return false;
} catch (ClassCastException ignored) {
return false;
}
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
final int[] hashes = mHashes;
int result = 0;
for (int i = 0, s = mSize; i < s; i++) {
result += hashes[i];
}
return result;
}
/**
* {@inheritDoc}
*
* <p>This implementation composes a string by iterating over its values. If
* this set contains itself as a value, the string "(this Set)"
* will appear in its place.
*/
@Override
public String toString() {
if (isEmpty()) {
return "{}";
}
StringBuilder buffer = new StringBuilder(mSize * 14);
buffer.append('{');
for (int i=0; i<mSize; i++) {
if (i > 0) {
buffer.append(", ");
}
Object value = valueAt(i);
if (value != this) {
buffer.append(value);
} else {
buffer.append("(this Set)");
}
}
buffer.append('}');
return buffer.toString();
}
// ------------------------------------------------------------------------
// Interop with traditional Java containers. Not as efficient as using
// specialized collection APIs.
// ------------------------------------------------------------------------
private MapCollections<E, E> getCollection() {
if (mCollections == null) {
mCollections = new MapCollections<E, E>() {
@Override
protected int colGetSize() {
return mSize;
}
@Override
protected Object colGetEntry(int index, int offset) {
return mArray[index];
}
@Override
protected int colIndexOfKey(Object key) {
return indexOf(key);
}
@Override
protected int colIndexOfValue(Object value) {
return indexOf(value);
}
@Override
protected Map<E, E> colGetMap() {
throw new UnsupportedOperationException("not a map");
}
@Override
protected void colPut(E key, E value) {
add(key);
}
@Override
protected E colSetValue(int index, E value) {
throw new UnsupportedOperationException("not a map");
}
@Override
protected void colRemoveAt(int index) {
removeAt(index);
}
@Override
protected void colClear() {
clear();
}
};
}
return mCollections;
}
@Override
public Iterator<E> iterator() {
return getCollection().getKeySet().iterator();
}
@Override
public boolean containsAll(Collection<?> collection) {
Iterator<?> it = collection.iterator();
while (it.hasNext()) {
if (!contains(it.next())) {
return false;
}
}
return true;
}
@Override
public boolean addAll(Collection<? extends E> collection) {
ensureCapacity(mSize + collection.size());
boolean added = false;
for (E value : collection) {
added |= add(value);
}
return added;
}
@Override
public boolean removeAll(Collection<?> collection) {
boolean removed = false;
for (Object value : collection) {
removed |= remove(value);
}
return removed;
}
@Override
public boolean retainAll(Collection<?> collection) {
boolean removed = false;
for (int i=mSize-1; i>=0; i--) {
if (!collection.contains(mArray[i])) {
removeAt(i);
removed = true;
}
}
return removed;
}
}
| gpl-3.0 |
zhangjianying/12306-android-Decompile | src/org/codehaus/jackson/map/ser/ContainerSerializers.java | 24128 | package org.codehaus.jackson.map.ser;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.BeanProperty;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ResolvableSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.TypeSerializer;
import org.codehaus.jackson.map.annotate.JacksonStdImpl;
import org.codehaus.jackson.map.ser.impl.PropertySerializerMap;
import org.codehaus.jackson.map.ser.impl.PropertySerializerMap.SerializerAndMapResult;
import org.codehaus.jackson.node.ObjectNode;
import org.codehaus.jackson.schema.JsonSchema;
import org.codehaus.jackson.schema.SchemaAware;
import org.codehaus.jackson.type.JavaType;
public final class ContainerSerializers
{
public static ContainerSerializerBase<?> collectionSerializer(JavaType paramJavaType, boolean paramBoolean, TypeSerializer paramTypeSerializer, BeanProperty paramBeanProperty, JsonSerializer<Object> paramJsonSerializer)
{
return new CollectionSerializer(paramJavaType, paramBoolean, paramTypeSerializer, paramBeanProperty, paramJsonSerializer);
}
public static JsonSerializer<?> enumSetSerializer(JavaType paramJavaType, BeanProperty paramBeanProperty)
{
return new EnumSetSerializer(paramJavaType, paramBeanProperty);
}
public static ContainerSerializerBase<?> indexedListSerializer(JavaType paramJavaType, boolean paramBoolean, TypeSerializer paramTypeSerializer, BeanProperty paramBeanProperty, JsonSerializer<Object> paramJsonSerializer)
{
return new IndexedListSerializer(paramJavaType, paramBoolean, paramTypeSerializer, paramBeanProperty, paramJsonSerializer);
}
public static ContainerSerializerBase<?> iterableSerializer(JavaType paramJavaType, boolean paramBoolean, TypeSerializer paramTypeSerializer, BeanProperty paramBeanProperty)
{
return new IterableSerializer(paramJavaType, paramBoolean, paramTypeSerializer, paramBeanProperty);
}
public static ContainerSerializerBase<?> iteratorSerializer(JavaType paramJavaType, boolean paramBoolean, TypeSerializer paramTypeSerializer, BeanProperty paramBeanProperty)
{
return new IteratorSerializer(paramJavaType, paramBoolean, paramTypeSerializer, paramBeanProperty);
}
public static abstract class AsArraySerializer<T> extends ContainerSerializerBase<T>
implements ResolvableSerializer
{
protected PropertySerializerMap _dynamicSerializers;
protected JsonSerializer<Object> _elementSerializer;
protected final JavaType _elementType;
protected final BeanProperty _property;
protected final boolean _staticTyping;
protected final TypeSerializer _valueTypeSerializer;
@Deprecated
protected AsArraySerializer(Class<?> paramClass, JavaType paramJavaType, boolean paramBoolean, TypeSerializer paramTypeSerializer, BeanProperty paramBeanProperty)
{
this(paramClass, paramJavaType, paramBoolean, paramTypeSerializer, paramBeanProperty, null);
}
protected AsArraySerializer(Class<?> paramClass, JavaType paramJavaType, boolean paramBoolean, TypeSerializer paramTypeSerializer, BeanProperty paramBeanProperty, JsonSerializer<Object> paramJsonSerializer)
{
super(false);
this._elementType = paramJavaType;
boolean bool1;
if (!paramBoolean)
{
bool1 = false;
if (paramJavaType != null)
{
boolean bool2 = paramJavaType.isFinal();
bool1 = false;
if (!bool2);
}
}
else
{
bool1 = true;
}
this._staticTyping = bool1;
this._valueTypeSerializer = paramTypeSerializer;
this._property = paramBeanProperty;
this._elementSerializer = paramJsonSerializer;
this._dynamicSerializers = PropertySerializerMap.emptyMap();
}
protected final JsonSerializer<Object> _findAndAddDynamic(PropertySerializerMap paramPropertySerializerMap, Class<?> paramClass, SerializerProvider paramSerializerProvider)
throws JsonMappingException
{
PropertySerializerMap.SerializerAndMapResult localSerializerAndMapResult = paramPropertySerializerMap.findAndAddSerializer(paramClass, paramSerializerProvider, this._property);
if (paramPropertySerializerMap != localSerializerAndMapResult.map)
this._dynamicSerializers = localSerializerAndMapResult.map;
return localSerializerAndMapResult.serializer;
}
protected final JsonSerializer<Object> _findAndAddDynamic(PropertySerializerMap paramPropertySerializerMap, JavaType paramJavaType, SerializerProvider paramSerializerProvider)
throws JsonMappingException
{
PropertySerializerMap.SerializerAndMapResult localSerializerAndMapResult = paramPropertySerializerMap.findAndAddSerializer(paramJavaType, paramSerializerProvider, this._property);
if (paramPropertySerializerMap != localSerializerAndMapResult.map)
this._dynamicSerializers = localSerializerAndMapResult.map;
return localSerializerAndMapResult.serializer;
}
public JsonNode getSchema(SerializerProvider paramSerializerProvider, Type paramType)
throws JsonMappingException
{
ObjectNode localObjectNode = createSchemaNode("array", true);
JavaType localJavaType = null;
if (paramType != null)
{
localJavaType = paramSerializerProvider.constructType(paramType).getContentType();
if ((localJavaType == null) && ((paramType instanceof ParameterizedType)))
{
Type[] arrayOfType = ((ParameterizedType)paramType).getActualTypeArguments();
if (arrayOfType.length == 1)
localJavaType = paramSerializerProvider.constructType(arrayOfType[0]);
}
}
if ((localJavaType == null) && (this._elementType != null))
localJavaType = this._elementType;
if (localJavaType != null)
{
Class localClass = localJavaType.getRawClass();
JsonNode localJsonNode = null;
if (localClass != Object.class)
{
JsonSerializer localJsonSerializer = paramSerializerProvider.findValueSerializer(localJavaType, this._property);
boolean bool = localJsonSerializer instanceof SchemaAware;
localJsonNode = null;
if (bool)
localJsonNode = ((SchemaAware)localJsonSerializer).getSchema(paramSerializerProvider, null);
}
if (localJsonNode == null)
localJsonNode = JsonSchema.getDefaultSchemaNode();
localObjectNode.put("items", localJsonNode);
}
return localObjectNode;
}
public void resolve(SerializerProvider paramSerializerProvider)
throws JsonMappingException
{
if ((this._staticTyping) && (this._elementType != null) && (this._elementSerializer == null))
this._elementSerializer = paramSerializerProvider.findValueSerializer(this._elementType, this._property);
}
public final void serialize(T paramT, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider)
throws IOException, JsonGenerationException
{
paramJsonGenerator.writeStartArray();
serializeContents(paramT, paramJsonGenerator, paramSerializerProvider);
paramJsonGenerator.writeEndArray();
}
protected abstract void serializeContents(T paramT, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider)
throws IOException, JsonGenerationException;
public final void serializeWithType(T paramT, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider, TypeSerializer paramTypeSerializer)
throws IOException, JsonGenerationException
{
paramTypeSerializer.writeTypePrefixForArray(paramT, paramJsonGenerator);
serializeContents(paramT, paramJsonGenerator, paramSerializerProvider);
paramTypeSerializer.writeTypeSuffixForArray(paramT, paramJsonGenerator);
}
}
@JacksonStdImpl
public static class CollectionSerializer extends ContainerSerializers.AsArraySerializer<Collection<?>>
{
@Deprecated
public CollectionSerializer(JavaType paramJavaType, boolean paramBoolean, TypeSerializer paramTypeSerializer, BeanProperty paramBeanProperty)
{
this(paramJavaType, paramBoolean, paramTypeSerializer, paramBeanProperty, null);
}
public CollectionSerializer(JavaType paramJavaType, boolean paramBoolean, TypeSerializer paramTypeSerializer, BeanProperty paramBeanProperty, JsonSerializer<Object> paramJsonSerializer)
{
super(paramJavaType, paramBoolean, paramTypeSerializer, paramBeanProperty, paramJsonSerializer);
}
public ContainerSerializerBase<?> _withValueTypeSerializer(TypeSerializer paramTypeSerializer)
{
return new CollectionSerializer(this._elementType, this._staticTyping, paramTypeSerializer, this._property);
}
public void serializeContents(Collection<?> paramCollection, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider)
throws IOException, JsonGenerationException
{
if (this._elementSerializer != null)
serializeContentsUsing(paramCollection, paramJsonGenerator, paramSerializerProvider, this._elementSerializer);
Iterator localIterator;
do
{
return;
localIterator = paramCollection.iterator();
}
while (!localIterator.hasNext());
PropertySerializerMap localPropertySerializerMap = this._dynamicSerializers;
TypeSerializer localTypeSerializer = this._valueTypeSerializer;
int i = 0;
while (true)
{
Object localObject;
Class localClass;
try
{
localObject = localIterator.next();
if (localObject != null)
continue;
paramSerializerProvider.defaultSerializeNull(paramJsonGenerator);
i++;
if (!localIterator.hasNext())
{
return;
localClass = localObject.getClass();
localJsonSerializer = localPropertySerializerMap.serializerFor(localClass);
if (localJsonSerializer != null)
continue;
if (this._elementType.hasGenericTypes())
{
localJsonSerializer = _findAndAddDynamic(localPropertySerializerMap, this._elementType.forcedNarrowBy(localClass), paramSerializerProvider);
localPropertySerializerMap = this._dynamicSerializers;
if (localTypeSerializer != null)
break label184;
localJsonSerializer.serialize(localObject, paramJsonGenerator, paramSerializerProvider);
continue;
}
}
}
catch (Exception localException)
{
wrapAndThrow(paramSerializerProvider, localException, paramCollection, i);
return;
}
JsonSerializer localJsonSerializer = _findAndAddDynamic(localPropertySerializerMap, localClass, paramSerializerProvider);
continue;
label184: localJsonSerializer.serializeWithType(localObject, paramJsonGenerator, paramSerializerProvider, localTypeSerializer);
}
}
public void serializeContentsUsing(Collection<?> paramCollection, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider, JsonSerializer<Object> paramJsonSerializer)
throws IOException, JsonGenerationException
{
Iterator localIterator = paramCollection.iterator();
TypeSerializer localTypeSerializer;
int i;
if (localIterator.hasNext())
{
localTypeSerializer = this._valueTypeSerializer;
i = 0;
}
while (true)
{
Object localObject = localIterator.next();
if (localObject == null);
try
{
paramSerializerProvider.defaultSerializeNull(paramJsonGenerator);
while (true)
{
i++;
if (localIterator.hasNext())
break;
return;
if (localTypeSerializer != null)
break label92;
paramJsonSerializer.serialize(localObject, paramJsonGenerator, paramSerializerProvider);
}
}
catch (Exception localException)
{
while (true)
{
wrapAndThrow(paramSerializerProvider, localException, paramCollection, i);
continue;
label92: paramJsonSerializer.serializeWithType(localObject, paramJsonGenerator, paramSerializerProvider, localTypeSerializer);
}
}
}
}
}
public static class EnumSetSerializer extends ContainerSerializers.AsArraySerializer<EnumSet<? extends Enum<?>>>
{
public EnumSetSerializer(JavaType paramJavaType, BeanProperty paramBeanProperty)
{
super(paramJavaType, true, null, paramBeanProperty);
}
public ContainerSerializerBase<?> _withValueTypeSerializer(TypeSerializer paramTypeSerializer)
{
return this;
}
public void serializeContents(EnumSet<? extends Enum<?>> paramEnumSet, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider)
throws IOException, JsonGenerationException
{
JsonSerializer localJsonSerializer = this._elementSerializer;
Iterator localIterator = paramEnumSet.iterator();
while (localIterator.hasNext())
{
Enum localEnum = (Enum)localIterator.next();
if (localJsonSerializer == null)
localJsonSerializer = paramSerializerProvider.findValueSerializer(localEnum.getDeclaringClass(), this._property);
localJsonSerializer.serialize(localEnum, paramJsonGenerator, paramSerializerProvider);
}
}
}
@JacksonStdImpl
public static class IndexedListSerializer extends ContainerSerializers.AsArraySerializer<List<?>>
{
public IndexedListSerializer(JavaType paramJavaType, boolean paramBoolean, TypeSerializer paramTypeSerializer, BeanProperty paramBeanProperty, JsonSerializer<Object> paramJsonSerializer)
{
super(paramJavaType, paramBoolean, paramTypeSerializer, paramBeanProperty, paramJsonSerializer);
}
public ContainerSerializerBase<?> _withValueTypeSerializer(TypeSerializer paramTypeSerializer)
{
return new IndexedListSerializer(this._elementType, this._staticTyping, paramTypeSerializer, this._property, this._elementSerializer);
}
public void serializeContents(List<?> paramList, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider)
throws IOException, JsonGenerationException
{
if (this._elementSerializer != null)
serializeContentsUsing(paramList, paramJsonGenerator, paramSerializerProvider, this._elementSerializer);
int i;
do
{
return;
if (this._valueTypeSerializer != null)
{
serializeTypedContents(paramList, paramJsonGenerator, paramSerializerProvider);
return;
}
i = paramList.size();
}
while (i == 0);
label184: for (int j = 0; ; j++)
while (true)
{
PropertySerializerMap localPropertySerializerMap;
Class localClass;
try
{
localPropertySerializerMap = this._dynamicSerializers;
if (j >= i)
break;
Object localObject1 = paramList.get(j);
if (localObject1 != null)
continue;
paramSerializerProvider.defaultSerializeNull(paramJsonGenerator);
break label184;
localClass = localObject1.getClass();
localObject2 = localPropertySerializerMap.serializerFor(localClass);
if (localObject2 != null)
continue;
if (this._elementType.hasGenericTypes())
{
localObject2 = _findAndAddDynamic(localPropertySerializerMap, this._elementType.forcedNarrowBy(localClass), paramSerializerProvider);
localPropertySerializerMap = this._dynamicSerializers;
((JsonSerializer)localObject2).serialize(localObject1, paramJsonGenerator, paramSerializerProvider);
}
}
catch (Exception localException)
{
wrapAndThrow(paramSerializerProvider, localException, paramList, j);
return;
}
JsonSerializer localJsonSerializer = _findAndAddDynamic(localPropertySerializerMap, localClass, paramSerializerProvider);
Object localObject2 = localJsonSerializer;
}
}
public void serializeContentsUsing(List<?> paramList, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider, JsonSerializer<Object> paramJsonSerializer)
throws IOException, JsonGenerationException
{
int i = paramList.size();
if (i == 0);
while (true)
{
return;
TypeSerializer localTypeSerializer = this._valueTypeSerializer;
for (int j = 0; j < i; j++)
{
Object localObject = paramList.get(j);
if (localObject == null);
try
{
paramSerializerProvider.defaultSerializeNull(paramJsonGenerator);
continue;
if (localTypeSerializer == null)
paramJsonSerializer.serialize(localObject, paramJsonGenerator, paramSerializerProvider);
}
catch (Exception localException)
{
wrapAndThrow(paramSerializerProvider, localException, paramList, j);
}
paramJsonSerializer.serializeWithType(localObject, paramJsonGenerator, paramSerializerProvider, localTypeSerializer);
}
}
}
public void serializeTypedContents(List<?> paramList, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider)
throws IOException, JsonGenerationException
{
int i = paramList.size();
if (i == 0)
return;
label159: for (int j = 0; ; j++)
while (true)
{
PropertySerializerMap localPropertySerializerMap;
Class localClass;
try
{
TypeSerializer localTypeSerializer = this._valueTypeSerializer;
localPropertySerializerMap = this._dynamicSerializers;
if (j >= i)
break;
Object localObject1 = paramList.get(j);
if (localObject1 != null)
continue;
paramSerializerProvider.defaultSerializeNull(paramJsonGenerator);
break label159;
localClass = localObject1.getClass();
localObject2 = localPropertySerializerMap.serializerFor(localClass);
if (localObject2 != null)
continue;
if (this._elementType.hasGenericTypes())
{
localObject2 = _findAndAddDynamic(localPropertySerializerMap, this._elementType.forcedNarrowBy(localClass), paramSerializerProvider);
localPropertySerializerMap = this._dynamicSerializers;
((JsonSerializer)localObject2).serializeWithType(localObject1, paramJsonGenerator, paramSerializerProvider, localTypeSerializer);
}
}
catch (Exception localException)
{
wrapAndThrow(paramSerializerProvider, localException, paramList, j);
return;
}
JsonSerializer localJsonSerializer = _findAndAddDynamic(localPropertySerializerMap, localClass, paramSerializerProvider);
Object localObject2 = localJsonSerializer;
}
}
}
@JacksonStdImpl
public static class IterableSerializer extends ContainerSerializers.AsArraySerializer<Iterable<?>>
{
public IterableSerializer(JavaType paramJavaType, boolean paramBoolean, TypeSerializer paramTypeSerializer, BeanProperty paramBeanProperty)
{
super(paramJavaType, paramBoolean, paramTypeSerializer, paramBeanProperty);
}
public ContainerSerializerBase<?> _withValueTypeSerializer(TypeSerializer paramTypeSerializer)
{
return new IterableSerializer(this._elementType, this._staticTyping, paramTypeSerializer, this._property);
}
public void serializeContents(Iterable<?> paramIterable, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider)
throws IOException, JsonGenerationException
{
Iterator localIterator = paramIterable.iterator();
TypeSerializer localTypeSerializer;
Object localObject1;
Object localObject2;
if (localIterator.hasNext())
{
localTypeSerializer = this._valueTypeSerializer;
localObject1 = null;
localObject2 = null;
}
while (true)
{
Object localObject3 = localIterator.next();
if (localObject3 == null)
paramSerializerProvider.defaultSerializeNull(paramJsonGenerator);
while (!localIterator.hasNext())
{
return;
Class localClass = localObject3.getClass();
Object localObject4;
if (localClass == localObject2)
localObject4 = localObject1;
while (true)
{
if (localTypeSerializer != null)
break label118;
((JsonSerializer)localObject4).serialize(localObject3, paramJsonGenerator, paramSerializerProvider);
break;
localObject4 = paramSerializerProvider.findValueSerializer(localClass, this._property);
localObject1 = localObject4;
localObject2 = localClass;
}
label118: ((JsonSerializer)localObject4).serializeWithType(localObject3, paramJsonGenerator, paramSerializerProvider, localTypeSerializer);
}
}
}
}
@JacksonStdImpl
public static class IteratorSerializer extends ContainerSerializers.AsArraySerializer<Iterator<?>>
{
public IteratorSerializer(JavaType paramJavaType, boolean paramBoolean, TypeSerializer paramTypeSerializer, BeanProperty paramBeanProperty)
{
super(paramJavaType, paramBoolean, paramTypeSerializer, paramBeanProperty);
}
public ContainerSerializerBase<?> _withValueTypeSerializer(TypeSerializer paramTypeSerializer)
{
return new IteratorSerializer(this._elementType, this._staticTyping, paramTypeSerializer, this._property);
}
public void serializeContents(Iterator<?> paramIterator, JsonGenerator paramJsonGenerator, SerializerProvider paramSerializerProvider)
throws IOException, JsonGenerationException
{
TypeSerializer localTypeSerializer;
Object localObject1;
Object localObject2;
if (paramIterator.hasNext())
{
localTypeSerializer = this._valueTypeSerializer;
localObject1 = null;
localObject2 = null;
}
while (true)
{
Object localObject3 = paramIterator.next();
if (localObject3 == null)
paramSerializerProvider.defaultSerializeNull(paramJsonGenerator);
while (!paramIterator.hasNext())
{
return;
Class localClass = localObject3.getClass();
Object localObject4;
if (localClass == localObject2)
localObject4 = localObject1;
while (true)
{
if (localTypeSerializer != null)
break label107;
((JsonSerializer)localObject4).serialize(localObject3, paramJsonGenerator, paramSerializerProvider);
break;
localObject4 = paramSerializerProvider.findValueSerializer(localClass, this._property);
localObject1 = localObject4;
localObject2 = localClass;
}
label107: ((JsonSerializer)localObject4).serializeWithType(localObject3, paramJsonGenerator, paramSerializerProvider, localTypeSerializer);
}
}
}
}
}
/* Location: D:\开发工具\dex2jar-0.0.9.13\classes_dex2jar.jar
* Qualified Name: org.codehaus.jackson.map.ser.ContainerSerializers
* JD-Core Version: 0.6.0
*/ | gpl-3.0 |
repoxIST/repoxEuropeana | repox-core/src/main/java/pt/utl/ist/util/sql/SqlResultRow.java | 1118 | /*
* Created on 28/Nov/2005
*
*/
package pt.utl.ist.util.sql;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class SqlResultRow {
Object[] row;
public SqlResultRow(ResultSet rs) throws SQLException{
row=new Object[rs.getMetaData().getColumnCount()];
for (int i=1; i<=rs.getMetaData().getColumnCount() ; i++) {
row[i-1]=rs.getObject(i);
}
}
public String getString(int index) {
return (String) row[index];
}
public int getInt(int index) {
if (row[index] instanceof Long)
return ((Long)row[index]).intValue();
if (row[index] instanceof BigDecimal)
return ((BigDecimal)row[index]).intValue();
if (row[index] instanceof Double)
return ((Double)row[index]).intValue();
if (row[index] instanceof BigInteger)
return ((BigInteger)row[index]).intValue();
return (Integer) row[index];
}
public Integer getInteger(int index) {
if (row[index]==null)
return null;
return getInt(index);
}
public Date getDate(int index) {
return (Date) row[index];
}
}
| gpl-3.0 |
xuxueli/xxl-incubator | project/level-1/xxl-web/xxl-web-core/src/main/java/com/xxl/web/core/handler/XxlWebHandler.java | 516 | package com.xxl.web.core.handler;
import com.xxl.web.core.request.XxlWebRequest;
import com.xxl.web.core.response.XxlWebResponse;
/**
* request handler
* @author xuxueli
* @version 2015-11-28 13:56:05
*/
public abstract class XxlWebHandler<T extends XxlWebRequest> {
/**
* do some validate
* @param request
* @return
*/
public abstract XxlWebResponse validate(T request);
/**
* invoke biz handle
* @param request
* @return
*/
public abstract XxlWebResponse handle(T request);
}
| gpl-3.0 |
rubenswagner/L2J-Global | java/com/l2jglobal/gameserver/ai/DoppelgangerAI.java | 6667 | /*
* This file is part of the L2J Global project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jglobal.gameserver.ai;
import static com.l2jglobal.gameserver.ai.CtrlIntention.AI_INTENTION_ATTACK;
import static com.l2jglobal.gameserver.ai.CtrlIntention.AI_INTENTION_FOLLOW;
import static com.l2jglobal.gameserver.ai.CtrlIntention.AI_INTENTION_IDLE;
import com.l2jglobal.commons.util.Rnd;
import com.l2jglobal.gameserver.GameTimeController;
import com.l2jglobal.gameserver.model.L2Object;
import com.l2jglobal.gameserver.model.Location;
import com.l2jglobal.gameserver.model.actor.L2Character;
import com.l2jglobal.gameserver.model.actor.instance.DoppelgangerInstance;
import com.l2jglobal.gameserver.model.items.instance.L2ItemInstance;
import com.l2jglobal.gameserver.model.skills.Skill;
import com.l2jglobal.gameserver.model.skills.SkillCaster;
import com.l2jglobal.gameserver.network.serverpackets.MoveToLocation;
public class DoppelgangerAI extends L2CharacterAI
{
private volatile boolean _thinking; // to prevent recursive thinking
private volatile boolean _startFollow;
private L2Character _lastAttack = null;
public DoppelgangerAI(DoppelgangerInstance clone)
{
super(clone);
}
@Override
protected void onIntentionIdle()
{
stopFollow();
_startFollow = false;
onIntentionActive();
}
@Override
protected void onIntentionActive()
{
if (_startFollow)
{
setIntention(AI_INTENTION_FOLLOW, getActor().getSummoner());
}
else
{
super.onIntentionActive();
}
}
private void thinkAttack()
{
final L2Object target = getTarget();
final L2Character attackTarget = (target != null) && target.isCharacter() ? (L2Character) target : null;
if (checkTargetLostOrDead(attackTarget))
{
setTarget(null);
return;
}
if (maybeMoveToPawn(target, _actor.getPhysicalAttackRange()))
{
return;
}
clientStopMoving(null);
_actor.doAttack(attackTarget);
}
private void thinkCast()
{
if (_actor.isCastingNow(SkillCaster::isAnyNormalType))
{
return;
}
final L2Object target = _skill.getTarget(_actor, _forceUse, _dontMove, false);
if (checkTargetLost(target))
{
setTarget(null);
return;
}
final boolean val = _startFollow;
if (maybeMoveToPawn(target, _actor.getMagicalAttackRange(_skill)))
{
return;
}
getActor().followSummoner(false);
setIntention(AI_INTENTION_IDLE);
_startFollow = val;
_actor.doCast(_skill, _item, _forceUse, _dontMove);
}
private void thinkInteract()
{
final L2Object target = getTarget();
if (checkTargetLost(target))
{
return;
}
if (maybeMoveToPawn(target, 36))
{
return;
}
setIntention(AI_INTENTION_IDLE);
}
@Override
protected void onEvtThink()
{
if (_thinking || _actor.isCastingNow() || _actor.isAllSkillsDisabled())
{
return;
}
_thinking = true;
try
{
switch (getIntention())
{
case AI_INTENTION_ATTACK:
thinkAttack();
break;
case AI_INTENTION_CAST:
thinkCast();
break;
case AI_INTENTION_INTERACT:
thinkInteract();
break;
}
}
finally
{
_thinking = false;
}
}
@Override
protected void onEvtFinishCasting()
{
if (_lastAttack == null)
{
getActor().followSummoner(_startFollow);
}
else
{
setIntention(CtrlIntention.AI_INTENTION_ATTACK, _lastAttack);
_lastAttack = null;
}
}
public void notifyFollowStatusChange()
{
_startFollow = !_startFollow;
switch (getIntention())
{
case AI_INTENTION_ACTIVE:
case AI_INTENTION_FOLLOW:
case AI_INTENTION_IDLE:
case AI_INTENTION_MOVE_TO:
case AI_INTENTION_PICK_UP:
getActor().followSummoner(_startFollow);
}
}
public void setStartFollowController(boolean val)
{
_startFollow = val;
}
@Override
protected void onIntentionCast(Skill skill, L2Object target, L2ItemInstance item, boolean forceUse, boolean dontMove)
{
if (getIntention() == AI_INTENTION_ATTACK)
{
_lastAttack = (getTarget() != null) && getTarget().isCharacter() ? (L2Character) getTarget() : null;
}
else
{
_lastAttack = null;
}
super.onIntentionCast(skill, target, item, forceUse, dontMove);
}
@Override
protected void moveToPawn(L2Object pawn, int offset)
{
// Check if actor can move
if (!_actor.isMovementDisabled() && (_actor.getMoveSpeed() > 0))
{
if (offset < 10)
{
offset = 10;
}
// prevent possible extra calls to this function (there is none?),
// also don't send movetopawn packets too often
boolean sendPacket = true;
if (_clientMoving && (getTarget() == pawn))
{
if (_clientMovingToPawnOffset == offset)
{
if (GameTimeController.getInstance().getGameTicks() < _moveToPawnTimeout)
{
return;
}
sendPacket = false;
}
else if (_actor.isOnGeodataPath())
{
// minimum time to calculate new route is 2 seconds
if (GameTimeController.getInstance().getGameTicks() < (_moveToPawnTimeout + 10))
{
return;
}
}
}
// Set AI movement data
_clientMoving = true;
_clientMovingToPawnOffset = offset;
setTarget(pawn);
_moveToPawnTimeout = GameTimeController.getInstance().getGameTicks();
_moveToPawnTimeout += 1000 / GameTimeController.MILLIS_IN_TICK;
if (pawn == null)
{
return;
}
// Calculate movement data for a move to location action and add the actor to movingObjects of GameTimeController
// _actor.moveToLocation(pawn.getX(), pawn.getY(), pawn.getZ(), offset);
final Location loc = new Location(pawn.getX() + Rnd.get(-offset, offset), pawn.getY() + Rnd.get(-offset, offset), pawn.getZ());
_actor.moveToLocation(loc.getX(), loc.getY(), loc.getZ(), 0);
if (!_actor.isMoving())
{
clientActionFailed();
return;
}
// Doppelgangers always send MoveToLocation packet.
if (sendPacket)
{
_actor.broadcastPacket(new MoveToLocation(_actor));
}
}
else
{
clientActionFailed();
}
}
@Override
public DoppelgangerInstance getActor()
{
return (DoppelgangerInstance) super.getActor();
}
}
| gpl-3.0 |
xorinox/Cassandra | Connect/trunk/src/main/java/com/xorinox/connect/dao/DBKundera.java | 2328 | /*
* Copyright (C) 2016 Michel Erb
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.xorinox.connect.dao;
import com.xorinox.connect.api.DBInterface;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
*
* @author Michel Erb
*/
public class DBKundera extends DB implements DBInterface {
//thread safe singleton
private static final DBKundera INSTANCE = new DBKundera();
private EntityManager eM;
private EntityManagerFactory eMF;
private DBKundera() {
}
//get instance of this class
public static DBKundera getInstance() {
return INSTANCE;
}
//open a connection but close in case it was already open
@Override
public final void open() {
logger.info("trying to open database");
if (eM == null && eMF == null) {
eMF = Persistence.createEntityManagerFactory(config.get("persistence-unit-name"));
eM = eMF.createEntityManager();
logger.info("database opened");
} else {
close();
}
}
//close the connection
@Override
public final void close() {
logger.info("try to close database");
if (eM != null) {
if (eM.isOpen()) {
eM.close();
}
eM = null;
}
if (eMF != null) {
if (eMF.isOpen()) {
eMF.close();
}
eMF = null;
}
logger.info("database closed");
}
public EntityManager getEntityManager() {
return this.eM;
}
public EntityManagerFactory getEntityManagerFactory() {
return this.eMF;
}
}
| gpl-3.0 |
iterate-ch/cyberduck | ftp/src/test/java/ch/cyberduck/core/ftp/parser/AXSPortFTPEntryParserTest.java | 1609 | package ch.cyberduck.core.ftp.parser;
/*
* Copyright (c) 2002-2016 iterate GmbH. All rights reserved.
* https://cyberduck.io/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
import ch.cyberduck.core.ftp.FTPParserSelector;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileEntryParser;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertNull;
public class AXSPortFTPEntryParserTest {
private FTPFileEntryParser parser;
@Before
public void conigure() {
this.parser = new FTPParserSelector().getParser("CMX TCP/IP - REMOTE FTP server (version 2.0) ready.");
}
/**
* #9192
*/
@Test
public void testParseFile() {
FTPFile parsed;
parsed = parser.parseFTPEntry(
"--------- 1 owner group 1845484 Dec 22 10:20 OPTICS.RPY");
assertNull(parsed);
}
@Test
public void testParseDirectory() {
FTPFile parsed;
parsed = parser.parseFTPEntry(
"d-------- 1 owner group 0 Dec 22 10:19 DATALOGS");
assertNull(parsed);
}
}
| gpl-3.0 |
forgodsake/TowerPlus | dependencyLibs/Mavlink/test/com/MAVLink/common/msg_attitude_quaternion_cov_test.java | 2809 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* java mavlink generator tool. It should not be modified by hand.
*/
// MESSAGE ATTITUDE_QUATERNION_COV PACKING
package com.MAVLink.common;
import com.MAVLink.MAVLinkPacket;
import com.MAVLink.Parser;
import com.MAVLink.ardupilotmega.CRC;
import java.nio.ByteBuffer;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
/**
* The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. Quaternion order is w, x, y, z and a zero rotation would be expressed as (1 0 0 0).
*/
public class msg_attitude_quaternion_cov_test{
public static final int MAVLINK_MSG_ID_ATTITUDE_QUATERNION_COV = 61;
public static final int MAVLINK_MSG_LENGTH = 68;
private static final long serialVersionUID = MAVLINK_MSG_ID_ATTITUDE_QUATERNION_COV;
private Parser parser = new Parser();
public CRC generateCRC(byte[] packet){
CRC crc = new CRC();
for (int i = 1; i < packet.length - 2; i++) {
crc.update_checksum(packet[i] & 0xFF);
}
crc.finish_checksum(MAVLINK_MSG_ID_ATTITUDE_QUATERNION_COV);
return crc;
}
public byte[] generateTestPacket(){
ByteBuffer payload = ByteBuffer.allocate(6 + MAVLINK_MSG_LENGTH + 2);
payload.put((byte)MAVLinkPacket.MAVLINK_STX); //stx
payload.put((byte)MAVLINK_MSG_LENGTH); //len
payload.put((byte)0); //seq
payload.put((byte)255); //sysid
payload.put((byte)190); //comp id
payload.put((byte)MAVLINK_MSG_ID_ATTITUDE_QUATERNION_COV); //msg id
payload.putInt(963497464); //time_boot_ms
//q
payload.putFloat((float)45.0);
payload.putFloat((float)46.0);
payload.putFloat((float)47.0);
payload.putFloat((float)48.0);
payload.putFloat((float)157.0); //rollspeed
payload.putFloat((float)185.0); //pitchspeed
payload.putFloat((float)213.0); //yawspeed
//covariance
payload.putFloat((float)241.0);
payload.putFloat((float)242.0);
payload.putFloat((float)243.0);
payload.putFloat((float)244.0);
payload.putFloat((float)245.0);
payload.putFloat((float)246.0);
payload.putFloat((float)247.0);
payload.putFloat((float)248.0);
payload.putFloat((float)249.0);
CRC crc = generateCRC(payload.array());
payload.put((byte)crc.getLSB());
payload.put((byte)crc.getMSB());
return payload.array();
}
@Test
public void test(){
byte[] packet = generateTestPacket();
for(int i = 0; i < packet.length - 1; i++){
parser.mavlink_parse_char(packet[i] & 0xFF);
}
MAVLinkPacket m = parser.mavlink_parse_char(packet[packet.length - 1] & 0xFF);
byte[] processedPacket = m.encodePacket();
assertArrayEquals("msg_attitude_quaternion_cov", processedPacket, packet);
}
}
| gpl-3.0 |
PuzzlesLab/PuzzlesCon | PuzzlesCon Bronze League/Bronze League X/B/8332436_kingkingyyk_B.java | 554 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
class Main {
public static void main (String [] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s=br.readLine())!=null) {
BigInteger n=new BigInteger(s);
BigInteger bi=BigInteger.ONE;
while (!bi.mod(n).equals(BigInteger.ZERO)) bi=bi.multiply(BigInteger.TEN).add(BigInteger.ONE);
System.out.println(bi.toString().length());
}
}
} | gpl-3.0 |
spartan2015/kata | hibernate/hibernate1/src/test/java/learning/hibernate/AppTest.java | 646 | package learning.hibernate;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| gpl-3.0 |
maxiee/buybuybuy | app/src/main/java/com/maxiee/buybuybuy/injector/components/AppComponent.java | 447 | package com.maxiee.buybuybuy.injector.components;
import com.maxiee.buybuybuy.BuyApplication;
import com.maxiee.buybuybuy.injector.modules.AppModule;
import com.maxiee.buybuybuy.model.repository.Repository;
import javax.inject.Singleton;
import dagger.Component;
/**
* Created by maxiee on 15/11/25.
*/
@Singleton @Component(modules = AppModule.class)
public interface AppComponent {
BuyApplication app();
Repository repository();
}
| gpl-3.0 |
yzhill/improve | hello/src/com/huayu/servletDemo/EncodingFilter.java | 791 | package com.huayu.servletDemo;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class EncodingFilter implements Filter {
private String charset;
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
arg0.setCharacterEncoding(this.charset); //ÉèÖÃͳһ±àÂë
System.out.println(this.charset);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
this.charset=arg0.getFilterName();
}
}
| gpl-3.0 |
prashant31191/andRoc | src/net/rocrail/androc/widgets/LevelCanvas.java | 3533 | /*
Rocrail - Model Railroad Software
Copyright (C) 2002-2010 - Rob Versluis <r.j.versluis@rocrail.net>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package net.rocrail.androc.widgets;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsoluteLayout;
import android.widget.ZoomButtonsController;
/*
The AbsoluteLayout is needed for drawing the Layout levels.
The API is flagged as deprecated but, as it seems, with another meaning than 'obsolete':
“I'll say again: we are not going to remove AbsoluteLayout from a future
release, but we strongly discourage people from using it.”
Dianne Hackborn
Android framework engineer
*/
@SuppressWarnings("deprecation")
public class LevelCanvas extends AbsoluteLayout {
private int currentX;
private int currentY;
private boolean startMoveInited = false;
private boolean firstMove = false;
public ZoomButtonsController zoomButtonsController = null;
public LevelCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDetachedFromWindow () {
if( zoomButtonsController != null )
zoomButtonsController.setVisible(false);
}
@Override
protected void onWindowVisibilityChanged (int visibility) {
if( visibility != View.VISIBLE && zoomButtonsController != null )
zoomButtonsController.setVisible(false);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
System.out.println("LevelCanvas::onTouchEvent action=" + event.getAction());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
System.out.println("LevelCanvas::DOWN");
currentX = (int) event.getRawX();
currentY = (int) event.getRawY();
startMoveInited = true;
firstMove = true;
break;
case MotionEvent.ACTION_MOVE:
System.out.println("LevelCanvas::MOVE");
if (startMoveInited) {
int x2 = (int) event.getRawX();
int y2 = (int) event.getRawY();
int xDelta = currentX - x2;
int yDelta = currentY - y2;
if( !firstMove || (xDelta >= 16 || xDelta <= -16 || yDelta >= 16 || yDelta <= -16) ) {
scrollBy(currentX - x2, currentY - y2);
int x = getScrollX();
int y = getScrollY();
if (x < 0 || y < 0)
scrollTo(x < 0 ? 0 : x, y < 0 ? 0 : y);
currentX = x2;
currentY = y2;
firstMove = false;
}
}
else {
currentX = (int) event.getRawX();
currentY = (int) event.getRawY();
startMoveInited = true;
firstMove = true;
}
return true;
case MotionEvent.ACTION_UP:
System.out.println("LevelCanvas::UP");
startMoveInited = false;
firstMove = true;
break;
}
return false;
}
}
| gpl-3.0 |
ecornely/gpx-jconverter | src/main/java/be/ecornely/gpx/Downloader.java | 7304 | package be.ecornely.gpx;
import java.io.IOException;
import java.net.URISyntaxException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.LoggerFactory;
import be.ecornely.gpx.configuration.Configuration;
import be.ecornely.gpx.configuration.DefaultConfiguration;
/**
* <p>This class can download HTML pages from www.geocaching.com</p>
* <p>On creation, it is using the {@link DefaultConfiguration} class to fill the cookies information of its' HTTPClient</p>
*/
public class Downloader {
private CloseableHttpClient client;
private CookieStore cookieStore;
private Configuration gcConfiguration;
/**
* Constructor initilializing a GCDownloader with the HTTPClient default Configuration
* */
public Downloader(Configuration gcConfiguration) {
this.gcConfiguration = gcConfiguration;
cookieStore = getDefaultCookieStore();
client = HttpClients.custom().setDefaultCookieStore(cookieStore)
.setUserAgent("Mozilla/5.0 (Windows NT 6.2; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0")
.setRedirectStrategy(new LaxRedirectStrategy()).build();
}
private CookieStore getDefaultCookieStore() {
BasicCookieStore cookieStore = new BasicCookieStore();
List<Configuration.Cookie> cookies = gcConfiguration.getCookies();
if(cookies != null && cookies.size()>0){
Iterator<Configuration.Cookie> iterator = cookies.iterator();
while (iterator.hasNext()) {
Configuration.Cookie cookie = (Configuration.Cookie) iterator.next();
cookieStore.addCookie(createGCCookie(cookie.getKey(), cookie.getValue()));
}
}
return cookieStore;
}
private BasicClientCookie createGCCookie(String key, String value) {
BasicClientCookie cookie = new BasicClientCookie(key, value);
cookie.setDomain("www.geocaching.com");
cookie.setPath("/");
cookie.setExpiryDate(Date.from(
LocalDate.now().plus(15, ChronoUnit.DAYS).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));
return cookie;
}
/**
* <p>Read the HTML content of a geocahe page based on it's GC code</p>
* <p>This will make a GET request to http://www.geocaching.com/geocache/{gcCode} and return the HTML content</p>
* */
public String getCachePage(String gcCode) throws URISyntaxException, IOException {
String pageContent = null;
HttpGet get = new HttpGet("http://www.geocaching.com/geocache/" + gcCode);
pageContent = executeMethod(get);
return pageContent;
}
private String executeMethod(HttpUriRequest request) throws IOException {
String pageContent = null;
try (CloseableHttpResponse response = client.execute(request)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
pageContent = EntityUtils.toString(entity);
} else {
throw new RuntimeException("Entity was null");
}
}
return pageContent;
}
/**
* <p>
* Check that the current the client has correct Cookie information to
* access the profile page of a user
* </p>
* <p>
* This is done by a GET to the login page (with redirect to profile in the
* parameters).<br/>
* If automatically redirected by the server to the profile page, nothing
* special is done
* </p>
* <p>
* Else a POST of the login form is done with the user credentials.
* </p>
*/
public void ensureLoggedIn() throws IOException {
String pageContent = executeMethod(
new HttpGet("https://www.geocaching.com/login/default.aspx?RESETCOMPLETE=y&redir=/profile"));
Document document = Jsoup.parse(pageContent);
String title = document.select("head title").text();
String viewstate = document.select("input[name='__VIEWSTATE']").val();
String viewstateGenerator = document.select("input[name='__VIEWSTATEGENERATOR]").val();
if (!title.contains("Profile for User")) {
LoggerFactory.getLogger(this.getClass()).info("ensureLoggedIn() - The profile page is not accessible will try to POST credentials");
HttpPost post = new HttpPost(
"https://www.geocaching.com/login/default.aspx?RESETCOMPLETE=Y&redir=http://www.geocaching.com/profile/default.aspx?");
List<NameValuePair> parameters = Arrays.asList(new BasicNameValuePair("__EVENTTARGET", ""),
new BasicNameValuePair("__EVENTARGUMENT", ""), new BasicNameValuePair("__VIEWSTATE", viewstate),
new BasicNameValuePair("__VIEWSTATEGENERATOR", viewstateGenerator),
new BasicNameValuePair("ctl00$ContentBody$tbUsername", this.gcConfiguration.getUsername()),
new BasicNameValuePair("ctl00$ContentBody$tbPassword", this.gcConfiguration.getPassword()),
new BasicNameValuePair("ctl00$ContentBody$cbRememberMe", "on"),
new BasicNameValuePair("ctl00$ContentBody$btnSignIn", "Sign In"));
post.setEntity(new UrlEncodedFormEntity(parameters));
pageContent = executeMethod(post);
title = Jsoup.parse(pageContent).select("head title").text();
if (!title.contains("Profile for User")) {
LoggerFactory.getLogger(this.getClass()).warn("ensureLoggedIn() - After the credential submit the profile page is still not accessible");
// TODO throw a real exception and have a clear message
throw new RuntimeException("After submitting credentials the page was not recognized");
}else{
ArrayList<DefaultConfiguration.Cookie> configCookies = new ArrayList<>();
Iterator<Cookie> iterator = cookieStore.getCookies().iterator();
while (iterator.hasNext()) {
Cookie cookie = (Cookie) iterator.next();
configCookies.add(new DefaultConfiguration.Cookie(cookie.getName(), cookie.getValue()));
}
DefaultConfiguration.getInstance().setCookies(configCookies);
}
}else{
LoggerFactory.getLogger(this.getClass()).info("ensureLoggedIn() - The profile page is accessible skipped");
}
}
String performSearch(float latitude, float longitude, int startIndex, String radius) throws IOException{
String pageContent = null;
HttpGet get = null;
if(startIndex==0){
get = new HttpGet("https://www.geocaching.com/play/search/@"+latitude+","+longitude+"?origin="+latitude+","+longitude+"&radius="+radius);
}else{
get = new HttpGet("https://www.geocaching.com/play/search/more-results?startIndex="+startIndex+"&inputOrigin="+latitude+","+longitude+"&sortOrigin="+latitude+"%2C"+longitude+"&fbu=false&filteredByOtherUsersFinds=false&originTreatment=0");
}
pageContent = executeMethod(get);
return pageContent;
}
}
| gpl-3.0 |
lostrepository/lainexperiment | lainexperiment-java/src/lainexperiment/leetcode/weeklycontest/_218/Task1_Goal_Parser_Interpretation.java | 1814 | /*
*
* This source file is a part of lainexperiment project.
* Description for it can be found in ReadMe.txt.
*
*/
package lainexperiment.leetcode.weeklycontest._218;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/**
* <pre>{@code
* Date: 05/12/2020
*
* Problem: Goal Parser Interpretation
* Status: accepted
*
* You own a Goal Parser that can interpret a string command.
* The command consists of an alphabet of "G", "()" and/or "(al)"
* in some order. The Goal Parser will interpret "G" as the string
* "G", "()" as the string "o", and "(al)" as the string "al". The
* interpreted strings are then concatenated in the original order.
*
* Given the string command, return the Goal Parser's interpretation
* of command.
*
* Example 1:
*
command = "G()(al)"
*
* Output
*
Goal
*
* }</pre>
*/
public class Task1_Goal_Parser_Interpretation {
public String interpret(String command) {
StringBuilder b = new StringBuilder();
int l = 0;
for (int i = 0; i < command.length(); i++) {
char ch = command.charAt(i);
switch (ch) {
case 'G':
b.append('G');
break;
case '(':
case 'a':
case 'l':
l++;
break;
case ')':
if (l == 1)
b.append('o');
else
b.append("al");
l = 0;
break;
}
}
return b.toString();
}
@Test
public void test() {
assertEquals("alGalooG", interpret("(al)G(al)()()G"));
assertEquals("Gooooal", interpret("G()()()()(al)"));
assertEquals("Goal", interpret("G()(al)"));
}
}
| gpl-3.0 |
Shadorc/Spinvader | src/me/shadorc/spinvader/Sound.java | 1991 | package me.shadorc.spinvader;
import me.shadorc.spinvader.Storage.Data;
import javax.sound.sampled.*;
import java.io.IOException;
public class Sound {
private final String name;
private FloatControl gainControl;
private Clip clip;
public Sound(String name, double gain, Data volumeType) {
this.name = name;
try {
clip = AudioSystem.getClip();
AudioInputStream audioIn = AudioSystem.getAudioInputStream(this.getClass().getResource("/snd/" + name));
clip.open(audioIn);
gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
this.setGain(Integer.parseInt(Storage.getData(volumeType)) * gain / 100);
// Close sound thread when the sound finished
clip.addLineListener(evt -> {
if (evt.getType() == LineEvent.Type.STOP) {
evt.getLine().close();
}
});
} catch (LineUnavailableException | IOException | UnsupportedAudioFileException err) {
err.printStackTrace();
}
}
public static void play(String name, double gain, Data volumeType) {
new Thread(() -> new Sound(name, gain, volumeType).start()).start();
}
public void start() {
clip.start();
}
public void stop() {
clip.stop();
}
public void restart() {
if (!clip.isOpen()) {
try {
AudioInputStream audioIn = AudioSystem.getAudioInputStream(this.getClass().getResource("/snd/" + name));
clip.open(audioIn);
} catch (LineUnavailableException | IOException | UnsupportedAudioFileException err) {
err.printStackTrace();
}
}
this.start();
}
public boolean isPlaying() {
return clip.isRunning();
}
public void setGain(double gain) {
gainControl.setValue((float) (Math.log(gain) / Math.log(10.0) * 20.0));
}
} | gpl-3.0 |
jtux270/translate | ovirt/3.6_source/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/UpdateWatchdogCommand.java | 1385 | package org.ovirt.engine.core.bll;
import java.util.List;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.common.action.WatchdogParameters;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.errors.EngineMessage;
public class UpdateWatchdogCommand extends AbstractVmWatchdogCommand<WatchdogParameters> {
public UpdateWatchdogCommand(WatchdogParameters parameters) {
this(parameters, null);
}
public UpdateWatchdogCommand(WatchdogParameters parameters, CommandContext commandContext) {
super(parameters, commandContext);
}
@Override
protected void executeCommand() {
List<VmDevice> watchdogs =
getWatchdogs();
VmDevice watchdogDevice = watchdogs.get(0); // there must be only one
watchdogDevice.setSpecParams(getSpecParams());
getVmDeviceDao().update(watchdogDevice);
setSucceeded(true);
}
@Override
protected boolean canDoAction() {
if (!super.canDoAction()) {
return false;
}
List<VmDevice> watchdogs = getWatchdogs();
if (watchdogs.isEmpty()) {
return failCanDoAction(EngineMessage.WATCHDOG_NOT_FOUND);
}
if (!validate(validateWatchdog())) {
return false;
}
return true;
}
}
| gpl-3.0 |
wangzhi15561399068/anyun-cloud-demo | sources/common/common-etcd/src/main/java/com/anyun/cloud/demo/common/etcd/spi/entity/api/ApiEntity.java | 2025 | package com.anyun.cloud.demo.common.etcd.spi.entity.api;
import java.util.LinkedList;
import java.util.List;
/**
* @auth TwitchGG <twitchgg@yahoo.com>
* @since 1.0.0 on 23/05/2017
*/
public class ApiEntity {
private String title = "";
private String description = "";
private String version = "";
private String baseUrl = "";
private List<ApiDocuementEntity> documents = new LinkedList<>();
private List<ApiResourceEntity> resources = new LinkedList<>();
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<ApiDocuementEntity> getDocuments() {
return documents;
}
public void setDocuments(List<ApiDocuementEntity> documents) {
this.documents = documents;
}
public List<ApiResourceEntity> getResources() {
return resources;
}
public void setResources(List<ApiResourceEntity> resources) {
this.resources = resources;
}
public void addResource(ApiResourceEntity resourceEntity) {
resources.add(resourceEntity);
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
@Override
public String toString() {
return "ApiEntity {" + "\n" +
" title='" + title + "\'\n" +
" description='" + description + "\'\n" +
" version='" + version + "\'\n" +
" baseUrl='" + baseUrl + "\'\n" +
" documents=" + documents + "\n" +
" resources=" + resources + "\n" +
'}';
}
}
| gpl-3.0 |
marvertin/geokuk | src/main/java/cz/geokuk/plugins/kesoid/genetika/Indexable.java | 419 | package cz.geokuk.plugins.kesoid.genetika;
/**
* Objekty, kterým jsou přidělovány indexy při jejich zřizování s tím, že objekty jsou vytvářeny v omezeném počtu.
* @author veverka
*
*/
@FunctionalInterface
public interface Indexable {
/**
* Index přidělený objektu.
* @return Index nezáporný a malý. Očekává se, že bude indexem v poli pro zrychlení mapování.
*/
int getIndex();
}
| gpl-3.0 |
StarTux/Custom | src/main/java/com/winthier/custom/entity/TickableEntity.java | 119 | package com.winthier.custom.entity;
public interface TickableEntity {
void onTick(EntityWatcher entityWatcher);
}
| gpl-3.0 |
songscribe/SongScribe | src/main/java/songscribe/publisher/publisheractions/ExportBatchSongsImages.java | 17434 | /*
SongScribe song notation program
Copyright (C) 2006 Csaba Kavai
This file is part of SongScribe.
SongScribe is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
SongScribe is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package songscribe.publisher.publisheractions;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import org.apache.log4j.Logger;
import songscribe.data.DoNotShowException;
import songscribe.data.FileExtensions;
import songscribe.data.PlatformFileDialog;
import songscribe.publisher.Page;
import songscribe.publisher.Publisher;
import songscribe.publisher.pagecomponents.PageComponent;
import songscribe.publisher.pagecomponents.Song;
import songscribe.ui.BorderPanel;
import songscribe.ui.MusicSheet;
import songscribe.ui.MyDialog;
import songscribe.ui.ProcessDialog;
import songscribe.ui.Utilities;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
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.util.ArrayList;
import java.util.ListIterator;
public class ExportBatchSongsImages extends AbstractAction {
private static Logger logger = Logger.getLogger(ExportBatchSongsImages.class);
private Publisher publisher;
private ExportBatchSongsImagesDialog exportBatchSongsImagesDialog;
private ProcessDialog processDialog;
private ArrayList<Song> songs;
public ExportBatchSongsImages(Publisher publisher) {
this.publisher = publisher;
putValue(NAME, "Create Image of All Songs...");
putValue(SMALL_ICON, publisher.blankIcon);
}
public void actionPerformed(ActionEvent e) {
if (exportBatchSongsImagesDialog == null) {
exportBatchSongsImagesDialog = new ExportBatchSongsImagesDialog();
}
exportBatchSongsImagesDialog.setVisible(true);
}
private class ExportThread extends Thread {
public void run() {
int successFul = 0;
processDialog.packAndPos();
for (Song song : songs) {
MusicSheet ms = song.getMusicSheet();
String lyrics = ms.getComposition().getUnderLyrics();
String translatedLyrics = ms.getComposition().getTranslatedLyrics();
String songTitle = ms.getComposition().getSongTitle();
try {
if (exportBatchSongsImagesDialog.exportWithoutLyricsCheckBox.isSelected()) {
ms.getComposition().setUnderLyrics("");
ms.getComposition().setTranslatedLyrics("");
}
if (exportBatchSongsImagesDialog.exportWithoutSongTitlesCheckBox.isSelected()) {
ms.getComposition().setSongTitle("");
}
BufferedImage bi = ms.createMusicSheetImageForExport(Color.white,
((Number) exportBatchSongsImagesDialog.resolutionSpinner.getValue()).doubleValue() /
(double) MusicSheet.RESOLUTION, exportBatchSongsImagesDialog.borderPanel.getMyBorder());
String fileName = song.getSongFile().getName();
if (fileName.endsWith(FileExtensions.SONGWRITER)) {
fileName = fileName.substring(0, fileName.length() - FileExtensions.SONGWRITER.length());
}
String extension = exportBatchSongsImagesDialog.formatCombo.getSelectedItem().toString().toLowerCase();
fileName += "." + extension;
Utilities.writeImage(bi, extension, new File(exportBatchSongsImagesDialog.directory, fileName));
successFul++;
}
catch (IOException e) {
publisher.showErrorMessage(Publisher.COULD_NOT_SAVE_MESSAGE + "\n" + song.getSongFile().getName());
logger.error("Saving image", e);
}
catch (AWTException e) {
publisher.showErrorMessage(Publisher.COULD_NOT_SAVE_MESSAGE + "\n" + song.getSongFile().getName());
logger.error("Saving image", e);
}
catch (OutOfMemoryError e) {
publisher.showErrorMessage(
"There is not enough memory for this resolution." + "\nCould not export: " +
song.getSongFile().getName());
}
finally {
if (exportBatchSongsImagesDialog.exportWithoutLyricsCheckBox.isSelected()) {
ms.getComposition().setUnderLyrics(lyrics);
ms.getComposition().setTranslatedLyrics(translatedLyrics);
}
if (exportBatchSongsImagesDialog.exportWithoutSongTitlesCheckBox.isSelected()) {
ms.getComposition().setSongTitle(songTitle);
}
}
processDialog.nextValue();
}
processDialog.setVisible(false);
if (successFul == songs.size()) {
JOptionPane.showMessageDialog(publisher, "Successfully exported all songs.", publisher.PROG_NAME, JOptionPane.INFORMATION_MESSAGE);
}
else if (successFul > 0) {
JOptionPane.showMessageDialog(publisher,
"Successfully exported " + successFul + " songs,\nbut could not export " +
(songs.size() - successFul) + " songs.", publisher.PROG_NAME, JOptionPane.INFORMATION_MESSAGE);
}
else {
publisher.showErrorMessage("No song was exported!");
}
}
}
private class ExportBatchSongsImagesDialog extends MyDialog {
private JPanel centerPanel;
private JSpinner resolutionSpinner;
private JCheckBox exportWithoutLyricsCheckBox;
private JLabel destinationFolder;
private JButton chooseFolderButton;
private JComboBox formatCombo;
private BorderPanel borderPanel;
private JCheckBox exportWithoutSongTitlesCheckBox;
private PlatformFileDialog directoryChooser;
private File directory;
private ExportBatchSongsImagesDialog() {
super(publisher, "Create Image of All Songs");
resolutionSpinner.setModel(new SpinnerNumberModel(100, 30, 1200, 1));
dialogPanel.add(BorderLayout.CENTER, centerPanel);
southPanel.remove(applyButton);
dialogPanel.add(BorderLayout.SOUTH, southPanel);
directory = publisher.getPreviousDirectory();
destinationFolder.setText(directory.getAbsolutePath());
chooseFolderButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (directoryChooser == null) {
directoryChooser = new PlatformFileDialog(publisher, "Select the destination folder for images", true, null, true);
}
if (directoryChooser.showDialog()) {
directory = directoryChooser.getFile();
destinationFolder.setText(directory.getAbsolutePath());
pack();
}
}
});
borderPanel.setPackListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pack();
}
});
}
protected void getData() throws DoNotShowException {
if (publisher.isBookNull()) {
throw new DoNotShowException();
}
borderPanel.setExpertBorder(false);
}
protected void setData() {
// find songs
songs = new ArrayList<Song>();
for (ListIterator<Page> pages = publisher.getBook().pageIterator(); pages.hasNext(); ) {
for (ListIterator<PageComponent> comps = pages.next().getPageComponentIterator(); comps.hasNext(); ) {
PageComponent c = comps.next();
if (c instanceof Song) {
songs.add((Song) c);
}
}
}
if (songs.size() == 0) {
publisher.showErrorMessage("There are no songs to export.");
} else {
processDialog = new ProcessDialog(publisher, "Creating images...", songs.size());
new ExportThread().start();
processDialog.packAndPos();
processDialog.setVisible(true);
}
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
centerPanel = new JPanel();
centerPanel.setLayout(new GridLayoutManager(7, 1, new Insets(0, 0, 0, 0), -1, -1));
centerPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10), null, TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(1, 4, new Insets(0, 0, 0, 0), -1, -1));
centerPanel.add(panel1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JLabel label1 = new JLabel();
label1.setText("Resolution:");
panel1.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
resolutionSpinner = new JSpinner();
panel1.add(resolutionSpinner, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(70, 22), null, 0, false));
final JLabel label2 = new JLabel();
label2.setText("dpi");
panel1.add(label2, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer1 = new Spacer();
panel1.add(spacer1, new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final Spacer spacer2 = new Spacer();
centerPanel.add(spacer2, new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
exportWithoutLyricsCheckBox = new JCheckBox();
exportWithoutLyricsCheckBox.setText("Export without lyrics under the songs");
centerPanel.add(exportWithoutLyricsCheckBox, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayoutManager(1, 4, new Insets(0, 0, 0, 0), -1, -1));
centerPanel.add(panel2, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JLabel label3 = new JLabel();
label3.setText("Destination folder:");
panel2.add(label3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
destinationFolder = new JLabel();
destinationFolder.setText("");
panel2.add(destinationFolder, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
chooseFolderButton = new JButton();
chooseFolderButton.setText("Choose folder");
panel2.add(chooseFolderButton, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer3 = new Spacer();
panel2.add(spacer3, new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1));
centerPanel.add(panel3, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final JLabel label4 = new JLabel();
label4.setText("Image format:");
panel3.add(label4, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer4 = new Spacer();
panel3.add(spacer4, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
formatCombo = new JComboBox();
final DefaultComboBoxModel defaultComboBoxModel1 = new DefaultComboBoxModel();
defaultComboBoxModel1.addElement("GIF");
defaultComboBoxModel1.addElement("JPG");
defaultComboBoxModel1.addElement("PNG");
formatCombo.setModel(defaultComboBoxModel1);
panel3.add(formatCombo, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final JPanel panel4 = new JPanel();
panel4.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
centerPanel.add(panel4, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
final Spacer spacer5 = new Spacer();
panel4.add(spacer5, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
borderPanel = new BorderPanel();
panel4.add(borderPanel.$$$getRootComponent$$$(), new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
exportWithoutSongTitlesCheckBox = new JCheckBox();
exportWithoutSongTitlesCheckBox.setText("Export without song titles");
centerPanel.add(exportWithoutSongTitlesCheckBox, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return centerPanel;
}
}
}
| gpl-3.0 |
kostovhg/SoftUni | Java_DBFundamentals-Jan18/DBAdvanced_HibernateSpring/n_Json_Processing/products_shop/src/main/java/products_shop/domain/model/Product.java | 1935 | package products_shop.domain.model;
import org.hibernate.validator.constraints.Length;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Set;
@Entity
@Table(name = "products")
public class Product {
private Long id;
private String name;
private BigDecimal price;
private User buyer;
private User seller;
private Set<Category> categories;
public Product() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", columnDefinition = "INT(11) UNSIGNED")
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@NotNull
@Length(min = 3)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@NotNull
public BigDecimal getPrice() {
return this.price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "buyer_id")
public User getBuyer() {
return this.buyer;
}
public void setBuyer(User buyer) {
this.buyer = buyer;
}
@NotNull
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "seller_id")
public User getSeller() {
return this.seller;
}
public void setSeller(User seller) {
this.seller = seller;
}
@ManyToMany
@JoinTable(
name="products_categories",
joinColumns=@JoinColumn(name="product_id", referencedColumnName="id"),
inverseJoinColumns=@JoinColumn(name="category_id", referencedColumnName="id"))
public Set<Category> getCategories() {
return this.categories;
}
public void setCategories(Set<Category> categories) {
this.categories = categories;
}
}
| gpl-3.0 |
wwu-pi/muggl | muggl-core/src/de/wwu/muggl/instructions/bytecode/DRem.java | 2659 | package de.wwu.muggl.instructions.bytecode;
import java.util.Stack;
import de.wwu.muggl.instructions.general.Rem;
import de.wwu.muggl.instructions.interfaces.Instruction;
import de.wwu.muggl.vm.Frame;
import de.wwu.muggl.vm.classfile.ClassFile;
import de.wwu.muggl.vm.execution.ExecutionException;
/**
* Implementation of the instruction <code>drem</code>.
*
* @author Tim Majchrzak
* @version 1.0.0, 2009-03-26
*/
public class DRem extends Rem implements Instruction {
/**
* Execute the instruction.
* @param frame The currently executed frame.
* @throws ExecutionException Thrown in case of fatal problems during the execution.
*/
@Override
public void execute(Frame frame) throws ExecutionException {
Stack<Object> stack = frame.getOperandStack();
Double value2 = (Double) stack.pop();
Double value1 = (Double) stack.pop();
stack.push(value1 % value2);
}
/**
* Resolve the instructions name.
* @return The instructions name as a String.
*/
@Override
public String getName() {
return "drem";
}
/**
* Get the type of elements this instruction will push onto the stack.
*
* @param methodClassFile The class file of the method this instruction belongs to.
* @return The type this instruction pushes. Types are {@link ClassFile#T_BOOLEAN},
* {@link ClassFile#T_BYTE} {@link ClassFile#T_CHAR}, {@link ClassFile#T_DOUBLE},
* {@link ClassFile#T_FLOAT}, {@link ClassFile#T_INT}, {@link ClassFile#T_LONG} and
* {@link ClassFile#T_SHORT}, 0 to indicate a reference or return address type or -1 to
* indicate the pushed type cannot be determined statically.
*/
public byte getTypePushed(ClassFile methodClassFile) {
return ClassFile.T_DOUBLE;
}
/**
* Get the types of elements this instruction will pop from the stack.
*
* @param methodClassFile The class file of the method this instruction belongs to.
* @return The types this instruction pops. The length of the arrays reflects the number of
* elements pushed in the order they are pushed. Types are {@link ClassFile#T_BOOLEAN},
* {@link ClassFile#T_BYTE} {@link ClassFile#T_CHAR}, {@link ClassFile#T_DOUBLE},
* {@link ClassFile#T_FLOAT}, {@link ClassFile#T_INT}, {@link ClassFile#T_LONG} and
* {@link ClassFile#T_SHORT}, 0 to indicate a reference or return address type or -1 to
* indicate the popped type cannot be determined statically.
*/
public byte[] getTypesPopped(ClassFile methodClassFile) {
byte[] types = {ClassFile.T_DOUBLE, ClassFile.T_DOUBLE};
return types;
}
}
| gpl-3.0 |
nickapos/myBill | src/main/java/gr/oncrete/nick/mybill/BusinessLogic/MergeCategories.java | 2838 | /*
* Copyright (C) 2010 nickapos
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package gr.oncrete.nick.mybill.BusinessLogic;
import gr.oncrete.nick.mybill.BusinessLogic.SelectInfo.SelectCompanyDetails;
import gr.oncrete.nick.mybill.BusinessLogic.UpdateInfo.UpdateCompanyRecord;
import java.util.List;
import java.util.Iterator;
import javax.swing.JLabel;
/**
*This class will be used to change the all the records of the database the belong to
* a specific category to another
* @author nickapos 6 Σεπ 2010
*/
public class MergeCategories {
private List idListTobeMerged;
private String newCategoryID;
private JLabel l;
/**
*
* @param listTobeMerged the id's list to be merget into the new category
* @param newCategoryID the id of the new category
* @param a label for the progress of the work the id of the new category
*/
public MergeCategories(List listTobeMerged, String categoryID, JLabel lbl) {
idListTobeMerged = listTobeMerged;
l = lbl;
newCategoryID = categoryID;
}
/**
*
*/
public MergeCategories() {
}
/**
* this method will preform the actual conversion
*/
public void mergeCategories() {
if (newCategoryID.length() > 0) {
//change id of category from the old to the new one
Iterator it = idListTobeMerged.iterator();
int counter = 0;
String expensesProgressText = "";
while (it.hasNext()) {
//get company details
SelectCompanyDetails cdt = new SelectCompanyDetails();
String[] id = (String[]) it.next();
cdt.SelectCompanyDetailsWithID(id[0]);
UpdateCompanyRecord upcr = new UpdateCompanyRecord(cdt.getID(),cdt.getName(),cdt.getAfm(),newCategoryID);
counter++;
double percentage =100*counter/idListTobeMerged.size();
expensesProgressText = java.util.ResourceBundle.getBundle("i18n/myBillUIBundle").getString("MergeCategories.progressLabel.text") + counter+" "+percentage +"%";
l.setText(expensesProgressText);
}
}
}
}
| gpl-3.0 |
ferquies/2dam | PMUL/Buscaminas/gen/com/fernando/buscaminas/BuildConfig.java | 265 | /*___Generated_by_IDEA___*/
package com.fernando.buscaminas;
/* This stub is only used by the IDE. It is NOT the BuildConfig class actually packed into the APK */
public final class BuildConfig {
public final static boolean DEBUG = Boolean.parseBoolean(null);
} | gpl-3.0 |
iPencil/UsefulCompass | main/java/com/creepgaming/usefulcompass/proxy/CommonProxy.java | 1232 | package com.creepgaming.usefulcompass.proxy;
import com.creepgaming.usefulcompass.UsefulCompass;
import com.creepgaming.usefulcompass.handler.HandlerGui;
import com.creepgaming.usefulcompass.handler.HandlerPackets;
import com.creepgaming.usefulcompass.items.ItemRegister;
import com.creepgaming.usefulcompass.recipes.CompassRecipeHandler;
import com.creepgaming.usefulcompass.recipes.RecipeRegister;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class CommonProxy {
public void preInit(FMLPreInitializationEvent e) {
ItemRegister.registerItems();
HandlerPackets.registerMessages(UsefulCompass.MODID);
}
public void init(FMLInitializationEvent e) {
NetworkRegistry.INSTANCE.registerGuiHandler(UsefulCompass.instance, new HandlerGui());
GameRegistry.addRecipe(new CompassRecipeHandler());
RecipeRegister.registerRecipes();
}
public void postInit(FMLPostInitializationEvent e) {
}
}
| gpl-3.0 |
jbrendel/RESTx | src/java/org/mulesoft/restx/exception/RestxMandatoryParameterMissingException.java | 1302 | /*
* RESTx: Sane, simple and effective data publishing and integration.
*
* Copyright (C) 2010 MuleSoft Inc. http://www.mulesoft.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mulesoft.restx.exception;
import org.mulesoft.restx.component.api.HTTP;
public class RestxMandatoryParameterMissingException extends RestxException
{
private static final long serialVersionUID = -4416078320919224064L;
public RestxMandatoryParameterMissingException()
{
this("Mandatory parameter missing");
}
public RestxMandatoryParameterMissingException(String message)
{
super(HTTP.BAD_REQUEST, message);
}
}
| gpl-3.0 |
ckaestne/CIDE | CIDE_Language_XML_concrete/src/tmp/generated_xhtml/EmptyTag_link.java | 778 | package tmp.generated_xhtml;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public class EmptyTag_link extends GenASTNode {
public EmptyTag_link(ArrayList<Attribute> attribute, Token firstToken, Token lastToken) {
super(new Property[] {
new PropertyZeroOrMore<Attribute>("attribute", attribute)
}, firstToken, lastToken);
}
public EmptyTag_link(Property[] properties, IToken firstToken, IToken lastToken) {
super(properties,firstToken,lastToken);
}
public ASTNode deepCopy() {
return new EmptyTag_link(cloneProperties(),firstToken,lastToken);
}
public ArrayList<Attribute> getAttribute() {
return ((PropertyZeroOrMore<Attribute>)getProperty("attribute")).getValue();
}
}
| gpl-3.0 |
Melacon/WirelessTransportEmulator | NetconfServerSimulator/src/test/java/net/i2cat/netconf/server/TestNetworkElement.java | 1756 | package net.i2cat.netconf.server;
import net.i2cat.netconf.server.netconf.types.NetconfTagList;
import net.i2cat.netconf.server.netconf.types.NetworkElement;
public class TestNetworkElement {
public static void main(String[] args) throws Exception {
NetworkElement ne = new NetworkElement("src/main/resources/ne_model/DVM_MicrowaveModelCore10.xml","yang/yangNeModel");
String xml;
System.out.println("Test-1 Start");
xml = ne.getXmlSubTreeAsString("//NetworkElement");
xml = xml.replaceFirst("NetworkElement", "NetworkElement xmlns=\"uri:onf:CoreModel-CoreNetworkModule-ObjectClasses\"");
System.out.println(xml);
System.out.println("Test-1 End");
System.out.println("Test-2 Start");
xml = ne.getXmlSubTreeAsString("//NetworkElement");
xml = xml.replaceFirst("NetworkElement", "NetworkElement xmlns=\"uri:onf:CoreModel-CoreNetworkModule-ObjectClasses\"");
System.out.println(xml);
System.out.println("Test-2 End");
System.out.println("Test-3");
NetconfTagList tags = new NetconfTagList();
tags.pushTag("MW_EthernetContainer_Pac", "ns1");
tags.pushTag("layerProtocol", "ns1");
tags.addTagsValue("LP-ETH-CTP-ifIndex1");
xml = ne.assembleRpcReplyFromFilterMessage("m-45", tags);
System.out.println(xml);
System.out.println("Test-4");
tags = new NetconfTagList();
tags.pushTag("MW_AirInterface_Pac", "ns1");
tags.pushTag("layerProtocol", "ns1");
tags.addTagsValue("LP-MWPS-ifIndex1");
tags.pushTag("airInterfaceCurrentProblems", "ns1");
xml = ne.assembleRpcReplyFromFilterMessage("m-46", tags);
System.out.println(xml);
}
}
| gpl-3.0 |
LTBuses/LTB-android | app/src/main/java/org/frasermccrossan/ltc/StopTimes.java | 9663 | package org.frasermccrossan.ltc;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Toast;
public class StopTimes extends Activity {
// how long before popping up an Toast about how long the LTC site is taking
static final long WARNING_DELAY = 10000;
String stopNumber;
LinearLayout routeViewLayout;
ScrollView vertRouteViewScrollview;
HorizontalScrollView horizRouteViewScrollview;
Button refreshButton;
Button notWorkingButton;
ArrayList<LTCRoute> routeList;
ArrayList<RouteDirTextView> routeViews;
PredictionAdapter adapter;
ListView predictionList;
PredictionTask task = null;
ArrayList<Prediction> predictions;
OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.refresh:
getPredictions();
break;
case R.id.not_working:
Intent diagnoseIntent = new Intent(StopTimes.this, DiagnoseProblems.class);
LTCScraper scraper = new LTCScraper(StopTimes.this);
diagnoseIntent.putExtra("testurl", routeViews.get(0).getPredictionUrl(scraper, stopNumber));
startActivity(diagnoseIntent);
break;
// no default
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
setContentView(R.layout.stop_times);
BusDb db = new BusDb(this);
Intent intent = getIntent();
stopNumber = intent.getStringExtra(BusDb.STOP_NUMBER);
LTCStop stop = db.findStop(stopNumber);
if (stop != null) {
setTitle(stop.name);
db.noteStopUse(stop.number);
}
refreshButton = (Button)findViewById(R.id.refresh);
refreshButton.setOnClickListener(buttonListener);
notWorkingButton = (Button)findViewById(R.id.not_working);
notWorkingButton.setOnClickListener(buttonListener);
routeViewLayout = (LinearLayout)findViewById(R.id.route_list);
vertRouteViewScrollview = (ScrollView)findViewById(R.id.vert_route_list_scrollview);
horizRouteViewScrollview = (HorizontalScrollView)findViewById(R.id.horiz_route_list_scrollview);
String routeNumberOnly = intent.getStringExtra(BusDb.ROUTE_NUMBER);
int routeDirectionOnly = intent.getIntExtra(BusDb.DIRECTION_NUMBER, 0);
routeList = db.findStopRoutes(stopNumber, routeNumberOnly, routeDirectionOnly);
db.close();
if (routeList.size() == 0) {
Toast.makeText(StopTimes.this, R.string.none_stop_today, Toast.LENGTH_SHORT).show();
finish();
}
else {
/* now create a list of route views based on that routeList */
routeViews = new ArrayList<RouteDirTextView>(routeList.size());
for (LTCRoute route : routeList) {
RouteDirTextView routeView = new RouteDirTextView(this, route);
routeViews.add(routeView);
routeViewLayout.addView(routeView);
}
predictionList = (ListView)findViewById(R.id.prediction_list);
predictionList.setEmptyView(findViewById(R.id.empty_prediction_list));
predictions = new ArrayList<Prediction>(3);
adapter = new PredictionAdapter(this, R.layout.prediction_item, predictions);
predictionList.setAdapter(adapter);
}
}
@Override
protected void onStart () {
super.onStart();
getPredictions();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
cancelTask();
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
void cancelTask() {
if (task != null) {
task.cancel(true); // we don't care if this fails because it has already stopped
task = null;
}
}
@SuppressLint("NewApi")
void getPredictions() {
cancelTask();
notWorkingButton.setVisibility(Button.GONE);
task = new PredictionTask();
RouteDirTextView[] routeViewAry = new RouteDirTextView[routeViews.size()];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
/* on Honeycomb and later, ASyncTasks run on a serial executor, and since
* we might have another asynctask running in an activity (e.g. fetching stop lists),
* we don't really want them all to block
*/
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
(RouteDirTextView[])(routeViews.toArray(routeViewAry)));
}
else {
task.execute((RouteDirTextView[])(routeViews.toArray(routeViewAry)));
}
}
/* this takes one or more LTCRoute objects and fetches the predictions for each
* one, publishing to the UI thread using publishProgress (somewhat counter-intuitively)
* and finally returns a void result since the list will have been updated by then
*/
class PredictionTask extends AsyncTask<RouteDirTextView, RouteDirTextView, Void> {
Toast toast;
Timer toastTimer;
int probCount = 0;
class ToastTask extends TimerTask {
public void run() {
toast.show();
}
}
@SuppressLint("ShowToast")
protected void onPreExecute() {
toast = Toast.makeText(StopTimes.this, R.string.website_slow, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
scheduleTimer();
for (RouteDirTextView routeView: routeViews) {
routeView.setStatus(RouteDirTextView.IDLE, null);
routeView.updateDisplay();
}
for (Prediction pred: predictions) {
pred.setQuerying();
}
}
protected Void doInBackground(RouteDirTextView... routeViews) {
LTCScraper scraper = new LTCScraper(StopTimes.this);
for (RouteDirTextView routeView: routeViews) {
routeView.setStatus(RouteDirTextView.QUERYING, null);
publishProgress(routeView);
routeView.scrapePredictions(scraper, stopNumber);
if (isCancelled()) {
break;
}
publishProgress(routeView);
}
return null;
}
protected void onProgressUpdate(RouteDirTextView... routeViews) {
// update predictions and ping the listview
cancelTimer();
scheduleTimer();
Calendar now = Calendar.getInstance();
for (RouteDirTextView routeView: routeViews) {
if (isCancelled()) {
break;
}
if (routeView.isOkToPost()) {
removeRouteFromPredictions(routeView.route);
for (Prediction p: routeView.getPredictions()) {
// find the position where this Prediction should be inserted
int insertPosition = Collections.binarySearch(predictions, p);
// we don't care if we get a direct hit or just an insert position, we do the same thing
if (insertPosition < 0) {
insertPosition = -(insertPosition + 1);
}
// insert the Prediction at that location
adapter.insert(p, insertPosition);
}
}
switch (routeView.problemType) {
case ScrapeStatus.PROBLEM_IMMEDIATELY:
notWorkingButton.setVisibility(Button.VISIBLE);
break;
case ScrapeStatus.PROBLEM_IF_ALL:
++probCount;
break;
}
for (Prediction p: predictions) {
p.updateFields(StopTimes.this, now);
}
adapter.notifyDataSetChanged();
routeView.updateDisplay();
if (isCancelled()) {
break;
}
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT &&
horizRouteViewScrollview != null) {
int right = routeView.getRight();
int svWidth = horizRouteViewScrollview.getWidth();
if (right > svWidth) {
horizRouteViewScrollview.smoothScrollTo(right - svWidth, 0);
}
else {
int left = routeView.getLeft();
int scrollPos = horizRouteViewScrollview.getScrollX();
if (left < scrollPos) {
horizRouteViewScrollview.smoothScrollTo(left, 0);
}
}
}
else if (vertRouteViewScrollview != null) {
int bottom = routeView.getBottom();
int svHeight = vertRouteViewScrollview.getHeight();
if (bottom > svHeight) {
vertRouteViewScrollview.smoothScrollTo(0, bottom - svHeight);
}
else {
int top = routeView.getTop();
int scrollPos = vertRouteViewScrollview.getScrollY();
if (top < scrollPos) {
vertRouteViewScrollview.smoothScrollTo(top, 0);
}
}
}
}
}
@Override
protected void onPostExecute(Void result) {
if (probCount == routeViews.size()) {
notWorkingButton.setVisibility(Button.VISIBLE);
}
cancelTimer();
}
@Override
protected void onCancelled() {
cancelTimer();
}
void scheduleTimer() {
toastTimer = new Timer();
ToastTask toastTask = new ToastTask();
toastTimer.schedule(toastTask, WARNING_DELAY);
}
void cancelTimer() {
toastTimer.cancel();
toast.cancel();
}
// removes all references to a particular route from the prediction list
private void removeRouteFromPredictions(LTCRoute route) {
int i = 0;
while (i < adapter.getCount()) {
Prediction entry = predictions.get(i);
if (entry.isOnRoute(route)) {
adapter.remove(entry);
}
else {
++i;
}
}
}
}
}
| gpl-3.0 |
tarekauel/WinnerGame | WinnerGame/src/annotation/Log.java | 335 | package annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD } )
public @interface Log {
}
| gpl-3.0 |
ctilluma/InspiredMead | app/src/main/java/com/inspiredpanama/inspiredmead/SpecGravity.java | 2034 | package com.inspiredpanama.inspiredmead;
import java.util.GregorianCalendar;
/**
* Created by ctilluma on 10/8/16.
*
* Class to hold Specific Gravity Information
*/
// Private class for each test
public class SpecGravity {
//Variables
private long id, meadID; //id records
private GregorianCalendar testDate; // Date of this test
private double testGravity; // Specific Gravity of this test
//Constructors
public SpecGravity() { //Empty Constructor
this(0.00); // Set value to 0.00
}
public SpecGravity(double testGravity) { //Constructor w/ test value, supply current time
this(-1, -1, new GregorianCalendar(), testGravity); //Set id as negative because it doesn't have a database number
}
public SpecGravity(long id, long meadID, GregorianCalendar testDate, double testGravity) { //Constructor w/ all info known
this.id = id;
this.meadID = meadID;
this.testDate = testDate;
this.testGravity = testGravity;
}
//Getter and Setter methods
public long getID() {
return id;
}
public void setID(long id) {
this.id = id;
}
public long getMeadID() {
return meadID;
}
public void setMeadID(long meadID) {
this.meadID = meadID;
}
public GregorianCalendar getTestDate() {
return testDate;
}
public void setTestDate(GregorianCalendar testDate) {
this.testDate = testDate;
}
public double getTestGravity() {
return testGravity;
}
public void setTestGravity(double testGravity) {
this.testGravity = testGravity;
}
public void setTestNow() { //Set current time of test to system time
this.testDate = new GregorianCalendar();
}
//Methods
public double getAlcohol(double originalGravity) {
return (76.08 * (originalGravity - this.testGravity) / (1.775 - originalGravity)) * (this.testGravity / 0.794); // Calculation to computer ABV
}
}
| gpl-3.0 |
fhnbarock/PALS | PALS/src/com/gopals/pals/JSONParser.java | 2320 | package com.gopals.pals;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0) {
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(5000);
conn.setConnectTimeout(10000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
if(result != null){
jObj = new JSONObject(result.toString());
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
} | gpl-3.0 |
pommedeterresautee/spmf | ca/pfv/spmf/algorithms/sequentialpatterns/BIDE_and_prefixspan_with_strings/Itemset.java | 2374 | package ca.pfv.spmf.algorithms.sequentialpatterns.BIDE_and_prefixspan_with_strings;
/* This file is copyright (c) 2008-2013 Philippe Fournier-Viger
*
* This file is part of the SPMF DATA MINING SOFTWARE
* (http://www.philippe-fournier-viger.com/spmf).
*
* SPMF is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* SPMF is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with
* SPMF. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This class represents an itemset for the BIDE+ and PrefixSpan that takes sequences of strings
* as input.
*
* @see AlgoPrefixSpan_with_Strings
* @see AlgoBIDEPlus_withStrings
* @author Philippe Fournier-Viger
*/
public class Itemset{
private final List<String> items = new ArrayList<String>(); // ordered list.
public Itemset(String item){
addItem(item);
}
public Itemset(){
}
public void addItem(String value){
if(!items.contains(value)){
items.add(value);
}
}
public List<String> getItems(){
return items;
}
public String get(int index){
return items.get(index);
}
public void print(){
System.out.print(toString());
}
public String toString(){
StringBuffer r = new StringBuffer ();
for(String attribute : items){
r.append(attribute.toString());
r.append(' ');
}
return r.toString();
}
public int size(){
return items.size();
}
public Itemset cloneItemSetMinusItems(Map<String, Set<Integer>> mapSequenceID, double minsuppRelatif) {
Itemset itemset = new Itemset();
for(String item : items){
if(mapSequenceID.get(item).size() >= minsuppRelatif){
itemset.addItem(item);
}
}
return itemset;
}
public Itemset cloneItemSet(){
Itemset itemset = new Itemset();
itemset.getItems().addAll(items);
return itemset;
}
}
| gpl-3.0 |
LaboratorioBioinformatica/caravela | caravela-web/src/test/java/br/usp/iq/lbi/caravela/domain/SegmentsCalculatorImplTest.java | 15742 | package br.usp.iq.lbi.caravela.domain;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import br.usp.iq.lbi.caravela.intervalTree.Segment;
import br.usp.iq.lbi.caravela.model.Taxon;
public class SegmentsCalculatorImplTest {
@Test
public void testSubtractionBetweenSegmentLists () throws Exception {
List<Segment<Taxon>> taxonsSegmentList = new ArrayList<Segment<Taxon>>();
List<Segment<Taxon>> noTaxonSegmentList = new ArrayList<Segment<Taxon>>();
Taxon taxonA = new Taxon(1l,1l,"Taxon A", "genus");
Taxon noTaxon = Taxon.getNOTaxon();
List<Taxon> taxonListA = createTaxonList(taxonA);
List<Taxon> NotaxonList = createTaxonList(noTaxon);
noTaxonSegmentList.add(new Segment<Taxon>(50, 120, NotaxonList));
noTaxonSegmentList.add(new Segment<Taxon>(280, 350, NotaxonList));
taxonsSegmentList.add(new Segment<Taxon>(30, 100, taxonListA));
taxonsSegmentList.add(new Segment<Taxon>(150, 300, taxonListA));
taxonsSegmentList.add(new Segment<Taxon>(320, 330, taxonListA));
List<Segment<Taxon>> noTaxonSubtractedSegmentList = new ArrayList<Segment<Taxon>>();
noTaxonSubtractedSegmentList.add(new Segment<Taxon>(101, 120, NotaxonList));
noTaxonSubtractedSegmentList.add(new Segment<Taxon>(301, 319, NotaxonList));
noTaxonSubtractedSegmentList.add(new Segment<Taxon>(331, 350, NotaxonList));
SegmentsCalculatorImpl target = new SegmentsCalculatorImpl();
Assert.assertEquals(noTaxonSubtractedSegmentList, target.subtract(noTaxonSegmentList, taxonsSegmentList));
}
@Test
public void testSubtractionBetweenNoTaxonSegmentListsBelongAllContigAndTaxonSegmentStartedOnSecondBase () throws Exception {
List<Segment<Taxon>> taxonsSegmentList = new ArrayList<Segment<Taxon>>();
List<Segment<Taxon>> noTaxonSegmentList = new ArrayList<Segment<Taxon>>();
Taxon taxonA = new Taxon(1l,1l,"Taxon A", "genus");
Taxon noTaxon = Taxon.getNOTaxon();
List<Taxon> taxonListA = createTaxonList(taxonA);
List<Taxon> NotaxonList = createTaxonList(noTaxon);
noTaxonSegmentList.add(new Segment<Taxon>(1, 311, NotaxonList));
taxonsSegmentList.add(new Segment<Taxon>(2, 311, taxonListA));
List<Segment<Taxon>> noTaxonSubtractedSegmentList = new ArrayList<Segment<Taxon>>();
noTaxonSubtractedSegmentList.add(new Segment<Taxon>(1, 1, NotaxonList));
SegmentsCalculatorImpl target = new SegmentsCalculatorImpl();
Assert.assertEquals(noTaxonSubtractedSegmentList, target.subtract(noTaxonSegmentList, taxonsSegmentList));
}
@Test
public void testSubtractionBetweenMinuendAndSubtrahendListWithJustOnlyOneElementWhenElementIsOnStartOfMinuend () throws Exception {
List<Segment<Taxon>> taxonsSegmentList = new ArrayList<Segment<Taxon>>();
List<Segment<Taxon>> noTaxonSegmentList = new ArrayList<Segment<Taxon>>();
Taxon taxonA = new Taxon(1l,1l,"Taxon A", "genus");
Taxon noTaxon = Taxon.getNOTaxon();
List<Taxon> taxonListA = createTaxonList(taxonA);
List<Taxon> NotaxonList = createTaxonList(noTaxon);
Segment<Taxon> noTaxonSegment = new Segment<Taxon>(1, 60, NotaxonList);
noTaxonSegmentList.add(noTaxonSegment);
taxonsSegmentList.add(new Segment<Taxon>(1, 10, taxonListA));
List<Segment<Taxon>> noTaxonSubtractedSegmentList = new ArrayList<Segment<Taxon>>();
noTaxonSubtractedSegmentList.add(new Segment<Taxon>(11, 60, NotaxonList));
SegmentsCalculatorImpl target = new SegmentsCalculatorImpl();
Assert.assertEquals(noTaxonSubtractedSegmentList, target.subtract(noTaxonSegment, taxonsSegmentList));
}
@Test
public void testSubtractionBetweenMinuendAndSubtrahendListWithJustOnlyOneElementWhenElementIsOnEndOfMinuend () throws Exception {
List<Segment<Taxon>> taxonsSegmentList = new ArrayList<Segment<Taxon>>();
List<Segment<Taxon>> noTaxonSegmentList = new ArrayList<Segment<Taxon>>();
Taxon taxonA = new Taxon(1l,1l,"Taxon A", "genus");
Taxon noTaxon = Taxon.getNOTaxon();
List<Taxon> taxonListA = createTaxonList(taxonA);
List<Taxon> NotaxonList = createTaxonList(noTaxon);
Segment<Taxon> noTaxonSegment = new Segment<Taxon>(1, 60, NotaxonList);
noTaxonSegmentList.add(noTaxonSegment);
taxonsSegmentList.add(new Segment<Taxon>(50, 60, taxonListA));
List<Segment<Taxon>> noTaxonSubtractedSegmentList = new ArrayList<Segment<Taxon>>();
noTaxonSubtractedSegmentList.add(new Segment<Taxon>(1, 49, NotaxonList));
SegmentsCalculatorImpl target = new SegmentsCalculatorImpl();
Assert.assertEquals(noTaxonSubtractedSegmentList, target.subtract(noTaxonSegment, taxonsSegmentList));
}
@Test
public void testSubtractionBetweenMinuendAndSubtrahendListWithJustOnlyOneElementWhenElementIsOnMidleOfMinuend () throws Exception {
List<Segment<Taxon>> taxonsSegmentList = new ArrayList<Segment<Taxon>>();
List<Segment<Taxon>> noTaxonSegmentList = new ArrayList<Segment<Taxon>>();
Taxon taxonA = new Taxon(1l,1l,"Taxon A", "genus");
Taxon noTaxon = Taxon.getNOTaxon();
List<Taxon> taxonListA = createTaxonList(taxonA);
List<Taxon> NotaxonList = createTaxonList(noTaxon);
Segment<Taxon> noTaxonSegment = new Segment<Taxon>(1, 60, NotaxonList);
noTaxonSegmentList.add(noTaxonSegment);
taxonsSegmentList.add(new Segment<Taxon>(20, 30, taxonListA));
List<Segment<Taxon>> noTaxonSubtractedSegmentList = new ArrayList<Segment<Taxon>>();
noTaxonSubtractedSegmentList.add(new Segment<Taxon>(1, 19, NotaxonList));
noTaxonSubtractedSegmentList.add(new Segment<Taxon>(31, 60, NotaxonList));
SegmentsCalculatorImpl target = new SegmentsCalculatorImpl();
Assert.assertEquals(noTaxonSubtractedSegmentList, target.subtract(noTaxonSegment, taxonsSegmentList));
}
@Test
public void testSubtractionBetweenMinuendAndSubtrahendListWithJustOnlyOneElementWhenElementIsOnMidleOfMinuendAndSubtrahendGreaterThanMinuend() throws Exception {
List<Segment<Taxon>> taxonsSegmentList = new ArrayList<Segment<Taxon>>();
List<Segment<Taxon>> noTaxonSegmentList = new ArrayList<Segment<Taxon>>();
Taxon taxonA = new Taxon(1l,1l,"Taxon A", "genus");
Taxon noTaxon = Taxon.getNOTaxon();
List<Taxon> taxonListA = createTaxonList(taxonA);
List<Taxon> NotaxonList = createTaxonList(noTaxon);
noTaxonSegmentList.add(new Segment<Taxon>(57, 258, NotaxonList));
noTaxonSegmentList.add(new Segment<Taxon>(396, 558, NotaxonList));
taxonsSegmentList.add(new Segment<Taxon>(1, 444, taxonListA));
taxonsSegmentList.add(new Segment<Taxon>(464, 1604, taxonListA));
List<Segment<Taxon>> noTaxonSubtractedSegmentList = new ArrayList<Segment<Taxon>>();
noTaxonSubtractedSegmentList.add(new Segment<Taxon>(445, 463, NotaxonList));
SegmentsCalculatorImpl target = new SegmentsCalculatorImpl();
Assert.assertEquals(noTaxonSubtractedSegmentList, target.subtract(noTaxonSegmentList, taxonsSegmentList));
}
@Test
public void testSubtractionBetweenMinuendAndSubtrahendListWithJustOnlyOneElementWhenElementIsOnMidleOfMinuend2 () throws Exception {
List<Segment<Taxon>> taxonsSegmentList = new ArrayList<Segment<Taxon>>();
List<Segment<Taxon>> noTaxonSegmentList = new ArrayList<Segment<Taxon>>();
Taxon taxonA = new Taxon(1l,1l,"Taxon A", "genus");
Taxon noTaxon = Taxon.getNOTaxon();
List<Taxon> taxonListA = createTaxonList(taxonA);
List<Taxon> NotaxonList = createTaxonList(noTaxon);
Segment<Taxon> noTaxonSegment = new Segment<Taxon>(1, 60, NotaxonList);
noTaxonSegmentList.add(noTaxonSegment);
taxonsSegmentList.add(new Segment<Taxon>(10, 20, taxonListA));
taxonsSegmentList.add(new Segment<Taxon>(30, 40, taxonListA));
List<Segment<Taxon>> noTaxonSubtractedSegmentList = new ArrayList<Segment<Taxon>>();
noTaxonSubtractedSegmentList.add(new Segment<Taxon>(1, 9, NotaxonList));
noTaxonSubtractedSegmentList.add(new Segment<Taxon>(21, 29, NotaxonList));
noTaxonSubtractedSegmentList.add(new Segment<Taxon>(41, 60, NotaxonList));
SegmentsCalculatorImpl target = new SegmentsCalculatorImpl();
Assert.assertEquals(noTaxonSubtractedSegmentList, target.subtract(noTaxonSegment, taxonsSegmentList));
}
@Test
public void testSubtractionBetweenMinuendAndSubtrahendListSegmentsWhenSubtrahendListIsEmpty() throws Exception {
List<Segment<Taxon>> noTaxonSegmentList = new ArrayList<Segment<Taxon>>();
List<Segment<Taxon>> taxonsSegmentList = new ArrayList<Segment<Taxon>>();
Taxon noTaxon = Taxon.getNOTaxon();
List<Taxon> NotaxonList = createTaxonList(noTaxon);
Segment<Taxon> noTaxonSegment = new Segment<Taxon>(1, 60, NotaxonList);
noTaxonSegmentList.add(noTaxonSegment);
List<Segment<Taxon>> noTaxonSubtractedSegmentList = new ArrayList<Segment<Taxon>>();
noTaxonSubtractedSegmentList.add(new Segment<Taxon>(1, 60, NotaxonList));
SegmentsCalculatorImpl target = new SegmentsCalculatorImpl();
Assert.assertEquals(noTaxonSubtractedSegmentList, target.subtract(noTaxonSegment, taxonsSegmentList));
}
@Test
public void teste1() throws Exception {
SegmentsCalculatorImpl target = new SegmentsCalculatorImpl();
List<Segment<Taxon>> segmentListA = new ArrayList<Segment<Taxon>>();
List<Segment<Taxon>> segmentListB = new ArrayList<Segment<Taxon>>();
List<Segment<Taxon>> segmentListC = new ArrayList<Segment<Taxon>>();
Taxon taxonA = new Taxon(1l,1l,"Arcobacter", "genus");
Taxon taxonB = new Taxon(2l,1l,"Streptococcus", "genus");
Taxon taxonC = Taxon.getNOTaxon();
List<Taxon> taxonListA = createTaxonList(taxonA);
List<Taxon> taxonListB = createTaxonList(taxonB);
List<Taxon> taxonListC = createTaxonList(taxonC);
segmentListA.add(new Segment<Taxon>(25, 1321, taxonListA));
segmentListA.add(new Segment<Taxon>(1326, 1835, taxonListA));
segmentListB.add(new Segment<Taxon>(878, 1128, taxonListB));
segmentListB.add(new Segment<Taxon>(1182, 1425, taxonListB));
segmentListC.add(new Segment<Taxon>(1405, 1477, taxonListC));
segmentListC.add(new Segment<Taxon>(1696, 1758, taxonListC));
Map<Taxon, List<Segment<Taxon>>> segmentsMap = new HashMap<Taxon, List<Segment<Taxon>>>();
segmentsMap.put(taxonA, segmentListA);
segmentsMap.put(taxonB, segmentListB);
segmentsMap.put(taxonC, segmentListC);
List<Segment<Taxon>> expectedUndefinedSegmentsByTaxon = new ArrayList<Segment<Taxon>>();
List<Taxon> segmentTaxonListAB = new ArrayList<Taxon>();
segmentTaxonListAB.add(taxonA);
segmentTaxonListAB.add(taxonB);
Segment<Taxon> s1 = new Segment<Taxon>(878, 1128, segmentTaxonListAB);
Segment<Taxon> s2 = new Segment<Taxon>(1182, 1321, segmentTaxonListAB);
Segment<Taxon> s3 = new Segment<Taxon>(1326, 1425, segmentTaxonListAB);
List<Taxon> segmentTaxonListAC = new ArrayList<Taxon>();
segmentTaxonListAC.add(taxonA);
segmentTaxonListAC.add(taxonC);
Segment<Taxon> s4 = new Segment<Taxon>(1405, 1477, segmentTaxonListAC);
Segment<Taxon> s5 = new Segment<Taxon>(1696, 1758, segmentTaxonListAC);
List<Taxon> sl6 = new ArrayList<Taxon>();
sl6.add(taxonB);
sl6.add(taxonC);
Segment<Taxon> s6 = new Segment<Taxon>(1405, 1425, sl6);
expectedUndefinedSegmentsByTaxon.add(s1);
expectedUndefinedSegmentsByTaxon.add(s2);
expectedUndefinedSegmentsByTaxon.add(s3);
expectedUndefinedSegmentsByTaxon.add(s4);
expectedUndefinedSegmentsByTaxon.add(s5);
expectedUndefinedSegmentsByTaxon.add(s6);
List<Segment<Taxon>> buildSegmentsByTaxon = target.buildUndfinedSegmentsByTaxon(segmentsMap);
Collections.sort(expectedUndefinedSegmentsByTaxon);
Assert.assertEquals(expectedUndefinedSegmentsByTaxon, buildSegmentsByTaxon);
}
@Test
public void teste2() throws Exception {
SegmentsCalculatorImpl target = new SegmentsCalculatorImpl();
List<Segment<Taxon>> featureViewerDataA = new ArrayList<Segment<Taxon>>();
List<Segment<Taxon>> featureViewerDataB = new ArrayList<Segment<Taxon>>();
List<Segment<Taxon>> featureViewerDataC = new ArrayList<Segment<Taxon>>();
List<Segment<Taxon>> featureViewerDataD = new ArrayList<Segment<Taxon>>();
List<Segment<Taxon>> featureViewerDataE = new ArrayList<Segment<Taxon>>();
Taxon taxonA = new Taxon(1l,1l,"Arcobacter", "genus");
Taxon taxonB = new Taxon(2l,1l,"Streptococcus", "genus");
Taxon taxonC = Taxon.getNOTaxon();
Taxon taxonD = new Taxon(3l,1l,"Fusca", "genus");
Taxon taxonE = new Taxon(4l,1l,"Bispora", "genus");
List<Taxon> taxonListA = createTaxonList(taxonA);
List<Taxon> taxonListB = createTaxonList(taxonB);
List<Taxon> taxonListC = createTaxonList(taxonC);
List<Taxon> taxonListD = createTaxonList(taxonD);
List<Taxon> taxonListE = createTaxonList(taxonE);
featureViewerDataA.add(new Segment<Taxon>(1, 100, taxonListA));
featureViewerDataB.add(new Segment<Taxon>(10, 30, taxonListB));
featureViewerDataC.add(new Segment<Taxon>(40, 120, taxonListC));
featureViewerDataD.add(new Segment<Taxon>(60, 90, taxonListD));
featureViewerDataE.add(new Segment<Taxon>(80, 150, taxonListE));
Map<Taxon, List<Segment<Taxon>>> segmentsMap = new HashMap<Taxon, List<Segment<Taxon>>>();
segmentsMap.put(taxonA, featureViewerDataA);
segmentsMap.put(taxonB, featureViewerDataB);
segmentsMap.put(taxonC, featureViewerDataC);
segmentsMap.put(taxonD, featureViewerDataD);
segmentsMap.put(taxonE, featureViewerDataE);
List<Segment<Taxon>> expectedUndefinedSegmentsByTaxon = new ArrayList<Segment<Taxon>>();
List<Taxon> segmentTaxonListAB = new ArrayList<Taxon>();
segmentTaxonListAB.add(taxonA);
segmentTaxonListAB.add(taxonB);
Segment<Taxon> s1AB = new Segment<Taxon>(10, 30, segmentTaxonListAB);
List<Taxon> segmentTaxonListAC = new ArrayList<Taxon>();
segmentTaxonListAC.add(taxonA);
segmentTaxonListAC.add(taxonC);
Segment<Taxon> s1AC = new Segment<Taxon>(40, 100, segmentTaxonListAC);
List<Taxon> segmentTaxonListAD = new ArrayList<Taxon>();
segmentTaxonListAD.add(taxonA);
segmentTaxonListAD.add(taxonD);
Segment<Taxon> s1AD = new Segment<Taxon>(60, 90, segmentTaxonListAD);
List<Taxon> segmentTaxonListAE = new ArrayList<Taxon>();
segmentTaxonListAE.add(taxonA);
segmentTaxonListAE.add(taxonE);
Segment<Taxon> s1AE = new Segment<Taxon>(80, 100, segmentTaxonListAE);
List<Taxon> segmentTaxonListCD = new ArrayList<Taxon>();
segmentTaxonListCD.add(taxonC);
segmentTaxonListCD.add(taxonD);
Segment<Taxon> s1CD = new Segment<Taxon>(60, 90, segmentTaxonListCD);
List<Taxon> segmentTaxonListCE = new ArrayList<Taxon>();
segmentTaxonListCE.add(taxonC);
segmentTaxonListCE.add(taxonE);
Segment<Taxon> s1CE = new Segment<Taxon>(80, 120, segmentTaxonListCE);
List<Taxon> segmentTaxonListDE = new ArrayList<Taxon>();
segmentTaxonListDE.add(taxonD);
segmentTaxonListDE.add(taxonE);
Segment<Taxon> s1DE = new Segment<Taxon>(80, 90, segmentTaxonListDE);
expectedUndefinedSegmentsByTaxon.add(s1AB);
expectedUndefinedSegmentsByTaxon.add(s1AC);
expectedUndefinedSegmentsByTaxon.add(s1AE);
expectedUndefinedSegmentsByTaxon.add(s1CD);
expectedUndefinedSegmentsByTaxon.add(s1AD);
expectedUndefinedSegmentsByTaxon.add(s1CE);
expectedUndefinedSegmentsByTaxon.add(s1DE);
Collections.sort(expectedUndefinedSegmentsByTaxon);
List<Segment<Taxon>> buildSegmentsByTaxon = target.buildUndfinedSegmentsByTaxon(segmentsMap);
Assert.assertEquals(expectedUndefinedSegmentsByTaxon, buildSegmentsByTaxon);
}
private List<Taxon> createTaxonList(Taxon... taxons) {
List<Taxon> taxonList = new ArrayList<Taxon>();
for (Taxon taxon : taxons) {
taxonList.add(taxon);
}
return taxonList;
}
}
| gpl-3.0 |
rubenswagner/L2J-Global | java/com/l2jglobal/gameserver/network/clientpackets/commission/RequestCommissionCancel.java | 1266 | /*
* This file is part of the L2J Global project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jglobal.gameserver.network.clientpackets.commission;
import com.l2jglobal.commons.network.PacketReader;
import com.l2jglobal.gameserver.network.client.L2GameClient;
import com.l2jglobal.gameserver.network.clientpackets.IClientIncomingPacket;
/**
* This Packet doesn't seem to be doing anything.
* @author NosBit
*/
public class RequestCommissionCancel implements IClientIncomingPacket
{
@Override
public boolean read(L2GameClient client, PacketReader packet)
{
return false;
}
@Override
public void run(L2GameClient client)
{
}
}
| gpl-3.0 |
MythTV-Clients/MythTV-Android-Frontend | src/org/mythtv/db/status/model/package-info.java | 904 | /**
* This file is part of MythTV Android Frontend
*
* MythTV Android Frontend is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MythTV Android Frontend is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MythTV Android Frontend. If not, see <http://www.gnu.org/licenses/>.
*
* This software can be found at <https://github.com/MythTV-Clients/MythTV-Android-Frontend/>
*/
/**
* @author Daniel Frey
*
*/
package org.mythtv.db.status.model; | gpl-3.0 |
ArneBinder/LanguageAnalyzer | src/main/java/ca/pfv/spmf/algorithms/frequentpatterns/fin_prepost/PrePost.java | 18947 | package ca.pfv.spmf.algorithms.frequentpatterns.fin_prepost;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import ca.pfv.spmf.tools.MemoryLogger;
/*
* Copyright (c) 2008-2015 ZHIHONG DENG
*
* This file is part of the SPMF DATA MINING SOFTWARE
* (http://www.philippe-fournier-viger.com/spmf).
*
* SPMF is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* SPMF is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* SPMF. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Java implementation of the PrePost/PrePost+ algorithm.
*
* This implementation was obtained by converting the original C++ code of
* Prepost by ZHIHONG DENG to Java.
*
* @author Philippe Fournier-Viger
*/
public class PrePost {
// the start time and end time of the last algorithm execution
long startTimestamp;
long endTimestamp;
// number of itemsets found
int outputCount;
// object to write the output file
BufferedWriter writer = null;
public int[][] bf;
public int bf_cursor;
public int bf_size;
public int bf_col;
public int bf_currentSize;
public int numOfFItem; // Number of items
public int minSupport; // minimum support
public Item[] item; // list of items sorted by support
// public FILE out;
public int[] result; // the current itemset
public int resultLen; // the size of the current itemset
public int resultCount;
public int nlLenSum; // node list length of the current itemset
// Tree stuff
public PPCTreeNode ppcRoot;
public NodeListTreeNode nlRoot;
public PPCTreeNode[] headTable;
public int[] headTableLen;
public int[] itemsetCount;
public int[] sameItems;
public int nlNodeCount;
// if this parameter is set to true, the PrePost+ algorithm is run instead of PrePost
// (both are implemented in this file, because they have similarities)
public boolean usePrePostPlus = false;
/**
* Use this method to indicate that you want to use the PrePost+ algorithm
* instead of PrePost.
* @param usePrePostPlus if true, PrePost+ will be run instead of PrePost when executing the method runAlgorithm()
*/
public void setUsePrePostPlus(boolean usePrePostPlus) {
this.usePrePostPlus = usePrePostPlus;
}
/**
* Comparator to sort items by decreasing order of frequency
*/
static Comparator<Item> comp = new Comparator<Item>() {
public int compare(Item a, Item b) {
return ((Item) b).num - ((Item) a).num;
}
};
private int numOfTrans;
/**
* Run the algorithm
*
* @param filename
* the input file path
* @param minsup
* the minsup threshold
* @param output
* the output file path
* @throws IOException
* if error while reading/writting to file
*/
public void runAlgorithm(String filename, double minsup, String output)
throws IOException {
outputCount = 0;
nlNodeCount = 0;
ppcRoot = new PPCTreeNode();
nlRoot = new NodeListTreeNode();
resultLen = 0;
resultCount = 0;
nlLenSum = 0;
MemoryLogger.getInstance().reset();
// create object for writing the output file
writer = new BufferedWriter(new FileWriter(output));
// record the start time
startTimestamp = System.currentTimeMillis();
bf_size = 1000000;
bf = new int[100000][];
bf_currentSize = bf_size * 10;
bf[0] = new int[bf_currentSize];
bf_cursor = 0;
bf_col = 0;
// ==========================
// Read Dataset
getData(filename, minsup);
resultLen = 0;
result = new int[numOfFItem];
// Build tree
buildTree(filename);
nlRoot.label = numOfFItem;
nlRoot.firstChild = null;
nlRoot.next = null;
// Initialize tree
initializeTree();
sameItems = new int[numOfFItem];
int from_cursor = bf_cursor;
int from_col = bf_col;
int from_size = bf_currentSize;
// Recursively traverse the tree
NodeListTreeNode curNode = nlRoot.firstChild;
NodeListTreeNode next = null;
while (curNode != null) {
next = curNode.next;
// call the recursive "traverse" method
traverse(curNode, nlRoot, 1, 0);
for (int c = bf_col; c > from_col; c--) {
bf[c] = null;
}
bf_col = from_col;
bf_cursor = from_cursor;
bf_currentSize = from_size;
curNode = next;
}
writer.close();
MemoryLogger.getInstance().checkMemory();
// record the end time
endTimestamp = System.currentTimeMillis();
}
/**
* Build the tree
*
* @param filename
* the input filename
* @throws IOException
* if an exception while reading/writting to file
*/
void buildTree(String filename) throws IOException {
ppcRoot.label = -1;
// READ THE FILE
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
// we will use a buffer to store each transaction that is read.
Item[] transaction = new Item[1000];
// for each line (transaction) until the end of the file
while (((line = reader.readLine()) != null)) {
// if the line is a comment, is empty or is a
// kind of metadata
if (line.isEmpty() == true || line.charAt(0) == '#'
|| line.charAt(0) == '%' || line.charAt(0) == '@') {
continue;
}
// split the line into items
String[] lineSplited = line.split(" ");
// for each item in the transaction
int tLen = 0; // tLen
for (String itemString : lineSplited) {
// get the item
int itemX = Integer.parseInt(itemString);
// add each item from the transaction except infrequent item
for (int j = 0; j < numOfFItem; j++) {
// if the item appears in the list of frequent items, we add
// it
if (itemX == item[j].index) {
transaction[tLen] = new Item();
transaction[tLen].index = itemX; // the item
transaction[tLen].num = 0 - j;
tLen++;
break;
}
}
}
// sort the transaction
Arrays.sort(transaction, 0, tLen, comp);
// Print the transaction
// for(int j=0; j < tLen; j++){
// System.out.print(" " + transaction[j].index + " ");
// }
// System.out.println();
int curPos = 0;
PPCTreeNode curRoot = (ppcRoot);
PPCTreeNode rightSibling = null;
while (curPos != tLen) {
PPCTreeNode child = curRoot.firstChild;
while (child != null) {
if (child.label == 0 - transaction[curPos].num) {
curPos++;
child.count++;
curRoot = child;
break;
}
if (child.rightSibling == null) {
rightSibling = child;
child = null;
break;
}
child = child.rightSibling;
}
if (child == null)
break;
}
for (int j = curPos; j < tLen; j++) {
PPCTreeNode ppcNode = new PPCTreeNode();
ppcNode.label = 0 - transaction[j].num;
if (rightSibling != null) {
rightSibling.rightSibling = ppcNode;
rightSibling = null;
} else {
curRoot.firstChild = ppcNode;
}
ppcNode.rightSibling = null;
ppcNode.firstChild = null;
ppcNode.father = curRoot;
ppcNode.labelSibling = null;
ppcNode.count = 1;
curRoot = ppcNode;
}
}
// close the input file
reader.close();
// System.out.println( "====");
// Create a header table
headTable = new PPCTreeNode[numOfFItem];
headTableLen = new int[numOfFItem];
PPCTreeNode[] tempHead = new PPCTreeNode[numOfFItem];
itemsetCount = new int[(numOfFItem - 1) * numOfFItem / 2];
PPCTreeNode root = ppcRoot.firstChild;
int pre = 0;
int last = 0;
while (root != null) {
root.foreIndex = pre;
pre++;
if (headTable[root.label] == null) {
headTable[root.label] = root;
tempHead[root.label] = root;
} else {
tempHead[root.label].labelSibling = root;
tempHead[root.label] = root;
}
headTableLen[root.label]++;
PPCTreeNode temp = root.father;
while (temp.label != -1) {
itemsetCount[root.label * (root.label - 1) / 2 + temp.label] += root.count;
temp = temp.father;
}
if (root.firstChild != null) {
root = root.firstChild;
} else {
// back visit
root.backIndex = last;
last++;
if (root.rightSibling != null) {
root = root.rightSibling;
} else {
root = root.father;
while (root != null) {
// back visit
root.backIndex = last;
last++;
if (root.rightSibling != null) {
root = root.rightSibling;
break;
}
root = root.father;
}
}
}
}
}
/**
* Initialize the tree
*/
void initializeTree() {
NodeListTreeNode lastChild = null;
for (int t = numOfFItem - 1; t >= 0; t--) {
if (bf_cursor > bf_currentSize - headTableLen[t] * 3) {
bf_col++;
bf_cursor = 0;
bf_currentSize = 10 * bf_size;
bf[bf_col] = new int[bf_currentSize];
}
NodeListTreeNode nlNode = new NodeListTreeNode();
nlNode.label = t;
nlNode.support = 0;
nlNode.NLStartinBf = bf_cursor;
nlNode.NLLength = 0;
nlNode.NLCol = bf_col;
nlNode.firstChild = null;
nlNode.next = null;
PPCTreeNode ni = headTable[t];
while (ni != null) {
nlNode.support += ni.count;
bf[bf_col][bf_cursor++] = ni.foreIndex;
bf[bf_col][bf_cursor++] = ni.backIndex;
bf[bf_col][bf_cursor++] = ni.count;
nlNode.NLLength++;
ni = ni.labelSibling;
}
if (nlRoot.firstChild == null) {
nlRoot.firstChild = nlNode;
lastChild = nlNode;
} else {
lastChild.next = nlNode;
lastChild = nlNode;
}
}
}
/**
* Read the input file to find the frequent items
*
* @param filename
* input file name
* @param minSupport
* @throws IOException
*/
void getData(String filename, double support) throws IOException {
numOfTrans = 0;
// (1) Scan the database and count the support of each item.
// The support of items is stored in map where
// key = item value = support count
Map<Integer, Integer> mapItemCount = new HashMap<Integer, Integer>();
// scan the database
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
// for each line (transaction) until the end of the file
while (((line = reader.readLine()) != null)) {
// if the line is a comment, is empty or is a
// kind of metadata
if (line.isEmpty() == true || line.charAt(0) == '#'
|| line.charAt(0) == '%' || line.charAt(0) == '@') {
continue;
}
numOfTrans++;
// split the line into items
String[] lineSplited = line.split(" ");
// for each item in the transaction
for (String itemString : lineSplited) {
// increase the support count of the item by 1
Integer item = Integer.parseInt(itemString);
Integer count = mapItemCount.get(item);
if (count == null) {
mapItemCount.put(item, 1);
} else {
mapItemCount.put(item, ++count);
}
}
}
// close the input file
reader.close();
minSupport = (int) Math.ceil(support * numOfTrans);
numOfFItem = mapItemCount.size();
Item[] tempItems = new Item[numOfFItem];
int i = 0;
for (Entry<Integer, Integer> entry : mapItemCount.entrySet()) {
if (entry.getValue() >= minSupport) {
tempItems[i] = new Item();
tempItems[i].index = entry.getKey();
tempItems[i].num = entry.getValue();
i++;
}
}
item = new Item[i];
System.arraycopy(tempItems, 0, item, 0, i);
numOfFItem = item.length;
Arrays.sort(item, comp);
}
NodeListTreeNode iskItemSetFreq(NodeListTreeNode ni, NodeListTreeNode nj,
int level, NodeListTreeNode lastChild, IntegerByRef sameCountRef) {
// System.out.println("====\n" + "isk_itemSetFreq() samecount = " +
// sameCountRef.count);
if (bf_cursor + ni.NLLength * 3 > bf_currentSize) {
bf_col++;
bf_cursor = 0;
bf_currentSize = bf_size > ni.NLLength * 1000 ? bf_size
: ni.NLLength * 1000;
bf[bf_col] = new int[bf_currentSize];
}
NodeListTreeNode nlNode = new NodeListTreeNode();
nlNode.support = 0;
nlNode.NLStartinBf = bf_cursor;
nlNode.NLCol = bf_col;
nlNode.NLLength = 0;
int cursor_i = ni.NLStartinBf;
int cursor_j = nj.NLStartinBf;
int col_i = ni.NLCol;
int col_j = nj.NLCol;
int last_cur = -1;
while (cursor_i < ni.NLStartinBf + ni.NLLength * 3
&& cursor_j < nj.NLStartinBf + nj.NLLength * 3) {
if (bf[col_i][cursor_i] > bf[col_j][cursor_j]
&& bf[col_i][cursor_i + 1] < bf[col_j][cursor_j + 1]) {
if (last_cur == cursor_j) {
bf[bf_col][bf_cursor - 1] += bf[col_i][cursor_i + 2];
} else {
bf[bf_col][bf_cursor++] = bf[col_j][cursor_j];
bf[bf_col][bf_cursor++] = bf[col_j][cursor_j + 1];
bf[bf_col][bf_cursor++] = bf[col_i][cursor_i + 2];
nlNode.NLLength++;
}
nlNode.support += bf[col_i][cursor_i + 2];
last_cur = cursor_j;
cursor_i += 3;
} else if (bf[col_i][cursor_i] < bf[col_j][cursor_j]) {
cursor_i += 3;
} else if (bf[col_i][cursor_i + 1] > bf[col_j][cursor_j + 1]) {
cursor_j += 3;
}
}
if (nlNode.support >= minSupport) {
if (ni.support == nlNode.support && (usePrePostPlus || nlNode.NLLength == 1)) {
sameItems[sameCountRef.count++] = nj.label;
bf_cursor = nlNode.NLStartinBf;
if (nlNode != null) {
nlNode = null;
}
} else {
nlNode.label = nj.label;
nlNode.firstChild = null;
nlNode.next = null;
if (ni.firstChild == null) {
ni.firstChild = nlNode;
lastChild = nlNode;
} else {
lastChild.next = nlNode;
lastChild = nlNode;
}
}
return lastChild;
} else {
bf_cursor = nlNode.NLStartinBf;
if (nlNode != null)
nlNode = null;
}
return lastChild;
}
/**
* Recursively traverse the tree to find frequent itemsets
* @param curNode
* @param curRoot
* @param level
* @param sameCount
* @throws IOException if error while writing itemsets to file
*/
public void traverse(NodeListTreeNode curNode, NodeListTreeNode curRoot,
int level, int sameCount) throws IOException {
MemoryLogger.getInstance().checkMemory();
// System.out.println("==== traverse(): " + curNode.label + " "+ level +
// " " + sameCount);
NodeListTreeNode sibling = curNode.next;
NodeListTreeNode lastChild = null;
while (sibling != null) {
if (level > 1
|| (level == 1 && itemsetCount[(curNode.label - 1)
* curNode.label / 2 + sibling.label] >= minSupport)) {
// tangible.RefObject<Integer> tempRef_sameCount = new
// tangible.RefObject<Integer>(
// sameCount);
// int sameCountTemp = sameCount;
IntegerByRef sameCountTemp = new IntegerByRef();
sameCountTemp.count = sameCount;
lastChild = iskItemSetFreq(curNode, sibling, level, lastChild,
sameCountTemp);
sameCount = sameCountTemp.count;
}
sibling = sibling.next;
}
resultCount += Math.pow(2.0, sameCount);
nlLenSum += Math.pow(2.0, sameCount) * curNode.NLLength;
result[resultLen++] = curNode.label;
// ============= Write itemset(s) to file ===========
writeItemsetsToFile(curNode, sameCount);
// ======== end of write to file
nlNodeCount++;
int from_cursor = bf_cursor;
int from_col = bf_col;
int from_size = bf_currentSize;
NodeListTreeNode child = curNode.firstChild;
NodeListTreeNode next = null;
while (child != null) {
next = child.next;
traverse(child, curNode, level + 1, sameCount);
for (int c = bf_col; c > from_col; c--) {
bf[c] = null;
}
bf_col = from_col;
bf_cursor = from_cursor;
bf_currentSize = from_size;
child = next;
}
resultLen--;
}
/**
* This method write an itemset to file + all itemsets that can be made
* using its node list.
*
* @param curNode
* the current node
* @param sameCount
* the same count
* @throws IOException
* exception if error reading/writting to file
*/
private void writeItemsetsToFile(NodeListTreeNode curNode, int sameCount)
throws IOException {
// create a stringuffer
StringBuilder buffer = new StringBuilder();
if(curNode.support >= minSupport) {
outputCount++;
// append items from the itemset to the StringBuilder
for (int i = 0; i < resultLen; i++) {
buffer.append(item[result[i]].index);
buffer.append(' ');
}
// append the support of the itemset
buffer.append("#SUP: ");
buffer.append(curNode.support);
buffer.append("\n");
}
// === Write all combination that can be made using the node list of
// this itemset
if (sameCount > 0) {
// generate all subsets of the node list except the empty set
for (long i = 1, max = 1 << sameCount; i < max; i++) {
for (int k = 0; k < resultLen; k++) {
buffer.append(item[result[k]].index);
buffer.append(' ');
}
// we create a new subset
for (int j = 0; j < sameCount; j++) {
// check if the j bit is set to 1
int isSet = (int) i & (1 << j);
if (isSet > 0) {
// if yes, add it to the set
buffer.append(item[sameItems[j]].index);
buffer.append(' ');
// newSet.add(item[sameItems[j]].index);
}
}
buffer.append("#SUP: ");
buffer.append(curNode.support);
buffer.append("\n");
outputCount++;
}
}
// write the strinbuffer to file and create a new line
// so that we are ready for writing the next itemset.
writer.write(buffer.toString());
}
/**
* Print statistics about the latest execution of the algorithm to
* System.out.
*/
public void printStats() {
String prePost = usePrePostPlus ? "PrePost+" : "PrePost";
System.out.println("========== " + prePost + " - STATS ============");
System.out.println(" Minsup = " + minSupport
+ "\n Number of transactions: " + numOfTrans);
System.out.println(" Number of frequent itemsets: " + outputCount);
System.out.println(" Total time ~: " + (endTimestamp - startTimestamp)
+ " ms");
System.out.println(" Max memory:"
+ MemoryLogger.getInstance().getMaxMemory() + " MB");
System.out.println("=====================================");
}
/**
* Class to pass an integer by reference as in C++
*/
class IntegerByRef {
int count;
}
class Item {
public int index;
public int num;
}
class NodeListTreeNode {
public int label;
public NodeListTreeNode firstChild;
public NodeListTreeNode next;
public int support;
public int NLStartinBf;
public int NLLength;
public int NLCol;
}
class PPCTreeNode {
public int label;
public PPCTreeNode firstChild;
public PPCTreeNode rightSibling;
public PPCTreeNode labelSibling;
public PPCTreeNode father;
public int count;
public int foreIndex;
public int backIndex;
}
}
| gpl-3.0 |
ricecakesoftware/CommunityMedicalLink | ricecakesoftware.communitymedicallink.sql.documentregistry/src/ricecakesoftware/communitymedicallink/sql/documentregistry/documentrlationship/SelDocumentRelationship004Parameter.java | 1148 | package ricecakesoftware.communitymedicallink.sql.documentregistry.documentrlationship;
import java.io.Serializable;
/**
* 文書間関係検索パラメーター
* @author RCSW)Y.Omoya
*/
public class SelDocumentRelationship004Parameter implements Serializable {
/** sourceObject */
private String sourceObject;
/** targetObject */
private String targetObject;
/**
* コンストラクター
*/
public SelDocumentRelationship004Parameter() {
this.sourceObject = null;
this.targetObject = null;
}
/**
* sourceObject取得
* @return sourceObject
*/
public String getSourceObject() {
return this.sourceObject;
}
/**
* sourceObject設定
* @param sourceObject sourceObject
*/
public void setSourceObject(String sourceObject) {
this.sourceObject = sourceObject;
}
/**
* targetObject取得
* @return targetObject
*/
public String getTargetObject() {
return this.targetObject;
}
/**
* targetObject設定
* @param targetObject targetObject
*/
public void setTargetObject(String targetObject) {
this.targetObject = targetObject;
}
}
| gpl-3.0 |
SzommerLaszlo/recommendation-engine | import-dataset/src/main/java/com/utcluj/recommender/dataset/batch/writers/PostItemWriter.java | 3192 | package com.utcluj.recommender.dataset.batch.writers;
import com.utcluj.recommender.dataset.domain.Post;
import com.utcluj.recommender.dataset.services.TagService;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Writer to handle the post related operations and validations.
*/
public class PostItemWriter implements ItemWriter<Post> {
/** Writer to delegate to. */
private ItemWriter<Post> postItemWriter;
/** Database template to handle the database operations. */
private JdbcOperations jdbcTemplate;
/** Service for making the relations between tags and the post. */
private TagService tagService;
@Override
public void write(List<? extends Post> items) throws Exception {
final List<Tuple<Long, Long>> postTagPairings = new ArrayList<>();
for (Post post : items) {
if (StringUtils.hasText(post.getTags())) {
post.setTagIds(new ArrayList<>());
String[] tags = post.getTags().split(">");
for (String tag : tags) {
String curTag = tag;
if (tag.startsWith("<")) {
curTag = tag.substring(1);
}
long tagId = tagService.getTagId(curTag);
post.getTagIds().add(tagId);
postTagPairings.add(new Tuple<>(post.getId(), tagId));
}
}
}
postItemWriter.write(items);
jdbcTemplate.batchUpdate("insert into POST_TAG (POST_ID, TAG_ID) VALUES (?, ?)",
new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setLong(1, postTagPairings.get(i).getKey());
ps.setLong(2, postTagPairings.get(i).getValue());
}
@Override
public int getBatchSize() {
return postTagPairings.size();
}
});
}
public void setDelegateWriter(ItemWriter<Post> postItemWriter) {
Assert.notNull(postItemWriter);
this.postItemWriter = postItemWriter;
}
@Autowired
public void setJdbcTemplate(JdbcOperations jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Autowired
public void setTagService(TagService tagService) {
this.tagService = tagService;
}
private class Tuple<T, D> {
private final T key;
private final D value;
public Tuple(T key, D value) {
this.key = key;
this.value = value;
}
public T getKey() {
return key;
}
public D getValue() {
return value;
}
@Override
public String toString() {
return "key: " + key + " value: " + value;
}
}
}
| gpl-3.0 |
abkumar/Implementation-of-Basic-Data-Structures-in-JAVA | ds/src/main/java/com/ds/LeetCode/ContainerWithMostWater.java | 1745 | /**
*
*/
package com.ds.LeetCode;
/**
* Created by Abhishek Kumar
* 8:09:02 PM Aug 30, 2012
*
* @Bangalore LeetCode Problems
* Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai).
* n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
* Find two lines,which together with x-axis forms a container, such that the container contains the most water.
*/
public class ContainerWithMostWater {
public static int maxAreaN2(int[] height) { //bad
// Start typing your Java solution below
// DO NOT write main() function
int area = 0;
for (int i = 0; i < height.length; i++) {
for (int j = i + 1; j < height.length; j++) {
if (j == i) {
continue;
}
if ((j - i) * Math.min(height[i], height[j]) > area) {
area = (j - i) * Math.min(height[i], height[j]);
}
}
}
return area;
}
public static int maxArea(int[] height) {
int maxArea = 0;
int start = 0;
int end = height.length - 1;
while (start < end) {
int minHeight = height[start] < height[end] ? height[start] : height[end];
if (minHeight * (end - start) > maxArea) {
maxArea = minHeight * (end - start);
}
if (height[start] <= height[end]) {
while (height[start] <= minHeight && start < end) {
start++;
}
} else {
while (height[end] <= minHeight && start < end) {
end--;
}
}
}
return maxArea;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] height = {1, 9, 1, 2, 1};
System.out.print(maxArea(height));
}
}
| gpl-3.0 |
TGAC/miso-lims | core/src/main/java/uk/ac/bbsrc/tgac/miso/core/data/workflow/WorkflowStepPrompt.java | 684 | package uk.ac.bbsrc.tgac.miso.core.data.workflow;
import java.util.Set;
import uk.ac.bbsrc.tgac.miso.core.data.workflow.ProgressStep.InputType;
public class WorkflowStepPrompt {
private Set<InputType> inputTypes;
private String message;
public WorkflowStepPrompt(Set<InputType> inputTypes, String message) {
this.inputTypes = inputTypes;
this.message = message;
}
public Set<InputType> getInputTypes() {
return inputTypes;
}
public void setInputTypes(Set<InputType> inputTypes) {
this.inputTypes = inputTypes;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| gpl-3.0 |
jmrunge/osiris-platform | osiris-web-lib/src/ar/com/zir/osiris/web/app/configuration/CalleNode.java | 868 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ar.com.zir.osiris.web.app.configuration;
import ar.com.zir.osiris.api.personas.Calle;
import ar.com.zir.osiris.web.app.DynamicTreeNode;
import ar.com.zir.osiris.web.app.NodeTypes;
import org.primefaces.model.TreeNode;
/**
*
* @author jmrunge
*/
public class CalleNode extends DynamicTreeNode {
public CalleNode(Calle calle, TreeNode parent, boolean selectable, boolean addChildren) {
super(NodeTypes.CALLE_NODE_TYPE, calle, parent, selectable, addChildren);
}
@Override
protected void addChildren() {
Calle calle = (Calle)getData();
new DynamicTreeNode("Nombre: " + calle.getNombre(), this, false, false);
new LocalidadNode(calle.getLocalidad(), this, false, false);
}
}
| gpl-3.0 |
lipki/TFCNT | src/Common/com/bioxx/tfc/Blocks/BlockTerra.java | 3381 | package com.bioxx.tfc.Blocks;
import static net.minecraftforge.common.util.ForgeDirection.UP;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.EnumPlantType;
import net.minecraftforge.common.IPlantable;
import net.minecraftforge.common.util.ForgeDirection;
import com.bioxx.tfc.Core.TFC_Core;
import com.bioxx.tfc.api.TFCOptions;
public abstract class BlockTerra extends Block
{
protected BlockTerra()
{
super(Material.rock);
}
protected BlockTerra(Material material)
{
super(material);
}
@Override
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityliving, ItemStack is)
{
//TODO: Debug Message should go here if debug is toggled on
if(TFCOptions.enableDebugMode && world.isRemote)
{
int metadata = world.getBlockMetadata(x, y, z);
System.out.println("Meta="+(new StringBuilder()).append(getUnlocalizedName()).append(":").append(metadata).toString());
}
}
@Override
public boolean canBeReplacedByLeaves(IBlockAccess world, int x, int y, int z)
{
return false;
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityplayer, int side, float hitX, float hitY, float hitZ)
{
if(TFCOptions.enableDebugMode && world.isRemote)
{
int metadata = world.getBlockMetadata(x, y, z);
System.out.println("Meta = "+(new StringBuilder()).append(getUnlocalizedName()).append(":").append(metadata).toString());
}
return false;
}
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLiving entityliving)
{
onBlockPlacedBy(world, x, y, z, entityliving, null);
}
@Override
public void harvestBlock(World world, EntityPlayer player, int x, int y, int z, int meta)
{
super.harvestBlock(world, player, x, y, z, meta);
TFC_Core.addPlayerExhaustion(player, 0.001f);
}
@Override
public boolean canSustainPlant(IBlockAccess world, int x, int y, int z, ForgeDirection direction, IPlantable plantable)
{
Block plant = plantable.getPlant(world, x, y + 1, z);
EnumPlantType plantType = plantable.getPlantType(world, x, y + 1, z);
if (plant == Blocks.cactus && this == Blocks.cactus)
{
return true;
}
if (plant == Blocks.reeds && this == Blocks.reeds)
{
return true;
}
switch (plantType)
{
case Cave: return isSideSolid(world, x, y, z, UP);
case Plains: return TFC_Core.isSoil(this);
case Water: return world.getBlock(x, y, z).getMaterial() == Material.water && world.getBlockMetadata(x, y, z) == 0;
case Beach:
boolean isBeach = TFC_Core.isSand(this) || TFC_Core.isGravel(this);
boolean hasWater = (world.getBlock(x - 1, y, z ).getMaterial() == Material.water ||
world.getBlock(x + 1, y, z ).getMaterial() == Material.water ||
world.getBlock(x, y, z - 1).getMaterial() == Material.water ||
world.getBlock(x, y, z + 1).getMaterial() == Material.water);
return isBeach && hasWater;
default: return false;
}
}
}
| gpl-3.0 |
PriscH/Netball | src/main/java/com/prisch/repositories/TeamMemberRepository.java | 3787 | package com.prisch.repositories;
import android.content.*;
import android.database.Cursor;
import android.net.Uri;
import com.prisch.content.NetballContentProvider;
import com.prisch.model.Position;
import com.prisch.model.TeamMember;
import java.util.*;
public class TeamMemberRepository {
private Context context;
public TeamMemberRepository(Context context) {
this.context = context;
}
// ===== Interface =====
public void createTeam(long gameId, Map<Long, Position> teamMap) {
for (long playerId : teamMap.keySet()) {
createTeamMember(gameId, playerId, teamMap.get(playerId));
}
}
public void updateTeam(long gameId, Map<Long, Position> teamMap) {
List<TeamMember> currentTeamMembers = new LinkedList<TeamMember>();
Cursor currentTeamCursor = getTeamForGame(gameId);
while (currentTeamCursor.moveToNext()) {
currentTeamMembers.add(new TeamMember(currentTeamCursor));
}
ContentValues deactivateContentValues = new ContentValues();
deactivateContentValues.put(TeamMember.ACTIVE, false);
String whereGame = TeamMember.GAME_ID + "=?";
String[] gameParameters = new String[] {Long.toString(gameId)};
context.getContentResolver().update(NetballContentProvider.URI_TEAMS, deactivateContentValues, whereGame, gameParameters);
for (Long playerId : teamMap.keySet()) {
Position position = teamMap.get(playerId);
TeamMember currentTeamMember = null;
for (TeamMember teamMember : currentTeamMembers) {
if (playerId.equals(teamMember.getPlayerId()) && position.equals(teamMember.getPosition())) {
currentTeamMember = teamMember;
break;
}
}
if (currentTeamMember == null) {
createTeamMember(gameId, playerId, position);
} else {
activateTeamMember(currentTeamMember.getId());
}
}
}
public long createTeamMember(long gameId, long playerId, Position position) {
ContentValues contentValues = new ContentValues();
contentValues.put(TeamMember.GAME_ID, gameId);
contentValues.put(TeamMember.PLAYER_ID, playerId);
contentValues.put(TeamMember.POSITION, position.getAcronym());
contentValues.put(TeamMember.ACTIVE, true);
Uri resultUri = context.getContentResolver().insert(NetballContentProvider.URI_TEAMS, contentValues);
return ContentUris.parseId(resultUri);
}
public void activateTeamMember(long teamMemberId) {
ContentValues contentValues = new ContentValues();
contentValues.put(TeamMember.ACTIVE, true);
String where = TeamMember.ID + "=?";
String[] parameters = new String[] {Long.toString(teamMemberId)};
context.getContentResolver().update(NetballContentProvider.URI_TEAMS, contentValues, where, parameters);
}
public Loader<Cursor> getActiveTeam() {
return new CursorLoader(context, NetballContentProvider.URI_ACTIVE_TEAM, null, null, null, null);
}
public Cursor getTeamForGame(long gameId) {
String where = TeamMember.GAME_ID + "=?";
String[] parameters = new String[] {Long.toString(gameId)};
return context.getContentResolver().query(NetballContentProvider.URI_TEAMS, TeamMember.DEFAULT_PROJECTION, where, parameters, null);
}
public Loader<Cursor> getTeamForGameLoader(long gameId) {
String where = TeamMember.GAME_ID + "=?";
String[] parameters = new String[] {Long.toString(gameId)};
return new CursorLoader(context, NetballContentProvider.URI_TEAMS, TeamMember.DEFAULT_PROJECTION, where, parameters, null);
}
}
| gpl-3.0 |
BasicOperations/vids | vids/src/beans/BluRay.java | 474 | package beans;
public class BluRay implements StorageMedium {
private int id;
private String title;
private Medium medium;
public BluRay(){
}
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
public int getID() {
return id;
}
public void setID(int id){
this.id = id;
}
public Medium getMedium() {
return medium;
}
public void setMedia(Medium medium) {
this.medium = medium;
}
}
| gpl-3.0 |
kyyblabla/ee-platform | ee-platform-module/src/main/java/com/ax/system/user/service/RoleService.java | 944 | package com.ax.system.user.service;
import com.ax.common.service.BaseService;
import com.ax.system.user.dao.RoleDao;
import com.ax.system.user.dao.UserRoleDao;
import com.ax.system.user.entity.Role;
import com.ax.system.user.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by AxCodeGen on 2017/10/27.
*/
@Service
public class RoleService extends BaseService<Role, RoleDao> {
@Autowired
private UserRoleDao userRoleDao;
/**
* 获取用户所有角色
*
* @param userId
* @return
*/
public List<Role> getAllByUserId(long userId) {
return dao.findAll(userRoleDao.findByUserId(userId)
.stream()
.map(UserRole::getUserId)
.distinct()
.collect(Collectors.toList()));
}
} | gpl-3.0 |
iterate-ch/cyberduck | dracoon/src/main/java/ch/cyberduck/core/sds/io/swagger/client/model/ClassificationPoliciesConfig.java | 3342 | /*
* DRACOON API
* REST Web Services for DRACOON<br><br>This page provides an overview of all available and documented DRACOON APIs, which are grouped by tags.<br>Each tag provides a collection of APIs that are intended for a specific area of the DRACOON.<br><br><a title='Developer Information' href='https://developer.dracoon.com'>Developer Information</a>  <a title='Get SDKs on GitHub' href='https://github.com/dracoon'>Get SDKs on GitHub</a><br><br><a title='Terms of service' href='https://www.dracoon.com/terms/general-terms-and-conditions/'>Terms of service</a>
*
* OpenAPI spec version: 4.30.0-beta.4
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package ch.cyberduck.core.sds.io.swagger.client.model;
import java.util.Objects;
import java.util.Arrays;
import ch.cyberduck.core.sds.io.swagger.client.model.ShareClassificationPolicies;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* Set of classification policies
*/
@Schema(description = "Set of classification policies")
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.JavaClientCodegen", date = "2021-08-16T11:28:10.116221+02:00[Europe/Zurich]")
public class ClassificationPoliciesConfig {
@JsonProperty("shareClassificationPolicies")
private ShareClassificationPolicies shareClassificationPolicies = null;
public ClassificationPoliciesConfig shareClassificationPolicies(ShareClassificationPolicies shareClassificationPolicies) {
this.shareClassificationPolicies = shareClassificationPolicies;
return this;
}
/**
* Get shareClassificationPolicies
* @return shareClassificationPolicies
**/
@Schema(description = "")
public ShareClassificationPolicies getShareClassificationPolicies() {
return shareClassificationPolicies;
}
public void setShareClassificationPolicies(ShareClassificationPolicies shareClassificationPolicies) {
this.shareClassificationPolicies = shareClassificationPolicies;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClassificationPoliciesConfig classificationPoliciesConfig = (ClassificationPoliciesConfig) o;
return Objects.equals(this.shareClassificationPolicies, classificationPoliciesConfig.shareClassificationPolicies);
}
@Override
public int hashCode() {
return Objects.hash(shareClassificationPolicies);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ClassificationPoliciesConfig {\n");
sb.append(" shareClassificationPolicies: ").append(toIndentedString(shareClassificationPolicies)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| gpl-3.0 |
papamas/DMS-KANGREG-XI-MANADO | src/main/java/com/openkm/frontend/client/widget/findsimilar/Status.java | 3199 | /**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.frontend.client.widget.findsimilar;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PopupPanel;
import com.openkm.frontend.client.Main;
import com.openkm.frontend.client.util.OKMBundleResources;
/**
* Status
*
* @author jllort
*
*/
public class Status extends PopupPanel {
private HorizontalPanel hPanel;
private HTML msg;
private HTML space;
private Image image;
private boolean flag_getChilds = false;
/**
* Status
*/
public Status() {
super(false,true);
hPanel = new HorizontalPanel();
image = new Image(OKMBundleResources.INSTANCE.indicator());
msg = new HTML("");
space = new HTML("");
hPanel.add(image);
hPanel.add(msg);
hPanel.add(space);
hPanel.setCellVerticalAlignment(image, HasAlignment.ALIGN_MIDDLE);
hPanel.setCellVerticalAlignment(msg, HasAlignment.ALIGN_MIDDLE);
hPanel.setCellHorizontalAlignment(image, HasAlignment.ALIGN_CENTER);
hPanel.setCellWidth(image, "30px");
hPanel.setCellWidth(space, "7px");
hPanel.setHeight("25px");
msg.setStyleName("okm-NoWrap");
super.hide();
setWidget(hPanel);
}
/**
* Refreshing satus
*/
public void refresh() {
if (flag_getChilds ) {
int left = ((Main.get().findSimilarDocumentSelectPopup.getOffsetWidth()-200)/2) +
Main.get().findSimilarDocumentSelectPopup.getAbsoluteLeft();
int top = ((Main.get().findSimilarDocumentSelectPopup.getOffsetHeight()-40)/2) +
Main.get().findSimilarDocumentSelectPopup.getAbsoluteTop();
setPopupPosition(left,top);
Main.get().findSimilarDocumentSelectPopup.scrollDocumentPanel.addStyleName("okm-PanelRefreshing");
super.show();
} else {
super.hide();
Main.get().findSimilarDocumentSelectPopup.scrollDocumentPanel.removeStyleName("okm-PanelRefreshing");
}
}
/**
* Set childs flag
*/
public void setFlagChilds() {
msg.setHTML(Main.i18n("filebrowser.status.refresh.document"));
flag_getChilds = true;
refresh();
}
/**
* Unset childs flag
*/
public void unsetFlagChilds() {
flag_getChilds = false;
refresh();
}
} | gpl-3.0 |
jrialland/parserjunior | old/parser/src/main/java/net/jr/parser/impl/BaseRule.java | 1687 | package net.jr.parser.impl;
import net.jr.common.Symbol;
import net.jr.parser.ParsingContext;
import net.jr.parser.Rule;
import java.util.function.Consumer;
/**
* Base implementation of a grammar {@link Rule}.
*/
public class BaseRule extends Rule {
private Consumer<ParsingContext> action;
private String name;
private String comment;
private Symbol target;
private Symbol[] clause;
private ActionType conflictArbitration;
private int precedenceLevel;
public BaseRule(int id, String name, Symbol target, Symbol... clause) {
setId(id);
this.name = name;
this.target = target;
this.clause = clause;
}
public Consumer<ParsingContext> getAction() {
return action;
}
public void setAction(Consumer<ParsingContext> action) {
this.action = action;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Symbol[] getClause() {
return clause;
}
public Symbol getTarget() {
return target;
}
public Integer getPrecedenceLevel() {
return precedenceLevel;
}
public void setPrecedenceLevel(int precedenceLevel) {
this.precedenceLevel = precedenceLevel;
}
public ActionType getConflictArbitration() {
return conflictArbitration;
}
public void setConflictArbitration(ActionType conflictArbitration) {
this.conflictArbitration = conflictArbitration;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
| gpl-3.0 |
ElMuto/anonbench | src/org/deidentifier/arx/algorithm/AlgorithmFlash.java | 32577 | /*
* ARX: Powerful Data Anonymization
* Copyright (C) 2012 - 2014 Florian Kohlmayer, Fabian Prasser
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.deidentifier.arx.algorithm;
import org.deidentifier.arx.ARXConfiguration.ARXConfigurationInternal;
import org.deidentifier.arx.criteria.PrivacyCriterion;
import org.deidentifier.arx.framework.check.INodeChecker;
import org.deidentifier.arx.framework.check.history.History;
import org.deidentifier.arx.framework.data.GeneralizationHierarchy;
import org.deidentifier.arx.framework.lattice.MaterializedLattice;
import org.deidentifier.arx.framework.lattice.Node;
import org.deidentifier.arx.framework.lattice.NodeAction;
import org.deidentifier.arx.framework.lattice.NodeAction.NodeActionConstant;
import org.deidentifier.arx.framework.lattice.NodeAction.NodeActionInverse;
import org.deidentifier.arx.framework.lattice.NodeAction.NodeActionOR;
import org.deidentifier.arx.metric.Metric;
/**
* This class provides a static method for instantiating the FLASH algorithm.
*
* @author Fabian Prasser
* @author Florian Kohlmayer
*/
public class AlgorithmFlash {
/**
* Monotonicity.
*/
private static enum Monotonicity {
/** TODO */
FULL,
/** TODO */
PARTIAL,
/** TODO */
NONE
}
/**
* Creates a new instance of the FLASH algorithm.
*
* @param lattice
* @param checker
* @param hierarchies
* @return
*/
public static AbstractBenchmarkAlgorithm create(final MaterializedLattice lattice,
final INodeChecker checker,
final GeneralizationHierarchy[] hierarchies) {
// Init
final FLASHStrategy strategy = new FLASHStrategy(lattice, hierarchies);
ARXConfigurationInternal config = checker.getConfiguration();
Metric<?> metric = checker.getMetric();
// NOTE:
// - If we assume practical monotonicity then we assume
// monotonicity for both criterion AND metric
// - Without suppression we assume monotonicity for all criteria
// - Without suppression we assume monotonicity for all metrics
// Determine monotonicity of metric
Monotonicity monotonicityMetric;
if (metric.isMonotonic() || (config.getMaxOutliers() == 0d) || config.isPracticalMonotonicity()) {
monotonicityMetric = Monotonicity.FULL;
} else {
monotonicityMetric = Monotonicity.NONE;
}
// First, determine whether the overall set of criteria is monotonic
Monotonicity monotonicityCriteria = Monotonicity.FULL;
for (PrivacyCriterion criterion : config.getCriteria()) {
if (!(criterion.isMonotonic() || (config.getMaxOutliers() == 0d) || config.isPracticalMonotonicity())) {
if (config.getMinimalGroupSize() != Integer.MAX_VALUE) {
monotonicityCriteria = Monotonicity.PARTIAL;
} else {
monotonicityCriteria = Monotonicity.NONE;
}
break;
}
}
// ******************************
// CASE 1
// ******************************
if ((monotonicityCriteria == Monotonicity.FULL) && (monotonicityMetric == Monotonicity.FULL)) {
return createFullFull(lattice, checker, strategy);
}
// ******************************
// CASE 2
// ******************************
if ((monotonicityCriteria == Monotonicity.FULL) && (monotonicityMetric == Monotonicity.NONE)) {
return createFullNone(lattice, checker, strategy);
}
// ******************************
// CASE 3
// ******************************
if ((monotonicityCriteria == Monotonicity.PARTIAL) && (monotonicityMetric == Monotonicity.FULL)) {
return createPartialFull(lattice, checker, strategy);
}
// ******************************
// CASE 4
// ******************************
if ((monotonicityCriteria == Monotonicity.PARTIAL) && (monotonicityMetric == Monotonicity.NONE)) {
return createPartialNone(lattice, checker, strategy);
}
// ******************************
// CASE 5
// ******************************
if ((monotonicityCriteria == Monotonicity.NONE) && (monotonicityMetric == Monotonicity.FULL)) {
return createNoneFull(lattice, checker, strategy);
}
// ******************************
// CASE 6
// ******************************
if ((monotonicityCriteria == Monotonicity.NONE) && (monotonicityMetric == Monotonicity.NONE)) {
return createNoneNone(lattice, checker, strategy);
}
throw new IllegalStateException("Oops");
}
/**
* Semantics of method name: monotonicity of criteria + monotonicity of metric.
*
* @param lattice
* @param checker
* @param strategy
* @return
*/
private static AbstractBenchmarkAlgorithm createFullFull(final MaterializedLattice lattice,
final INodeChecker checker,
final FLASHStrategy strategy) {
// We focus on the anonymity property
int anonymityProperty = Node.PROPERTY_ANONYMOUS;
// Skip nodes for which the anonymity property is known
NodeAction triggerSkip = new NodeAction() {
@Override
public boolean appliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_NOT_ANONYMOUS);
}
};
// We predictively tag the anonymity property
NodeAction triggerTag = new NodeAction() {
@Override
public void action(Node node) {
if (node.hasProperty(Node.PROPERTY_ANONYMOUS)) {
lattice.setPropertyUpwards(node, false, Node.PROPERTY_ANONYMOUS | Node.PROPERTY_SUCCESSORS_PRUNED);
lattice.setProperty(node, Node.PROPERTY_SUCCESSORS_PRUNED);
} else {
lattice.setPropertyDownwards(node, false, Node.PROPERTY_NOT_ANONYMOUS);
}
}
@Override
public boolean appliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_NOT_ANONYMOUS);
}
};
// No evaluation
NodeAction triggerEvaluate = new NodeActionConstant(false);
NodeAction triggerCheck = new NodeActionInverse(triggerSkip);
NodeAction triggerFireEvent = new NodeActionOR(triggerSkip) {
@Override
protected boolean additionalConditionAppliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_SUCCESSORS_PRUNED);
}
};
// Only one binary phase
// Deactivate pruning due to lower bound as it increases number of checks needed
FLASHConfiguration config = FLASHConfiguration.createBinaryPhaseConfiguration(new FLASHPhaseConfiguration(anonymityProperty,
triggerTag,
triggerCheck,
triggerEvaluate,
triggerSkip),
History.STORAGE_TRIGGER_NON_ANONYMOUS,
triggerFireEvent,
false);
return new FLASHAlgorithmImpl(lattice, checker, strategy, config);
}
/**
* Semantics of method name: monotonicity of criteria + monotonicity of metric.
*
* @param lattice
* @param checker
* @param strategy
* @return
*/
private static AbstractBenchmarkAlgorithm createFullNone(final MaterializedLattice lattice,
final INodeChecker checker,
final FLASHStrategy strategy) {
/* *******************************
* BINARY PHASE
* *******************************
*/
// We focus on the anonymity property
int binaryAnonymityProperty = Node.PROPERTY_ANONYMOUS;
// Skip nodes for which the anonymity property is known
NodeAction binaryTriggerSkip = new NodeAction() {
@Override
public boolean appliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_NOT_ANONYMOUS);
}
};
// We predictively tag the anonymity property
NodeAction binaryTriggerTag = new NodeAction() {
@Override
public void action(Node node) {
if (node.hasProperty(Node.PROPERTY_ANONYMOUS)) {
lattice.setPropertyUpwards(node, false, Node.PROPERTY_ANONYMOUS);
} else {
lattice.setPropertyDownwards(node, false, Node.PROPERTY_NOT_ANONYMOUS);
}
}
@Override
public boolean appliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_NOT_ANONYMOUS);
}
};
// No evaluation
NodeAction binaryTriggerCheck = new NodeActionInverse(binaryTriggerSkip);
NodeAction binaryTriggerEvaluate = new NodeActionConstant(false);
/* *******************************
* LINEAR PHASE
* *******************************
*/
// We focus on the anonymity property
int linearAnonymityProperty = Node.PROPERTY_ANONYMOUS;
// We skip nodes which are not anonymous or which have already been visited during the second phase
NodeAction linearTriggerSkip = new NodeAction() {
@Override
public boolean appliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_NOT_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_VISITED);
}
};
// We evaluate nodes which have not been skipped, if the metric is independent
NodeAction linearTriggerEvaluate = new NodeAction() {
@Override
public boolean appliesTo(Node node) {
return checker.getMetric().isIndependent() &&
!node.hasProperty(Node.PROPERTY_CHECKED) &&
!node.hasProperty(Node.PROPERTY_NOT_ANONYMOUS);
}
};
// We check nodes which have not been skipped, if the metric is dependent
NodeAction linearTriggerCheck = new NodeAction() {
@Override
public boolean appliesTo(Node node) {
return !checker.getMetric().isIndependent() &&
!node.hasProperty(Node.PROPERTY_CHECKED) &&
!node.hasProperty(Node.PROPERTY_NOT_ANONYMOUS);
}
};
// Mark nodes as already visited during the second phase
NodeAction linearTriggerTag = new NodeAction() {
@Override
public void action(Node node) {
lattice.setProperty(node, Node.PROPERTY_VISITED);
}
@Override
public boolean appliesTo(Node node) {
return true;
}
};
// Fire event
NodeAction triggerFireEvent = new NodeActionOR(linearTriggerSkip) {
@Override
protected boolean additionalConditionAppliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_SUCCESSORS_PRUNED);
}
};
// Two interwoven phases
FLASHConfiguration config = FLASHConfiguration.createTwoPhaseConfiguration(new FLASHPhaseConfiguration(binaryAnonymityProperty,
binaryTriggerTag,
binaryTriggerCheck,
binaryTriggerEvaluate,
binaryTriggerSkip),
new FLASHPhaseConfiguration(linearAnonymityProperty,
linearTriggerTag,
linearTriggerCheck,
linearTriggerEvaluate,
linearTriggerSkip),
History.STORAGE_TRIGGER_ALL,
triggerFireEvent,
true);
return new FLASHAlgorithmImpl(lattice, checker, strategy, config);
}
/**
* Semantics of method name: monotonicity of criteria + monotonicity of metric.
*
* @param lattice
* @param checker
* @param strategy
* @return
*/
private static AbstractBenchmarkAlgorithm createNoneFull(final MaterializedLattice lattice,
final INodeChecker checker,
final FLASHStrategy strategy) {
// We focus on the anonymity property
int anonymityProperty = Node.PROPERTY_ANONYMOUS;
// We skip nodes for which the anonymity property is known or which have insufficient utility
NodeAction triggerSkip = new NodeAction() {
@Override
public boolean appliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_NOT_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_INSUFFICIENT_UTILITY);
}
};
// No evaluation
NodeAction triggerEvaluate = new NodeActionConstant(false);
NodeAction triggerCheck = new NodeActionInverse(triggerSkip);
NodeAction triggerFireEvent = new NodeActionOR(triggerSkip) {
@Override
protected boolean additionalConditionAppliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_SUCCESSORS_PRUNED);
}
};
// We predictively tag nodes with insufficient utility because of the monotonic metric
NodeAction triggerTag = new NodeAction() {
@Override
public void action(Node node) {
lattice.setPropertyUpwards(node, false, Node.PROPERTY_INSUFFICIENT_UTILITY | Node.PROPERTY_SUCCESSORS_PRUNED);
lattice.setProperty(node, Node.PROPERTY_SUCCESSORS_PRUNED);
}
@Override
public boolean appliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_ANONYMOUS);
}
};
// Only one linear phase
FLASHConfiguration config = FLASHConfiguration.createLinearPhaseConfiguration(new FLASHPhaseConfiguration(anonymityProperty,
triggerTag,
triggerCheck,
triggerEvaluate,
triggerSkip),
History.STORAGE_TRIGGER_ALL,
triggerFireEvent,
true);
return new FLASHAlgorithmImpl(lattice, checker, strategy, config);
}
/**
* Semantics of method name: monotonicity of criteria + monotonicity of metric.
*
* @param lattice
* @param checker
* @param strategy
* @return
*/
private static AbstractBenchmarkAlgorithm createNoneNone(MaterializedLattice lattice,
INodeChecker checker,
FLASHStrategy strategy) {
// We focus on the anonymity property
int anonymityProperty = Node.PROPERTY_ANONYMOUS;
// Skip nodes for which the anonymity property is known
NodeAction triggerSkip = new NodeAction() {
@Override
public boolean appliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_NOT_ANONYMOUS);
}
};
// No evaluation, no tagging
NodeAction triggerEvaluate = new NodeActionConstant(false);
NodeAction triggerCheck = new NodeActionInverse(triggerSkip);
NodeAction triggerTag = new NodeActionConstant(false);
NodeAction triggerFireEvent = new NodeActionOR(triggerSkip) {
@Override
protected boolean additionalConditionAppliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_SUCCESSORS_PRUNED);
}
};
// Only one linear phase
FLASHConfiguration config = FLASHConfiguration.createLinearPhaseConfiguration(new FLASHPhaseConfiguration(anonymityProperty,
triggerTag,
triggerCheck,
triggerEvaluate,
triggerSkip),
History.STORAGE_TRIGGER_ALL,
triggerFireEvent,
true);
return new FLASHAlgorithmImpl(lattice, checker, strategy, config);
}
/**
* Semantics of method name: monotonicity of criteria + monotonicity of metric.
*
* @param lattice
* @param checker
* @param strategy
* @return
*/
private static AbstractBenchmarkAlgorithm createPartialFull(final MaterializedLattice lattice,
final INodeChecker checker,
final FLASHStrategy strategy) {
/* *******************************
* BINARY PHASE
* *******************************
*/
// We focus on the k-anonymity property
int binaryAnonymityProperty = Node.PROPERTY_K_ANONYMOUS;
// Skip nodes for which the k-anonymity property is known or which have insufficient utility
NodeAction binaryTriggerSkip = new NodeAction() {
@Override
public boolean appliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_K_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_NOT_K_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_INSUFFICIENT_UTILITY);
}
};
// We predictively tag the k-anonymity property and the insufficient utility property
NodeAction binaryTriggerTag = new NodeAction() {
@Override
public void action(Node node) {
// Tag k-anonymity
if (node.hasProperty(Node.PROPERTY_K_ANONYMOUS)) {
lattice.setPropertyUpwards(node, false, Node.PROPERTY_K_ANONYMOUS);
} else {
lattice.setPropertyDownwards(node, false, Node.PROPERTY_NOT_K_ANONYMOUS);
}
// Tag insufficient utility
if (node.hasProperty(Node.PROPERTY_ANONYMOUS)) {
lattice.setPropertyUpwards(node, false, Node.PROPERTY_INSUFFICIENT_UTILITY | Node.PROPERTY_SUCCESSORS_PRUNED);
lattice.setProperty(node, Node.PROPERTY_SUCCESSORS_PRUNED);
}
}
@Override
public boolean appliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_K_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_NOT_K_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_ANONYMOUS);
}
};
// No evaluation
NodeAction binaryTriggerCheck = new NodeActionInverse(binaryTriggerSkip);
NodeAction binaryTriggerEvaluate = new NodeActionConstant(false);
/* *******************************
* LINEAR PHASE
* *******************************
*/
// We focus on the anonymity property
int linearAnonymityProperty = Node.PROPERTY_ANONYMOUS;
// We skip nodes for which the anonymity property is known, which are not k-anonymous,
// or which have insufficient utility
NodeAction linearTriggerSkip = new NodeAction() {
@Override
public boolean appliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_VISITED) ||
node.hasProperty(Node.PROPERTY_NOT_K_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_INSUFFICIENT_UTILITY);
}
};
// No evaluation
NodeAction linearTriggerEvaluate = new NodeActionConstant(false);
// We check nodes which have not been skipped
NodeAction linearTriggerCheck = new NodeAction() {
@Override
public boolean appliesTo(Node node) {
return !node.hasProperty(Node.PROPERTY_VISITED) &&
!node.hasProperty(Node.PROPERTY_NOT_K_ANONYMOUS) &&
!node.hasProperty(Node.PROPERTY_INSUFFICIENT_UTILITY) &&
!node.hasProperty(Node.PROPERTY_CHECKED);
}
};
// We predictively tag the insufficient utility property
NodeAction linearTriggerTag = new NodeAction() {
@Override
public void action(Node node) {
lattice.setProperty(node, Node.PROPERTY_VISITED);
if (node.hasProperty(Node.PROPERTY_ANONYMOUS)) {
lattice.setPropertyUpwards(node, false, Node.PROPERTY_INSUFFICIENT_UTILITY | Node.PROPERTY_SUCCESSORS_PRUNED);
lattice.setProperty(node, Node.PROPERTY_SUCCESSORS_PRUNED);
}
}
@Override
public boolean appliesTo(Node node) {
return true;
}
};
// Fire event
NodeAction triggerFireEvent = new NodeActionOR(linearTriggerSkip) {
@Override
protected boolean additionalConditionAppliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_SUCCESSORS_PRUNED);
}
};
// Two interwoven phases
FLASHConfiguration config = FLASHConfiguration.createTwoPhaseConfiguration(new FLASHPhaseConfiguration(binaryAnonymityProperty,
binaryTriggerTag,
binaryTriggerCheck,
binaryTriggerEvaluate,
binaryTriggerSkip),
new FLASHPhaseConfiguration(linearAnonymityProperty,
linearTriggerTag,
linearTriggerCheck,
linearTriggerEvaluate,
linearTriggerSkip),
History.STORAGE_TRIGGER_ALL,
triggerFireEvent,
true);
return new FLASHAlgorithmImpl(lattice, checker, strategy, config);
}
/**
* Semantics of method name: monotonicity of criteria + monotonicity of metric.
*
* @param lattice
* @param checker
* @param strategy
* @return
*/
private static AbstractBenchmarkAlgorithm createPartialNone(final MaterializedLattice lattice,
final INodeChecker checker,
final FLASHStrategy strategy) {
/* *******************************
* BINARY PHASE
* *******************************
*/
// We focus on the k-anonymity property
int binaryAnonymityProperty = Node.PROPERTY_K_ANONYMOUS;
// Skip nodes for which the k-anonymity property is known
NodeAction binaryTriggerSkip = new NodeAction() {
@Override
public boolean appliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_K_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_NOT_K_ANONYMOUS);
}
};
// We predictively tag the k-anonymity property
NodeAction binaryTriggerTag = new NodeAction() {
@Override
public void action(Node node) {
if (node.hasProperty(Node.PROPERTY_K_ANONYMOUS)) {
lattice.setPropertyUpwards(node, false, Node.PROPERTY_K_ANONYMOUS);
} else {
lattice.setPropertyDownwards(node, false, Node.PROPERTY_NOT_K_ANONYMOUS);
}
}
@Override
public boolean appliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_K_ANONYMOUS) ||
node.hasProperty(Node.PROPERTY_NOT_K_ANONYMOUS);
}
};
// No evaluation
NodeAction binaryTriggerCheck = new NodeActionInverse(binaryTriggerSkip);
NodeAction binaryTriggerEvaluate = new NodeActionConstant(false);
/* *******************************
* LINEAR PHASE
* *******************************
*/
// We focus on the anonymity property
int linearAnonymityProperty = Node.PROPERTY_ANONYMOUS;
// We skip nodes for which are not k-anonymous and which have not been visited yet in the 2nd phase
NodeAction linearTriggerSkip = new NodeAction() {
@Override
public boolean appliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_VISITED) ||
node.hasProperty(Node.PROPERTY_NOT_K_ANONYMOUS);
}
};
// No evaluation
NodeAction linearTriggerEvaluate = new NodeActionConstant(false);
// We check nodes which are k-anonymous and have not been checked already
NodeAction linearTriggerCheck = new NodeAction() {
@Override
public boolean appliesTo(Node node) {
return !node.hasProperty(Node.PROPERTY_CHECKED) &&
!node.hasProperty(Node.PROPERTY_NOT_K_ANONYMOUS);
}
};
// Mark nodes as already visited during the second phase
NodeAction linearTriggerTag = new NodeAction() {
@Override
public void action(Node node) {
lattice.setProperty(node, Node.PROPERTY_VISITED);
}
@Override
public boolean appliesTo(Node node) {
return true;
}
};
// Fire event
NodeAction triggerFireEvent = new NodeActionOR(linearTriggerSkip) {
@Override
protected boolean additionalConditionAppliesTo(Node node) {
return node.hasProperty(Node.PROPERTY_SUCCESSORS_PRUNED);
}
};
// Two interwoven phases
FLASHConfiguration config = FLASHConfiguration.createTwoPhaseConfiguration(new FLASHPhaseConfiguration(binaryAnonymityProperty,
binaryTriggerTag,
binaryTriggerCheck,
binaryTriggerEvaluate,
binaryTriggerSkip),
new FLASHPhaseConfiguration(linearAnonymityProperty,
linearTriggerTag,
linearTriggerCheck,
linearTriggerEvaluate,
linearTriggerSkip),
History.STORAGE_TRIGGER_ALL,
triggerFireEvent,
true);
return new FLASHAlgorithmImpl(lattice, checker, strategy, config);
}
}
| gpl-3.0 |
mrenoch/handy | applet/src/handy/Interaction/RotateBehavior.java | 1293 | /**
* Title: RotateBehavior
* Description:
*
* $Header: /home/users/jonah/cvs/handy/Interaction/RotateBehavior.java,v 1.1 2001/07/22 08:15:05 jonah Exp $
* $Version: $
*/
package Interaction;
import java.awt.*;
import java.awt.event.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import java.util.*;
public class RotateBehavior extends Behavior
implements ActionListener {
private TransformGroup transformGroup;
private Transform3D trans = new Transform3D();
private WakeupCriterion criterion;
private float angle = 0.0f;
// create a new AWTInteractionBehavior
public RotateBehavior(TransformGroup tg) {
transformGroup = tg;
}
// initialize the behavior to wakeup on a behavior post with the id
// MouseEvent.MOUSE_CLICKED
public void initialize() {
criterion = new WakeupOnBehaviorPost(this,
MouseEvent.MOUSE_CLICKED);
wakeupOn(criterion);
}
// processStimulus to rotate the cube
public void processStimulus(Enumeration criteria) {
angle += Math.toRadians(10.0);
trans.rotY(angle);
transformGroup.setTransform(trans);
wakeupOn(criterion);
}
// when the mouse is clicked, postId for the behavior
public void actionPerformed(ActionEvent e) {
postId(MouseEvent.MOUSE_CLICKED);
}
}
| gpl-3.0 |
Fxe/biosynth-framework | biosynth-biodb/src/main/java/pt/uminho/sysbio/biosynthframework/io/AbstractMetaboliteDao.java | 379 | package pt.uminho.sysbio.biosynthframework.io;
import pt.uminho.sysbio.biosynthframework.Metabolite;
public abstract class AbstractMetaboliteDao<M extends Metabolite>
implements MetaboliteDao<M> {
protected final String version;
public AbstractMetaboliteDao(String version) {
this.version = version;
}
public String getVersion() {
return version;
}
}
| gpl-3.0 |
yongs2/mts-project | mts/src/main/java/com/devoteam/srit/xmlloader/sigtran/ap/BN_APMessage.java | 5993 | /*
* Copyright 2012 Devoteam http://www.devoteam.com
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
*
* This file is part of Multi-Protocol Test Suite (MTS).
*
* Multi-Protocol Test Suite (MTS) is free software: you can redistribute
* it and/or modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of the
* License.
*
* Multi-Protocol Test Suite (MTS) is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Multi-Protocol Test Suite (MTS).
* If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.devoteam.srit.xmlloader.sigtran.ap;
import java.util.Collection;
import gp.utils.arrays.Array;
import gp.utils.arrays.DefaultArray;
import org.dom4j.Element;
import com.devoteam.srit.xmlloader.asn1.ASNMessage;
import com.devoteam.srit.xmlloader.asn1.BN_ASNMessage;
import com.devoteam.srit.xmlloader.sigtran.ap.map.Component;
import com.devoteam.srit.xmlloader.sigtran.ap.map.Invoke;
import com.devoteam.srit.xmlloader.sigtran.ap.map.Reject;
import com.devoteam.srit.xmlloader.sigtran.ap.map.ReturnError;
import com.devoteam.srit.xmlloader.sigtran.ap.map.ReturnResult;
/**
*
* @author fhenry
*/
public class BN_APMessage extends BN_ASNMessage
{
public BN_APMessage(ASNMessage tcapMessage)
{
}
public BN_APMessage(String className) throws Exception
{
super(className);
}
public String getClassName()
{
return this.className;
}
public void setClassName(String className)
{
this.className = className;
}
public boolean isRequest()
{
Component apMessage = (Component) asnObject;
if (apMessage.isInvokeSelected())
{
return true;
}
else if (apMessage.isReturnResultLastSelected())
{
return false;
}
else if (apMessage.isRejectSelected())
{
return false;
}
else if (apMessage.isReturnErrorSelected())
{
return false;
}
return false;
}
public String getType()
{
Component apMessage = (Component) asnObject;
if (apMessage.isInvokeSelected())
{
Invoke invoke = apMessage.getInvoke();
return Long.toString(invoke.getOpCode().getLocalValue().getValue());
}
else if (apMessage.isReturnResultLastSelected())
{
ReturnResult returnResult = apMessage.getReturnResultLast();
if (returnResult != null && returnResult.getResultretres() != null)
{
return Long.toString(returnResult.getResultretres().getOpCode().getLocalValue().getValue());
}
else
{
return null;
}
}
else
{
// TO DO use the transaction
return null;
}
}
public String getResult()
{
Component apMessage = (Component) asnObject;
if (apMessage.isInvokeSelected())
{
return null;
}
else if (apMessage.isReturnResultLastSelected())
{
ReturnResult returnResult = apMessage.getReturnResultLast();
return "OK";
}
else if (apMessage.isReturnErrorSelected())
{
ReturnError returnError = apMessage.getReturnError();
if (returnError.getErrorCode() != null)
{
if (returnError.getErrorCode().isGlobalValueSelected())
{
return returnError.getErrorCode().getGlobalValue().getValue();
}
if (returnError.getErrorCode().isLocalValueSelected())
{
return Long.toString(returnError.getErrorCode().getLocalValue().getValue());
}
else
{
return "KO";
}
}
}
else if (apMessage.isRejectSelected())
{
Reject reject = apMessage.getReject();
if (reject.getProblem() != null)
{
if (reject.getProblem().isGeneralProblemSelected())
{
return Long.toString(reject.getProblem().getGeneralProblem().getValue());
}
else if (reject.getProblem().isInvokeProblemSelected())
{
return Long.toString(reject.getProblem().getInvokeProblem().getValue());
}
else if (reject.getProblem().isReturnErrorProblemSelected())
{
return Long.toString(reject.getProblem().getReturnErrorProblem().getValue());
}
else if (reject.getProblem().isReturnResultProblemSelected())
{
return Long.toString(reject.getProblem().getReturnResultProblem().getValue());
}
}
}
return "KO";
}
public String getTransactionId()
{
Component apMessage = (Component) asnObject;
String transId = null;
if (apMessage.isInvokeSelected())
{
transId = String.valueOf(apMessage.getInvoke().getInvokeID().getValue());
}
else if (apMessage.isReturnResultLastSelected())
{
transId = String.valueOf(apMessage.getReturnResultLast().getInvokeID().getValue());
}
else if (apMessage.isRejectSelected())
{
transId = null;
}
else if (apMessage.isReturnErrorSelected())
{
transId = String.valueOf(apMessage.getReturnError().getInvokeID().getValue());
}
return transId;
}
/*
public Collection<Component> getTCAPComponents()
{
if (((TCMessage) asnObject).isBeginSelected())
{
return ((TCMessage) asnObject).getBegin().getComponents().getValue();
}
else if (((TCMessage) asnObject).isEndSelected())
{
return ((TCMessage) asnObject).getEnd().getComponents().getValue();
}
else if (((TCMessage) asnObject).isContinue1Selected())
{
return ((TCMessage) asnObject).getContinue1().getComponents().getValue();
}
else if (((TCMessage) asnObject).isAbortSelected())
{
return null;
}
else if (((TCMessage) asnObject).isUnidirectionalSelected())
{
return ((TCMessage) asnObject).getUnidirectional().getComponents().getValue();
}
return null;
}
*/
} | gpl-3.0 |
nickshoust/HubTrail | src/com/nickshoust/hubtrail/SettingsActivity.java | 3882 | package com.nickshoust.hubtrail;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import com.google.analytics.tracking.android.EasyTracker;
public class SettingsActivity extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
long startTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
@Override
protected void onStart() {
super.onStart();
CheckBox checkBoxEarthView = (CheckBox)findViewById(R.id.checkbox_earthview);
CheckBox checkBoxMyLocation = (CheckBox)findViewById(R.id.checkbox_mylocation);
CheckBox checkBoxAltRoute = (CheckBox)findViewById(R.id.checkbox_altRoute);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
if (settings.contains("earthview")){
checkBoxEarthView.setChecked(settings.getBoolean("earthview", false));
}
if (settings.contains("mylocation")){
checkBoxMyLocation.setChecked(settings.getBoolean("mylocation", true));
}
if (settings.contains("altRoute")){
checkBoxAltRoute.setChecked(settings.getBoolean("altRoute",false));
}
EasyTracker.getInstance(this).activityStart(this);
}
@Override
public void onStop() {
super.onStop();
EasyTracker.getInstance(this).activityStart(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_help) {
Intent intent = new Intent(this, HelpActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_settings,
container, false);
return rootView;
}
}
public void onCheckboxClicked(View view) {
CheckBox checkBoxEarthView = (CheckBox)findViewById(R.id.checkbox_earthview);
CheckBox checkBoxMyLocation = (CheckBox)findViewById(R.id.checkbox_mylocation);
CheckBox checkBoxAltRoute = (CheckBox)findViewById(R.id.checkbox_altRoute);
boolean earthViewChecked = checkBoxEarthView.isChecked();
boolean myLocationChecked = checkBoxMyLocation.isChecked();
boolean altRoute = checkBoxAltRoute.isChecked();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
Editor editor = settings.edit();
if (earthViewChecked){
editor.putBoolean("earthview", true);
} else {
editor.putBoolean("earthview", false);
}
if (myLocationChecked){
editor.putBoolean("mylocation", true);
} else {
editor.putBoolean("mylocation", false);
}
if (altRoute){
editor.putBoolean("altRoute", true);
} else {
editor.putBoolean("altRoute", false);
}
editor.commit();
}
}
| gpl-3.0 |
thevpc/upa | upa-api/src/main/java/net/thevpc/upa/expressions/GreaterThan.java | 2185 | /**
* ====================================================================
* UPA (Unstructured Persistence API)
* Yet another ORM Framework
* ++++++++++++++++++++++++++++++++++
* Unstructured Persistence API, referred to as UPA, is a genuine effort
* to raise programming language frameworks managing relational data in
* applications using Java Platform, Standard Edition and Java Platform,
* Enterprise Edition and Dot Net Framework equally to the next level of
* handling ORM for mutable data structures. UPA is intended to provide
* a solid reflection mechanisms to the mapped data structures while
* affording to make changes at runtime of those data structures.
* Besides, UPA has learned considerably of the leading ORM
* (JPA, Hibernate/NHibernate, MyBatis and Entity Framework to name a few)
* failures to satisfy very common even known to be trivial requirement in
* enterprise applications.
* <p>
* Copyright (C) 2014-2015 Taha BEN SALAH
* <p>
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* <p>
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* <p>
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
* ====================================================================
*/
package net.thevpc.upa.expressions;
public final class GreaterThan extends BinaryOperatorExpression
implements Cloneable {
private static final long serialVersionUID = 1L;
public GreaterThan(Expression left, Object right) {
super(BinaryOperator.GT, left, right);
}
public GreaterThan(Expression left, Expression right) {
super(BinaryOperator.GT, left, right);
}
}
| gpl-3.0 |
axlecho/JtsViewer | app/src/main/java/com/axlecho/jtsviewer/activity/detail/JtsCommentsActivity.java | 15145 | package com.axlecho.jtsviewer.activity.detail;
import android.animation.Animator;
import android.app.ProgressDialog;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import com.afollestad.aesthetic.AestheticActivity;
import com.axlecho.jtsviewer.R;
import com.axlecho.jtsviewer.action.ui.JtsStopVideoAction;
import com.axlecho.jtsviewer.module.JtsTabDetailModule;
import com.axlecho.jtsviewer.module.JtsTabInfoModel;
import com.axlecho.jtsviewer.module.JtsThreadModule;
import com.axlecho.jtsviewer.network.JtsNetworkManager;
import com.axlecho.jtsviewer.network.JtsServer;
import com.axlecho.jtsviewer.untils.JtsConf;
import com.axlecho.jtsviewer.untils.JtsTextUnitls;
import com.axlecho.jtsviewer.untils.JtsToolUnitls;
import com.axlecho.jtsviewer.untils.JtsViewerLog;
import com.axlecho.jtsviewer.widget.RecycleViewDivider;
import com.axlecho.sakura.SakuraPlayerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.hippo.refreshlayout.RefreshLayout;
import com.hippo.yorozuya.AnimationUtils;
import com.hippo.yorozuya.SimpleAnimatorListener;
import java.util.ArrayList;
import java.util.List;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
public class JtsCommentsActivity extends AestheticActivity implements RefreshLayout.OnRefreshListener {
private static final String TAG = "comments-scene";
public RecyclerView recyclerView;
public RefreshLayout refreshLayout;
public EditText comment;
public ImageView send;
public View commentLayout;
public FloatingActionButton replyButton;
private int page = 1;
private JtsThreadListAdapter adapter;
private JtsTabInfoModel info;
private JtsTabDetailModule detail;
private List<Disposable> disposables = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
recyclerView = findViewById(R.id.comment_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL));
refreshLayout = (RefreshLayout) findViewById(R.id.main_swip_refresh_layout);
refreshLayout.setFooterColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
android.R.color.holo_orange_light, android.R.color.holo_red_light);
refreshLayout.setHeaderColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
android.R.color.holo_orange_light, android.R.color.holo_red_light);
refreshLayout.setOnRefreshListener(this);
commentLayout = findViewById(R.id.comment_layout);
send = findViewById(R.id.comment_send);
replyButton = findViewById(R.id.fab);
comment = findViewById(R.id.comment_edittext);
initAction();
loadComments();
}
public void showEditPanelWithAnimation() {
if (null == replyButton || null == commentLayout) {
return;
}
replyButton.setTranslationX(0.0f);
replyButton.setTranslationY(0.0f);
replyButton.setScaleX(1.0f);
replyButton.setScaleY(1.0f);
int fabEndX = commentLayout.getLeft() + (commentLayout.getWidth() / 2) - (replyButton.getWidth() / 2);
int fabEndY = commentLayout.getTop() + (commentLayout.getHeight() / 2) - (replyButton.getHeight() / 2);
replyButton.animate().x(fabEndX).y(fabEndY).scaleX(0.0f).scaleY(0.0f)
.setInterpolator(AnimationUtils.SLOW_FAST_SLOW_INTERPOLATOR)
.setDuration(300L).setListener(new SimpleAnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
if (null == replyButton || null == commentLayout) {
return;
}
replyButton.setVisibility(View.INVISIBLE);
commentLayout.setVisibility(View.VISIBLE);
int halfW = commentLayout.getWidth() / 2;
int halfH = commentLayout.getHeight() / 2;
Animator animator = ViewAnimationUtils.createCircularReveal(commentLayout, halfW, halfH, 0,
(float) Math.hypot(halfW, halfH)).setDuration(300L);
animator.addListener(new SimpleAnimatorListener() {
@Override
public void onAnimationEnd(Animator a) {
}
});
animator.start();
}
}).start();
}
private void hideEditPanelWithAnimation() {
if (null == replyButton || null == commentLayout) {
return;
}
int halfW = commentLayout.getWidth() / 2;
int halfH = commentLayout.getHeight() / 2;
Animator animator = ViewAnimationUtils.createCircularReveal(commentLayout, halfW, halfH,
(float) Math.hypot(halfW, halfH), 0.0f).setDuration(300L);
animator.addListener(new SimpleAnimatorListener() {
@Override
public void onAnimationEnd(Animator a) {
if (null == replyButton || null == commentLayout) {
return;
}
if (Looper.myLooper() != Looper.getMainLooper()) {
// Some devices may run this block in non-UI thread.
// It might be a bug of Android OS.
// Check it here to avoid crash.
return;
}
commentLayout.setVisibility(View.GONE);
((View) replyButton).setVisibility(View.VISIBLE);
int fabStartX = commentLayout.getLeft() + (commentLayout.getWidth() / 2) - (replyButton.getWidth() / 2);
int fabStartY = commentLayout.getTop() + (commentLayout.getHeight() / 2) - (replyButton.getHeight() / 2);
replyButton.setX(fabStartX);
replyButton.setY(fabStartY);
replyButton.setScaleX(0.0f);
replyButton.setScaleY(0.0f);
replyButton.setRotation(-45.0f);
replyButton.animate().translationX(0.0f).translationY(0.0f).scaleX(1.0f).scaleY(1.0f).rotation(0.0f)
.setInterpolator(AnimationUtils.SLOW_FAST_SLOW_INTERPOLATOR)
.setDuration(300L).setListener(new SimpleAnimatorListener() {
@Override
public void onAnimationEnd(Animator animation) {
}
}).start();
}
});
animator.start();
}
public void initAction() {
replyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showEditPanelWithAnimation();
}
});
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendComment();
}
});
}
public void loadComments() {
this.info = (JtsTabInfoModel) getIntent().getSerializableExtra("info");
this.detail = (JtsTabDetailModule) getIntent().getSerializableExtra("detail");
processDetail();
}
@Override
protected void onDestroy() {
quit();
super.onDestroy();
}
@Override
public void onHeaderRefresh() {
refreshLayout.setHeaderRefreshing(false);
}
@Override
public void onFooterRefresh() {
loadMoreThread();
}
public void processDetail() {
if (adapter == null) {
adapter = new JtsThreadListAdapter(this);
this.recyclerView.setAdapter(adapter);
}
adapter.addData(detail.threadList);
adapter.notifyDataSetChanged();
}
public void loadMoreThread() {
page++;
long tabKey = JtsTextUnitls.getTabKeyFromUrl(info.url);
Disposable disposable = JtsServer.getSingleton(this).getThread(tabKey, page)
.doOnSubscribe(new Consumer<Disposable>() {
@Override
public void accept(Disposable disposable) throws Exception {
refreshLayout.setFooterRefreshing(true);
}
})
.doOnTerminate(new Action() {
@Override
public void run() throws Exception {
refreshLayout.setFooterRefreshing(false);
}
})
.subscribe(new Consumer<List<JtsThreadModule>>() {
@Override
public void accept(List<JtsThreadModule> jtsThreadModules) throws Exception {
processLoadMoreThread(jtsThreadModules);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
showMessage(throwable.getMessage());
}
});
disposables.add(disposable);
}
public void sendComment() {
String content = comment.getText().toString();
if (TextUtils.isEmpty(content)) {
JtsToolUnitls.hideSoftInput(this, comment);
return;
}
final ProgressDialog loadingProgressDialog = new ProgressDialog(this);
loadingProgressDialog.setTitle(null);
loadingProgressDialog.setMessage(getResources().getString(R.string.sending_tip));
Disposable disposable = JtsServer.getSingleton(this)
.postComment(detail.fid, JtsTextUnitls.getTabKeyFromUrl(info.url), content, detail.formhash)
.doOnSubscribe(new Consumer<Disposable>() {
@Override
public void accept(Disposable disposable) throws Exception {
loadingProgressDialog.show();
}
})
.doOnTerminate(new Action() {
@Override
public void run() throws Exception {
JtsToolUnitls.hideSoftInput(JtsCommentsActivity.this, comment);
if (null != commentLayout && commentLayout.getVisibility() == View.VISIBLE) {
hideEditPanelWithAnimation();
}
loadingProgressDialog.dismiss();
}
})
.subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
processPostComment(s);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
}
});
disposables.add(disposable);
}
public void processLoadMoreThread(List<JtsThreadModule> threads) {
if (threads == null) {
JtsViewerLog.e(TAG, "[processLoadMoreThread] null");
return;
}
if (threads.size() == 0) {
JtsViewerLog.e(TAG, "[processLoadMoreThread] empty");
return;
}
if (threads.get(0) != null) {
for (JtsThreadModule module : detail.threadList) {
if (module.floor.equals(threads.get(0).floor)) {
JtsViewerLog.w(TAG, "[processLoadMoreThread] over flow");
return;
}
}
}
detail.threadList.addAll(threads);
adapter.notifyDataSetChanged();
}
public void processPostComment(String result) {
JtsToolUnitls.hideSoftInput(this, comment);
if (result.equals(JtsConf.STATUS_SUCCESSED)) {
comment.setText("");
refresh();
showMessage(R.string.comment_success);
} else {
showMessage(R.string.comment_failed);
}
}
public void refresh() {
}
public void showMessage(int resId) {
View rootView = findViewById(R.id.comment_layout);
Snackbar.make(rootView, resId, Snackbar.LENGTH_LONG).show();
}
public void showMessage(String msg) {
View rootView = findViewById(R.id.comment_layout);
Snackbar.make(rootView, msg, Snackbar.LENGTH_LONG).show();
}
public void quit() {
this.stopVideoPlayer();
JtsNetworkManager.getInstance(this).cancelAll();
for (Disposable disposable : disposables) {
if (disposable != null && !disposable.isDisposed()) {
disposable.dispose();
}
}
disposables.clear();
}
private void stopVideoPlayer() {
JtsStopVideoAction action = new JtsStopVideoAction(this);
action.execute();
}
public boolean processBackPressed() {
if (null != commentLayout && commentLayout.getVisibility() == View.VISIBLE) {
hideEditPanelWithAnimation();
return false;
}
SakuraPlayerView player = this.findViewById(R.id.player);
if (player != null) {
if (player.isFullScreen) {
player.toggleFullScreen();
return false;
}
player.stop();
ViewGroup root = this.findViewById(android.R.id.content);
root.removeView(player);
return false;
}
return true;
}
@Override
public void onBackPressed() {
if (this.processBackPressed()) {
super.onBackPressed();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}
| gpl-3.0 |
TheWhiteShadow3/cuina | engine/src/cuina/graphics/transform/Transform3D.java | 5706 | package cuina.graphics.transform;
import static org.lwjgl.opengl.GL11.GL_MODELVIEW;
import static org.lwjgl.opengl.GL11.GL_TEXTURE;
import static org.lwjgl.opengl.GL11.glPopMatrix;
import static org.lwjgl.opengl.GL11.glPushMatrix;
import static org.lwjgl.opengl.GL11.glRotatef;
import static org.lwjgl.opengl.GL11.glScalef;
import static org.lwjgl.opengl.GL11.glTranslatef;
import cuina.graphics.GLCache;
import cuina.util.Vector;
public class Transform3D implements Transformation
{
public final Vector pos = new Vector();
public final Vector origin = new Vector();
public final Vector scale = new Vector(1, 1, 1);
public final Vector angle = new Vector();
public float texX;
public float texY;
public float texAngle;
public float texSX = 1;
public float texSY = 1;
public void clear()
{
clearModelTransformation();
clearTexturTransformation();
}
public void clearModelTransformation()
{
clearPosition();
clearRotation();
clearScale();
}
public void clearTexturTransformation()
{
texX = 0;
texY = 0;
texAngle = 0;
texSX = 1;
texSY = 1;
}
public void clearPosition()
{
pos.set(0, 0, 0);
origin.set(0, 0, 0);
}
public void clearRotation()
{
angle.set(0, 0, 0);
}
public void clearScale()
{
this.scale.set(1, 1, 1);
}
public void setPosition(Vector v)
{
this.pos.set(v);
}
public void setOrigion(Vector v)
{
this.origin.set(v);
}
public void setRotation(Vector v)
{
this.angle.set(v);
}
public void setScale(Vector v)
{
this.scale.set(v);
}
public void setTexturPosition(float x, float y)
{
this.texX = x;
this.texY = y;
}
public void setTexturAngle(float angle)
{
this.texAngle = angle;
}
// public void addPortOffset(int ox, int oy)
// {
// vecX1 -= ox;
// vecY1 -= oy;
// vecX2 -= ox;
// vecY2 -= oy;
// }
// /** Legt einen Port mit dem angegebnen Bildausschnitt fest. */
// public void setPort(Rectangle rect)
// {
// setPort(rect.x, rect.y, rect.width, rect.height);
// }
//
// /** Legt einen Port mit dem angegebnen Bildausschnitt fest. */
// public void setPort(int x, int y, float scaleX, float scaleY)
// {
// this.ox = x;
// this.oy = y;
// this.sx = scaleX;
// this.sy = scaleY;
//// vecX2 = x + width;
//// vecY2 = y + height;
// }
//
// /** Legt einen Port in dem angegebnen Größe fest. */
// public void setPort(int width, int height)
// {
// setPort(0, 0, width, height);
// }
//
// /** Legt einen Port für ein Image fest. */
// public void setPort(Image image)
// {
// setPort(0, 0, image.getWidth(), image.getHeight());
// }
/** Legt einen View über die ganze Textur fest. */
public void setDefaultView()
{
texX = 0;
texY = 0;
texAngle = 0;
texSX = 1;
texSY = 1;
}
/**
* Legt einen View in der angegebenen Größe fest.
*/
public void setView(float x, float y)
{
texX = x;
texY = y;
texSX = 1;
texSY = 1;
}
/**
* Legt einen View in der angegebenen Größe fest.
*/
public void setView(float x, float y, float scaleX, float scaleY)
{
this.texX = x;
this.texY = y;
this.texSX = scaleX;
this.texSY = scaleY;
}
// /**
// * Steckt das Image.
// * @param scaleX
// * @param scaleY
// */
// public void expand(float scaleX, float scaleY, float texScaleX, float texScaleY)
// {
// this.sx = scaleX;
// this.sy = scaleY;
// this.texSX = scaleX / texScaleX;
// this.texSY = scaleY / texScaleY;
// }
// /** Legt einen View für ein Image fest. */
// public void setView(Image image, float zoomX, float zoomY)
// {
// this.texX = image.getX() / (float)image.getTexture().getWidth();
// this.texY = image.getY() / (float)image.getTexture().getHeight();
// this.texSX = zoomX;
// this.texSY = zoomX;
// this.sx = zoomX;
// this.sy = zoomY;
// setView(image.getTexture(), image.getRect());
// Rectangle rect = image.getRect();
// texX1 = rect.x / (float) image.getWidth();
// texY1 = rect.y / (float) image.getHeight();
// texX2 = (rect.x +
// texY2 = (rect.y + rect.height) / (float) image.getHeight();
// }
//
// /** Legt einen View für eine Textur fest. */
// public void setView(Texture texture)
// {
// texX = 0;
// texY = 0;
// texX2 = texture.getImageWidth() / (float) texture.getTextureWidth();
// texY2 = texture.getImageHeight() / (float) texture.getTextureHeight();
// }
// public void setView(Texture texture, Rectangle rect)
// {
// setView(texture, rect.x, rect.y, rect.width, rect.height);
// }
//
// public void setView(Texture texture, int x, int y, int width, int height)
// {
// texX1 = x / (float) texture.getTextureWidth();
// texY1 = y / (float) texture.getTextureHeight();
// texX2 = (x + width) / (float) texture.getTextureWidth();
// texY2 = (y + height) / (float) texture.getTextureHeight();
// }
float funnyCounter = 0;
@Override
public void pushTransformation()
{
GLCache.setMatrix(GL_MODELVIEW);
glPushMatrix();
if (pos.x != 1 || pos.y != 1 || pos.z != 1) glTranslatef(pos.x, pos.y, pos.z);
if (angle.x != 0) glRotatef(angle.x, 1, 0, 0);
if (angle.y != 0) glRotatef(angle.y, 0, 1, 0);
if (angle.z != 0) glRotatef(angle.z, 0, 0, 1);
if (origin.x != 1 || origin.y != 1 || origin.z != 1) glTranslatef(origin.x, origin.y, origin.z);
if (scale.x != 1 || scale.y != 1 || scale.z != 1) glScalef(scale.x, scale.y, scale.z);
GLCache.setMatrix(GL_TEXTURE);
glPushMatrix();
if (texX != 0 || texY != 0) glTranslatef(texX, texY, 0);
if (texAngle != 0) glRotatef(texAngle, 0, 0, 1);
if (texSX != 1 || texSY != 1) glScalef(texSX, texSY, 1);
}
@Override
public void popTransformation()
{
GLCache.setMatrix(GL_TEXTURE);
glPopMatrix();
GLCache.setMatrix(GL_MODELVIEW);
glPopMatrix();
}
} | gpl-3.0 |
active-citizen/android.java | app/src/main/java/ru/mos/polls/survey/hearing/controller/PguUIController.java | 6149 | package ru.mos.polls.survey.hearing.controller;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import me.ilich.juggler.change.Add;
import ru.mos.polls.R;
import ru.mos.polls.base.activity.BaseActivity;
import ru.mos.polls.helpers.FunctionalHelper;
import ru.mos.polls.profile.state.PguAuthState;
import ru.mos.polls.profile.vm.PguAuthFragmentVM;
public abstract class PguUIController {
public static void showHearingSubscribe(final BaseActivity elkActivity, String title, final long hearingId, final long meetingId) {
AlertDialog.Builder builder = new AlertDialog.Builder(elkActivity);
builder.setMessage(R.string.subscribe_hearng_text);
builder.setPositiveButton(elkActivity.getString(R.string.subscribe_confirm), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
hearingSubscribe(elkActivity, hearingId, meetingId);
}
});
builder.setNegativeButton(elkActivity.getString(R.string.cancel), null);
builder.show();
}
public static void showSimpleDialog(Context context, String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
if (!TextUtils.isEmpty(title)) {
builder.setTitle(title);
}
builder.setMessage(message)
.setPositiveButton(context.getString(R.string.close), null)
.show();
}
public static void showBindToPGUDialog(final BaseActivity context, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setPositiveButton(context.getString(R.string.ag_continue), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// PguVerifyActivity.startActivity(context);
context.navigateTo().state(Add.newActivityForResult(new PguAuthState(PguAuthState.PGU_AUTH), BaseActivity.class, PguAuthFragmentVM.CODE_PGU_AUTH));
}
});
builder.setNegativeButton(context.getString(R.string.cancel), null);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
public static void showBindToPGUDialogForInvalidFields(final BaseActivity context, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(context, R.style.StackedAlertDialogStyle);
}
builder.setNeutralButton(context.getString(R.string.go_to_pgu), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
FunctionalHelper.startBrowser(context, R.string.pgu_link_value);
}
});
builder.setMessage(message);
builder.setPositiveButton(context.getString(R.string.cancel), null);
builder.setNegativeButton(R.string.title_nind_other_profile_pgu, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// PguVerifyActivity.startActivity(context);
context.navigateTo().state(Add.newActivityForResult(new PguAuthState(PguAuthState.PGU_AUTH), BaseActivity.class, PguAuthFragmentVM.CODE_PGU_AUTH));
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
final Button button = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
LinearLayout linearLayout = (LinearLayout) button.getParent();
linearLayout.setOrientation(LinearLayout.VERTICAL);
} catch (Exception ignored) {
}
}
}
public static void hearingSubscribe(final BaseActivity elkActivity, long hearingId, long meetingId) {
HearingApiControllerRX.HearingCheckListener listener = new HearingApiControllerRX.HearingCheckListener() {
@Override
public void onSuccess(String title, String message) {
showSimpleDialog(elkActivity, title, message);
}
@Override
public void onPguAuthError(int code, String message) {
hearingErrorProcess(elkActivity, code, message);
}
@Override
public void onError(String message) {
showSimpleDialog(elkActivity, null, message);
}
};
HearingApiControllerRX.hearingCheck(elkActivity.getDisposables(), hearingId, meetingId, listener);
}
public static void hearingErrorProcess(final BaseActivity elkActivity, int code, String message) {
switch (code) {
case HearingApiControllerRX.ERROR_SESSION_EXPIRED:
case HearingApiControllerRX.ERROR_PGU_NOT_ATTACHED:
case HearingApiControllerRX.ERROR_CODE_NO_MASTER_SSO_ID:
case HearingApiControllerRX.ERROR_PGU_SESSION_EXPIRED:
case HearingApiControllerRX.ERROR_PGU_FLAT_NOT_VALID:
showBindToPGUDialog(elkActivity, message);
break;
case HearingApiControllerRX.ERROR_FIELDS_ARE_EMPTY:
case HearingApiControllerRX.ERROR_PGU_FLAT_NOT_MATCH:
case HearingApiControllerRX.ERROR_AG_FLAT_NOT_MATCH:
case HearingApiControllerRX.ERROR_PGU_USER_DATA:
showBindToPGUDialogForInvalidFields(elkActivity, message);
break;
default:
Toast.makeText(elkActivity, message, Toast.LENGTH_SHORT).show();
break;
}
}
}
| gpl-3.0 |
Kivitoe/HEXlator | src/2.1/mo.java | 4279 | import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import shc.ide;
import shc.ohc;
import tm.tstart;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JSeparator;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Toolkit;
public class mo extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mo frame = new mo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public mo() {
setIconImage(Toolkit.getDefaultToolkit().getImage(mo.class.getResource("/imgs/color_picker.png")));
setResizable(false);
setTitle("Hexlator");
setSize(441, 365);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JButton btnTutorial = new JButton("Tutorial Mode");
btnTutorial.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
Main.frmHexlator.setVisible(false);
tstart.main(null);
}
});
JSeparator separator = new JSeparator();
JLabel lblMoreOptionsView = new JLabel("More Options View");
lblMoreOptionsView.setFont(new Font("Tahoma", Font.BOLD, 17));
lblMoreOptionsView.setIcon(new ImageIcon(mo.class.getResource("/javax/swing/plaf/metal/icons/ocean/info.png")));
JButton btnSaveAHex = new JButton("Save a HEX Code");
btnSaveAHex.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ide.main(null);
}
});
JButton btnOpenHexCode = new JButton("Open HEX Code");
btnOpenHexCode.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ohc.main(null);
}
});
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
.addComponent(lblMoreOptionsView)
.addGap(109))
.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
.addComponent(separator, GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
.addContainerGap())
.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
.addComponent(btnOpenHexCode, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
.addComponent(btnSaveAHex, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
.addComponent(btnTutorial, GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE))
.addContainerGap())))
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(lblMoreOptionsView, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnTutorial, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnSaveAHex, GroupLayout.PREFERRED_SIZE, 35, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnOpenHexCode, GroupLayout.PREFERRED_SIZE, 34, GroupLayout.PREFERRED_SIZE)
.addContainerGap(158, Short.MAX_VALUE))
);
contentPane.setLayout(gl_contentPane);
}
}
| gpl-3.0 |
OpenRubiconProject/rrpg-core | src/com/openrubicon/core/rarity/Bronze.java | 457 | package com.openrubicon.core.rarity;
public class Bronze extends Rarity {
public Bronze() {
super();
this.rarity = 4;
this.grade = 2;
this.costModifier = 4.0f;
this.color = "&e";
this.name = "Bronze";
this.description = "A fusion of copper and tin makes Bronze the first of the mid grade materials. Bronze is still fairly easy to get, and the attribute points really start to add up.";
}
}
| gpl-3.0 |
mikesligo/visGrid | ie.tcd.gmf.visGrid.diagram/src/visGrid/diagram/sheet/VisGridSheetLabelProvider.java | 2116 | package visGrid.diagram.sheet;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.viewers.BaseLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.graphics.Image;
/**
* @generated
*/
public class VisGridSheetLabelProvider extends BaseLabelProvider implements
ILabelProvider {
/**
* @generated
*/
public String getText(Object element) {
element = unwrap(element);
if (element instanceof visGrid.diagram.navigator.VisGridNavigatorGroup) {
return ((visGrid.diagram.navigator.VisGridNavigatorGroup) element)
.getGroupName();
}
IElementType etype = getElementType(getView(element));
return etype == null ? "" : etype.getDisplayName();
}
/**
* @generated
*/
public Image getImage(Object element) {
IElementType etype = getElementType(getView(unwrap(element)));
return etype == null ? null
: visGrid.diagram.providers.VisGridElementTypes.getImage(etype);
}
/**
* @generated
*/
private Object unwrap(Object element) {
if (element instanceof IStructuredSelection) {
return ((IStructuredSelection) element).getFirstElement();
}
return element;
}
/**
* @generated
*/
private View getView(Object element) {
if (element instanceof View) {
return (View) element;
}
if (element instanceof IAdaptable) {
return (View) ((IAdaptable) element).getAdapter(View.class);
}
return null;
}
/**
* @generated
*/
private IElementType getElementType(View view) {
// For intermediate views climb up the containment hierarchy to find the one associated with an element type.
while (view != null) {
int vid = visGrid.diagram.part.VisGridVisualIDRegistry
.getVisualID(view);
IElementType etype = visGrid.diagram.providers.VisGridElementTypes
.getElementType(vid);
if (etype != null) {
return etype;
}
view = view.eContainer() instanceof View ? (View) view.eContainer()
: null;
}
return null;
}
}
| gpl-3.0 |
Cride5/jablus | src/uk/co/crider/jablus/agent/starter/InitialisePlan.java | 2263 | package uk.co.crider.jablus.agent.starter;
import uk.co.crider.jablus.SimulationManager;
import jadex.runtime.Plan;
/** Initialises this starter agent, by supplying the SimulationManager with a callback object */
public class InitialisePlan extends Plan {
/** Unique class ID */
private static final long serialVersionUID = 576288899040405238L;
//private AgentIdentifier id;
//private int simId;
//public String exptFile;
/** Create a new plan. */
public InitialisePlan() {
// this.id = (AgentIdentifier)getBeliefbase().getBelief("id").getFact();
// this.simId = ((Integer)getBeliefbase().getBelief("sim_id").getFact()).intValue();
// this.exptFile = (String)getBeliefbase().getBelief("expt_file").getFact();
}
/** Plan content */
public void body() {
//System.out.println("InitialisePlan: " + id);
SimulationManager.setStarterRef(this.getExternalAccess());
/*final int simId = Simulation.startSimulation(exptFile);
Hashtable<String, Object> args = new Hashtable<String, Object>();
args.put("starter_id", id);
args.put("sim_id", simId);
StartAgentInfo info = new StartAgentInfo("jablus/agent/sim/Simulation.agent.xml", "Simulation_" + simId, 0, args);
IGoal start = getExternalAccess().getGoalbase().createGoal("start_agents");
start.getParameterSet("agentinfos").addValue(info);
getExternalAccess().getGoalbase().dispatchTopLevelGoal(start);
*/
//Create internal event to await simulation start request
//final IInternalEvent event = createInternalEvent("await_start_event");
//dispatchInternalEvent(event);
/* SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Start simulation
final int simId = SimulationManager.startSimulation(exptFile);
Hashtable<String, Object> args = new Hashtable<String, Object>();
args.put("starter_id", id);
args.put("sim_id", simId);
StartAgentInfo info = new StartAgentInfo("jablus/agent/sim/Simulation.agent.xml", "Simulation_" + simId, 0, args);
IGoal start = getExternalAccess().getGoalbase().createGoal("start_agents");
start.getParameterSet("agentinfos").addValue(info);
getExternalAccess().getGoalbase().dispatchTopLevelGoal(start);
}
});
*/
}
}
| gpl-3.0 |
highsad/iDesktop-Cross | Core/src/com/supermap/desktop/core/DictionaryServiceImpl.java | 668 | package com.supermap.desktop.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class DictionaryServiceImpl implements DictionaryService {
private List fDictionaries = new ArrayList();
public void registerDictionary(Dictionary dictionary) {
fDictionaries.add(dictionary);
}
public void unregisterDictionary(Dictionary dictionary) {
fDictionaries.remove(dictionary);
}
public boolean check(String word) {
for (int i = 0; i < fDictionaries.size(); i++ ) {
Dictionary dictionary = (Dictionary) fDictionaries.get(i);
if(dictionary.check(word))
return true;
}
return false;
}
}
| gpl-3.0 |
cabralje/niem-tools | niemtools-bouml/src/fr/bouml/UmlArtifact.java | 1775 | package fr.bouml;
import java.io.*;
/**
* This class manages 'artifacts'
*
* You can modify it as you want (except the constructor)
*/
class UmlArtifact extends UmlBaseArtifact {
public UmlArtifact(long id, String n){ super(id, n); }
/**
* entry to produce the html code receiving chapter number
* path, rank in the mother and level in the browser tree
*/
public void html(String pfix, int rank, int level) throws IOException {
UmlCom.message(name());
html("Artifact", associatedDiagram());
UmlItem[] l;
if (stereotype().equals("source")) {
fw.write("<p>Artifact <i>source</i>");
l = associatedElements();
}
else if (stereotype().equals("database")) {
fw.write("<p>Artifact <i>database</i>");
l = associatedElements();
}
else {
fw.write("<p><i>");
writeq(stereotype());
fw.write("</i>");
l = associatedArtifacts();
}
String sep = " associated with : ";
for (int i = 0; i != l.length; i += 1) {
fw.write(sep);
l[i].write();
sep = ", ";
}
fw.write("</p>\n");
UmlItem[] ch = children();
if (ch.length != 0) {
String spfix = (rank == 0)
? ""
: (pfix + String.valueOf(rank) + ".");
level += 1;
rank = 1;
fw.write("<div class=\"sub\">\n");
for (int i = 0; i != ch.length; i += 1) {
if (ch[i].kind() == anItemKind.anExtraArtifactDefinition) {
ch[i].html(spfix, rank, level);
if (ch[i].chapterp())
rank += 1;
}
}
fw.write("</div>\n");
}
unload(false, false);
}
/**
* returns a string indicating the king of the element
*/
public String sKind() {
return "artifact";
}
};
| gpl-3.0 |
bradajewski/PZUkalkulator | src/main/java/com/bradajewski/pzukalkulator/Month.java | 10353 | package com.bradajewski.pzukalkulator;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.*;
import java.time.*;
import java.util.*;
/**
* Klasa reprezentująca podstawową jednostkę danych programu {@code PZUkalkulator}.
* Obiekty klasy Month przechowują dane o wynikach pracownika w danym miesiącu
* i pozwalają na wykonywanie obliczeń koniecznych do określenia poziomu realizacji celów.
*
* @author Bogumił Radajewski
* @version 1.0
*/
public final class Month {
//Lista dni miesiąca w postaci obiektów klasy Day
private List<Day> days;
//Mapa zdefiniowanych celów w postaci par nazwa_celu : wartość_celu
private Map<String, Integer> goals;
//Liczba godzin pracujących
public static final int WORK_HOURS = 8;
/**
* Konstruktor domyślny. Tworzy obiekt {@code Month} na podstawie roku i miesiąca
* podanych jako kolejne argumenty i wypełnia go obiektami klasy {@code Day}.
*
* @param y rok
* @param m miesiąc
*/
public Month(int y, int m) {
this();
for (int i = 1; i <= LocalDate.of(y, m, 1).lengthOfMonth(); i++) {
days.add(new Day(y, m, i));
}
}
/**
* Konstruktor tworzący pusty obiekt
*/
public Month() {
days = new ArrayList<>();
goals = new LinkedHashMap<>();
}
/**
* Konstruktor kopiujący
* @param other obiekt do skopiowania
*/
public Month(Month other) {
this();
other.days.forEach(d -> this.days.add(new Day(d)));
this.goals.putAll(other.goals);
}
/**
* Zwraca widok na listę dni miesiąca
* @return {@code List<Day>} - lista dni
*/
public List<Day> getDays() {
return days;
}
/**
* Zwraca widok na mapę celów miesiąca
* @return {@code Map<String, Integer>} - cele
*/
public Map<String, Integer> getGoals() {
return goals;
}
/**
* Zwraca sumę procesów ze wszystkich obiektów na liście {@code days}
* @return int - suma procesów
*/
public int sumDone() {
return days.stream()
.mapToInt(Day::getDone)
.sum();
}
/**
* Oblicza z listy {@code days} czas kwalifikujących się do tzw. czasu odliczonego.
* Zwraca wynik jako ułamek całego dnia roboczego.
* @return double - czas odliczony
*/
public double countOff() {
int sum = days.stream()
.mapToInt(Day::getOff)
.sum();
return (double) sum/60/WORK_HOURS;
}
/**
* Zwraca liczbę dni pracujących na liście {@code days}.
* @return int - liczba dni pracujących
*/
private int workingDays() {
return (int) days.stream()
.filter(Day::isWorking)
.count();
}
/**
* Zwraca liczbę dni urlopu na liście {@code days}.
* @return int - liczba dni urlopu
*/
private int vacationDays() {
return (int) days.stream()
.filter(Day::isVacation)
.count();
}
/**
* Zwraca liczbę dni na liście {@code days}, które już zostały przepracowane.
* @return int - liczba dni przepracowanych
*/
private int completedDays() {
return (int) days.stream()
.filter(Day::isCompleted)
.count();
}
/**
* Zwraca liczbę dni pracujących na liście {@code days}, które jeszcze nie
* zostały przepracowane.
* @return int - liczba pozostałych dni pracujących
*/
private int countDaysLeft() {
return workingDays() - completedDays() - vacationDays();
}
/**
* Zwraca średnią dzienną liczbę wykonanych procesów
* @return double - średnia z dni przepracowanych
*/
public double countAverage() {
OptionalDouble result = days.stream()
.filter(Day::isCompleted)
.mapToInt(Day::getDone)
.average();
return result.orElse(0);
}
/**
* Zwraca liczbę procesów doliczonych do końcowego wyniku w miesiącu
* za dni urlopu i odliczony czas pracy
*
* @return double - procesy doliczone
*/
public double countAdditional() {
double average = countAverage();
return (average * countOff()) + (average * vacationDays());
}
/**
* Oblicza oststeczny wynik w miesiącu po uwzględnieniu wszystkich doliczeń
*
* @return double - wynik końcowy
*/
public double countAllDone() {
return sumDone() + countAdditional();
}
/**
* Zwraca procent realizacji danego celu
* @param target wartość celu (np. 850)
* @return double - procent realizacji celu
*/
public double countPercentFor(int target) {
return (target > 0) ? ((countAllDone() / target) * 100) : 0;
}
/**
* Zwraca liczbę procesów pozostałą do osiągnięcia danego celu
* @param target wartość celu (np. 850)
* @return double brakujące procesy
*/
public double countLeftTo(int target) {
double result = (target - countAllDone());
return (result > 0) ? result : 0;
}
/**
* Zwraca średnią, jaką trzeba osiągnąć w pozostałych dniach pracujcych aby
* zrealizować dany cel premiowy
* @param target wartość celu
* @return double - średnia dzienna potrzebna do osiągnięcia celu
*/
public double countAverageLeftTo(int target) {
int left = countDaysLeft();
return (left > 0) ? (countLeftTo(target)/left) : 0;
}
/**
* Zapisuje serializowaną postać obiektu do wskazanego pliku
* @param fName plik docelowy
* @throws IOException przy błędzie zapisu
*/
public void saveToFile(Path fName) throws IOException {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fName.toFile()))) {
out.writeObject(this.days);
out.writeObject(this.goals);
}
}
/**
* Odtwarza obiekt z serializowanej postaci zapisanej w pliku
* @param fName plik źródłowy
* @return obiekt po deserializacji
* @throws ClassNotFoundException - w przzypadku błędu serializacji
* @throws IOException - w przypadku błędu w dostępie do pliku
*/
public static Month readFromFile(Path fName) throws ClassNotFoundException, IOException {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(fName.toFile()))) {
Month result = new Month();
result.days = (List<Day>) in.readObject();
result.goals = (Map<String, Integer>) in.readObject();
return result;
}
}
/**
* Zwraca tekstową reprezetację obiektu w postaci:
* <p>1990 STYCZEŃ<br>
* 1990-01-01 pracujący: TAK/NIE chorobowe: TAK/NIE urlop TAK/NIE odliczenia: 0 procesy: 0<br>
* 1990-01-02 pracujący: TAK/NIE chorobowe: TAK/NIE urlop TAK/NIE odliczenia: 0 procesy: 0<br>
* ...<br>
* 1990-01-31 pracujący: TAK/NIE chorobowe: TAK/NIE urlop TAK/NIE odliczenia: 0 procesy: 0</p>
*
* @return
*/
@Override
public String toString() {
StringBuilder result = new StringBuilder();
LocalDate date = days.get(0).getDate();
result.append(date.getYear())
.append(" ")
.append(date.getMonth())
.append(System.getProperty("line.separator"));
days.forEach((d) -> {
result.append(d.toString())
.append(System.getProperty("line.separator"));
});
return result.toString();
}
@Override
public int hashCode() {
int hash = 17;
if (days != null) {
for (Day d : this.days) {
hash = 31 * hash + d.hashCode();
}
}
if (goals != null) {
for (Map.Entry<String, Integer> g : this.goals.entrySet()) {
hash = 31 * hash + g.getKey().hashCode();
hash = 31 * hash + g.getValue();
}
}
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Month)) {
return false;
}
final Month other = (Month) obj;
if (days != null && other.days != null) {
if (days.size() != other.getDays().size()) return false;
else {
for (int i = 0; i < days.size(); i++) {
if (!Objects.equals(days.get(i), other.getDays().get(i))) return false;
}
}
} else {
if (days == null && other.days != null) return false;
if (days != null && other.days == null) return false;
}
if (goals != null && other.goals != null) {
final Set<String> thisKeySet = goals.keySet();
final Set<String> otherKeySet = other.getGoals().keySet();
if (thisKeySet.size() != otherKeySet.size()) return false;
else {
for (String key : thisKeySet) {
if (!otherKeySet.contains(key)) return false;
else {
if (!Objects.equals(goals.get(key), other.getGoals().get(key))) return false;
}
}
}
} else {
if (goals == null && other.goals != null) return false;
if (goals != null && other.goals == null) return false;
}
return true;
}
}
| gpl-3.0 |
FedericoPecora/coordination_oru | src/main/java/se/oru/coordination/coordination_oru/tests/TestTrajectoryEnvelopeCoordinatorWithMotionPlanner3.java | 8473 | package se.oru.coordination.coordination_oru.tests;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Random;
import org.metacsp.multi.spatioTemporal.paths.Pose;
import org.metacsp.multi.spatioTemporal.paths.PoseSteering;
import org.metacsp.multi.spatioTemporal.paths.TrajectoryEnvelope;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import se.oru.coordination.coordination_oru.ConstantAccelerationForwardModel;
import se.oru.coordination.coordination_oru.CriticalSection;
import se.oru.coordination.coordination_oru.Mission;
import se.oru.coordination.coordination_oru.RobotAtCriticalSection;
import se.oru.coordination.coordination_oru.RobotReport;
import se.oru.coordination.coordination_oru.demo.DemoDescription;
import se.oru.coordination.coordination_oru.motionplanning.ompl.ReedsSheppCarPlanner;
import se.oru.coordination.coordination_oru.simulation2D.TrajectoryEnvelopeCoordinatorSimulation;
import se.oru.coordination.coordination_oru.util.JTSDrawingPanelVisualization;
import se.oru.coordination.coordination_oru.util.Missions;
@DemoDescription(desc = "Coordination of 2 robots along wave-like paths obtained with the ReedsSheppCarPlanner in opposing directions.")
public class TestTrajectoryEnvelopeCoordinatorWithMotionPlanner3 {
public static void main(String[] args) throws InterruptedException {
double MAX_ACCEL = 1.0;
double MAX_VEL = 4.0;
//Instantiate a trajectory envelope coordinator.
//The TrajectoryEnvelopeCoordinatorSimulation implementation provides
// -- the factory method getNewTracker() which returns a trajectory envelope tracker
// -- the getCurrentTimeInMillis() method, which is used by the coordinator to keep time
//You still need to add one or more comparators to determine robot orderings thru critical sections (comparators are evaluated in the order in which they are added)
final TrajectoryEnvelopeCoordinatorSimulation tec = new TrajectoryEnvelopeCoordinatorSimulation(MAX_VEL,MAX_ACCEL);
tec.addComparator(new Comparator<RobotAtCriticalSection> () {
@Override
public int compare(RobotAtCriticalSection o1, RobotAtCriticalSection o2) {
CriticalSection cs = o1.getCriticalSection();
RobotReport robotReport1 = o1.getRobotReport();
RobotReport robotReport2 = o2.getRobotReport();
return ((cs.getTe1Start()-robotReport1.getPathIndex())-(cs.getTe2Start()-robotReport2.getPathIndex()));
}
});
tec.addComparator(new Comparator<RobotAtCriticalSection> () {
@Override
public int compare(RobotAtCriticalSection o1, RobotAtCriticalSection o2) {
return (o2.getRobotReport().getRobotID()-o1.getRobotReport().getRobotID());
}
});
//You probably also want to provide a non-trivial forward model
//(the default assumes that robots can always stop)
tec.setForwardModel(1, new ConstantAccelerationForwardModel(MAX_ACCEL, MAX_VEL, tec.getTemporalResolution(), tec.getControlPeriod(), tec.getRobotTrackingPeriodInMillis(1)));
tec.setForwardModel(2, new ConstantAccelerationForwardModel(MAX_ACCEL, MAX_VEL, tec.getTemporalResolution(), tec.getControlPeriod(), tec.getRobotTrackingPeriodInMillis(2)));
Coordinate footprint1 = new Coordinate(-1.0,0.5);
Coordinate footprint2 = new Coordinate(1.0,0.5);
Coordinate footprint3 = new Coordinate(1.0,-0.5);
Coordinate footprint4 = new Coordinate(-1.0,-0.5);
tec.setDefaultFootprint(footprint1, footprint2, footprint3, footprint4);
//Need to setup infrastructure that maintains the representation
tec.setupSolver(0, 100000000);
//Start the thread that checks and enforces dependencies at every clock tick
tec.startInference();
//Setup a simple GUI (null means empty map, otherwise provide yaml file)
String yamlFile = "maps/map-empty.yaml";
JTSDrawingPanelVisualization viz = new JTSDrawingPanelVisualization(yamlFile);
tec.setVisualization(viz);
tec.setUseInternalCriticalPoints(false);
//MetaCSPLogging.setLevel(tec.getClass().getSuperclass(), Level.FINEST);
//Instantiate a simple motion planner
ReedsSheppCarPlanner rsp = new ReedsSheppCarPlanner();
rsp.setMap(yamlFile);
rsp.setRadius(0.2);
rsp.setFootprint(footprint1, footprint2, footprint3, footprint4);
rsp.setTurningRadius(4.0);
rsp.setDistanceBetweenPathPoints(0.5);
ArrayList<Pose> posesRobot1 = new ArrayList<Pose>();
posesRobot1.add(new Pose(2.0,10.0,0.0));
posesRobot1.add(new Pose(10.0,13.0,0.0));
posesRobot1.add(new Pose(18.0,10.0,0.0));
posesRobot1.add(new Pose(26.0,13.0,0.0));
posesRobot1.add(new Pose(34.0,10.0,0.0));
posesRobot1.add(new Pose(42.0,13.0,0.0));
posesRobot1.add(new Pose(50.0,10.0,0.0));
ArrayList<Pose> posesRobot2 = new ArrayList<Pose>();
//Robot 1 and robot 2 in opposing directions
posesRobot2.add(new Pose(50.0,13.0,Math.PI));
posesRobot2.add(new Pose(42.0,10.0,Math.PI));
posesRobot2.add(new Pose(34.0,13.0,Math.PI));
posesRobot2.add(new Pose(26.0,10.0,Math.PI));
posesRobot2.add(new Pose(18.0,13.0,Math.PI));
posesRobot2.add(new Pose(10.0,10.0,Math.PI));
posesRobot2.add(new Pose(2.0,13.0,Math.PI));
// //Robot 1 and Robot 2 in same direction
// posesRobot2.add(new Pose(2.0,13.0,0.0));
// posesRobot2.add(new Pose(10.0,10.0,0.0));
// posesRobot2.add(new Pose(18.0,13.0,0.0));
// posesRobot2.add(new Pose(26.0,10.0,0.0));
// posesRobot2.add(new Pose(34.0,13.0,0.0));
// posesRobot2.add(new Pose(42.0,10.0,0.0));
// posesRobot2.add(new Pose(50.0,13.0,0.0));
//Place robots in their initial locations (looked up in the data file that was loaded above)
// -- creates a trajectory envelope for each location, representing the fact that the robot is parked
// -- each trajectory envelope has a path of one pose (the pose of the location)
// -- each trajectory envelope is the footprint of the corresponding robot in that pose
tec.placeRobot(1, posesRobot1.get(0));
tec.placeRobot(2, posesRobot2.get(0));
rsp.setStart(posesRobot1.get(0));
rsp.setGoals(posesRobot1.subList(1, posesRobot1.size()).toArray(new Pose[posesRobot1.size()-1]));
rsp.clearObstacles();
Geometry fpGeom = TrajectoryEnvelope.createFootprintPolygon(footprint1, footprint2, footprint3, footprint4);
rsp.addObstacles(fpGeom, posesRobot2.get(0), posesRobot2.get(posesRobot2.size()-1));
if (!rsp.plan()) throw new Error ("No path along goals " + posesRobot1);
PoseSteering[] robot1path = rsp.getPath();
PoseSteering[] robot1pathInv = rsp.getPathInv();
rsp.setStart(posesRobot2.get(0));
rsp.setGoals(posesRobot2.subList(1, posesRobot2.size()).toArray(new Pose[posesRobot2.size()-1]));
rsp.clearObstacles();
rsp.addObstacles(fpGeom, posesRobot1.get(0), posesRobot1.get(posesRobot1.size()-1));
if (!rsp.plan()) throw new Error ("No path along goals " + posesRobot2);
PoseSteering[] robot2path = rsp.getPath();
PoseSteering[] robot2pathInv = rsp.getPathInv();
Missions.enqueueMission(new Mission(1, robot1path));
Missions.enqueueMission(new Mission(1, robot1pathInv));
Missions.enqueueMission(new Mission(2, robot2path));
Missions.enqueueMission(new Mission(2, robot2pathInv));
System.out.println("Added missions " + Missions.getMissions());
final Random rand = new Random(Calendar.getInstance().getTimeInMillis());
final int minDelay = 500;
final int maxDelay = 3000;
//Start a mission dispatching thread for each robot, which will run forever
for (int i = 1; i <= 2; i++) {
final int robotID = i;
//For each robot, create a thread that dispatches the "next" mission when the robot is free
Thread t = new Thread() {
int iteration = 0;
@Override
public void run() {
while (true) {
//Mission to dispatch alternates between (rip -> desti) and (desti -> rip)
Mission m = Missions.getMission(robotID, iteration%2);
synchronized(tec) {
//addMission returns true iff the robot was free to accept a new mission
if (tec.addMissions(m)) {
if (minDelay > 0) {
long delay = minDelay+rand.nextInt(maxDelay-minDelay);
//Sleep for a random delay in [minDelay,maxDelay]
try { Thread.sleep(delay); }
catch (InterruptedException e) { e.printStackTrace(); }
}
iteration++;
}
}
//Sleep for a little (2 sec)
try { Thread.sleep(2000); }
catch (InterruptedException e) { e.printStackTrace(); }
}
}
};
//Start the thread!
t.start();
}
}
}
| gpl-3.0 |
PhoenixDevTeam/Phoenix-for-VK | app/src/main/java/biz/dealnote/messenger/link/types/AbsLink.java | 1058 | package biz.dealnote.messenger.link.types;
public abstract class AbsLink {
public static final int PHOTO = 0;
public static final int PHOTO_ALBUM = 1;
public static final int PROFILE = 2;
public static final int GROUP = 3;
public static final int TOPIC = 4;
public static final int DOMAIN = 5;
public static final int WALL_POST = 6;
public static final int PAGE = 7;
public static final int ALBUMS = 8;
public static final int DIALOG = 9;
public static final int EXTERNAL_LINK = 10;
public static final int WALL = 11;
public static final int DIALOGS = 12;
public static final int VIDEO = 13;
public static final int DOC = 14;
public static final int AUDIOS = 15;
public static final int FAVE = 16;
public static final int WALL_COMMENT = 17;
public static final int BOARD = 18;
public static final int FEED_SEARCH = 19;
public int type;
public AbsLink(int vkLinkType) {
this.type = vkLinkType;
}
public boolean isValid(){
return true;
}
} | gpl-3.0 |
boost-starai/BoostSRL | code/src/edu/wisc/cs/will/Boosting/RDN/RegressionRDNExample.java | 7272 | package edu.wisc.cs.will.Boosting.RDN;
import java.io.Serializable;
import java.util.Arrays;
import edu.wisc.cs.will.Boosting.EM.HiddenLiteralState;
import edu.wisc.cs.will.DataSetUtils.Example;
import edu.wisc.cs.will.DataSetUtils.RegressionExample;
import edu.wisc.cs.will.FOPC.HandleFOPCstrings;
import edu.wisc.cs.will.FOPC.Literal;
import edu.wisc.cs.will.Utils.ProbDistribution;
import edu.wisc.cs.will.Utils.Utils;
/**
* Regression Example used for learning RDNs
* TODO move to DataSetUtils, maybe?
* @author Tushar Khot
*
*/
public class RegressionRDNExample extends RegressionExample implements Serializable {
/**
* This is used to indicate the original truth value of an example
* Should not be changed once set
*/
@Deprecated
private boolean originalTruthValue = false;
/**
* Rather than using a boolean value, use integer for original value
* for single class problem, 0==false, 1==true
* for multi class problem, the originalValue is an index to a constant value stored in MultiClassExampleHandler
*/
private int originalValue = 0;
/**
* This indicates whether this is a hidden literal. Original truth value wouldn't be useful if this is
* set to true.
*
*/
private boolean hiddenLiteral = false;
/**
* Only set if hiddenLiteral is set to true.
*/
private int originalHiddenLiteralVal = 0;
/**
* This is to be only used while sampling.
*/
@Deprecated
private boolean sampledTruthValue=(Utils.random() > 0.8);
/**
* Rather than using a boolean value, use integer for sampled value
* for single class problem, 0==false, 1==true
* for multi class problem, the sampledValue is an index to a constant value stored in MultiClassExampleHandler
*/
private int sampledValue= (Utils.random() > 0.8) ? 1 : 0;
/**
* Examples may have an associated state assignment to the hidden literals for the corresponding
* output value.
*/
private HiddenLiteralState stateAssociatedWithOutput = null;
/**
* The probability of this example being true. Generally set by sampling procedure
* Hence has Nan default value.
*/
private ProbDistribution probOfExample = null;
public RegressionRDNExample(HandleFOPCstrings stringHandler, Literal literal, double outputValue, String provenance, String extraLabel) {
super(stringHandler, literal, outputValue, provenance, extraLabel);
}
public RegressionRDNExample(HandleFOPCstrings stringHandler, Literal literal, double outputValue, String provenance, String extraLabel, boolean truthValue) {
super(stringHandler, literal, outputValue, provenance, extraLabel);
originalTruthValue = truthValue;
originalValue = truthValue ? 1:0;
}
public RegressionRDNExample(RegressionRDNExample copy) {
super(copy);
originalTruthValue = copy.originalTruthValue;
probOfExample = new ProbDistribution(copy.probOfExample);
sampledTruthValue = copy.sampledTruthValue;
hiddenLiteral = copy.hiddenLiteral;
originalValue = copy.originalValue;
sampledValue = copy.sampledValue;
stateAssociatedWithOutput = copy.stateAssociatedWithOutput;
}
public RegressionRDNExample(Example ex, boolean truthValue) {
super(ex.getStringHandler(), ex, (truthValue ? 1 : 0), ex.provenance, ex.extraLabel);
originalTruthValue = truthValue;
originalValue = truthValue ? 1:0;
}
public RegressionRDNExample(Literal lit, boolean truthValue, String provenance) {
this(lit.getStringHandler(), lit, (truthValue ? 1 : 0), provenance, null);
}
/*
public RegressionRDNExample(HandleFOPCstrings stringHandler, Example ex) {
super(stringHandler, ex);
originalTruthValue = truthValue;
}
*/
/**
*
*/
private static final long serialVersionUID = 5438994291636517166L;
/**
* @return the originalTruthValue
*/
public boolean isOriginalTruthValue() {
if (isHiddenLiteral()) {
Utils.waitHere("Can't trust original truth value here");
}
if (getOriginalValue() > 1) {
Utils.error("Checking for truth value for multi-class example.");
}
return getOriginalValue() == 1;
//return originalTruthValue;
}
/**
* @param originalTruthValue the originalTruthValue to set
*/
public void setOriginalTruthValue(boolean originalTruthValue) {
// this.originalTruthValue = originalTruthValue;
setOriginalValue(originalTruthValue?1:0);
}
/**
* @return the hiddenLiteral
*/
public boolean isHiddenLiteral() {
return hiddenLiteral;
}
/**
* @param hiddenLiteral the hiddenLiteral to set
*/
public void setHiddenLiteral(boolean hiddenLiteral) {
this.hiddenLiteral = hiddenLiteral;
}
/**
* @return the originalHiddenLiteralVal
*/
public int getOriginalHiddenLiteralVal() {
if (!isHiddenLiteral()) {
Utils.error("Not hidden literal!");
}
return originalHiddenLiteralVal;
}
/**
* @param originalHiddenLiteralVal the originalHiddenLiteralVal to set
*/
public void setOriginalHiddenLiteralVal(int originalHiddenLiteralVal) {
if (!isHiddenLiteral()) {
Utils.error("Not hidden literal!");
}
this.originalHiddenLiteralVal = originalHiddenLiteralVal;
}
/**
* @return the probOfExample
*/
public ProbDistribution getProbOfExample() {
if (probOfExample == null) {
Utils.error("Probability was not set");
return null;
}
return probOfExample;
}
/**
* @param probOfExample the probOfExample to set
*/
public void setProbOfExample(ProbDistribution probOfExample) {
// System.out.println("Probability set:" + probOfExample);
this.probOfExample = probOfExample;
}
public String toString() {
String result= super.toString();
return result; // + " Actual Bool=" + originalTruthValue +" Prob=" + probOfExample + " Output=" + outputValue;
}
public String toPrettyString() {
String result= super.toString();
result += " Actual Bool=" + originalTruthValue +" Prob=" + probOfExample + " Output=";
if (isHasRegressionVector()) {
result += Arrays.toString(getOutputVector());
} else {
result += getOutputValue();
}
return result;
}
/* *//**
* @param sampledTruthValue the sampledTruthValue to set
*//*
public void setSampledTruthValue(boolean sampledTruthValue) {
this.sampledTruthValue = sampledTruthValue;
}
*//**
* @return the sampledTruthValue
*//*
public boolean getSampledTruthValue() {
return sampledTruthValue;
}
*/
/**
* @return the originalValue
*/
public int getOriginalValue() {
if (isHiddenLiteral()) {
Utils.waitHere("Can't trust original value here");
}
return originalValue;
}
/**
* @param originalValue the originalValue to set
*/
public void setOriginalValue(int originalValue) {
this.originalValue = originalValue;
}
/**
* @return the sampledValue
*/
public int getSampledValue() {
return sampledValue;
}
/**
* @param sampledValue the sampledValue to set
*/
public void setSampledValue(int sampledValue) {
this.sampledValue = sampledValue;
}
/**
* @return the stateAssociatedWithOutput
*/
public HiddenLiteralState getStateAssociatedWithOutput() {
return stateAssociatedWithOutput;
}
/**
* @param stateAssociatedWithOutput the stateAssociatedWithOutput to set
*/
public void setStateAssociatedWithOutput(HiddenLiteralState stateAssociatedWithOutput) {
this.stateAssociatedWithOutput = stateAssociatedWithOutput;
}
}
| gpl-3.0 |
Consolefire/swing-helper | src/main/java/com/consolefire/swing/helper/model/syntax/WordFont.java | 1317 | /**
*
*/
package com.consolefire.swing.helper.model.syntax;
import java.io.Serializable;
/**
* @author Sabuj Das
*
*/
public class WordFont implements Serializable {
private boolean editable;
private String fontName;
private Integer fontSize;
private FontStyle fontStyle;
public WordFont() {
// TODO Auto-generated constructor stub
}
/**
* @return the editable
*/
public boolean isEditable() {
return editable;
}
/**
* @param editable the editable to set
*/
public void setEditable(boolean editable) {
this.editable = editable;
}
/**
* @return the fontName
*/
public String getFontName() {
return fontName;
}
/**
* @return the fontSize
*/
public Integer getFontSize() {
return fontSize;
}
/**
* @return the fontStyle
*/
public FontStyle getFontStyle() {
return fontStyle;
}
/**
* @param fontName the fontName to set
*/
public void setFontName(String fontName) {
this.fontName = fontName;
}
/**
* @param fontSize the fontSize to set
*/
public void setFontSize(Integer fontSize) {
this.fontSize = fontSize;
}
/**
* @param fontStyle the fontStyle to set
*/
public void setFontStyle(FontStyle fontStyle) {
this.fontStyle = fontStyle;
}
}
| gpl-3.0 |
toxeh/ExecuteQuery | java/src/org/executequery/gui/erd/ErdLineStyleDialog.java | 14674 | /*
* ErdLineStyleDialog.java
*
* Copyright (C) 2002-2013 Takis Diakoumis
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.executequery.gui.erd;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import org.executequery.GUIUtilities;
import org.executequery.components.ColourChooserButton;
import org.executequery.gui.DefaultPanelButton;
import org.executequery.gui.WidgetFactory;
import org.underworldlabs.swing.AbstractBaseDialog;
/**
*
* @author Takis Diakoumis
* @version $Revision: 160 $
* @date $Date: 2013-02-08 17:15:04 +0400 (пт, 08 фев 2013) $
*/
public class ErdLineStyleDialog extends AbstractBaseDialog {
/** The line weight combo box */
private JComboBox weightCombo;
/** The line style combo box */
private JComboBox styleCombo;
/** The arrow style combo box */
private JComboBox arrowCombo;
/** The colour selection button */
private ColourChooserButton colourButton;
/** The dependency panel where changes will occur */
private ErdDependanciesPanel dependsPanel;
/** <p>Creates a new instance with the specified values
* pre-selected within respective combo boxes.
*
* @param the <code>ErdDependanciesPanel</code> where
* changes will occur
* @param the line weight
* @param the line style index to be selected:<br>
* 0 - solid line
* 1 - dotted line
* 2 - dashed line
* @param the arrow index to be selected:<br>
* 0 - filled arrow
* 1 - outline arrow
* @param the line colour
*/
public ErdLineStyleDialog(ErdDependanciesPanel dependsPanel) {
super(GUIUtilities.getParentFrame(), "Line Style", true);
this.dependsPanel = dependsPanel;
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
determineWeightComboSelection(dependsPanel);
styleCombo.setSelectedIndex(dependsPanel.getLineStyleIndex());
arrowCombo.setSelectedIndex(dependsPanel.getArrowStyleIndex());
pack();
this.setLocation(GUIUtilities.getLocationForDialog(this.getSize()));
setVisible(true);
}
private void determineWeightComboSelection(ErdDependanciesPanel dependsPanel) {
float lineWeight = dependsPanel.getLineWeight();
if (isFloatEqual(lineWeight, 0.5f)) {
weightCombo.setSelectedIndex(0);
} else if (isFloatEqual(lineWeight, 1.0f)) {
weightCombo.setSelectedIndex(1);
} else if (isFloatEqual(lineWeight, 1.5f)) {
weightCombo.setSelectedIndex(2);
} else if (isFloatEqual(lineWeight, 2.0f)) {
weightCombo.setSelectedIndex(3);
}
}
private void jbInit() throws Exception {
LineStyleRenderer renderer = new LineStyleRenderer();
LineWeightIcon[] weightIcons = {new LineWeightIcon(0),
new LineWeightIcon(1),
new LineWeightIcon(2),
new LineWeightIcon(3)};
weightCombo = WidgetFactory.createComboBox(weightIcons);
weightCombo.setRenderer(renderer);
LineStyleIcon[] styleIcons = {new LineStyleIcon(0),
new LineStyleIcon(1),
new LineStyleIcon(2)};
styleCombo = WidgetFactory.createComboBox(styleIcons);
styleCombo.setRenderer(renderer);
ArrowStyleIcon[] arrowIcons = {new ArrowStyleIcon(0),
new ArrowStyleIcon(1)};
arrowCombo = WidgetFactory.createComboBox(arrowIcons);
arrowCombo.setRenderer(renderer);
JButton cancelButton = new DefaultPanelButton("Cancel");
JButton okButton = new DefaultPanelButton("OK");
ActionListener btnListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttons_actionPerformed(e); }
};
cancelButton.addActionListener(btnListener);
okButton.addActionListener(btnListener);
colourButton = new ColourChooserButton(dependsPanel.getLineColour());
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(14,10,5,10);
gbc.anchor = GridBagConstraints.NORTHWEST;
panel.add(new JLabel("Line Style:"), gbc);
gbc.gridwidth = 2;
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets.top = 10;
gbc.weightx = 1.0;
panel.add(styleCombo, gbc);
gbc.insets.top = 0;
gbc.gridy = 1;
panel.add(weightCombo, gbc);
gbc.gridwidth = 1;
gbc.insets.top = 5;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
gbc.gridx = 0;
panel.add(new JLabel("Line Weight:"), gbc);
gbc.gridy = 2;
panel.add(new JLabel("Arrow Style:"), gbc);
gbc.gridwidth = 2;
gbc.insets.top = 0;
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
panel.add(arrowCombo, gbc);
gbc.gridy = 3;
gbc.fill = GridBagConstraints.BOTH;
panel.add(colourButton, gbc);
gbc.insets.left = 10;
gbc.insets.top = 5;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
gbc.gridx = 0;
gbc.gridwidth = 1;
panel.add(new JLabel("Line Colour:"), gbc);
gbc.gridx = 1;
gbc.insets.right = 5;
gbc.ipadx = 25;
gbc.insets.left = 143;
gbc.insets.top = 5;
gbc.insets.bottom = 10;
gbc.weighty = 1.0;
gbc.weightx = 1.0;
gbc.gridy = 4;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
panel.add(okButton, gbc);
gbc.ipadx = 0;
gbc.insets.right = 10;
gbc.insets.left = 0;
gbc.gridx = 2;
gbc.weightx = 0;
panel.add(cancelButton, gbc);
panel.setBorder(BorderFactory.createEtchedBorder());
panel.setPreferredSize(new Dimension(450, 200));
Container c = this.getContentPane();
c.setLayout(new GridBagLayout());
c.add(panel, new GridBagConstraints(1, 1, 1, 1, 1.0, 1.0,
GridBagConstraints.SOUTHEAST, GridBagConstraints.BOTH,
new Insets(7, 7, 7, 7), 0, 0));
setResizable(false);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
}
/** <p>Performs the respective action upon selection
* of a button within this dialog.
*
* @param the <code>ActionEvent</code>
*/
private void buttons_actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Cancel"))
dispose();
else if (command.equals("OK")) {
int index = weightCombo.getSelectedIndex();
float lineWeight = 0f;
switch (index) {
case 0:
lineWeight = 0.5f;
break;
case 1:
lineWeight = 1.0f;
break;
case 2:
lineWeight = 1.5f;
break;
case 3:
lineWeight = 2.0f;
break;
}
dependsPanel.setLineWeight(lineWeight);
dependsPanel.setArrowStyle(arrowCombo.getSelectedIndex() == 0 ? true : false);
dependsPanel.setLineColour(colourButton.getColour());
dependsPanel.setLineStyle(styleCombo.getSelectedIndex());
dependsPanel.repaint();
dispose();
}
}
private boolean isFloatEqual(float value1, float value2) {
return (Math.abs(value1 - value2) < .0000001);
}
} // class
/** <p>Draws the available arrow styles as an
* <code>ImageIcon</code> to be added to the combo
* box through the renderer.
*/
class ArrowStyleIcon extends ImageIcon {
private int type;
public ArrowStyleIcon(int type) {
super();
this.type = type;
}
public int getIconWidth() {
return 250;
}
public int getIconHeight() {
return 20;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
// fill the background
g.setColor(Color.WHITE);
g.fillRect(0, 0, 290, 20);
// draw the line
g.setColor(Color.BLACK);
g.drawLine(5, 10, 250, 10);
int[] polyXs = {240, 250, 240};
int[] polyYs = {16, 10, 4};
switch (type) {
case 0:
g.fillPolygon(polyXs, polyYs, 3);
break;
case 1:
g.drawPolyline(polyXs, polyYs, 3);
break;
}
}
} // ArrowStyleIcon
class LineStyleRenderer extends JLabel
implements ListCellRenderer {
private static final Color focusColour =
UIManager.getColor("ComboBox.selectionBackground");
public LineStyleRenderer() {
super();
}
public Component getListCellRendererComponent(JList list, Object obj, int row,
boolean sel, boolean hasFocus) {
if (obj instanceof ImageIcon) {
setIcon((ImageIcon)obj);
if (sel)
setBorder(BorderFactory.createLineBorder(focusColour, 2));
else
setBorder(null);
} else
setText("ERROR");
return this;
}
} // LineStyleRenderer
/** <p>Draws the available line weights as an
* <code>ImageIcon</code> to be added to the combo
* box through the renderer.
*/
class LineWeightIcon extends ImageIcon {
private static final BasicStroke solidStroke_1 = new BasicStroke(0.5f);
private static final BasicStroke solidStroke_2 = new BasicStroke(1.0f);
private static final BasicStroke solidStroke_3 = new BasicStroke(1.5f);
private static final BasicStroke solidStroke_4 = new BasicStroke(2.0f);
private static final String HALF = "0.5";
private static final String ONE = "1.0";
private static final String ONE_FIVE = "1.5";
private static final String TWO = "2.0";
private int type;
public LineWeightIcon(int type) {
super();
this.type = type;
}
public int getIconWidth() {
return 250;
}
public int getIconHeight() {
return 20;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D)g;
String text = null;
switch (type) {
case 0:
g2d.setStroke(solidStroke_1);
text = HALF;
break;
case 1:
g2d.setStroke(solidStroke_2);
text = ONE;
break;
case 2:
g2d.setStroke(solidStroke_3);
text = ONE_FIVE;
break;
case 3:
g2d.setStroke(solidStroke_4);
text = TWO;
break;
}
// fill the background
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, 290, 20);
FontMetrics fm = g2d.getFontMetrics();
// draw the line style
g2d.setColor(Color.BLACK);
g2d.drawString(text, 5, fm.getHeight());
g2d.drawLine(30, 10, 250, 10);
}
} // LineWeightIcon
/** <p>Draws the available line styles as an
* <code>ImageIcon</code> to be added to the combo
* box through the renderer.
*/
class LineStyleIcon extends ImageIcon {
private static final BasicStroke solidStroke = new BasicStroke(1.0f);
private static final float dash1[] = {2.0f};
private static final BasicStroke dashedStroke_1 =
new BasicStroke(1.0f, 0, 0, 10f, dash1, 0.0f);
private static final float dash2[] = {5f, 2.0f};
private static final BasicStroke dashedStroke_2 =
new BasicStroke(1.0f, 0, 0, 10f, dash2, 0.0f);
private int type;
public LineStyleIcon(int type) {
super();
this.type = type;
}
public int getIconWidth() {
return 250;
}
public int getIconHeight() {
return 20;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D)g;
switch (type) {
case 0:
g2d.setStroke(solidStroke);
break;
case 1:
g2d.setStroke(dashedStroke_1);
break;
case 2:
g2d.setStroke(dashedStroke_2);
break;
}
// fill the background
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, 290, 20);
// draw the line style
g2d.setColor(Color.BLACK);
g2d.drawLine(5, 10, 250, 10);
}
} // LineStyleIcon
| gpl-3.0 |
AKSW/LIMES-dev | limes-gui/src/main/java/org/aksw/limes/core/gui/view/graphBuilder/NodeViewRectangle.java | 7654 | package org.aksw.limes.core.gui.view.graphBuilder;
import org.aksw.limes.core.gui.model.metric.Node;
import org.aksw.limes.core.gui.model.metric.Property;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.shape.ArcType;
import javafx.scene.text.Text;
/**
* used for the shape of a
* {@link org.aksw.limes.core.gui.view.graphBuilder.NodeView}
*
* @author Daniel Obraczka {@literal <} soz11ffe{@literal @}
* studserv.uni-leipzig.de{@literal >}
*
*/
public class NodeViewRectangle {
public static final Color targetCol = Color.rgb(23, 104, 19);
public static final Color targetOptionalCol = Color.rgb(23, 104, 19, 0.6);
public static final Color sourceCol = Color.rgb(128, 23, 26);
public static final Color sourceOptionalCol = Color.rgb(128, 23, 26, 0.6);
public static final Color metricCol = Color.rgb(129, 70, 23);
public static final Color operatorCol = Color.rgb(14, 78, 76);
public static final Color outputCol = Color.rgb(1, 30, 0);
public static final Color targetHeadTextCol = Color.rgb(236, 237, 236);
public static final Color sourceHeadTextCol = Color.rgb(254, 242, 242);
public static final Color metricHeadTextCol = Color.rgb(217, 218, 218);
public static final Color operatorHeadtextCol = Color.rgb(255, 254, 253);
public static final Color outputHeadTextCol = Color.rgb(243, 243, 243);
public static double arch = 50;
private final NodeView node;
private final double x;
private final double y;
private Color color;
private Color HeadTextCol;
private Node nodeData;
/**
* Constructor
*
* @param x
* x position
* @param y
* y position
* @param nodeShape
* shape
* @param node
* nodeview
* @param nodeData
* data model
*/
public NodeViewRectangle(double x, double y, int nodeShape, NodeView node, Node nodeData) {
this.x = x;
this.y = y;
this.nodeData = nodeData;
switch (nodeShape) {
case NodeView.METRIC:
this.color = metricCol;
this.HeadTextCol = metricHeadTextCol;
break;
case NodeView.OUTPUT:
this.color = outputCol;
this.HeadTextCol = outputHeadTextCol;
break;
case NodeView.OPERATOR:
this.color = operatorCol;
this.HeadTextCol = operatorHeadtextCol;
break;
case NodeView.SOURCE:
this.HeadTextCol = sourceHeadTextCol;
if (((Property) nodeData).isOptional()) {
this.color = sourceOptionalCol;
} else {
this.color = sourceCol;
}
break;
case NodeView.TARGET:
this.HeadTextCol = targetHeadTextCol;
if (((Property) nodeData).isOptional()) {
this.color = targetOptionalCol;
} else {
this.color = targetCol;
}
break;
}
this.node = node;
this.nodeData = nodeData;
}
/**
* draws the NodeViewRectangle object according to its variables in the
* {@link javafx.scene.canvas.GraphicsContext}
*
* @param gc
* GraphicsContext
*/
public void drawNodeViewRectangle(GraphicsContext gc) {
if (this.color != metricCol) {
gc.setFill(Color.rgb(243, 243, 243));
gc.setStroke(this.color);
gc.strokeRoundRect(this.x, this.y, this.node.getWidth(), this.node.getHeight(), NodeViewRectangle.arch,
NodeViewRectangle.arch);
gc.fillRoundRect(this.x, this.y, this.node.getWidth(), this.node.getHeight(), NodeViewRectangle.arch,
NodeViewRectangle.arch);
gc.setFill(this.color);
gc.fillArc(this.x, this.y, NodeViewRectangle.arch, NodeViewRectangle.arch, 90.0, 90.0, ArcType.ROUND);
gc.fillArc(this.x + this.node.getWidth() - NodeViewRectangle.arch, this.y, NodeViewRectangle.arch,
NodeViewRectangle.arch, 0.0, 90.0, ArcType.ROUND);
gc.fillRect(this.x + arch / 2, this.y, this.node.getWidth() - arch, arch / 2);
} else {
gc.setFill(this.color);
gc.fillRoundRect(this.x, this.y, this.node.getWidth(), this.node.getHeight(), NodeViewRectangle.arch,
NodeViewRectangle.arch);
}
if (this.color != sourceCol && this.color != sourceOptionalCol && this.color != targetCol
&& this.color != targetOptionalCol) {
gc.setFill(this.HeadTextCol);
this.fillText(gc, this.nodeData.id, this.node.getWidth(), 0, arch / 4, false);
if (this.color == outputCol) {
gc.setFill(operatorCol);
this.fillText(gc, "Acceptance threshold: ", this.nodeData.param1, this.node.getWidth(), 4, arch * 0.75,
true);
this.fillText(gc, "Verification threshold: ", this.nodeData.param2, this.node.getWidth(), 4,
arch * 1.25, true);
} else if (this.color == operatorCol) {
gc.setFill(operatorCol);
if (this.nodeData.getChilds().isEmpty()) {
this.fillText(gc, "parent1 threshold: ", this.nodeData.param1, this.node.getWidth(), 4, arch * 0.75,
true);
this.fillText(gc, "parent2 threshold: ", this.nodeData.param2, this.node.getWidth(), 4, arch * 1.25,
true);
} else if (this.nodeData.getChilds().size() == 1) {
this.fillText(gc, this.nodeData.getChilds().get(0).id + " threshold: ", this.nodeData.param1,
this.node.getWidth(), 4.0, arch * 0.75, true);
this.fillText(gc, "parent2 threshold: ", this.nodeData.param2, this.node.getWidth(), 4, arch * 1.25,
true);
} else {
this.fillText(gc, this.nodeData.getChilds().get(0).id + " threshold: ", this.nodeData.param1,
this.node.getWidth(), 4.0, arch * 0.75, true);
this.fillText(gc, this.nodeData.getChilds().get(1).id + " threshold: ", this.nodeData.param2,
this.node.getWidth(), 4.0, arch * 1.25, true);
}
}
} else if (this.color == sourceCol || this.color == sourceOptionalCol) {
gc.setFill(this.HeadTextCol);
this.fillText(gc, "source", this.node.getWidth(), 0.0, arch / 4, false);
gc.setFill(operatorCol);
this.fillText(gc, this.nodeData.id, this.node.getWidth(), 4, arch * 0.75, true);
} else if (this.color == targetCol || this.color == targetOptionalCol) {
gc.setFill(this.HeadTextCol);
this.fillText(gc, "target", this.node.getWidth(), 0.0, arch / 4, false);
gc.setFill(operatorCol);
this.fillText(gc, this.nodeData.id, this.node.getWidth(), 4, arch * 0.75, true);
}
}
private void fillText(GraphicsContext gc, String text, int nodeWidth, double xoffset, double yoffset,
boolean leftAligned) {
this.fillText(gc, text, -1, nodeWidth, xoffset, yoffset, leftAligned);
}
private void fillText(GraphicsContext gc, String text, double thresholdValue, int nodeWidth, double xoffset,
double yoffset, boolean leftAligned) {
Text label = new Text(text);
final double labelWidth = label.getLayoutBounds().getWidth();
// check if the label needs to be cutoff
if (labelWidth > 0.85 * this.node.getWidth()) {
double cutoff = 0.0;
if (leftAligned) {
cutoff = (100 / (double) (this.node.getWidth() - 20) * labelWidth - 100) / 100;
} else {
cutoff = (100 / (double) (this.node.getWidth() - 30) * labelWidth - 100) / 100;
}
if (thresholdValue == -1) {
label = new Text(text.substring(0, (int) (text.length() - Math.abs(text.length() * cutoff))) + "...");
} else {
label = new Text(
text.substring(0, (int) (text.length() - Math.abs(text.length() * cutoff))) + "... : ");
}
}
if (!leftAligned) {
xoffset += this.calculateOffset(label, nodeWidth);
}
if (thresholdValue == -1) {
gc.fillText(label.getText(), this.x + xoffset, this.y + yoffset);
} else {
gc.fillText(label.getText() + thresholdValue, this.x + xoffset, this.y + yoffset);
}
}
/**
* Calculate the offset, to get the text centered
*/
private int calculateOffset(Text label, int width) {
final double labelWidth = label.getLayoutBounds().getWidth();
return (int) (width / 2.0 - labelWidth / 2.0);
}
}
| gpl-3.0 |
syncany/syncany-plugin-gui | src/main/java/org/syncany/gui/util/WindowsRegistryUtil.java | 5206 | /*
* Syncany, www.syncany.org
* Copyright (C) 2011-2015 Philipp C. Heckel <philipp.heckel@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.syncany.gui.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WindowsRegistryUtil {
/**
* Reads a value from the Windows registry (only string type, REG_SZ).
*
* <p>This method executes the following command (example):
* <pre>
* $>reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v Syncany /t REG_SZ
*
* HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
* Syncany REG_SZ <value>
*
* End of search: 1 match(es) found.
* </pre>
*
* @throws IOException
*/
public static final String readString(String path, String key) throws IOException {
// Build command
List<String> command = new ArrayList<>();
command.add("reg");
command.add("query");
command.add(path);
command.add("/t");
command.add("REG_SZ");
// Run it
try {
Process regProcess = Runtime.getRuntime().exec(command.toArray(new String[0]));
BufferedReader regOutputReader = new BufferedReader(new InputStreamReader(regProcess.getInputStream()));
// And parse the output
Pattern outputMatchPattern = Pattern.compile("\\s+" + key + "\\s+REG_SZ\\s+(.+)");
String result = null;
String line = null;
while ((line = regOutputReader.readLine()) != null) {
Matcher outputLineMatcher = outputMatchPattern.matcher(line);
if (outputLineMatcher.find()) {
result = outputLineMatcher.group(1);
}
}
throwAwayStream(regProcess.getErrorStream());
regProcess.waitFor();
return result;
}
catch (InterruptedException e) {
throw new IOException(e);
}
}
/**
* Deletes a registry key from the Windows registry.
*
* <p>This method executes the following command (example):
* <pre>
* $> reg delete /f HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v Syncany
* The operation completed successfully.
* </pre>
*
* @throws IOException
*/
public static final void deleteKey(String path, String key) throws IOException {
Objects.requireNonNull(path);
// Build command
List<String> command = new ArrayList<>();
command.add("reg");
command.add("delete");
command.add(path);
if (key != null) {
command.add("/v");
command.add(key);
}
else {
command.add("/ve");
}
command.add("/f");
// And run it
try {
Process regProcess = Runtime.getRuntime().exec(command.toArray(new String[0]));
throwAwayStream(regProcess.getInputStream());
throwAwayStream(regProcess.getErrorStream());
regProcess.waitFor();
}
catch (InterruptedException e) {
throw new IOException(e);
}
}
/**
* Writes a registry key to the Windows registry (only string type, REG_SZ).
*
* <p>This method executes the following command (example):
* <pre>
* $> reg add /f HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v Syncany /t REG_SZ /d "<path>"
* </pre>
*
* @throws InterruptedException
* @throws IOException
*/
public static final void writeString(String path, String key, String value) throws IOException {
Objects.requireNonNull(path, value);
// Build command
List<String> command = new ArrayList<>();
command.add("reg");
command.add("add");
command.add(path);
if (key != null) {
command.add("/v");
command.add(key);
}
command.add("/t");
command.add("REG_SZ");
command.add("/d");
command.add(value);
command.add("/f");
// And run it
try {
Process regProcess = Runtime.getRuntime().exec(command.toArray(new String[0]));
throwAwayStream(regProcess.getInputStream());
throwAwayStream(regProcess.getErrorStream());
regProcess.waitFor();
}
catch (InterruptedException e) {
throw new IOException(e);
}
}
private static void throwAwayStream(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
while ((reader.readLine()) != null) {
// Do nothing.
}
}
} | gpl-3.0 |
jason-callaway/open-keychain | OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptActivity.java | 6303 | package org.sufficientlysecure.keychain.ui;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import org.openintents.openpgp.util.OpenPgpApi;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.operations.results.PgpSignEncryptResult;
import org.sufficientlysecure.keychain.operations.results.SignEncryptResult;
import org.sufficientlysecure.keychain.pgp.SignEncryptParcel;
import org.sufficientlysecure.keychain.service.KeychainIntentService;
import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler;
import java.util.Date;
public abstract class EncryptActivity extends BaseActivity {
public static final int REQUEST_CODE_PASSPHRASE = 0x00008001;
public static final int REQUEST_CODE_NFC = 0x00008002;
// For NFC data
protected String mSigningKeyPassphrase = null;
protected Date mNfcTimestamp = null;
protected byte[] mNfcHash = null;
protected void startPassphraseDialog(long subkeyId) {
Intent intent = new Intent(this, PassphraseDialogActivity.class);
intent.putExtra(PassphraseDialogActivity.EXTRA_SUBKEY_ID, subkeyId);
startActivityForResult(intent, REQUEST_CODE_PASSPHRASE);
}
protected void startNfcSign(long keyId, String pin, byte[] hashToSign, int hashAlgo) {
// build PendingIntent for Yubikey NFC operations
Intent intent = new Intent(this, NfcActivity.class);
intent.setAction(NfcActivity.ACTION_SIGN_HASH);
// pass params through to activity that it can be returned again later to repeat pgp operation
intent.putExtra(NfcActivity.EXTRA_DATA, new Intent()); // not used, only relevant to OpenPgpService
intent.putExtra(NfcActivity.EXTRA_KEY_ID, keyId);
intent.putExtra(NfcActivity.EXTRA_PIN, pin);
intent.putExtra(NfcActivity.EXTRA_NFC_HASH_TO_SIGN, hashToSign);
intent.putExtra(NfcActivity.EXTRA_NFC_HASH_ALGO, hashAlgo);
startActivityForResult(intent, REQUEST_CODE_NFC);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_PASSPHRASE: {
if (resultCode == RESULT_OK && data != null) {
mSigningKeyPassphrase = data.getStringExtra(PassphraseDialogActivity.MESSAGE_DATA_PASSPHRASE);
startEncrypt();
return;
}
break;
}
case REQUEST_CODE_NFC: {
if (resultCode == RESULT_OK && data != null) {
mNfcHash = data.getByteArrayExtra(OpenPgpApi.EXTRA_NFC_SIGNED_HASH);
startEncrypt();
return;
}
break;
}
default: {
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
}
public void startEncrypt() {
if (!inputIsValid()) {
// Notify was created by inputIsValid.
return;
}
// Send all information needed to service to edit key in other thread
Intent intent = new Intent(this, KeychainIntentService.class);
intent.setAction(KeychainIntentService.ACTION_SIGN_ENCRYPT);
Bundle data = new Bundle();
data.putParcelable(KeychainIntentService.SIGN_ENCRYPT_PARCEL, createEncryptBundle());
intent.putExtra(KeychainIntentService.EXTRA_DATA, data);
// Message is received after encrypting is done in KeychainIntentService
KeychainIntentServiceHandler serviceHandler = new KeychainIntentServiceHandler(this,
getString(R.string.progress_encrypting), ProgressDialog.STYLE_HORIZONTAL) {
public void handleMessage(Message message) {
// handle messages by standard KeychainIntentServiceHandler first
super.handleMessage(message);
if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) {
SignEncryptResult result =
message.getData().getParcelable(SignEncryptResult.EXTRA_RESULT);
PgpSignEncryptResult pgpResult = result.getPending();
if (pgpResult != null && pgpResult.isPending()) {
if ((pgpResult.getResult() & PgpSignEncryptResult.RESULT_PENDING_PASSPHRASE) ==
PgpSignEncryptResult.RESULT_PENDING_PASSPHRASE) {
startPassphraseDialog(pgpResult.getKeyIdPassphraseNeeded());
} else if ((pgpResult.getResult() & PgpSignEncryptResult.RESULT_PENDING_NFC) ==
PgpSignEncryptResult.RESULT_PENDING_NFC) {
mNfcTimestamp = pgpResult.getNfcTimestamp();
startNfcSign(pgpResult.getNfcKeyId(), pgpResult.getNfcPassphrase(),
pgpResult.getNfcHash(), pgpResult.getNfcAlgo());
} else {
throw new RuntimeException("Unhandled pending result!");
}
return;
}
if (result.success()) {
onEncryptSuccess(result);
} else {
result.createNotify(EncryptActivity.this).show();
}
// no matter the result, reset parameters
mSigningKeyPassphrase = null;
mNfcHash = null;
mNfcTimestamp = null;
}
}
};
// Create a new Messenger for the communication back
Messenger messenger = new Messenger(serviceHandler);
intent.putExtra(KeychainIntentService.EXTRA_MESSENGER, messenger);
// show progress dialog
serviceHandler.showProgressDialog(this);
// start service with intent
startService(intent);
}
protected abstract boolean inputIsValid();
protected abstract void onEncryptSuccess(SignEncryptResult result);
protected abstract SignEncryptParcel createEncryptBundle();
}
| gpl-3.0 |
appnativa/rare | source/rare/core/com/appnativa/rare/iCancelableFuture.java | 1945 | /*
* Copyright appNativa Inc. All Rights Reserved.
*
* This file is part of the Real-time Application Rendering Engine (RARE).
*
* RARE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.appnativa.rare;
import com.appnativa.util.iCancelable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public interface iCancelableFuture<T> extends iCancelable {
/**
* Waits if necessary for the computation to complete, and then retrieves its result
* <p>
* Only the first invocation is guaranteed to return the result. Subsequent calls
* may return a null value.
* </p>
*
* @return the computed result
*/
T get() throws InterruptedException, ExecutionException;
/**
* Waits if necessary for at most the given time for the computation to complete,
* and then retrieves its result, if available.
* <p>
* Only the first invocation is guaranteed to return the result. Subsequent calls
* may return a null value.
* </p>
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return the computed result
*/
T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}
| gpl-3.0 |
active-citizen/android.java | app/src/main/java/ru/mos/polls/support/model/FeedbackInfo.java | 583 | package ru.mos.polls.support.model;
import com.google.gson.annotations.SerializedName;
public class FeedbackInfo {
private String app;
@SerializedName("app_version")
private String appVersion;
private String device;
private String os;
@SerializedName("session_id")
private String sessionId;
public FeedbackInfo(String app, String appVersion, String device, String os, String sessionId) {
this.app = app;
this.appVersion = appVersion;
this.device = device;
this.os = os;
this.sessionId = sessionId;
}
}
| gpl-3.0 |
avdata99/SIAT | siat-1.0-SOURCE/src/view/src/WEB-INF/src/ar/gov/rosario/siat/ef/view/struts/BuscarAprobacionActaInvDAction.java | 8958 | //Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda.
//This file is part of SIAT. SIAT is licensed under the terms
//of the GNU General Public License, version 3.
//See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt>
package ar.gov.rosario.siat.ef.view.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import ar.gov.rosario.siat.base.view.struts.BaseDispatchAction;
import ar.gov.rosario.siat.base.view.util.UserSession;
import ar.gov.rosario.siat.ef.iface.model.OpeInvConSearchPage;
import ar.gov.rosario.siat.ef.iface.service.EfServiceLocator;
import ar.gov.rosario.siat.ef.iface.util.EfSecurityConstants;
import ar.gov.rosario.siat.ef.view.util.EfConstants;
import coop.tecso.demoda.iface.helper.DemodaUtil;
public final class BuscarAprobacionActaInvDAction extends BaseDispatchAction {
private Log log = LogFactory.getLog(BuscarAprobacionActaInvDAction.class);
public ActionForward inicializar(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String funcName = DemodaUtil.currentMethodName();
String act = getCurrentAct(request);
if (log.isDebugEnabled()) log.debug(funcName + ": enter");
UserSession userSession = canAccess(request, mapping, EfSecurityConstants.ADM_APROBACIONACTAINV, act);
if (userSession==null) return forwardErrorSession(request);
try {
OpeInvConSearchPage opeInvConSearchPageVO = EfServiceLocator.getInvestigacionService().getAprobacionActasSearchPageInit(userSession);
// Tiene errores recuperables
if (opeInvConSearchPageVO.hasErrorRecoverable()) {
log.error("recoverable error en: " + funcName + ": " + opeInvConSearchPageVO.infoString());
saveDemodaErrors(request, opeInvConSearchPageVO);
return forwardErrorRecoverable(mapping, request, userSession, OpeInvConSearchPage.NAME, opeInvConSearchPageVO);
}
// Tiene errores no recuperables
if (opeInvConSearchPageVO.hasErrorNonRecoverable()) {
log.error("error en: " + funcName + ": " + opeInvConSearchPageVO.errorString());
return forwardErrorNonRecoverable(mapping, request, funcName, OpeInvConSearchPage.NAME, opeInvConSearchPageVO);
}
// Si no tiene error
baseInicializarSearchPage(mapping, request, userSession , OpeInvConSearchPage.NAME, opeInvConSearchPageVO);
return mapping.findForward(EfConstants.FWD_APROBACIONACTAINV_SEARCHPAGE);
} catch (Exception exception) {
return baseException(mapping, request, funcName, exception, OpeInvConSearchPage.NAME);
}
}
public ActionForward limpiar(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String funcName = DemodaUtil.currentMethodName();
return this.baseRefill(mapping, form, request, response, funcName, OpeInvConSearchPage.NAME);
}
public ActionForward buscar(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String funcName = DemodaUtil.currentMethodName();
if (log.isDebugEnabled()) log.debug(funcName + ": enter");
UserSession userSession = getCurrentUserSession(request, mapping);
if (userSession == null) return forwardErrorSession(request);
try {
// Bajo el searchPage del userSession
OpeInvConSearchPage OpeInvConSearchPageVO = (OpeInvConSearchPage) userSession.get(OpeInvConSearchPage.NAME);
// Si es nulo no se puede continuar
if (OpeInvConSearchPageVO == null) {
log.error("error en: " + funcName + ": " + OpeInvConSearchPage.NAME + " IS NULL. No se pudo obtener de la sesion");
return forwardErrorSessionNullObject(mapping, request, funcName, OpeInvConSearchPage.NAME);
}
// si el buscar diparado desde la pagina de busqueda
if (((String)userSession.get("reqAttIsSubmittedForm")).equals("true")) {
// Recuperamos datos del form en el vo
DemodaUtil.populateVO(OpeInvConSearchPageVO, request);
// Setea el PageNumber del PageModel
OpeInvConSearchPageVO.setPageNumber(new Long((String)userSession.get("reqAttPageNumber")));
}
// Tiene errores recuperables
if (OpeInvConSearchPageVO.hasErrorRecoverable()) {
log.error("recoverable error en: " + funcName + ": " + OpeInvConSearchPageVO.infoString());
saveDemodaErrors(request, OpeInvConSearchPageVO);
return forwardErrorRecoverable(mapping, request, userSession, OpeInvConSearchPage.NAME, OpeInvConSearchPageVO);
}
// Llamada al servicio
OpeInvConSearchPageVO = EfServiceLocator.getInvestigacionService().getAprobacionActasSearchPageResult(userSession, OpeInvConSearchPageVO);
// Tiene errores recuperables
if (OpeInvConSearchPageVO.hasErrorRecoverable()) {
log.error("recoverable error en: " + funcName + ": " + OpeInvConSearchPageVO.infoString());
saveDemodaErrors(request, OpeInvConSearchPageVO);
return forwardErrorRecoverable(mapping, request, userSession, OpeInvConSearchPage.NAME, OpeInvConSearchPageVO);
}
// Tiene errores no recuperables
if (OpeInvConSearchPageVO.hasErrorNonRecoverable()) {
log.error("error en: " + funcName + ": " + OpeInvConSearchPageVO.errorString());
return forwardErrorNonRecoverable(mapping, request, funcName, OpeInvConSearchPage.NAME, OpeInvConSearchPageVO);
}
// Envio el VO al request
request.setAttribute(OpeInvConSearchPage.NAME, OpeInvConSearchPageVO);
// Subo en el el searchPage al userSession
userSession.put(OpeInvConSearchPage.NAME, OpeInvConSearchPageVO);
return mapping.findForward(EfConstants.FWD_APROBACIONACTAINV_SEARCHPAGE);
} catch (Exception exception) {
return baseException(mapping, request, funcName, exception, OpeInvConSearchPage.NAME);
}
}
public ActionForward paramPlan(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String funcName = DemodaUtil.currentMethodName();
if (log.isDebugEnabled()) log.debug(funcName + ": enter");
UserSession userSession = getCurrentUserSession(request, mapping);
if (userSession == null) return forwardErrorSession(request);
try {
// Bajo el searchPage del userSession
OpeInvConSearchPage OpeInvConSearchPageVO = (OpeInvConSearchPage) userSession.get(OpeInvConSearchPage.NAME);
// Si es nulo no se puede continuar
if (OpeInvConSearchPageVO == null) {
log.error("error en: " + funcName + ": " + OpeInvConSearchPage.NAME + " IS NULL. No se pudo obtener de la sesion");
return forwardErrorSessionNullObject(mapping, request, funcName, OpeInvConSearchPage.NAME);
}
// Recuperamos datos del form en el vo
DemodaUtil.populateVO(OpeInvConSearchPageVO, request);
// Llamada al servicio
OpeInvConSearchPageVO = EfServiceLocator.getInvestigacionService().getAprobacionActasSearchPageParamPlan(userSession, OpeInvConSearchPageVO);
// Tiene errores recuperables
if (OpeInvConSearchPageVO.hasErrorRecoverable()) {
log.error("recoverable error en: " + funcName + ": " + OpeInvConSearchPageVO.infoString());
saveDemodaErrors(request, OpeInvConSearchPageVO);
return forwardErrorRecoverable(mapping, request, userSession, OpeInvConSearchPage.NAME, OpeInvConSearchPageVO);
}
// Tiene errores no recuperables
if (OpeInvConSearchPageVO.hasErrorNonRecoverable()) {
log.error("error en: " + funcName + ": " + OpeInvConSearchPageVO.errorString());
return forwardErrorNonRecoverable(mapping, request, funcName, OpeInvConSearchPage.NAME, OpeInvConSearchPageVO);
}
// Envio el VO al request
request.setAttribute(OpeInvConSearchPage.NAME, OpeInvConSearchPageVO);
// Subo en el el searchPage al userSession
userSession.put(OpeInvConSearchPage.NAME, OpeInvConSearchPageVO);
return mapping.findForward(EfConstants.FWD_APROBACIONACTAINV_SEARCHPAGE);
} catch (Exception exception) {
return baseException(mapping, request, funcName, exception, OpeInvConSearchPage.NAME);
}
}
public ActionForward cambiarEstado(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String funcName = DemodaUtil.currentMethodName();
return baseForwardSearchPage(mapping, request, funcName, EfConstants.FWD_APROBACTAINV, EfConstants.ACT_CAMBIARESTADO );
}
public ActionForward volver(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return baseVolver(mapping, form, request, response, OpeInvConSearchPage.NAME);
}
}
| gpl-3.0 |
silverweed/pokepon | util/MessageManager.java | 10198 | //: battle/MessageManager.java
package pokepon.util;
import pokepon.battle.Battle;
import pokepon.pony.Pony;
import java.util.*;
import java.io.PrintStream;
import java.nio.*;
import java.nio.charset.*;
import java.text.*;
/** Class that provides an abstraction level for communication
* between battle classes and UI.
*
* @author silverweed
*/
public class MessageManager {
public static final char CMD_PREFIX = '/';
public static final char CMN_PREFIX = '!';
public static final char BTL_PREFIX = '~';
private static StrAppendable altOut, altErr;
/** Do not instance me, plz! */
private MessageManager() {}
public static void setAltOut(StrAppendable alt) {
altOut = alt;
}
public static void setAltErr(StrAppendable alt) {
altErr = alt;
}
public static StrAppendable getAltOut() {
return altOut;
}
public static StrAppendable getAltErr() {
return altErr;
}
public static void printMsg(String str) {
if(altOut == null)
System.out.println(str);
else
altOut.append(str+"\n");
}
public static void printMsgnb(String str) {
if(altOut == null)
System.out.print(str);
else
altErr.append(str);
}
public static void printDebug(String str) {
if(altErr == null)
System.err.println(str);
else
altErr.append(str+"\n");
}
public static void printDebugnb(String str) {
if(altErr == null)
System.err.print(str);
else
altErr.append(str);
}
public static void printFormat(String str, Object... args) {
if(altOut == null)
System.out.format(str, args);
else
altOut.append(String.format(null, str, args));
}
public static void consoleMsg(String str) {
System.out.println(str);
}
public static void consoleMsgnb(String str) {
System.out.print(str);
}
public static void consoleDebug(String str) {
System.err.println(str);
}
public static void consoleDebugnb(String str) {
System.err.print(str);
}
public static void consoleFormat(String format,Object... args) {
System.out.format(format,args);
}
public static <T> void consoleTable(Collection<T> c, int cols) {
consoleTable(c, cols, 2);
}
/** Prints a collection in an ordered table with 'cols' columns
* Spaces between columns are automatically resized to fit longest
* element's name in each column; note that this uses T.toString()
* method.
* @param c The collection of elements to output
* @param cols The number of columns
* @param colspacing Spacing between columns (default: 2)
*/
public static <T> void consoleTable(Collection<T> c, int cols, int colspacing) {
if(Debug.pedantic) {
printDebug("passed collection: "+c.toString());
printDebug("size: "+c.size()+" (size/cols: "+c.size()/cols+")");
}
/* Get elements' lengths */
List<Integer> len = new ArrayList<Integer>();
for(T t : c) {
len.add(t.toString().length());
}
/* Convert collection into 2D array */
String[][] matrix = new String[c.size()/cols+1][cols];
for(int i = 0; i < c.size(); ++i) {
matrix[i/cols][i%cols] = c.toArray()[i].toString();
}
/* Ensure no element is null */
for(int i = 0; i < c.size()/cols+1; ++i)
for(int j = 0; j < cols; ++j)
if(matrix[i][j] == null) matrix[i][j] = "";
if(Debug.pedantic) {
printDebug("matrix:");
for(int i = 0; i < c.size()/cols+1; ++i) {
printDebugnb("["+i+"] ");
for(int j = 0; j < cols; ++j)
printDebugnb(matrix[i][j]+" ");
printDebug("");
}
}
/* Get max lengths of each columns */
int[] maxLen = new int[cols];
if(Debug.pedantic) {
printDebug("maxLen:");
for(int i = 0; i < cols; ++i)
printDebugnb(maxLen[i]+" | ");
printDebug("");
}
for(int j = 0; j < cols; ++j) {
for(int i = 0; i < c.size()/cols+1; ++i)
if(matrix[i][j].length() > maxLen[j]) maxLen[j] = matrix[i][j].length();
if(Debug.pedantic) System.err.println("Column "+j+": maxlen= "+maxLen[j]);
}
for(int i = 0; i < c.size()/cols+1; ++i) {
for(int j = 0; j < cols; ++j) {
System.out.format("%-"+Math.max(1,maxLen[j])+"s",matrix[i][j]);
if(j < cols-1)
for(int k = 0; k < colspacing; ++k) System.out.print(" ");
}
System.out.println("");
}
}
public static <T> void consoleFixedTable(Collection<T> c,int cols) {
consoleFixedTable(c, cols, 2);
}
/** Prints a collection in ordered table with 'cols' columns;
* columns are equally spaced with enough space to fit longest element
* in collection; differs from consoleTable in that the cols' width is
* the same for each column, while consoleTable uses a different width
* for each column (i.e: here maxLen is global, in consoleTable is column-wise).
*/
public static <T> void consoleFixedTable(Collection<T> c,int cols,int colspacing) {
int maxLen = 1;
for(T t : c)
if(t.toString().length() > maxLen) maxLen = t.toString().length();
int i = 1;
for(T t : c) {
System.out.format("%-"+maxLen+"s",t.toString());
if(i++ % cols != 0)
for(int k = 0; k < colspacing; ++k) System.out.print(" ");
else System.out.println("");
}
System.out.println("");
}
public static void consoleHeader(String text) {
consoleHeader(new String[] { text });
}
public static void consoleHeader(String text, char d) {
consoleHeader(new String[] { text }, d);
}
public static void consoleHeader(String text, char d, PrintStream stream) {
consoleHeader(new String[] { text }, d, stream);
}
public static void consoleHeader(String text, char d, PrintStream stream, int vSpacing) {
consoleHeader(new String[] { text }, d, stream, vSpacing);
}
public static void consoleHeader(String text, char d, PrintStream stream, int vSpacing, int hSpacing) {
consoleHeader(new String[] { text }, d, stream, vSpacing, hSpacing);
}
public static void consoleHeader(String[] text) {
consoleHeader(text, '*');
}
public static void consoleHeader(String[] text, char d) {
consoleHeader(text, d, System.out);
}
public static void consoleHeader(String[] text, char d, PrintStream stream) {
consoleHeader(text, d, stream, 1);
}
public static void consoleHeader(String[] text, char d, PrintStream stream, int vSpacing) {
consoleHeader(text, d, stream, vSpacing, 2);
}
/** Prints a 'header' in a nice format, boxed by char:
* e.g if char='*', print a 'string' like this:
* <pre>
* ************************
* * *
* * STRING *
* * *
* ************************
* </pre>
* @param text An array of Strings, where each element is a different row of the header
* @param d (Optional) The box delimiter (default: '*')
* @param stream (Optional) A PrintStream where to output (default: System.out)
* @param vSpacing (Optional) the number of lines to leave before and after the strings (default: 1)
* @param hSpacing (Optional) the number of characters to leave before and after each line (default: 2)
*/
public static void consoleHeader(String[] text, char d, PrintStream stream, int vSpacing, int hSpacing) {
/* First, get maximum length of a row */
int maxLen = 0;
for(String s : text) {
if(s.length() > maxLen) maxLen = s.length();
}
maxLen += hSpacing; // leave some space
StringBuilder sb = new StringBuilder("");
for(int i = 0; i < maxLen; ++i)
sb.append(d);
/* Print first line of box */
stream.format("%c%-"+maxLen+"s%c\n",d,sb.toString(),d);
/* Print leading vertical gap */
for(int i = 0; i < vSpacing; ++i)
stream.format("%c%-"+maxLen+"s%c\n",d," ",d);
/* Print content lines (centered) */
for(String s : text) {
int lineLen = (maxLen-s.length())/2 + s.length() + (maxLen-s.length())/2;
if(Debug.pedantic) printDebug("consoleHeader - lineLen="+lineLen+", maxLen="+maxLen);
/* This is to fix integer rounding issues which may cause disalignment */
if(lineLen < maxLen)
stream.format("%c%-"+((maxLen-s.length())/2)+"s%s%-"+((maxLen-s.length())/2+1)+"s%c\n",d," ",s," ",d);
else
stream.format("%c%-"+((maxLen-s.length())/2)+"s%s%-"+((maxLen-s.length())/2)+"s%c\n",d," ",s," ",d);
}
/* Print trailing vertical gap */
for(int i = 0; i < vSpacing; ++i)
stream.format("%c%-"+maxLen+"s%c\n",d," ",d);
/* Print last line */
stream.format("%c%-"+maxLen+"s%c\n",d,sb.toString(),d);
}
public static void printDamageMsg(Pony pony,int inflictedDamage) {
if(Battle.SHOW_HP_PERC) printMsg(pony.getNickname()+" lost "+(int)(100.*inflictedDamage/pony.maxhp())+"% of its HP!");
else printMsg(pony.getNickname()+" lost "+inflictedDamage+" HP!");
}
/** This is a hand-made function that converts some HTML entities to their entity number;
* in future this may be replaced by a more advanced sanitizer.
*/
public static String sanitize(String str) {
return str
.replaceAll("<","<")
.replaceAll(">",">")
.replaceAll("/","/")
// remove "zalgo" effect (thanks, Zarel)
.replaceAll("[\u0300-\u036f\u0483-\u0489\u0E31\u0E34-\u0E3A\u0E47-\u0E4E]{3,}","");
}
/** Given a char[], gives back a byte[], using UTF-8 encoding. */
public static byte[] charsToBytes(char[] chars) {
CharBuffer charBuffer = CharBuffer.wrap(chars);
ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
byteBuffer.position(), byteBuffer.limit());
Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data
Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
return bytes;
}
/** Given a number of _seconds, returns a human-readable date in
* format days : hours : minutes : seconds
*/
public static String secondsToDate(long _seconds) {
int days;
int hours;
int minutes;
int seconds;
days = (int)(_seconds / 86400);
hours = (int)((_seconds % 86400) / 3600);
minutes = (int)((_seconds % 3600) / 60);
seconds = (int)(_seconds % 60);
return (days > 0 ? days + "d" : "") +
(hours > 0 ? hours + "h " : "") +
(minutes > 0 ? minutes + "m " : "") +
seconds + "s";
}
public static String now() {
return now("yy-MM-dd HH:mm:ss");
}
public static String now(final String format) {
return new SimpleDateFormat(format).format(new Date());
}
}
| gpl-3.0 |
kostovhg/SoftUni | Java_DBFundamentals-Jan18/DBAdvanced_HibernateSpring/c_Java_Basics/src/main/java/e_IntegerToHexAndBinary.java | 427 |
import java.util.Scanner;
public class e_IntegerToHexAndBinary {
public static void main(String[] args) {
Scanner scann = new Scanner(System.in);
Integer inputNumber = Integer.parseInt(scann.nextLine());
System.out.println(String.format("%X", inputNumber));
System.out.println(Integer.toBinaryString(inputNumber));
//System.out.println(Integer.toHexString(inputNumber));
}
}
| gpl-3.0 |
GlowstoneMC/Glowkit-Legacy | src/main/java/org/bukkit/material/Banner.java | 5170 | package org.bukkit.material;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
/**
* MaterialData for placed Banners
*/
public class Banner extends MaterialData implements Attachable {
public Banner() {
super(Material.STANDING_BANNER);
}
/**
* @deprecated Magic value
*/
@Deprecated
public Banner(final int type) {
super(type);
}
public Banner(final Material type) {
super(type);
}
/**
* @deprecated Magic value
*/
@Deprecated
public Banner(final int type, final byte data) {
super(type, data);
}
/**
* @deprecated Magic value
*/
@Deprecated
public Banner(final Material type, final byte data) {
super(type, data);
}
/**
* Check whether this Banner is attached to a wall.
*
* @return true if Banner is attached to a wall, false if on top of a block
*/
public boolean isWallBanner() {
return getItemType() == Material.WALL_BANNER;
}
@Override
public BlockFace getAttachedFace() {
if (!isWallBanner()) {
return BlockFace.DOWN;
}
byte data = getData();
switch (data) {
case 0x2:
return BlockFace.SOUTH;
case 0x3:
return BlockFace.NORTH;
case 0x4:
return BlockFace.EAST;
case 0x5:
return BlockFace.WEST;
}
return null;
}
@Override
public void setFacingDirection(BlockFace face) {
byte data;
if (isWallBanner()) {
switch (face) {
case NORTH:
data = 0x2;
break;
case SOUTH:
data = 0x3;
break;
case WEST:
data = 0x4;
break;
case EAST:
default:
data = 0x5;
}
} else {
switch (face) {
case SOUTH:
data = 0x0;
break;
case SOUTH_SOUTH_WEST:
data = 0x1;
break;
case SOUTH_WEST:
data = 0x2;
break;
case WEST_SOUTH_WEST:
data = 0x3;
break;
case WEST:
data = 0x4;
break;
case WEST_NORTH_WEST:
data = 0x5;
break;
case NORTH_WEST:
data = 0x6;
break;
case NORTH_NORTH_WEST:
data = 0x7;
break;
case NORTH:
data = 0x8;
break;
case NORTH_NORTH_EAST:
data = 0x9;
break;
case NORTH_EAST:
data = 0xA;
break;
case EAST_NORTH_EAST:
data = 0xB;
break;
case EAST:
data = 0xC;
break;
case EAST_SOUTH_EAST:
data = 0xD;
break;
case SOUTH_SOUTH_EAST:
data = 0xF;
break;
case SOUTH_EAST:
default:
data = 0xE;
}
}
setData(data);
}
@Override
public BlockFace getFacing() {
byte data = getData();
if (isWallBanner()) {
return getAttachedFace().getOppositeFace();
}
switch (data) {
case 0x0:
return BlockFace.SOUTH;
case 0x1:
return BlockFace.SOUTH_SOUTH_WEST;
case 0x2:
return BlockFace.SOUTH_WEST;
case 0x3:
return BlockFace.WEST_SOUTH_WEST;
case 0x4:
return BlockFace.WEST;
case 0x5:
return BlockFace.WEST_NORTH_WEST;
case 0x6:
return BlockFace.NORTH_WEST;
case 0x7:
return BlockFace.NORTH_NORTH_WEST;
case 0x8:
return BlockFace.NORTH;
case 0x9:
return BlockFace.NORTH_NORTH_EAST;
case 0xA:
return BlockFace.NORTH_EAST;
case 0xB:
return BlockFace.EAST_NORTH_EAST;
case 0xC:
return BlockFace.EAST;
case 0xD:
return BlockFace.EAST_SOUTH_EAST;
case 0xE:
return BlockFace.SOUTH_EAST;
case 0xF:
return BlockFace.SOUTH_SOUTH_EAST;
}
return null;
}
@Override
public String toString() {
return super.toString() + " facing " + getFacing();
}
@Override
public Banner clone() {
return (Banner) super.clone();
}
}
| gpl-3.0 |
Pikamander2/japanese-characters | app/src/androidTest/java/com/pikamander2/japanesequizz/ExampleInstrumentedTest.java | 753 | package com.pikamander2.japanesequizz;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("pikamander2.com.japchar", appContext.getPackageName());
}
}
| gpl-3.0 |
seshurajup/phrasal | src/edu/stanford/nlp/mt/decoder/recomb/TranslationNgramRecombinationFilter.java | 2801 | package edu.stanford.nlp.mt.decoder.recomb;
import java.util.LinkedList;
import java.util.List;
import edu.stanford.nlp.mt.decoder.feat.DerivationFeaturizer;
import edu.stanford.nlp.mt.decoder.feat.Featurizer;
import edu.stanford.nlp.mt.decoder.feat.FeaturizerState;
import edu.stanford.nlp.mt.decoder.feat.base.NGramLanguageModelFeaturizer;
import edu.stanford.nlp.mt.decoder.util.Derivation;
import edu.stanford.nlp.mt.lm.LMState;
import edu.stanford.nlp.mt.util.IString;
/**
* Implements n-gram language model recombination.
*
* @author Spence Green
*
*/
public class TranslationNgramRecombinationFilter
implements RecombinationFilter<Derivation<IString, String>> {
private final List<DerivationFeaturizer<IString,String>> lmFeaturizers;
/**
* Constructor.
*
* @param featurizers
*/
public TranslationNgramRecombinationFilter(
List<Featurizer<IString, String>> featurizers) {
lmFeaturizers = new LinkedList<>();
for (Featurizer<IString,String> featurizer : featurizers) {
if (featurizer instanceof NGramLanguageModelFeaturizer) {
lmFeaturizers.add((NGramLanguageModelFeaturizer) featurizer);
}
}
}
@Override
public boolean combinable(Derivation<IString, String> hypA, Derivation<IString, String> hypB) {
if (hypA.featurizable == null && hypB.featurizable == null) {
// null hypothesis
return true;
} else if (hypA.featurizable == null || hypB.featurizable == null) {
// one or the other is the null hypothesis
return false;
}
for (DerivationFeaturizer<IString,String> lmFeaturizer : lmFeaturizers) {
FeaturizerState stateA = (FeaturizerState) hypA.featurizable.getState(lmFeaturizer);
FeaturizerState stateB = (FeaturizerState) hypB.featurizable.getState(lmFeaturizer);
// Do the two states hash to the same bucket?
if ( ! (stateA.hashCode() == stateB.hashCode() &&
stateA.equals(stateB))) {
return false;
}
}
return true;
}
@Override
public long recombinationHashCode(Derivation<IString, String> hyp) {
if (hyp.featurizable == null) {
// null hypothesis. This hashCode doesn't actually matter because of the checks
// in the combinable() function above.
return hyp.sourceSequence.hashCode();
}
int maxLength = -1;
int hashCode = 0;
for (DerivationFeaturizer<IString,String> lmFeaturizer : lmFeaturizers) {
LMState state = (LMState) hyp.featurizable.getState(lmFeaturizer);
if (state.length() > maxLength) {
maxLength = state.length();
hashCode = state.hashCode();
}
}
assert maxLength >= 0;
return hashCode;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| gpl-3.0 |
sistemi-territoriali/StatPortalOpenData | StatPortalOpenData/src/it/sister/statportal/odata/navigationproperty/NodeRows.java | 463 | package it.sister.statportal.odata.navigationproperty;
import it.sister.statportal.odata.JITProducer;
import it.sister.statportal.odata.StatPortalJPAProducer;
import org.odata4j.edm.EdmDataServices;
public class NodeRows extends Rows {
public NodeRows(StatPortalJPAProducer baseProducer,
JITProducer jitProducer, String namespace,
EdmDataServices edmDataServices) {
super(baseProducer, jitProducer, namespace, edmDataServices);
}
}
| gpl-3.0 |
AKD92/Very-Simple-Messenger-V2 | src/net/vsmudp/gui/util/GUIUtils.java | 2615 | package net.vsmudp.gui.util;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.KeyboardFocusManager;
import javax.swing.*;
import net.vsmudp.Application;
public class GUIUtils {
static final String STR_COPYMENU_LABEL,
STR_CAPTUREMENU_LABEL;
static {
STR_COPYMENU_LABEL = "Copy text to clipboard";
STR_CAPTUREMENU_LABEL = "Capture web addresses";
}
public static void sizeMenuProperly(JPopupMenu menu) {
JMenuItem item = null;
Dimension size = null;
MenuElement[] menus = menu.getSubElements();
for (MenuElement x : menus) {
item = (JMenuItem) x;
if (item != null) {
size = item.getPreferredSize();
size.height += 2;
item.setPreferredSize(size);
}
}
}
public static void sizeMenuProperly(JMenu mnu) {
sizeMenuProperly(mnu.getPopupMenu());
}
public static JPopupMenu createPopupForMessageList(JList msgList) {
JPopupMenu listMenu;
JMenuItem mntmCopy;
JMenuItem mntmCaptureURL;
listMenu = new JPopupMenu();
mntmCopy = new JMenuItem(STR_COPYMENU_LABEL);
mntmCopy.addActionListener(new CopyTextHandler(msgList));
listMenu.add(mntmCopy);
mntmCaptureURL = new JMenuItem(STR_CAPTUREMENU_LABEL);
mntmCaptureURL.addActionListener(new CaptureWebAddressHandler(msgList));
listMenu.add(mntmCaptureURL);
listMenu.pack();
sizeMenuProperly(listMenu);
msgList.addMouseListener(new MessageListPopupHandler(listMenu));
return listMenu;
}
private static boolean isOwnsShowing(Window[] all) {
boolean res = false;
for (Window x : all) {
if (x.isShowing() == true) {
res= true;
break;
}
}
return res;
}
// get the current active window
private static Window getActiveWindow(Window start) {
if (start.isShowing() == true) {
Window[] owns = start.getOwnedWindows();
boolean isThis = owns == null || owns.length == 0 || isOwnsShowing(owns) == false;
if (isThis == true) return start;
else {
Window res = null;
for (Window x : owns) {
Window gres = getActiveWindow(x);
if (gres != null) {
res = gres;
break;
}
}
return res;
}
}
else {
return null;
}
}
public static Window getActiveWindow() {
KeyboardFocusManager kfg = KeyboardFocusManager.getCurrentKeyboardFocusManager();
Window win = kfg.getActiveWindow();
if (win == null) {
win = (Window) Application.getInstance().getMainViewer();
win = getActiveWindow(win);
}
return win;
}
}
| gpl-3.0 |
dmolony/DiskBrowser | src/com/bytezone/diskbrowser/nib/V2dFile.java | 3732 | package com.bytezone.diskbrowser.nib;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import com.bytezone.diskbrowser.utilities.HexFormatter;
import com.bytezone.diskbrowser.utilities.Utility;
/*
* from Gerard Putter's email:
* Offsets in bytes
* From To Meaning
* 0000 0003 Length of disk image, from offset 8 to the end (big endian)
* 0004 0007 Type indication; always 'D5NI'
* 0008 0009 Number of tracks (typical value: $23, but can be different). Also big endian.
* 000A 000B Track nummer * 4, starting with track # 0. Big endian.
* 000C 000D Length of track, not counting this length-field. Big endian.
* 000E 000E + length field - 1 Nibble-data of track, byte-for-byte.
* After this, the pattern from offset 000A repeats for each track. Note that
* "track number * 4" means that on a regular disk the tracks are numbered 0, 4, 8 etc.
* Half-tracks are numbered 2, 6, etc. The stepper motor of the disk uses 4 phases to
* travel from one track to the next, so quarter-tracks could also be stored with this
* format (I have never heard of disk actually using quarter tracks, though).
*/
// Physical disk interleave:
// Info from http://www.applelogic.org/TheAppleIIEGettingStarted.html
// Block ..: 0 1 2 3 4 5 6 7 8 9 A B C D E F
// Position: 0 8 1 9 2 A 3 B 4 C 5 D 6 E 7 F - Prodos (.PO disks)
// Position: 0 7 E 6 D 5 C 4 B 3 A 2 9 1 8 F - Dos (.DO disks)
public class V2dFile
{
// private static int[][] interleave =
// { { 0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15 },
// { 0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15 } };
// private static final int DOS = 0;
// private static final int PRODOS = 1;
private static final int TRACK_LENGTH = 6304;
private final Nibblizer nibbler;
public final File file;
final int tracks;
final byte[] diskBuffer = new byte[4096 * 35];
public V2dFile (File file)
{
this.file = file;
int tracks = 0;
nibbler = new Nibblizer ();
try
{
byte[] header = new byte[10];
BufferedInputStream in = new BufferedInputStream (new FileInputStream (file));
in.read (header);
int diskLength = Utility.getLongBigEndian (header, 0); // 4 bytes
String id = HexFormatter.getString (header, 4, 4); // 4 bytes
tracks = Utility.getShortBigEndian (header, 8); // 2 bytes
assert diskLength + 8 == file.length ();
assert "D5NI".equals (id);
byte[] trackHeader = new byte[4];
byte[] trackData = new byte[TRACK_LENGTH];
for (int i = 0; i < tracks; i++)
{
in.read (trackHeader);
int trackNumber = Utility.getShortBigEndian (trackHeader, 0);
int trackLength = Utility.getShortBigEndian (trackHeader, 2); // 6304
assert trackLength == TRACK_LENGTH;
int dataRead = in.read (trackData);
assert dataRead == TRACK_LENGTH;
int fullTrackNo = trackNumber / 4;
int halfTrackNo = trackNumber % 4;
if (halfTrackNo == 0) // only process full tracks
nibbler.processTrack (fullTrackNo, 16, trackData, diskBuffer);
else
System.out.printf ("%s skipping half track %02X / %02X%n", file.getName (),
fullTrackNo, halfTrackNo);
}
in.close ();
}
catch (IOException e)
{
e.printStackTrace ();
}
this.tracks = tracks;
}
// ---------------------------------------------------------------------------------//
// getDiskBuffer
// ---------------------------------------------------------------------------------//
public byte[] getDiskBuffer ()
{
return diskBuffer;
}
} | gpl-3.0 |
Waikato/meka | src/main/java/meka/classifiers/multitarget/IncrementalMultiTargetClassifier.java | 1089 | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* IncrementalMultiTargetClassifier.java
* Copyright (C) 2015 University of Waikato, Hamilton, NZ
*/
package meka.classifiers.multitarget;
import weka.classifiers.UpdateableClassifier;
/**
* Interface for incremental multi-target classifiers.
*
* @author Joerg Wicker
* @version $Revision$
*/
public interface IncrementalMultiTargetClassifier
extends MultiTargetClassifier, UpdateableClassifier{
}
| gpl-3.0 |
janov/robocode | src/voidious/move/formulas/FlattenerFormula.java | 1803 | package voidious.move.formulas;
import robocode.Rules;
import voidious.utils.DistanceFormula;
import voidious.utils.Wave;
/**
* Copyright (c) 2009-2012 - Voidious
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
public class FlattenerFormula extends DistanceFormula {
public FlattenerFormula() {
weights = new double[]{3, 4, 3, 5, 1, 4, 3, 3, 2, 2, 2};
}
@Override
public double[] dataPointFromWave(Wave w, boolean aiming) {
return new double[]{
(Math.min(91, w.targetDistance / w.bulletSpeed()) / 91),
(((w.targetVelocitySign * w.targetVelocity) + 0.1) / 8.1),
(Math.sin(w.targetRelativeHeading)),
((Math.cos(w.targetRelativeHeading) + 1) / 2),
(((w.targetAccel / (w.targetAccel < 0
? Rules.DECELERATION : Rules.ACCELERATION)) + 1) / 2),
(Math.min(1.0, w.targetWallDistance) / 1.0),
(Math.min(1.0, w.targetRevWallDistance) / 1.0),
(Math.min(1, ((double) w.targetVchangeTime)
/ (w.targetDistance/w.bulletSpeed()))),
(w.targetDl8t / 64),
(w.targetDl20t / 160),
(w.targetDl40t / 320),
};
}
}
| gpl-3.0 |
derkaiserreich/structr | structr-core/src/main/java/org/structr/core/function/Functions.java | 14255 | /**
* Copyright (C) 2010-2016 Structr GmbH
*
* This file is part of Structr <http://structr.org>.
*
* Structr is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Structr is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Structr. If not, see <http://www.gnu.org/licenses/>.
*/
package org.structr.core.function;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.text.Normalizer;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.structr.common.error.FrameworkException;
import org.structr.core.GraphObject;
import org.structr.core.parser.ArrayExpression;
import org.structr.core.parser.CacheExpression;
import org.structr.core.parser.ConstantExpression;
import org.structr.core.parser.EachExpression;
import org.structr.core.parser.Expression;
import org.structr.core.parser.FilterExpression;
import org.structr.core.parser.FunctionExpression;
import org.structr.core.parser.FunctionValueExpression;
import org.structr.core.parser.GroupExpression;
import org.structr.core.parser.IfExpression;
import org.structr.core.parser.NullExpression;
import org.structr.core.parser.RootExpression;
import org.structr.core.parser.ValueExpression;
import org.structr.core.parser.function.PrivilegedFindFunction;
import org.structr.schema.action.ActionContext;
import org.structr.schema.action.Function;
/**
*
*
*/
public class Functions {
public static final Map<String, Function<Object, Object>> functions = new LinkedHashMap<>();
public static final String NULL_STRING = "___NULL___";
public static Function<Object, Object> get(final String name) {
return functions.get(name);
}
public static Object evaluate(final ActionContext actionContext, final GraphObject entity, final String expression) throws FrameworkException {
final String expressionWithoutNewlines = expression.replace('\n', ' ');
final StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(expressionWithoutNewlines));
tokenizer.eolIsSignificant(true);
tokenizer.ordinaryChar('.');
tokenizer.wordChars('_', '_');
tokenizer.wordChars('.', '.');
tokenizer.wordChars('!', '!');
Expression root = new RootExpression();
Expression current = root;
Expression next = null;
String lastToken = null;
int token = 0;
int level = 0;
while (token != StreamTokenizer.TT_EOF) {
token = nextToken(tokenizer);
switch (token) {
case StreamTokenizer.TT_EOF:
break;
case StreamTokenizer.TT_EOL:
break;
case StreamTokenizer.TT_NUMBER:
if (current == null) {
throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before NUMBER");
}
next = new ConstantExpression(tokenizer.nval);
current.add(next);
lastToken += "NUMBER";
break;
case StreamTokenizer.TT_WORD:
if (current == null) {
throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + tokenizer.sval);
}
next = checkReservedWords(tokenizer.sval);
Expression previousExpression = current.getPrevious();
if (tokenizer.sval.startsWith(".") && previousExpression != null && previousExpression instanceof FunctionExpression && next instanceof ValueExpression) {
final FunctionExpression previousFunctionExpression = (FunctionExpression) previousExpression;
final ValueExpression valueExpression = (ValueExpression) next;
current.replacePrevious(new FunctionValueExpression(previousFunctionExpression, valueExpression));
} else {
current.add(next);
}
lastToken = tokenizer.sval;
break;
case '(':
if (((current == null || current instanceof RootExpression) && next == null) || current == next) {
// an additional bracket without a new function,
// this can only be an execution group.
next = new GroupExpression();
current.add(next);
}
current = next;
lastToken += "(";
level++;
break;
case ')':
if (current == null) {
throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + lastToken);
}
current = current.getParent();
if (current == null) {
throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken);
}
lastToken += ")";
level--;
break;
case '[':
// bind directly to the previous expression
next = new ArrayExpression();
current.add(next);
current = next;
lastToken += "[";
level++;
break;
case ']':
if (current == null) {
throw new FrameworkException(422, "Invalid expression: mismatched closing bracket before " + lastToken);
}
current = current.getParent();
if (current == null) {
throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken);
}
lastToken += "]";
level--;
break;
case ';':
next = null;
lastToken += ";";
break;
case ',':
next = current;
lastToken += ",";
break;
default:
if (current == null) {
throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + tokenizer.sval);
}
current.add(new ConstantExpression(tokenizer.sval));
lastToken = tokenizer.sval;
}
}
if (level > 0) {
throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken);
}
return root.evaluate(actionContext, entity);
}
private static Expression checkReservedWords(final String word) throws FrameworkException {
if (word == null) {
return new NullExpression();
}
switch (word) {
case "cache":
return new CacheExpression();
case "true":
return new ConstantExpression(true);
case "false":
return new ConstantExpression(false);
case "if":
return new IfExpression();
case "each":
return new EachExpression();
case "filter":
return new FilterExpression();
case "data":
return new ValueExpression("data");
case "null":
return new ConstantExpression(NULL_STRING);
}
// no match, try functions
final Function<Object, Object> function = Functions.get(word);
if (function != null) {
return new FunctionExpression(word, function);
} else {
return new ValueExpression(word);
}
}
public static int nextToken(final StreamTokenizer tokenizer) {
try {
return tokenizer.nextToken();
} catch (IOException ioex) {
}
return StreamTokenizer.TT_EOF;
}
static {
functions.put("error", new ErrorFunction());
functions.put("md5", new MD5Function());
functions.put("upper", new UpperFunction());
functions.put("lower", new LowerFunction());
functions.put("join", new JoinFunction());
functions.put("concat", new ConcatFunction());
functions.put("split", new SplitFunction());
functions.put("split_regex", new SplitRegexFunction());
functions.put("abbr", new AbbrFunction());
functions.put("capitalize", new CapitalizeFunction());
functions.put("titleize", new TitleizeFunction());
functions.put("num", new NumFunction());
functions.put("int", new IntFunction());
functions.put("random", new RandomFunction());
functions.put("rint", new RintFunction());
functions.put("index_of", new IndexOfFunction());
functions.put("contains", new ContainsFunction());
functions.put("substring", new SubstringFunction());
functions.put("length", new LengthFunction());
functions.put("replace", new ReplaceFunction());
functions.put("clean", new CleanFunction());
functions.put("urlencode", new UrlEncodeFunction());
functions.put("escape_javascript", new EscapeJavascriptFunction());
functions.put("escape_json", new EscapeJsonFunction());
functions.put("empty", new EmptyFunction());
functions.put("equal", new EqualFunction());
functions.put("eq", new EqualFunction());
functions.put("add", new AddFunction());
functions.put("double_sum", new DoubleSumFunction());
functions.put("int_sum", new IntSumFunction());
functions.put("is_collection", new IsCollectionFunction());
functions.put("is_entity", new IsEntityFunction());
functions.put("extract", new ExtractFunction());
functions.put("merge", new MergeFunction());
functions.put("merge_unique", new MergeUniqueFunction());
functions.put("complement", new ComplementFunction());
functions.put("unwind", new UnwindFunction());
functions.put("sort", new SortFunction());
functions.put("lt", new LtFunction());
functions.put("gt", new GtFunction());
functions.put("lte", new LteFunction());
functions.put("gte", new GteFunction());
functions.put("subt", new SubtFunction());
functions.put("mult", new MultFunction());
functions.put("quot", new QuotFunction());
functions.put("mod", new ModFunction());
functions.put("floor", new FloorFunction());
functions.put("ceil", new CeilFunction());
functions.put("round", new RoundFunction());
functions.put("max", new MaxFunction());
functions.put("min", new MinFunction());
functions.put("config", new ConfigFunction());
functions.put("date_format", new DateFormatFunction());
functions.put("parse_date", new ParseDateFunction());
functions.put("number_format", new NumberFormatFunction());
functions.put("template", new TemplateFunction());
functions.put("not", new NotFunction());
functions.put("and", new AndFunction());
functions.put("or", new OrFunction());
functions.put("get", new GetFunction());
functions.put("get_or_null", new GetOrNullFunction());
functions.put("size", new SizeFunction());
functions.put("first", new FirstFunction());
functions.put("last", new LastFunction());
functions.put("nth", new NthFunction());
functions.put("get_counter", new GetCounterFunction());
functions.put("inc_counter", new IncCounterFunction());
functions.put("reset_counter", new ResetCounterFunction());
functions.put("merge_properties", new MergePropertiesFunction());
functions.put("keys", new KeysFunction());
functions.put("values", new ValuesFunction());
functions.put("changelog", new ChangelogFunction());
functions.put("timer", new TimerFunction());
functions.put("str_replace", new StrReplaceFunction());
functions.put("find_privileged", new PrivilegedFindFunction());
// ----- BEGIN functions with side effects -----
functions.put("retrieve", new RetrieveFunction());
functions.put("store", new StoreFunction());
functions.put("print", new PrintFunction());
functions.put("log", new LogFunction());
functions.put("read", new ReadFunction());
functions.put("write", new WriteFunction());
functions.put("append", new AppendFunction());
functions.put("xml", new XmlFunction());
functions.put("xpath", new XPathFunction());
functions.put("set", new SetFunction());
functions.put("geocode", new GeocodeFunction());
functions.put("find", new FindFunction());
functions.put("search", new SearchFunction());
functions.put("create", new CreateFunction());
functions.put("delete", new DeleteFunction());
functions.put("incoming", new IncomingFunction());
functions.put("instantiate", new InstantiateFunction());
functions.put("outgoing", new OutgoingFunction());
functions.put("has_relationship", new HasRelationshipFunction());
functions.put("has_outgoing_relationship", new HasOutgoingRelationshipFunction());
functions.put("has_incoming_relationship", new HasIncomingRelationshipFunction());
functions.put("get_relationships", new GetRelationshipsFunction());
functions.put("get_outgoing_relationships", new GetOutgoingRelationshipsFunction());
functions.put("get_incoming_relationships", new GetIncomingRelationshipsFunction());
functions.put("create_relationship", new CreateRelationshipFunction());
functions.put("grant", new GrantFunction());
functions.put("revoke", new RevokeFunction());
functions.put("is_allowed", new IsAllowedFunction());
functions.put("unlock_readonly_properties_once", new UnlockReadonlyPropertiesFunction());
functions.put("unlock_system_properties_once", new UnlockSystemPropertiesFunction());
functions.put("call", new CallFunction());
functions.put("exec", new ExecFunction());
functions.put("exec_binary", new ExecBinaryFunction());
functions.put("set_privileged", new SetPrivilegedFunction());
functions.put("cypher", new CypherFunction());
functions.put("localize", new LocalizeFunction());
functions.put("property_info", new PropertyInfoFunction());
functions.put("disable_notifications", new DisableNotificationsFunction());
functions.put("enable_notifications", new EnableNotificationsFunction());
}
public static String cleanString(final Object input) {
if (input == null) {
return "";
}
String normalized = Normalizer.normalize(input.toString(), Normalizer.Form.NFD)
.replaceAll("\\<", "")
.replaceAll("\\>", "")
.replaceAll("\\.", "")
.replaceAll("\\'", "-")
.replaceAll("\\?", "")
.replaceAll("\\(", "")
.replaceAll("\\)", "")
.replaceAll("\\{", "")
.replaceAll("\\}", "")
.replaceAll("\\[", "")
.replaceAll("\\]", "")
.replaceAll("\\+", "-")
.replaceAll("/", "-")
.replaceAll("–", "-")
.replaceAll("\\\\", "-")
.replaceAll("\\|", "-")
.replaceAll("'", "-")
.replaceAll("!", "")
.replaceAll(",", "")
.replaceAll("-", " ")
.replaceAll("_", " ")
.replaceAll("`", "-");
String result = normalized.replaceAll("-", " ");
result = StringUtils.normalizeSpace(result.toLowerCase());
result = result.replaceAll("[^\\p{ASCII}]", "").replaceAll("\\p{P}", "-").replaceAll("\\-(\\s+\\-)+", "-");
result = result.replaceAll(" ", "-");
return result;
}
}
| gpl-3.0 |
isnuryusuf/ingress-indonesia-dev | apk/classes-ekstartk/com/nianticproject/ingress/common/v/ah.java | 1035 | package com.nianticproject.ingress.common.v;
import com.nianticproject.ingress.common.c.g;
public abstract interface ah
{
public abstract void A();
public abstract void a(g paramg);
public abstract void a(ai paramai);
public abstract void d();
public abstract void e();
public abstract void f();
public abstract void g();
public abstract void h();
public abstract void i();
public abstract void j();
public abstract void k();
public abstract void l();
public abstract void m();
public abstract void n();
public abstract void o();
public abstract void p();
public abstract void q();
public abstract void r();
public abstract void s();
public abstract void t();
public abstract void u();
public abstract void v();
public abstract void w();
public abstract void x();
public abstract void y();
public abstract void z();
}
/* Location: classes_dex2jar.jar
* Qualified Name: com.nianticproject.ingress.common.v.ah
* JD-Core Version: 0.6.2
*/ | gpl-3.0 |
avdata99/SIAT | siat-1.0-SOURCE/src/buss/src/ar/gov/rosario/siat/pad/buss/dao/CuentaTitularDAO.java | 19168 | //Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda.
//This file is part of SIAT. SIAT is licensed under the terms
//of the GNU General Public License, version 3.
//See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt>
package ar.gov.rosario.siat.pad.buss.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.classic.Session;
import ar.gov.rosario.siat.base.buss.dao.GenericDAO;
import ar.gov.rosario.siat.base.buss.dao.SiatHibernateUtil;
import ar.gov.rosario.siat.base.iface.model.SiatParam;
import ar.gov.rosario.siat.pad.buss.bean.Contribuyente;
import ar.gov.rosario.siat.pad.buss.bean.Cuenta;
import ar.gov.rosario.siat.pad.buss.bean.CuentaTitular;
import ar.gov.rosario.siat.pad.buss.bean.Cuit;
import coop.tecso.demoda.buss.helper.LogFile;
import coop.tecso.demoda.iface.helper.DateUtil;
import coop.tecso.demoda.iface.helper.DemodaUtil;
import coop.tecso.demoda.iface.model.SiNo;
public class CuentaTitularDAO extends GenericDAO {
private Logger log = Logger.getLogger(CuentaTitularDAO.class);
private static long migId = -1;
public CuentaTitularDAO() {
super(CuentaTitular.class);
}
/**
* Obtiene la lista de cuentas del Contribuyente ordenadas por descripcion del recurso y por fecha desde
* @param contribuyente
* @return List<CuentaTitular>
*/
public List<CuentaTitular> getListOrderByRecursoFecDesde(Contribuyente contribuyente){
Session session = SiatHibernateUtil.currentSession();
String consulta = "FROM CuentaTitular ct WHERE ct.contribuyente = :contribuyente " +
"ORDER BY ct.cuenta.recurso.desRecurso, ct.fechaDesde ";
Query query = session.createQuery(consulta).setEntity("contribuyente", contribuyente );
return (ArrayList<CuentaTitular>) query.list();
}
/**
* Determina si el Contribuyente registra ser titular de cuenta
* @param contribuyente
* @return Boolean
*/
public Boolean registraTitularDeCuentaByContribuyente(Contribuyente contribuyente){
Session session = SiatHibernateUtil.currentSession();
String sQuery = "SELECT COUNT(ct) FROM CuentaTitular ct " +
" WHERE ct.contribuyente = :contribuyente ";
Query query = session.createQuery(sQuery).setEntity("contribuyente", contribuyente );
Long cantidad = (Long) query.uniqueResult();
return cantidad > 0;
}
/**
* Obtiene la CuentaTitular para la Cuenta y el Contribuyente indicados
* @param cuenta, contribuyente
* @return cuentaTitular
*/
public CuentaTitular getByCuentaYContribuyente(Cuenta cuenta, Contribuyente contribuyente){
Session session = SiatHibernateUtil.currentSession();
String queryString = "FROM CuentaTitular c " +
" WHERE c.cuenta.id = " + cuenta.getId()+
" AND c.contribuyente.id = " + contribuyente.getId() +
" AND (c.fechaHasta is null OR c.fechaHasta > TO_DATE('" +
DateUtil.formatDate(new Date(), DateUtil.ddSMMSYYYY_MASK) + "','%d/%m/%Y')) ";
Query query = session.createQuery(queryString);
CuentaTitular cuentaTitular = (CuentaTitular) query.uniqueResult();
return cuentaTitular;
}
/**
* Obtiene las CuentaTitular para la Cuenta y fecha de vigencia desde indicados
* Ordenado de tal manera que aparece primiero el titular principal.
* No cambiar este orden.
*
* @param cuenta, contribuyente
* @return cuentaTitular
*/
public List<CuentaTitular> getByCuentaYFechaVigencia(Cuenta cuenta, Date fecha){
Session session = SiatHibernateUtil.currentSession();
String queryString = "FROM CuentaTitular c " +
" WHERE c.cuenta.id = " + cuenta.getId();
queryString += " AND (c.fechaHasta is null OR c.fechaHasta > TO_DATE('" +
DateUtil.formatDate(fecha, DateUtil.ddSMMSYYYY_MASK) + "','%d/%m/%Y')) " +
" ORDER BY esTitularPrincipal DESC";
Query query = session.createQuery(queryString);
return (ArrayList<CuentaTitular>) query.list();
}
/**
* Obtiene la cuenta titular principal para la cuenta dada.
* Si la cuenta no tiene tiene titulares principales vigentes,
* retorna la cuentatitular con mayor id
* Si la cuenta no tiene titulares devuelve null
* @param cuenta
* @return CuentaTitular
*/
public CuentaTitular getPrincipalByCuenta(Cuenta cuenta) throws Exception {
Session session = SiatHibernateUtil.currentSession();
String queryString = "FROM CuentaTitular ct " +
" WHERE ct.cuenta.id = " + cuenta.getId() +
" and (ct.fechaHasta is null or ct.fechaHasta > :fechaVig)" +
" AND ct.esTitularPrincipal = " + SiNo.SI.getId();
//" ORDER BY id desc";
Query query = session.createQuery(queryString);
query.setParameter("fechaVig", new Date());
CuentaTitular titular = (CuentaTitular) query.uniqueResult();
return titular;
//List<CuentaTitular> listTitular = query.list();
/*if (listTitular.isEmpty()) {
//cuenta.addRecoverableValueError("La Cuenta " + cuenta.getNumeroCuenta() + " no posee titulares.");
return null;
}
//buscamos el primero que esta marcado como principal.
for(CuentaTitular ct : listTitular) {
if (SiNo.SI.getId().equals(ct.getEsTitularPrincipal())) {
return ct;
}
}
//si estoy aca es que no econtre un titular principal.
return listTitular.get(0);
*/
}
/**
* Devuelve el proximo valor de id a asignar.
* Para se inicializa obteniendo el ultimo id asignado el archivo de migracion con datos pasados como parametro
* y luego en cada llamada incrementa el valor.
*
* @return long - el proximo id a asignar.
* @throws Exception
*/
public long getNextId(String path, String nameFile) throws Exception{
// Si migId==-1 buscar MaxId en el archivo de load. Si migId!=-1, migId++ y retornar migId;
if(getMigId()==-1){
setMigId(this.getLastId(path, nameFile)+1);
}else{
setMigId(getMigId() + 1);
}
return getMigId();
}
/**
* Inserta una linea con los datos de la CuentaTitular para luego realizar un load desde Informix.
* (la linea se inserta en el archivo pasado como parametro a traves del LogFile)
* @param cuentaTitular, output - La CuentaTitular a crear y el Archivo al que se le agrega la linea.
* @return long - El id generado.
* @throws Exception
*/
public Long createForLoad(CuentaTitular o, LogFile output) throws Exception {
// Obtenemos el valor del id autogenerado a insertar.
long id = getNextId(output.getPath(), output.getNameFile());
// Estrucura de la linea:
// id|idcuenta|idcontribuyente|idtipotitular|estitularprincipal|fechadesde|fechanovedad|esaltamanual|usuario|fechaultmdf|estado|
StringBuffer line = new StringBuffer();
line.append(id);
line.append("|");
line.append(o.getCuenta().getId());
line.append("|");
line.append(o.getContribuyente().getId());
line.append("|");
line.append(o.getTipoTitular().getId());
line.append("|");
line.append(o.getEsTitularPrincipal());
line.append("|");
line.append(DateUtil.formatDate(o.getFechaDesde(), "yyyy-MM-dd"));
line.append("|");
if(o.getFechaNovedad()!=null){
line.append(DateUtil.formatDate(o.getFechaNovedad(), "yyyy-MM-dd"));
} // Si es null no se inserta nada, viene el proximo pipe.
line.append("|");
line.append(o.getEsAltaManual());
line.append("|");
line.append(DemodaUtil.currentUserContext().getUserName());
line.append("|");
line.append("2010-01-01 00:00:00");
line.append("|");
line.append("1");
line.append("|");
if(o.getFechaHasta()!=null){
line.append(DateUtil.formatDate(o.getFechaHasta(), "yyyy-MM-dd"));
} // Si es null no se inserta nada, viene el proximo pipe.
line.append("|");
output.addline(line.toString());
// Seteamos el id generado en el bean.
o.setId(id);
return id;
}
/**
* Obtiene las cuentas titular vigentes para una cuenta en una fecha
* Poniendo el titular principal al principio de la lista.
* (No cambiar este orden.)
* @param cuenta
* @param fecha
* @return List<CuentaTitular>
*/
public List<CuentaTitular> getListCuentaTitularVigentes(Cuenta cuenta, Date fecha) {
Session session = SiatHibernateUtil.currentSession();
String queryString = "FROM CuentaTitular ct " +
" WHERE ct.cuenta = :cuenta " +
" AND ct.fechaDesde <= :fecha " +
" AND (ct.fechaHasta IS NULL OR ct.fechaHasta > :fecha) " +
" order by esTitularPrincipal desc";
Query query = session.createQuery(queryString)
.setEntity("cuenta", cuenta)
.setDate("fecha", fecha);
return (ArrayList<CuentaTitular>) query.list();
}
/**
* Obtiene las cuentas titular vigentes para una cuenta en una fecha,
* considerando un intervalo de tiempo cerrado.
*
* Pone el titular principal al principio de la lista.
* (No cambiar este orden.)
* @param cuenta
* @param fecha
* @return List<CuentaTitular>
*/
public List<CuentaTitular> getListCuentaTitularVigentesCerrado(Cuenta cuenta, Date fecha) {
Session session = SiatHibernateUtil.currentSession();
String queryString = "FROM CuentaTitular ct " +
" WHERE ct.cuenta = :cuenta " +
" AND ct.fechaDesde <= :fecha " +
" AND (ct.fechaHasta IS NULL OR ct.fechaHasta >= :fecha) " +
" order by esTitularPrincipal desc";
Query query = session.createQuery(queryString)
.setEntity("cuenta", cuenta)
.setDate("fecha", fecha);
return (ArrayList<CuentaTitular>) query.list();
}
/**
* Retorna el nombre y apellido o descripcion juridica del titular principal de la cuenta.
* <p>Si chekOtros es true, verficia si existes algun otro titular vigente al dia de hoy y agrega la cadena "y Otros" en caso que exista alguno mas del principal.
* <p>Si la cuenta no tiene ningun titular principal retorna, retorna el de mayor id de CuentaTitular (osea el ultimo insertado.)
* <p>Si la cuenta no tiene ningun titular de cuenta, retorna "";
*/
public String getNombreTitularPrincipal(Cuenta cuenta, boolean checkOtros) throws Exception {
String funcName = DemodaUtil.currentMethodName();
if (log.isDebugEnabled()) log.debug(funcName + ": enter");
Connection con;
PreparedStatement ps;
ResultSet rs;
long count = 0;
String ret = "";
String apellido = "";
String nombre = "";
// ahora nos conseguimos la connection JDBC de hibernate...
SiatHibernateUtil.currentSession().flush();
con = currentSession().connection();
String generalDbName = SiatParam.getGeneralDbName();
String sql = "select cuentatit.id, cuentatit.esTitularPrincipal, pid.id_persona, per.apellido, per.nombre_per from ";
sql += " pad_cuentatitular cuentatit ";
sql += " INNER JOIN " + generalDbName + ":persona_id pid on (pid.id_persona = cuentatit.idContribuyente) ";
sql += " INNER JOIN " + generalDbName + ":personas per on (pid.cuit00 = per.cuit00 and pid.cuit01 = per.cuit01 and pid.cuit02 = per.cuit02 and pid.cuit03 = per.cuit03) ";
sql += " where ";
sql += " cuentatit.idCuenta = ?" ;
sql += " and (cuentatit.fechaHasta is null or cuentatit.fechaHasta > ?) ";
sql += " order by cuentatit.esTitularPrincipal desc, cuentatit.id desc";
// ejecucion de la consulta de resultado
if (log.isDebugEnabled()) log.debug("queryString: " + sql + " idcuenta=" + cuenta.getId() + " fechaDesde= ahora!");
ps = con.prepareStatement(sql);
ps.setLong(1, cuenta.getId());
ps.setTimestamp(2, new Timestamp(new Date().getTime()));
rs = ps.executeQuery();
//probamos si es persona fisica
while(rs.next()) {
if (count == 0) {
apellido = rs.getString("apellido");
nombre = rs.getString("nombre_per");
}
count++;
if (!checkOtros)
break;
}
rs.close();
ps.close();
//probamos si es persona juridica
if (count == 0) {
sql = "select cuentatit.id, cuentatit.esTitularPrincipal, pid.id_persona, soc.razon_soc from ";
sql += " pad_cuentatitular cuentatit ";
sql += " INNER JOIN " + generalDbName + ":persona_id pid on (pid.id_persona = cuentatit.idContribuyente) ";
sql += " INNER JOIN " + generalDbName + ":sociedades soc on (pid.cuit00 = soc.cuit00_soc and pid.cuit01 = soc.cuit01_soc and pid.cuit02 = soc.cuit02_soc and pid.cuit03 = soc.cuit03_soc) ";
sql += " where ";
sql += " cuentatit.idCuenta = ?" ;
sql += " and (cuentatit.fechaHasta is null or cuentatit.fechaHasta > ?) ";
sql += " order by cuentatit.esTitularPrincipal desc, cuentatit.id desc";
if (log.isDebugEnabled()) log.debug("queryString: " + sql + " idcuenta=" + cuenta.getId() + " fechaDesde= ahora!");
ps = con.prepareStatement(sql);
ps.setLong(1, cuenta.getId());
ps.setTimestamp(2, new Timestamp(new Date().getTime()));
rs = ps.executeQuery();
while(rs.next()) {
if (count == 0) {
apellido = rs.getString("razon_soc");
nombre = "";
}
count++;
if (!checkOtros)
break;
}
rs.close();
ps.close();
}
if (count>0) {
if (nombre == null) nombre = "";
if (apellido == null) apellido = "";
ret = apellido.trim() + " " + nombre.trim();
ret = ret.toUpperCase();
if (count > 1) ret += " Y OTROS";
}
if (log.isDebugEnabled()) log.debug(funcName + ": exit");
return ret;
}
//TODO: para usar en la migracion. Hay que hacer que filtre por idContribuyente, no por idCuenta
public Cuit getCuit(Cuenta cuenta) throws Exception {
Connection con;
PreparedStatement ps;
ResultSet rs;
// ahora nos conseguimos la connection JDBC de hibernate...
con = currentSession().connection();
String generalDbName = SiatParam.getGeneralDbName();
String sql = "select pid.cuit00, pid.cuit01, pid.cuit02, pid.cuit03 from ";
sql += " pad_cuentatitular cuentatit ";
sql += " INNER JOIN " + generalDbName + ":persona_id pid on (pid.id_persona = cuentatit.idContribuyente) ";
sql += " where ";
sql += " cuentatit.idCuenta = ?" ;
if (log.isDebugEnabled()) log.debug("queryString: " + sql + " idcuenta=" + cuenta.getId() + " fechaDesde= ahora!");
ps = con.prepareStatement(sql);
ps.setLong(1, cuenta.getId());
rs = ps.executeQuery();
while(rs.next()) {
log.debug(rs.getObject(1));
log.debug(rs.getObject(2));
log.debug(rs.getObject(3));
log.debug(rs.getObject(4));
}
rs.close();
ps.close();
return null;
}
/**
* Devuelve una lista de Ids de las Cuentas que tienen un unico Titular y no es principal.
* (usado en la migracion para completar los titulares principales)
*
* @return
*/
public List<Long> getListIdCuentaWithOneTitular(){
List<Object[]> listIdCuenta;
Session session = SiatHibernateUtil.currentSession();
String querySQLString = "select idcuenta, max(estitularprincipal) from pad_cuentatitular" +
" group by idcuenta having count(idcuenta) = 1 and max(estitularprincipal) = 0" +
" order by idcuenta";
//select idcuenta, max(estitularprincipal)
//from pad_cuentatitular
//group by idcuenta
//having count(idcuenta) = 1 and max(estitularprincipal) = 0
//order by idcuenta
Query query = session.createSQLQuery(querySQLString);
listIdCuenta = (ArrayList<Object[]>) query.list();
List<Long> listIdCuentaLong = new ArrayList<Long>();
for(Object[] idCta:listIdCuenta){
if(idCta != null)
listIdCuentaLong.add(new Long((Integer) idCta[0]));
}
return listIdCuentaLong;
}
/**
* Obtiene un mapa con idCuenta y idPersona.
*
* @return mapa
*/
public Map<String, String> getMapaTitularPrincipalYCuenta() throws Exception {
Session session = SiatHibernateUtil.currentSession();
Map<String, String> mapCtaPer = new HashMap<String, String>();
String querySQLString = "select idCuenta, idContribuyente FROM pad_CuentaTitular ct " +
" WHERE (ct.fechaHasta is null or ct.fechaHasta > :fechaVig)" +
" AND ct.esTitularPrincipal = " + SiNo.SI.getId();
Query query = session.createSQLQuery(querySQLString);
query.setParameter("fechaVig", new Date());
//CuentaTitular titular = (CuentaTitular) query.uniqueResult();
List<Object[]> listIdCtaPer = (ArrayList<Object[]>) query.list();
if(listIdCtaPer != null){
for(Object[] idCtaPer: listIdCtaPer){
mapCtaPer.put(((Integer) idCtaPer[0]).toString(), ((Integer) idCtaPer[1]).toString());
}
}
return mapCtaPer;
}
/**
* Obtiene una lista de cuentasTitulares para el contribuyente pasado como parametro y excluye de la lista
* que retorna, la cuenta pasada como parametro
* @param contribuyente
* @param cuentaExcluir - Esta cuenta no se incluira en la lista que retorna
* @return
*/
public List<CuentaTitular> getList(Contribuyente contribuyente, Cuenta cuentaExcluir) {
Session session = SiatHibernateUtil.currentSession();
String queryString = "FROM CuentaTitular ct " +
" WHERE ct.cuenta != :cuenta " +
" AND ct.contribuyente = :contribuyente";
// " AND ct.fechaDesde <= :fecha " +
// " AND (ct.fechaHasta IS NULL OR ct.fechaHasta > :fecha) " +
// " order by esTitularPrincipal desc";
Query query = session.createQuery(queryString)
.setEntity("cuenta", cuentaExcluir)
.setEntity("contribuyente", contribuyente);
return (ArrayList<CuentaTitular>) query.list();
}
public List<CuentaTitular> getListByContribuyente(Contribuyente contribuyente) {
Session session = SiatHibernateUtil.currentSession();
String queryString = "FROM CuentaTitular ct " +
" WHERE ct.contribuyente = :contribuyente";
// " AND ct.fechaDesde <= :fecha " +
// " AND (ct.fechaHasta IS NULL OR ct.fechaHasta > :fecha) " +
// " order by esTitularPrincipal desc";
Query query = session.createQuery(queryString)
.setEntity("contribuyente", contribuyente);
return (ArrayList<CuentaTitular>) query.list();
}
public static void setMigId(long migId) {
CuentaTitularDAO.migId = migId;
}
public static long getMigId() {
return migId;
}
/**
* Verifica si el contribuyente es titular vigente para la Cuenta en la fecha desde pasada.
*
* @param cuenta
* @param contribuyente
* @param fechaDesde
* @return Boolean
*/
public Boolean existeComoTitularVigente(Cuenta cuenta, Contribuyente contribuyente, Date fechaDesde){
Session session = SiatHibernateUtil.currentSession();
String queryString = "FROM CuentaTitular ct WHERE ct.contribuyente = :contribuyente and ct.cuenta = :cuenta ";
queryString += " and ct.fechaDesde <= :fechaDesde ";
queryString += " and (ct.fechaHasta IS NULL OR ct.fechaHasta >= :fechaDesde)";
Query query = session.createQuery(queryString).setEntity("contribuyente", contribuyente )
.setEntity("cuenta", cuenta)
.setDate("fechaDesde", fechaDesde);
query.setMaxResults(1);
CuentaTitular cuentaTitular = (CuentaTitular) query.uniqueResult();
if(cuentaTitular != null)
return true;
return false;
}
}
| gpl-3.0 |
nfell2009/Skript | src/main/java/ch/njol/util/CaseInsensitiveString.java | 2301 | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* Copyright 2011-2014 Peter Güttinger
*
*/
package ch.njol.util;
import java.io.Serializable;
import java.util.Locale;
import javax.annotation.Nullable;
/**
* A string which is compared ignoring it's case.
*
* @author Peter Güttinger
*/
public class CaseInsensitiveString implements Serializable, Comparable<CharSequence>, CharSequence {
private static final long serialVersionUID = 1205018864604639962L;
private final String s;
private final String lc;
private final Locale locale;
@SuppressWarnings("null")
public CaseInsensitiveString(final String s) {
this.s = s;
locale = Locale.getDefault();
lc = "" + s.toLowerCase(locale);
}
public CaseInsensitiveString(final String s, final Locale locale) {
this.s = s;
this.locale = locale;
lc = "" + s.toLowerCase(locale);
}
@Override
public int hashCode() {
return lc.hashCode();
}
@SuppressWarnings("null")
@Override
public boolean equals(final @Nullable Object o) {
if (o == this)
return true;
if (o instanceof CharSequence)
return ((CharSequence) o).toString().toLowerCase(locale).equals(lc);
return false;
}
@Override
public String toString() {
return s;
}
@Override
public char charAt(final int i) {
return s.charAt(i);
}
@Override
public int length() {
return s.length();
}
@Override
public CaseInsensitiveString subSequence(final int start, final int end) {
return new CaseInsensitiveString("" + s.substring(start, end), locale);
}
@SuppressWarnings("null")
@Override
public int compareTo(final CharSequence s) {
return lc.compareTo(s.toString().toLowerCase(locale));
}
}
| gpl-3.0 |
GedMarc/JWebSwing | src/test/java/com/jwebmp/base/html/QuotationTest.java | 1096 | /*
* Copyright (C) 2017 GedMarc
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jwebmp.core.base.html;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author GedMarc
*/
public class QuotationTest
{
public QuotationTest()
{
}
@Test
public void testSomeMethod()
{
Quotation q = new Quotation("q");
q.setID("id");
System.out.println(q.toString(true));
assertEquals("" + "<q id=\"id\"></q>", q.toString(true));
}
}
| gpl-3.0 |
Anisorf/ENCODE | encode/src/org/wandora/application/tools/fng/DigitalPictureRemover.java | 7440 | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2015 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* DigitalPictureRemover.java
*
* Created on August 19, 2004, 2:07 PM
*/
package org.wandora.application.tools.fng;
import org.wandora.topicmap.TopicInUseException;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.XTMPSI;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.Association;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.*;
import org.wandora.*;
import org.wandora.piccolo.Logger;
import org.wandora.piccolo.utils.*;
import java.util.*;
import java.text.*;
/**
*
* @author olli
*/
public class DigitalPictureRemover {
/** Creates a new instance of DigitalPictureRemover */
public DigitalPictureRemover() {
}
public TopicMap process(TopicMap tm,Logger logger) throws TopicMapException {
logger.writelog("Applying DigitalPictureRemover filter");
Topic photograph=tm.getTopic("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#E73_Information_ObjectValokuvanro");
Topic digikuva=tm.getTopic("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#E73_Information_ObjectDigikuvanro");
Topic work=tm.getTopic("http://www.fng.fi/wandora/wandora-fng.xtm#kp-teos");
Topic desc=tm.getTopic("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#sisältökuvaus");
Topic name=tm.getTopic("http://www.fng.fi/wandora/wandora-fng.xtm#kp-nimi");
Topic hasType=tm.getTopic("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#P2F_has_type");
Topic hasTitle=tm.getTopic("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#rP102F_has_title");
Topic depicts=tm.getTopic("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#rP62F_depicts");
Topic depictedBy=tm.getTopic("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#rP62B_is_depicted_by");
Topic performed=tm.getTopic("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#rP14B_performed");
Topic technique=tm.getTopic("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#rP32B_was_technique_of");
Topic producedBy=tm.getTopic("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#P108B_was_produced_by");
if(desc!=null){
desc.addSubjectIdentifier(tm.createLocator("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#sisältökuvaus_(1)"));
desc.addSubjectIdentifier(tm.createLocator("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#sisältökuvaus_(2)"));
desc.addSubjectIdentifier(tm.createLocator("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#sisältökuvaus_(3)"));
desc.removeSubjectIdentifier(tm.createLocator("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#sisältökuvaus_(1)"));
desc.removeSubjectIdentifier(tm.createLocator("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#sisältökuvaus_(2)"));
desc.removeSubjectIdentifier(tm.createLocator("http://www.fng.fi/muusa/FNG_CIDOC_v3.4.dtd#sisältökuvaus_(3)"));
}
if(photograph==null || digikuva==null || work==null || desc==null || name==null ||
hasType==null || hasTitle==null || depicts==null || depictedBy==null ||
performed==null || technique==null || producedBy==null ){
logger.writelog("Coludn't find all needed topics, aborting.");
return tm;
}
Topic display=TMBox.getOrCreateTopic(tm, XTMPSI.DISPLAY);
Topic langfi=TMBox.getOrCreateTopic(tm, XTMPSI.getLang("fi"));
int counter=0;
HashSet pictures=new HashSet();
Iterator iter=tm.getTopicsOfType(photograph).iterator();
while(iter.hasNext()){
Topic t=(Topic)iter.next();
if(!t.isOfType(work)) pictures.add(t);
}
iter=tm.getTopicsOfType(digikuva).iterator();
while(iter.hasNext()){
Topic t=(Topic)iter.next();
if(!t.isOfType(work)) pictures.add(t);
}
Vector descriptions=new Vector();
iter=pictures.iterator();
int counter3=0;
while(iter.hasNext()){
Topic pict=(Topic)iter.next();
Topic depict=null;
String descS="";
// Iterator iter2=pict.getAssociations(name,hasTitle).iterator();
Iterator iter2=pict.getAssociations().iterator();
Collection tobedeleted=new Vector();
while(iter2.hasNext()){
Association a=(Association)iter2.next();
if(a.getType()==producedBy){
tobedeleted.add(a);
continue;
}
if(a.getType()!=name || a.getPlayer(hasTitle)!=pict){
continue;
}
Topic descT=a.getPlayer(name);
if(descT==null || a.getPlayer(hasType)!=desc) continue;
if(descT.getBaseName()==null) continue;
descriptions.add(descT);
if(descS.length()!=0) descS+="; ";
descS+=descT.getBaseName();
}
iter2=tobedeleted.iterator();
while(iter2.hasNext()){
Association a=(Association)iter2.next();
if(a.isRemoved()) continue;
Topic player=a.getPlayer(performed);
if(player!=null) try{player.remove();counter3++;}catch(TopicInUseException tiue){}
player=a.getPlayer(technique);
if(player!=null) try{player.remove();counter3++;}catch(TopicInUseException tiue){}
}
iter2=pict.getAssociations(depicts,depicts).iterator();
while(iter2.hasNext()){
Association a=(Association)iter2.next();
depict=a.getPlayer(depictedBy);
if(depict!=null) break;
}
descS=descS.trim();
if(depict!=null && descS.length()>0){
depict.setData(desc,langfi,descS);
counter++;
}
try{
pict.remove();
}catch(TopicInUseException tiue){}
}
int counter2=0;
iter=descriptions.iterator();
while(iter.hasNext()){
Topic t=(Topic)iter.next();
try{
t.remove();
counter2++;
}catch(TopicInUseException tiue){}
}
logger.writelog("Deleted "+pictures.size()+" topics. Set description to "+counter+" topics. Removed "+counter2+" description topics and "+counter3+" authors or techniques");
return tm;
}
}
| gpl-3.0 |
weloxux/Overchan-Android | src/nya/miku/wishmaster/chans/sevenchan/SevenchanModule.java | 14774 | /*
* Overchan Android (Meta Imageboard Client)
* Copyright (C) 2014-2015 miku-nyan <https://github.com/miku-nyan>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nya.miku.wishmaster.chans.sevenchan;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntityHC4;
import org.apache.http.message.BasicNameValuePair;
import nya.miku.wishmaster.R;
import nya.miku.wishmaster.api.interfaces.CancellableTask;
import nya.miku.wishmaster.api.interfaces.ProgressListener;
import nya.miku.wishmaster.api.models.BoardModel;
import nya.miku.wishmaster.api.models.CaptchaModel;
import nya.miku.wishmaster.api.models.DeletePostModel;
import nya.miku.wishmaster.api.models.SendPostModel;
import nya.miku.wishmaster.api.models.SimpleBoardModel;
import nya.miku.wishmaster.api.models.UrlPageModel;
import nya.miku.wishmaster.api.util.ChanModels;
import nya.miku.wishmaster.api.util.WakabaReader;
import nya.miku.wishmaster.chans.AbstractWakabaModule;
import nya.miku.wishmaster.common.IOUtils;
import nya.miku.wishmaster.http.ExtendedMultipartBuilder;
import nya.miku.wishmaster.http.recaptcha.Recaptcha;
import nya.miku.wishmaster.http.streamer.HttpRequestModel;
import nya.miku.wishmaster.http.streamer.HttpResponseModel;
import nya.miku.wishmaster.http.streamer.HttpStreamer;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.v4.content.res.ResourcesCompat;
@SuppressWarnings("deprecation") // https://issues.apache.org/jira/browse/HTTPCLIENT-1632
public class SevenchanModule extends AbstractWakabaModule {
private static final String CHAN_NAME = "7chan.org";
private static final String RECAPTCHA_KEY = "6LdVg8YSAAAAAOhqx0eFT1Pi49fOavnYgy7e-lTO";
static final String TIMEZONE = "GMT+4"; // ?
private static final Pattern ERROR_POSTING = Pattern.compile("<h2(?:[^>]*)>(.*?)</h2>", Pattern.DOTALL);
private static final SimpleBoardModel[] BOARDS = new SimpleBoardModel[] {
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "7ch", "Site Discussion", "7chan & Related Services", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "ch7", "Channel7 & Radio7", "7chan & Related Services", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "irc", "Internet Relay Circlejerk", "7chan & Related Services", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "777", "/selfhelp/", "Premium Content", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "b", "Random", "Premium Content", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "banner", "Banners", "Premium Content", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "fl", "Flash", "Premium Content", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "gfx", "Graphics Manipulation", "Premium Content", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "class", "The Finer Things", "SFW", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "co", "Comics and Cartoons", "SFW", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "eh", "Particularly uninteresting conversation", "SFW", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "fit", "Fitness & Health", "SFW", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "halp", "Technical Support", "SFW", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "jew", "Thrifty Living", "SFW", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "lit", "Literature", "SFW", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "phi", "Philosophy", "SFW", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "pr", "Programming", "SFW", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "rnb", "Rage and Baww", "SFW", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "sci", "Science, Technology, Engineering, and Mathematics", "SFW", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "tg", "Tabletop Games", "SFW", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "w", "Weapons", "SFW", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "zom", "Zombies", "SFW", false),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "a", "Anime & Manga", "General", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "grim", "Cold, Grim & Miserable", "General", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "hi", "History and Culture", "General", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "me", "Film, Music & Television", "General", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "rx", "Drugs", "General", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "vg", "", "General", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "wp", "Wallpapers", "General", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "x", "Paranormal & Conspiracy", "General", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "cake", "Delicious", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "cd", "Crossdressing", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "d", "Alternative Hentai", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "di", "Sexy Beautiful Traps", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "elit", "Erotic Literature", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "fag", "Men Discussion", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "fur", "Furry", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "gif", "Animated GIFs", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "h", "Hentai", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "men", "Sexy Beautiful Men", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "pco", "Porn Comics", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "s", "Sexy Beautiful Women", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "sm", "Shotacon", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "ss", "Straight Shotacon", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "unf", "Uniforms", "Porn", true),
ChanModels.obtainSimpleBoardModel(CHAN_NAME, "v", "The Vineyard", "Porn", true)
};
private Recaptcha lastCaptcha = null;
public SevenchanModule(SharedPreferences preferences, Resources resources) {
super(preferences, resources);
}
@Override
public String getChanName() {
return CHAN_NAME;
}
@Override
public String getDisplayingName() {
return "7chan";
}
@Override
public Drawable getChanFavicon() {
return ResourcesCompat.getDrawable(resources, R.drawable.favicon_7chan, null);
}
@Override
protected String getUsingDomain() {
return "7chan.org";
}
@Override
protected boolean canHttps() {
return true;
}
@Override
protected boolean canCloudflare() {
return true;
}
@Override
protected WakabaReader getWakabaReader(InputStream stream, UrlPageModel urlModel) {
return new SevenchanReader(stream);
}
@Override
protected SimpleBoardModel[] getBoardsList() {
return BOARDS;
}
@Override
public BoardModel getBoard(String shortName, ProgressListener listener, CancellableTask task) throws Exception {
BoardModel board = super.getBoard(shortName, listener, task);
board.timeZoneId = TIMEZONE;
board.defaultUserName = "";
board.readonlyBoard = false;
board.requiredFileForNewThread = !shortName.equals("halp") && !shortName.equals("7ch");
board.allowDeletePosts = true;
board.allowDeleteFiles = true;
board.allowReport = BoardModel.REPORT_WITH_COMMENT;
board.allowNames = !shortName.equals("b");
board.allowSubjects = true;
board.allowSage = true;
board.allowEmails = true;
board.ignoreEmailIfSage = true;
board.allowCustomMark = false;
board.allowRandomHash = true;
board.allowIcons = false;
board.attachmentsMaxCount = 1;
board.attachmentsFormatFilters = shortName.equals("fl") ? new String[] { "swf" } : null;
board.markType = BoardModel.MARK_BBCODE;
return board;
}
@Override
public CaptchaModel getNewCaptcha(String boardName, String threadNumber, ProgressListener listener, CancellableTask task) throws Exception {
if (threadNumber != null) return null;
Recaptcha recaptcha = Recaptcha.obtain(RECAPTCHA_KEY, task, httpClient, useHttps() ? "https" : "http");
CaptchaModel model = new CaptchaModel();
model.type = CaptchaModel.TYPE_NORMAL;
model.bitmap = recaptcha.bitmap;
lastCaptcha = recaptcha;
return model;
}
@Override
public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception {
String url = getUsingUrl() + "board.php";
ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create().setDelegates(listener, task).
addString("board", model.boardName).
addString("replythread", model.threadNumber == null ? "0" : model.threadNumber).
addString("name", model.name).
addString("em", model.sage ? "sage" : model.email).
addString("subject", model.subject).
addString("message", model.comment);
if (model.threadNumber == null) {
if (lastCaptcha == null) throw new Exception("Invalid captcha");
postEntityBuilder.
addString("recaptcha_challenge_field", lastCaptcha.challenge).
addString("recaptcha_response_field", model.captchaAnswer);
lastCaptcha = null;
postEntityBuilder.addString("embed", "");
}
if (model.attachments != null && model.attachments.length > 0)
postEntityBuilder.addFile("imagefile[]", model.attachments[0], model.randomHash);
else if (model.threadNumber == null) postEntityBuilder.addString("nofile", "on");
postEntityBuilder.addString("postpassword", model.password);
HttpRequestModel request = HttpRequestModel.builder().setPOST(postEntityBuilder.build()).setNoRedirect(true).build();
HttpResponseModel response = null;
try {
response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, null, task);
if (response.statusCode == 302) {
for (Header header : response.headers) {
if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) {
return fixRelativeUrl(header.getValue());
}
}
} else if (response.statusCode == 200) {
ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
IOUtils.copyStream(response.stream, output);
String htmlResponse = output.toString("UTF-8");
Matcher errorMatcher = ERROR_POSTING.matcher(htmlResponse);
if (errorMatcher.find()) throw new Exception(errorMatcher.group(1).trim());
} else throw new Exception(response.statusCode + " - " + response.statusReason);
} finally {
if (response != null) response.release();
}
return null;
}
@Override
public String deletePost(DeletePostModel model, ProgressListener listener, CancellableTask task) throws Exception {
String url = getUsingUrl() + "board.php";
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("board", model.boardName));
pairs.add(new BasicNameValuePair("post[]", model.postNumber));
if (model.onlyFiles) pairs.add(new BasicNameValuePair("fileonly", "on"));
pairs.add(new BasicNameValuePair("postpassword", model.password));
pairs.add(new BasicNameValuePair("deletepost", "Delete"));
HttpRequestModel request = HttpRequestModel.builder().setPOST(new UrlEncodedFormEntityHC4(pairs, "UTF-8")).setNoRedirect(true).build();
String result = HttpStreamer.getInstance().getStringFromUrl(url, request, httpClient, listener, task, false);
if (result.contains("Incorrect password")) throw new Exception("Incorrect password");
return null;
}
@Override
public String reportPost(DeletePostModel model, ProgressListener listener, CancellableTask task) throws Exception {
String url = getUsingUrl() + "board.php";
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("board", model.boardName));
pairs.add(new BasicNameValuePair("post[]", model.postNumber));
pairs.add(new BasicNameValuePair("reportreason", model.reportReason));
pairs.add(new BasicNameValuePair("reportpost", "Report"));
HttpRequestModel request = HttpRequestModel.builder().setPOST(new UrlEncodedFormEntityHC4(pairs, "UTF-8")).setNoRedirect(true).build();
String result = HttpStreamer.getInstance().getStringFromUrl(url, request, httpClient, listener, task, false);
if (result.contains("Post successfully reported.")) return null;
throw new Exception(result);
}
@Override
public String fixRelativeUrl(String url) {
if (url.startsWith("//")) return (useHttps() ? "https:" : "http:") + url;
return super.fixRelativeUrl(url);
}
}
| gpl-3.0 |
talek69/curso | stimulsoft/src/com/stimulsoft/report/components/interfaces/IStiPopupParentControl.java | 227 | /*
* Decompiled with CFR 0_114.
*/
package com.stimulsoft.report.components.interfaces;
public interface IStiPopupParentControl {
public boolean isLockPopupInvoke();
public void setLockPopupInvoke(boolean var1);
}
| gpl-3.0 |
joaoamr/iSPD | src/ispd/arquivo/exportador/Exportador.java | 37319 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ispd.arquivo.exportador;
import ispd.arquivo.xml.IconicoXML;
import ispd.arquivo.xml.ManipuladorXML;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* Classe para converter modelo do iSPD para outros simuladores
* @author Rafael Stabile
*/
public class Exportador {
Document descricao;
public Exportador(Document descricao) {
this.descricao = descricao;
}
/**
* Converte modelo iconico do iSPD nos arquivos xml do SimGrid 3.2
*
* @param descricao modelo iconico do iSPD
* @param arquivo local no qual será salvo os arquivos plataform e
* application no formato do xml usado no SimGrid 3.2
*/
public void toSimGrid(File arquivo) {
IconicoXML.validarModelo(descricao);
NodeList docCarga = descricao.getElementsByTagName("load");
Integer numeroTarefas = 0;
Double maxComputacao = 0.0;
Double maxComunicacao = 0.0;
//Realiza leitura da configuração de carga random
if (docCarga.getLength() != 0) {
Element cargaAux = (Element) docCarga.item(0);
docCarga = cargaAux.getElementsByTagName("random");
if (docCarga.getLength() != 0) {
Element carga = (Element) docCarga.item(0);
numeroTarefas = Integer.parseInt(carga.getAttribute("tasks"));
NodeList size = carga.getElementsByTagName("size");
for (int i = 0; i < size.getLength(); i++) {
Element size1 = (Element) size.item(i);
if (size1.getAttribute("type").equals("computing")) {
maxComputacao = Double.parseDouble(size1.getAttribute("maximum"));
} else if (size1.getAttribute("type").equals("communication")) {
maxComunicacao = Double.parseDouble(size1.getAttribute("maximum"));
}
}
} else {
docCarga = cargaAux.getElementsByTagName("node");
}
}
Document docApplication = ManipuladorXML.novoDocumento();
Element tagApplication = docApplication.createElement("platform_description");
tagApplication.setAttribute("version", "1");
docApplication.appendChild(tagApplication);
Document docPlataform = ManipuladorXML.novoDocumento();
Element tagPlataform = docPlataform.createElement("platform_description");
tagPlataform.setAttribute("version", "1");
docPlataform.appendChild(tagPlataform);
NodeList docmaquinas = descricao.getElementsByTagName("machine");
NodeList docCluster = descricao.getElementsByTagName("cluster");
NodeList doclinks = descricao.getElementsByTagName("link");
NodeList docNets = descricao.getElementsByTagName("internet");
int numMestre = 0;
HashMap<Integer, String> maquinas = new HashMap<Integer, String>();
HashMap<Integer, String> comutacao = new HashMap<Integer, String>();
HashMap<Integer, Integer> link_origem = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> link_destino = new HashMap<Integer, Integer>();
//Busca poder das máquinas
for (int i = 0; i < docmaquinas.getLength(); i++) {
Element maquina = (Element) docmaquinas.item(i);
if (maquina.getElementsByTagName("master").getLength() > 0) {
numMestre++;
}
Element id = (Element) maquina.getElementsByTagName("icon_id").item(0);
int global = Integer.parseInt(id.getAttribute("global"));
maquinas.put(global, maquina.getAttribute("id"));
Element cpu = docPlataform.createElement("cpu");
cpu.setAttribute("name", maquina.getAttribute("id"));
cpu.setAttribute("power", maquina.getAttribute("power"));
tagPlataform.appendChild(cpu);
}
//Busca clusters
for (int i = 0; i < docCluster.getLength(); i++) {
Element cluster = (Element) docCluster.item(i);
Element id = (Element) cluster.getElementsByTagName("icon_id").item(0);
int global = Integer.parseInt(id.getAttribute("global"));
maquinas.put(global, cluster.getAttribute("id"));
Element cpu = docPlataform.createElement("cpu");
cpu.setAttribute("name", cluster.getAttribute("id"));
cpu.setAttribute("power", cluster.getAttribute("power"));
tagPlataform.appendChild(cpu);
}
//Busca busca banda das redes
for (int i = 0; i < doclinks.getLength(); i++) {
Element link = (Element) doclinks.item(i);
Element network = docPlataform.createElement("network_link");
network.setAttribute("name", link.getAttribute("id"));
network.setAttribute("bandwidth", link.getAttribute("bandwidth"));
network.setAttribute("latency", link.getAttribute("latency"));
tagPlataform.appendChild(network);
Element connect = (Element) link.getElementsByTagName("connect").item(0);
//salva origem e destino do link
Element id = (Element) link.getElementsByTagName("icon_id").item(0);
int global = Integer.parseInt(id.getAttribute("global"));
comutacao.put(global, link.getAttribute("id"));
link_origem.put(global, Integer.parseInt(connect.getAttribute("origination")));
link_destino.put(global, Integer.parseInt(connect.getAttribute("destination")));
}
for (int i = 0; i < docNets.getLength(); i++) {
Element link = (Element) docNets.item(i);
Element network = docPlataform.createElement("network_link");
network.setAttribute("name", link.getAttribute("id"));
network.setAttribute("bandwidth", link.getAttribute("bandwidth"));
network.setAttribute("latency", link.getAttribute("latency"));
tagPlataform.appendChild(network);
//salva elemento na lista com os elementos de comutação
Element id = (Element) link.getElementsByTagName("icon_id").item(0);
int global = Integer.parseInt(id.getAttribute("global"));
comutacao.put(global, link.getAttribute("id"));
}
//Escreve mestres
boolean primeiro = true;
for (int i = 0; i < docmaquinas.getLength(); i++) {
Element maquina = (Element) docmaquinas.item(i);
if (maquina.getElementsByTagName("master").getLength() > 0) {
Element mestre = docApplication.createElement("process");
String idMestre = maquina.getAttribute("id");
mestre.setAttribute("host", idMestre);
mestre.setAttribute("function", "master");
//Adicionar tarefas
if (docCarga.item(0).getNodeName().equals("random")) {
//Number of tasks
Element carga = docApplication.createElement("argument");
if (primeiro) {
primeiro = false;
Integer temp = (numeroTarefas / numMestre) + (numeroTarefas % numMestre);
carga.setAttribute("value", temp.toString());
} else {
Integer temp = (numeroTarefas / numMestre);
carga.setAttribute("value", temp.toString());
}
mestre.appendChild(carga);
//Max computation size of tasks
carga = docApplication.createElement("argument");
carga.setAttribute("value", maxComputacao.toString());
mestre.appendChild(carga);
//Max communication size of tasks
carga = docApplication.createElement("argument");
carga.setAttribute("value", maxComunicacao.toString());
mestre.appendChild(carga);
} else if (docCarga.item(0).getNodeName().equals("node")) {
numeroTarefas = 0;
for (int j = 0; j < docCarga.getLength(); j++) {
Element carga = (Element) docCarga.item(j);
String escalonador = carga.getAttribute("id_master");
if (escalonador.equals(idMestre)) {
numeroTarefas += Integer.parseInt(carga.getAttribute("tasks"));
NodeList size = carga.getElementsByTagName("size");
for (int k = 0; k < size.getLength(); k++) {
Element size1 = (Element) size.item(k);
if (size1.getAttribute("type").equals("computing")) {
double temp = Double.parseDouble(size1.getAttribute("maximum"));
if (temp > maxComputacao) {
maxComputacao = temp;
}
} else if (size1.getAttribute("type").equals("communication")) {
double temp = Double.parseDouble(size1.getAttribute("maximum"));
if (temp > maxComunicacao) {
maxComunicacao = temp;
}
}
}
}
}
//Number of tasks
Element carga = docApplication.createElement("argument");
carga.setAttribute("value", numeroTarefas.toString());
mestre.appendChild(carga);
//Max computation size of tasks
carga = docApplication.createElement("argument");
carga.setAttribute("value", maxComputacao.toString());
mestre.appendChild(carga);
//Max communication size of tasks
carga = docApplication.createElement("argument");
carga.setAttribute("value", maxComunicacao.toString());
mestre.appendChild(carga);
}
//Adiciona escravos ao mestre
NodeList slaves = maquina.getElementsByTagName("slave");
for (int j = 0; j < slaves.getLength(); j++) {
Element escravo = docApplication.createElement("argument");
Element slave = (Element) slaves.item(j);
String idEscravo = maquinas.get(Integer.parseInt(slave.getAttribute("id")));
escravo.setAttribute("value", idEscravo);
mestre.appendChild(escravo);
//Define roteamento entre mestre e escravo
Element rota = docPlataform.createElement("route");
rota.setAttribute("src", idMestre);
rota.setAttribute("dst", idEscravo);
ArrayList<Element> caminho = caminho(idMestre, idEscravo, docPlataform, link_origem, link_destino, comutacao, maquinas, null);
if (caminho != null) {
for (Element element : caminho) {
rota.appendChild(element);
}
}
tagPlataform.appendChild(rota);
rota = docPlataform.createElement("route");
rota.setAttribute("src", idEscravo);
rota.setAttribute("dst", idMestre);
caminho = caminho(idEscravo, idMestre, docPlataform, link_origem, link_destino, comutacao, maquinas, null);
if (caminho != null) {
for (Element element : caminho) {
rota.appendChild(element);
}
}
tagPlataform.appendChild(rota);
}
tagApplication.appendChild(mestre);
}
}
//Escreve escravos
for (int i = 0; i < docmaquinas.getLength(); i++) {
Element maquina = (Element) docmaquinas.item(i);
if (maquina.getElementsByTagName("master").getLength() == 0) {
Element escravo = docApplication.createElement("process");
escravo.setAttribute("host", maquina.getAttribute("id"));
escravo.setAttribute("function", "slave");
tagApplication.appendChild(escravo);
}
}
for (int i = 0; i < docCluster.getLength(); i++) {
Element cluster = (Element) docCluster.item(i);
Element escravo = docApplication.createElement("process");
escravo.setAttribute("host", cluster.getAttribute("id"));
escravo.setAttribute("function", "slave");
Element maqs = docApplication.createElement("argument");
maqs.setAttribute("value", cluster.getAttribute("nodes"));
escravo.appendChild(maqs);
tagApplication.appendChild(escravo);
}
String name = arquivo.getName();
String diretorio = arquivo.getPath();
ManipuladorXML.escrever(docPlataform, new File(arquivo.getParentFile(), "plataform_" + name), "surfxml.dtd");
ManipuladorXML.escrever(docApplication, new File(arquivo.getParentFile(), "application_" + name), "surfxml.dtd");
}
/**
* Converte modelo iconico do iSPD no arquivo java do GridSim
* @param file arquivo na qual as classes serão salvas
*/
public void toGridSim(File file) {
NodeList owners = descricao.getElementsByTagName("owner");
HashMap<String, Integer> usuarios = new HashMap<String, Integer>();
HashMap<Integer, String> recursos = new HashMap<Integer, String>();
NodeList maquinas = descricao.getElementsByTagName("machine");
NodeList clusters = descricao.getElementsByTagName("cluster");
NodeList internet = descricao.getElementsByTagName("internet");
NodeList links = descricao.getElementsByTagName("link");
NodeList cargas = descricao.getElementsByTagName("load");
try {
FileWriter writer = new FileWriter(file);
PrintWriter saida = new PrintWriter(writer, true);
/*
* --------------------------SAIDA---------------------------
*/
saida.println("\n import java.util.*; \n import gridsim.*;\n import gridsim.net.*;"); //Imports do modelo
//Classe Mestre
saida.println("\nclass Mestre extends GridSim {\n");
saida.println("\tGridletList list; \n\tprivate Integer ID_; \n\tpublic Router r; \n\tArrayList Escravos_;\n\t int Escal;");
saida.println("\n\n\tMestre(String nome, Link link,GridletList list, ArrayList Escravo, int esc) throws Exception {");
saida.println("\n\t\tsuper(nome, link); \n\t\tthis.list = list;\n\t\tthis.ID_ = new Integer(getEntityId(nome));\n\t\t this.Escravos_ = Escravo; \n\t\tthis.Escal=esc; }");
saida.println("\n\t@Override\n\tpublic void body() {");
saida.println("\t\tArrayList<GridResource> resList = this.Escravos_;\n\t\tint ids[] = new int[resList.size()];");
saida.println("\t\tdouble temp_ini, temp_fim; \n\twhile (true) {");
saida.println("\t\tsuper.gridSimHold(2.0); \n\t\tLinkedList recur = GridSim.getGridResourceList(); \t\tif (recur.size() > 0) break; \n\t}");
saida.println("\t\t\tfor(int j=0;j<resList.size(); j++){ \n\t\t ids[j] = resList.get(j).get_id();\n\t}");
saida.println("\n\t\tfor(int i = 0; i < resList.size(); i++){");
saida.println("\t\t\tsuper.send(ids[i], GridSimTags.SCHEDULE_NOW, GridSimTags.RESOURCE_CHARACTERISTICS, this.ID_);\n\t\t}");
saida.println("\t\ttemp_ini = GridSim.clock();");
saida.println("\t\tif(this.Escal==1){ //O escalonador é Workqueue");
saida.println("\t\t\tint cont=0; int k; Gridlet gl;");
saida.println("\t\t\tfor(k=0; k < Escravos_.size() && cont < list.size(); k++, cont++){");
saida.println("\t\t\t\tint num = resList.get(k).get_id();;");
saida.println("\t\t\t\tlist.get(cont).setUserID(this.ID_);\n\t\t\t\tsuper.gridletSubmit((Gridlet)list.get(cont),num , 0.0, true);\n\t\t\t}");
saida.println("\t\t\tint res=0; \n\t\t\twhile(cont<list.size() || res<list.size()) {\n\t\t\t\t gl = super.gridletReceive();\n\t\t\t\tres++; \n\t\t\t\tint num = gl.getResourceID();\n\t\t\t\tif(cont<list.size()){ ");
saida.println("\t\t\t\t\tlist.get(cont).setUserID(this.ID_); \n\t\t\t\t\tsuper.gridletSubmit((Gridlet)list.get(cont),num , 0.0, true); \n\t\t\t\t\tcont++; \n\t\t\t\t} \n\t\t\t}");
saida.println("\t\t}else{//É RoundRobin");
saida.println("\t\t");
saida.println("\t\t}");
saida.println("\t\ttemp_fim = GridSim.clock(); \n\t\tSystem.out.println(\"TEMPO DE SIMULAÇÂO:\"+(temp_fim-temp_ini));\n\t\tsuper.shutdownGridStatisticsEntity();");
saida.println("\t\tsuper.shutdownUserEntity();\n\t\t super.terminateIOEntities();\n\t\t } \n\t}");
//Classe principal
saida.println(" \nclass Modelo{ \n\n \tpublic static void main(String[] args) {\n");
saida.println("\t\ttry {");
saida.println("\t\t\tCalendar calendar = Calendar.getInstance(); \n\t\t\t boolean trace_flag = true;");
saida.println("\t\t\tString[] exclude_from_file = {\"\"}; \n\t\t\t String[] exclude_from_processing = {\"\"};");
saida.println("\t\t\tGridSim.init(" + owners.getLength() + ",calendar, true, exclude_from_file,exclude_from_processing, null);");
saida.println("\n\t\t\tFIFOScheduler resSched = new FIFOScheduler( \" GridResSched \");");
//Recursos
saida.println("\t\t\tdouble baud_rate = 100.0; \n\t\t\tdouble delay =0.1; \n\t\t\tint MTU = 100;");
for (int i = 0; i < maquinas.getLength(); i++) { //Quando o recurso é uma só máquina
Element maquina = (Element) maquinas.item(i);
if (maquina.getElementsByTagName("master").getLength() == 0) {
Element id = (Element) maquina.getElementsByTagName("icon_id").item(0);
int global = Integer.parseInt(id.getAttribute("global"));
recursos.put(global, maquina.getAttribute("id"));
saida.println("\n\t\t\tGridResource " + maquina.getAttribute("id") + " = createResource(\"" + maquina.getAttribute("id") + "_\", baud_rate, delay, MTU, 1, (int)" + maquina.getAttribute("power") + ");");
saida.println("\t\t\tRouter r_" + maquina.getAttribute("id") + " = new RIPRouter( \"router_" + i + "\", trace_flag);");
saida.println("\t\t\tr_" + maquina.getAttribute("id") + ".attachHost( " + maquina.getAttribute("id") + ", resSched); ");
//saida.println("\n\t\t\tMachineList mList" + i + " = new MachineList(); ");
//saida.println("\t\t\tmList" + i + ".add( new Machine(" + i + ",1,(int)" + maquina.getAttribute("power") + "));");
//saida.println("\t\t\tResourceCharacteristics resConfig" + i + " = new ResourceCharacteristics(\"Sun Ultra\",\"Solaris\" , mList" + i + ", ResourceCharacteristics.TIME_SHARED, 0, 0);");
//saida.println("\t\t\tGridResource " + maquina.getAttribute("id") + " = new GridResource(\"" + maquina.getAttribute("id") + "\",0 ,resConfig" + i + ", null);");//link???
//saida.println("\t\t\tRouter r_"+maquina.getAttribute("id") + " = new RIPRouter( \" router_"+i + " \", trace_flag);");//Cada recurso é conectado ao seu próprio reteador
//saida.println("\t\t\tFIFOScheduler resSched = new FIFOScheduler( \" GridResSched \");");
//saida.println("\t\t\t r_"+ maquina.getAttribute("id")+".attachHost( "+maquina.getAttribute("id") + ", resSched); "); //nome roteador igual ao recurso
}
}
for (int j = 0, i = maquinas.getLength(); i < maquinas.getLength() + clusters.getLength(); i++, j++) {//Quando o recurso é um cluster
Element cluster = (Element) clusters.item(j);
Element id = (Element) cluster.getElementsByTagName("icon_id").item(0);
int global = Integer.parseInt(id.getAttribute("global"));
recursos.put(global, cluster.getAttribute("id"));
saida.println("\n\t\t\tGridResource " + cluster.getAttribute("id") + "= createResource(\"" + cluster.getAttribute("id") + "_\", baud_rate, delay, MTU," + (Integer.parseInt(cluster.getAttribute("nodes"))) + ",(int)" + cluster.getAttribute("power") + ");");
saida.println("\t\t\tRouter r_" + cluster.getAttribute("id") + " = new RIPRouter( \"router_" + i + "\", trace_flag);");
saida.println("\t\t\tr_" + cluster.getAttribute("id") + ".attachHost( " + cluster.getAttribute("id") + ", resSched); ");
//saida.println("\n\t\t\tMachineList mList" + i + " = new MachineList(); ");
//saida.println("\t\t\tfor(int k = 0; k < " + (Integer.parseInt(cluster.getAttribute("nodes"))) + "; k++)");
//saida.println("\t\t\t\tmList" + i + ".add( new Machine( k ,1,(int)" + cluster.getAttribute("power") + "));");
//saida.println("\t\t\tResourceCharacteristics resConfig" + i + " = new ResourceCharacteristics(\"Sun Ultra\",\"Solaris\" , mList" + i + ", ResourceCharacteristics.TIME_SHARED, 0, 0);");
//saida.println("\t\t\tGridResource " + cluster.getAttribute("id") + " = new GridResource(" + cluster.getAttribute("id") + ",0 ,resConfig" + i + ", null);");//link???
//saida.println("\t\t\tRouter r_"+cluster.getAttribute("id") + " = new RIPRouter( \"router_"+i +"\", trace_flag);");//Cada recurso é conectado ao seu próprio reteador
//saida.println("\t\t\tFIFOScheduler resSched = new FIFOScheduler( \"GridResSched"+ i +"\");");
//saida.println("\t\t\tr_"+cluster.getAttribute("id")+".attachHost( "+cluster.getAttribute("id") + ", resSched); ");
}
//Carga
if (cargas.getLength() != 0) {
Element cargaAux = (Element) cargas.item(0);
NodeList trace = cargaAux.getElementsByTagName("trace");
if (trace.getLength() == 0) {
saida.println("\n\t\t\tGridletList list = createGridlet();\n");
} else { //Leitura de trace
cargaAux = (Element) trace.item(0);
saida.println("\n\t\t\t String[] fileName = { ");
saida.println("\t\t\t\t" + cargaAux.getAttribute("file_path"));
saida.println("\n\t\t\t}");
saida.println("\n\t\t\t ArrayList load = new ArrayList();");
saida.println("\t\t\t for (i = 0; i < fileName.length; i++){");
saida.println("\t\t\t\tWorkload w = new Workload(\"Load_\"+i, fileName[i], resList[], rating);");//falta acabar, resList[] e rating
saida.println("\t\t\t\tload.add(w);\n\t\t\t}");
}
}
//Mestres
saida.println("\n\t\t\tLink link = new SimpleLink(\"link_\", 100, 0.01, 1500 );");
for (int i = 0; i < maquinas.getLength(); i++) {
Element maquina = (Element) maquinas.item(i);
if (maquina.getElementsByTagName("master").getLength() == 1) {
Element id = (Element) maquina.getElementsByTagName("icon_id").item(0);
int global = Integer.parseInt(id.getAttribute("global"));
recursos.put(global, maquina.getAttribute("id"));
NodeList escravos = ((Element) maquina.getElementsByTagName("master").item(0)).getElementsByTagName("slave");
saida.println("\n\t\t\tArrayList esc" + i + " = new ArrayList();");
for (int j = 0; j < escravos.getLength(); j++) {
int global_escravo = Integer.parseInt(((Element) escravos.item(j)).getAttribute("id"));
saida.println("\t\t\tesc" + i + ".add(" + recursos.get(global_escravo) + ");");
}
saida.println("\n\t\t\tMestre " + maquina.getAttribute("id") + " = new Mestre(\"" + maquina.getAttribute("id") + "_\", link, list, esc" + i + ", " + escravos.getLength() + ");");
saida.println("\t\t\tRouter r_" + maquina.getAttribute("id") + " = new RIPRouter( \"router_" + i + "\", trace_flag);");
saida.println("\t\t\tr_" + maquina.getAttribute("id") + ".attachHost( " + maquina.getAttribute("id") + ", resSched); ");
for (int j = 0; j < escravos.getLength(); j++) {
int global_escravo = Integer.parseInt(((Element) escravos.item(j)).getAttribute("id"));
saida.println("\n\t\t\tr_" + maquina.getAttribute("id") + ".attachHost( " + recursos.get(global_escravo) + ", resSched); ");
}
}
}
//Usuário
saida.println("\n\t\t\tResourceUserList userList = createGridUser();");
//Rede
for (int i = 0; i < internet.getLength(); i++) {//PAra internet
Element net = (Element) internet.item(i);
Element id = (Element) net.getElementsByTagName("icon_id").item(0);
int global = Integer.parseInt(id.getAttribute("global"));
recursos.put(global, net.getAttribute("id"));
saida.println("\t\t\tRouter r_" + net.getAttribute("id") + " = new RIPRouter(" + net.getAttribute("id") + ",trace_flag);");
}
saida.println("\t\t\tFIFOScheduler rSched = new FIFOScheduler(\"r_Sched\");");
for (int i = 0; i < links.getLength(); i++) {//Pega cada conexão que nao seja mestre
Element link = (Element) links.item(i);
Element connect = (Element) link.getElementsByTagName("connect").item(0);
int origin = Integer.parseInt(connect.getAttribute("origination"));
int dest = Integer.parseInt(connect.getAttribute("destination"));
//if(!(recursos.get(dest)==null) && !(recursos.get(origin)==null))//Conexão que nao tenham mestre
saida.println("\n\t\t\tLink " + link.getAttribute("id") + " = new SimpleLink(\"link_" + i + "\", " + link.getAttribute("bandwidth") + "*1000, " + link.getAttribute("latency") + "*1000,1500 );");
//saida.println("\t\t\tr_"+recursos.get(origin)+".attachRouter(r_"+recursos.get(dest)+","+link.getAttribute("id") +",rSched, );");
}
//simulaçao
saida.println("\n\t\t\tGridSim.startGridSimulation();");
saida.println("\t\t} \t\tcatch (Exception e){ ");
saida.println("\t\t\t e.printStackTrace();\n \t\t\tSystem.out.println(\"Unwanted ERRORS happened\"); \n\t\t} \n\t} ");
//Fim Main
//metodo criação de Usuário
saida.println("\n\n\tprivate static ResourceUserList createGridUser(){");
saida.println("\t\tResourceUserList userList = new ResourceUserList();");
for (int i = 0; i < owners.getLength(); i++) {
Element owner = (Element) owners.item(i);
usuarios.put(owner.getAttribute("id"), i);
saida.println("\t\tuserList.add(" + i + ");");
}
saida.println("\t\treturn userList;\n\t}");
//Método para a criação de recursos
saida.println("\n\tprivate static GridResource createResource(String name, double baud_rate, double delay, int MTU, int n_maq, int cap){");
saida.println("\n\t\t\tMachineList mList = new MachineList();\n\t\t\tfor(int i = 0; i < n_maq; i++){");
saida.println(" \n\t\t\t mList.add( new Machine(i, 1, cap)); \n\t\t}");
saida.println("\n\t\t\tString arch = \"Sun Ultra\"; \n\t\t\tString os = \"Solaris\"; \n\t\t\tdouble time_zone = 9.0; \n\t\t\tdouble cost = 3.0;");
saida.println("\n\t\tResourceCharacteristics resConfig = new ResourceCharacteristics(arch, os, mList, ResourceCharacteristics.TIME_SHARED,time_zone, cost);");
saida.println("\n\t\tlong seed = 11L*13*17*19*23+1; \n\t\tdouble peakLoad = 0.0; \n\t\tdouble offPeakLoad = 0.0; \n\t\tdouble holidayLoad = 0.0;");
saida.println("\n\t\tLinkedList Weekends = new LinkedList(); \n\t\tWeekends.add(new Integer(Calendar.SATURDAY)); \n\t\tWeekends.add(new Integer(Calendar.SUNDAY)); \n\t\tLinkedList Holidays = new LinkedList();");
saida.println("\t\tGridResource gridRes=null;");
saida.println("\n\t\ttry\n\t\t { \n\t\t\t gridRes = new GridResource(name, new SimpleLink(name + \"_link\", baud_rate, delay, MTU),seed, resConfig, peakLoad, offPeakLoad, holidayLoad,Weekends, Holidays);");
saida.println("\n\t\t} \n\t\tcatch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}");
saida.println("\n\t\treturn gridRes;\n\t}");
//metodo Criação de Tarefas
saida.println("\n\n\tprivate static GridletList createGridlet(){ \n\t\tdouble length; \n\t\tlong file_size;\n\t\tRandom random = new Random();");
saida.println("\n\t\tGridletList list = new GridletList();");
for (int j = 0; j < cargas.getLength(); j++) {
Element carga = (Element) cargas.item(j);
double minComputacao = 0;
double maxComputacao = 0;
double minComunicacao = 0;
double maxComunicacao = 0;
double value = 0;
double val = 0;
double mincp = 0;
double maxcp = 0;
double mincm = 0;
double maxcm = 0;
NodeList size = carga.getElementsByTagName("size");
for (int k = 0; k < size.getLength(); k++) {
Element size1 = (Element) size.item(k);
if (size1.getAttribute("type").equals("computing")) {
minComputacao = Double.parseDouble(size1.getAttribute("minimum"));
maxComputacao = Double.parseDouble(size1.getAttribute("maximum"));
value = Double.parseDouble(size1.getAttribute("average"));
mincp = (value - minComputacao) / value;
if (mincp > 1.0) {
mincp = 1.0;
}
maxcp = (maxComputacao - value) / value;
if (maxcp > 1.0) {
maxcp = 1.0;
}
} else if (size1.getAttribute("type").equals("communication")) {
minComunicacao = Double.parseDouble(size1.getAttribute("minimum"));
maxComunicacao = Double.parseDouble(size1.getAttribute("maximum"));
val = Double.parseDouble(size1.getAttribute("average"));
mincm = (val - minComputacao) / val;
if (mincm > 1.0) {
mincp = 1.0;
}
maxcm = (maxComputacao - val) / val;
if (maxcm > 1.0) {
maxcp = 1.0;
}
}
saida.println("\t\tlength = GridSimRandom.real(" + value + "," + mincp + "," + maxcp + ",random.nextDouble());");
saida.println("\t\tfile_size = (long) GridSimRandom.real(" + val + "," + mincm + "," + maxcm + ",random.nextDouble());");
saida.println("\t\tGridlet gridlet" + k + " = new Gridlet(" + k + ", length, file_size,file_size);");
saida.println("\t\tlist.add(gridlet" + k + ");");
saida.println("\n\t\tgridlet" + k + ".setUserID(0);");
}
saida.println("\n\t\treturn list;");
}
saida.println("\n\t} \n}");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Warning", JOptionPane.WARNING_MESSAGE);
}
}
/**
* Método auxiliar na conversão para SimGrim.
* utilizado para criar uma rota entre duas máquinas
*/
private static ArrayList<Element> caminho(String origem, String destino, Document docPlataform, HashMap<Integer, Integer> link_origem, HashMap<Integer, Integer> link_destino, HashMap<Integer, String> comutacao, HashMap<Integer, String> maquinas, ArrayList<String> expandido) {
ArrayList<Element> caminho = new ArrayList<Element>();
for (Map.Entry<Integer, Integer> entry : link_origem.entrySet()) {
Integer chaveLink = entry.getKey();
Integer idOrigem = entry.getValue();
if (maquinas.get(idOrigem) != null && maquinas.get(idOrigem).equals(origem)) {
if (maquinas.get(link_destino.get(chaveLink)) == null) {
ArrayList<Element> temp = caminho(comutacao.get(link_destino.get(chaveLink)), destino, docPlataform, link_origem, link_destino, comutacao, maquinas, new ArrayList<String>());
if (temp != null) {
Element elemento = docPlataform.createElement("route_element");
elemento.setAttribute("name", comutacao.get(chaveLink));
caminho.add(elemento);
for (Element element : temp) {
caminho.add(element);
}
return caminho;
}
} else {
if (maquinas.get(link_destino.get(chaveLink)).equals(destino)) {
Element elemento = docPlataform.createElement("route_element");
elemento.setAttribute("name", comutacao.get(chaveLink));
caminho.add(elemento);
return caminho;
}
}
} else if (comutacao.get(idOrigem) != null && comutacao.get(idOrigem).equals(origem)) {
if (maquinas.get(link_destino.get(chaveLink)) == null) {
if (!expandido.contains(comutacao.get(link_destino.get(chaveLink)))) {
ArrayList<String> tempExp = new ArrayList<String>(expandido);
tempExp.add(comutacao.get(idOrigem));
ArrayList<Element> temp = caminho(comutacao.get(link_destino.get(chaveLink)), destino, docPlataform, link_origem, link_destino, comutacao, maquinas, tempExp);
if (temp != null) {
Element elemento = docPlataform.createElement("route_element");
elemento.setAttribute("name", comutacao.get(idOrigem));
caminho.add(elemento);
elemento = docPlataform.createElement("route_element");
elemento.setAttribute("name", comutacao.get(chaveLink));
caminho.add(elemento);
for (Element element : temp) {
caminho.add(element);
}
return caminho;
}
}
} else {
if (maquinas.get(link_destino.get(chaveLink)).equals(destino)) {
Element elemento = docPlataform.createElement("route_element");
elemento.setAttribute("name", comutacao.get(idOrigem));
caminho.add(elemento);
elemento = docPlataform.createElement("route_element");
elemento.setAttribute("name", comutacao.get(chaveLink));
caminho.add(elemento);
return caminho;
}
}
}
}
return null;
}
}
| gpl-3.0 |
tomas-pluskal/masscascade | MassCascadeChem/src/main/java/uk/ac/ebi/masscascade/brush/judge/IsotopeJudge.java | 6554 | /*
* Copyright (C) 2013 EMBL - European Bioinformatics Institute
*
* This file is part of MassCascade.
*
* MassCascade is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MassCascade is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MassCascade. If not, see <http://www.gnu.org/licenses/>.
*
* Contributors:
* Stephan Beisken - initial API and implementation
*/
package uk.ac.ebi.masscascade.brush.judge;
import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.openscience.cdk.formula.IsotopeContainer;
import org.openscience.cdk.formula.IsotopePattern;
import org.openscience.cdk.formula.IsotopePatternGenerator;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.interfaces.IMolecularFormula;
import org.openscience.cdk.tools.manipulator.MolecularFormulaManipulator;
import uk.ac.ebi.masscascade.commons.Evidence;
import uk.ac.ebi.masscascade.commons.Status;
import uk.ac.ebi.masscascade.compound.CompoundEntity;
import uk.ac.ebi.masscascade.compound.CompoundSpectrum;
import uk.ac.ebi.masscascade.compound.NotationUtil;
import uk.ac.ebi.masscascade.parameters.Constants;
import uk.ac.ebi.masscascade.utilities.range.ToleranceRange;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* Judge resolving the isotope patterns based on detected isotope signals and compound entity annotations.
* <p/>
* The judge can increase the total score of a compound entity by a maximum of 200.
*/
public class IsotopeJudge implements Judge {
private static final Logger LOGGER = Logger.getLogger(IsotopeJudge.class);
private final double TOLERANCE_PPM = 100000.0; // 10%
private final double STEPSIZE_PPM = 50000.0; // 5%
private int removed = 0;
/**
* The core method of the judge executing the filtering process.
*
* @param compoundSpectra the input list of compound spectra
* @return the filtered input list
*/
@Override
public List<CompoundSpectrum> judge(List<CompoundSpectrum> compoundSpectra) {
LOGGER.log(Level.DEBUG, "Starting Isotope Judge...");
List<CompoundSpectrum> filteredCS = new ArrayList<>();
for (CompoundSpectrum cs : compoundSpectra) {
Set<Integer> isotopes = cs.getIndexToIsotope().keySet();
if (isotopes.isEmpty() || isotopes.size() == 1) {
filteredCS.add(cs);
continue;
}
double[] intensities = new double[isotopes.size()];
int i = 0;
for (int isotope : isotopes) {
intensities[i++] = cs.getPeakList().get(isotope - 1).y;
}
// ascending numerical order and reversed (or use comparator...)
Arrays.sort(intensities);
ArrayUtils.reverse(intensities);
// normalise to 1
double maxIntensity = intensities[0];
for (int j = 0; j < intensities.length; j++) {
intensities[j] = intensities[j] / maxIntensity;
}
List<CompoundEntity> resultCEs = new ArrayList<>();
for (CompoundEntity ce : cs.getCompounds()) {
String isoLog = "";
boolean filter = false;
String notation = ce.getNotation(ce.getId());
IAtomContainer molecule = NotationUtil.getMoleculePlain(notation);
if (molecule.isEmpty()) {
isoLog = "Empty molecule container";
filter = true;
} else {
IMolecularFormula mf = MolecularFormulaManipulator.getMolecularFormula(molecule);
double[] isoIntensities = getIsoIntensities(mf);
for (int j = 0; j < intensities.length; j++) {
isoLog += isoIntensities[j] + " \\ " + new ToleranceRange(intensities[j],
TOLERANCE_PPM).toString() + "\n";
if (!(new ToleranceRange(intensities[j], TOLERANCE_PPM + STEPSIZE_PPM * j)).contains(
isoIntensities[j])) {
filter = true;
break;
}
}
}
if (filter) {
LOGGER.log(Level.DEBUG, "Removed " + notation + ":\n" + isoLog);
removed++;
} else {
ce.setStatus(Status.INTERMEDIATE);
ce.setEvidence(Evidence.MSI_3);
ce.addScore(200);
resultCEs.add(ce);
}
}
cs.setCompounds(resultCEs);
if (cs.getCompounds().size() > 0) {
filteredCS.add(cs);
}
}
return filteredCS;
}
private double[] getIsoIntensities(IMolecularFormula mf) {
IsotopePatternGenerator ipg = new IsotopePatternGenerator(0);
IsotopePattern ip = ipg.getIsotopes(mf);
double halfedProton = Constants.PARTICLES.PROTON.getMass() / 2d;
int isoIndex = 0;
IsotopeContainer pIsotope = null;
double[] isoIntensities = new double[ip.getNumberOfIsotopes()];
for (IsotopeContainer isotope : ip.getIsotopes()) {
if (pIsotope == null) {
isoIntensities[isoIndex] = isotope.getIntensity();
} else if (isotope.getMass() - pIsotope.getMass() < halfedProton) {
if (isotope.getIntensity() >= isoIntensities[isoIndex]) {
isoIntensities[isoIndex] = isotope.getIntensity();
}
} else {
isoIntensities[++isoIndex] = isotope.getIntensity();
}
pIsotope = isotope;
}
return isoIntensities;
}
/**
* Returns the number of removed or filtered compound spectra.
*
* @return the number of removed or filtered compound spectra
*/
@Override
public int removed() {
return removed;
}
} | gpl-3.0 |