repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
JalexChang/leetcode | 144. Binary Tree Preorder Traversal/Solution_iteration.java | 795 | /* Problem Link: https://leetcode.com/problems/binary-tree-preorder-traversal/
* Hint: Iteration, Stack
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> paths =new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
//stack.push(root);
while(root!=null){
paths.add(root.val);
if(root.right!=null) stack.push(root.right);
if(root.left!=null) root = root.left;
else if(!stack.empty()) root = stack.pop();
else break;
}
return paths;
}
} | mit |
divotkey/cogaen3-java | Cogaen Core/src/org/cogaen/entity/EntityService.java | 2672 | package org.cogaen.entity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cogaen.core.Core;
import org.cogaen.core.Updatable;
import org.cogaen.core.UpdateableService;
import org.cogaen.name.CogaenId;
import org.cogaen.util.Bag;
public class EntityService extends UpdateableService {
public static final CogaenId ID = new CogaenId("org.cogaen.entity.EntityService");
public static final String NAME = "Cogaen Entity Service";
private Map<CogaenId, Entity> entitiesMap = new HashMap<CogaenId, Entity>();
private List<Entity> entities = new ArrayList<Entity>();
private List<Entity> entitiesToRemove = new ArrayList<Entity>();
private Bag<Updatable> updateables = new Bag<Updatable>();
public static EntityService getInstance(Core core) {
return (EntityService) core.getService(ID);
}
public EntityService() {
// intentionally left empty
}
@Override
public CogaenId getId() {
return ID;
}
@Override
public String getName() {
return NAME;
}
@Override
public void update() {
for (Entity entity : this.entitiesToRemove) {
this.entitiesMap.remove(entity.getId());
this.entities.remove(entity);
entity.disengage();
}
this.entitiesToRemove.clear();
for (updateables.reset(); updateables.hasNext();) {
updateables.next().update();
}
}
public void addEntity(Entity entity) {
CogaenId id = entity.getId();
Entity old = this.entitiesMap.put(id, entity);
if (old != null) {
this.entitiesMap.put(id, old);
throw new RuntimeException("ambiguous entity id " + id);
}
this.entities.add(entity);
entity.engage();
}
public void removeEntity(CogaenId entityId) {
this.entitiesToRemove.add(getEntity(entityId));
}
public boolean hasEntity(CogaenId entityId) {
return this.entitiesMap.containsKey(entityId);
}
public void removeAllEntities() {
for (Entity entity : this.entitiesMap.values()) {
entity.disengage();
}
this.entitiesMap.clear();
this.entities.clear();
}
public Entity getEntity(CogaenId entityId) {
Entity entity = this.entitiesMap.get(entityId);
if (entity == null) {
throw new RuntimeException("unknown entity " + entityId);
}
return entity;
}
public Entity getEntity(int idx) {
return this.entities.get(idx);
}
public void addUpdatable(Updatable updateable) {
this.updateables.add(updateable);
}
public void removeUpdatable(Updatable updateable) {
this.updateables.remove(updateable);
}
public int numEntities() {
return this.entitiesMap.size();
}
}
| mit |
YunaBraska/Challenge-Statistic-Counter | src/main/java/com/springfrosch/challenge/statistic/configuration/TimeConfig.java | 338 | package com.springfrosch.challenge.statistic.configuration;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
@Configuration
public class TimeConfig {
@PostConstruct
void started() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
}
| mit |
garymabin/YGOMobile | apache-async-http-HC4/src/org/apache/http/HC4/impl/nio/codecs/IdentityDecoder.java | 4857 | /*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.HC4.impl.nio.codecs;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.HC4.annotation.NotThreadSafe;
import org.apache.http.HC4.nio.FileContentDecoder;
import org.apache.http.HC4.nio.reactor.SessionInputBuffer;
import org.apache.http.HC4.util.Args;
import org.apache.http.HC4.impl.io.HttpTransportMetricsImpl;
/**
* Content decoder that reads data without any transformation. The end of the
* content entity is delineated by closing the underlying connection
* (EOF condition). Entities transferred using this input stream can be of
* unlimited length.
* <p>
* This decoder is optimized to transfer data directly from the underlying
* I/O session's channel to a {@link FileChannel}, whenever
* possible avoiding intermediate buffering in the session buffer.
*
* @since 4.0
*/
@NotThreadSafe
public class IdentityDecoder extends AbstractContentDecoder
implements FileContentDecoder {
public IdentityDecoder(
final ReadableByteChannel channel,
final SessionInputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super(channel, buffer, metrics);
}
/**
* Sets the completed status of this decoder. Normally this is not necessary
* (the decoder will automatically complete when the underlying channel
* returns EOF). It is useful to mark the decoder as completed if you have
* some other means to know all the necessary data has been read and want to
* reuse the underlying connection for more messages.
*/
public void setCompleted(final boolean completed) {
this.completed = completed;
}
@Override
public int read(final ByteBuffer dst) throws IOException {
Args.notNull(dst, "Byte buffer");
if (this.completed) {
return -1;
}
final int bytesRead;
if (this.buffer.hasData()) {
bytesRead = this.buffer.read(dst);
} else {
bytesRead = readFromChannel(dst);
}
if (bytesRead == -1) {
this.completed = true;
}
return bytesRead;
}
@Override
public long transfer(
final FileChannel dst,
final long position,
final long count) throws IOException {
if (dst == null) {
return 0;
}
if (this.completed) {
return 0;
}
long bytesRead;
if (this.buffer.hasData()) {
dst.position(position);
bytesRead = this.buffer.read(dst);
} else {
if (this.channel.isOpen()) {
if (position > dst.size()) {
throw new IOException("Position past end of file [" + position +
" > " + dst.size() + "]");
}
bytesRead = dst.transferFrom(this.channel, position, count);
if (count > 0 && bytesRead == 0) {
bytesRead = this.buffer.fill(this.channel);
}
} else {
bytesRead = -1;
}
if (bytesRead > 0) {
this.metrics.incrementBytesTransferred(bytesRead);
}
}
if (bytesRead == -1) {
this.completed = true;
}
return bytesRead;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("[identity; completed: ");
sb.append(this.completed);
sb.append("]");
return sb.toString();
}
}
| mit |
SpongePowered/Mixin | src/ap/java/org/spongepowered/tools/obfuscation/mirror/TypeHandleSimulated.java | 7426 | /*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.tools.obfuscation.mirror;
import java.lang.annotation.Annotation;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName;
import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod;
import org.spongepowered.asm.util.SignaturePrinter;
/**
* A simulated type handle, used with virtual (pseudo) mixins. For obfuscation
* purposes, we have to use some kind of context to resolve target members so
* that appropriate refmaps can be generated. For this purpose we use the mixin
* itself as the context in order to allow us to look up members in superclasses
* and superinterfaces of the mixin (in the hope that we can locate targets
* there. If we cannot achieve this, then remapping will have to be done by hand
*/
public class TypeHandleSimulated extends TypeHandle {
private final TypeElement simulatedType;
public TypeHandleSimulated(String name, TypeMirror type) {
this(TypeUtils.getPackage(type), name, type);
}
public TypeHandleSimulated(PackageElement pkg, String name, TypeMirror type) {
super(pkg, name);
this.simulatedType = (TypeElement)((DeclaredType)type).asElement();
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.mirror.TypeHandle
* #getTargetElement()
*/
@Override
protected TypeElement getTargetElement() {
return this.simulatedType;
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.mirror.TypeHandle#isPublic()
*/
@Override
public boolean isPublic() {
// We have no idea
return true;
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.mirror.TypeHandle#isImaginary()
*/
@Override
public boolean isImaginary() {
// it actually is, but we need the AP to assume that it isn't
return false;
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.mirror.TypeHandle#isSimulated()
*/
@Override
public boolean isSimulated() {
// hell yeah
return true;
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.mirror.TypeHandle
* #getAnnotation(java.lang.Class)
*/
@Override
public AnnotationHandle getAnnotation(Class<? extends Annotation> annotationClass) {
// nope
return null;
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.mirror.TypeHandle
* #getSuperclass()
*/
@Override
public TypeHandle getSuperclass() {
return null;
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.mirror.TypeHandle
* #findDescriptor(org.spongepowered.asm.mixin.injection.struct.MemberInfo)
*/
@Override
public String findDescriptor(ITargetSelectorByName memberInfo) {
// Identity, refs need to be FQ
return memberInfo != null ? memberInfo.getDesc() : null;
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.mirror.TypeHandle
* #findField(java.lang.String, java.lang.String, boolean)
*/
@Override
public FieldHandle findField(String name, String type, boolean caseSensitive) {
return new FieldHandle((String)null, name, type);
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.mirror.TypeHandle
* #findMethod(java.lang.String, java.lang.String, boolean)
*/
@Override
public MethodHandle findMethod(String name, String desc, boolean caseSensitive) {
// assume we find it
return new MethodHandle(null, name, desc);
}
/* (non-Javadoc)
* @see org.spongepowered.tools.obfuscation.mirror.TypeHandle
* #getMappingMethod(java.lang.String, java.lang.String)
*/
@Override
public MappingMethod getMappingMethod(String name, String desc) {
// Transform the MemberInfo descriptor into a signature
String signature = new SignaturePrinter(name, desc).setFullyQualified(true).toDescriptor();
String rawSignature = TypeUtils.stripGenerics(signature);
// Try to locate a member anywhere in the hierarchy which matches
MethodHandle method = TypeHandleSimulated.findMethodRecursive(this, name, signature, rawSignature, true);
// If we find one, return it otherwise just simulate the method
return method != null ? method.asMapping(true) : super.getMappingMethod(name, desc);
}
private static MethodHandle findMethodRecursive(TypeHandle target, String name, String signature, String rawSignature, boolean matchCase) {
TypeElement elem = target.getTargetElement();
if (elem == null) {
return null;
}
MethodHandle method = TypeHandle.findMethod(target, name, signature, rawSignature, matchCase);
if (method != null) {
return method;
}
for (TypeMirror iface : elem.getInterfaces()) {
method = TypeHandleSimulated.findMethodRecursive(iface, name, signature, rawSignature, matchCase);
if (method != null) {
return method;
}
}
TypeMirror superClass = elem.getSuperclass();
if (superClass == null || superClass.getKind() == TypeKind.NONE) {
return null;
}
return TypeHandleSimulated.findMethodRecursive(superClass, name, signature, rawSignature, matchCase);
}
private static MethodHandle findMethodRecursive(TypeMirror target, String name, String signature, String rawSignature, boolean matchCase) {
if (!(target instanceof DeclaredType)) {
return null;
}
TypeElement element = (TypeElement)((DeclaredType)target).asElement();
return TypeHandleSimulated.findMethodRecursive(new TypeHandle(element), name, signature, rawSignature, matchCase);
}
}
| mit |
McJty/ImmersiveCraft | src/main/java/mcjty/immcraft/blocks/generic/handles/ICraftingContainer.java | 362 | package mcjty.immcraft.blocks.generic.handles;
import mcjty.immcraft.schemas.Schema;
import net.minecraft.item.ItemStack;
import java.util.List;
public interface ICraftingContainer {
Schema getCurrentSchema();
void nextSchema();
void previousSchema();
List<ItemStack> getInventory();
void updateInventory(List<ItemStack> inventory);
}
| mit |
GluuFederation/oxTrust | model/src/main/java/org/gluu/oxtrust/model/InumConf.java | 1842 | /*
* oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxtrust.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/**
* InumConfig
*
* @author Reda Zerrad Date: 08.22.2012
*/
@XmlRootElement(name = "InumConfig")
@XmlAccessorType(XmlAccessType.FIELD)
@JsonPropertyOrder({ "personPrefix", "groupPrefix", "clientPrefix", "scopePrefix", "scriptName" })
@XmlType(propOrder = { "personPrefix", "groupPrefix", "clientPrefix", "scopePrefix", "scriptName" })
public class InumConf {
private String personPrefix;
private String groupPrefix;
private String clientPrefix;
private String scopePrefix;
private String scriptName;
public InumConf() {
personPrefix = "";
groupPrefix = "";
clientPrefix = "";
scopePrefix = "";
scriptName = "";
}
public String getPersonPrefix() {
return this.personPrefix;
}
public void setPersonPrefix(String personPrefix) {
this.personPrefix = personPrefix;
}
public String getGroupPrefix() {
return this.groupPrefix;
}
public void setGroupPrefix(String groupPrefix) {
this.groupPrefix = groupPrefix;
}
public String getClientPrefix() {
return this.clientPrefix;
}
public void setClientPrefix(String clientPrefix) {
this.clientPrefix = clientPrefix;
}
public String getScopePrefix() {
return this.scopePrefix;
}
public void setScopePrefix(String scopePrefix) {
this.scopePrefix = scopePrefix;
}
public String getScriptName() {
return this.scriptName;
}
public void setScriptName(String scriptName) {
this.scriptName = scriptName;
}
}
| mit |
archimatetool/archi | com.archimatetool.model/src/com/archimatetool/model/ISpecializationRelationship.java | 572 | /**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.model;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Specialization Relationship</b></em>'.
* <!-- end-user-doc -->
*
*
* @see com.archimatetool.model.IArchimatePackage#getSpecializationRelationship()
* @model
* @generated
*/
public interface ISpecializationRelationship extends IOtherRelationship {
} // ISpecializationRelationship
| mit |
vincentzhang96/HearthCaptureLib | src/main/java/co/phoenixlab/hearthstone/hearthcapturelib/tcp/TCPPacket.java | 3205 | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Vincent Zhang
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package co.phoenixlab.hearthstone.hearthcapturelib.tcp;
import org.jnetpcap.nio.JBuffer;
import org.jnetpcap.nio.JMemory;
import org.jnetpcap.packet.PcapPacket;
import org.jnetpcap.protocol.network.Ip4;
import org.jnetpcap.protocol.tcpip.Tcp;
import java.time.Instant;
public class TCPPacket implements Comparable<TCPPacket> {
public final Instant packetTime;
public final TCPConnectionInfo connectionInfo;
/**
* @see org.jnetpcap.protocol.tcpip.Tcp#flags()
*/
public final int tcpFlags;
/**
* The TCP SEQ number, used to track packet ordering and duplicate data.
*/
public final long seqNumber;
public final long ackNumber;
public final byte[] payload;
public TCPPacket(PcapPacket packet) {
packetTime = Instant.now();
Ip4 ip4 = packet.getHeader(new Ip4());
Tcp tcp = packet.getHeader(new Tcp());
connectionInfo = new TCPConnectionInfo(ip4.sourceToInt(), tcp.source(), ip4.destinationToInt(), tcp.destination());
seqNumber = tcp.seq();
ackNumber = tcp.ack();
tcpFlags = tcp.flags();
JBuffer storage = new JBuffer(JMemory.Type.POINTER);
JBuffer packetPayload = tcp.peerPayloadTo(storage);
payload = new byte[packetPayload.size()];
packetPayload.getByteArray(0, payload);
}
public long nextExpectedSeqNumber() {
// If the ACK flag is set then SEQ must advance by at least one, otherwise SEQ is not incremented.
return seqNumber + ((tcpFlags & 0x10) != 0 ? Math.max(1, payload.length) : 0);
}
@Override
public int compareTo(TCPPacket o) {
return Long.compare(seqNumber, o.seqNumber);
}
public int getByte(long byteNum) {
long internByte = byteNum - seqNumber;
boolean greater = internByte >= 0;
boolean less = internByte < payload.length;
if (greater && less) {
return Byte.toUnsignedInt(payload[(int) internByte]);
}
if (!greater) {
return -1;
}
return -2;
}
}
| mit |
JimiPepper/passmember | src/main/java/rose/project/passmember/gui/event/ImplTreeSelectionExpandListener.java | 1949 | package rose.project.passmember.gui.event;
import rose.project.passmember.gui.JTreeWrapper;
import rose.project.passmember.gui.PassViewerPanel;
import rose.project.passmember.util.entry.FolderEntry;
import javax.swing.event.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreePath;
/**
* Created by Lord Rose on 07/04/2017.
*/
public class ImplTreeSelectionExpandListener implements TreeSelectionListener, TreeWillExpandListener {
private JTreeWrapper GUITree;
private PassViewerPanel viewerPanel;
public ImplTreeSelectionExpandListener(JTreeWrapper GUITree, PassViewerPanel viewerPanel) {
this.GUITree = GUITree;
this.viewerPanel = viewerPanel;
}
@Override
public void valueChanged(TreeSelectionEvent e) {
System.out.println(e.getPath().toString());
if(GUITree.hasSelection()) {
TreePath currentPath = this.GUITree.getGUITree().getSelectionPath();
if(currentPath == null) {
this.GUITree.setCurrentSelectedNode(this.GUITree.getPasswordsTree()); //root
}
else {
this.GUITree.setCurrentSelectedNode((DefaultMutableTreeNode) currentPath.getLastPathComponent());
}
this.viewerPanel.loadSavedPassword(this.GUITree.getEntry());
}
}
@Override
public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
DefaultMutableTreeNode expandedNode = (DefaultMutableTreeNode)event.getPath().getLastPathComponent();
((FolderEntry)expandedNode.getUserObject()).show = true;
}
@Override
public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
DefaultMutableTreeNode expandedNode = (DefaultMutableTreeNode)event.getPath().getLastPathComponent();
((FolderEntry)expandedNode.getUserObject()).show = false;
}
}
| mit |
Bitcoinsulting/Qora | Qora/src/qora/transaction/RegisterNameTransaction.java | 9007 | package qora.transaction;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.simple.JSONObject;
import qora.account.Account;
import qora.account.PrivateKeyAccount;
import qora.account.PublicKeyAccount;
import qora.crypto.Crypto;
import qora.naming.Name;
import com.google.common.primitives.Bytes;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import database.DBSet;
public class RegisterNameTransaction extends Transaction
{
private static final int REGISTRANT_LENGTH = 32;
private static final int REFERENCE_LENGTH = 64;
private static final int FEE_LENGTH = 8;
private static final int SIGNATURE_LENGTH = 64;
private static final int BASE_LENGTH = TIMESTAMP_LENGTH + REFERENCE_LENGTH + REGISTRANT_LENGTH + FEE_LENGTH + SIGNATURE_LENGTH;
private PublicKeyAccount registrant;
private Name name;
public RegisterNameTransaction(PublicKeyAccount registrant, Name name, BigDecimal fee, long timestamp, byte[] reference, byte[] signature)
{
super(REGISTER_NAME_TRANSACTION, fee, timestamp, reference, signature);
this.registrant = registrant;
this.name = name;
}
//GETTERS/SETTERS
public PublicKeyAccount getRegistrant()
{
return this.registrant;
}
public Name getName()
{
return this.name;
}
//PARSE CONVERT
public static Transaction Parse(byte[] data) throws Exception
{
//CHECK IF WE MATCH BLOCK LENGTH
if(data.length < BASE_LENGTH)
{
throw new Exception("Data does not match block length");
}
int position = 0;
//READ TIMESTAMP
byte[] timestampBytes = Arrays.copyOfRange(data, position, position + TIMESTAMP_LENGTH);
long timestamp = Longs.fromByteArray(timestampBytes);
position += TIMESTAMP_LENGTH;
//READ REFERENCE
byte[] reference = Arrays.copyOfRange(data, position, position + REFERENCE_LENGTH);
position += REFERENCE_LENGTH;
//READ REGISTRANT
byte[] registrantBytes = Arrays.copyOfRange(data, position, position + REGISTRANT_LENGTH);
PublicKeyAccount registrant = new PublicKeyAccount(registrantBytes);
position += REGISTRANT_LENGTH;
//READ NAME
Name name = Name.Parse(Arrays.copyOfRange(data, position, data.length));
position += name.getDataLength();
//READ FEE
byte[] feeBytes = Arrays.copyOfRange(data, position, position + FEE_LENGTH);
BigDecimal fee = new BigDecimal(new BigInteger(feeBytes), 8);
position += FEE_LENGTH;
//READ SIGNATURE
byte[] signatureBytes = Arrays.copyOfRange(data, position, position + SIGNATURE_LENGTH);
return new RegisterNameTransaction(registrant, name, fee, timestamp, reference, signatureBytes);
}
@SuppressWarnings("unchecked")
@Override
public JSONObject toJson()
{
//GET BASE
JSONObject transaction = this.getJsonBase();
//ADD REGISTRANT/NAME/VALUE
transaction.put("registrant", this.registrant.getAddress());
transaction.put("owner", this.name.getOwner().getAddress());
transaction.put("name", this.name.getName());
transaction.put("value", this.name.getValue());
return transaction;
}
@Override
public byte[] toBytes()
{
byte[] data = new byte[0];
//WRITE TYPE
byte[] typeBytes = Ints.toByteArray(REGISTER_NAME_TRANSACTION);
typeBytes = Bytes.ensureCapacity(typeBytes, TYPE_LENGTH, 0);
data = Bytes.concat(data, typeBytes);
//WRITE TIMESTAMP
byte[] timestampBytes = Longs.toByteArray(this.timestamp);
timestampBytes = Bytes.ensureCapacity(timestampBytes, TIMESTAMP_LENGTH, 0);
data = Bytes.concat(data, timestampBytes);
//WRITE REFERENCE
data = Bytes.concat(data, this.reference);
//WRITE REGISTRANT
data = Bytes.concat(data, this.registrant.getPublicKey());
//WRITE NAME
data = Bytes.concat(data , this.name.toBytes());
//WRITE FEE
byte[] feeBytes = this.fee.unscaledValue().toByteArray();
byte[] fill = new byte[FEE_LENGTH - feeBytes.length];
feeBytes = Bytes.concat(fill, feeBytes);
data = Bytes.concat(data, feeBytes);
//SIGNATURE
data = Bytes.concat(data, this.signature);
return data;
}
@Override
public int getDataLength()
{
return TYPE_LENGTH + BASE_LENGTH + this.name.getDataLength();
}
//VALIDATE
public boolean isSignatureValid()
{
byte[] data = new byte[0];
//WRITE TYPE
byte[] typeBytes = Ints.toByteArray(REGISTER_NAME_TRANSACTION);
typeBytes = Bytes.ensureCapacity(typeBytes, TYPE_LENGTH, 0);
data = Bytes.concat(data, typeBytes);
//WRITE TIMESTAMP
byte[] timestampBytes = Longs.toByteArray(this.timestamp);
timestampBytes = Bytes.ensureCapacity(timestampBytes, TIMESTAMP_LENGTH, 0);
data = Bytes.concat(data, timestampBytes);
//WRITE REFERENCE
data = Bytes.concat(data, this.reference);
//WRITE REGISTRANT
data = Bytes.concat(data, this.registrant.getPublicKey());
//WRITE NAME
data = Bytes.concat(data , this.name.toBytes());
//WRITE FEE
byte[] feeBytes = this.fee.unscaledValue().toByteArray();
byte[] fill = new byte[FEE_LENGTH - feeBytes.length];
feeBytes = Bytes.concat(fill, feeBytes);
data = Bytes.concat(data, feeBytes);
return Crypto.getInstance().verify(this.registrant.getPublicKey(), this.signature, data);
}
@Override
public int isValid(DBSet db)
{
//CHECK NAME LENGTH
int nameLength = this.name.getName().getBytes(StandardCharsets.UTF_8).length;
if(nameLength > 400 || nameLength < 1)
{
return INVALID_NAME_LENGTH;
}
//CHECK IF LOWERCASE
if(!this.name.getName().equals(this.name.getName().toLowerCase()))
{
return NAME_NOT_LOWER_CASE;
}
//CHECK VALUE LENGTH
int valueLength = this.name.getValue().getBytes(StandardCharsets.UTF_8).length;
if(valueLength > 4000 || valueLength < 1)
{
return INVALID_VALUE_LENGTH;
}
//CHECK OWNER
if(!Crypto.getInstance().isValidAddress(this.name.getOwner().getAddress()))
{
return INVALID_ADDRESS;
}
//CHECK NAME NOT REGISTRED ALREADY
if(db.getNameMap().contains(this.name))
{
return NAME_ALREADY_REGISTRED;
}
//CHECK IF REGISTRANT HAS ENOUGH MONEY
if(this.registrant.getBalance(1, db).compareTo(this.fee) == -1)
{
return NO_BALANCE;
}
//CHECK IF REFERENCE IS OKE
if(!Arrays.equals(this.registrant.getLastReference(db), this.reference))
{
return INVALID_REFERENCE;
}
//CHECK IF FEE IS POSITIVE
if(this.fee.compareTo(BigDecimal.ZERO) <= 0)
{
return NEGATIVE_FEE;
}
return VALIDATE_OKE;
}
//PROCESS/ORPHAN
@Override
public void process(DBSet db)
{
//UPDATE OWNER
this.registrant.setConfirmedBalance(this.registrant.getConfirmedBalance(db).subtract(this.fee), db);
//UPDATE REFERENCE OF OWNER
this.registrant.setLastReference(this.signature, db);
//INSERT INTO DATABASE
db.getNameMap().add(this.name);
}
@Override
public void orphan(DBSet db)
{
//UPDATE OWNER
this.registrant.setConfirmedBalance(this.registrant.getConfirmedBalance(db).add(this.fee), db);
//UPDATE REFERENCE OF OWNER
this.registrant.setLastReference(this.reference, db);
//INSERT INTO DATABASE
db.getNameMap().delete(this.name);
}
@Override
public PublicKeyAccount getCreator()
{
return this.registrant;
}
@Override
public List<Account> getInvolvedAccounts()
{
List<Account> accounts = new ArrayList<Account>();
accounts.add(this.registrant);
accounts.add(this.name.getOwner());
return accounts;
}
@Override
public boolean isInvolved(Account account)
{
String address = account.getAddress();
if(address.equals(this.registrant.getAddress()) || address.equals(this.name.getOwner().getAddress()))
{
return true;
}
return false;
}
@Override
public BigDecimal getAmount(Account account)
{
if(account.getAddress().equals(this.registrant.getAddress()))
{
return BigDecimal.ZERO.setScale(8).subtract(this.fee);
}
return BigDecimal.ZERO;
}
public static byte[] generateSignature(DBSet db, PrivateKeyAccount creator, Name name, BigDecimal fee, long timestamp)
{
byte[] data = new byte[0];
//WRITE TYPE
byte[] typeBytes = Ints.toByteArray(REGISTER_NAME_TRANSACTION);
typeBytes = Bytes.ensureCapacity(typeBytes, TYPE_LENGTH, 0);
data = Bytes.concat(data, typeBytes);
//WRITE TIMESTAMP
byte[] timestampBytes = Longs.toByteArray(timestamp);
timestampBytes = Bytes.ensureCapacity(timestampBytes, TIMESTAMP_LENGTH, 0);
data = Bytes.concat(data, timestampBytes);
//WRITE REFERENCE
data = Bytes.concat(data, creator.getLastReference(db));
//WRITE REGISTRANT
data = Bytes.concat(data, creator.getPublicKey());
//WRITE NAME
data = Bytes.concat(data , name.toBytes());
//WRITE FEE
byte[] feeBytes = fee.unscaledValue().toByteArray();
byte[] fill = new byte[FEE_LENGTH - feeBytes.length];
feeBytes = Bytes.concat(fill, feeBytes);
data = Bytes.concat(data, feeBytes);
return Crypto.getInstance().sign(creator, data);
}
}
| mit |
rainu/alexa-skill | cloud/src/main/java/de/rainu/alexa/cloud/calendar/exception/CalendarReadException.java | 487 | package de.rainu.alexa.cloud.calendar.exception;
/**
* This {@link Exception} should be thrown every times if the calendar could not read.
*/
public class CalendarReadException extends AlexaExcpetion {
private static final String ERROR_MESSAGE_KEY = "event.error.read";
public CalendarReadException(String message) {
super(ERROR_MESSAGE_KEY, message);
}
public CalendarReadException(String message, Throwable cause) {
super(ERROR_MESSAGE_KEY, message, cause);
}
}
| mit |
dbwiddis/oshi | oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java | 9336 | /*
* MIT License
*
* Copyright (c) 2016-2022 The OSHI Project Contributors: https://github.com/oshi/oshi/graphs/contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package oshi.util.platform.mac;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jna.NativeLong;
import com.sun.jna.platform.mac.IOKit.IOConnect;
import com.sun.jna.platform.mac.IOKit.IOService;
import com.sun.jna.platform.mac.IOKitUtil;
import com.sun.jna.ptr.NativeLongByReference;
import com.sun.jna.ptr.PointerByReference;
import oshi.annotation.concurrent.ThreadSafe;
import oshi.jna.platform.mac.IOKit;
import oshi.jna.platform.mac.IOKit.SMCKeyData;
import oshi.jna.platform.mac.IOKit.SMCKeyDataKeyInfo;
import oshi.jna.platform.mac.IOKit.SMCVal;
import oshi.jna.platform.mac.SystemB;
import oshi.util.ParseUtil;
/**
* Provides access to SMC calls on macOS
*/
@ThreadSafe
public final class SmcUtil {
private static final Logger LOG = LoggerFactory.getLogger(SmcUtil.class);
private static final IOKit IO = IOKit.INSTANCE;
/**
* Thread-safe map for caching info retrieved by a key necessary for subsequent
* calls.
*/
private static Map<Integer, SMCKeyDataKeyInfo> keyInfoCache = new ConcurrentHashMap<>();
/**
* Byte array used for matching return type
*/
private static final byte[] DATATYPE_SP78 = ParseUtil.asciiStringToByteArray("sp78", 5);
private static final byte[] DATATYPE_FPE2 = ParseUtil.asciiStringToByteArray("fpe2", 5);
private static final byte[] DATATYPE_FLT = ParseUtil.asciiStringToByteArray("flt ", 5);
public static final String SMC_KEY_FAN_NUM = "FNum";
public static final String SMC_KEY_FAN_SPEED = "F%dAc";
public static final String SMC_KEY_CPU_TEMP = "TC0P";
public static final String SMC_KEY_CPU_VOLTAGE = "VC0C";
public static final byte SMC_CMD_READ_BYTES = 5;
public static final byte SMC_CMD_READ_KEYINFO = 9;
public static final int KERNEL_INDEX_SMC = 2;
private SmcUtil() {
}
/**
* Open a connection to SMC.
*
* @return The connection if successful, null if failure
*/
public static IOConnect smcOpen() {
IOService smcService = IOKitUtil.getMatchingService("AppleSMC");
if (smcService != null) {
PointerByReference connPtr = new PointerByReference();
int result = IO.IOServiceOpen(smcService, SystemB.INSTANCE.mach_task_self(), 0, connPtr);
smcService.release();
if (result == 0) {
return new IOConnect(connPtr.getValue());
} else if (LOG.isErrorEnabled()) {
LOG.error(String.format("Unable to open connection to AppleSMC service. Error: 0x%08x", result));
}
} else {
LOG.error("Unable to locate AppleSMC service");
}
return null;
}
/**
* Close connection to SMC.
*
* @param conn
* The connection
*
* @return 0 if successful, nonzero if failure
*/
public static int smcClose(IOConnect conn) {
return IO.IOServiceClose(conn);
}
/**
* Get a value from SMC which is in a floating point datatype (SP78, FPE2, FLT)
*
* @param conn
* The connection
* @param key
* The key to retrieve
* @return Double representing the value
*/
public static double smcGetFloat(IOConnect conn, String key) {
SMCVal val = new SMCVal();
int result = smcReadKey(conn, key, val);
if (result == 0 && val.dataSize > 0) {
if (Arrays.equals(val.dataType, DATATYPE_SP78) && val.dataSize == 2) {
// First bit is sign, next 7 bits are integer portion, last 8 bits are
// fractional portion
return val.bytes[0] + val.bytes[1] / 256d;
} else if (Arrays.equals(val.dataType, DATATYPE_FPE2) && val.dataSize == 2) {
// First E (14) bits are integer portion last 2 bits are fractional portion
return ParseUtil.byteArrayToFloat(val.bytes, val.dataSize, 2);
} else if (Arrays.equals(val.dataType, DATATYPE_FLT) && val.dataSize == 4) {
// Standard 32-bit floating point
return ByteBuffer.wrap(val.bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat();
}
}
// Read failed
return 0d;
}
/**
* Get a 64-bit integer value from SMC
*
* @param conn
* The connection
* @param key
* The key to retrieve
* @return Long representing the value
*/
public static long smcGetLong(IOConnect conn, String key) {
SMCVal val = new SMCVal();
int result = smcReadKey(conn, key, val);
if (result == 0) {
return ParseUtil.byteArrayToLong(val.bytes, val.dataSize);
}
// Read failed
return 0;
}
/**
* Get cached keyInfo if it exists, or generate new keyInfo
*
* @param conn
* The connection
* @param inputStructure
* Key data input
* @param outputStructure
* Key data output
* @return 0 if successful, nonzero if failure
*/
public static int smcGetKeyInfo(IOConnect conn, SMCKeyData inputStructure, SMCKeyData outputStructure) {
if (keyInfoCache.containsKey(inputStructure.key)) {
SMCKeyDataKeyInfo keyInfo = keyInfoCache.get(inputStructure.key);
outputStructure.keyInfo.dataSize = keyInfo.dataSize;
outputStructure.keyInfo.dataType = keyInfo.dataType;
outputStructure.keyInfo.dataAttributes = keyInfo.dataAttributes;
} else {
inputStructure.data8 = SMC_CMD_READ_KEYINFO;
int result = smcCall(conn, KERNEL_INDEX_SMC, inputStructure, outputStructure);
if (result != 0) {
return result;
}
SMCKeyDataKeyInfo keyInfo = new SMCKeyDataKeyInfo();
keyInfo.dataSize = outputStructure.keyInfo.dataSize;
keyInfo.dataType = outputStructure.keyInfo.dataType;
keyInfo.dataAttributes = outputStructure.keyInfo.dataAttributes;
keyInfoCache.put(inputStructure.key, keyInfo);
}
return 0;
}
/**
* Read a key from SMC
*
* @param conn
* The connection
* @param key
* Key to read
* @param val
* Structure to receive the result
* @return 0 if successful, nonzero if failure
*/
public static int smcReadKey(IOConnect conn, String key, SMCVal val) {
SMCKeyData inputStructure = new SMCKeyData();
SMCKeyData outputStructure = new SMCKeyData();
inputStructure.key = (int) ParseUtil.strToLong(key, 4);
int result = smcGetKeyInfo(conn, inputStructure, outputStructure);
if (result == 0) {
val.dataSize = outputStructure.keyInfo.dataSize;
val.dataType = ParseUtil.longToByteArray(outputStructure.keyInfo.dataType, 4, 5);
inputStructure.keyInfo.dataSize = val.dataSize;
inputStructure.data8 = SMC_CMD_READ_BYTES;
result = smcCall(conn, KERNEL_INDEX_SMC, inputStructure, outputStructure);
if (result == 0) {
System.arraycopy(outputStructure.bytes, 0, val.bytes, 0, val.bytes.length);
return 0;
}
}
return result;
}
/**
* Call SMC
*
* @param conn
* The connection
* @param index
* Kernel index
* @param inputStructure
* Key data input
* @param outputStructure
* Key data output
* @return 0 if successful, nonzero if failure
*/
public static int smcCall(IOConnect conn, int index, SMCKeyData inputStructure, SMCKeyData outputStructure) {
return IO.IOConnectCallStructMethod(conn, index, inputStructure, new NativeLong(inputStructure.size()),
outputStructure, new NativeLongByReference(new NativeLong(outputStructure.size())));
}
}
| mit |
timnew/RemoteImagePicker | RemoteImagePicker/src/main/java/me/timnew/remoteimagepicker/ImagePickerActivity.java | 8973 | package me.timnew.remoteimagepicker;
import android.app.ActionBar;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.future.ImageViewFuture;
import me.timnew.remoteimagepicker.events.ImagePickedEvent;
import me.timnew.remoteimagepicker.events.PreviewImageEvent;
import me.timnew.remoteimagepicker.images.RestClient;
import me.timnew.shared.events.Bus;
import org.androidannotations.annotations.*;
import java.io.File;
import java.io.IOException;
import static android.view.Gravity.LEFT;
@EActivity(R.layout.activity_image_picker)
public class ImagePickerActivity extends FragmentActivity {
public static final String TAG_IMAGE_LIST = "image_list";
public static final String TAG_IMAGE_PREVIEW = "image_preview";
@ViewById(R.id.drawer_layout)
protected DrawerLayout drawerLayout;
private ActionBar actionBar;
protected ActionBarDrawerToggle drawerToggle;
@Bean
protected Bus bus;
@Bean
protected RestClient client;
@AfterViews
protected void afterViews() {
actionBar = getActionBar();
//noinspection ConstantConditions
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
drawerToggle = new SlidingMenuToggle();
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
bus.register(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
bus.unregister(this);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
@OptionsItem(android.R.id.home)
public void toggleSlidingMenu() {
if (isSlidingMenuShown()) {
closeSlidingMenu();
} else {
openSlidingMenu();
}
}
public boolean isSlidingMenuShown() {
return drawerLayout.isDrawerOpen(LEFT);
}
public void openSlidingMenu() {
drawerLayout.openDrawer(LEFT);
}
public void closeSlidingMenu() {
drawerLayout.closeDrawer(LEFT);
}
public void onEvent(SlidingMenuCommands command) {
command.applyTo(this);
}
public void onEvent(final PreviewImageEvent event) {
DialogFragment previewFragment = new DialogFragment() {
private ImageViewFuture downloadImageRequest;
private void downloadImage(ImageView imageView) {
cancelRequest();
downloadImageRequest = client.previewImage(event.imageInfo, imageView);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialog = new Dialog(ImagePickerActivity.this, android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(R.layout.preview_image_dialog);
final ImageView imageView = (ImageView) dialog.findViewById(R.id.image_view);
RelativeLayout layout = (RelativeLayout) dialog.findViewById(R.id.container);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ImagePickedEvent pickedEvent = new ImagePickedEvent(event.imageInfo);
bus.post(pickedEvent);
dialog.dismiss();
}
});
layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
downloadImage(imageView);
}
});
return dialog;
}
@Override
public void onDetach() {
super.onDetach();
cancelRequest();
}
private void cancelRequest() {
if (downloadImageRequest != null && !downloadImageRequest.isDone()) {
downloadImageRequest.cancel(true);
}
}
};
FragmentTransaction fragmentTransaction = getSupportFragmentManager()
.beginTransaction()
.addToBackStack(TAG_IMAGE_PREVIEW);
previewFragment.show(fragmentTransaction, TAG_IMAGE_PREVIEW);
}
public void onEvent(ImagePickedEvent event) {
Intent intent = getIntent();
String action = intent.getAction();
if (action.equals(MediaStore.ACTION_IMAGE_CAPTURE)) {
Uri outputPath = intent.getParcelableExtra(MediaStore.EXTRA_OUTPUT);
if (outputPath == null) {
client.downloadBitmap(event.imageInfo).setCallback(new FutureCallback<Bitmap>() {
@Override
public void onCompleted(Exception e, Bitmap bitmap) {
Intent resultIntent = new Intent();
resultIntent.putExtra(MediaStore.EXTRA_OUTPUT, bitmap);
setResult(RESULT_OK, resultIntent);
finish();
}
});
} else {
client.download(event.imageInfo, new File(outputPath.getPath())).setCallback(new FutureCallback<File>() {
@Override
public void onCompleted(Exception e, File file) {
setResult(RESULT_OK, new Intent());
finish();
}
});
}
} else if (action.equals(Intent.ACTION_GET_CONTENT)) {
try {
File outputDir = getCacheDir();
File tempFile = File.createTempFile("remote-image", ".jpg", outputDir);
// FIXME: this apporoach doesn't work since the path is not guaranteed to be accessible from other apps.
client.download(event.imageInfo, tempFile).setCallback(new FutureCallback<File>() {
@Override
public void onCompleted(Exception e, File file) {
Uri uri = Uri.fromFile(file);
try {
if (e != null)
throw e;
Intent resultIntent = Intent.parseUri(uri.toString(), 0);
setResult(RESULT_OK, resultIntent);
finish();
} catch (Exception e1) {
e1.printStackTrace();
setResult(RESULT_CANCELED);
finish();
}
}
});
} catch (IOException e) {
e.printStackTrace();
setResult(RESULT_CANCELED);
finish();
}
}
}
public static enum SlidingMenuCommands {
OPEN_SLIDING_MENU {
@Override
void applyTo(ImagePickerActivity activity) {
activity.openSlidingMenu();
}
},
CLOSE_SLIDING_MENU {
@Override
void applyTo(ImagePickerActivity activity) {
activity.closeSlidingMenu();
}
};
abstract void applyTo(ImagePickerActivity activity);
}
private class SlidingMenuToggle extends ActionBarDrawerToggle {
public SlidingMenuToggle() {
super(ImagePickerActivity.this,
drawerLayout,
R.drawable.ic_navigation_drawer,
R.string.drawer_open, R.string.drawer_close);
}
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
actionBar.setTitle(ImagePickerActivity.this.getTitle());
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
actionBar.setTitle(R.string.sliding_menu_title);
invalidateOptionsMenu();
}
}
}
| mit |
Azure/azure-sdk-for-java | sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchContinuationToken.java | 3841 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.search.documents.implementation.models;
import com.azure.core.util.serializer.SerializerEncoding;
import com.azure.search.documents.util.SearchPagedResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.Objects;
import static com.azure.search.documents.implementation.util.Utility.getDefaultSerializerAdapter;
/**
* Serialization and deserialization of search page continuation token.
*/
public final class SearchContinuationToken {
/**
* Api version which is used by continuation token.
*/
public static final String API_VERSION = "apiVersion";
/**
* Next link which is used by continuation token.
*/
public static final String NEXT_LINK = "nextLink";
/**
* Next page parameters which is used by continuation token.
*/
public static final String NEXT_PAGE_PARAMETERS = "nextPageParameters";
private static final ObjectMapper MAPPER = new ObjectMapper();
private SearchContinuationToken() {
}
/**
* Serialize to search continuation token using {@code apiVersion}, {@code nextLink} and {@link SearchRequest}
*
* @param apiVersion The api version string.
* @param nextLink The next link from search document result. {@link SearchDocumentsResult}
* @param nextPageParameters {@link SearchRequest} The next page parameters which use to fetch next page.
* @return The search encoded continuation token.
*/
public static String serializeToken(String apiVersion, String nextLink, SearchRequest nextPageParameters) {
Objects.requireNonNull(apiVersion);
if (nextLink == null || nextPageParameters == null || nextPageParameters.getSkip() == null) {
return null;
}
String nextParametersString;
try {
nextParametersString = getDefaultSerializerAdapter().serialize(nextPageParameters, SerializerEncoding.JSON);
} catch (IOException ex) {
throw new IllegalStateException("Failed to serialize the search request.");
}
ObjectNode tokenJson = MAPPER.createObjectNode();
tokenJson.put(API_VERSION, apiVersion);
tokenJson.put(NEXT_LINK, nextLink);
tokenJson.put(NEXT_PAGE_PARAMETERS, nextParametersString);
return Base64.getEncoder().encodeToString(tokenJson.toString().getBytes(StandardCharsets.UTF_8));
}
/**
* Deserialize the continuation token to {@link SearchRequest}
*
* @param apiVersion The api version string.
* @param continuationToken The continuation token from {@link SearchPagedResponse}
* @return {@link SearchRequest} The search request used for fetching next page.
*/
@SuppressWarnings("unchecked")
public static SearchRequest deserializeToken(String apiVersion, String continuationToken) {
try {
String decodedToken = new String(Base64.getDecoder().decode(continuationToken), StandardCharsets.UTF_8);
Map<String, String> tokenFields = MAPPER.readValue(decodedToken, Map.class);
if (!apiVersion.equals(tokenFields.get(API_VERSION))) {
throw new IllegalStateException("Continuation token uses invalid apiVersion" + apiVersion);
}
return getDefaultSerializerAdapter().deserialize(tokenFields.get(NEXT_PAGE_PARAMETERS), SearchRequest.class,
SerializerEncoding.JSON);
} catch (IOException e) {
throw new IllegalArgumentException("The continuation token is invalid. Token: " + continuationToken);
}
}
}
| mit |
zhuzaixiaoshulin/swallow | src/main/java/com/swallow/core/constant/AlgorithmConstant.java | 262 | package com.swallow.core.constant;
/**
* 算法常量
*
* @author laohans 2017-04-12 15:15
*/
public interface AlgorithmConstant {
/**
* RSA签名方式
*/
String RSA = "RSA";
/**
* 签名方式
*/
String MD5 = "MD5";
}
| mit |
PhilippHeuer/twitch4j | chat/src/main/java/com/github/twitch4j/chat/events/channel/FollowEvent.java | 787 | package com.github.twitch4j.chat.events.channel;
import com.github.twitch4j.chat.events.AbstractChannelEvent;
import com.github.twitch4j.common.events.domain.EventChannel;
import com.github.twitch4j.common.events.domain.EventUser;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Value;
/**
* This event gets called when a user gets a new followers
*/
@Value
@Getter
@EqualsAndHashCode(callSuper = false)
public class FollowEvent extends AbstractChannelEvent {
/**
* User
*/
private EventUser user;
/**
* Event Constructor
*
* @param channel The channel that this event originates from.
* @param user The user who triggered the event.
*/
public FollowEvent(EventChannel channel, EventUser user) {
super(channel);
this.user = user;
}
}
| mit |
Pamasich/strategygame4school | src/pamasich/strategy/objects/ground/Grass.java | 653 | package pamasich.strategy.objects.ground;
import java.awt.Color;
import pamasich.strategy.logic.random.RandomWrapper;
public class Grass extends Ground {
private int fertility;
public Grass() {
this(true);
}
public Grass(boolean random_fertility, int min, int max) {
this((random_fertility) ? RandomWrapper.getRandom().nextInt(max-min+1)+min : Math.abs(max-min));
}
public Grass(boolean random_fertility) {
this(random_fertility, 1, 10);
}
public Grass(int fertility) {
super(Color.green, "farmable");
this.fertility = fertility;
}
public int getFertility() {
return fertility;
}
}
| mit |
mbuzdalov/non-dominated-sorting | implementations/src/main/java/ru/ifmo/nds/SetIntersectionSort.java | 317 | package ru.ifmo.nds;
import ru.ifmo.nds.mnds.BitSetImplementation;
public final class SetIntersectionSort {
private static final NonDominatedSortingFactory BIT_SET_INSTANCE = BitSetImplementation::new;
public static NonDominatedSortingFactory getBitSetInstance() {
return BIT_SET_INSTANCE;
}
}
| mit |
waleedarafa/Ecommerce-Shopping | backend-rest-api/src/main/java/com/nitsoft/ecommerce/scheduler/EmailNotificationWorker.java | 2080 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.nitsoft.ecommerce.scheduler;
import com.nitsoft.ecommerce.core.LocalQueueManager;
import com.nitsoft.ecommerce.notification.email.EmailSender;
import com.nitsoft.ecommerce.tracelogged.EventLogManager;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* @Class Name: EmailNotificationWorker.java
* @author: lxanh
* @created: Dec 09, 2014
* @version: 2.0
* @brief: Implement EmailNotificationWorker
* @RTM: HG_project_file_encode
*/
@Component
public class EmailNotificationWorker extends JobWorker{
//static Logger logger = Logger.getLogger("service");
@Autowired private EmailSender emailSender;
@Async
@Override
public void doWork(){
if (!LocalQueueManager.getInstance().IsMailQueueEmpty()) {
// EventLogManager.getInstance().info("doWork send notification email");
Map<String, Object> request= LocalQueueManager.getInstance().getMailQueue();
String emailAddress=(String)request.get("mail_address");
String subject=(String)request.get("subject");
String body=(String)request.get("body");
EventLogManager.getInstance().info("EmailNotificationWorker Send email to=" +emailAddress);
emailSender.SendEmail(emailAddress, subject, body);
}
}
private String jobName = "EmailNotificationWorker";
@Override
public String getJobName() {
return this.jobName;
}
@Override
public void setJobName(String name) {
this.jobName=name;
}
@Override
public synchronized Boolean isQueueEmpty() {
return LocalQueueManager.getInstance().IsMailQueueEmpty();
}
@Override
public JobType getJobType() {
return JobType.MULTIPLE;
}
}
| mit |
openregister/openregister-java | src/test/java/uk/gov/register/views/RecordsViewTest.java | 3403 | package uk.gov.register.views;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import io.dropwizard.jackson.Jackson;
import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import uk.gov.register.core.*;
import uk.gov.register.service.ItemConverter;
import uk.gov.register.util.HashValue;
import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class RecordsViewTest {
@Test
public void recordsJson_returnsTheMapOfRecords() throws IOException, JSONException {
ObjectMapper objectMapper = Jackson.newObjectMapper();
Instant t1 = Instant.parse("2016-03-29T08:59:25Z");
Instant t2 = Instant.parse("2016-03-28T09:49:26Z");
Item item1 = new Item(objectMapper.readTree("{\"address\":\"123\",\"street\":\"foo\"}"));
Item item2 = new Item( objectMapper.readTree("{\"address\":\"456\",\"street\":\"bar\"}"));
Entry entry1 = new Entry(1, item1.getSha256hex(), item1.getBlobHash(), t1, "123", EntryType.user);
Entry entry2 = new Entry(2, item2.getSha256hex(), item2.getBlobHash(), t2, "456", EntryType.user);
Record record1 = new Record(entry1, item1);
Record record2 = new Record(entry2, item2);
ItemConverter itemConverter = mock(ItemConverter.class);
Map<String, Field> fieldsByName = mock(Map.class);
when(itemConverter.convertItem(item1, fieldsByName)).thenReturn(ImmutableMap.of("address", new StringValue("123"),
"street", new StringValue("foo")));
when(itemConverter.convertItem(item2, fieldsByName )).thenReturn(ImmutableMap.of("address", new StringValue("456"),
"street", new StringValue("bar")));
RecordsView recordsView = new RecordsView(Arrays.asList(record1, record2), fieldsByName, itemConverter, false, false);
Map<String, JsonNode> result = recordsView.getNestedRecordJson();
assertThat(result.size(), equalTo(2));
JSONAssert.assertEquals(
"{" +
"\"index-entry-number\":\"1\"," +
"\"entry-number\":\"1\"," +
"\"entry-timestamp\":\"2016-03-29T08:59:25Z\"," +
"\"key\":\"123\"," +
"\"item\":[{" +
"\"address\":\"123\"," +
"\"street\":\"foo\"" +
"}]}",
Jackson.newObjectMapper().writeValueAsString(result.get("123")),
false
);
JSONAssert.assertEquals(
"{" +
"\"index-entry-number\":\"2\"," +
"\"entry-number\":\"2\"," +
"\"entry-timestamp\":\"2016-03-28T09:49:26Z\"," +
"\"key\":\"456\"," +
"\"item\":[{" +
"\"address\":\"456\"," +
"\"street\":\"bar\"" +
"}]}",
Jackson.newObjectMapper().writeValueAsString(result.get("456")),
false
);
}
}
| mit |
gregwym/joos-compiler-java | src/ca/uwaterloo/joos/ast/expr/MethodInvokeExpression.java | 2372 | package ca.uwaterloo.joos.ast.expr;
import java.util.List;
import ca.uwaterloo.joos.ast.ASTNode;
import ca.uwaterloo.joos.ast.descriptor.ChildDescriptor;
import ca.uwaterloo.joos.ast.descriptor.ChildListDescriptor;
import ca.uwaterloo.joos.ast.expr.name.Name;
import ca.uwaterloo.joos.ast.expr.name.QualifiedName;
import ca.uwaterloo.joos.ast.expr.name.SimpleName;
import ca.uwaterloo.joos.ast.expr.primary.Primary;
import ca.uwaterloo.joos.parser.ParseTree.LeafNode;
import ca.uwaterloo.joos.parser.ParseTree.Node;
import ca.uwaterloo.joos.parser.ParseTree.TreeNode;
public class MethodInvokeExpression extends Expression {
public static final ChildDescriptor NAME = new ChildDescriptor(Name.class);
public static final ChildDescriptor PRIMARY = new ChildDescriptor(Primary.class);
public static final ChildListDescriptor ARGUMENTS = new ChildListDescriptor(Expression.class);
public String fullyQualifiedName = null;
public MethodInvokeExpression(Node node, ASTNode parent) throws Exception {
super(node, parent);
}
public Name getName() throws ChildTypeUnmatchException {
return (Name) this.getChildByDescriptor(NAME);
}
public Primary getPrimary() throws ChildTypeUnmatchException {
return (Primary) this.getChildByDescriptor(PRIMARY);
}
@SuppressWarnings("unchecked")
public List<Expression> getArguments() throws ChildTypeUnmatchException {
return (List<Expression>) this.getChildByDescriptor(ARGUMENTS);
}
@Override
public List<Node> processTreeNode(TreeNode treeNode) throws Exception {
String kind = treeNode.getKind();
if (kind.equals("simplename")) {
Name name = new SimpleName(treeNode, this);
this.addChild(NAME, name);
} else if (kind.equals("qualifiedname")) {
Name name = new QualifiedName(treeNode, this);
this.addChild(NAME, name);
} else if (kind.equals("primary")) {
Primary primary = Primary.newPrimary(treeNode, this);
this.addChild(PRIMARY, primary);
} else if (kind.equals("expr")) {
Expression arg = Expression.newExpression(treeNode, this);
this.addChild(ARGUMENTS, arg);
} else {
return super.processTreeNode(treeNode);
}
return null;
}
@Override
public void processLeafNode(LeafNode leafNode) throws Exception {
String kind = leafNode.getKind();
if (kind.equals("ID")) {
Name name = new SimpleName(leafNode, this);
this.addChild(NAME, name);
}
}
}
| mit |
anars/usps4j | samples/com/anars/usps4j/samples/AddressValidate1.java | 2562 | /**
* usps4j - USPS API Java Client
* Copyright (c) 2017 Anar Software LLC <http://anars.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.anars.usps4j.samples;
import com.anars.usps4j.Address;
import com.anars.usps4j.USPSClient;
import com.anars.usps4j.exception.USPSException;
public class AddressValidate1 {
public AddressValidate1() {
//
Address address = new Address();
address.setAddress1("350 5th Ave");
address.setAddress2("Suite 4400");
address.setCity("New York");
address.setState("NY");
// address.setZip5("10118");
//
USPSClient uspsClient = new USPSClient("123XXX321");
//
try {
Address addressResponse = uspsClient.addressValidate(address);
//
System.out.println("Address :");
System.out.println("---------");
System.out.println(addressResponse.getAddress2());
System.out.println(addressResponse.getAddress1());
System.out.print(addressResponse.getCity());
System.out.print(", ");
System.out.println(addressResponse.getState());
System.out.print(addressResponse.getZip5());
System.out.print("-");
System.out.println(addressResponse.getZip4());
}
catch(USPSException uspsException) {
uspsException.printStackTrace();
}
}
public static void main(String[] args) {
new AddressValidate1();
}
}
| mit |
CyclopsMC/IntegratedDynamics | src/main/java/org/cyclops/integrateddynamics/api/network/IFullNetworkListener.java | 3393 | package org.cyclops.integrateddynamics.api.network;
import net.minecraft.util.Direction;
import org.cyclops.integrateddynamics.api.path.IPathElement;
/**
* This should be implemented on network capabilities that wish to listen to all network events.
* @author rubensworks
*/
public interface IFullNetworkListener {
/**
* Add a given network element to the network
* Also checks if it can tick and will handle it accordingly.
* @param element The network element.
* @param networkPreinit If the network is still in the process of being initialized.
* @return If the addition succeeded.
*/
public boolean addNetworkElement(INetworkElement element, boolean networkPreinit);
/**
* Checks if the given network element can be removed from the network
* @param element The network element.
* @return If the element was can be removed from the network.
*/
public boolean removeNetworkElementPre(INetworkElement element);
/**
* Remove a given network element from the network.
* Also removed its tickable instance.
* @param element The network element.
*/
public void removeNetworkElementPost(INetworkElement element);
/**
* Terminate the network elements for this network.
*/
public void kill();
/**
* This network updating should be called each tick.
*/
public void update();
/**
* This guaranteed network updating should be called each tick, even in safe-mode.
*/
public void updateGuaranteed();
/**
* Remove the given path element from the network.
* If the path element had any network elements registered in the network, these will be killed and removed as well.
* @param pathElement The path element.
* @param side The side.
* @return If the path element was removed.
*/
public boolean removePathElement(IPathElement pathElement, Direction side);
/**
* Called when the server loaded this network.
* This is the time to notify all network elements of this network.
*/
public void afterServerLoad();
/**
* Called when the server will save this network before stopping.
* This is the time to notify all network elements of this network.
*/
public void beforeServerStop();
/**
* If the given element can update.
* @param element The network element.
* @return If it can update.
*/
public boolean canUpdate(INetworkElement element);
/**
* Called after a network element's update was called.
* @param element The network element.
*/
public void postUpdate(INetworkElement element);
/**
* When the given element is not being updated because {@link INetwork#canUpdate(INetworkElement)}
* returned false.
* @param element The element that is not being updated.
*/
public void onSkipUpdate(INetworkElement element);
/**
* Invalidate the given element.
* Called when the element's chunk is being unloaded.
* @param element The network element to invalidate.
*/
public void invalidateElement(INetworkElement element);
/**
* Revalidate the given element.
* Called when the element's chunk is being reloaded.
* @param element The network element to invalidate.
*/
public void revalidateElement(INetworkElement element);
}
| mit |
fabian-braun/reignOfDke | reignOfDKE/HQ.java | 5939 | package reignOfDKE;
import battlecode.common.Direction;
import battlecode.common.GameActionException;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.Robot;
import battlecode.common.RobotController;
import battlecode.common.RobotType;
public class HQ extends AbstractRobotType {
private MapLocation myHq;
private MapLocation otherHq;
private MapAnalyzer mapAnalyzer;
/**
* soldiers are distributed over 3 teams: <br>
* team 0: 50% of soldiers -> flexible attacking team <br>
* team 1: 25% of soldiers -> build pastr / defend pastr <br>
* team 2: 25% of soldiers -> flexible attacking team / build 2nd pastr /
* defend 2nd pastr <br>
*/
private Team[] teams;
private Direction spawningDefault;
private int teamId;
private int pastrThreshold;
private int[] teamIdAssignment;
private int teamIndex = 0;
// info about opponent, is updated in updateInfoAboutOpponent()
private int oppMilkQuantity = 0;
public HQ(RobotController rc) {
super(rc);
}
@Override
protected void act() throws GameActionException {
Team.updateSoldierCount(rc, teams);
// Check if a robot is spawnable and spawn one if it is
if (rc.isActive() && rc.senseRobotCount() < GameConstants.MAX_ROBOTS) {
// determine team id of soldier to spawn:
teamIndex++;
teamIndex %= teams.length;
teamId = teamIdAssignment[teamIndex];
Channel.assignTeamId(rc, teamId);
Robot[] closeOpponents = rc.senseNearbyGameObjects(Robot.class,
RobotType.HQ.sensorRadiusSquared, rc.getTeam().opponent());
if (size(closeOpponents) > 0) {
Direction away = rc.senseLocationOf(closeOpponents[0])
.directionTo(myHq);
spawningDefault = away;
}
if (rc.canMove(spawningDefault)) {
rc.spawn(spawningDefault);
} else {
int i = 0;
Direction dir = spawningDefault;
while (!rc.canMove(dir) && i < C.DIRECTIONS.length) {
dir = dir.rotateLeft();
}
if (rc.canMove(dir)) {
rc.spawn(dir);
}
}
}
updateInfoAboutOpponent();
if (rc.senseRobotCount() < 1) {
// location between our HQ and opponent's HQ:
MapLocation target = new MapLocation(
(myHq.x * 3 / 4 + otherHq.x / 4),
(myHq.y * 3 / 4 + otherHq.y / 4));
teams[0].setTask(Task.CIRCULATE, target);
teams[1].setTask(Task.CIRCULATE, target);
teams[2].setTask(Task.CIRCULATE, target);
} else {
coordinateTroops();
}
}
private void coordinateTroops() {
MapLocation[] opponentPastrLocations = rc.sensePastrLocations(rc
.getTeam().opponent());
// If the opponent has any PASTRs
if (size(opponentPastrLocations) > 0) {
teams[0].setTask(Task.GOTO, opponentPastrLocations[0]);
if (oppMilkQuantity > 4000000) {
teams[1].setTask(Task.GOTO, opponentPastrLocations[0]);
teams[2].setTask(Task.GOTO, opponentPastrLocations[0]);
} else if (Channel.getPastrCount(rc) == 0) {
assignBuildPastrTask(1);
assignBuildPastrTask(2);
} else if (Channel.getPastrCount(rc) == 1) {
assignBuildPastrTask(1);
assignDefendIfNotBuilding(2, Channel.getTarget(rc, 1));
} else { // more than 1 pastr already
assignDefendIfNotBuilding(1, Channel.getTarget(rc, 1));
assignDefendIfNotBuilding(2, Channel.getTarget(rc, 1));
}
} else {
if (Channel.getPastrCount(rc) == 0) {
assignBuildPastrTask(1);
assignBuildPastrTask(2);
} else if (Channel.getPastrCount(rc) == 1) {
assignBuildPastrTask(1);
assignDefendIfNotBuilding(2, Channel.getTarget(rc, 1));
} else { // more than 1 pastr already
assignDefendIfNotBuilding(1, Channel.getTarget(rc, 1));
assignDefendIfNotBuilding(2, Channel.getTarget(rc, 1));
}
teams[0].setTask(Task.CIRCULATE, Channel.getTarget(rc, 1));
}
}
private void assignBuildPastrTask(int teamId) {
if (Channel.getTask(rc, teamId).equals(Task.BUILD_NOISETOWER)
|| Channel.getTask(rc, teamId).equals(Task.BUILD_PASTR)) {
return;
}
if (rc.senseRobotCount() > pastrThreshold
&& Channel.getPastrLocation(rc, teamId).y > 0) {
// 2nd check is for being sure that there is a valid location
teams[teamId].setTask(Task.BUILD_PASTR,
Channel.getPastrLocation(rc, teamId));
}
}
private void assignDefendIfNotBuilding(int teamId, MapLocation target) {
if (Channel.getTask(rc, teamId).equals(Task.BUILD_NOISETOWER)) {
return;
}
teams[teamId].setTask(Task.CIRCULATE, target);
}
@Override
protected void init() throws GameActionException {
myHq = rc.senseHQLocation();
otherHq = rc.senseEnemyHQLocation();
teams = Team.getTeams(rc);
int ySize = rc.getMapHeight();
int xSize = rc.getMapHeight();
mapAnalyzer = new MapAnalyzer(rc, null, otherHq, myHq, ySize, xSize, 0,
null);
initTeamIdAssignment();
initPastrTreshold();
spawningDefault = myHq.directionTo(otherHq);
int i = 0;
while (!rc.canMove(spawningDefault) && i < C.DIRECTIONS.length) {
spawningDefault = C.DIRECTIONS[i];
i++;
}
}
// against reference player this method does not lead to a better
// performance.
// We should always build 2 pastrs as soon as possible against the
// refPlayer, so the pastr threshold is set to a low value for all map
// sizes.
// Could be adjusted when playing against more advanced opponents.
private void initPastrTreshold() {
MapSize size = mapAnalyzer.getMapType();
switch (size) {
case LARGE:
pastrThreshold = 2;
break;
case MEDIUM:
pastrThreshold = 2;
break;
default: // Small
pastrThreshold = 2;
break;
}
}
private void initTeamIdAssignment() {
MapSize size = mapAnalyzer.getMapType();
switch (size) {
case SMALL:
// On a small map, we want more members in Team 2
teamIdAssignment = new int[] { 2, 0, 1, 2 };
break;
default:
// This is the default team distribution
teamIdAssignment = new int[] { 2, 0, 1, 0 };
break;
}
}
private void updateInfoAboutOpponent() {
oppMilkQuantity = Channel.getOpponentMilkQuantity(rc);
}
}
| mit |
oracle/apps-cloud-ui-kit | DemoMaster/src/oracle/apps/uikit/bean/FilmStripBean.java | 4063 | package oracle.apps.uikit.bean;
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
*
**/
import java.util.HashMap;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import oracle.adf.controller.TaskFlowId;
import oracle.adf.share.ADFContext;
import oracle.adf.view.rich.render.ClientEvent;
import oracle.apps.uikit.common.bean.UtilsBean;
import oracle.apps.uikit.data.ItemNode;
import oracle.apps.uikit.memoryCache.SessionState;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;
public class FilmStripBean {
private UtilsBean _utils = new UtilsBean();
public void handleFilmStripCardClick(ClientEvent clientEvent) {
_utils.setEL("#{sessionScope.selectedItemId}", clientEvent.getParameters().get("itemNodeId"));
}//handleFilmStripCardClick
public TaskFlowId getDynamicTaskFlowId(){
TaskFlowId taskFlowId = new TaskFlowId("/WEB-INF/oracle/apps/uikit/flow/NotImplementedFlow.xml", "NotImplementedFlow");
String itemId = "";
String groupId = "";
if (ADFContext.getCurrent().getSessionScope().get("selectedGroupId") != null)
groupId = (String)ADFContext.getCurrent().getSessionScope().get("selectedGroupId");
if (ADFContext.getCurrent().getSessionScope().get("selectedItemId") != null)
itemId = (String)ADFContext.getCurrent().getSessionScope().get("selectedItemId");
//
SessionState sessionState = (SessionState)_utils.getSessionScope().get("SessionState");
ItemNode node = sessionState.getClusterMap().get(itemId);
if (node != null){
String destUrl = node.getDestinationUrl();
String result = destUrl.substring(0, destUrl.lastIndexOf("."));
String localTFId = result.substring(destUrl.lastIndexOf("/") + 1);
taskFlowId = new TaskFlowId(destUrl, localTFId);
// } else {
//System.out.println(">>>>> THIS IS REQUIRED");
// taskFlowId = new TaskFlowId("/WEB-INF/oracle/apps/uikit/flow/PaaSApplicationFlow.xml", "PaaSApplicationFlow");
}//null check
//
return taskFlowId;
}//getDynamicTaskFlowId
public Map getFilmStripLayout(){
return new HashMap<String, String>(){
public String get(Object key){
try {
String groupId = null;
String itemId = "";
if (ADFContext.getCurrent().getSessionScope().get("selectedGroupId") != null)
groupId = (String)ADFContext.getCurrent().getSessionScope().get("selectedGroupId");
if (ADFContext.getCurrent().getSessionScope().get("selectedItemId") != null)
itemId = (String)ADFContext.getCurrent().getSessionScope().get("selectedItemId");
//
SessionState sessionState = (SessionState)_utils.getSessionScope().get("SessionState");
String rootMenuData = sessionState.fetchGridNodes(groupId);
FacesContext fctx = FacesContext.getCurrentInstance();
ExtendedRenderKitService erks = Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
String js = "filmStripLayoutManager.handleFilmDocumentLoad('" + rootMenuData + "','" + itemId + "');";
erks.addScript(fctx, js);
} catch (Exception e) {
e.printStackTrace();
}//try-catch
return null;
}//get
};
}//getFilmStripLayout
public void toggleStripRender(ActionEvent actionEvent) {
boolean hideStrip = (Boolean)_utils.evaluateEL("#{sessionScope.hideStrip}");
if (hideStrip)
_utils.setEL("#{sessionScope.hideStrip}", false);
else
_utils.setEL("#{sessionScope.hideStrip}", true);
_utils.refreshView();
}//toggleStripRender
}//FilmStripBean
| mit |
SunnyBat/PAXChecker | src/main/java/com/github/sunnybat/paxchecker/status/CheckerInfoOutput.java | 156 | package com.github.sunnybat.paxchecker.status;
/**
*
* @author SunnyBat
*/
public interface CheckerInfoOutput {
public void update(String output);
}
| mit |
Matsv/ViaVersion | common/src/main/java/us/myles/ViaVersion/protocols/protocol1_11to1_10/packets/InventoryPackets.java | 6085 | package us.myles.ViaVersion.protocols.protocol1_11to1_10.packets;
import us.myles.ViaVersion.api.PacketWrapper;
import us.myles.ViaVersion.api.minecraft.item.Item;
import us.myles.ViaVersion.api.remapper.PacketHandler;
import us.myles.ViaVersion.api.remapper.PacketRemapper;
import us.myles.ViaVersion.api.type.Type;
import us.myles.ViaVersion.packets.State;
import us.myles.ViaVersion.protocols.protocol1_11to1_10.EntityIdRewriter;
import us.myles.ViaVersion.protocols.protocol1_11to1_10.Protocol1_11To1_10;
public class InventoryPackets {
public static void register(Protocol1_11To1_10 protocol) {
/*
Incoming packets
*/
// Set slot packet
protocol.registerOutgoing(State.PLAY, 0x16, 0x16, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.BYTE); // 0 - Window ID
map(Type.SHORT); // 1 - Slot ID
map(Type.ITEM); // 2 - Slot Value
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
Item stack = wrapper.get(Type.ITEM, 0);
EntityIdRewriter.toClientItem(stack);
}
});
}
});
// Window items packet
protocol.registerOutgoing(State.PLAY, 0x14, 0x14, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.UNSIGNED_BYTE); // 0 - Window ID
map(Type.ITEM_ARRAY); // 1 - Window Values
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
Item[] stacks = wrapper.get(Type.ITEM_ARRAY, 0);
for (Item stack : stacks)
EntityIdRewriter.toClientItem(stack);
}
});
}
});
// Entity Equipment Packet
protocol.registerOutgoing(State.PLAY, 0x3C, 0x3C, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.VAR_INT); // 0 - Entity ID
map(Type.VAR_INT); // 1 - Slot ID
map(Type.ITEM); // 2 - Item
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
Item stack = wrapper.get(Type.ITEM, 0);
EntityIdRewriter.toClientItem(stack);
}
});
}
});
// Plugin message Packet -> Trading
protocol.registerOutgoing(State.PLAY, 0x18, 0x18, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.STRING); // 0 - Channel
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
if (wrapper.get(Type.STRING, 0).equalsIgnoreCase("MC|TrList")) {
wrapper.passthrough(Type.INT); // Passthrough Window ID
int size = wrapper.passthrough(Type.UNSIGNED_BYTE);
for (int i = 0; i < size; i++) {
EntityIdRewriter.toClientItem(wrapper.passthrough(Type.ITEM)); // Input Item
EntityIdRewriter.toClientItem(wrapper.passthrough(Type.ITEM)); // Output Item
boolean secondItem = wrapper.passthrough(Type.BOOLEAN); // Has second item
if (secondItem)
EntityIdRewriter.toClientItem(wrapper.passthrough(Type.ITEM)); // Second Item
wrapper.passthrough(Type.BOOLEAN); // Trade disabled
wrapper.passthrough(Type.INT); // Number of tools uses
wrapper.passthrough(Type.INT); // Maximum number of trade uses
}
}
}
});
}
});
/*
Incoming packets
*/
// Click window packet
protocol.registerIncoming(State.PLAY, 0x07, 0x07, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.UNSIGNED_BYTE); // 0 - Window ID
map(Type.SHORT); // 1 - Slot
map(Type.BYTE); // 2 - Button
map(Type.SHORT); // 3 - Action number
map(Type.VAR_INT); // 4 - Mode
map(Type.ITEM); // 5 - Clicked Item
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
Item item = wrapper.get(Type.ITEM, 0);
EntityIdRewriter.toServerItem(item);
}
});
}
}
);
// Creative Inventory Action
protocol.registerIncoming(State.PLAY, 0x18, 0x18, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.SHORT); // 0 - Slot
map(Type.ITEM); // 1 - Clicked Item
handler(new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
Item item = wrapper.get(Type.ITEM, 0);
EntityIdRewriter.toServerItem(item);
}
});
}
}
);
}
}
| mit |
sdsmdg/Cognizance | Cognizance/src/in/co/sdslabs/cognizance/DatabaseHelper.java | 26868 | package in.co.sdslabs.cognizance;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.PointF;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/in.co.sdslabs.cognizance/databases/";
private static String DB_NAME = "cognizance14.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
private DatabaseHelper ourHelper;
// fields for table 1
public static final String KEY_ROWID_VENUE = "_id_venue";
public static final String KEY_MINX = "_minX";
public static final String KEY_MINY = "_minY";
public static final String KEY_MAXX = "_maxX";
public static final String KEY_MAXY = "_maxY";
public static final String KEY_TOUCH_VENUE = "_touch_venue";
public static final String KEY_VENUE = "_place_name";
public static final String DATABASE_TABLE1 = "table_venue";
public static final String DATABASE_TABLE2 = "table_place";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist)
return;
else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
public DatabaseHelper getInstance(Context context) {
if (ourHelper == null) {
ourHelper = new DatabaseHelper(context);
}
return this;
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null)
checkDB.close();
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public ArrayList<String> getCategory() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM table_category_details",
null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("category")));
}
}
cursor.close();
return data;
}
public String getCategoryDescription(String category_name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_category_details WHERE category='"
+ category_name + "'", null);
String data = null;
if (cursor != null) {
cursor.moveToFirst();
}
data = cursor.getString(cursor.getColumnIndex("category_description"));
cursor.close();
return data;
}
public ArrayList<String> getEventName(String category_name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE category='"
+ category_name + "'", null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("event_name")));
}
}
cursor.close();
return data;
}
public ArrayList<String> getEventoneLiner(String category_name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE category='"
+ category_name + "'", null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("one_liner")));
}
}
cursor.close();
return data;
}
public String getEventDescription(String eventname) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='"
+ eventname + "'", null);
String data = null;
if (cursor != null) {
if (cursor.moveToNext()) {
cursor.moveToFirst();
}
data = cursor.getString(cursor.getColumnIndex("description"));
}
cursor.close();
return data;
}
public String getEventOneLiner(String eventname) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT one_liner FROM table_event_details WHERE event_name='"
+ eventname + "'", null);
String data = null;
if (cursor != null) {
if (cursor.moveToNext()) {
cursor.moveToFirst();
data = cursor.getString(cursor.getColumnIndex("one_liner"));
}
}
cursor.close();
return data;
}
public ArrayList<String> getEventNamex(int day) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor;
if (day == 1) {
cursor = db
.rawQuery(
"SELECT * FROM table_event_details WHERE day= 1 OR day = 12 OR day = 123 ORDER BY start_time",
null);
} else if (day == 2) {
cursor = db
.rawQuery(
"SELECT * FROM table_event_details WHERE day= 2 OR day = 23 OR day = 123 ORDER BY start_time",
null);
} else {
cursor = db
.rawQuery(
"SELECT * FROM table_event_details WHERE day= 3 OR day = 23 OR day = 123 ORDER BY start_time",
null);
}
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("event_name")));
}
}
cursor.close();
return data;
}
public ArrayList<String> getEventoneLinerx(int day) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor;
if (day == 1) {
cursor = db
.rawQuery(
"SELECT * FROM table_event_details WHERE day= 1 OR day = 12 OR day = 123 ORDER BY start_time",
null);
} else if (day == 2) {
cursor = db
.rawQuery(
"SELECT * FROM table_event_details WHERE day= 2 OR day = 23 OR day = 123 ORDER BY start_time",
null);
} else {
cursor = db
.rawQuery(
"SELECT * FROM table_event_details WHERE day= 3 OR day = 23 OR day = 123 ORDER BY start_time",
null);
}
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("one_liner")));
}
}
cursor.close();
return data;
}
public String searchEntryForVenue(String x, String y) throws SQLException {
// TODO Auto-generated method stub
myDataBase = this.getReadableDatabase();
String[] columns = new String[] { KEY_ROWID_VENUE, KEY_MINX, KEY_MINY,
KEY_MAXX, KEY_MAXY, KEY_TOUCH_VENUE };
int ix = Integer.parseInt(x) * 2;
int iy = Integer.parseInt(y) * 2;
Cursor c = myDataBase.query(DATABASE_TABLE1, columns, KEY_MINX + "<="
+ ix + " AND " + KEY_MINY + "<=" + iy + " AND " + KEY_MAXX
+ ">=" + ix + " AND " + KEY_MAXY + ">=" + iy, null, null, null,
null);
try {
if (c != null) {
c.moveToFirst();
String venue = c.getString(5);
c.close();
return venue;
}
} catch (CursorIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
c.close();
return null;
}
return null;
}
public PointF searchPlaceForCoordinates(String selection) {
// TODO Auto-generated method stub
myDataBase = this.getReadableDatabase();
String[] columns = new String[] { KEY_MINX, KEY_MINY, KEY_MAXX,
KEY_MAXY, KEY_TOUCH_VENUE };
PointF coor = new PointF();
Cursor c = myDataBase.query(DATABASE_TABLE1, columns, KEY_TOUCH_VENUE
+ "==\"" + selection + "\"", null, null, null, null);
int iMinX = c.getColumnIndex(KEY_MINX);
int iMinY = c.getColumnIndex(KEY_MINY);
int iMaxX = c.getColumnIndex(KEY_MAXX);
int iMaxY = c.getColumnIndex(KEY_MAXY);
try {
if (c != null) {
c.moveToFirst();
coor.x = (Integer.parseInt(c.getString(iMinX)) + Integer
.parseInt(c.getString(iMaxX))) / 4;
coor.y = (Integer.parseInt(c.getString(iMinY)) + Integer
.parseInt(c.getString(iMaxY))) / 4;
c.close();
}
} catch (CursorIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return coor;
}
public String getVenueDisplay(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='" + event
+ "'", null);
String data = null;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
data = cursor.getString(cursor.getColumnIndex("venue_display"));
cursor.close();
return data;
}
public String getVenueMap(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT venue_map FROM table_event_details WHERE event_name='"
+ event + "'", null);
String data = null;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
data = cursor.getString(cursor.getColumnIndex("venue_map"));
cursor.close();
return data;
}
public String getVenueMapD(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT venue_map FROM table_departments WHERE dept_name='"
+ event + "'", null);
String data = null;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
data = cursor.getString(cursor.getColumnIndex("venue_map"));
cursor.close();
return data;
}
public int getID(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='" + event
+ "'", null);
String category;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
category = cursor.getString(cursor.getColumnIndex("category"));
cursor.close();
cursor = db.rawQuery(
"SELECT * FROM table_category_details WHERE category= '"
+ category + "'", null);
int id;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
id = cursor.getInt(cursor.getColumnIndex("category"));
cursor.close();
return (id - 1);
}
public ArrayList<String> getcontactsname() {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM contacts", null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
list.add(cursor.getString(cursor.getColumnIndexOrThrow("name")));
}
// if(cursor.moveToNext()) cursor.moveToFirst();
}
cursor.close();
return list;
}
public ArrayList<String> getcontactsnumber() {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM contacts", null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
list.add(cursor.getString(cursor
.getColumnIndexOrThrow("number")));
}
cursor.close();
}
return list;
}
public ArrayList<String> getcontactspost() {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM contacts", null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
list.add(cursor.getString(cursor
.getColumnIndexOrThrow("position")));
}
// if(cursor.moveToNext()) cursor.moveToFirst();
}
cursor.close();
return list;
}
public ArrayList<String> getcontactsemail() {
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM contacts", null);
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
list.add(cursor.getString(cursor
.getColumnIndexOrThrow("email_id")));
}
cursor.close();
}
return list;
}
public int getImageX(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT image_x FROM table_event_details WHERE event_name='"
+ event + "'", null);
int imageX = 0;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
imageX = cursor.getInt(cursor.getColumnIndex("image_x"));
}
cursor.close();
return (imageX);
}
public int getImageY(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT image_y FROM table_event_details WHERE event_name='"
+ event + "'", null);
int imageY = 0;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
imageY = cursor.getInt(cursor.getColumnIndex("image_y"));
}
cursor.close();
return (imageY);
}
public void markAsFavouriteD(String event, String dept) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(
"UPDATE table_departments SET isFavourite = 1 WHERE dept_name ='"
+ dept + "' AND dept_event='" + event + "'", null);
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
cursor.close();
}
public void unmarkAsFavouriteD(String event, String dept) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(
"UPDATE table_departments SET isFavourite = 0 WHERE dept_name ='"
+ dept + "' AND dept_event='" + event + "'", null);
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
cursor.close();
}
public boolean isFavouriteD(String event, String dept) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db
.rawQuery(
"SELECT isFavourite FROM table_departments WHERE dept_name = ? AND dept_event = ?",
new String[] { dept, event });
int flag = 0;
if (cursor != null) {
if (cursor.moveToNext()) {
cursor.moveToFirst();
flag = cursor.getInt(cursor.getColumnIndex("isFavourite"));
}
}
cursor.close();
if (flag == 1) {
return true;
} else {
return false;
}
}
public void markAsFavourite(String event) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(
"UPDATE table_event_details SET isFavourite = 1 WHERE event_name='"
+ event + "'", null);
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
cursor.close();
}
public void unmarkAsFavourite(String event) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(
"UPDATE table_event_details SET isFavourite = 0 WHERE event_name='"
+ event + "'", null);
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
cursor.close();
}
public boolean isFavourite(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='" + event
+ "'", null);
int flag;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
flag = cursor.getInt(cursor.getColumnIndex("isFavourite"));
cursor.close();
if (flag == 1) {
return true;
} else {
return false;
}
}
public ArrayList<String> getFavouritesName() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db
.rawQuery(
"SELECT event_name FROM table_event_details WHERE isFavourite= 1",
null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("event_name")));
}
}
cursor.close();
Cursor cursor1 = db
.rawQuery(
"SELECT dept_event FROM table_departments WHERE isFavourite= 1",
null);
Cursor cursor2 = db.rawQuery(
"SELECT dept_name FROM table_departments WHERE isFavourite= 1",
null);
if (cursor1 != null && cursor2 != null) {
while (cursor1.moveToNext() && cursor2.moveToNext()) {
String event = cursor1.getString(cursor1
.getColumnIndex("dept_event"));
String dept = cursor2.getString(cursor2
.getColumnIndex("dept_name"));
data.add(event + ":" + dept);
}
}
cursor.close();
cursor1.close();
cursor2.close();
return data;
}
public String getEventDate(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='" + event
+ "'", null);
int day;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
day = cursor.getInt(cursor.getColumnIndex("day"));
cursor.close();
switch (day) {
case 1:
return "21st March 2014";
case 2:
return "22nd March 2014";
case 3:
return "23rd March 2014";
case 12:
return "21-22 March 2014";
case 123:
return "21-23 March 2014";
case 23:
return "22-23 March 2014";
default:
return null;
}
}
public int getEventDay(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='" + event
+ "'", null);
int day;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
day = cursor.getInt(cursor.getColumnIndex("day"));
cursor.close();
return day;
}
public String getEventDDate(String event, String dept) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db
.rawQuery(
"SELECT day FROM table_departments WHERE dept_name = ? AND dept_event = ?",
new String[] { dept, event });
int day;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
day = cursor.getInt(cursor.getColumnIndex("day"));
cursor.close();
switch (day) {
case 1:
return "21st March 2014";
case 2:
return "22nd March 2014";
case 3:
return "23rd March 2014";
case 12:
return "21-22 March 2014";
case 123:
return "21-23 March 2014";
case 23:
return "22-23 March 2014";
default:
return null;
}
}
public int getEventDayDept(String event, String dept) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db
.rawQuery(
"SELECT day FROM table_departments WHERE dept_name = ? AND dept_event = ?",
new String[] { dept, event });
int day;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
day = cursor.getInt(cursor.getColumnIndex("day"));
cursor.close();
return day;
}
public String getEventTime(String string) {
return null;
}
public int getStartTime(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='" + event
+ "'", null);
int startTime;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
startTime = cursor.getInt(cursor.getColumnIndex("start_time"));
cursor.close();
return (startTime);
}
public int getEndTime(String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM table_event_details WHERE event_name='" + event
+ "'", null);
int endTime;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
endTime = cursor.getInt(cursor.getColumnIndex("end_time"));
cursor.close();
return (endTime);
}
public int getStartTimeD(String dept, String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db
.rawQuery(
"SELECT start_time FROM table_departments WHERE dept_name = ? AND dept_event = ?",
new String[] { dept, event });
int startTime;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
startTime = cursor.getInt(cursor.getColumnIndex("start_time"));
cursor.close();
return (startTime);
}
public int getEndTimeD(String dept, String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db
.rawQuery(
"SELECT end_time FROM table_departments WHERE dept_name = ? AND dept_event = ?",
new String[] { dept, event });
int endTime;
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
endTime = cursor.getInt(cursor.getColumnIndex("end_time"));
cursor.close();
return (endTime);
}
public PointF searchPlaceForLatLong(String selection) {
// TODO Auto-generated method stub
myDataBase = this.getReadableDatabase();
String[] columns = new String[] { "_lat", "_lng" };
PointF coor = new PointF();
Cursor c = myDataBase.query(DATABASE_TABLE2, columns, KEY_VENUE
+ "==\"" + selection + "\"", null, null, null, null);
int iLat = c.getColumnIndex("_lat");
int iLong = c.getColumnIndex("_lng");
try {
if (c != null) {
c.moveToFirst();
coor.x = (Float.parseFloat(c.getString(iLat)));
coor.y = (Float.parseFloat(c.getString(iLong)));
c.close();
}
} catch (CursorIndexOutOfBoundsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return coor;
}
/** Functions for Departmental Events */
public ArrayList<String> getDepartments() {
/** Retrieves unique department names from the database */
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT DISTINCT dept_name FROM "
+ "table_departments ORDER BY dept_name", null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("dept_name")));
}
}
cursor.close();
return data;
}
public ArrayList<String> getDepartmentalEvents(String deptName) {
/** Retrieves list of events for each department */
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db
.rawQuery("SELECT dept_event FROM "
+ "table_departments WHERE dept_name ='" + deptName
+ "'", null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
data.add(cursor.getString(cursor.getColumnIndex("dept_event")));
}
}
cursor.close();
return data;
}
public String getDepartmentalEventVenue(String dept, String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db
.rawQuery(
"SELECT venue_display FROM table_departments WHERE dept_name = ? AND dept_event = ?",
new String[] { dept, event });
String data = "";
if (cursor != null) {
cursor.moveToFirst();
data = cursor.getString(cursor.getColumnIndex("venue_display"));
}
cursor.close();
if (data.equals("")) {
return "";
}
return data;
}
public String getDepartmentalEventDescription(String dept, String event) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db
.rawQuery(
"SELECT event_description FROM table_departments WHERE dept_name = ? AND dept_event = ?",
new String[] { dept, event });
String data = "";
if (cursor != null && cursor.moveToFirst()) {
data = cursor.getString(cursor.getColumnIndex("event_description"));
}
cursor.close();
return data;
}
public void markAsFavouriteDept(String event) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(
"UPDATE table_departments SET isFavourite = 1 WHERE dept_event='"
+ event + "'", null);
if (cursor != null) {
if (cursor.moveToNext())
cursor.moveToFirst();
}
cursor.close();
}
public boolean isDeptEvent(String event) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(
"SELECT dept_name FROM table_departments WHERE dept_event = ?",
new String[] { event });
String data = null;
if (cursor != null) {
cursor.moveToFirst();
data = cursor.getString(cursor.getColumnIndex("dept_name"));
}
if (cursor == null) {
return false;
}
cursor.close();
return true;
}
public ArrayList<String> getUpcomingEventNames(int day) {
/** Retrieves unique department names from the database */
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "
+ "table_event_details WHERE 1=1", null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
int day1 = cursor.getInt(cursor.getColumnIndexOrThrow("day"));
if (day1 % 10 == day || (day1 / 10) % 10 == day
|| (day1 / 100) % 10 == day) {
data.add(cursor.getString(cursor
.getColumnIndex("event_name")));
}
}
}
cursor.close();
return data;
}
public ArrayList<Long> getUpcomingTime(int day) {
/** Retrieves unique department names from the database */
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + "table_event_details",
null);
ArrayList<Long> data = new ArrayList<Long>();
if (cursor != null) {
while (cursor.moveToNext()) {
int day1 = cursor.getInt(cursor.getColumnIndexOrThrow("day"));
if (day1 % 10 == day || (day1 / 10) % 10 == day
|| (day1 / 100) % 10 == day) {
data.add(cursor.getLong(cursor.getColumnIndex("start_time")));
}
}
}
cursor.close();
return data;
}
public ArrayList<String> getUpcomingEventoneLiner(int day) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM table_event_details", null);
ArrayList<String> data = new ArrayList<String>();
if (cursor != null) {
while (cursor.moveToNext()) {
int day1 = cursor.getInt(cursor.getColumnIndexOrThrow("day"));
if (day1 % 10 == day || (day1 / 10) % 10 == day
|| (day1 / 100) % 10 == day) {
data.add(cursor.getString(cursor
.getColumnIndex("one_liner")));
}
}
}
cursor.close();
return data;
}
} | mit |
maniero/SOpt | Java/Exception/Validation2.java | 1700 | import java.util.InputMismatchException;
import java.util.Scanner;
class Teste_Calc {
public static void main(String[] args) {
while (true) {
System.out.println("---------------------------------");
System.out.println("Escolha uma das opções a seguir:");
System.out.println("1) Somar!");
System.out.println("2) Subtrair!");
System.out.println("3) Multiplicar!");
System.out.println("4) dividir!");
System.out.println("5) Sair do programa!");
System.out.println("---------------------------------");
int opcao;
try {
Scanner sc1 = new Scanner(System.in);
opcao = sc1.nextInt();
} catch (InputMismatchException exception) {
System.out.println("Caracter inserido não compatível!");
continue;
}
if (opcao == 5) {
System.out.println("Programa finalizado!");
break;
} else {
switch (opcao) {
case 1:
System.out.println("1) Somar!");
break;
case 2:
System.out.println("2) Subtrair!");
break;
case 3:
System.out.println("3) Multiplicar!");
break;
case 4:
System.out.println("4) dividir!");
break;
default:
System.out.println("Opção invalida");
}
}
}
}
}
//https://pt.stackoverflow.com/q/390450/101
| mit |
wipu/iwant | essential/iwant-core/src/main/java/org/fluentjava/iwant/core/Target.java | 1113 | package org.fluentjava.iwant.core;
import java.util.SortedSet;
import java.util.TreeSet;
public class Target<CONTENT extends Content> extends Path {
private final CONTENT content;
public Target(String name, CONTENT content) {
super(name);
this.content = content;
}
public CONTENT content() {
return content;
}
public SortedSet<Path> ingredients() {
return content.ingredients();
}
public SortedSet<Target<?>> dependencies() {
SortedSet<Target<?>> dependencies = new TreeSet<Target<?>>();
for (Path ingredient : ingredients()) {
if (ingredient instanceof Target) {
dependencies.add((Target<?>) ingredient);
}
}
return dependencies;
}
@Override
public String asAbsolutePath(Locations locations) {
return locations.targetCacheDir() + "/" + name();
}
/**
* TODO override when the cache obeys it, to avoid name clashes between user
* targets and wsDefClasses like asAbsolutePath does for the actual cached
* target.
*/
public final String contentDescriptionCacheDir(Locations locations) {
return locations.contentDescriptionCacheDir() + "/" + name();
}
}
| mit |
Eluinhost/UHC | src/main/java/gg/uhc/uhc/modules/border/WorldBorderCommand.java | 7936 | /*
* Project: UHC
* Class: gg.uhc.uhc.modules.border.WorldBorderCommand
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Graham Howden <graham_howden1 at yahoo.co.uk>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package gg.uhc.uhc.modules.border;
import gg.uhc.flagcommands.converters.DoubleConverter;
import gg.uhc.flagcommands.converters.LongConverter;
import gg.uhc.flagcommands.converters.WorldConverter;
import gg.uhc.flagcommands.joptsimple.ArgumentAcceptingOptionSpec;
import gg.uhc.flagcommands.joptsimple.OptionSet;
import gg.uhc.flagcommands.joptsimple.OptionSpec;
import gg.uhc.flagcommands.predicates.DoublePredicates;
import gg.uhc.flagcommands.predicates.LongPredicates;
import gg.uhc.flagcommands.tab.FixedValuesTabComplete;
import gg.uhc.flagcommands.tab.WorldTabComplete;
import gg.uhc.uhc.commands.TemplatedOptionCommand;
import gg.uhc.uhc.messages.MessageTemplates;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.bukkit.World;
import org.bukkit.WorldBorder;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import java.util.List;
public class WorldBorderCommand extends TemplatedOptionCommand {
protected final ArgumentAcceptingOptionSpec<Double> sizeSpec;
protected final ArgumentAcceptingOptionSpec<World> worldSpec;
protected final ArgumentAcceptingOptionSpec<Double> centreSpec;
protected final OptionSpec<Void> resetSpec;
protected final ArgumentAcceptingOptionSpec<Long> timeSpec;
public WorldBorderCommand(MessageTemplates messages) {
super(messages);
resetSpec = parser
.acceptsAll(ImmutableList.of("reset"), "Clears the border back to default settings");
sizeSpec = parser
.acceptsAll(
ImmutableList.of("s", "size", "r", "radius"),
"The radius of the border from the centre."
+ "Use 1000>200 format for shrinking borders (requires -t/--time parameter)"
)
.requiredUnless(resetSpec)
.withRequiredArg()
.withValuesConvertedBy(
new DoubleConverter()
.setPredicate(DoublePredicates.GREATER_THAN_ZERO)
.setType("Number > 0")
)
.withValuesSeparatedBy('>');
completers.put(sizeSpec, new FixedValuesTabComplete("250", "500", "1000", "1000>200"));
worldSpec = parser
.acceptsAll(
ImmutableList.of("w", "world"),
"The world to create the border in, defaults to the world you are in"
)
.withRequiredArg()
.withValuesConvertedBy(new WorldConverter());
completers.put(worldSpec, WorldTabComplete.INSTANCE);
centreSpec = parser
.acceptsAll(ImmutableList.of("c", "centre"), "The centre coordinates x:z of the border to create")
.withRequiredArg()
.withValuesConvertedBy(new DoubleConverter().setType("coordinate"))
.withValuesSeparatedBy(':')
.defaultsTo(new Double[]{0D, 0D});
completers.put(centreSpec, new FixedValuesTabComplete("0:0"));
timeSpec = parser
.acceptsAll(
ImmutableList.of("t", "time"),
"How many seconds to move to the radius given from the previous value"
)
.withRequiredArg()
.withValuesConvertedBy(
new LongConverter()
.setPredicate(LongPredicates.GREATER_THAN_ZERO_INC)
.setType("Integer > 0")
);
completers.put(timeSpec, new FixedValuesTabComplete("300", "600", "900", "1200"));
}
protected Optional<World> getWorld(CommandSender sender) {
if (sender instanceof Entity) {
return Optional.of(((Entity) sender).getWorld());
}
if (sender instanceof BlockCommandSender) {
return Optional.of(((BlockCommandSender) sender).getBlock().getWorld());
}
return Optional.absent();
}
@Override
protected boolean runCommand(CommandSender sender, OptionSet options) {
final World world;
// grab the world
if (options.has(worldSpec)) {
world = worldSpec.value(options);
} else {
final Optional<World> optionalWorld = getWorld(sender);
if (optionalWorld.isPresent()) {
world = optionalWorld.get();
} else {
sender.sendMessage(messages.getRaw("provide world"));
return true;
}
}
// check for reset first
if (options.has(resetSpec)) {
world.getWorldBorder().reset();
sender.sendMessage(messages.evalTemplate("reset", ImmutableMap.of("world", world.getName())));
return true;
}
final List<Double> coords = centreSpec.values(options);
final List<Double> radii = sizeSpec.values(options);
if (coords.size() != 2) {
sender.sendMessage(messages.getRaw("invalid coords"));
return true;
}
if (radii.size() == 0) {
sender.sendMessage(messages.getRaw("provide radius"));
return true;
}
final double radius = radii.get(0);
final Optional<Double> targetRadius;
long time = 0;
if (radii.size() == 1) {
targetRadius = Optional.absent();
} else {
if (!options.has(timeSpec)) {
sender.sendMessage(messages.getRaw("provide time"));
return true;
}
targetRadius = Optional.of(radii.get(1));
time = timeSpec.value(options);
}
final WorldBorder border = world.getWorldBorder();
// set centre
border.setCenter(coords.get(0), coords.get(1));
// set initial size
border.setSize(radius * 2.0D);
sender.sendMessage(messages.evalTemplate(
"set regular",
ImmutableMap.of(
"world", world.getName(),
"radius", radius,
"x", coords.get(0),
"z", coords.get(1)
)
));
if (targetRadius.isPresent()) {
border.setSize(radii.get(1) * 2.0D, time);
sender.sendMessage(messages.evalTemplate(
"set shrinking",
ImmutableMap.of("radius", radii.get(1), "seconds", time))
);
}
return true;
}
}
| mit |
phillipm/textual-filters | test/net/quined/textual_filters/CorpusTest.java | 1791 | package net.quined.textual_filters;
/**
* Test basic functionality of importing text into a Corpus.
*
* @author Phillip Mates
* @version 0.1
*/
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.After;
import org.junit.Test;
import java.util.Map;
public class CorpusTest {
private Corpus c;
@Before
public void setUp() {
c = new Corpus();
}
@After
public void tearDown() {
c = null;
}
/**
* Since there is only one line, no newlines are added.
* Punctuation is not thought of as individual words
*/
@Test
public void loadOneLineString() {
String inputStr = "hello world, every word should only occur once.";
c.loadText(inputStr);
assertEquals(8, c.length());
assertEquals(8, c.maxLineLength());
assertEquals(1, c.newlineCount());
for(Map.Entry<String, Integer> keyValuePair : c.wordFrequency().entrySet()) {
assertEquals(1, (int) keyValuePair.getValue());
}
assertEquals(inputStr, c.getOriginalText());
assertEquals(8, c.uniqueWordCount());
}
/**
* Newlines are thought of as words.
* Punctuation is not thought of as individual words
*/
@Test
public void loadMultiLineString() {
String inputStr = "Hello world!\n"
+ "If only there was someone to talk to.\n"
+ "Is anyone there?";
c.loadText(inputStr);
assertEquals(15, c.length());
assertEquals(9, c.maxLineLength());
assertEquals(3, c.newlineCount());
for(Map.Entry<String, Integer> keyValuePair : c.wordFrequency().entrySet()) {
if (keyValuePair.getKey() != "\n") {
assertEquals(1, (int) keyValuePair.getValue());
}
}
assertEquals(inputStr, c.getOriginalText());
assertEquals(14, c.uniqueWordCount());
}
}
| mit |
mhjabreel/FDTKit | src/fdt/utils/Utils.java | 13120 |
package fdt.utils;
import com.google.common.collect.Streams;
import fdt.core.DecisionNode;
import fdt.core.DecisionSet;
import fdt.core.EdgeBase;
import fdt.core.IntermediateNode;
import fdt.core.Node;
import fdt.data.Attribute;
import fdt.data.Dataset;
import fdt.data.Term;
import fdt.infer.InferenceEngine;
import fdt.infer.InferenceModelSpec;
import fdt.infer.PredictionResult;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.ejml.data.Complex_F64;
import org.ejml.data.DMatrixRMaj;
import org.ejml.dense.row.factory.DecompositionFactory_DDRM;
import org.ejml.interfaces.decomposition.EigenDecomposition_F64;
/**
*
* @author Mohammed Jabreel
*/
public class Utils {
/**
*
*/
public static double EPSILON = 1e-9;
/**
*
* @param target
* @param source
* @return
*/
public static double[] sortBy(double[] target, double[] source) {
Tuple<Integer, Double>[] map = new Tuple[source.length];
for (int i = 0; i < source.length; i++) {
map[i] = new Tuple<>(i, source[i]);
}
Arrays.sort(map, (a, b) -> b.getSecond().compareTo(a.getSecond()));
double[] sortedTarget = new double[target.length];
for (int i = 0; i < target.length; i++) {
sortedTarget[i] = target[map[i].getFirst()];
}
return sortedTarget;
}
/**
*
* @param condition
* @param conclusion
* @return
*/
public static double subsethood(double[] condition, double[] conclusion) {
double s = Arrays.stream(condition).boxed().mapToDouble(Double::doubleValue).sum();
// if(s == 0) {
// return 1;
// }
double ret = Streams.zip(
Arrays.stream(condition).boxed(),
Arrays.stream(conclusion).boxed(),
(c1, c2) -> Math.min(c1, c2)
).mapToDouble(Double::doubleValue).sum() / s;
return ret;
}
/**
*
* @param a
* @return
*/
public static boolean embpty(double[] a) {
double s = Arrays.stream(a).sum();
// System.out.println(s + " " + (s == 0));
return s == 0;
}
/**
*
* @param distribution
* @param normalize
* @return
*/
public static double ambiguity(double[] distribution, Optional<Boolean> normalize) {
//Eqs (2, 3, 4)
Supplier<Stream<Double>> streamSupplier = () -> Arrays.stream(distribution).boxed();
Stream<Double> dStream = streamSupplier.get();
if (normalize.orElse(Boolean.TRUE)) {
double maxValue = streamSupplier
.get()
.mapToDouble(Double::doubleValue)
.max()
.getAsDouble() + EPSILON;
dStream = streamSupplier.get().map((t) -> t / maxValue);
}
List<Double> distributionList = dStream.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
distributionList.add(0d);
Supplier<Stream<Double>> streamSupplier2 = () -> distributionList.stream();
List<Tuple<Double, Double>> collected = Streams.zip(streamSupplier2.get().limit(distributionList.size() - 1),
streamSupplier2.get().skip(1), (u, t) -> new Tuple<>(u, t)).collect(Collectors.toList());
double g = IntStream.range(0, collected.size())
.mapToDouble(i -> Math.log(i + 1) * (collected.get(i).getFirst() - collected.get(i).getSecond())).sum();
return g;
}
/**
*
* @param model
*/
public static void printTree(InferenceModelSpec model) {
System.out.println(getStringTree(model.getTree(), ""));
}
private static String getStringTree(Node node, String prefix) {
String s = "";
if(node.isLeaf()) {
s += String.format("%s\t\t[%s (%.3f)]\n", prefix, node.getText(), ((DecisionNode)node).getSupport());
}
else {
s += String.format("%s|%s, %.3f, %.3f|\n", prefix, node.getText(), ((IntermediateNode)node).getAmbiguity(), ((IntermediateNode)node).getLambda());
for(EdgeBase e : ((IntermediateNode) node).getEdges()) {
s += String.format("%s\t<%s, %.3f>\n", prefix, e.getText(), e.getAmbiguity());
s += getStringTree(e.getChild(), "\t\t" + prefix);
}
}
return s;
}
/**
*
* @param model
*/
public static void printRules(InferenceModelSpec model) {
for (DecisionSet s : model.getDecisionSets()) {
for(DecisionNode leaf : s.getDecisionNodes()) {
printRule(leaf);
}
}
}
private static void printRule(DecisionNode leaf) {
List<String> conditions = new ArrayList<>();
fdt.core.Node node2 = leaf.getParent();
fdt.core.Node node = leaf;
while(node2 != null) {
conditions.add(0, String.format("%s IS %s", node2.getText(), node.getEdge().getText()));
node = node2;
node2 = node2.getParent();
}
String cond = String.join(" AND ", conditions);
System.out.println(String.format("IF %s THEN %s [%.3f, %.3f]", cond, leaf.getText(), leaf.getSupport(), ((IntermediateNode) leaf.getParent()).getAmbiguity()));
}
/**
*
* @param confusionMatrix
* @return
*/
public static double printClassificationReport(HashMap<String, HashMap<String, Integer>> confusionMatrix) {
System.out.println(String.format("\t\t\t%s", String.join("\t", confusionMatrix.keySet())));
confusionMatrix.keySet().stream().map((c) -> {
System.out.println(String.format("%s\t\t:", c));
return c;
}).map((c) -> {
confusionMatrix.keySet().forEach((c2) -> {
System.out.print(String.format("\t%d\t", confusionMatrix.get(c).get(c2)));
});
System.out.print(String.format("\t%d\t", confusionMatrix.get(c).get("UnKnown")));
return c;
}).forEachOrdered((__) -> {
System.out.println("");
});
double sensitivity = (confusionMatrix.get("Class0").get("Class0") * 1.0) / ((double) confusionMatrix.get("Class0").get("Class0") + confusionMatrix.get("Class0").get("Class1"));
double specifity = (confusionMatrix.get("Class1").get("Class1") * 1.0) / ((double) confusionMatrix.get("Class1").get("Class1") + confusionMatrix.get("Class1").get("Class0"));
double npv = (confusionMatrix.get("Class0").get("Class0") * 1.0) / ((double) confusionMatrix.get("Class0").get("Class0") + confusionMatrix.get("Class1").get("Class0"));
double accuracy = (confusionMatrix.get("Class0").get("Class0") * 1.0 + confusionMatrix.get("Class1").get("Class1"))
/ ((double) confusionMatrix.get("Class0").get("Class0")
+ confusionMatrix.get("Class1").get("Class1")
+ confusionMatrix.get("Class1").get("Class0")
+ confusionMatrix.get("Class0").get("Class1"));
double precision = (confusionMatrix.get("Class1").get("Class1") * 1.0) / ((double) confusionMatrix.get("Class1").get("Class1") + confusionMatrix.get("Class0").get("Class1"));
double hm = 2 * (specifity * sensitivity) / (specifity + sensitivity);
DecimalFormat df = new DecimalFormat("0.000");
System.out.println(String.format("Accuracy: %s", df.format(accuracy)));
System.out.println(String.format("Specifity: %s", df.format(specifity)));
System.out.println(String.format("Sensitivity: %s", df.format(sensitivity)));
System.out.println(String.format("HM: %s", df.format(hm)));
System.out.println(String.format("Precision: %s", df.format(precision)));
System.out.println(String.format("Negative Predicted Value (NPV): %s", df.format(npv)));
return hm;
}
/**
*
* @param dataset
* @param inferenceEngine
* @return
*/
public static double evaluate(Dataset dataset, InferenceEngine inferenceEngine) {
Attribute targetAttr = dataset.getTarget();
HashMap<String, HashMap<String, Integer>> confusionMatrix = new HashMap<>();
targetAttr.getTerms().stream().map((term1) -> {
HashMap<String, Integer> entry = new HashMap<>();
confusionMatrix.put(term1.getName(), entry);
return entry;
}).forEachOrdered((entry) -> {
targetAttr.getTerms().forEach((term2) -> {
entry.put(term2.getName(), 0);
});
entry.put("UnKnown", 0);
});
//IntStream.range(0, dataset.getNumberOfRows()).parallel().forEach(i ->{
for (int i = 0; i < dataset.getNumberOfRows(); i++) {
HashMap<String, Double> inputSpec = new HashMap<>();
for (Attribute att : dataset.getInputs()) {
for (Term term : att.getTerms()) {
String k = String.format("%s.%s", att.getName(), term.getName());
inputSpec.put(k, term.get(i));
}
}
PredictionResult res = inferenceEngine.predict(inputSpec);
int classIndex = (int) targetAttr.get(i);
String expectedClass = targetAttr.getTerm(classIndex).getName();
HashMap<String, Integer> map = confusionMatrix.get(expectedClass);
int v = map.get(res.getClassName());
confusionMatrix.get(expectedClass).put(res.getClassName(), v + 1);
//});
}
return printClassificationReport(confusionMatrix);
}
/**
*
* @param x
* @param i
* @param j
*/
public static void swap(int[] x, int i, int j) {
int s = x[i];
x[i] = x[j];
x[j] = s;
}
/**
*
* @param x
* @param i
* @param j
*/
public static void swap(float[] x, int i, int j) {
float s = x[i];
x[i] = x[j];
x[j] = s;
}
/**
*
* @param x
* @param i
* @param j
*/
public static void swap(double[] x, int i, int j) {
double s = x[i];
x[i] = x[j];
x[j] = s;
}
/**
*
* @param x
* @param i
* @param j
*/
public static void swap(String[] x, int i, int j) {
String s = x[i];
x[i] = x[j];
x[j] = s;
}
/**
*
* @param coefficients
* @return
*/
public static Complex_F64[] findRoots(double[] coefficients) {
int n = coefficients.length - 1;
// Construct the companion matrix
DMatrixRMaj c = new DMatrixRMaj(n, n);
double a = coefficients[n];
for (int i = 0; i < n; i++) {
c.set(i, n - 1, -coefficients[i] / a);
}
for (int i = 1; i < n; i++) {
c.set(i, i - 1, 1);
}
// use generalized eigenvalue decomposition to find the roots
EigenDecomposition_F64<DMatrixRMaj> evd = DecompositionFactory_DDRM.eig(n, false);
evd.decompose(c);
Complex_F64[] roots = new Complex_F64[n];
for (int i = 0; i < n; i++) {
roots[i] = evd.getEigenvalue(i);
}
return roots;
}
/**
*
* @param a
* @param b
* @return
*/
public static double cosineSimilarity(double [] a, double [] b) {
double s1 = 0, s2 = 0, s3 = 0;
for(int i = 0; i < a.length; i++) {
s1 += a[i] * b[i];
s2 += a[i] * a[i];
s3 += b[i] * b[i];
}
return s1 / (Math.sqrt(s2) * Math.sqrt(s3));
}
/**
*
* @param a
* @param b
* @return
*/
public static double getNormalizedSimilarity(double [] a, double [] b) {
double s = cosineSimilarity(a, b);
s += 1;
s /= 2;
return s;
}
/**
*
* @param vec
* @param numberOfSamples
* @param scales
* @param offsets
* @param sampleAroundInstance
* @return
*/
public double [][] getSamples(double [] vec, int numberOfSamples, double [] scales, double [] offsets, boolean sampleAroundInstance) {
double [][] samples = new double[numberOfSamples][vec.length];
double [] weights = new double[numberOfSamples];
for(int i = 0; i < numberOfSamples; i++) {
for(int j = 0; j < vec.length; j++) {
double v = RandomFactory.nextGaussian() * scales[j];
v += sampleAroundInstance ? vec[j] : offsets[j];
samples[i][j] = v;
}
double w = getNormalizedSimilarity(vec, samples[i]);
weights[i] = w;
}
return samples;
}
}
| mit |
mrmaxent/Maxent | density/tools/Node.java | 1229 | /*
Copyright (c) 2016 Steven Phillips, Miro Dudik and Rob Schapire
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package density.tools;
class Node {
int r, c, heapIndex;
double qweight;
Node(int rr, int cc) { r=rr; c = cc; }
}
| mit |
BT-OpenSource/bt-openlink-java | openlink-core/src/test/java/com/bt/openlink/iq/MakeCallRequestBuilderTest.java | 3193 | package com.bt.openlink.iq;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.bt.openlink.CoreFixtures;
import com.bt.openlink.MakeCallFixtures;
import com.bt.openlink.type.OriginatorReference;
@SuppressWarnings({"ConstantConditions", "RedundantThrows"})
public class MakeCallRequestBuilderTest {
private static class Builder extends MakeCallRequestBuilder<MakeCallRequestBuilder, String, CoreFixtures.typeEnum> {
protected Builder() {
super(CoreFixtures.typeEnum.class);
}
}
@Rule public final ExpectedException expectedException = ExpectedException.none();
private Builder builder;
@Before
public void setUp() throws Exception {
builder = new Builder();
builder.setTo("to");
builder.setFrom("from");
builder.setId("id");
}
@Test
public void willValidateAPopulatedBuilder() throws Exception {
final List<String> errors = new ArrayList<>();
builder.setJID("jid")
.setProfileId(CoreFixtures.PROFILE_ID)
.setInterestId(CoreFixtures.INTEREST_ID)
.addFeature(MakeCallFixtures.MAKE_CALL_FEATURE)
.setDestination(CoreFixtures.CALLED_DESTINATION)
.addOriginatorReference(CoreFixtures.ORIGINATOR_REFERENCE)
.addOriginatorReference("key2", "value2");
builder.validate();
builder.validate(errors);
assertThat(errors, is(empty()));
assertThat(builder.getJID().get(), is("jid"));
assertThat(builder.getProfileId().get(), is(CoreFixtures.PROFILE_ID));
assertThat(builder.getInterestId().get(), is(CoreFixtures.INTEREST_ID));
assertThat(builder.getFeatures(), contains(MakeCallFixtures.MAKE_CALL_FEATURE));
assertThat(builder.getDestination().get(), is(CoreFixtures.CALLED_DESTINATION));
assertThat(builder.getOriginatorReferences(),contains(CoreFixtures.ORIGINATOR_REFERENCE, new OriginatorReference("key2", "value2")));
}
@Test
public void willValidateTheJidIsSet() throws Exception {
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("The make-call request 'jid' has not been set");
builder.validate();
}
@Test
public void willCheckThatJidIsSet() throws Exception {
final List<String> errors = new ArrayList<>();
builder.validate(errors);
assertThat(errors, contains("Invalid make-call request stanza; missing or invalid 'jid'"));
assertThat(builder.getJID(), is(Optional.empty()));
assertThat(builder.getProfileId(), is(Optional.empty()));
assertThat(builder.getInterestId(), is(Optional.empty()));
assertThat(builder.getFeatures(), is(empty()));
assertThat(builder.getDestination(), is(Optional.empty()));
}
} | mit |
joshiejack/Harvest-Festival | src/main/java/uk/joshiejack/harvestcore/network/mail/PacketReceiveLetter.java | 771 | package uk.joshiejack.harvestcore.network.mail;
import uk.joshiejack.harvestcore.client.mail.Inbox;
import uk.joshiejack.harvestcore.registry.letter.Letter;
import uk.joshiejack.penguinlib.network.packet.PacketSendPenguin;
import uk.joshiejack.penguinlib.util.PenguinLoader;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.fml.relauncher.Side;
@PenguinLoader(side = Side.CLIENT)
public class PacketReceiveLetter extends PacketSendPenguin<Letter> {
public PacketReceiveLetter() {
super(Letter.REGISTRY);
}
public PacketReceiveLetter(Letter letter) {
super(Letter.REGISTRY, letter);
}
@Override
public void handlePacket(EntityPlayer player, Letter letter) {
Inbox.PLAYER.remove(letter);
}
} | mit |
Breinify/brein-api-library-android | brein-api-library-android/src/main/java/com/brein/domain/BreinActivityType.java | 780 | package com.brein.domain;
/**
* The type of the activity collected, i.e., one of search, login, logout, addToCart, removeFromCart, checkOut,
* selectProduct, or other.
*/
public class BreinActivityType {
private BreinActivityType() {}
// pre-defined activity types
public static final String SEARCH = "search";
public static final String LOGIN = "login";
public static final String LOGOUT = "logout";
public static final String ADD_TO_CART = "addToCart";
public static final String REMOVE_FROM_CART = "removeFromCart";
public static final String SELECT_PRODUCT = "selectProduct";
public static final String CHECKOUT = "checkOut";
public static final String PAGEVISIT = "pageVisit";
public static final String OTHER = "other";
}
| mit |
rideg/jtext | src/main/java/org/jtext/ui/graphics/Line.java | 3426 | package org.jtext.ui.graphics;
import org.jtext.curses.Point;
import org.jtext.ui.attribute.Direction;
import java.util.Objects;
public final class Line {
private final Point start;
private final int length;
private final Direction direction;
public Line(final int x, final int y, final int length, final Direction direction) {
this(Point.at(x, y), length, direction);
}
private Line(final Point start, final int length, final Direction direction) {
if (length < 0) {
throw new IllegalArgumentException("Length cannot be negative!");
}
this.start = start;
this.length = length;
this.direction = direction;
}
public int getLength() {
return length;
}
public Direction getDirection() {
return direction;
}
public static Line horizontal(final Point a, final Point b) {
if (a.getY() != b.getY()) {
throw new IllegalArgumentException("Cannot create a straight horizontal line between the two points");
}
if (a.getX() < b.getX()) {
return horizontal(a.getX(), a.getY(), b.getX() - a.getX() + 1);
} else {
return horizontal(b.getX(), b.getY(), a.getX() - b.getX() + 1);
}
}
public static Line vertical(final Point a, final Point b) {
if (a.getX() != b.getX()) {
throw new IllegalArgumentException("Cannot create a straight vertical line between the two points");
}
if (a.getY() < b.getY()) {
return vertical(a.getX(), a.getY(), b.getY() - a.getY() + 1);
} else {
return vertical(b.getX(), b.getY(), a.getY() - b.getY() + 1);
}
}
public static Line line(final Point a, final Point b, final Direction direction) {
return direction == Direction.HORIZONTAL ? horizontal(a, b) : vertical(a, b);
}
public static Line horizontal(final int x, final int y, final int length) {
return new Line(x, y, length, Direction.HORIZONTAL);
}
public static Line vertical(final int x, final int y, final int length) {
return new Line(x, y, length, Direction.VERTICAL);
}
public static Line horizontal(final Point start, final int length) {
return new Line(start, length, Direction.HORIZONTAL);
}
public static Line vertical(final Point start, final int length) {
return new Line(start, length, Direction.VERTICAL);
}
public Point end() {
return isHorizontal() ? start.shiftX(length - 1) : start.shiftY(length - 1);
}
public Point start() {
return start;
}
public boolean isHorizontal() {
return direction == Direction.HORIZONTAL;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Line)) {
return false;
}
final Line line = (Line) o;
return length == line.length &&
Objects.equals(start, line.start) &&
direction == line.direction;
}
@Override
public int hashCode() {
return Objects.hash(start, length, direction);
}
@Override
public String toString() {
return "Line{" +
"start=" + start +
", length=" + length +
", direction=" + direction +
'}';
}
}
| mit |
andreytim/jafar | problems/src/main/java/com/andreytim/jafar/problems/leetcode/GenPermutationsIterative.java | 1186 | package com.andreytim.jafar.problems.leetcode;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* Created by shpolsky on 17.01.15.
*/
public class GenPermutationsIterative {
public List<List<Integer>> permute(int[] num) {
LinkedList<List<Integer>> ans = new LinkedList<>();
ans.offer(new LinkedList<Integer>());
for (int n = 0; n < num.length; n++) {
while (n == ans.peek().size()) {
List<Integer> l = ans.poll();
for (int i = 0; i <= l.size(); i++) {
LinkedList<Integer> newL = new LinkedList<>(l.subList(0,i));
newL.add(num[n]);
newL.addAll(l.subList(i,l.size()));
ans.offer(newL);
}
}
}
return ans;
}
public static void test(int[] num) {
System.out.printf("Input: %s; Output:\n %s\n", Arrays.toString(num),
new GenPermutationsIterative().permute(num).toString());
}
public static void main(String[] args) {
test(new int[]{1});
test(new int[]{1, 2});
test(new int[]{1, 2, 3});
}
}
| mit |
hmagalhaes/exemplo-rh | rh-spring/src/main/java/br/eti/hmagalhaes/rh/model/service/DepartamentoService.java | 1368 | package br.eti.hmagalhaes.rh.model.service;
import br.eti.hmagalhaes.rh.model.dto.DepartamentoFormDTO;
import br.eti.hmagalhaes.rh.model.entity.Departamento;
import java.util.Collection;
/**
* Serviço de manipulação de {@link Departamento departamentos}.
* @author Hudson P. Magalhães <hudson@hmagalhaes.eti.br>
* @since 27-Feb-2014
*/
public interface DepartamentoService extends CRUDService<Departamento, Long> {
/**
* Quantidade geral de departamentos sem colaboradores.
* @return
*/
int qtdDepartamentosVazios();
/**
* Listagem de departamentos sem colaboradores.
* @return
*/
Collection<Departamento> departamentosVazios();
/**
* Quantidade de colaboradores no departamento indicado pelo ID.
* @param id
* @return
*/
int qtdColaboradoresPorDepto(long id);
Departamento inserir(DepartamentoFormDTO form);
Departamento atualizar(DepartamentoFormDTO form);
/**
* Remove o departamento indicado e todos os colaboradores vinculados.
* @param id
*/
void removerDepartamentoEColaboradores(long id);
/**
* Remove o departamento indicado, mas antes transfere os colaboradores
* vinculados para outro departamento.
* @param idRemover ID do depto. a remover.
* @param idTransf ID do depto. a transferir os colaboradores
*/
void removerDepartamentoTransfColaboradores(long idRemover, long idTransf);
} | mit |
Azure/azure-sdk-for-java | sdk/mariadb/azure-resourcemanager-mariadb/src/main/java/com/azure/resourcemanager/mariadb/implementation/ReplicasImpl.java | 1955 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.mariadb.implementation;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.mariadb.fluent.ReplicasClient;
import com.azure.resourcemanager.mariadb.fluent.models.ServerInner;
import com.azure.resourcemanager.mariadb.models.Replicas;
import com.azure.resourcemanager.mariadb.models.Server;
import com.fasterxml.jackson.annotation.JsonIgnore;
public final class ReplicasImpl implements Replicas {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ReplicasImpl.class);
private final ReplicasClient innerClient;
private final com.azure.resourcemanager.mariadb.MariaDBManager serviceManager;
public ReplicasImpl(ReplicasClient innerClient, com.azure.resourcemanager.mariadb.MariaDBManager serviceManager) {
this.innerClient = innerClient;
this.serviceManager = serviceManager;
}
public PagedIterable<Server> listByServer(String resourceGroupName, String serverName) {
PagedIterable<ServerInner> inner = this.serviceClient().listByServer(resourceGroupName, serverName);
return Utils.mapPage(inner, inner1 -> new ServerImpl(inner1, this.manager()));
}
public PagedIterable<Server> listByServer(String resourceGroupName, String serverName, Context context) {
PagedIterable<ServerInner> inner = this.serviceClient().listByServer(resourceGroupName, serverName, context);
return Utils.mapPage(inner, inner1 -> new ServerImpl(inner1, this.manager()));
}
private ReplicasClient serviceClient() {
return this.innerClient;
}
private com.azure.resourcemanager.mariadb.MariaDBManager manager() {
return this.serviceManager;
}
}
| mit |
Fastjur/SEM-Project | src/main/java/net/liquidpineapple/pang/objects/Player.java | 5339 | package net.liquidpineapple.pang.objects;
import net.liquidpineapple.pang.Application;
import net.liquidpineapple.pang.AudioSystem;
import net.liquidpineapple.pang.SoundEffect;
import net.liquidpineapple.pang.gui.LifeSystem;
import net.liquidpineapple.pang.gui.TimeSystem;
import net.liquidpineapple.pang.logger.Logger;
import net.liquidpineapple.pang.objects.playerschemes.PlayerScheme;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @author Jurriaan Den Toonder
* @date 2016/09/06.
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class Player extends GameObject {
private boolean shootheld = false;
private boolean isHit = false;
private PlayerScheme playerScheme;
public int activeHooks = 0;
public int maximumHooks = 1;
public int shield = 0;
public int hookRemoveDelay = 0;
private boolean frozen = false;
private boolean hasDefaultTexture = true;
private enum PlayerMovement {
LEFT_DIRECTION(-4 / 5.0),
RIGHT_DIRECTION(4 / 5.0),
NO_MOVEMENT(0);
private final double dx;
PlayerMovement(double dx) {
this.dx = dx;
}
}
private double dx;
public Player(double startX, double startY, PlayerScheme playerScheme) {
super(playerScheme.getTextureName(), startX, startY);
this.playerScheme = playerScheme;
}
/**
* Method that moves the player.
*/
public void move() {
xpos += dx;
xpos = Math.max(xpos,1);
int boardWidth = Application.getBoard().getWidth();
double playerMaxPosX = boardWidth - this.getWidth();
xpos = Math.min(xpos, playerMaxPosX);
AudioSystem.playEffect(SoundEffect.FOOTSTEP, false, 3);
}
@Override
public void doUpdate() {
super.doUpdate();
updatePlayerState();
updatePlayerTexture();
handlePlayerMovement();
handlePlayerShooting();
handlePlayerCollision();
}
private void updatePlayerState() {
if (TimeSystem.getFrozen() > 0 && !frozen) {
frozen = true;
} else if (TimeSystem.getFrozen() == 0 && frozen){
frozen = false;
}
}
/**
* Handles the player texture.
* eg. sets it to frozen or shield when necessary.
*/
private void updatePlayerTexture() {
if (frozen) {
this.changeImage(playerScheme.getFrozenTextureName());
} else if (shield > 0) {
this.changeImage(playerScheme.getShieldTextureName());
} else if (!hasDefaultTexture) {
this.changeImage(playerScheme.getTextureName());
hasDefaultTexture = true;
}
}
@Override
public void changeImage(String textureLocation) {
super.changeImage(textureLocation);
hasDefaultTexture = false;
}
/**
* Checks for keypresses and sets player movement accordingly.
*/
private void handlePlayerMovement() {
if (playerScheme.leftPressed()) {
if (!playerScheme.rightPressed()) {
dx = PlayerMovement.LEFT_DIRECTION.dx;
move();
}
} else if (playerScheme.rightPressed()) {
dx = PlayerMovement.RIGHT_DIRECTION.dx;
move();
} else {
dx = PlayerMovement.NO_MOVEMENT.dx;
}
}
/**
* Checks for shooting keypress and initiates the {@link HookAndRope} and sound effect.
*/
private void handlePlayerShooting() {
if (playerScheme.shootPressed() && !shootheld && activeHooks < maximumHooks) {
HookAndRope newRope = new HookAndRope(getXpos(), 0, this, hookRemoveDelay);
Application.getBoard().getCurrentScreen().objectList.add(newRope);
AudioSystem.playEffect(SoundEffect.HOOK_SHOOT);
activeHooks++;
shootheld = true;
}
if (!playerScheme.shootPressed() && shootheld) {
shootheld = false;
}
}
/**
* Checks if player collides and updates lives when necessary.
* Also plays a sound effect on hit.
*/
private void handlePlayerCollision() {
if (collisionPlayer() && !isHit && !Application.cheatMode && !frozen) {
if (shield > 0) {
shield -= 1;
if (shield == 0) {
this.changeImage(playerScheme.getTextureName());
}
} else {
LifeSystem.loseLife();
}
isHit = true;
AudioSystem.playEffect(SoundEffect.PLAYER_HIT);
}
}
/**
* Method that handles the collision of a player with a ball.
* @return a true if player collides with the ball, false otherwise.
*/
public boolean collisionPlayer() {
for (GameObject object : Application.getBoard().getCurrentScreen().objectList) {
if (object instanceof Ball || object instanceof Drop) {
double playerPos = this.getXpos() + (this.getImage().getWidth(null)) / 2;
if (playerPos - object.getXpos() >= 0 && playerPos - object.getXpos() <= object.getWidth()
&& object.getYpos() + object.getHeight() >= this.getYpos()) {
Logger.info(playerScheme.getName() + " collided with object:" + object);
if (object instanceof Drop) {
Drop drop = (Drop) object;
drop.playerCollision(this);
return false;
} else {
return true;
}
}
}
}
isHit = false;
return false;
}
/**
* Sets the player shield.
* @param shield 'Amount' of shield to add. Every value is 1 hit protection.
*/
public final void setShield(int shield) {
this.shield = shield;
this.changeImage(playerScheme.getShieldTextureName());
}
}
| mit |
Heitor-Monteiro/LADES-Hospital-Veterinario- | SIHV/src/main/java/com/lades/sihv/controller/dashboard/ScheduledConsultations.java | 2514 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.lades.sihv.controller.dashboard;
import com.lades.sihv.bean.AbstractBean;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
/**
*
* @author thiberius
*/
public class ScheduledConsultations extends AbstractBean {
private int qtd = 0;
private String scheduleCanceledInTheMonth = "0";
private String confirmedSchedules = "0";
public ScheduledConsultations() {
List<?> list = getDaoGenerico().list("select s from Scheduling s \n"
+ "where \n"
+ "s.statusService='agendado(a)'");
if (list != null && !list.isEmpty()) {
qtd = list.size();
}
scheduleCanceledInTheMonth = scheduleInTheMonth("cancelado(a)");
confirmedSchedules = scheduleInTheMonth("confirmado(a)");
}
private String scheduleInTheMonth(String statusService) {
String quantityOfItems = "0";
Calendar cal = GregorianCalendar.getInstance();
int currentYear = cal.get(Calendar.YEAR);
int currentMonth = cal.get(Calendar.MONTH);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, currentMonth);
int day = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
List<?> list;
if (statusService.equals("confirmado(a)")) {
list = getDaoGenerico().list("select count(s.pkSchedule) from Scheduling s \n"
+ "where \n"
+ "s.statusService='" + statusService + "'");
} else {
list = getDaoGenerico().list("select count(s.pkSchedule) from Scheduling s \n"
+ "where \n"
+ "s.statusService='" + statusService + "' and \n"
+ "s.schedulingDate>='" + currentYear + "-" + (currentMonth + 1) + "-01 01:00:00' and \n"
+ "s.schedulingDate<='" + currentYear + "-" + (currentMonth + 1) + "-" + day + " 23:59:59' ");
}
if (list != null && !list.isEmpty()) {
quantityOfItems = "" + list.get(0);
}
return quantityOfItems;
}
public int getQtd() {
return qtd;
}
public String getScheduleCanceledInTheMonth() {
return scheduleCanceledInTheMonth;
}
public String getConfirmedSchedules() {
return confirmedSchedules;
}
}
| mit |
joowani/leetcode | src/solutions/Solution191.java | 585 | package solutions;
/**
* 191. Number of 1 Bits
*
* Write a function that takes an unsigned integer and returns the number of
* '1' bits it has (also known as the Hamming weight).
*
* For example, the 32-bit integer ’11' has binary representation
* 00000000000000000000000000001011, so the function should return 3.
*
*/
public class Solution191 {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while (n > 0) {
count += 1 & n;
n = n >> 1;
}
return count;
}
}
| mit |
Sw1cH/Android-Ebook | assets/source/MultiprocessingDemo2.java | 10995 | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* This demo program divides up a large computation into a fairly
* large number of smaller tasks. The computation is to compute
* an image, and each task computes one row of pixels in the image.
* The tasks are placed into a thread-safe queue. Several "worker"
* threads remove tasks from the queue and carry them out. When
* all the tasks have completed, the worker threads terminate.
* The number of worker threads is specified by the user.
* (The image is a small piece of the famous Mandelbrot set,
* which is used just because it takes some time to compute.
* There is no need to understand what the image means.)
*/
public class MultiprocessingDemo2 extends JPanel {
/**
* This main routine just shows a panel of type MultiprocessingDemo2.
*/
public static void main(String[] args) {
JFrame window = new JFrame("Multiprocessing Demo 2");
MultiprocessingDemo2 content = new MultiprocessingDemo2();
window.setContentPane(content);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack();
window.setResizable(false);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation( (screenSize.width - window.getWidth()) / 2,
(screenSize.height - window.getHeight()) / 2 );
window.setVisible(true);
}
private WorkerThread[] workers; // the threads that compute the image
private ConcurrentLinkedQueue<Runnable> taskQueue; // holds individual tasks.
private volatile int threadsCompleted; // how many tasks have finished?
private volatile boolean running; // used to signal the thread to abort
private JButton startButton; // button the user can click to start or abort the thread
private JComboBox threadCountSelect; // for specifying the number of threads to be used
private BufferedImage image; // contains the image that is computed by this program
int[] palette; // Holds a spectrum of RGB color values; used in computing pixel colors.
/**
* The display is a JPanel that shows the image. The part of the image that has
* not yet been computed is gray. If the image has not yet been created, the
* entire display is filled with gray.
*/
private JPanel display = new JPanel() {
protected void paintComponent(Graphics g) {
if (image == null)
super.paintComponent(g); // fill with background color, gray
else {
/* Copy the image onto the display. This is synchronized because
* there are several threads that compete for access to the image:
* the threads that compute the image and the thread that does the
* painting. These threads all synchronize on the image object,
* although any object could be used.
*/
synchronized(image) {
g.drawImage(image,0,0,null);
}
}
}
};
/**
* Constructor creates a panel to hold the display, with a "Start" button
* and a pop-up menu for selecting the number of threads below it.
*/
public MultiprocessingDemo2() {
display.setPreferredSize(new Dimension(800,600));
display.setBackground(Color.LIGHT_GRAY);
setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
setLayout(new BorderLayout());
add(display, BorderLayout.CENTER);
JPanel bottom = new JPanel();
startButton = new JButton("Start");
bottom.add(startButton);
threadCountSelect = new JComboBox();
threadCountSelect.addItem("Use 1 thread.");
threadCountSelect.addItem("Use 2 threads.");
threadCountSelect.addItem("Use 3 threads.");
threadCountSelect.addItem("Use 4 threads.");
threadCountSelect.addItem("Use 5 threads.");
threadCountSelect.setSelectedIndex(1);
bottom.add(threadCountSelect);
bottom.setBackground(Color.WHITE);
add(bottom,BorderLayout.SOUTH);
palette = new int[256];
for (int i = 0; i < 256; i++)
palette[i] = Color.getHSBColor(i/255F, 1, 1).getRGB();
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (running)
stop();
else
start();
}
});
}
/**
* This method is called when the user clicks the Start button,
* while no computation is in progress. It starts as many new
* threads as the user has specified. It creates one
* MandelbrotTask object for each row of the image and places
* all the tasks into a queue. The threads will remove tasks
* from the queue to process them. The threads are run at lower
* priority than the event-handling thread, in order to keep the
* GUI responsive.
*/
private void start() {
startButton.setText("Abort"); // change name while computation is in progress
threadCountSelect.setEnabled(false); // will be re-enabled when all threads finish
int width = display.getWidth() + 2;
int height = display.getHeight() + 2;
if (image == null)
image = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics(); // fill image with gray
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0,0,width,height);
g.dispose();
display.repaint();
taskQueue = new ConcurrentLinkedQueue<Runnable>();
double xmin = -1.6744096740931858;
double xmax = -1.674409674093473;
double ymin = 4.716540768697223E-5;
double ymax = 4.716540790246652E-5;
int maxIterations = 10000;
double dx = (xmax-xmin)/(width-1);
double dy = (ymax-ymin)/(height-1);
for (int row = 0; row < height; row++) {
double y = ymax - row*dy;
MandelbrotTask task = new MandelbrotTask(row, width, maxIterations, xmin, y, dx);
taskQueue.add(task);
}
int threadCount = threadCountSelect.getSelectedIndex() + 1;
workers = new WorkerThread[threadCount];
running = true; // Set the signal before starting the threads!
threadsCompleted = 0; // Records how many of the threads have terminated.
for (int i = 0; i < threadCount; i++) {
workers[i] = new WorkerThread();
try {
workers[i].setPriority( Thread.currentThread().getPriority() - 1 );
}
catch (Exception e) {
}
workers[i].start();
}
}
/**
* This method is called when the user clicks the button while
* a thread is running. A signal is sent to the thread to terminate,
* by setting the value of the signaling variable, running, to false.
*/
private void stop() {
startButton.setEnabled(false); // will be re-enabled when all threads finish
running = false;
}
/**
* This method is called by each thread when it terminates. We keep track
* of the number of threads that have terminated, so that when they have
* all finished, we can put the program into the correct state, such as
* changing the name of the button to "Start Again" and re-enabling the
* pop-up menu.
*/
synchronized private void threadFinished() {
threadsCompleted++;
if (threadsCompleted == workers.length) { // all threads have finished
startButton.setText("Start Again");
startButton.setEnabled(true);
running = false; // Make sure running is false after the thread ends.
workers = null;
threadCountSelect.setEnabled(true); // re-enable pop-up menu
}
}
/**
* An object of type MandelbrotTask represents the task of computing one row
* of pixels in an image of the Mandelbrot set. The task has a run() method
* that does the actual computation and also applies the colors that it has
* computed to the image on the screen.
*/
private class MandelbrotTask implements Runnable {
int rowNumber; // Which row of pixels does this task compute?
double xmin; // The x-value for the first pixel in the row.
double y; // The y-value for all the pixels in the row.
double dx; // The change in x-value from one pixel to the next.
int width; // The number of pixels in the row.
int maxIterations; // The maximum count in the Mandelbrot algorithm.
MandelbrotTask( int rowNumber, int width, int maxIterations, double xmin, double y, double dx) {
this.rowNumber = rowNumber;
this.maxIterations = maxIterations;
this.xmin = xmin;
this.y = y;
this.dx = dx;
this.width = width;
}
public void run() {
int[] rgb= new int[width]; // The colors computed for the pixels.
for (int i = 0; i < rgb.length; i++) {
double x = xmin + i * dx;
int count = 0;
double xx = x;
double yy = y;
while (count < maxIterations && (xx*xx + yy*yy) < 4) {
count++;
double newxx = xx*xx - yy*yy + x;
yy = 2*xx*yy + y;
xx = newxx;
}
if (count == maxIterations)
rgb[i] = 0;
else
rgb[i] = palette[count % 256];
}
synchronized(image) {
/* Add the newly computed row of pixel colors to the image. This is
* synchronized because this thread and the thread that paints the
* display might both try to access the image simultaneously.
*/
image.setRGB(0,rowNumber, width, 1, rgb, 0, width);
}
display.repaint(0,rowNumber,width,1); // Repaint just the newly computed row.
}
}
/**
* This class defines the worker threads that carry out the tasks.
* A WorkerThread runs in a loop in which it retrieves a task from the
* taskQueue and calls the run() method in that task. The thread
* terminates when the queue is empty. (Note that for this to work
* properly, all the tasks must be placed into the queue before the
* thread is started. If the queue is empty when the thread starts,
* the thread will simply exit immediately.) The thread also terminates
* if the signal variable, running, is set to false. Just before it
* terminates, the thread calls the threadFinished() method.
*/
private class WorkerThread extends Thread {
public void run() {
try {
while (running) {
Runnable task = taskQueue.poll();
if (task == null)
break;
task.run();
}
}
finally {
threadFinished();
}
}
}
}
| mit |
katzenpapst/amunra | src/main/java/de/katzenpapst/amunra/mothership/fueldisplay/MothershipFuelDisplayFluid.java | 1059 | package de.katzenpapst.amunra.mothership.fueldisplay;
import net.minecraft.util.IIcon;
import net.minecraftforge.fluids.Fluid;
public class MothershipFuelDisplayFluid extends MothershipFuelDisplay {
private Fluid fluid;
public MothershipFuelDisplayFluid(Fluid fluid) {
this.fluid = fluid;
}
@Override
public IIcon getIcon() {
return fluid.getIcon();
}
@Override
public String getDisplayName() {
return fluid.getLocalizedName();
}
@Override
public int getSpriteNumber() {
return fluid.getSpriteNumber();
}
@Override
public String getUnit() {
return "B";
}
@Override
public float getFactor() {
return 0.001F;
}
@Override
public boolean equals(Object other) {
if(!(other instanceof MothershipFuelDisplayFluid)) {
return false;
}
return fluid == ((MothershipFuelDisplayFluid)other).fluid;
}
@Override
public int hashCode() {
return fluid.hashCode() + 89465;
}
}
| mit |
wbates/SierpinskiGenerator | src/com/wbates/android/sierpinski/generator/DrawActivity.java | 2614 | package com.wbates.android.sierpinski.generator;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;
public class DrawActivity extends Activity {
TextView tv;
SierpinskiCanvas canvas;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_draw);
Intent i = getIntent();
canvas = new SierpinskiCanvas(
this,
i.getIntExtra("sb1x",0),
i.getIntExtra("sb1y",0),
i.getIntExtra("sb2x",0),
i.getIntExtra("sb2y",0),
i.getIntExtra("sb3x",0),
i.getIntExtra("sb3y",0)
);
FrameLayout main = (FrameLayout) findViewById(R.id.sierpinski_draw_view);
main.addView(canvas);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_draw, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
Context context = getApplicationContext();
switch(item.getItemId()) {
case R.id.menu_save_image: CanvasImageSaver imagesaver = new CanvasImageSaver(canvas, context);
imagesaver.saveToImage();
return true;
case R.id.menu_share_fb: CanvasSocialShare socialshare = new CanvasSocialShare(canvas,context,this);
socialshare.shareImage();
return true;
case R.id.menu_about: openAboutDialog();
return true;
}
return false;
}
private void openAboutDialog() {
new AlertDialog.Builder(this)
.setTitle(R.string.menu_about)
.setMessage("Package:\n\t\t" + getString(R.string.app_name) + "\n" +
"Author:\n\t\t" + getString(R.string.author_name) + "\n" +
"Copyright:\n\t\t" + getString(R.string.copyright) + "\n" +
"License:\n\t\t" + getString(R.string.license_short) + "\n"
)
.setPositiveButton(R.string.close_button,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{
}
})
.show();
}
}
| mit |
dx14/SLogo | src/parser/structure/CompoundTurtle.java | 5110 | package parser.structure;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import gui.modelinterface.GUITurtle;
import parser.ParserException;
import parser.command.Evaluable;
import util.Coordinate;
import util.LineStyle;
import util.SlogoPath;
public class CompoundTurtle implements Turtle, GUITurtle{
private Map<Integer, Turtle> myTurtles;
private int currentTurtleID;
private TurtleContainer myContainer;
public CompoundTurtle(TurtleContainer container, List<Turtle> turtles){
myContainer = container;
myTurtles = turtles.stream()
.collect(Collectors.toMap((t) -> t.getID(), Function.identity()));
currentTurtleID = myTurtles.values().stream().reduce( (t1, t2) -> t2 ).get().getID();
System.out.println("CURRENT TURTLE ID: " + currentTurtleID);
}
private double recursiveSet(TurtleFunction<Turtle, Double> operation) throws ParserException{
double result = 0;
for(Turtle t : myTurtles.values()){
currentTurtleID = t.getID();
result = operation.apply(t);
System.out.println("Applying operation to turtle " + currentTurtleID);
update();
}
return result;
}
private double recursiveSet(TurtleFunction<Turtle, Double> operation, boolean exceptionsOn){
double result = 0;
try{
result = recursiveSet(operation);
}
catch(ParserException e){
e.printStackTrace();
}
return result;
}
@Override
public int getID() {
return currentTurtleID;
}
@Override
public List<SlogoPath> getPaths() {
return myTurtles.get(currentTurtleID).getPaths();
}
@Override
public List<SlogoPath> getHistory() {
return myTurtles.get(currentTurtleID).getHistory();
}
@Override
public Pen getPen() {
return myTurtles.get(currentTurtleID).getPen();
}
@Override
public boolean isShowing() {
return myTurtles.get(currentTurtleID).isShowing();
}
@Override
public boolean isClear() {
return myTurtles.get(currentTurtleID).isClear();
}
@Override
public void completeUpdate() {
myTurtles.get(currentTurtleID).completeUpdate();
}
@Override
public double move(Evaluable distance, UnaryOperator<Double> operator) throws ParserException {
return recursiveSet( (t) -> t.move(distance, operator) );
}
@Override
public boolean visible() {
return myTurtles.get(currentTurtleID).visible();
}
@Override
public boolean visible(boolean visible) {
recursiveSet( (t) -> { t.visible(visible); return 0.0; }, false);
return visible;
}
@Override
public void penDown() {
recursiveSet( (t) -> { t.penDown(); return 0.0; } , false);
}
@Override
public void penUp() {
recursiveSet( (t) -> { t.penUp(); return 0.0; }, false);
}
@Override
public boolean isPenDown() {
return myTurtles.get(currentTurtleID).isPenDown();
}
@Override
public double getHeading() {
return myTurtles.get(currentTurtleID).getHeading();
}
@Override
public double setPosition(Evaluable x, Evaluable y) throws ParserException {
return recursiveSet( (t) -> t.setPosition(x, y) );
}
@Override
public double setHeading(Evaluable angle) throws ParserException {
return recursiveSet( (t) -> t.setHeading(angle) );
}
@Override
public double setTowards(Evaluable x, Evaluable y) throws ParserException {
return recursiveSet((t) -> t.setTowards(x, y) );
}
@Override
public void clear() {
recursiveSet( (t) -> {t.clear(); return 0.0;}, false );
}
@Override
public double goHome() {
return recursiveSet((t) -> t.goHome(), false);
}
@Override
public double turn(Evaluable angle, UnaryOperator<Double> operator) throws ParserException {
return recursiveSet((t)->t.turn(angle, operator));
}
@Override
public Coordinate getCoordinate() {
return myTurtles.get(currentTurtleID).getCoordinate();
}
private void update(){
myContainer.update();
}
@Override
public void setPenColor(int color) {
myTurtles.get(currentTurtleID).setPenColor(color);
}
@Override
public boolean isStamped() {
return myTurtles.get(currentTurtleID).isStamped();
}
@Override
public double setPenSize(Evaluable size) throws ParserException {
return recursiveSet((t) -> t.setPenSize(size));
}
@Override
public double setPenColor(Evaluable color) throws ParserException {
return recursiveSet((t) -> t.setPenColor(color));
}
@Override
public double setShape(Evaluable shape) throws ParserException {
return recursiveSet((t) -> t.setShape(shape));
}
@Override
public double getShape() {
return myTurtles.get(currentTurtleID).getShape();
}
@Override
public double stamp() {
return recursiveSet((t) -> t.stamp(), false);
}
@Override
public void setPenStyle(LineStyle style) {
recursiveSet((t) -> { t.setPenStyle(style); return 0.0;}, false);
}
@Override
public LineStyle getPenStyle() {
return myTurtles.get(currentTurtleID).getPenStyle();
}
@Override
public int getDisplayIndex() {
return myTurtles.get(currentTurtleID).getDisplayIndex();
}
@Override
public void setDisplayIndex(int display) {
recursiveSet((t) -> {t.setDisplayIndex(display); return 0.0;}, false);
}
}
| mit |
pta2002/Mercury | Project/src/com/radirius/mercury/tutorials/BasicRendering.java | 1168 | package com.radirius.mercury.tutorials;
import com.radirius.mercury.framework.*;
import com.radirius.mercury.graphics.*;
import com.radirius.mercury.math.geometry.Rectangle;
/**
* @author wessles
*/
public class BasicRendering extends Core {
public BasicRendering(CoreSetup coreSetup) {
super(coreSetup);
}
public static void main(String[] args) {
CoreSetup coreSetup = new CoreSetup("Basic Rendering");
coreSetup.width = 800;
coreSetup.height = 600;
BasicRendering basicRendering = new BasicRendering(coreSetup);
basicRendering.start();
}
@Override
public void init() {
}
@Override
public void update() {
}
@Override
public void render(Graphics g) {
// A 100x100 rectangle at (10, 10)
Rectangle rectangle = new Rectangle(10, 10, 100, 100);
// Set the color of the rectangle
g.setColor(Color.GREEN);
// Draw the solid green rectangle
g.drawShape(rectangle);
// A 100x100 rectangle at (500, 500)
Rectangle rectangle2 = new Rectangle(500, 500, 100, 100);
// Set the color of the rectangle
g.setColor(Color.BLUE);
// Trace the green rectangle
g.traceShape(rectangle2);
}
@Override
public void cleanup() {
}
} | mit |
wzh880801/productai-java-sdk | src/main/java/cn/productai/api/pai/entity/batch/StartTaskRequest.java | 846 | package cn.productai.api.pai.entity.batch;
import cn.productai.api.core.attribute.ParaSignAttribute;
import cn.productai.api.core.base.BaseRequest;
public class StartTaskRequest extends BaseRequest<StartTaskResponse> {
@Override
public Class<StartTaskResponse> getResponseClass() {
return StartTaskResponse.class;
}
@Override
public String getApiUrl() {
return String.format("https://%s/batch/_1000001/task/apply", this.getHost());
}
@ParaSignAttribute(Name = "task_id")
public String taskId;
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public StartTaskRequest() {
super();
}
public StartTaskRequest(String taskId) {
this();
this.setTaskId(taskId);
}
}
| mit |
klangner/github-analysis | src/main/java/com/matrobot/gha/insights/app/repo/ChartApp.java | 6535 | package com.matrobot.gha.insights.app.repo;
import java.awt.Dimension;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import javax.swing.JPanel;
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import com.matrobot.gha.insights.filter.RegressionRepositoryFilter;
import com.matrobot.gha.insights.ml.Dataset;
import com.matrobot.gha.insights.ml.Sample;
/**
* Checked correlation:
* - current activity <-> activity rating (no correlation)
* - old rating <-> new rating (no correlation)
*
*/
@SuppressWarnings("serial")
public class ChartApp extends ApplicationFrame {
private Properties prop = new Properties();
private Dataset dataset;
private XYSeriesCollection chartDataset;
double corrCoeff;
public ChartApp(String firstPath, String secondPath, String thirdPath) throws IOException {
super("Activity correlations");
prop.load(new FileInputStream("config.properties"));
RegressionRepositoryFilter filter = new RegressionRepositoryFilter(
prop.getProperty("data_path") + firstPath,
prop.getProperty("data_path") + secondPath,
prop.getProperty("data_path") + thirdPath);
dataset = filter.getDataset();
createChartDataset();
}
public void showChart(){
ApplicationFrame frame = new ApplicationFrame("Correlation");
JPanel jpanel = createChartPanel();
jpanel.setPreferredSize(new Dimension(800, 600));
frame.add(jpanel);
frame.pack();
RefineryUtilities.centerFrameOnScreen(frame);
frame.setVisible(true);
}
private JPanel createChartPanel() {
JFreeChart jfreechart = ChartFactory.createScatterPlot(
"Activity correlation", "Activity current", "Activity next", chartDataset,
PlotOrientation.VERTICAL, true, true, false);
// XYPlot plot = (XYPlot) jfreechart.getPlot();
// plot.getRangeAxis().setRange(new Range(0, 10));
// plot.getDomainAxis().setRange(new Range(0, 10));
return new ChartPanel(jfreechart);
}
private void createChartDataset(){
chartDataset = new XYSeriesCollection();
XYSeries series = new XYSeries("Activity");
for(Sample sample : dataset.getData()){
if(sample.features[0] > 0 && sample.output > 0 /*&& Math.random() < 0.01*/){
// double x = Math.log10(sample.features[0]);
// double y = Math.log10(sample.output);
double x = sample.features[0];
double y = sample.output;
if(x+y < 10000){
series.add(x, y);
}
else{
System.err.println("Suspicious repo: " + sample.name);
}
}
}
double[] a = new double[series.getItemCount()];
double[] b = new double[series.getItemCount()];
for(int i = 0; i < series.getItemCount(); i++){
a[i] = series.getDataItem(i).getXValue();
b[i] = series.getDataItem(i).getYValue();
}
corrCoeff = new PearsonsCorrelation().correlation(a, b);
chartDataset.addSeries(series);
}
public static void main(String args[]) throws IOException {
// ChartApp app = new ChartApp("2012-2/",
// "2012-7/", "2012-8/");
// System.out.println("Correlation 7-8 = " + app.corrCoeff);
// app.showChart();
show2011();
}
public static void show2011() throws IOException {
ChartApp app;
app = new ChartApp("2012-2/",
"2011-3/", "2011-4/");
System.out.println("Correlation 3-4 = " + app.corrCoeff);
app = new ChartApp("2012-2/",
"2011-4/", "2011-5/");
System.out.println("Correlation 4-5 = " + app.corrCoeff);
app = new ChartApp("2012-2/",
"2011-5/", "2011-6/");
System.out.println("Correlation 5-6 = " + app.corrCoeff);
app = new ChartApp("2012-2/",
"2011-6/", "2011-7/");
System.out.println("Correlation 6-7 = " + app.corrCoeff);
app = new ChartApp("2012-2/",
"2011-7/", "2011-8/");
System.out.println("Correlation 7-8 = " + app.corrCoeff);
app = new ChartApp("2012-2/",
"2011-8/", "2011-9/");
System.out.println("Correlation 8-9 = " + app.corrCoeff);
app = new ChartApp("2012-2/",
"2011-9/", "2011-10/");
System.out.println("Correlation 9-10 = " + app.corrCoeff);
app = new ChartApp("2012-2/",
"2011-10/", "2011-11/");
System.out.println("Correlation 10-11 = " + app.corrCoeff);
app = new ChartApp("2012-2/",
"2011-11/", "2011-12/");
System.out.println("Correlation 11-12 = " + app.corrCoeff);
app = new ChartApp("2012-2/",
"2011-12/", "2012-1/");
System.out.println("Correlation 12-1 = " + app.corrCoeff);
}
public static void show2012() throws IOException {
ChartApp app;
app = new ChartApp("2012-2/", "2012-1/", "2012-2/");
System.out.println("Correlation 1-2 = " + app.corrCoeff);
app = new ChartApp("2012-2/", "2012-2/", "2012-3/");
System.out.println("Correlation 2-3 = " + app.corrCoeff);
app = new ChartApp("2012-2/", "2012-3/", "2012-4/");
System.out.println("Correlation 3-4 = " + app.corrCoeff);
app = new ChartApp("2012-2/", "2012-4/", "2012-5/");
System.out.println("Correlation 4-5 = " + app.corrCoeff);
app = new ChartApp("2012-2/", "2012-5/", "2012-6/");
System.out.println("Correlation 5-6 = " + app.corrCoeff);
app = new ChartApp("2012-2/", "2012-6/", "2012-7/");
System.out.println("Correlation 6-7 = " + app.corrCoeff);
app = new ChartApp("2012-2/", "2012-7/", "2012-8/");
System.out.println("Correlation 7-8 = " + app.corrCoeff);
app = new ChartApp("2012-2/", "2012-8/", "2012-9/");
System.out.println("Correlation 8-9 = " + app.corrCoeff);
app = new ChartApp("2012-2/", "2012-9/", "2012-10/");
System.out.println("Correlation 9-10 = " + app.corrCoeff);
app = new ChartApp("2012-2/", "2012-10/", "2012-11/");
System.out.println("Correlation 10-11 = " + app.corrCoeff);
}
} | mit |
danieljoppi/gaia-framework | gaia-core/src/main/java/net/sf/gaia/persistence/schema/PostgreSQLSafeNamingStrategy.java | 21997 | package net.sf.gaia.persistence.schema;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author daniel.joppi
*
*/
public class PostgreSQLSafeNamingStrategy extends SafeNamingStrategy {
@SuppressWarnings("unused")
private static final Log logger = LogFactory.getLog(PostgreSQLSafeNamingStrategy.class);
private static final long serialVersionUID = 1L;
public static final PostgreSQLSafeNamingStrategy INSTANCE = new PostgreSQLSafeNamingStrategy();
private static final Set<String> keywordSet = new HashSet<String>();
static
{
keywordSet.add("a");
keywordSet.add("abort");
keywordSet.add("abs");
keywordSet.add("absent");
keywordSet.add("absolute");
keywordSet.add("access");
keywordSet.add("according");
keywordSet.add("action");
keywordSet.add("ada");
keywordSet.add("add");
keywordSet.add("admin");
keywordSet.add("after");
keywordSet.add("aggregate");
keywordSet.add("alias");
keywordSet.add("all");
keywordSet.add("allocate");
keywordSet.add("also");
keywordSet.add("alter");
keywordSet.add("always");
keywordSet.add("analyse");
keywordSet.add("analyze");
keywordSet.add("and");
keywordSet.add("any");
keywordSet.add("are");
keywordSet.add("array");
keywordSet.add("array_agg");
keywordSet.add("as");
keywordSet.add("asc");
keywordSet.add("asensitive");
keywordSet.add("assertion");
keywordSet.add("assignment");
keywordSet.add("asymmetric");
keywordSet.add("at");
keywordSet.add("atomic");
keywordSet.add("attribute");
keywordSet.add("attributes");
keywordSet.add("authorization");
keywordSet.add("avg");
keywordSet.add("backward");
keywordSet.add("base64");
keywordSet.add("before");
keywordSet.add("begin");
keywordSet.add("bernoulli");
keywordSet.add("between");
keywordSet.add("bigint");
keywordSet.add("binary");
keywordSet.add("bit");
keywordSet.add("bitvar");
keywordSet.add("bit_length");
keywordSet.add("blob");
keywordSet.add("bom");
keywordSet.add("boolean");
keywordSet.add("both");
keywordSet.add("breadth");
keywordSet.add("by");
keywordSet.add("c");
keywordSet.add("cache");
keywordSet.add("call");
keywordSet.add("called");
keywordSet.add("cardinality");
keywordSet.add("cascade");
keywordSet.add("cascaded");
keywordSet.add("case");
keywordSet.add("cast");
keywordSet.add("catalog");
keywordSet.add("catalog_name");
keywordSet.add("ceil");
keywordSet.add("ceiling");
keywordSet.add("chain");
keywordSet.add("char");
keywordSet.add("character");
keywordSet.add("characteristics");
keywordSet.add("characters");
keywordSet.add("character_length");
keywordSet.add("character_set_catalog");
keywordSet.add("character_set_name");
keywordSet.add("character_set_schema");
keywordSet.add("char_length");
keywordSet.add("check");
keywordSet.add("checked");
keywordSet.add("checkpoint");
keywordSet.add("class");
keywordSet.add("class_origin");
keywordSet.add("clob");
keywordSet.add("close");
keywordSet.add("cluster");
keywordSet.add("coalesce");
keywordSet.add("cobol");
keywordSet.add("collate");
keywordSet.add("collation");
keywordSet.add("collation_catalog");
keywordSet.add("collation_name");
keywordSet.add("collation_schema");
keywordSet.add("collect");
keywordSet.add("column");
keywordSet.add("columns");
keywordSet.add("column_name");
keywordSet.add("command_function");
keywordSet.add("command_function_code");
keywordSet.add("comment");
keywordSet.add("commit");
keywordSet.add("committed");
keywordSet.add("completion");
keywordSet.add("concurrently");
keywordSet.add("condition");
keywordSet.add("condition_number");
keywordSet.add("configuration");
keywordSet.add("connect");
keywordSet.add("connection");
keywordSet.add("connection_name");
keywordSet.add("constraint");
keywordSet.add("constraints");
keywordSet.add("constraint_catalog");
keywordSet.add("constraint_name");
keywordSet.add("constraint_schema");
keywordSet.add("constructor");
keywordSet.add("contains");
keywordSet.add("content");
keywordSet.add("continue");
keywordSet.add("conversion");
keywordSet.add("convert");
keywordSet.add("copy");
keywordSet.add("corr");
keywordSet.add("corresponding");
keywordSet.add("cost");
keywordSet.add("count");
keywordSet.add("covar_pop");
keywordSet.add("covar_samp");
keywordSet.add("create");
keywordSet.add("createdb");
keywordSet.add("createrole");
keywordSet.add("createuser");
keywordSet.add("cross");
keywordSet.add("csv");
keywordSet.add("cube");
keywordSet.add("cume_dist");
keywordSet.add("current");
keywordSet.add("current_catalog");
keywordSet.add("current_date");
keywordSet.add("current_default_transform_group");
keywordSet.add("current_path");
keywordSet.add("current_role");
keywordSet.add("current_schema");
keywordSet.add("current_time");
keywordSet.add("current_timestamp");
keywordSet.add("current_transform_group_for_type");
keywordSet.add("current_user");
keywordSet.add("cursor");
keywordSet.add("cursor_name");
keywordSet.add("cycle");
keywordSet.add("data");
keywordSet.add("database");
keywordSet.add("date");
keywordSet.add("datetime_interval_code");
keywordSet.add("datetime_interval_precision");
keywordSet.add("day");
keywordSet.add("deallocate");
keywordSet.add("dec");
keywordSet.add("decimal");
keywordSet.add("declare");
keywordSet.add("default");
keywordSet.add("defaults");
keywordSet.add("deferrable");
keywordSet.add("deferred");
keywordSet.add("defined");
keywordSet.add("definer");
keywordSet.add("degree");
keywordSet.add("delete");
keywordSet.add("delimiter");
keywordSet.add("delimiters");
keywordSet.add("dense_rank");
keywordSet.add("depth");
keywordSet.add("deref");
keywordSet.add("derived");
keywordSet.add("desc");
keywordSet.add("describe");
keywordSet.add("descriptor");
keywordSet.add("destroy");
keywordSet.add("destructor");
keywordSet.add("deterministic");
keywordSet.add("diagnostics");
keywordSet.add("dictionary");
keywordSet.add("disable");
keywordSet.add("discard");
keywordSet.add("disconnect");
keywordSet.add("dispatch");
keywordSet.add("distinct");
keywordSet.add("do");
keywordSet.add("document");
keywordSet.add("domain");
keywordSet.add("double");
keywordSet.add("drop");
keywordSet.add("dynamic");
keywordSet.add("dynamic_function");
keywordSet.add("dynamic_function_code");
keywordSet.add("each");
keywordSet.add("element");
keywordSet.add("else");
keywordSet.add("empty");
keywordSet.add("enable");
keywordSet.add("encoding");
keywordSet.add("encrypted");
keywordSet.add("end");
keywordSet.add("end-exec");
keywordSet.add("enum");
keywordSet.add("equals");
keywordSet.add("escape");
keywordSet.add("every");
keywordSet.add("except");
keywordSet.add("exception");
keywordSet.add("exclude");
keywordSet.add("excluding");
keywordSet.add("exclusive");
keywordSet.add("exec");
keywordSet.add("execute");
keywordSet.add("existing");
keywordSet.add("exists");
keywordSet.add("exp");
keywordSet.add("explain");
keywordSet.add("external");
keywordSet.add("extract");
keywordSet.add("false");
keywordSet.add("family");
keywordSet.add("fetch");
keywordSet.add("filter");
keywordSet.add("final");
keywordSet.add("first");
keywordSet.add("first_value");
keywordSet.add("flag");
keywordSet.add("float");
keywordSet.add("floor");
keywordSet.add("following");
keywordSet.add("for");
keywordSet.add("force");
keywordSet.add("foreign");
keywordSet.add("fortran");
keywordSet.add("forward");
keywordSet.add("found");
keywordSet.add("free");
keywordSet.add("freeze");
keywordSet.add("from");
keywordSet.add("full");
keywordSet.add("function");
keywordSet.add("fusion");
keywordSet.add("g");
keywordSet.add("general");
keywordSet.add("generated");
keywordSet.add("get");
keywordSet.add("global");
keywordSet.add("go");
keywordSet.add("goto");
keywordSet.add("grant");
keywordSet.add("granted");
keywordSet.add("greatest");
keywordSet.add("group");
keywordSet.add("grouping");
keywordSet.add("handler");
keywordSet.add("having");
keywordSet.add("header");
keywordSet.add("hex");
keywordSet.add("hierarchy");
keywordSet.add("hold");
keywordSet.add("host");
keywordSet.add("hour");
keywordSet.add("id");
keywordSet.add("identity");
keywordSet.add("if");
keywordSet.add("ignore");
keywordSet.add("ilike");
keywordSet.add("immediate");
keywordSet.add("immutable");
keywordSet.add("implementation");
keywordSet.add("implicit");
keywordSet.add("in");
keywordSet.add("including");
keywordSet.add("increment");
keywordSet.add("indent");
keywordSet.add("index");
keywordSet.add("indexes");
keywordSet.add("indicator");
keywordSet.add("infix");
keywordSet.add("inherit");
keywordSet.add("inherits");
keywordSet.add("initialize");
keywordSet.add("initially");
keywordSet.add("inner");
keywordSet.add("inout");
keywordSet.add("input");
keywordSet.add("insensitive");
keywordSet.add("insert");
keywordSet.add("instance");
keywordSet.add("instantiable");
keywordSet.add("instead");
keywordSet.add("int");
keywordSet.add("integer");
keywordSet.add("intersect");
keywordSet.add("intersection");
keywordSet.add("interval");
keywordSet.add("into");
keywordSet.add("invoker");
keywordSet.add("is");
keywordSet.add("isnull");
keywordSet.add("isolation");
keywordSet.add("iterate");
keywordSet.add("join");
keywordSet.add("k");
keywordSet.add("key");
keywordSet.add("key_member");
keywordSet.add("key_type");
keywordSet.add("lag");
keywordSet.add("lancompiler");
keywordSet.add("language");
keywordSet.add("large");
keywordSet.add("last");
keywordSet.add("last_value");
keywordSet.add("lateral");
keywordSet.add("lc_collate");
keywordSet.add("lc_ctype");
keywordSet.add("lead");
keywordSet.add("leading");
keywordSet.add("least");
keywordSet.add("left");
keywordSet.add("length");
keywordSet.add("less");
keywordSet.add("level");
keywordSet.add("like");
keywordSet.add("like_regex");
keywordSet.add("limit");
keywordSet.add("listen");
keywordSet.add("ln");
keywordSet.add("load");
keywordSet.add("local");
keywordSet.add("localtime");
keywordSet.add("localtimestamp");
keywordSet.add("location");
keywordSet.add("locator");
keywordSet.add("lock");
keywordSet.add("login");
keywordSet.add("lower");
keywordSet.add("m");
keywordSet.add("map");
keywordSet.add("mapping");
keywordSet.add("match");
keywordSet.add("matched");
keywordSet.add("max");
keywordSet.add("maxvalue");
keywordSet.add("max_cardinality");
keywordSet.add("member");
keywordSet.add("merge");
keywordSet.add("message_length");
keywordSet.add("message_octet_length");
keywordSet.add("message_text");
keywordSet.add("method");
keywordSet.add("min");
keywordSet.add("minute");
keywordSet.add("minvalue");
keywordSet.add("mod");
keywordSet.add("mode");
keywordSet.add("modifies");
keywordSet.add("modify");
keywordSet.add("module");
keywordSet.add("month");
keywordSet.add("more");
keywordSet.add("move");
keywordSet.add("multiset");
keywordSet.add("mumps");
keywordSet.add("name");
keywordSet.add("names");
keywordSet.add("namespace");
keywordSet.add("national");
keywordSet.add("natural");
keywordSet.add("nchar");
keywordSet.add("nclob");
keywordSet.add("nesting");
keywordSet.add("new");
keywordSet.add("next");
keywordSet.add("nfc");
keywordSet.add("nfd");
keywordSet.add("nfkc");
keywordSet.add("nfkd");
keywordSet.add("nil");
keywordSet.add("no");
keywordSet.add("nocreatedb");
keywordSet.add("nocreaterole");
keywordSet.add("nocreateuser");
keywordSet.add("noinherit");
keywordSet.add("nologin");
keywordSet.add("none");
keywordSet.add("normalize");
keywordSet.add("normalized");
keywordSet.add("nosuperuser");
keywordSet.add("not");
keywordSet.add("nothing");
keywordSet.add("notify");
keywordSet.add("notnull");
keywordSet.add("nowait");
keywordSet.add("nth_value");
keywordSet.add("ntile");
keywordSet.add("null");
keywordSet.add("nullable");
keywordSet.add("nullif");
keywordSet.add("nulls");
keywordSet.add("number");
keywordSet.add("numeric");
keywordSet.add("object");
keywordSet.add("occurrences_regex");
keywordSet.add("octets");
keywordSet.add("octet_length");
keywordSet.add("of");
keywordSet.add("off");
keywordSet.add("offset");
keywordSet.add("oids");
keywordSet.add("old");
keywordSet.add("on");
keywordSet.add("only");
keywordSet.add("open");
keywordSet.add("operation");
keywordSet.add("operator");
keywordSet.add("option");
keywordSet.add("options");
keywordSet.add("or");
keywordSet.add("order");
keywordSet.add("ordering");
keywordSet.add("ordinality");
keywordSet.add("others");
keywordSet.add("out");
keywordSet.add("outer");
keywordSet.add("output");
keywordSet.add("over");
keywordSet.add("overlaps");
keywordSet.add("overlay");
keywordSet.add("overriding");
keywordSet.add("owned");
keywordSet.add("owner");
keywordSet.add("p");
keywordSet.add("pad");
keywordSet.add("parameter");
keywordSet.add("parameters");
keywordSet.add("parameter_mode");
keywordSet.add("parameter_name");
keywordSet.add("parameter_ordinal_position");
keywordSet.add("parameter_specific_catalog");
keywordSet.add("parameter_specific_name");
keywordSet.add("parameter_specific_schema");
keywordSet.add("parser");
keywordSet.add("partial");
keywordSet.add("partition");
keywordSet.add("pascal");
keywordSet.add("passing");
keywordSet.add("password");
keywordSet.add("path");
keywordSet.add("percentile_cont");
keywordSet.add("percentile_disc");
keywordSet.add("percent_rank");
keywordSet.add("placing");
keywordSet.add("plans");
keywordSet.add("pli");
keywordSet.add("position");
keywordSet.add("position_regex");
keywordSet.add("postfix");
keywordSet.add("power");
keywordSet.add("preceding");
keywordSet.add("precision");
keywordSet.add("prefix");
keywordSet.add("preorder");
keywordSet.add("prepare");
keywordSet.add("prepared");
keywordSet.add("preserve");
keywordSet.add("primary");
keywordSet.add("prior");
keywordSet.add("privileges");
keywordSet.add("procedural");
keywordSet.add("procedure");
keywordSet.add("public");
keywordSet.add("quote");
keywordSet.add("range");
keywordSet.add("rank");
keywordSet.add("read");
keywordSet.add("reads");
keywordSet.add("real");
keywordSet.add("reassign");
keywordSet.add("recheck");
keywordSet.add("recursive");
keywordSet.add("ref");
keywordSet.add("references");
keywordSet.add("referencing");
keywordSet.add("regr_avgx");
keywordSet.add("regr_avgy");
keywordSet.add("regr_count");
keywordSet.add("regr_intercept");
keywordSet.add("regr_r2");
keywordSet.add("regr_slope");
keywordSet.add("regr_sxx");
keywordSet.add("regr_sxy");
keywordSet.add("regr_syy");
keywordSet.add("reindex");
keywordSet.add("relative");
keywordSet.add("release");
keywordSet.add("rename");
keywordSet.add("repeatable");
keywordSet.add("replace");
keywordSet.add("replica");
keywordSet.add("reset");
keywordSet.add("respect");
keywordSet.add("restart");
keywordSet.add("restrict");
keywordSet.add("result");
keywordSet.add("return");
keywordSet.add("returned_cardinality");
keywordSet.add("returned_length");
keywordSet.add("returned_octet_length");
keywordSet.add("returned_sqlstate");
keywordSet.add("returning");
keywordSet.add("returns");
keywordSet.add("revoke");
keywordSet.add("right");
keywordSet.add("role");
keywordSet.add("rollback");
keywordSet.add("rollup");
keywordSet.add("routine");
keywordSet.add("routine_catalog");
keywordSet.add("routine_name");
keywordSet.add("routine_schema");
keywordSet.add("row");
keywordSet.add("rows");
keywordSet.add("row_count");
keywordSet.add("row_number");
keywordSet.add("rule");
keywordSet.add("savepoint");
keywordSet.add("scale");
keywordSet.add("schema");
keywordSet.add("schema_name");
keywordSet.add("scope");
keywordSet.add("scope_catalog");
keywordSet.add("scope_name");
keywordSet.add("scope_schema");
keywordSet.add("scroll");
keywordSet.add("search");
keywordSet.add("second");
keywordSet.add("section");
keywordSet.add("security");
keywordSet.add("select");
keywordSet.add("self");
keywordSet.add("sensitive");
keywordSet.add("sequence");
keywordSet.add("serializable");
keywordSet.add("server");
keywordSet.add("server_name");
keywordSet.add("session");
keywordSet.add("session_user");
keywordSet.add("set");
keywordSet.add("setof");
keywordSet.add("sets");
keywordSet.add("share");
keywordSet.add("show");
keywordSet.add("similar");
keywordSet.add("simple");
keywordSet.add("size");
keywordSet.add("smallint");
keywordSet.add("some");
keywordSet.add("source");
keywordSet.add("space");
keywordSet.add("specific");
keywordSet.add("specifictype");
keywordSet.add("specific_name");
keywordSet.add("sql");
keywordSet.add("sqlcode");
keywordSet.add("sqlerror");
keywordSet.add("sqlexception");
keywordSet.add("sqlstate");
keywordSet.add("sqlwarning");
keywordSet.add("sqrt");
keywordSet.add("stable");
keywordSet.add("standalone");
keywordSet.add("start");
keywordSet.add("state");
keywordSet.add("statement");
keywordSet.add("static");
keywordSet.add("statistics");
keywordSet.add("stddev_pop");
keywordSet.add("stddev_samp");
keywordSet.add("stdin");
keywordSet.add("stdout");
keywordSet.add("storage");
keywordSet.add("strict");
keywordSet.add("strip");
keywordSet.add("structure");
keywordSet.add("style");
keywordSet.add("subclass_origin");
keywordSet.add("sublist");
keywordSet.add("submultiset");
keywordSet.add("substring");
keywordSet.add("substring_regex");
keywordSet.add("sum");
keywordSet.add("superuser");
keywordSet.add("symmetric");
keywordSet.add("sysid");
keywordSet.add("system");
keywordSet.add("system_user");
keywordSet.add("t");
keywordSet.add("table");
keywordSet.add("tablesample");
keywordSet.add("tablespace");
keywordSet.add("table_name");
keywordSet.add("temp");
keywordSet.add("template");
keywordSet.add("temporary");
keywordSet.add("terminate");
keywordSet.add("text");
keywordSet.add("than");
keywordSet.add("then");
keywordSet.add("ties");
keywordSet.add("time");
keywordSet.add("timestamp");
keywordSet.add("timezone_hour");
keywordSet.add("timezone_minute");
keywordSet.add("to");
keywordSet.add("top_level_count");
keywordSet.add("trailing");
keywordSet.add("transaction");
keywordSet.add("transactions_committed");
keywordSet.add("transactions_rolled_back");
keywordSet.add("transaction_active");
keywordSet.add("transform");
keywordSet.add("transforms");
keywordSet.add("translate");
keywordSet.add("translate_regex");
keywordSet.add("translation");
keywordSet.add("treat");
keywordSet.add("trigger");
keywordSet.add("trigger_catalog");
keywordSet.add("trigger_name");
keywordSet.add("trigger_schema");
keywordSet.add("trim");
keywordSet.add("trim_array");
keywordSet.add("true");
keywordSet.add("truncate");
keywordSet.add("trusted");
keywordSet.add("type");
keywordSet.add("uescape");
keywordSet.add("unbounded");
keywordSet.add("uncommitted");
keywordSet.add("under");
keywordSet.add("unencrypted");
keywordSet.add("union");
keywordSet.add("unique");
keywordSet.add("unknown");
keywordSet.add("unlisten");
keywordSet.add("unnamed");
keywordSet.add("unnest");
keywordSet.add("until");
keywordSet.add("untyped");
keywordSet.add("update");
keywordSet.add("upper");
keywordSet.add("uri");
keywordSet.add("usage");
keywordSet.add("user");
keywordSet.add("user_defined_type_catalog");
keywordSet.add("user_defined_type_code");
keywordSet.add("user_defined_type_name");
keywordSet.add("user_defined_type_schema");
keywordSet.add("using");
keywordSet.add("vacuum");
keywordSet.add("valid");
keywordSet.add("validator");
keywordSet.add("value");
keywordSet.add("values");
keywordSet.add("varbinary");
keywordSet.add("varchar");
keywordSet.add("variable");
keywordSet.add("variadic");
keywordSet.add("varying");
keywordSet.add("var_pop");
keywordSet.add("var_samp");
keywordSet.add("verbose");
keywordSet.add("version");
keywordSet.add("view");
keywordSet.add("volatile");
keywordSet.add("when");
keywordSet.add("whenever");
keywordSet.add("where");
keywordSet.add("whitespace");
keywordSet.add("width_bucket");
keywordSet.add("window");
keywordSet.add("with");
keywordSet.add("within");
keywordSet.add("without");
keywordSet.add("work");
keywordSet.add("wrapper");
keywordSet.add("write");
keywordSet.add("xml");
keywordSet.add("xmlagg");
keywordSet.add("xmlattributes");
keywordSet.add("xmlbinary");
keywordSet.add("xmlcast");
keywordSet.add("xmlcomment");
keywordSet.add("xmlconcat");
keywordSet.add("xmldeclaration");
keywordSet.add("xmldocument");
keywordSet.add("xmlelement");
keywordSet.add("xmlexists");
keywordSet.add("xmlforest");
keywordSet.add("xmliterate");
keywordSet.add("xmlnamespaces");
keywordSet.add("xmlparse");
keywordSet.add("xmlpi");
keywordSet.add("xmlquery");
keywordSet.add("xmlroot");
keywordSet.add("xmlschema");
keywordSet.add("xmlserialize");
keywordSet.add("xmltable");
keywordSet.add("xmltext");
keywordSet.add("xmlvalidate");
keywordSet.add("year");
keywordSet.add("yes");
keywordSet.add("zone");
}
@Override
protected Set<String> getKeywordSet()
{
return keywordSet;
}
} | mit |
Bammerbom/UltimateCore | src/main/java/bammerbom/ultimatecore/sponge/api/command/argument/arguments/DefaultArgument.java | 2224 | /*
* This file is part of UltimateCore, licensed under the MIT License (MIT).
*
* Copyright (c) Bammerbom
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package bammerbom.ultimatecore.sponge.api.command.argument.arguments;
import bammerbom.ultimatecore.sponge.api.command.argument.UCommandElement;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.ArgumentParseException;
import org.spongepowered.api.command.args.CommandArgs;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.text.Text;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* This is just a class to copy-paste while making new arguments
* DO NOT USE THIS
*/
public class DefaultArgument extends UCommandElement {
public DefaultArgument(@Nullable Text key) {
super(key);
}
@Nullable
@Override
public Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
return null;
}
@Override
public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
return new ArrayList<>();
}
}
| mit |
douggie/XChange | xchange-poloniex/src/main/java/org/knowm/xchange/poloniex/PoloniexAdapters.java | 14153 | package org.knowm.xchange.poloniex;
import static org.knowm.xchange.dto.account.FundingRecord.Type.*;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.LoanOrder;
import org.knowm.xchange.dto.Order;
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.account.Balance;
import org.knowm.xchange.dto.account.FundingRecord;
import org.knowm.xchange.dto.account.FundingRecord.Type;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.dto.marketdata.Trade;
import org.knowm.xchange.dto.marketdata.Trades;
import org.knowm.xchange.dto.marketdata.Trades.TradeSortType;
import org.knowm.xchange.dto.meta.CurrencyMetaData;
import org.knowm.xchange.dto.meta.CurrencyPairMetaData;
import org.knowm.xchange.dto.meta.ExchangeMetaData;
import org.knowm.xchange.dto.trade.FixedRateLoanOrder;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.OpenOrders;
import org.knowm.xchange.dto.trade.UserTrade;
import org.knowm.xchange.poloniex.dto.LoanInfo;
import org.knowm.xchange.poloniex.dto.account.PoloniexBalance;
import org.knowm.xchange.poloniex.dto.account.PoloniexLoan;
import org.knowm.xchange.poloniex.dto.marketdata.PoloniexCurrencyInfo;
import org.knowm.xchange.poloniex.dto.marketdata.PoloniexDepth;
import org.knowm.xchange.poloniex.dto.marketdata.PoloniexMarketData;
import org.knowm.xchange.poloniex.dto.marketdata.PoloniexPublicTrade;
import org.knowm.xchange.poloniex.dto.marketdata.PoloniexTicker;
import org.knowm.xchange.poloniex.dto.trade.PoloniexAdjustment;
import org.knowm.xchange.poloniex.dto.trade.PoloniexDeposit;
import org.knowm.xchange.poloniex.dto.trade.PoloniexDepositsWithdrawalsResponse;
import org.knowm.xchange.poloniex.dto.trade.PoloniexOpenOrder;
import org.knowm.xchange.poloniex.dto.trade.PoloniexUserTrade;
import org.knowm.xchange.poloniex.dto.trade.PoloniexWithdrawal;
/**
* @author Zach Holmes
* @author Dave Seyb
* @version 2.0 *
*/
public class PoloniexAdapters {
public static Ticker adaptPoloniexTicker(
PoloniexTicker poloniexTicker, CurrencyPair currencyPair) {
PoloniexMarketData marketData = poloniexTicker.getPoloniexMarketData();
return adaptPoloniexTicker(marketData, currencyPair);
}
public static Ticker adaptPoloniexTicker(
PoloniexMarketData marketData, CurrencyPair currencyPair) {
BigDecimal last = marketData.getLast();
BigDecimal bid = marketData.getHighestBid();
BigDecimal ask = marketData.getLowestAsk();
BigDecimal high = marketData.getHigh24hr();
BigDecimal low = marketData.getLow24hr();
BigDecimal volume = marketData.getQuoteVolume();
BigDecimal percentageChange = marketData.getPercentChange();
return new Ticker.Builder()
.currencyPair(currencyPair)
.last(last)
.bid(bid)
.ask(ask)
.high(high)
.low(low)
.volume(volume)
.percentageChange(percentageChange.multiply(new BigDecimal("100"), new MathContext(8)))
.build();
}
public static OrderBook adaptPoloniexDepth(PoloniexDepth depth, CurrencyPair currencyPair) {
List<LimitOrder> asks = adaptPoloniexPublicOrders(depth.getAsks(), OrderType.ASK, currencyPair);
List<LimitOrder> bids = adaptPoloniexPublicOrders(depth.getBids(), OrderType.BID, currencyPair);
return new OrderBook(null, asks, bids);
}
public static List<LimitOrder> adaptPoloniexPublicOrders(
List<List<BigDecimal>> rawLevels, OrderType orderType, CurrencyPair currencyPair) {
List<LimitOrder> orders = new ArrayList<>();
for (List<BigDecimal> rawlevel : rawLevels) {
LimitOrder limitOrder =
new LimitOrder.Builder(orderType, currencyPair)
.originalAmount(rawlevel.get(1))
.limitPrice(rawlevel.get(0))
.build();
orders.add(limitOrder);
}
return orders;
}
public static Trades adaptPoloniexPublicTrades(
PoloniexPublicTrade[] poloniexPublicTrades, CurrencyPair currencyPair) {
List<Trade> trades = new ArrayList<>();
for (PoloniexPublicTrade poloniexTrade : poloniexPublicTrades) {
trades.add(adaptPoloniexPublicTrade(poloniexTrade, currencyPair));
}
return new Trades(trades, TradeSortType.SortByTimestamp);
}
public static Trade adaptPoloniexPublicTrade(
PoloniexPublicTrade poloniexTrade, CurrencyPair currencyPair) {
OrderType type =
poloniexTrade.getType().equalsIgnoreCase("buy") ? OrderType.BID : OrderType.ASK;
Date timestamp = PoloniexUtils.stringToDate(poloniexTrade.getDate());
return new Trade.Builder()
.type(type)
.originalAmount(poloniexTrade.getAmount())
.currencyPair(currencyPair)
.price(poloniexTrade.getRate())
.timestamp(timestamp)
.id(poloniexTrade.getTradeID())
.build();
}
public static List<Balance> adaptPoloniexBalances(
HashMap<String, PoloniexBalance> poloniexBalances) {
List<Balance> balances = new ArrayList<>();
for (Map.Entry<String, PoloniexBalance> item : poloniexBalances.entrySet()) {
Currency currency = Currency.getInstance(item.getKey());
balances.add(
new Balance(
currency, null, item.getValue().getAvailable(), item.getValue().getOnOrders()));
}
return balances;
}
public static LoanInfo adaptPoloniexLoans(HashMap<String, PoloniexLoan[]> poloniexLoans) {
Map<String, List<LoanOrder>> loans = new HashMap<>();
for (Map.Entry<String, PoloniexLoan[]> item : poloniexLoans.entrySet()) {
List<LoanOrder> loanOrders = new ArrayList<>();
for (PoloniexLoan poloniexLoan : item.getValue()) {
Date date = PoloniexUtils.stringToDate(poloniexLoan.getDate());
loanOrders.add(
new FixedRateLoanOrder(
OrderType.ASK,
poloniexLoan.getCurrency(),
poloniexLoan.getAmount(),
poloniexLoan.getRange(),
poloniexLoan.getId(),
date,
poloniexLoan.getRate())); // TODO
}
loans.put(item.getKey(), loanOrders);
}
return new LoanInfo(loans.get("provided"), loans.get("used"));
}
public static OpenOrders adaptPoloniexOpenOrders(
Map<String, PoloniexOpenOrder[]> poloniexOpenOrders) {
List<LimitOrder> openOrders = new ArrayList<>();
for (String pairString : poloniexOpenOrders.keySet()) {
CurrencyPair currencyPair = PoloniexUtils.toCurrencyPair(pairString);
for (PoloniexOpenOrder openOrder : poloniexOpenOrders.get(pairString)) {
openOrders.add(adaptPoloniexOpenOrder(openOrder, currencyPair));
}
}
return new OpenOrders(openOrders);
}
public static LimitOrder adaptPoloniexOpenOrder(
PoloniexOpenOrder openOrder, CurrencyPair currencyPair) {
OrderType type = openOrder.getType().equals("buy") ? OrderType.BID : OrderType.ASK;
Date timestamp = PoloniexUtils.stringToDate(openOrder.getDate());
return new LimitOrder.Builder(type, currencyPair)
.limitPrice(openOrder.getRate())
.originalAmount(openOrder.getStartingAmount())
.cumulativeAmount(openOrder.getStartingAmount().subtract(openOrder.getAmount()))
.id(openOrder.getOrderNumber())
.timestamp(timestamp)
.build();
}
public static UserTrade adaptPoloniexUserTrade(
PoloniexUserTrade userTrade, CurrencyPair currencyPair) {
OrderType orderType =
userTrade.getType().equalsIgnoreCase("buy") ? OrderType.BID : OrderType.ASK;
BigDecimal amount = userTrade.getAmount();
BigDecimal price = userTrade.getRate();
Date date = PoloniexUtils.stringToDate(userTrade.getDate());
String tradeId = String.valueOf(userTrade.getTradeID());
String orderId = String.valueOf(userTrade.getOrderNumber());
// Poloniex returns fee as a multiplier, e.g. a 0.2% fee is 0.002
// fee currency/size depends on trade direction (buy/sell). It appears to be rounded down
final BigDecimal feeAmount;
final String feeCurrencyCode;
if (orderType == OrderType.ASK) {
feeAmount =
amount.multiply(price).multiply(userTrade.getFee()).setScale(8, RoundingMode.DOWN);
feeCurrencyCode = currencyPair.counter.getCurrencyCode();
} else {
feeAmount = amount.multiply(userTrade.getFee()).setScale(8, RoundingMode.DOWN);
feeCurrencyCode = currencyPair.base.getCurrencyCode();
}
return new UserTrade.Builder()
.type(orderType)
.originalAmount(amount)
.currencyPair(currencyPair)
.price(price)
.timestamp(date)
.id(tradeId)
.orderId(orderId)
.feeAmount(feeAmount)
.feeCurrency(Currency.getInstance(feeCurrencyCode))
.build();
}
public static ExchangeMetaData adaptToExchangeMetaData(
Map<String, PoloniexCurrencyInfo> poloniexCurrencyInfo,
Map<String, PoloniexMarketData> poloniexMarketData,
ExchangeMetaData exchangeMetaData) {
Map<Currency, CurrencyMetaData> currencyMetaDataMap = exchangeMetaData.getCurrencies();
CurrencyMetaData currencyArchetype = currencyMetaDataMap.values().iterator().next();
for (Map.Entry<String, PoloniexCurrencyInfo> entry : poloniexCurrencyInfo.entrySet()) {
Currency ccy = Currency.getInstance(entry.getKey());
if (!currencyMetaDataMap.containsKey(ccy)) currencyMetaDataMap.put(ccy, currencyArchetype);
}
Map<CurrencyPair, CurrencyPairMetaData> marketMetaDataMap = exchangeMetaData.getCurrencyPairs();
CurrencyPairMetaData marketArchetype = marketMetaDataMap.values().iterator().next();
for (String market : poloniexMarketData.keySet()) {
CurrencyPair currencyPair = PoloniexUtils.toCurrencyPair(market);
if (!marketMetaDataMap.containsKey(currencyPair))
marketMetaDataMap.put(currencyPair, marketArchetype);
}
return exchangeMetaData;
}
public static List<FundingRecord> adaptFundingRecords(
PoloniexDepositsWithdrawalsResponse poloFundings) {
final ArrayList<FundingRecord> fundingRecords = new ArrayList<>();
for (PoloniexAdjustment a : poloFundings.getAdjustments()) {
fundingRecords.add(adaptAdjustment(a));
}
for (PoloniexDeposit d : poloFundings.getDeposits()) {
fundingRecords.add(adaptDeposit(d));
}
for (PoloniexWithdrawal w : poloFundings.getWithdrawals()) {
fundingRecords.add(adaptWithdrawal(w));
}
return fundingRecords;
}
private static FundingRecord adaptAdjustment(PoloniexAdjustment a) {
FundingRecord.Type type = OTHER_INFLOW;
// There seems to be a spelling error in the returning reason. In case that ever gets
// corrected, this will still pick it up.
if (a.getReason().toLowerCase().contains("aidrop")
|| a.getReason().toLowerCase().contains("airdrop")) {
type = Type.AIRDROP;
}
// There could be other forms of adjustements, but it seems to be some kind of deposit.
return new FundingRecord(
null,
a.getTimestamp(),
Currency.getInstance(a.getCurrency()),
a.getAmount(),
null,
null,
type,
FundingRecord.Status.resolveStatus(a.getStatus()),
null,
null,
a.getCategory()
+ ":"
+ a.getReason()
+ "\n"
+ a.getAdjustmentTitle()
+ "\n"
+ a.getAdjustmentDesc()
+ "\n"
+ a.getAdjustmentHelp());
}
private static FundingRecord adaptDeposit(final PoloniexDeposit d) {
return new FundingRecord(
d.getAddress(),
d.getTimestamp(),
Currency.getInstance(d.getCurrency()),
d.getAmount(),
String.valueOf(d.getDepositNumber()),
d.getTxid(),
DEPOSIT,
FundingRecord.Status.resolveStatus(d.getStatus()),
null,
null,
d.getStatus());
}
private static FundingRecord adaptWithdrawal(final PoloniexWithdrawal w) {
final String[] statusParts = w.getStatus().split(": *");
final String statusStr = statusParts[0];
final FundingRecord.Status status = FundingRecord.Status.resolveStatus(statusStr);
final String externalId = statusParts.length == 1 ? null : statusParts[1];
// Poloniex returns the fee as an absolute value, that behaviour differs from UserTrades
final BigDecimal feeAmount = w.getFee();
return new FundingRecord(
w.getAddress(),
w.getTimestamp(),
Currency.getInstance(w.getCurrency()),
w.getAmount(),
String.valueOf(w.getWithdrawalNumber()),
externalId,
WITHDRAWAL,
status,
null,
feeAmount,
w.getStatus());
}
public static LimitOrder adaptUserTradesToOrderStatus(
String orderId, PoloniexUserTrade[] poloniexUserTrades) {
if (poloniexUserTrades.length == 0) return null;
OrderType orderType = null;
CurrencyPair currencyPair = null;
BigDecimal amount = new BigDecimal(0);
List<BigDecimal> weightedPrices = new ArrayList<>();
for (PoloniexUserTrade poloniexUserTrade : poloniexUserTrades) {
orderType =
poloniexUserTrade.getType().equals("buy")
? OrderType.BID
: OrderType.ASK; // what about others?
amount = amount.add(poloniexUserTrade.getAmount());
weightedPrices.add(poloniexUserTrade.getRate().multiply(poloniexUserTrade.getAmount()));
}
BigDecimal weightedAveragePrice =
weightedPrices.stream()
.reduce(new BigDecimal(0), BigDecimal::add)
.divide(amount, RoundingMode.HALF_UP);
return new LimitOrder(
orderType,
null,
currencyPair,
orderId,
null,
null,
weightedAveragePrice,
amount,
null,
Order.OrderStatus.UNKNOWN);
}
}
| mit |
craynafinal/libGDX_baby-trader | core/src/com/jsl/babytrader/Screens/GameScreen.java | 25236 | package com.jsl.babytrader.Screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.StringBuilder;
import com.badlogic.gdx.utils.Timer;
import com.jsl.babytrader.BabyTrader;
import com.jsl.babytrader.Controls.Configuration;
import com.jsl.babytrader.Data.Attribute;
import com.jsl.babytrader.Data.Baby;
import com.jsl.babytrader.Data.Customer;
import com.jsl.babytrader.Data.SharedData;
import com.jsl.babytrader.Popups.PopupPause;
import com.jsl.babytrader.Popups.PopupUpgrade;
import com.jsl.babytrader.Utilities.CommonUtilities;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Actual game screen for play.
*/
public class GameScreen extends BaseScreen {
// background graphic
private Texture sprite_background = new Texture("sprites/gameScreen_background_1024x576.png");
// buttons
private Texture sprite_button_browse_left = new Texture("sprites/gameScreen_browse_left_34x35.png");
private Texture sprite_button_browse_left_inv = new Texture("sprites/gameScreen_browse_left_inv_34x35.png");
private Texture sprite_button_browse_right = new Texture("sprites/gameScreen_browse_right_34x35.png");
private Texture sprite_button_browse_right_inv = new Texture("sprites/gameScreen_browse_right_inv_34x35.png");
private Texture sprite_button_menu = new Texture("sprites/gameScreen_menuButton_186x45.png");
private Texture sprite_button_menu_inv = new Texture("sprites/gameScreen_menuButton_inv_186x45.png");
private Texture sprite_button_promotion = new Texture("sprites/gameScreen_promotionButton_186x45.png");
private Texture sprite_button_promotion_inv = new Texture("sprites/gameScreen_promotionButton_inv_186x45.png");
private Texture sprite_button_research = new Texture("sprites/gameScreen_researchButton_186x45.png");
private Texture sprite_button_research_inv = new Texture("sprites/gameScreen_researchButton_inv_186x45.png");
private Texture sprite_button_upgrade = new Texture("sprites/gameScreen_upgradeButton_167x45.png");
private Texture sprite_button_upgrade_inv = new Texture("sprites/gameScreen_upgradeButton_inv_167x45.png");
private ImageButton button_browse_left = null;
private ImageButton button_browse_right = null;
private ImageButton button_menu = null;
private ImageButton button_promotion = null;
private ImageButton button_research = null;
private ImageButton button_upgrade_sell = null;
private ImageButton button_upgrade_buy = null;
private Label label_money = null;
private Label label_time = null;
private Label label_count_babies = null;
private Label label_count_customers_sell = null;
private Label label_count_customers_buy = null;
private Label label_properties_title_baby = null;
private Label label_properties_list_baby = null;
private Label label_properties_title_sell = null;
private Label label_properties_list_sell = null;
private Label label_properties_title_buy = null;
private Label label_properties_list_buy = null;
private Label label_level_sell = null;
private Label label_level_buy = null;
private Label label_sold = null;
private Label label_purchased = null;
// pause popup windows
private PopupPause popup_pause = null;
private Texture sprite_popup_paused = new Texture("sprites/popup_pause_305x240.png");
private Texture sprite_button_popup_continue = new Texture("sprites/popup_pause_button_continue_186x45.png");
private Texture sprite_button_popup_continue_inv = new Texture("sprites/popup_pause_button_continue_186x45.png");
private Texture sprite_button_popup_mainMenu = new Texture("sprites/popup_pause_button_mainMenu_186x45.png");
private Texture sprite_button_popup_mainMenu_inv = new Texture("sprites/popup_pause_button_mainMenu_inv_186x45.png");
private ImageButton button_popup_continue = null;
private ImageButton button_popup_mainMenu = null;
// upgrade popup windows
private PopupUpgrade popup_upgrade = null;
private Texture sprite_popup_upgrade = new Texture("sprites/popup_upgrade_background_525x390.png");
private Texture sprite_button_popup_cancel = new Texture("sprites/button_popup_cancel_186x45.png");
private Texture sprite_button_popup_cancel_inv = new Texture("sprites/button_popup_cancel_inv_186x45.png");
private Texture sprite_button_popup_upgrade = new Texture("sprites/button_popup_upgrade_186x45.png");
private Texture sprite_button_popup_upgrade_inv = new Texture("sprites/button_popup_upgrade_inv_186x45.png");
private ImageButton button_popup_cancel = null;
private ImageButton button_popup_upgrade = null;
// baby trader faces
private Texture sprite_babyTrader_face_normal = new Texture("sprites/babyTraderFaceUi_normal_163x190.png");
private Texture sprite_babyTrader_face_crazy = new Texture("sprites/babyTraderFaceUi_crazy_163x190.png");
// meta data
private int currentBabyIndex = 0;
public static final float COLOR_BG_RED_GAME = 0.3882f;
public static final float COLOR_BG_BLUE_GAME = 0.4392f;
public static final float COLOR_BG_GREEN_GAME = 0.4745f;
// configuration
private Configuration config = null;
public GameScreen(BabyTrader game) {
super(game);
config = new Configuration();
// bgm setup
setupMusic(getMusic(), true);
popupSetup();
labelSetup();
buttonSetup();
addElementsToStage(
button_browse_left,
button_browse_right,
button_menu,
button_promotion,
button_research,
button_upgrade_sell,
button_upgrade_buy,
label_money,
label_time,
label_count_babies,
label_count_customers_sell,
label_count_customers_buy,
label_properties_title_baby,
label_properties_list_baby,
label_properties_title_sell,
label_properties_list_sell,
label_properties_title_buy,
label_properties_list_buy,
label_level_sell,
label_level_buy,
popup_pause.getTable(),
popup_upgrade.getTable(),
label_sold,
label_purchased
);
// taking inputs from ui
Gdx.input.setInputProcessor(stage);
}
private String getMusic() {
List<String> musicList = new ArrayList<String>();
musicList.add("music/game_boukyaku_eq.mp3");
musicList.add("music/game_katarusis.mp3");
musicList.add("music/game_omoide_loft.mp3");
return musicList.get(CommonUtilities.getRandomInteger(0, musicList.size()));
}
private void popupSetup() {
// popup pause
popup_pause = new PopupPause(sprite_popup_paused);
button_popup_continue = generateButton(sprite_button_popup_continue, sprite_button_popup_continue_inv);
button_popup_continue.setPosition(0, 0);
button_popup_continue.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
sound_buttonClick.play();
popup_pause.getTable().setVisible(false);
resume();
}
});
button_popup_mainMenu = generateButton(sprite_button_popup_mainMenu, sprite_button_popup_mainMenu_inv);
button_popup_mainMenu.setPosition(0, 0);
button_popup_mainMenu.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
sound_buttonClick.play();
switchScreen(BabyTrader.initScreen);
}
});
popup_pause.addElements(button_popup_continue, button_popup_mainMenu);
// popup upgrade
popup_upgrade = new PopupUpgrade(
sprite_popup_upgrade,
getLabelStyle(FONT_WORK_EXTRA_BOLD, 29, Color.WHITE)
);
button_popup_cancel = generateButton(sprite_button_popup_cancel, sprite_button_popup_cancel_inv);
button_popup_cancel.setPosition(0, 0);
button_popup_cancel.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
sound_buttonClick.play();
resume();
popup_upgrade.setVisible(false);
}
});
button_popup_upgrade = generateButton(sprite_button_popup_upgrade, sprite_button_popup_upgrade_inv);
button_popup_upgrade.setPosition(0, 0);
button_popup_upgrade.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
sound_buttonClick.play();
upgrade();
}
});
popup_upgrade.addElements(button_popup_cancel, button_popup_upgrade);
}
private void upgrade() {
String warningMsg = "You don't have\nenough money to upgrade.".toUpperCase();
String type = popup_upgrade.getTextType();
if (type.equals(PopupUpgrade.TYPE_SELLER)) {
if (SharedData.getMoney() >= Configuration.getUpgradeCostSeller()) {
SharedData.spendMoney(Configuration.getUpgradeCostSeller());
config.levelUpSeller();
resume();
popup_upgrade.setVisible(false);
} else {
popup_upgrade.setTextDescription(warningMsg);
}
} else if (type.equals(PopupUpgrade.TYPE_BUYER)){
if (SharedData.getMoney() >= Configuration.getUpgradeCostBuyer()) {
SharedData.spendMoney(Configuration.getUpgradeCostBuyer());
config.levelUpBuyer();
resume();
popup_upgrade.setVisible(false);
} else {
popup_upgrade.setTextDescription(warningMsg);
}
} else if (type.equals(PopupUpgrade.TYPE_PROMOTION)) {
if (SharedData.getMoney() >= Configuration.getUpgradeCostPromotion()) {
SharedData.spendMoney(Configuration.getUpgradeCostPromotion());
config.levelUpPromotion();
resume();
popup_upgrade.setVisible(false);
} else {
popup_upgrade.setTextDescription(warningMsg);
}
} else if (type.equals(PopupUpgrade.TYPE_RESEARCH)) {
if (SharedData.getMoney() >= Configuration.getUpgradeCostResearch()) {
SharedData.spendMoney(Configuration.getUpgradeCostResearch());
config.levelUpResearch();
resume();
popup_upgrade.setVisible(false);
} else {
popup_upgrade.setTextDescription(warningMsg);
}
}
}
private void renderCustomer(Customer customer, Label label_title, Label label_properties, int x, int y, String description, boolean displaySprite, Label labelReplaceSprite) {
if (customer != null) {
if (displaySprite) {
labelReplaceSprite.setVisible(true);
} else {
labelReplaceSprite.setVisible(false);
stage.getBatch().draw(customer.getSprite(), x, y);
}
label_title.setText(customer.getName() + " (" + customer.getAge() + ")");
StringBuilder stringBuilder = new StringBuilder((customer.isMale() ? "His" : "Her") + " " + description + ":\n");
Set<Attribute> attributes = customer.isSelling() ? customer.getAttributes() : customer.getBaby().getAttributes();
for (Attribute attribute : attributes) {
stringBuilder.append(propertyFormat(attribute.getName()));
}
label_properties.setText(stringBuilder.toString().toUpperCase());
}
}
private void renderBaby() {
Baby baby = null;
synchronized (this) {
if (currentBabyIndex >= SharedData.getBabySize()) {
currentBabyIndex = SharedData.getBabySize() - 1;
} else if (currentBabyIndex < 0) {
currentBabyIndex = 0;
}
baby = SharedData.getBabyWithoutRemoval(currentBabyIndex);
}
if (baby != null) {
stage.getBatch().draw(baby.getSprite(), 484, 131);
label_properties_title_baby.setText(baby.getName().toUpperCase() + " (" + baby.getAge() + ") $" + baby.getSellPrice());
StringBuilder stringBuilder = new StringBuilder();
for (Attribute attribute : baby.getAttributes()) {
stringBuilder.append(propertyFormat(attribute.getName()));
}
label_properties_list_baby.setText(stringBuilder.toString().toUpperCase());
} else {
label_properties_title_baby.setText("");
label_properties_list_baby.setText("");
}
}
// returns an attribute in a formatted string
private static String propertyFormat(String attribute) {
return "• " + attribute + "\n";
}
@Override
public void render(float delta) {
// exit if game is over
if (SharedData.getMoney() <= 0 || config.isTimeOver()) {
switchScreen(BabyTrader.gameOverScreen);
}
clearingScreen(COLOR_BG_RED_GAME, COLOR_BG_BLUE_GAME, COLOR_BG_GREEN_GAME, COLOR_BG_ALPHA);
viewportRender();
// stage.draw() must appear before game batch
stage.act(Gdx.graphics.getDeltaTime());
stage.getBatch().begin();
stage.getBatch().draw(sprite_background, 0, 0);
stage.getBatch().draw(Configuration.isBabyTraderFaceNormal() ? sprite_babyTrader_face_normal : sprite_babyTrader_face_crazy, 831, 319);
// baby sprite
renderBaby();
// customer sprites
// this one should appear when customer is accepted by sales / purchase team
renderCustomer(SharedData.getCustomerSellingLatest(), label_properties_title_sell, label_properties_list_sell, 15, 306, "dream baby", Configuration.isSellerSold(), label_sold);
renderCustomer(SharedData.getCustomerBuyingLatest(), label_properties_title_buy, label_properties_list_buy, 15, 15, "baby for sale", Configuration.isBuyerPurchased(), label_purchased);
label_money.setText("$" + SharedData.getMoney());
label_time.setText(config.getTime());
label_count_babies.setText(SharedData.getBabySize() + "");
label_count_customers_sell.setText(SharedData.getCustomerSellingSize() + "");
label_count_customers_buy.setText(SharedData.getCustomerBuyingSize() + "");
label_level_sell.setText(Configuration.getLevelSeller() + "");
label_level_buy.setText(Configuration.getLevelBuyer() + "");
stage.getBatch().end();
stage.draw();
game.batch.begin();
game.batch.end();
}
private void buttonSetup() {
button_browse_left = generateButton(sprite_button_browse_left, sprite_button_browse_left_inv);
button_browse_left.setPosition(467, 528);
button_browse_left.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
Gdx.app.log("Clicking Browse Left button", "Activated");
currentBabyIndex--;
sound_buttonClick.play();
}
});
button_browse_right = generateButton(sprite_button_browse_right, sprite_button_browse_right_inv);
button_browse_right.setPosition(738, 528);
button_browse_right.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
Gdx.app.log("Clicking Browse Right button", "Activated");
currentBabyIndex++;
sound_buttonClick.play();
}
});
button_menu = generateButton(sprite_button_menu, sprite_button_menu_inv);
button_menu.setPosition(817, 14);
button_menu.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
Gdx.app.log("Clicking Menu button", "Activated");
sound_buttonClick.play();
pause();
popup_pause.setVisible(true);
}
});
button_promotion = generateButton(sprite_button_promotion, sprite_button_promotion_inv);
button_promotion.setPosition(817, 118);
button_promotion.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
Gdx.app.log("Clicking Promotion button", "Activated");
sound_buttonClick.play();
popupUpgradeOpen(PopupUpgrade.TYPE_PROMOTION, Configuration.getLevelPromotion(), Configuration.isNextMaxPromotion(), Configuration.getUpgradeCostPromotion(), PopupUpgrade.DESCRIPTION_PROMOTION);
}
});
button_research = generateButton(sprite_button_research, sprite_button_research_inv);
button_research.setPosition(817, 66);
button_research.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
Gdx.app.log("Clicking Research button", "Activated");
sound_buttonClick.play();
popupUpgradeOpen(PopupUpgrade.TYPE_RESEARCH, Configuration.getLevelResearch(), Configuration.isNextMaxResearch(), Configuration.getUpgradeCostResearch(), PopupUpgrade.DESCRIPTION_RESEARCH);
}
});
button_upgrade_sell = generateButton(sprite_button_upgrade, sprite_button_upgrade_inv);
button_upgrade_sell.setPosition(13, 484);
button_upgrade_sell.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
Gdx.app.log("Clicking Sell Upgrade button", "Activated");
sound_buttonClick.play();
popupUpgradeOpen(PopupUpgrade.TYPE_SELLER, Configuration.getLevelSeller(), Configuration.isNextMaxSeller(), Configuration.getUpgradeCostSeller(), PopupUpgrade.DESCRIPTION_SELLER);
}
});
button_upgrade_buy = generateButton(sprite_button_upgrade, sprite_button_upgrade_inv);
button_upgrade_buy.setPosition(13, 193);
button_upgrade_buy.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
Gdx.app.log("Clicking Buy Upgrade button", "Activated");
sound_buttonClick.play();
popupUpgradeOpen(PopupUpgrade.TYPE_BUYER, Configuration.getLevelBuyer(), Configuration.isNextMaxBuyer(), Configuration.getUpgradeCostBuyer(), PopupUpgrade.DESCRIPTION_BUYER);
}
});
}
private void popupUpgradeOpen(String type, int level, boolean isMax, int cost, String description) {
if (level != Configuration.MAX_LEVEL) {
pause();
popup_upgrade.setTextType(type);
popup_upgrade.setTextLevel(PopupUpgrade.getLevelText(level, level + 1, isMax));
popup_upgrade.setTextCost(PopupUpgrade.getMoneyText(cost));
popup_upgrade.setTextDescription(description);
popup_upgrade.setVisible(true);
}
}
private void labelSetup() {
label_money = new Label("", getLabelStyle(FONT_SARPANCH_SEMI_BOLD, 28, FONT_COLOR_GREEN));
label_money.setAlignment(Align.right);
label_money.setPosition(994, 190);
label_time = new Label("", getLabelStyle(FONT_SARPANCH_SEMI_BOLD, 28, FONT_COLOR_GREEN));
label_time.setAlignment(Align.right);
label_time.setPosition(994, 260);
label_count_babies = new Label("", getLabelStyle(FONT_WORK_EXTRA_BOLD, 43, FONT_COLOR_LIGHT_GRAY));
label_count_babies.setAlignment(Align.right);
label_count_babies.setPosition(607, 545);
label_count_customers_sell = new Label("", getLabelStyle(FONT_WORK_EXTRA_BOLD, 43, FONT_COLOR_LIGHT_GRAY));
label_count_customers_sell.setAlignment(Align.right);
label_count_customers_sell.setPosition(290, 502);
label_count_customers_buy = new Label("", getLabelStyle(FONT_WORK_EXTRA_BOLD, 43, FONT_COLOR_LIGHT_GRAY));
label_count_customers_buy.setAlignment(Align.right);
label_count_customers_buy.setPosition(290, 209);
label_properties_title_baby = new Label("", getLabelStyle(FONT_WORK_EXTRA_BOLD, 20, FONT_COLOR_LIGHT_GRAY));
label_properties_title_baby.setPosition(505, 113);
label_properties_list_baby = new Label("", getLabelStyle(FONT_WORK_EXTRA_BOLD, 14, FONT_COLOR_LIGHT_GRAY));
label_properties_list_baby.setPosition(505, 55);
label_properties_title_sell = new Label("", getLabelStyle(FONT_WORK_EXTRA_BOLD, 20, FONT_COLOR_LIGHT_GRAY));
label_properties_title_sell.setPosition(193, 418);
label_properties_list_sell = new Label("", getLabelStyle(FONT_WORK_EXTRA_BOLD, 14, FONT_COLOR_LIGHT_GRAY));
label_properties_list_sell.setPosition(193, 350);
label_properties_title_buy = new Label("", getLabelStyle(FONT_WORK_EXTRA_BOLD, 20, FONT_COLOR_LIGHT_GRAY));
label_properties_title_buy.setPosition(193, 127);
label_properties_list_buy = new Label("", getLabelStyle(FONT_WORK_EXTRA_BOLD, 14, FONT_COLOR_LIGHT_GRAY));
label_properties_list_buy.setPosition(193, 59);
label_level_sell = new Label("", getLabelStyle(FONT_WORK_EXTRA_BOLD, 15, Color.WHITE));
label_level_sell.setPosition(154, 549);
label_level_buy = new Label("", getLabelStyle(FONT_WORK_EXTRA_BOLD, 15, Color.WHITE));
label_level_buy.setPosition(154, 258);
label_sold = new Label("Sold!", getLabelStyle(FONT_WORK_EXTRA_BOLD, 30, FONT_COLOR_LIGHT_GRAY));
label_sold.setPosition(97 - label_sold.getWidth() / 2, 390);
label_sold.setVisible(false);
label_purchased = new Label("Purchased!", getLabelStyle(FONT_WORK_EXTRA_BOLD, 26, FONT_COLOR_LIGHT_GRAY));
label_purchased.setPosition(97 - label_purchased.getWidth() / 2, 99);
label_purchased.setVisible(false);
}
@Override
public void pause() {
Timer.instance().stop();
SharedData.pause();
setButtonDisabled(true);
}
@Override
public void resume() {
Timer.instance().start();
SharedData.resume();
setButtonDisabled(false);
}
private void setButtonDisabled(boolean isDisabled) {
button_browse_left.setDisabled(isDisabled);
button_browse_right.setDisabled(isDisabled);
button_menu.setDisabled(isDisabled);
button_promotion.setDisabled(isDisabled);
button_research.setDisabled(isDisabled);
button_upgrade_sell.setDisabled(isDisabled);
button_upgrade_buy.setDisabled(isDisabled);
}
@Override
public void hide() {
super.hide();
config.killThreads();
config.timerCancel();
// pick another random music
setupMusic(getMusic(), true);
}
@Override
public void show() {
super.show();
config.initialize();
config.timerSetup();
config.startThreadsAndTimer();
popup_pause.setVisible(false);
setButtonDisabled(false);
// in case when game stopped in the middle of sprite change
label_sold.setVisible(false);
label_purchased.setVisible(false);
}
@Override
public void dispose() {
super.dispose();
sprite_background.dispose();
sprite_button_browse_left.dispose();
sprite_button_browse_left_inv.dispose();
sprite_button_browse_right.dispose();
sprite_button_browse_right_inv.dispose();
sprite_button_menu.dispose();
sprite_button_menu_inv.dispose();
sprite_button_promotion.dispose();
sprite_button_promotion_inv.dispose();
sprite_button_research.dispose();
sprite_button_research_inv.dispose();
sprite_button_upgrade.dispose();
sprite_button_upgrade_inv.dispose();
sprite_popup_paused.dispose();
sprite_button_popup_continue.dispose();
sprite_button_popup_continue_inv.dispose();
sprite_button_popup_mainMenu.dispose();
sprite_button_popup_mainMenu_inv.dispose();
sprite_popup_upgrade.dispose();
sprite_button_popup_cancel.dispose();
sprite_button_popup_cancel_inv.dispose();
sprite_button_popup_upgrade.dispose();
sprite_button_popup_upgrade_inv.dispose();
sprite_babyTrader_face_normal.dispose();
sprite_babyTrader_face_crazy.dispose();
}
}
| mit |
aranega/featuretests | model-api/src/test/java/co/edu/uniandes/csw/model/tests/selenium/ShapeIT.java | 5820 | /*
The MIT License (MIT)
Copyright (c) 2015 Los Andes University
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package co.edu.uniandes.csw.model.tests.selenium;
import co.edu.uniandes.csw.model.dtos.minimum.ShapeDTO;
import co.edu.uniandes.csw.model.resources.ShapeResource;
import co.edu.uniandes.csw.model.tests.selenium.pages.shape.ShapeCreatePage;
import co.edu.uniandes.csw.model.tests.selenium.pages.shape.ShapeListPage;
import co.edu.uniandes.csw.model.tests.selenium.pages.LoginPage;
import co.edu.uniandes.csw.model.tests.selenium.pages.shape.ShapeDeletePage;
import co.edu.uniandes.csw.model.tests.selenium.pages.shape.ShapeDetailPage;
import co.edu.uniandes.csw.model.tests.selenium.pages.shape.ShapeEditPage;
import java.io.File;
import java.net.URL;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.graphene.page.InitialPage;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.GenericArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.importer.ExplodedImporter;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import uk.co.jemos.podam.api.PodamFactory;
import uk.co.jemos.podam.api.PodamFactoryImpl;
@RunWith(Arquillian.class)
public class ShapeIT {
private static PodamFactory factory = new PodamFactoryImpl();
@ArquillianResource
private URL deploymentURL;
@Drone
private WebDriver browser;
@Page
private ShapeCreatePage createPage;
@Page
private ShapeDetailPage detailPage;
@Page
private ShapeEditPage editPage;
@Page
private ShapeDeletePage deletePage;
@Deployment(testable = false)
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class)
// Se agrega las dependencias
.addAsLibraries(Maven.resolver().loadPomFromFile("pom.xml")
.importRuntimeDependencies().resolve()
.withTransitivity().asFile())
// Se agregan los compilados de los paquetes de servicios
.addPackage(ShapeResource.class.getPackage())
// El archivo que contiene la configuracion a la base de datos.
.addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml")
// El archivo beans.xml es necesario para injeccion de dependencias.
.addAsWebInfResource(new File("src/main/webapp/WEB-INF/beans.xml"))
// El archivo shiro.ini es necesario para injeccion de dependencias
.addAsWebInfResource(new File("src/main/webapp/WEB-INF/shiro.ini"))
// El archivo web.xml es necesario para el despliegue de los servlets
.setWebXML(new File("src/main/webapp/WEB-INF/web.xml"))
.merge(ShrinkWrap.create(GenericArchive.class).as(ExplodedImporter.class)
.importDirectory("src/main/webapp").as(GenericArchive.class), "/");
}
@Before
public void setup() {
browser.manage().window().maximize();
browser.get(deploymentURL.toExternalForm());
}
@Test
@InSequence(0)
public void login(@InitialPage LoginPage loginPage) {
browser.manage().deleteAllCookies();
loginPage.login();
}
@Test
@InSequence(1)
public void createShape(@InitialPage ShapeListPage listPage) {
Integer expected = 0;
Assert.assertEquals(expected, listPage.countShapes());
listPage.create();
ShapeDTO expected_shape = factory.manufacturePojo(ShapeDTO.class);
createPage.saveShape(expected_shape);
ShapeDTO actual_shape = detailPage.getData();
Assert.assertEquals(expected_shape.getName(), actual_shape.getName());
}
@Test
@InSequence(2)
public void editShape(@InitialPage ShapeListPage listPage) {
ShapeDTO expected_shape = factory.manufacturePojo(ShapeDTO.class);
listPage.editShape(0);
editPage.saveShape(expected_shape);
ShapeDTO actual_shape = detailPage.getData();
Assert.assertEquals(expected_shape.getName(), actual_shape.getName());
}
@Test
@InSequence(3)
public void deleteShape(@InitialPage ShapeListPage listPage) {
listPage.deleteShape(0);
deletePage.confirm();
Integer expected = 0;
Assert.assertEquals(expected, listPage.countShapes());
}
}
| mit |
james-ff/SEG_Android_Project | Worldly/src/com/worldly/swipe/SwipeListener.java | 3105 | package com.worldly.swipe;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
/**
* Abstract class that provides easy and straight forward implementation of swipe gestures in all four directions.
*
* @author Marek Matejka
*/
public abstract class SwipeListener extends SimpleOnGestureListener
{
private final int SWIPE_MAX_OFF_PATH = 200; //specifies by how many pixels the swipe can be off at max
private final int SWIPE_MIN_DISTANCE = 120; //defines the min distance of the swipe
private final int SWIPE_MAX_VELOCITY = 200; //defines the max (threshold) velocity of the swipe
/* (non-Javadoc)
* @see android.view.GestureDetector.SimpleOnGestureListener#onFling(android.view.MotionEvent, android.view.MotionEvent, float, float)
*/
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) //na tahu prstu po obrazovke
{
if (Math.abs(e1.getY() - e2.getY()) <= SWIPE_MAX_OFF_PATH) //if the swipe is not too far from Y axis
{
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_MAX_VELOCITY) //if the swipe is long and fast enough
return onRightToLeftSwipe();
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_MAX_VELOCITY) //if the swipe is long and fast enough
return onLeftToRightSwipe();
}
else if (Math.abs(e1.getX() - e2.getX()) <= SWIPE_MAX_OFF_PATH) //if the swipe is not too far from Y axis
{
if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_MAX_VELOCITY) //if the swipe is long and fast enough
return onBottomToTopSwipe();
else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_MAX_VELOCITY) //if the swipe is long and fast enough
return onTopToBottomSwipe();
}
return false; //else return FALSE
}
/**
* Method triggered when a swipe from left to right of the screen is identified.
* The swipe must meet basic parameters which are always adjusted to screen rotation.
*
* @return TRUE if action happened, FALSE if not.
*/
public abstract boolean onLeftToRightSwipe();
/**
* Method triggered when a swipe from right to left of the screen is identified.
* The swipe must meet basic parameters which are always adjusted to screen rotation.
*
* @return TRUE if action happened, FALSE if not.
*/
public abstract boolean onRightToLeftSwipe();
/**
* Method triggered when a swipe from bottom to top of the screen is identified.
* The swipe must meet basic parameters which are always adjusted to screen rotation.
*
* @return TRUE if action happened, FALSE if not.
*/
public abstract boolean onBottomToTopSwipe();
/**
* Method triggered when a swipe from top to bottom of the screen is identified.
* The swipe must meet basic parameters which are always adjusted to screen rotation.
*
* @return TRUE if action happened, FALSE if not.
*/
public abstract boolean onTopToBottomSwipe();
} | mit |
poetix/fluvius | fluvius-api/src/main/java/com/codepoetics/fluvius/api/description/package-info.java | 130 | /**
* Interfaces pertaining to describing and writing descriptions of Flows.
*/
package com.codepoetics.fluvius.api.description; | mit |
Azure/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/network/generated/PrivateLinkServicesListAutoApprovedPrivateLinkServicesSamples.java | 1180 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.generated;
import com.azure.core.util.Context;
/** Samples for PrivateLinkServices ListAutoApprovedPrivateLinkServices. */
public final class PrivateLinkServicesListAutoApprovedPrivateLinkServicesSamples {
/*
* x-ms-original-file: specification/network/resource-manager/Microsoft.Network/stable/2021-05-01/examples/AutoApprovedPrivateLinkServicesGet.json
*/
/**
* Sample code: Get list of private link service id that can be linked to a private end point with auto approved.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void getListOfPrivateLinkServiceIdThatCanBeLinkedToAPrivateEndPointWithAutoApproved(
com.azure.resourcemanager.AzureResourceManager azure) {
azure
.networks()
.manager()
.serviceClient()
.getPrivateLinkServices()
.listAutoApprovedPrivateLinkServices("regionName", Context.NONE);
}
}
| mit |
BACMiao/Train | src/main/java/com/bapocalypse/train/util/UUIDGenerator.java | 531 | package com.bapocalypse.train.util;
import java.util.UUID;
/**
* @package: com.bapocalypse.train.util
* @Author: 陈淼
* @Date: 2016/11/21
* @Description: uuid的生成的工具类
*/
public class UUIDGenerator {
public UUIDGenerator() {}
public static String getUUID() {
UUID uuid = UUID.randomUUID();
String str = uuid.toString();
return str.substring(0, 8) + str.substring(9, 13) +
str.substring(14, 18) + str.substring(19, 23) +
str.substring(24);
}
}
| mit |
ljtfreitas/java-restify | java-restify-http-client-jersey/src/test/java/com/github/ljtfreitas/restify/http/client/request/jersey/JerseyRxObservableHttpClientEndpointRequestExecutorTest.java | 7046 | package com.github.ljtfreitas.restify.http.client.request.jersey;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import static org.mockserver.model.JsonBody.json;
import static org.mockserver.model.StringBody.exact;
import static org.mockserver.verify.VerificationTimes.once;
import java.net.URI;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockserver.client.server.MockServerClient;
import org.mockserver.junit.MockServerRule;
import org.mockserver.model.HttpRequest;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.ljtfreitas.restify.http.client.message.Header;
import com.github.ljtfreitas.restify.http.client.message.Headers;
import com.github.ljtfreitas.restify.http.client.request.EndpointRequest;
import com.github.ljtfreitas.restify.http.client.response.EndpointResponse;
import com.github.ljtfreitas.restify.http.client.response.EndpointResponseException;
public class JerseyRxObservableHttpClientEndpointRequestExecutorTest {
@Rule
public MockServerRule mockServerRule = new MockServerRule(this, 7080);
@Rule
public ExpectedException expectedException = ExpectedException.none();
private JerseyRxObservableHttpClientEndpointRequestExecutor executor;
private MockServerClient mockServerClient;
@Before
public void setup() {
mockServerClient = new MockServerClient("localhost", 7080);
executor = new JerseyRxObservableHttpClientEndpointRequestExecutor();
}
@Test
public void shouldSendGetRequestOnJsonFormat() {
mockServerClient
.when(request()
.withMethod("GET")
.withPath("/json"))
.respond(response()
.withStatusCode(200)
.withHeader("Content-Type", "application/json")
.withBody(json("{\"name\": \"Tiago de Freitas Lima\",\"age\":31}")));
EndpointRequest endpointRequest = new EndpointRequest(URI.create("http://localhost:7080/json"), "GET", MyModel.class);
EndpointResponse<MyModel> myModelResponse = executor.<MyModel> executeAsync(endpointRequest)
.toCompletableFuture().join();
assertTrue(myModelResponse.status().isOk());
MyModel myModel = myModelResponse.body();
assertEquals("Tiago de Freitas Lima", myModel.name);
assertEquals(31, myModel.age);
}
@Test
public void shouldSendPostRequestOnJsonFormat() {
HttpRequest httpRequest = request()
.withMethod("POST")
.withPath("/json")
.withHeader("Content-Type", "application/json")
.withBody(json("{\"name\":\"Tiago de Freitas Lima\",\"age\":31}"));
mockServerClient
.when(httpRequest)
.respond(response()
.withStatusCode(201)
.withHeader("Content-Type", "text/plain")
.withBody(exact("OK")));
MyModel myModel = new MyModel("Tiago de Freitas Lima", 31);
Headers headers = new Headers()
.add(new Header("Content-Type", "application/json"));
EndpointRequest endpointRequest = new EndpointRequest(URI.create("http://localhost:7080/json"), "POST", headers,
myModel, String.class);
EndpointResponse<String> myModelResponse = executor.<String> executeAsync(endpointRequest)
.toCompletableFuture()
.join();
assertTrue(myModelResponse.status().isCreated());
assertEquals("OK", myModelResponse.body());
mockServerClient.verify(httpRequest, once());
}
@Test
public void shouldSendGetRequestOnXmlFormat() {
mockServerClient
.when(request()
.withMethod("GET")
.withPath("/xml"))
.respond(response()
.withStatusCode(200)
.withHeader("Content-Type", "application/xml")
.withBody(exact("<model><name>Tiago de Freitas Lima</name><age>31</age></model>")));
EndpointRequest endpointRequest = new EndpointRequest(URI.create("http://localhost:7080/xml"), "GET", MyModel.class);
EndpointResponse<MyModel> myModelResponse = executor.<MyModel> executeAsync(endpointRequest)
.toCompletableFuture()
.join();
assertTrue(myModelResponse.status().isOk());
MyModel myModel = myModelResponse.body();
assertEquals("Tiago de Freitas Lima", myModel.name);
assertEquals(31, myModel.age);
}
@Test
public void shouldSendPostRequestOnXmlFormat() {
HttpRequest httpRequest = request()
.withMethod("POST")
.withPath("/xml")
.withHeader("Content-Type", "application/xml")
.withBody(exact("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><model><name>Tiago de Freitas Lima</name><age>31</age></model>"));
mockServerClient
.when(httpRequest)
.respond(response()
.withStatusCode(201)
.withHeader("Content-Type", "text/plain")
.withBody(exact("OK")));
MyModel myModel = new MyModel("Tiago de Freitas Lima", 31);
Headers headers = new Headers()
.add(new Header("Content-Type", "application/xml"));
EndpointRequest endpointRequest = new EndpointRequest(URI.create("http://localhost:7080/xml"), "POST", headers,
myModel, String.class);
EndpointResponse<String> myModelResponse = executor.<String> executeAsync(endpointRequest)
.toCompletableFuture()
.join();
assertTrue(myModelResponse.status().isCreated());
assertEquals("OK", myModelResponse.body());
mockServerClient.verify(httpRequest, once());
}
@Test
public void shouldReadServerErrorResponse() {
mockServerClient
.when(request()
.withMethod("GET")
.withPath("/json"))
.respond(response()
.withStatusCode(500));
EndpointRequest endpointRequest = new EndpointRequest(URI.create("http://localhost:7080/json"), "GET", MyModel.class);
EndpointResponse<Object> endpointResponse = executor.executeAsync(endpointRequest)
.exceptionally(e -> EndpointResponse.error((EndpointResponseException) e))
.toCompletableFuture()
.join();
assertThat(endpointResponse.status().isInternalServerError(), is(true));
}
@Test
public void shouldReturnNullBodyWhenResponseIsNotFound() {
mockServerClient
.when(request()
.withMethod("GET")
.withPath("/json"))
.respond(response()
.withStatusCode(404));
EndpointRequest endpointRequest = new EndpointRequest(URI.create("http://localhost:7080/json"), "GET", MyModel.class);
EndpointResponse<Object> endpointResponse = executor.<Object> executeAsync(endpointRequest)
.toCompletableFuture()
.join();
assertTrue(endpointResponse.status().isNotFound());
assertNull(endpointResponse.body());
}
@XmlRootElement(name = "model")
@XmlAccessorType(XmlAccessType.FIELD)
public static class MyModel {
@JsonProperty
String name;
@JsonProperty
int age;
public MyModel() {
}
public MyModel(@JsonProperty String name, @JsonProperty int age) {
this.name = name;
this.age = age;
}
}
}
| mit |
AndreasArvidsson/Rest-App | src/main/java/com/andreas/restapp/domain/FileMeta.java | 2343 | package com.andreas.restapp.domain;
import static javax.persistence.GenerationType.IDENTITY;
import java.io.Serializable;
import java.util.Date;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.ws.rs.core.MultivaluedMap;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import com.andreas.restapp.domain.base.BaseDomainEntity;
/**
* @author Andreas Arvidsson
*
*
*/
@Entity
@Table(name = "files")
public class FileMeta extends BaseDomainEntity implements Serializable {
@Id
@NotNull
@GeneratedValue(strategy = IDENTITY)
private long id;
@NotNull
@Column(unique = true)
private String uuid;
@NotNull
@Column(name = "file_name")
private String fileName;
@NotNull
@Column(name = "mime_type")
private String mimeType;
@NotNull
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "time_stamp")
private Date timestamp;
public FileMeta() {
}
public FileMeta(InputPart inputPart) throws Exception {
fileName = getFileName(inputPart);
mimeType = inputPart.getMediaType().toString();
uuid = UUID.randomUUID().toString();
timestamp = new Date();
}
@Override
public long getId() {
return id;
}
public String getUuid() {
return uuid;
}
public Date getTimestamp() {
return timestamp;
}
public String getFileName() {
return fileName;
}
public String getMimeType() {
return mimeType;
}
private String getFileName(InputPart inputPart) throws Exception {
MultivaluedMap<String, String> headers = inputPart.getHeaders();
String[] contentDispositionHeader = headers.getFirst("Content-Disposition").split(";");
for (String name : contentDispositionHeader) {
if ((name.trim().startsWith("filename"))) {
String[] tmp = name.split("=");
return tmp[1].trim().replaceAll("\"", "");
}
}
throw new Exception("Can't extract file name from input part");
}
}
| mit |
matthewfcarlson/Melay | app/android/app/src/main/java/com/melay/sync/SyncLog.java | 1471 | package com.melay.sync;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
/**
* Created by matth on 2/15/2018.
*/
public class SyncLog {
private static BufferedWriter out;
private static BufferedWriter createFileOnDevice(Boolean append) throws IOException {
/*
* Function to initially create the log file and it also writes the time of creation to file.
*/
File Root = Environment.getExternalStorageDirectory();
if(Root.canWrite()){
File LogFile = new File(Root, "SyncLog.txt");
FileWriter LogWriter = new FileWriter(LogFile, append);
out = new BufferedWriter(LogWriter);
Date date = new Date();
out.write("Logged at" + String.valueOf(date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "\n"));
return out;
}
return null;
}
public static void write(String TAG, String message) {
try {
BufferedWriter out = createFileOnDevice(true);
out.write(message + "\n");
Log.i(TAG, "ArchivingService started!");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void write(String message) {
write("SYNCLOG",message);
}
}
| mit |
iseki-masaya/spongycastle | prov/src/main/jdk1.3/org/spongycastle/jcajce/provider/asymmetric/x509/X509CRLObject.java | 17121 | package org.spongycastle.jcajce.provider.asymmetric.x509;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Principal;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.CRLException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509CRL;
import java.security.cert.X509CRLEntry;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.spongycastle.asn1.ASN1Encodable;
import org.spongycastle.asn1.ASN1Encoding;
import org.spongycastle.asn1.ASN1InputStream;
import org.spongycastle.asn1.ASN1ObjectIdentifier;
import org.spongycastle.asn1.ASN1Integer;
import org.spongycastle.asn1.util.ASN1Dump;
import org.spongycastle.asn1.x500.X500Name;
import org.spongycastle.asn1.x509.CRLDistPoint;
import org.spongycastle.asn1.x509.CRLNumber;
import org.spongycastle.asn1.x509.CertificateList;
import org.spongycastle.asn1.x509.Extension;
import org.spongycastle.asn1.x509.Extensions;
import org.spongycastle.asn1.x509.GeneralNames;
import org.spongycastle.asn1.x509.IssuingDistributionPoint;
import org.spongycastle.asn1.x509.TBSCertList;
import org.spongycastle.jce.X509Principal;
import org.spongycastle.jce.provider.RFC3280CertPathUtilities;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.spongycastle.util.encoders.Hex;
import org.spongycastle.x509.extension.X509ExtensionUtil;
/**
* The following extensions are listed in RFC 2459 as relevant to CRLs
*
* Authority Key Identifier
* Issuer Alternative Name
* CRL Number
* Delta CRL Indicator (critical)
* Issuing Distribution Point (critical)
*/
class X509CRLObject
extends X509CRL
{
private CertificateList c;
private String sigAlgName;
private byte[] sigAlgParams;
private boolean isIndirect;
static boolean isIndirectCRL(X509CRL crl)
throws CRLException
{
try
{
byte[] idp = crl.getExtensionValue(Extension.issuingDistributionPoint.getId());
return idp != null
&& IssuingDistributionPoint.getInstance(X509ExtensionUtil.fromExtensionValue(idp)).isIndirectCRL();
}
catch (Exception e)
{
throw new ExtCRLException(
"Exception reading IssuingDistributionPoint", e);
}
}
public X509CRLObject(
CertificateList c)
throws CRLException
{
this.c = c;
try
{
this.sigAlgName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm());
if (c.getSignatureAlgorithm().getParameters() != null)
{
this.sigAlgParams = ((ASN1Encodable)c.getSignatureAlgorithm().getParameters()).toASN1Primitive().getEncoded(ASN1Encoding.DER);
}
else
{
this.sigAlgParams = null;
}
this.isIndirect = isIndirectCRL(this);
}
catch (Exception e)
{
throw new CRLException("CRL contents invalid: " + e);
}
}
/**
* Will return true if any extensions are present and marked
* as critical as we currently dont handle any extensions!
*/
public boolean hasUnsupportedCriticalExtension()
{
Set extns = getCriticalExtensionOIDs();
if (extns == null)
{
return false;
}
extns.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
extns.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
return !extns.isEmpty();
}
private Set getExtensionOIDs(boolean critical)
{
if (this.getVersion() == 2)
{
Extensions extensions = c.getTBSCertList().getExtensions();
if (extensions != null)
{
Set set = new HashSet();
Enumeration e = extensions.oids();
while (e.hasMoreElements())
{
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement();
Extension ext = extensions.getExtension(oid);
if (critical == ext.isCritical())
{
set.add(oid.getId());
}
}
return set;
}
}
return null;
}
public Set getCriticalExtensionOIDs()
{
return getExtensionOIDs(true);
}
public Set getNonCriticalExtensionOIDs()
{
return getExtensionOIDs(false);
}
public byte[] getExtensionValue(String oid)
{
Extensions exts = c.getTBSCertList().getExtensions();
if (exts != null)
{
Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid));
if (ext != null)
{
try
{
return ext.getExtnValue().getEncoded();
}
catch (Exception e)
{
throw new IllegalStateException("error parsing " + e.toString());
}
}
}
return null;
}
public byte[] getEncoded()
throws CRLException
{
try
{
return c.getEncoded(ASN1Encoding.DER);
}
catch (IOException e)
{
throw new CRLException(e.toString());
}
}
public void verify(PublicKey key)
throws CRLException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException, SignatureException
{
verify(key, BouncyCastleProvider.PROVIDER_NAME);
}
public void verify(PublicKey key, String sigProvider)
throws CRLException, NoSuchAlgorithmException,
InvalidKeyException, NoSuchProviderException, SignatureException
{
if (!c.getSignatureAlgorithm().equals(c.getTBSCertList().getSignature()))
{
throw new CRLException("Signature algorithm on CertificateList does not match TBSCertList.");
}
Signature sig;
if (sigProvider != null)
{
sig = Signature.getInstance(getSigAlgName(), sigProvider);
}
else
{
sig = Signature.getInstance(getSigAlgName());
}
sig.initVerify(key);
sig.update(this.getTBSCertList());
if (!sig.verify(this.getSignature()))
{
throw new SignatureException("CRL does not verify with supplied public key.");
}
}
public int getVersion()
{
return c.getVersionNumber();
}
public Principal getIssuerDN()
{
return new X509Principal(X500Name.getInstance(c.getIssuer().toASN1Primitive()));
}
public Date getThisUpdate()
{
return c.getThisUpdate().getDate();
}
public Date getNextUpdate()
{
if (c.getNextUpdate() != null)
{
return c.getNextUpdate().getDate();
}
return null;
}
private Set loadCRLEntries()
{
Set entrySet = new HashSet();
Enumeration certs = c.getRevokedCertificateEnumeration();
X500Name previousCertificateIssuer = c.getIssuer();
while (certs.hasMoreElements())
{
TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement();
X509CRLEntryObject crlEntry = new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer);
entrySet.add(crlEntry);
if (isIndirect && entry.hasExtensions())
{
Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer);
if (currentCaName != null)
{
previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName());
}
}
}
return entrySet;
}
public X509CRLEntry getRevokedCertificate(BigInteger serialNumber)
{
Enumeration certs = c.getRevokedCertificateEnumeration();
X500Name previousCertificateIssuer = c.getIssuer();
while (certs.hasMoreElements())
{
TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement();
if (serialNumber.equals(entry.getUserCertificate().getValue()))
{
return new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer);
}
if (isIndirect && entry.hasExtensions())
{
Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer);
if (currentCaName != null)
{
previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName());
}
}
}
return null;
}
public Set getRevokedCertificates()
{
Set entrySet = loadCRLEntries();
if (!entrySet.isEmpty())
{
return Collections.unmodifiableSet(entrySet);
}
return null;
}
public byte[] getTBSCertList()
throws CRLException
{
try
{
return c.getTBSCertList().getEncoded("DER");
}
catch (IOException e)
{
throw new CRLException(e.toString());
}
}
public byte[] getSignature()
{
return c.getSignature().getBytes();
}
public String getSigAlgName()
{
return sigAlgName;
}
public String getSigAlgOID()
{
return c.getSignatureAlgorithm().getAlgorithm().getId();
}
public byte[] getSigAlgParams()
{
if (sigAlgParams != null)
{
byte[] tmp = new byte[sigAlgParams.length];
System.arraycopy(sigAlgParams, 0, tmp, 0, tmp.length);
return tmp;
}
return null;
}
/**
* Returns a string representation of this CRL.
*
* @return a string representation of this CRL.
*/
public String toString()
{
StringBuffer buf = new StringBuffer();
String nl = System.getProperty("line.separator");
buf.append(" Version: ").append(this.getVersion()).append(
nl);
buf.append(" IssuerDN: ").append(this.getIssuerDN())
.append(nl);
buf.append(" This update: ").append(this.getThisUpdate())
.append(nl);
buf.append(" Next update: ").append(this.getNextUpdate())
.append(nl);
buf.append(" Signature Algorithm: ").append(this.getSigAlgName())
.append(nl);
byte[] sig = this.getSignature();
buf.append(" Signature: ").append(
new String(Hex.encode(sig, 0, 20))).append(nl);
for (int i = 20; i < sig.length; i += 20)
{
if (i < sig.length - 20)
{
buf.append(" ").append(
new String(Hex.encode(sig, i, 20))).append(nl);
}
else
{
buf.append(" ").append(
new String(Hex.encode(sig, i, sig.length - i))).append(nl);
}
}
Extensions extensions = c.getTBSCertList().getExtensions();
if (extensions != null)
{
Enumeration e = extensions.oids();
if (e.hasMoreElements())
{
buf.append(" Extensions: ").append(nl);
}
while (e.hasMoreElements())
{
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
Extension ext = extensions.getExtension(oid);
if (ext.getExtnValue() != null)
{
byte[] octs = ext.getExtnValue().getOctets();
ASN1InputStream dIn = new ASN1InputStream(octs);
buf.append(" critical(").append(
ext.isCritical()).append(") ");
try
{
if (oid.equals(Extension.cRLNumber))
{
buf.append(
new CRLNumber(ASN1Integer.getInstance(
dIn.readObject()).getPositiveValue()))
.append(nl);
}
else if (oid.equals(Extension.deltaCRLIndicator))
{
buf.append(
"Base CRL: "
+ new CRLNumber(ASN1Integer.getInstance(
dIn.readObject()).getPositiveValue()))
.append(nl);
}
else if (oid
.equals(Extension.issuingDistributionPoint))
{
buf.append(
IssuingDistributionPoint.getInstance(dIn.readObject())).append(nl);
}
else if (oid
.equals(Extension.cRLDistributionPoints))
{
buf.append(
CRLDistPoint.getInstance(dIn.readObject())).append(nl);
}
else if (oid.equals(Extension.freshestCRL))
{
buf.append(
CRLDistPoint.getInstance(dIn.readObject())).append(nl);
}
else
{
buf.append(oid.getId());
buf.append(" value = ").append(
ASN1Dump.dumpAsString(dIn.readObject()))
.append(nl);
}
}
catch (Exception ex)
{
buf.append(oid.getId());
buf.append(" value = ").append("*****").append(nl);
}
}
else
{
buf.append(nl);
}
}
}
Set set = getRevokedCertificates();
if (set != null)
{
Iterator it = set.iterator();
while (it.hasNext())
{
buf.append(it.next());
buf.append(nl);
}
}
return buf.toString();
}
/**
* Checks whether the given certificate is on this CRL.
*
* @param cert the certificate to check for.
* @return true if the given certificate is on this CRL,
* false otherwise.
*/
public boolean isRevoked(Certificate cert)
{
if (!cert.getType().equals("X.509"))
{
throw new RuntimeException("X.509 CRL used with non X.509 Cert");
}
TBSCertList.CRLEntry[] certs = c.getRevokedCertificates();
X500Name caName = c.getIssuer();
if (certs != null)
{
BigInteger serial = ((X509Certificate)cert).getSerialNumber();
for (int i = 0; i < certs.length; i++)
{
if (isIndirect && certs[i].hasExtensions())
{
Extension currentCaName = certs[i].getExtensions().getExtension(Extension.certificateIssuer);
if (currentCaName != null)
{
caName = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName());
}
}
if (certs[i].getUserCertificate().getValue().equals(serial))
{
X500Name issuer;
try
{
issuer = org.spongycastle.asn1.x509.Certificate.getInstance(cert.getEncoded()).getIssuer();
}
catch (CertificateEncodingException e)
{
throw new RuntimeException("Cannot process certificate");
}
if (!caName.equals(issuer))
{
return false;
}
return true;
}
}
}
return false;
}
}
| mit |
hosaka893/junit-tutorial | src/main/java/junit/tutorial/book/Author.java | 495 | // Copyright(c) 2013 GROWTH XPARTNERS, Incorporated.
//
//
package junit.tutorial.book;
public class Author {
private String firstName;
private String lastName;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
| mit |
Blunderchips/Dwarf2D | src/dwarf/system.java | 4400 | package dwarf;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Provides an interface to your system (sys) and other system base utilities.
*
* @author Matthew 'siD' Van der Bijl
*/
public final class system {
/**
* you can not instantiate this class.
*/
public system() throws UnsupportedOperationException {
// Prevents instantiation of this class.
throw new UnsupportedOperationException(
"you can not instantiate this class.");
}
/**
* @return Operating system version
*/
public static String getOSVersion() {
return System.getProperty("os.version");
}
/**
* @return Operating system name
*/
public static String getOSName() {
return System.getProperty("os.name");
}
/**
* @return Operating system architecture
*/
public static String getOSArch() {
return System.getProperty("os.arch");
}
/**
* @return JRE version number
*/
public static String getJavaVersion() {
return System.getProperty("java.version");
}
/**
* @return JRE vendor URL
*/
public static String getJavaVenderUrl() {
return System.getProperty("java.vendor.url");
}
/**
* @return User account name
*/
public static String getUserName() {
return System.getProperty("user.name");
}
/**
* @return User working directory
*/
public static String getUserDir() {
return System.getProperty("user.dir");
}
/**
* @return Sequence used by operating system to separate lines in text
* files.
*/
public static String getLineSeparator() {
return System.getProperty("line.separator");
}
/**
* @return JRE vendor name
*/
public static String getJavaVender() {
return System.getProperty("java.vendor");
}
/**
* @return Installation directory for Java Runtime Environment (JRE).
*/
public static String getJavaHome() {
return System.getProperty("java.home");
}
/**
* @return Path used to find directories and JAR archives containing class
* files. Elements of the class path are separated by a platform-specific
* character specified in the path.separator property.
*/
public static String getJavaClassPath() {
return System.getProperty("java.class.path");
}
/**
* @return Character that separates components of a file path. This is "/"
* on UNIX and "\" on Windows.
*/
public static String getFileSeparator() {
return System.getProperty("file.separator");
}
/**
* Total number of processors or cores available to the JVM.
*
* @return Available processors (cores)
*/
public static int getAvailableProcessors() {
return Runtime.getRuntime().availableProcessors();
}
/**
* Total amount of free memory available to the JVM.
*
* @return Free memory (bytes)
*/
public static long getFreeMemory() {
return Runtime.getRuntime().freeMemory();
}
/**
* Total memory currently available to the JVM.
*
* @return Total memory available to JVM (bytes)
*/
public static long getTotalMemory() {
return Runtime.getRuntime().totalMemory();
}
/**
* @return The Name of JIT.
*/
public static String getJavaCompiler() {
return System.getProperty("java.compiler");
}
public static String executeCommand(String command) throws DwarfException {
StringBuilder output = new StringBuilder();
Process p = null;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
} catch (IOException | InterruptedException ex) {
throw new DwarfException(ex);
}
return output.toString();
}
/**
* @return the version of the Lightweight Java Game Library (LWJGL) in use.
*/
public static String getLWJGLVersion() {
return org.lwjgl.Sys.getVersion();
}
}
| mit |
ssauermann/BlockAPI | src/main/java/com/tree_bit/rcdl/blocks/Axis.java | 1475 | package com.tree_bit.rcdl.blocks;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.EnumSet;
import java.util.Set;
/**
* Axes of the three dimensional World.
*
* <ul>
* <li>x-Axis (longitude - 'east-west')</li>
* <li>y-Axis (elevation - 'height')</li>
* <li>z-Axis (latitude - 'south-north'</li>
* </ul>
*
*/
public enum Axis {
/** x-Axis (longitude - 'east-west') */
X,
/** y-Axis (elevation - 'height') */
Y,
/** z-Axis (latitude - 'south-north' */
Z;
/**
* Creates a EnumSet with the two given axes representing a plain in the
* coordinate system.
*
* @param a First axis
* @param b Second axis (mustn't be identical with the first one)
* @return Plain spanned by the two given axes.
*/
// Checked by Guava
@SuppressWarnings("null")
public static EnumSet<Axis> plain(final Axis a, final Axis b) {
if (a == b) {
throw new IllegalArgumentException("The two axes mustn't be identical: " + a);
}
return checkNotNull(EnumSet.of(a, b));
}
/**
* Checks a plain for validity.
*
* @param plain Plain to check
* @return Given plain
*/
public static Set<Axis> checkPlain(final Set<Axis> plain) {
if (plain.size() != 2) {
throw new IllegalArgumentException("A plain has to have exactly two distinct axes. Not: " + plain.size());
}
return plain;
}
}
| mit |
tobiasdiez/jabref | src/test/java/org/jabref/logic/layout/format/AuthorLF_FFTest.java | 546 | package org.jabref.logic.layout.format;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class AuthorLF_FFTest {
/**
* Test method for
* {@link org.jabref.logic.layout.format.AuthorLF_FF#format(java.lang.String)}.
*/
@Test
public void testFormat() {
assertEquals("von Neumann, John and John Smith and Peter Black Brown, Jr",
new AuthorLF_FF()
.format("von Neumann,,John and John Smith and Black Brown, Jr, Peter"));
}
}
| mit |
fieldenms/tg | platform-pojo-bl/src/test/java/ua/com/fielden/platform/reflection/asm/impl/DynamicEntityTypeMixedAndRepetitiveModificationTest.java | 6635 | package ua.com.fielden.platform.reflection.asm.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static ua.com.fielden.platform.reflection.asm.impl.DynamicTypeNamingService.APPENDIX;
import java.lang.reflect.Field;
import org.junit.Before;
import org.junit.Test;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.annotation.Calculated;
import ua.com.fielden.platform.entity.annotation.factory.CalculatedAnnotation;
import ua.com.fielden.platform.reflection.Finder;
import ua.com.fielden.platform.reflection.asm.api.NewProperty;
import ua.com.fielden.platform.reflection.asm.impl.entities.EntityBeingEnhanced;
import ua.com.fielden.platform.reflection.asm.impl.entities.EntityBeingModified;
import ua.com.fielden.platform.reflection.asm.impl.entities.TopLevelEntity;
import ua.com.fielden.platform.types.Money;
/**
* A test case to ensure correct dynamic property modification for existing entity types with the modification and enhancement applied multiple times.
*
* @author TG Team
*
*/
public class DynamicEntityTypeMixedAndRepetitiveModificationTest {
private static final String NEW_PROPERTY_DESC = "Description for new money property";
private static final String NEW_PROPERTY_TITLE = "New money property";
private static final String NEW_PROPERTY_EXPRESSION = "2 * 3 - [integerProp]";
private static final String NEW_PROPERTY = "newProperty";
private DynamicEntityClassLoader cl;
private final Calculated calculated = new CalculatedAnnotation().contextualExpression(NEW_PROPERTY_EXPRESSION).newInstance();
private final NewProperty pd1 = new NewProperty(NEW_PROPERTY, Money.class, false, NEW_PROPERTY_TITLE, NEW_PROPERTY_DESC, calculated);
private final NewProperty pd2 = new NewProperty(NEW_PROPERTY + 1, Money.class, false, NEW_PROPERTY_TITLE, NEW_PROPERTY_DESC, calculated);
@Before
public void setUp() {
cl = DynamicEntityClassLoader.getInstance(ClassLoader.getSystemClassLoader());
}
@Test
public void test_complex_class_loading_with_multiple_repetative_enhancements() throws Exception {
// first enhancement
// get the enhanced EntityBeingEnhanced type
final Class<?> oneTimeEnhancedType = cl.startModification(EntityBeingEnhanced.class).addProperties(pd1).endModification();
// second enhancement
// get the enhanced EntityBeingEnhanced type
final Class<?> twoTimesEnhancedType = cl.startModification(oneTimeEnhancedType).addProperties(pd2).endModification();
assertTrue("Incorrect name.", oneTimeEnhancedType.getName().startsWith(EntityBeingEnhanced.class.getName() + APPENDIX + "_"));
assertEquals("Incorrect parent.", AbstractEntity.class, oneTimeEnhancedType.getSuperclass());
assertTrue("Incorrect name.", twoTimesEnhancedType.getName().startsWith(EntityBeingEnhanced.class.getName() + APPENDIX + "_"));
assertEquals("Incorrect parent.", AbstractEntity.class, twoTimesEnhancedType.getSuperclass());
final Field field1 = Finder.findFieldByName(twoTimesEnhancedType, NEW_PROPERTY);
assertNotNull("Property should exist.", field1);
final Field field2 = Finder.findFieldByName(twoTimesEnhancedType, NEW_PROPERTY + 1);
assertNotNull("Property should exist.", field2);
}
@Test
public void test_sequential_multiple_enhancements_and_modification() throws Exception {
// get the enhanced EntityBeingEnhanced type
final Class<?> entityBeingEnhancedEnhancedType = //
cl.startModification(EntityBeingEnhanced.class).//
addProperties(pd1).//
addProperties(pd2).//
endModification();
assertTrue("Incorrect property type.", entityBeingEnhancedEnhancedType.getName().startsWith(EntityBeingEnhanced.class.getName() + DynamicTypeNamingService.APPENDIX + "_"));
// get the modified and enhanced EntityBeingModified type
final Class<?> entityBeingModifiedModifiedType = //
cl.startModification(EntityBeingModified.class).//
addProperties(pd1).//
modifyProperties(NewProperty.changeType("prop1", entityBeingEnhancedEnhancedType)).//
endModification();
assertTrue("Incorrect property type.", entityBeingModifiedModifiedType.getName().startsWith(EntityBeingModified.class.getName() + DynamicTypeNamingService.APPENDIX + "_"));
// get the modified TopLevelEntity type
final Class<?> topLevelEntityModifiedType = //
cl.startModification(TopLevelEntity.class).//
addProperties(pd1).//
addProperties(pd2).//
modifyProperties(NewProperty.changeType("prop1", entityBeingModifiedModifiedType)).//
modifyProperties(NewProperty.changeType("prop2", entityBeingModifiedModifiedType)).//
endModification();
assertTrue("Incorrect property type.", topLevelEntityModifiedType.getName().startsWith(TopLevelEntity.class.getName() + DynamicTypeNamingService.APPENDIX + "_"));
// create a new instance of the modified TopLevelEntity type
final Object topLevelEntity = topLevelEntityModifiedType.newInstance();
assertNotNull("Should not be null.", topLevelEntity);
// let's ensure that property types are compatible -- prop2 should be compatible with prop1 as its type is a super class for type of prop1
final Field prop1 = topLevelEntityModifiedType.getDeclaredField("prop1");
final Field prop2 = topLevelEntityModifiedType.getDeclaredField("prop2");
assertEquals("prop 1 and prop 2 should be of the same type", prop2.getType(), prop1.getType());
// now take one of the properties from top level entity and ensure that it's type is property modified
final Field enhancedProp = prop1.getType().getDeclaredField("prop1");
final Field unenhancedProp = prop1.getType().getDeclaredField("prop2");
assertTrue("Incorrect property type.", enhancedProp.getType().getName().startsWith(EntityBeingEnhanced.class.getName() + DynamicTypeNamingService.APPENDIX + "_"));
assertEquals("Incorrect property type.", EntityBeingEnhanced.class.getName(), unenhancedProp.getType().getName());
assertFalse("Original type should not be assignable to the enhanced type", unenhancedProp.getType().isAssignableFrom(enhancedProp.getType()));
assertFalse("Enhanced type should not be assignable to the original type", enhancedProp.getType().isAssignableFrom(unenhancedProp.getType()));
}
}
| mit |
codewarrior0/StorageDrawers | src/com/jaquadro/minecraft/storagedrawers/block/BlockController.java | 6321 | package com.jaquadro.minecraft.storagedrawers.block;
import com.jaquadro.minecraft.storagedrawers.StorageDrawers;
import com.jaquadro.minecraft.storagedrawers.api.storage.INetworked;
import com.jaquadro.minecraft.storagedrawers.block.tile.TileEntityController;
import com.jaquadro.minecraft.storagedrawers.core.ModCreativeTabs;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.util.MathHelper;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import java.util.Random;
public class BlockController extends BlockContainer implements INetworked
{
@SideOnly(Side.CLIENT)
private IIcon iconFront;
@SideOnly(Side.CLIENT)
private IIcon iconSide;
@SideOnly(Side.CLIENT)
private IIcon iconSideEtched;
@SideOnly(Side.CLIENT)
private IIcon iconTrim;
public BlockController (String blockName) {
super(Material.rock);
setCreativeTab(ModCreativeTabs.tabStorageDrawers);
setHardness(5f);
setBlockName(blockName);
setStepSound(Block.soundTypeStone);
setBlockBounds(0, 0, 0, 1, 1, 1);
setTickRandomly(true);
}
@Override
public boolean renderAsNormalBlock () {
return false;
}
@Override
public boolean isOpaqueCube () {
return false;
}
@Override
public int getRenderType () {
return StorageDrawers.proxy.controllerRenderID;
}
@Override
public int tickRate (World world) {
return 100;
}
@Override
public void onBlockPlacedBy (World world, int x, int y, int z, EntityLivingBase entity, ItemStack itemStack) {
TileEntityController tile = getTileEntitySafe(world, x, y, z);
if (tile.getDirection() > 1)
return;
int quadrant = MathHelper.floor_double((entity.rotationYaw * 4f / 360f) + .5) & 3;
switch (quadrant) {
case 0:
tile.setDirection(2);
break;
case 1:
tile.setDirection(5);
break;
case 2:
tile.setDirection(3);
break;
case 3:
tile.setDirection(4);
break;
}
if (world.isRemote) {
tile.invalidate();
world.markBlockForUpdate(x, y, z);
}
}
@Override
public void onPostBlockPlaced (World world, int x, int y, int z, int meta) {
if (world.isRemote)
return;
TileEntityController te = getTileEntity(world, x, y, z);
if (te == null)
return;
te.updateCache();
}
@Override
public boolean onBlockActivated (World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) {
TileEntityController te = getTileEntitySafe(world, x, y, z);
if (te.getDirection() != side)
return false;
if (!world.isRemote)
te.interactPutItemsIntoInventory(player);
return true;
}
@Override
public boolean isSideSolid (IBlockAccess world, int x, int y, int z, ForgeDirection side) {
if (getTileEntity(world, x, y, z) == null)
return true;
if (side.ordinal() != getTileEntity(world, x, y, z).getDirection())
return true;
return false;
}
@Override
public void updateTick (World world, int x, int y, int z, Random rand) {
if (world.isRemote)
return;
TileEntityController te = getTileEntity(world, x, y, z);
if (te == null)
return;
te.updateCache();
world.scheduleBlockUpdate(x, y, z, this, this.tickRate(world));
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon (int side, int meta) {
switch (side) {
case 0:
case 1:
return iconSide;
case 4:
return iconFront;
default:
return iconSideEtched;
}
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon (IBlockAccess blockAccess, int x, int y, int z, int side) {
TileEntityController tile = getTileEntity(blockAccess, x, y, z);
if (tile == null)
return iconFront;
if (side == tile.getDirection())
return iconFront;
switch (side) {
case 0:
case 1:
return iconSide;
default:
return iconSideEtched;
}
}
@SideOnly(Side.CLIENT)
public IIcon getIconTrim (int meta) {
return iconTrim;
}
@Override
public TileEntityController createNewTileEntity (World world, int meta) {
return new TileEntityController();
}
public TileEntityController getTileEntity (IBlockAccess blockAccess, int x, int y, int z) {
TileEntity tile = blockAccess.getTileEntity(x, y, z);
return (tile instanceof TileEntityController) ? (TileEntityController) tile : null;
}
public TileEntityController getTileEntitySafe (World world, int x, int y, int z) {
TileEntityController tile = getTileEntity(world, x, y, z);
if (tile == null) {
tile = createNewTileEntity(world, world.getBlockMetadata(x, y, z));
world.setTileEntity(x, y, z, tile);
}
return tile;
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons (IIconRegister register) {
iconFront = register.registerIcon(StorageDrawers.MOD_ID + ":drawers_controller_front");
iconSide = register.registerIcon(StorageDrawers.MOD_ID + ":drawers_comp_side");
iconSideEtched = register.registerIcon(StorageDrawers.MOD_ID + ":drawers_comp_side_2");
iconTrim = register.registerIcon(StorageDrawers.MOD_ID + ":drawers_comp_trim");
}
}
| mit |
Aarronmc/WallpaperCraft | 1.10.2/src/main/java/Aarron/WallpaperCraft/blocks/rippled/RippledCyan.java | 798 | package Aarron.WallpaperCraft.blocks.rippled;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyEnum;
import Aarron.WallpaperCraft.blockStates.BlockStates;
import Aarron.WallpaperCraft.blockStates.BlockTypes2;
import Aarron.WallpaperCraft.blocks.IMetaBlock2;
public class RippledCyan extends IMetaBlock2<BlockTypes2> {
public RippledCyan() {
super(Material.WOOD, "rippledcyan");
this.setSoundType(SoundType.WOOD);
}
@Override
protected BlockTypes2 getDefaultStateVariant() {
return BlockTypes2.Zero;
}
@Override
protected BlockTypes2 fromMeta(int meta) {
return BlockTypes2.fromMeta(meta);
}
@Override
protected PropertyEnum<BlockTypes2> getVariantEnum() {
return BlockStates.WPblocks2;
}
} | mit |
ljacqu/DependencyInjector | injector-extras/src/test/java/ch/jalu/injector/extras/samples/animals/Frog.java | 629 | package ch.jalu.injector.extras.samples.animals;
import ch.jalu.injector.extras.samples.animals.services.CroakService;
import ch.jalu.injector.extras.samples.animals.services.NameService;
import javax.inject.Inject;
/**
* Frog.
*/
public class Frog implements Animal {
@Inject
private NameService nameService;
@Inject
private CroakService croakService;
@Override
public String getName() {
return nameService.constructName(this);
}
@Override
public boolean canFly() {
return false;
}
public String makeSound() {
return croakService.makeSound();
}
}
| mit |
igormich/JavaDB | src/records/Record.java | 1428 | package records;
import java.util.Set;
import fields.FieldInfo;
public interface Record {
Object get(String name);
default <T> T getAs(String name){
@SuppressWarnings("unchecked")
T result = (T) get(name);
return result;
}
default String getString(String name) {
return get(name).toString();
}
default int getInt(String name){
return (int) get(name);
}
default long getLong(String name) {
return (long) get(name);
}
default double getDouble(String name) {
return (double) get(name);
}
default float getFloat(String name) {
return (float) get(name);
}
default boolean getBoolean(String name) {
return (boolean) get(name);
}
Set<String> getFieldsNames();
FieldInfo getFieldInfo(String name);
String getTableName();
default long count(){
throw new UnsupportedOperationException("Count can be applyed only for GroupBy result");
}
default Object max(String name){
throw new UnsupportedOperationException("Max can be applyed only for GroupBy result");
}
default Object min(String name){
throw new UnsupportedOperationException("Min can be applyed only for GroupBy result");
}
default Number avg(String name){
throw new UnsupportedOperationException("Avg can be applyed only for GroupBy result");
}
default Number sum(String name){
throw new UnsupportedOperationException("Avg can be applyed only for GroupBy result");
}
}
| mit |
ashri/java-wordpress-api | src/main/java/com/tearsofaunicorn/wordpress/api/model/Post.java | 1005 | package com.tearsofaunicorn.wordpress.api.model;
import java.io.Serializable;
import java.util.Set;
import java.util.TreeSet;
public class Post implements Serializable {
private static final long serialVersionUID = -6834915997622886337L;
private final String title;
private final String content;
private Category category;
private Set<Tag> tags;
public Post(String title, String content) {
this.title = title;
this.content = content;
this.tags = new TreeSet<Tag>();
}
public String getTitle() {
return this.title;
}
public String getContent() {
return this.content;
}
public Category getCategory() {
return this.category;
}
public void setCategory(Category category) {
this.category = category;
}
public Set<Tag> getTags() {
return this.tags;
}
public void addTag(Tag tag) {
this.tags.add(tag);
}
public boolean hasTaxonomies() {
return this.category != null || !this.tags.isEmpty();
}
@Override
public String toString() {
return this.title;
}
}
| mit |
microsoftgraph/msgraph-sdk-java | src/main/java/com/microsoft/graph/models/ExpirationPattern.java | 2774 | // Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.models.ExpirationPatternType;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Expiration Pattern.
*/
public class ExpirationPattern implements IJsonBackedObject {
/** the OData type of the object as returned by the service */
@SerializedName("@odata.type")
@Expose
@Nullable
public String oDataType;
private transient AdditionalDataManager additionalDataManager = new AdditionalDataManager(this);
@Override
@Nonnull
public final AdditionalDataManager additionalDataManager() {
return additionalDataManager;
}
/**
* The Duration.
* The requestor's desired duration of access represented in ISO 8601 format for durations. For example, PT3H refers to three hours. If specified in a request, endDateTime should not be present and the type property should be set to afterDuration.
*/
@SerializedName(value = "duration", alternate = {"Duration"})
@Expose
@Nullable
public javax.xml.datatype.Duration duration;
/**
* The End Date Time.
* Timestamp of date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z.
*/
@SerializedName(value = "endDateTime", alternate = {"EndDateTime"})
@Expose
@Nullable
public java.time.OffsetDateTime endDateTime;
/**
* The Type.
* The requestor's desired expiration pattern type. The possible values are: notSpecified, noExpiration, afterDateTime, afterDuration.
*/
@SerializedName(value = "type", alternate = {"Type"})
@Expose
@Nullable
public ExpirationPatternType type;
/**
* Sets the raw JSON object
*
* @param serializer the serializer
* @param json the JSON object to set this object to
*/
public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {
}
}
| mit |
oskopek/learnr | src/main/java/cz/matfyz/oskopek/learnr/ui/LearnrPanel.java | 4349 | /*
* #%L
* Learnr
* %%
* Copyright (C) 2014 Ondrej Skopek
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
package cz.matfyz.oskopek.learnr.ui;
import cz.matfyz.oskopek.learnr.tools.Localizable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
/**
* The base panel (inside of <code>LearnrFrame</code>). Also manages localization (bottom-up).
*/
public class LearnrPanel extends JPanel implements Localizable {
private static final Logger LOGGER = LoggerFactory.getLogger(LearnrPanel.class);
final MainPanel mainPanel;
final MenuPanel menuPanel;
private ResourceBundle resourceBundle;
public LearnrPanel() {
languageChange(Locale.forLanguageTag("en-US"), false); // default en-US
setLayout(new BorderLayout());
mainPanel = new MainPanel(this);
menuPanel = new MenuPanel(this);
add(menuPanel, BorderLayout.LINE_START);
add(mainPanel, BorderLayout.CENTER);
localizationChanged();
}
public void languageChange(Locale locale, boolean initializeRedraw) {
try {
resourceBundle = new PropertyResourceBundle(getClass().getResourceAsStream("/strings/messages." + locale.toLanguageTag() + ".properties"));
} catch (IOException e) {
LOGGER.error("No such resourceBundle found: \'{}\'", locale.toLanguageTag());
e.printStackTrace();
}
LOGGER.debug("Loaded resourceBundle: \'{}\'", locale.toLanguageTag());
setLocale(locale); //necessary?
if (initializeRedraw) {
localizationChanged();
}
}
public HashMap<String, String> getAvailableLanguages() {
//Old version, used while loading only from file system (wouldn't work in an exec-able jar)
/*
File langDir = new File("./prog1/zapoctak_learnr/data/strings/");
java.util.List<String> availableLanguages = new ArrayList<>();
for (String filename : langDir.list()) {
LOGGER.info("Inspecting file \'{}\' for language resources.", filename);
if (filename.split("\\.").length != 3) continue;
String langCode = filename.split("\\.")[1];
LOGGER.info("Found language \'{}\'.", langCode);
availableLanguages.add(langCode);
}
String[] availableLangArr = new String[availableLanguages.size()];
availableLanguages.toArray(availableLangArr);
return availableLangArr;
*/
HashMap<String, String> availableLanguages = new HashMap<>();
availableLanguages.put(localizedText("english"), "en-US");
availableLanguages.put(localizedText("slovak"), "sk-SK");
availableLanguages.put(localizedText("german"), "de-DE");
availableLanguages.put(localizedText("czech"), "cs-CS");
//Add new languages here
return availableLanguages;
}
@Override
public String localizedText(String id) {
return resourceBundle.getString(id);
}
@Override
public void localizationChanged() {
mainPanel.localizationChanged();
menuPanel.localizationChanged();
}
}
| mit |
anasanasanas/material-calendarview | sample/src/main/java/com/prolificinteractive/materialcalendarview/sample/BasicActivity.java | 2054 | package com.prolificinteractive.materialcalendarview.sample;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import com.prolificinteractive.materialcalendarview.OnMonthChangedListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Shows off the most basic usage
*/
public class BasicActivity extends AppCompatActivity implements OnDateSelectedListener, OnMonthChangedListener {
private static final DateFormat FORMATTER = SimpleDateFormat.getDateInstance();
@BindView(R.id.calendarView)
MaterialCalendarView widget;
@BindView(R.id.textView)
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic);
ButterKnife.bind(this);
widget.setOnDateChangedListener(this);
widget.setOnMonthChangedListener(this);
//Setup initial text
textView.setText(getSelectedDatesString());
}
@Override
public void onDateSelected(@NonNull MaterialCalendarView widget, @Nullable CalendarDay date, boolean selected) {
textView.setText(getSelectedDatesString());
}
@Override
public void onMonthChanged(MaterialCalendarView widget, CalendarDay date) {
//noinspection ConstantConditions
getSupportActionBar().setTitle(FORMATTER.format(date.getDate()));
}
private String getSelectedDatesString() {
CalendarDay date = widget.getSelectedDate();
if (date == null) {
return "No Selection";
}
return FORMATTER.format(date.getDate());
}
}
| mit |
BrainDoctor/clustercode | clustercode.impl.constraint/src/main/java/clustercode/impl/constraint/FileNameConstraint.java | 928 | package clustercode.impl.constraint;
import clustercode.api.domain.Media;
import javax.inject.Inject;
import java.util.regex.Pattern;
/**
* Provides a constraint which enables file name checking by regex. The input path of the candidate is being
* checked (relative, without base input directory). Specify a Java-valid regex pattern, otherwise a runtime
* exception is being thrown.
*/
public class FileNameConstraint
extends AbstractConstraint {
private final Pattern pattern;
@Inject
FileNameConstraint(ConstraintConfig config) {
this.pattern = Pattern.compile(config.filename_regex());
}
@Override
public boolean accept(Media candidate) {
String toTest = candidate.getSourcePath().toString();
return logAndReturnResult(pattern.matcher(toTest).matches(), "file name of {} with regex {}",
candidate.getSourcePath(), pattern.pattern());
}
}
| mit |
desertblackeagle/SQA_ChineseChess | src/ui/LodingFrame.java | 1029 | package ui;
import java.awt.Image;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class LodingFrame extends ParentFrame {
JLabel background, lodingGifLabel;
ImageIcon backgroundPhoto, lodingGif;
public LodingFrame() {
// TODO Auto-generated constructor stub
initLabel();
initBounds();
}
private void initLabel() {
java.net.URL imUrl = getClass().getResource("/image/");
String path = imUrl.toString() + "matching_2.gif";
URL url = null;
try {
url = new URL(path);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
backgroundPhoto = new ImageIcon(url);
backgroundPhoto.setImage(backgroundPhoto.getImage().getScaledInstance(getWidth(), getHeight(), Image.SCALE_DEFAULT));
background = new JLabel(backgroundPhoto);
add(background);
}
private void initBounds() {
background.setBounds(0, 0, getWidth(), getHeight());
}
}
| mit |
X-corpion/jDiff | src/main/java/org/xcorpion/jdiff/util/ReflectionObjectDiffMapper.java | 19523 | package org.xcorpion.jdiff.util;
import org.xcorpion.jdiff.annotation.TypeHandler;
import org.xcorpion.jdiff.api.*;
import org.xcorpion.jdiff.exception.DiffException;
import org.xcorpion.jdiff.exception.MergingException;
import org.xcorpion.jdiff.internal.model.DefaultDiffingContext;
import org.xcorpion.jdiff.internal.model.DefaultMergingContext;
import org.xcorpion.jdiff.util.collection.DiffApplicationTree;
import org.xcorpion.jdiff.util.collection.Iterables;
import org.xcorpion.jdiff.util.collection.Tree;
import org.xcorpion.jdiff.util.reflection.ReflectionUtils;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.reflect.*;
import java.util.*;
public class ReflectionObjectDiffMapper
extends BaseObjectDiffMapper
implements ObjectDiffMapper {
@Override
@Nonnull
public <T> DiffNode diff(@Nullable T src, @Nullable T target) {
if (isEqualTo(src, target)) {
return new DiffNode();
}
Tree<DiffNode> diffTree = createNextDiffTreeNode(ObjectUtils.inferClass(src, target), src, target);
Iterable<DiffNode> diffGroups = diffTree.preOrderTraversal();
Iterator<DiffNode> iter = diffGroups.iterator();
DiffNode root = iter.next();
// this introduces side effects as it builds the tree as traversal goes
while (iter.hasNext()) {
iter.next();
}
return root;
}
@Nonnull
private DiffNode createDiffGroupOneLevel(@Nullable Object src, @Nullable Object target) {
if (target == DELETION_MARK) {
return new DiffNode(new Diff(Diff.Operation.REMOVE_VALUE, src, null));
}
if (src == null || target == null) {
return new DiffNode(new Diff(Diff.Operation.UPDATE_VALUE, src, target));
}
if (isPrimitive(src)) {
return createPrimitiveUpdateDiffGroup(src, target);
}
if (src.getClass().isArray()) {
return createArrayDiffGroup(src, target);
}
return new DiffNode(new Diff(Diff.Operation.NO_OP, null, null));
}
@Nonnull
private <T> Iterable<Tree<DiffNode>> generateChildDiffGroups(@Nonnull final DiffNode parentDiffNode,
Type type,
@Nullable final T src, @Nullable final T target) {
if (target == null || isPrimitive(target)) {
return Iterables.empty();
}
return createFieldDiffIterable(parentDiffNode, ReflectionUtils.typeToClass(type), src, target);
}
private Iterable<Tree<DiffNode>> createFieldDiffIterable(@Nonnull DiffNode parentDiffNode,
Class<?> objectClass,
@Nullable final Object src, final @Nonnull Object target) {
if (src == null) {
return Collections.singletonList(new Tree<>(
new DiffNode(new Diff(Diff.Operation.UPDATE_VALUE, null, target))
));
}
if (objectClass.isArray()) {
return createArrayDiffIterable(parentDiffNode, src, target);
}
if (src instanceof Set) {
return createSetDiffIterable(parentDiffNode, src, target);
}
if (src instanceof Map) {
return createMapDiffIterable(parentDiffNode, src, target);
}
if (src instanceof Iterable) {
return createOrderedDiffIterable(parentDiffNode, src, target);
}
List<Field> fields = ReflectionUtils.getAllFieldsRecursive(objectClass);
return () -> new Iterator<Tree<DiffNode>>() {
int index = 0;
Field field;
Type fieldType;
Object srcFieldValue;
Object targetFieldValue;
DiffingHandler<Object> fieldDiffingHandler;
private void reset() {
fieldType = null;
srcFieldValue = null;
targetFieldValue = null;
}
@Override
public boolean hasNext() {
fieldDiffingHandler = null;
for (; index < fields.size(); index++) {
reset();
field = fields.get(index);
if (isEnabled(Feature.IgnoreFields.TRANSIENT)) {
if (Modifier.isTransient(field.getModifiers())) {
continue;
}
}
if (isEnabled(Feature.IgnoreFields.INACCESSIBLE) && !field.isAccessible()) {
continue;
}
field.setAccessible(true);
try {
srcFieldValue = field.get(src);
} catch (IllegalAccessException e) {
throw new DiffException("Failed to access field " + field.getName() +
" in " + src.getClass().getName(), e);
}
try {
targetFieldValue = field.get(target);
} catch (IllegalAccessException e) {
throw new DiffException("Failed to access field " + field.getName() +
" in " + target.getClass().getName(), e);
}
if (isEqualTo(srcFieldValue, targetFieldValue)) {
continue;
}
fieldType = ReflectionUtils.guessType(field, srcFieldValue, targetFieldValue);
index++;
if (!isEnabled(Feature.DiffingHandler.IGNORE_FIELD_TYPE_HANDLER)) {
TypeHandler typeHandler = field.getAnnotation(TypeHandler.class);
if (typeHandler != null && typeHandler.diffUsing() != TypeHandler.None.class) {
try {
//noinspection unchecked
fieldDiffingHandler = (DiffingHandler<Object>) typeHandler.diffUsing().newInstance();
}
catch (Throwable e) {
String message = String.format("Failed to instantiate diffing handler %s for %s in %s",
typeHandler.diffUsing().getName(),
field.getName(),
objectClass.getName());
throw new DiffException(message);
}
}
if (fieldDiffingHandler == null) {
fieldDiffingHandler = getDiffingHandler(fieldType);
}
}
if (fieldDiffingHandler == null && !isEnabled(Feature.DiffingHandler.IGNORE_GLOBAL_TYPE_HANDLER)) {
fieldDiffingHandler = getDiffingHandler(fieldType);
}
return true;
}
return false;
}
@Override
public Tree<DiffNode> next() {
Tree<DiffNode> nextDiffTreeNode;
if (fieldDiffingHandler != null) {
DiffNode diffNode = fieldDiffingHandler.diff(srcFieldValue, targetFieldValue,
new DefaultDiffingContext(ReflectionObjectDiffMapper.this));
nextDiffTreeNode = new Tree<>(diffNode);
} else {
nextDiffTreeNode = createNextDiffTreeNode(fieldType, srcFieldValue, targetFieldValue);
}
parentDiffNode.addFieldDiff(field.getName(), nextDiffTreeNode.getNodeValue());
return nextDiffTreeNode;
}
};
}
private Iterable<Tree<DiffNode>> createArrayDiffIterable(@Nonnull DiffNode parentDiffNode,
@Nonnull final Object src, @Nonnull final Object target) {
int srcArraySize = Array.getLength(src);
int targetArraySize = Array.getLength(target);
int maxSize = Math.max(srcArraySize, targetArraySize);
return () -> new Iterator<Tree<DiffNode>>() {
int index = 0;
Object srcValue = null;
Object targetValue = null;
@Override
public boolean hasNext() {
for (; index < maxSize; index++) {
srcValue = null;
targetValue = null;
if (index < srcArraySize) {
srcValue = Array.get(src, index);
}
if (index < targetArraySize) {
targetValue = Array.get(target, index);
}
if (isEqualTo(srcValue, targetValue)) {
continue;
}
index++;
return true;
}
return false;
}
@Override
public Tree<DiffNode> next() {
int diffIndex = index - 1;
if (srcValue != null && targetValue != null) {
Tree<DiffNode> nextDiffTreeNode = createNextDiffTreeNode(ObjectUtils.inferClass(srcValue, targetValue),
srcValue, targetValue);
parentDiffNode.addFieldDiff(diffIndex, nextDiffTreeNode.getNodeValue());
return nextDiffTreeNode;
}
DiffNode nextLevelRoot;
if (diffIndex >= targetArraySize) {
nextLevelRoot = createDiffGroupOneLevel(srcValue, DELETION_MARK);
} else {
if (targetValue == null) {
nextLevelRoot = createDiffGroupOneLevel(srcValue, null);
} else {
nextLevelRoot = createDiffGroupOneLevel(null, targetValue);
}
}
parentDiffNode.addFieldDiff(diffIndex, nextLevelRoot);
return new Tree<>(nextLevelRoot);
}
};
}
@SuppressWarnings("unchecked")
private Iterable<Tree<DiffNode>> createOrderedDiffIterable(@Nonnull DiffNode parentDiffNode,
@Nonnull Object src, @Nonnull Object target) {
Iterable<Object> srcIterable = (Iterable<Object>) src;
Iterable<Object> targetIterable = (Iterable<Object>) target;
return () -> new Iterator<Tree<DiffNode>>() {
Object srcValue = null;
Object targetValue = null;
Iterator<Object> srcIter = srcIterable.iterator();
Iterator<Object> targetIter = targetIterable.iterator();
int index = 0;
boolean srcIterHasNext = false;
boolean targetIterHasNext = false;
@Override
public boolean hasNext() {
while (true) {
srcValue = null;
targetValue = null;
srcIterHasNext = srcIter.hasNext();
targetIterHasNext = targetIter.hasNext();
if (!srcIterHasNext && !targetIterHasNext) {
return false;
}
if (srcIterHasNext) {
srcValue = srcIter.next();
}
if (targetIterHasNext) {
targetValue = targetIter.next();
}
if (isEqualTo(srcValue, targetValue)) {
index++;
continue;
}
index++;
return true;
}
}
@Override
public Tree<DiffNode> next() {
int diffIndex = index - 1;
DiffNode nextLevelRoot;
if (srcIterHasNext && targetIterHasNext) {
Tree<DiffNode> nextDiffTreeNode = createNextDiffTreeNode(ObjectUtils.inferClass(srcValue, targetValue),
srcValue, targetValue);
parentDiffNode.addFieldDiff(diffIndex, nextDiffTreeNode.getNodeValue());
return nextDiffTreeNode;
} else if (!targetIterHasNext) {
nextLevelRoot = new DiffNode(new Diff(Diff.Operation.REMOVE_VALUE, srcValue, null));
} else {
nextLevelRoot = new DiffNode(new Diff(Diff.Operation.ADD_VALUE, null, targetValue));
}
parentDiffNode.addFieldDiff(diffIndex, nextLevelRoot);
return new Tree<>(nextLevelRoot);
}
};
}
@SuppressWarnings("unchecked")
private Iterable<Tree<DiffNode>> createSetDiffIterable(@Nonnull DiffNode parentDiffNode,
@Nonnull Object src, @Nonnull Object target) {
final Set<Object> srcSet = (Set<Object>) src;
final Set<Object> targetSet = (Set<Object>) target;
final Set<Object> allElementsSet = new HashSet<>(targetSet);
allElementsSet.addAll(srcSet);
List<Tree<DiffNode>> diffGroupNextLevelRootNodes = new ArrayList<>();
int diffIndex = 0;
for (Object obj : allElementsSet) {
boolean srcHasElement = srcSet.contains(obj);
boolean targetHasElement = targetSet.contains(obj);
if (srcHasElement && targetHasElement) {
//noinspection UnnecessaryContinue
continue;
} else {
DiffNode nextLevelRoot;
if (srcHasElement) {
nextLevelRoot = createDiffGroupOneLevel(obj, DELETION_MARK);
} else {
nextLevelRoot = new DiffNode(new Diff(Diff.Operation.ADD_VALUE, null, obj));
}
diffGroupNextLevelRootNodes.add(new Tree<>(nextLevelRoot));
parentDiffNode.addFieldDiff(diffIndex++, nextLevelRoot);
}
}
return diffGroupNextLevelRootNodes;
}
@SuppressWarnings("unchecked")
private Iterable<Tree<DiffNode>> createMapDiffIterable(@Nonnull DiffNode parentDiffNode,
@Nonnull Object src, @Nonnull Object target) {
final Map<Object, Object> srcMap = (Map<Object, Object>) src;
final Map<Object, Object> targetMap = (Map<Object, Object>) target;
final Map<Object, Object> mapWithAllElements = new HashMap<>(targetMap);
mapWithAllElements.putAll(srcMap);
List<Tree<DiffNode>> diffGroupNextLevelRootNodes = new ArrayList<>();
for (Map.Entry<Object, Object> entry : mapWithAllElements.entrySet()) {
Object key = entry.getKey();
boolean srcHasKey = srcMap.containsKey(key);
boolean targetHasKey = targetMap.containsKey(key);
if (srcHasKey && targetHasKey) {
Object srcElement = srcMap.get(key);
Object targetElement = targetMap.get(key);
if (isEqualTo(srcElement, targetElement)) {
continue;
}
Tree<DiffNode> nextLevelTreeNode = createNextDiffTreeNode(ObjectUtils.inferClass(srcElement, targetElement),
srcElement, targetElement);
diffGroupNextLevelRootNodes.add(nextLevelTreeNode);
parentDiffNode.addFieldDiff(key, nextLevelTreeNode.getNodeValue());
} else {
DiffNode nextLevelRoot;
if (srcHasKey) {
nextLevelRoot = createDiffGroupOneLevel(entry.getValue(), DELETION_MARK);
} else {
nextLevelRoot = new DiffNode(new Diff(Diff.Operation.ADD_VALUE, null, entry.getValue()));
}
diffGroupNextLevelRootNodes.add(new Tree<>(nextLevelRoot));
parentDiffNode.addFieldDiff(key, nextLevelRoot);
}
}
return diffGroupNextLevelRootNodes;
}
private Tree<DiffNode> createNextDiffTreeNode(@Nonnull Type type, @Nullable Object src, @Nullable Object target) {
DiffNode node;
if (src == target) {
node = new DiffNode(new Diff());
} else if (src == null || target == null) {
node = new DiffNode(new Diff(Diff.Operation.UPDATE_VALUE, src, target));
} else {
node = diffUsingClassLevelCustomHandler(type, src, target);
}
if (node != null) {
return new Tree<>(node);
}
node = createDiffGroupOneLevel(src, target);
Iterable<Tree<DiffNode>> nextLevelDiffChildren =
generateChildDiffGroups(node, type, src, target);
return new Tree<>(node, nextLevelDiffChildren);
}
@SuppressWarnings("unchecked")
private DiffNode diffUsingClassLevelCustomHandler(@Nonnull Type type, @Nonnull Object src, @Nonnull Object target) {
Class<?> cls = ReflectionUtils.typeToClass(type);
if (!isEnabled(Feature.DiffingHandler.IGNORE_CLASS_TYPE_HANDLER)) {
TypeHandler typeHandler = ReflectionUtils.getClassAnnotation(cls, TypeHandler.class);
if (typeHandler != null) {
Class<? extends DiffingHandler<?>> handlerClass = typeHandler.diffUsing();
if (handlerClass != TypeHandler.None.class) {
DiffingHandler<Object> diffingHandler;
try {
diffingHandler = (DiffingHandler<Object>) handlerClass.newInstance();
}
catch (Throwable e) {
String message = String.format("Failed to instantiate diffing handler %s for %s",
handlerClass.getName(),
type.getTypeName());
throw new DiffException(message);
}
return diffingHandler.diff(src, target, new DefaultDiffingContext(this));
}
}
}
if (!isEnabled(Feature.DiffingHandler.IGNORE_GLOBAL_TYPE_HANDLER)) {
DiffingHandler<Object> diffingHandler = getDiffingHandler(type);
if (diffingHandler != null) {
return diffingHandler.diff(src, target, new DefaultDiffingContext(this));
}
}
return null;
}
@Override
public <T> T applyDiff(@Nullable T src, @Nonnull DiffNode diffs, @Nonnull Set<Feature.MergingStrategy> mergingStrategies) {
DiffApplicationTree diffApplicationTree = new DiffApplicationTree(ObjectUtils.inferClass(src, diffs),
src, diffs);
try {
Iterable<DiffApplicationTree> applicationTreeNodes = diffApplicationTree.preOrderTraversal();
Iterator<DiffApplicationTree> iter = applicationTreeNodes.iterator();
@SuppressWarnings("unchecked")
T newRoot = (T) iter.next().applyDiff(new DefaultMergingContext(
this,
mergingStrategies,
true
));
while (iter.hasNext()) {
DiffApplicationTree node = iter.next();
node.applyDiff(new DefaultMergingContext(
this,
mergingStrategies,
false
));
}
return newRoot;
}
catch (Throwable e) {
if (e instanceof MergingException) {
throw e;
}
throw new MergingException("Failed to merge diff: " + e.getMessage(), e);
}
}
}
| mit |
noogotte/CWJ | src/main/java/fr/aumgn/cwj/event/Event.java | 674 | package fr.aumgn.cwj.event;
public abstract class Event<E extends Event<E>> {
/**
* Returns the {@link EventSupport} for this Event.
* <p>
* Implementing this method means that the Event is actually meant to be
* listened to.
*/
public abstract EventSupport<E> getEventSupport();
/**
* This is called before {@link EventPhase.MONITOR} and
* {@link EventPhase.POST_MONITOR} in order to allow implementation to
* enforce immutability.
* <p>
* Overriding this method is not necessary because EventPhase is before all
* a contract between the API and the users.
*/
protected void freeze() {
}
}
| mit |
jalves94/azure-sdk-for-java | azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/NetworkManager.java | 5773 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.network.implementation;
import com.microsoft.azure.AzureEnvironment;
import com.microsoft.azure.management.network.NetworkSecurityGroups;
import com.microsoft.azure.management.network.LoadBalancers;
import com.microsoft.azure.management.network.NetworkInterfaces;
import com.microsoft.azure.management.network.Networks;
import com.microsoft.azure.management.network.PublicIpAddresses;
import com.microsoft.azure.management.resources.fluentcore.arm.AzureConfigurable;
import com.microsoft.azure.management.resources.fluentcore.arm.implementation.AzureConfigurableImpl;
import com.microsoft.azure.management.resources.fluentcore.arm.implementation.Manager;
import com.microsoft.azure.RestClient;
import com.microsoft.rest.credentials.ServiceClientCredentials;
/**
* Entry point to Azure network management.
*/
public final class NetworkManager extends Manager<NetworkManager, NetworkManagementClientImpl> {
// Collections
private PublicIpAddresses publicIpAddresses;
private Networks networks;
private NetworkSecurityGroups networkSecurityGroups;
private NetworkInterfaces networkInterfaces;
private LoadBalancers loadBalancers;
/**
* Get a Configurable instance that can be used to create {@link NetworkManager}
* with optional configuration.
*
* @return the instance allowing configurations
*/
public static Configurable configure() {
return new NetworkManager.ConfigurableImpl();
}
/**
* Creates an instance of NetworkManager that exposes network resource management API entry points.
*
* @param credentials the credentials to use
* @param subscriptionId the subscription UUID
* @return the NetworkManager
*/
public static NetworkManager authenticate(ServiceClientCredentials credentials, String subscriptionId) {
return new NetworkManager(AzureEnvironment.AZURE.newRestClientBuilder()
.withCredentials(credentials)
.build(), subscriptionId);
}
/**
* Creates an instance of NetworkManager that exposes network resource management API entry points.
*
* @param restClient the RestClient to be used for API calls.
* @param subscriptionId the subscription UUID
* @return the NetworkManager
*/
public static NetworkManager authenticate(RestClient restClient, String subscriptionId) {
return new NetworkManager(restClient, subscriptionId);
}
/**
* The interface allowing configurations to be set.
*/
public interface Configurable extends AzureConfigurable<Configurable> {
/**
* Creates an instance of NetworkManager that exposes network management API entry points.
*
* @param credentials the credentials to use
* @param subscriptionId the subscription UUID
* @return the interface exposing network management API entry points that work across subscriptions
*/
NetworkManager authenticate(ServiceClientCredentials credentials, String subscriptionId);
}
/**
* The implementation for Configurable interface.
*/
private static class ConfigurableImpl
extends AzureConfigurableImpl<Configurable>
implements Configurable {
public NetworkManager authenticate(ServiceClientCredentials credentials, String subscriptionId) {
return NetworkManager.authenticate(buildRestClient(credentials), subscriptionId);
}
}
private NetworkManager(RestClient restClient, String subscriptionId) {
super(
restClient,
subscriptionId,
new NetworkManagementClientImpl(restClient).withSubscriptionId(subscriptionId));
}
/**
* @return entry point to virtual network management
*/
public Networks networks() {
if (this.networks == null) {
this.networks = new NetworksImpl(
super.innerManagementClient,
this);
}
return this.networks;
}
/**
* @return entry point to network security group management
*/
public NetworkSecurityGroups networkSecurityGroups() {
if (this.networkSecurityGroups == null) {
this.networkSecurityGroups = new NetworkSecurityGroupsImpl(
super.innerManagementClient.networkSecurityGroups(),
this);
}
return this.networkSecurityGroups;
}
/**
* @return entry point to public IP address management
*/
public PublicIpAddresses publicIpAddresses() {
if (this.publicIpAddresses == null) {
this.publicIpAddresses = new PublicIpAddressesImpl(
super.innerManagementClient.publicIPAddresses(),
this);
}
return this.publicIpAddresses;
}
/**
* @return entry point to network interface management
*/
public NetworkInterfaces networkInterfaces() {
if (networkInterfaces == null) {
this.networkInterfaces = new NetworkInterfacesImpl(
super.innerManagementClient.networkInterfaces(),
this);
}
return this.networkInterfaces;
}
/**
* @return entry point to load balancer management
*/
public LoadBalancers loadBalancers() {
if (this.loadBalancers == null) {
this.loadBalancers = new LoadBalancersImpl(
super.innerManagementClient,
this);
}
return this.loadBalancers;
}
}
| mit |
marcelganczak/swift-js-transpiler | OperatorLoader.java | 1791 | import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
public class OperatorLoader {
static public void load(Cache cache, SwiftParser.Top_levelContext topLevel) {
InputStream is = Prefix.class.getResourceAsStream("operators.json");
String jsonTxt = null;
JSONObject definitions = null;
try { jsonTxt = IOUtils.toString(is); } catch(IOException e) {}
try { definitions = new JSONObject(jsonTxt); } catch(JSONException e) {}
for(int i = 0; i < definitions.names().length(); i++) {
String operator = definitions.names().optString(i);
JSONObject src = definitions.optJSONObject(operator);
Operator definition = parseDefinition(src, cache, topLevel);
cache.cacheOne(operator, definition, topLevel);
}
}
static private Operator parseDefinition(JSONObject src, Cache cache, SwiftParser.Top_levelContext topLevel) {
Operator definition = new Operator();
definition.priority = src.optInt("priority");
if(src.has("result")) {
definition.result = (Definition)cache.find(src.optString("result"), topLevel).object;
}
if(src.optJSONObject("codeReplacement") != null) {
definition.codeReplacement = new HashMap<String, String>();
for(int i = 0; i < src.optJSONObject("codeReplacement").names().length(); i++) {
String language = src.optJSONObject("codeReplacement").names().optString(i);
definition.codeReplacement.put(language, src.optJSONObject("codeReplacement").optString(language));
}
}
return definition;
}
}
| mit |
ajakuba/AJAmarks | AJAmarksServer/src/integrationTest/java/com/jakub/ajamarks/repositories/ClassroomRepositoryIntegrationTest.java | 238 | package com.jakub.ajamarks.repositories;
import org.junit.Test;
/**
* Created by ja on 11.01.17.
*/
public class ClassroomRepositoryIntegrationTest {
@Test
public void testFindStudentsInClassroom() throws Exception {
}
} | mit |
cedias/PIAD | SRD/src/database/sql/HonestySQL.java | 934 | package database.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Honesty statements
* @author charles
*
*/
public class HonestySQL {
/**
* Get Update Honesty PreparedStatement
* @param conn
* @return
* @throws SQLException
*/
public static PreparedStatement getUpdateHonestyStatement(Connection conn) throws SQLException{
final String sql = "UPDATE reviews SET honesty_score = ? WHERE review_id=?;";
return conn.prepareStatement(sql);
}
/**
* Configure Update Honesty PreparedStatement
* @param st
* @param score
* @param review_id
* @return
* @throws SQLException
*/
public static PreparedStatement insertBatchUpdateHonesty(PreparedStatement st, double score,int review_id) throws SQLException{
/*
* 1: reliability_score
* 2: review_id_id
*/
st.setDouble(1, score);
st.setInt(2, review_id);
st.addBatch();
return st;
}
}
| mit |
mgatelabs/SWFTools-Core | src/com/mgatelabs/swftools/support/swf/objects/FID.java | 270 | /*
Copyright M-Gate Labs 2007
Can be edited with permission only.
*/
package com.mgatelabs.swftools.support.swf.objects;
public interface FID {
// All Flash Objects must have a FLash ID
// Used to make working with objects easier.
public int getID();
} | mit |
evsoncustodio/ES2TB2-2 | src/controller/DisciplinaController.java | 1910 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import dao.DisciplinaDAO;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import model.Disciplina;
/**
*
* @author evson
*/
public class DisciplinaController extends Observable {
private static final DisciplinaController CONTROL = new DisciplinaController();
private static final String[] NOME_COLUNAS = { "ID", "Nome", "Média Disciplina" };
private static final List<Disciplina> DISCIPLINAS = new ArrayList<>(DisciplinaDAO.getInstance().query().values());
private DisciplinaController() {
}
public static DisciplinaController getInstance() {
return CONTROL;
}
public static List<Disciplina> getDisciplinas() {
return DISCIPLINAS;
}
public static String[] getNomeColunas() {
return NOME_COLUNAS;
}
public Object[] getDisciplinaObject(Object object) {
Disciplina disciplina = (Disciplina) object;
return new Object[] {
disciplina.getId(),
disciplina.getNome(),
disciplina.getMediaTurma() != null ? disciplina.getMediaTurma() : "-"
};
}
public Object[][] getDisciplinasObjects() {
Object[][] data = new Object[DISCIPLINAS.size()][NOME_COLUNAS.length];
for (int i = 0; i < DISCIPLINAS.size(); i++) {
data[i] = getDisciplinaObject(DISCIPLINAS.get(i));
}
return data;
}
public void adicionarDisciplina(String nome) {
Disciplina disciplina = new Disciplina(null, nome, null);
DisciplinaDAO.getInstance().create(disciplina);
DISCIPLINAS.add(disciplina);
setChanged();
notifyObservers(disciplina);
}
}
| mit |
Axellience/vue-gwt | docs/examples/src/main/java/com/axellience/vuegwtexamples/client/examples/kitten/KittenClientBundle.java | 426 | package com.axellience.vuegwtexamples.client.examples.kitten;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
/**
* @author Adrien Baron
*/
public interface KittenClientBundle extends ClientBundle {
KittenClientBundle INSTANCE = GWT.create(KittenClientBundle.class);
@Source("kitten.jpg")
ImageResource myKitten();
} | mit |
kanglaive/PoE-Helper | src/model/basetype/Shield.java | 122 | package model.basetype;
import model.Item;
/**
* Created by Kang on 7/7/2017.
*/
public class Shield extends Item {
}
| mit |
habibmasuro/XChange | xchange-bitfinex/src/test/java/com/xeiam/xchange/btce/v2/service/account/BitfinexAccountInfoJSONTest.java | 2065 | /**
* Copyright (C) 2012 - 2014 Xeiam LLC http://xeiam.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.xeiam.xchange.btce.v2.service.account;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xeiam.xchange.bitfinex.v1.dto.account.BitfinexBalancesResponse;
/**
* Test BTCEDepth JSON parsing
*/
public class BitfinexAccountInfoJSONTest {
@Test
public void testUnmarshal() throws IOException {
// Read in the JSON from the example resources
InputStream is = BitfinexAccountInfoJSONTest.class.getResourceAsStream("/v1/account/example-account-info-data.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
BitfinexBalancesResponse readValue = mapper.readValue(is, BitfinexBalancesResponse.class);
assertEquals(readValue.getAmount().toString(), new BigDecimal("8.53524686").toString());
}
}
| mit |
jananzhu/cellsociety | src/model/cells/FireCell.java | 844 | package model.cells;
import java.util.Random;
/**
* This is the square superclass for Fire simulation.
* It holds the method to update each cell
* It also holds the method to calculate the probability that a cell will catch fire
* @author Sunjeev and Sid
*
*/
public abstract class FireCell extends Cell{
protected Random myRandom;
public FireCell(){
myRandom = new Random();
}
/**
* @return the current state of the tree after checking with neighbors determined by making a new SquareFire
* class
*/
public FireCell update(){
return this.checkStatus();
}
public boolean calculateProbability(Cell cell) {
if(cell.viewProperties().get("probCatch") != null){
return myRandom.nextInt(100) <= cell.viewProperties().get("probCatch");
}
return false;
}
protected abstract FireCell checkStatus();
}
| mit |
Lanceolata/code-problems | java/src/main/java/com/lanceolata/leetcode_medium/Question_150_Game_of_Life.java | 1020 | package com.lanceolata.leetcode_medium;
/**
* Created by lance on 2018/8/20.
*/
public class Question_150_Game_of_Life {
public void gameOfLife(int[][] board) {
int m = board.length, n = board[0].length;
int dx[] = {-1, -1, -1, 0, 1, 1, 1, 0};
int dy[] = {-1, 0, 1, 1, 1, 0, -1, -1};
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int cnt = 0;
for (int k = 0; k < 8; ++k) {
int x = i + dx[k], y = j + dy[k];
if (x >= 0 && x < m && y >= 0 && y < n && (board[x][y] == 1 || board[x][y] == 2)) {
++cnt;
}
}
if (board[i][j] == 1 && (cnt < 2 || cnt > 3)) board[i][j] = 2;
else if (board[i][j] == 0 && cnt == 3) board[i][j] = 3;
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
board[i][j] %= 2;
}
}
}
}
| mit |
sundarinc/sundar-android | src/io/sundar/sundarsupply/MainActivity.java | 1466 | package io.sundar.sundarsupply;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class MainActivity extends Activity {
static MainActivity thisActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
thisActivity = this;
setAccessories();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
overridePendingTransition(R.anim.detail_in, R.anim.menu_out);
}
}, 1500);
}
private void setAccessories() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisc(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| mit |
DragonMouth22/AllArmor | src/main/java/net/jusanov/allarmor/items/ItemCloth.java | 471 | package net.jusanov.allarmor.items;
import net.jusanov.allarmor.common.AllArmor;
import net.jusanov.allarmor.common.Reference;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
public class ItemCloth extends Item {
public ItemCloth() {
setUnlocalizedName(Reference.AllArmorItems.CLOTH.getUnlocalizedName());
setRegistryName(Reference.AllArmorItems.CLOTH.getRegistryName());
this.setCreativeTab(AllArmor.allarmorMaterialsTab);
}
} | mit |
wolfgangimig/joa | java/joa-im/src-gen/com/wilutions/mslib/uccollaborationlib/impl/Fire__IContentSharingModalityEvents.java | 3313 | /* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.uccollaborationlib.impl;
import com.wilutions.com.*;
import com.wilutions.mslib.uccollaborationlib._IContentSharingModalityEvents;
@SuppressWarnings("all")
public class Fire__IContentSharingModalityEvents {
public final static void onOnModalityStateChanged(final IDispatch __joa__disp, final com.wilutions.mslib.uccollaborationlib.IModality _eventSource, final com.wilutions.mslib.uccollaborationlib.IModalityStateChangedEventData _eventData) throws ComException {
assert(__joa__disp != null);
assert(_eventSource != null);
assert(_eventData != null);
__joa__disp._fireEvent(_IContentSharingModalityEvents.class, (l)->l.onOnModalityStateChanged(_eventSource,_eventData));
}
public final static void onOnActionAvailabilityChanged(final IDispatch __joa__disp, final com.wilutions.mslib.uccollaborationlib.IModality _eventSource, final com.wilutions.mslib.uccollaborationlib.IModalityActionAvailabilityChangedEventData _eventData) throws ComException {
assert(__joa__disp != null);
assert(_eventSource != null);
assert(_eventData != null);
__joa__disp._fireEvent(_IContentSharingModalityEvents.class, (l)->l.onOnActionAvailabilityChanged(_eventSource,_eventData));
}
public final static void onOnContentAdded(final IDispatch __joa__disp, final com.wilutions.mslib.uccollaborationlib.IContentSharingModality _eventSource, final com.wilutions.mslib.uccollaborationlib.IContentCollectionChangedEventData _eventData) throws ComException {
assert(__joa__disp != null);
assert(_eventSource != null);
assert(_eventData != null);
__joa__disp._fireEvent(_IContentSharingModalityEvents.class, (l)->l.onOnContentAdded(_eventSource,_eventData));
}
public final static void onOnContentRemoved(final IDispatch __joa__disp, final com.wilutions.mslib.uccollaborationlib.IContentSharingModality _eventSource, final com.wilutions.mslib.uccollaborationlib.IContentCollectionChangedEventData _eventData) throws ComException {
assert(__joa__disp != null);
assert(_eventSource != null);
assert(_eventData != null);
__joa__disp._fireEvent(_IContentSharingModalityEvents.class, (l)->l.onOnContentRemoved(_eventSource,_eventData));
}
public final static void onOnActivePresenterChanged(final IDispatch __joa__disp, final com.wilutions.mslib.uccollaborationlib.IContentSharingModality _eventSource, final com.wilutions.mslib.uccollaborationlib.IActivePresenterChangedEventData _eventData) throws ComException {
assert(__joa__disp != null);
assert(_eventSource != null);
assert(_eventData != null);
__joa__disp._fireEvent(_IContentSharingModalityEvents.class, (l)->l.onOnActivePresenterChanged(_eventSource,_eventData));
}
public final static void onOnActiveContentChanged(final IDispatch __joa__disp, final com.wilutions.mslib.uccollaborationlib.IContentSharingModality _eventSource, final com.wilutions.mslib.uccollaborationlib.IActiveContentChangedEventData _eventData) throws ComException {
assert(__joa__disp != null);
assert(_eventSource != null);
assert(_eventData != null);
__joa__disp._fireEvent(_IContentSharingModalityEvents.class, (l)->l.onOnActiveContentChanged(_eventSource,_eventData));
}
}
| mit |
mateusz-dziurdziak/gis2014z | src/test/java/pl/edu/pw/elka/gis2014z/writer/TextWriterTest.java | 1215 | package pl.edu.pw.elka.gis2014z.writer;
import org.junit.Test;
import pl.edu.pw.elka.gis2014z.graph.Graph;
import java.io.ByteArrayOutputStream;
import static org.junit.Assert.assertEquals;
public class TextWriterTest {
@Test
public void testWriteEmpty() {
Graph graph = new Graph(0);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
TextWriter.writeGraphToStream(graph, outputStream);
assertEquals("Wierzchołek | sąsiad\n", outputStream.toString());
}
@Test
public void testNonEmptyWithoutEdges() {
Graph graph = new Graph(6);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
TextWriter.writeGraphToStream(graph, outputStream);
assertEquals("Wierzchołek | sąsiad\n", outputStream.toString());
}
@Test
public void testNonEmpty() {
Graph graph = new Graph(4);
graph.addEdge(0, 1);
graph.addEdge(2, 3);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
TextWriter.writeGraphToStream(graph, outputStream);
assertEquals("Wierzchołek | sąsiad\n0 1\n2 3\n", new String(outputStream.toByteArray()));
}
}
| mit |
flesire/ontrack | ontrack-extension-api/src/test/java/net/nemerosa/ontrack/extension/api/support/TestExtensionFeature.java | 571 | package net.nemerosa.ontrack.extension.api.support;
import net.nemerosa.ontrack.model.extension.ExtensionFeature;
import org.springframework.stereotype.Component;
@Component
public class TestExtensionFeature implements ExtensionFeature {
@Override
public String getId() {
return "test";
}
@Override
public String getName() {
return "Test extension";
}
@Override
public String getDescription() {
return "Extensions for tests";
}
@Override
public String getVersion() {
return "test";
}
}
| mit |
wikiteams/emergent-task-allocation | src/intelligence/TasksDiviner.java | 3101 | package intelligence;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import strategies.Strategy;
import tasks.CentralAssignment;
import tasks.HeterophylyExpBased;
import tasks.HomophylyExpBased;
import tasks.Preferential;
import collaboration.Agent;
import collaboration.Task;
/***
* Class chooses which math modules to execute
*
* @author Oskar Jarczyk
* @since 2.0
* @version 3.0
*/
public class TasksDiviner {
public static synchronized Task chooseTask(Agent agent,
Strategy.TaskChoice strategy, Map<String, Task> tasks) {
Task chosen = null;
assert strategy != null;
switch (strategy) {
case HOMOPHYLY:
HomophylyExpBased homophylyExp = new HomophylyExpBased(tasks);
chosen = homophylyExp.concludeMath(agent);
break;
case HETEROPHYLY:
HeterophylyExpBased heterophylyExp = new HeterophylyExpBased(tasks);
chosen = heterophylyExp.concludeMath(agent);
break;
case PREFERENTIAL:
Preferential preferential = new Preferential(tasks);
chosen = preferential.concludeMath(agent);
break;
case RANDOM:
List<Task> internalRandomList;
Collection<Task> coll = tasks.values();
if (coll instanceof List)
internalRandomList = (List<Task>) coll;
else
internalRandomList = new ArrayList<Task>(coll);
Collections.shuffle(internalRandomList);
for (Task singleTaskFromPool : internalRandomList) {
if (singleTaskFromPool.getTaskInternals().size() > 0)
if (singleTaskFromPool.getGeneralAdvance() < 1.) {
chosen = singleTaskFromPool;
break;
}
}
break;
case CENTRAL:
CentralAssignment centralAssignment = new CentralAssignment();
chosen = centralAssignment.concludeMath(agent);
break;
default:
assert false; // there is no default method, so please never happen
break;
}
/* if (chosen != null) {
System.out.println("Agent " + agent.toString() + " uses strategy "
+ agent.getStrategy() + " and chooses task "
+ chosen.getId() + " by " + strategy + " to work on.");
}*/
if (chosen == null) {
/* System.out.println("Agent (" + agent.getId() + ") "
+ agent.toString() + " uses strategy "
+ agent.getStrategy() + " by " + strategy
+ " but didn't found any task to work on.");*/
// Choosing any task left
List<Task> internalRandomList;
Collection<Task> coll = tasks.values();
if (coll instanceof List)
internalRandomList = (List<Task>) coll;
else
internalRandomList = new ArrayList<Task>(coll);
Collections.shuffle(internalRandomList);
for (Task singleTaskFromPool : internalRandomList) {
if (singleTaskFromPool.getTaskInternals().size() > 0)
if (singleTaskFromPool.getGeneralAdvance() < 1.) {
chosen = singleTaskFromPool;
break;
}
}
// assert chosen != null;
//System.out.println("Tick" + agent.getIteration());
//System.out.println("WARNING - No task has been choosen!");
}
return chosen;
}
}
| mit |
nolanlab/vortex | src/main/java/vortex/mahalonobis/MahalonobisDistance.java | 4549 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vortex.mahalonobis;
import cern.colt.matrix.impl.DenseDoubleMatrix1D;
import cern.colt.matrix.impl.DenseDoubleMatrix2D;
import cern.colt.matrix.linalg.Algebra;
import java.sql.SQLException;
import util.MatrixOp;
import util.logger;
/**
*
* @author Zina
*/
public class MahalonobisDistance {
public DenseDoubleMatrix2D covMtx;
public DenseDoubleMatrix1D center;
private DenseDoubleMatrix2D invCovMtx;
private boolean Covariance = false;
public MahalonobisDistance( DenseDoubleMatrix1D center, DenseDoubleMatrix2D covMtx) {
this.covMtx = covMtx;
this.center = center;
this.invCovMtx = (DenseDoubleMatrix2D)Algebra.DEFAULT.inverse(covMtx);
}
@Override
public String toString() {
return "Center: " + center.toString()+"\nCovMtx\n"+
covMtx.toString();
}
public MahalonobisDistance(sandbox.clustering.Cluster c) {
//Compute the center of the cluster
//logger.print("starting Mahalonobis Distance init");
double[][] dataTable = new double[c.size()][];
for (int i = 0; i < c.size(); i++) {
dataTable[i] = c.getClusterMembers()[i].getDatapoint().getVector();
}
sandbox.clustering.ClusterMember[] cm = c.getClusterMembers();
double[] vec = MatrixOp.copy(cm[0].getDatapoint().getVector());
for (int i = 1; i < cm.length; i++) {
double[] vec2 = cm[i].getDatapoint().getVector();
for (int dim = 0; dim < vec2.length; dim++) {
vec[dim] += vec2[dim];
}
}
for (int dim = 0; dim < vec.length; dim++) {
vec[dim] /= c.size();
}
center = new DenseDoubleMatrix1D(vec);
covMtx = new DenseDoubleMatrix2D(CovarianceMatrix.covarianceMatrix(dataTable));
if (!Covariance) {
//logger.print("no covariance, var = 0.25");
for (int i = 0; i < center.size(); i++) {
for (int j = 0; j < center.size(); j++) {
if (i != j) {
covMtx.setQuick(i, j, 0);
}else{
covMtx.setQuick(i, j, Math.max(0.19,covMtx.getQuick(i, j)));
}
}
}
}
invCovMtx = (DenseDoubleMatrix2D) Algebra.DEFAULT.transpose(covMtx);
//Compute covariance matrix of the cluster
//Take the inverse cov matrix
invCovMtx = (DenseDoubleMatrix2D) Algebra.DEFAULT.inverse(covMtx);
}
public MahalonobisDistance(double[][] dataTable) {
// logger.print("init MD");
//Compute the center of the cluster
double[] vec = MatrixOp.copy(dataTable[0]);
for (int i = 1; i < dataTable.length; i++) {
double[] vec2 = dataTable[i];
for (int dim = 0; dim < vec2.length; dim++) {
vec[dim] += vec2[dim];
}
}
for (int dim = 0; dim < vec.length; dim++) {
vec[dim] /= (double) dataTable.length;
}
center = new DenseDoubleMatrix1D(vec);
covMtx = new DenseDoubleMatrix2D(CovarianceMatrix.covarianceMatrix(dataTable));
if ( !Covariance) {
logger.print("no covariance, var = 0.19");
for (int i = 0; i < center.size(); i++) {
for (int j = 0; j < center.size(); j++) {
if (i != j) {
covMtx.setQuick(i, j, 0);
}else{
covMtx.setQuick(i, j, Math.max(0.19,covMtx.getQuick(i, j)));
}
}
}
}
invCovMtx = (DenseDoubleMatrix2D) Algebra.DEFAULT.transpose(covMtx);
//Compute covariance matrix of the cluster
//Take the inverse cov matrix
invCovMtx = (DenseDoubleMatrix2D) Algebra.DEFAULT.inverse(covMtx);
}
public double distTo(double[] x) {
DenseDoubleMatrix1D diff = new DenseDoubleMatrix1D(x.length);
for (int i = 0; i < x.length; i++) {
diff.setQuick(i, x[i] - center.getQuick(i));
}
double dist = Algebra.DEFAULT.mult(diff, Algebra.DEFAULT.mult(invCovMtx, diff));
return Math.sqrt(dist);
}
}
| mit |