repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
cgiannoula/distrib-system
src/ChordNode.java
21371
import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Set; import java.io.*; import java.net.*; /* * ChordNode class * This is the class for a node-server. * Each node implements insert/delete/query requests * and the first node handle also join/depart requests for nodes. */ public class ChordNode extends Thread implements Comparable<Object>{ public static int port = 49152; public static int k = 3; // factor for replicas (if there is no replicas this factor must be 1) public static int mode = 1; // mode = (0,1,2) => (noReplicas(with k=1), Linearizability, EventualConsistency) Chord chord; // Just for debug private int alive; // when alive == 0 the thread dies private int id; private String nodeId; private int predId; private String predNodeId; private int succId; private String succNodeId; private ArrayList<Socket> client = new ArrayList<Socket>(); private Hashtable<String, String> nodeMap = new Hashtable<String, String>(); private Hashtable<String, String> replicaMap = new Hashtable<String, String>(); private ServerSocket s; private Object lock = new Object(); public ChordNode(Chord chrd, int serialNo) throws NoSuchAlgorithmException { this.chord = chrd; String serialNoString = Integer.toString(serialNo); this.nodeId = Hash.hash(serialNoString); this.id = serialNo; this.alive = 1; } @Override public void run() { try { s = new ServerSocket(ChordNode.port + id); for (;;) { if(this.alive == 0) break; Socket incoming = s.accept(); Thread t = new Handler(this, incoming); t.start(); //t.join(); // if we want to serve a request at a time } System.out.println("A thread-node died"); return; } catch (Exception e) { e.printStackTrace(); } } /* * Insert key */ public String insertKey(String key, String value, int s) throws NoSuchAlgorithmException, UnknownHostException, IOException, ClassNotFoundException { String chrdKey = new String(Hash.hash(key)); if ((this.predNodeId.compareTo(this.getNodeId()) > 0)) { if (chrdKey.compareTo(this.predNodeId) > 0 || chrdKey.compareTo(this.getNodeId()) <= 0) { synchronized(this.getLock()){ if (nodeMap.containsKey(chrdKey)) { nodeMap.remove(chrdKey); } nodeMap.put(chrdKey, value); } if(ChordNode.mode == 1){ String message = "insertRep, " + chrdKey + ", " + value + ", " + (ChordNode.k-1) + "\n"; Request req = new Request(this.getSuccId(), message); req.sendRequest(s); return new String("NOT"); }else if(ChordNode.mode == 2){ /* * Create a new thread to insert replicas */ String message = "insertRepLazy, " + chrdKey + ", " + value + ", " + (ChordNode.k-1) + "\n"; Thread t = new HandlerLazy(this, message); t.start(); return new String("OK"); } return new String("OK"); }else { String message = "insertS, " + key + ", " + value + "\n"; Request req = new Request(this.getSuccId(), message); req.sendRequest(s); return new String("NOT"); } } else { if ((chrdKey.compareTo(this.predNodeId) > 0) && (chrdKey.compareTo(this.getNodeId()) <= 0)) { synchronized(this.getLock()){ if (nodeMap.containsKey(chrdKey)) { nodeMap.remove(chrdKey); } nodeMap.put(chrdKey, value); } if(ChordNode.mode == 1){ String message = "insertRep, " + chrdKey + ", " + value + ", " + (ChordNode.k-1) + "\n"; Request req = new Request(this.getSuccId(), message); req.sendRequest(s); return new String("NOT"); }else if(ChordNode.mode == 2){ /* * Create a new thread to insert replicas */ String message = "insertRepLazy, " + chrdKey + ", " + value + ", " + (ChordNode.k-1) + "\n"; Thread t = new HandlerLazy(this, message); t.start(); return new String("OK"); } return new String("OK"); }else { String message = "insertS, " + key + ", " + value + "\n"; Request req = new Request(this.getSuccId(), message); req.sendRequest(s); return new String("NOT"); } } } /* * Delete key from a node */ public String deleteKey(String key, int s) throws NoSuchAlgorithmException, UnknownHostException, IOException, ClassNotFoundException { String chrdKey = new String(Hash.hash(key)); if ((this.predNodeId.compareTo(this.getNodeId()) > 0)) { if (chrdKey.compareTo(this.predNodeId) > 0 || chrdKey.compareTo(this.getNodeId()) <= 0) { Boolean flag; synchronized(this.getLock()){ flag = nodeMap.containsKey(chrdKey); } if (flag) { if(ChordNode.mode == 1){ synchronized(this.getLock()){ nodeMap.remove(chrdKey); } String message = "deleteRep, " + chrdKey + ", " + (ChordNode.k-1) + "\n"; Request req = new Request(this.getSuccId(), message); req.sendRequest(s); return new String("NOT"); }else if(ChordNode.mode == 2){ /* * Create a new thread to delete replicas */ String message = "deleteRepLazy, " + chrdKey + ", " + (ChordNode.k-1) + "\n"; Thread t = new HandlerLazy(this, message); t.start(); } String value1; synchronized(this.getLock()){ value1 = nodeMap.remove(chrdKey); } return value1; } else { System.out.println("This key doesn't exist !"); return new String("NOT"); } }else { String message = "deleteS, " + key + "\n"; Request req = new Request(this.getSuccId(), message); req.sendRequest(s); return new String("NOT"); } } else { if ((chrdKey.compareTo(this.predNodeId) > 0) && (chrdKey.compareTo(this.getNodeId()) <= 0)) { Boolean flag; synchronized(this.getLock()){ flag = nodeMap.containsKey(chrdKey); } if(flag) { if(ChordNode.mode == 1){ synchronized(this.getLock()){ nodeMap.remove(chrdKey); } String message = "deleteRep, " + chrdKey + ", " + (ChordNode.k-1) + "\n"; Request req = new Request(this.getSuccId(), message); req.sendRequest(s); return new String("NOT"); }else if(ChordNode.mode == 2){ /* * Create a new thread to delete replicas */ String message = "deleteRepLazy, " + chrdKey + ", " + (ChordNode.k-1) + "\n"; Thread t = new HandlerLazy(this, message); t.start(); } String value1; synchronized(this.getLock()){ value1 = nodeMap.remove(chrdKey); } return value1; } else { System.out.println("This key doesn't exist !"); return new String("NOT"); } }else { String message = "deleteS, " + key + "\n"; Request req = new Request(this.getSuccId(), message); req.sendRequest(s); return new String("NOT"); } } } /* * The character '*' returns all the keys in the chord * and the string '**' returns the keys in the current node-server. */ public Hashtable<String, String> queryKey(String key, int s) throws NoSuchAlgorithmException, UnknownHostException, IOException, ClassNotFoundException { Hashtable<String, String> keyArray = new Hashtable<String, String>(); String chrdKey = new String(Hash.hash(key)); if (!key.equals("*") && !key.equals("**")) { if (this.predNodeId.compareTo(this.getNodeId()) > 0) { if (chrdKey.compareTo(this.predNodeId) > 0 || chrdKey.compareTo(this.getNodeId()) <= 0) { Boolean flag; synchronized(this.getLock()){ flag = nodeMap.containsKey(chrdKey); } if (flag) { if(ChordNode.mode == 0){ synchronized(this.getLock()){ keyArray.put(key, nodeMap.get(chrdKey)); } return keyArray; }else if(ChordNode.mode == 1){ String message = "queryRep, " + key + ", " + chrdKey + "\n"; Request req = new Request(findInChain(ChordNode.k - 2, this.succId), message); req.sendRequest(s); return null; } return null; } else { System.out.println("This key doesn't exist !"); keyArray.put("The key doesn't exist", "The key doesn't exist"); return keyArray; } } else { String message = "queryS, " + key + "\n"; Request req = new Request(this.getSuccId(), message); req.sendRequest(s); return null; } } else { if ((chrdKey.compareTo(this.predNodeId) > 0) && (chrdKey.compareTo(this.getNodeId()) <= 0)) { Boolean flag; synchronized(this.getLock()){ flag = nodeMap.containsKey(chrdKey); } if (flag) { if(ChordNode.mode == 0){ synchronized(this.getLock()){ keyArray.put(key, nodeMap.get(chrdKey)); } return keyArray; }else if(ChordNode.mode == 1){ String message = "queryRep, " + key + ", " + chrdKey + "\n"; Request req = new Request(findInChain(ChordNode.k - 2, this.succId), message); req.sendRequest(s); return null; } return null; } else { System.out.println("This key doesn't exist !"); keyArray.put("The key doesn't exist", "The key doesn't exist"); return keyArray; } } else { String message = "queryS, " + key + "\n"; Request req = new Request(this.getSuccId(), message); req.sendRequest(s); return null; } } } else if (!key.equals("*")) { return this.nodeMap; } else { return requestAllKeys(); } } /* * Request for query for all keys must be transfered to all nodes */ public Hashtable<String, String> requestAllKeys() throws UnknownHostException, ClassNotFoundException, IOException { Hashtable<String, String> response = new Hashtable<String, String>(); if (!this.nodeMap.isEmpty()) { response.putAll(this.getHashTable()); } int succ = this.succId; String message1 = "getNodeMap" + "\n"; String message2 = "find succId" + "\n"; while (succ != this.id) { Request req1 = new Request(succ, message1); Hashtable <String, String> readObject1 = req1.queryRequest(); if (!readObject1.isEmpty()) response.putAll(readObject1); Request req2 = new Request(succ, message2); succ = req2.IdRequest(); } return response; } /* * Search if key exists in replicaMap OR nodeMap * if not query succNode */ public Hashtable<String, String> queryKeyLazy(String key,int begId, int s, int cycle) throws NoSuchAlgorithmException, UnknownHostException, IOException, ClassNotFoundException { Hashtable<String, String> keyArray = new Hashtable<String, String>(); String chrdKey = new String(Hash.hash(key)); //System.out.print(chrdKey); System.out.println(begId); if(this.getSerialNo() == begId && cycle == 1){ System.out.println("This key doesn't exist !"); keyArray.put("The key doesn't exist", "The key doesn't exist"); return keyArray; } if (!key.equals("*") && !key.equals("**")) { Boolean flag; synchronized(this.getLock()){ flag = this.replicaMap.containsKey(chrdKey); } if(flag){ synchronized(this.getLock()){ keyArray.put(key, this.replicaMap.get(chrdKey)); } return keyArray; }else{ String message = "queryS, " + key + ", " + begId + "\n"; Request req = new Request(this.getSuccId(), message); req.sendRequest(s); return null; } } else if (!key.equals("*")) { return this.nodeMap; } else { return requestAllKeys(); } } /* * Join request for a node * It gives the serialNodeNo as input for the new node */ public String joinNode(int nodeId) throws NoSuchAlgorithmException, UnknownHostException, ClassNotFoundException, IOException, InterruptedException { String response = new String("OK"); /* * Find position in the chord * Set new neighbors * Grab the keys from successor * Join the chord */ Hashtable<String, String> chrdNodeMap = new Hashtable<String, String>(); ChordNode chrdNode = this.chord.createNode(nodeId); // Add to nodeList Just for debug // SOS check if the node with nodeId already exists in the chord !!! int succ = this.getSerialNo(); int pred = this.predId; String succVal = this.getNodeId(); String predVal = this.predNodeId; int bool = 0; String message1 = "find succId" + "\n"; String message2 = "find succNodeId" + "\n"; while (true){ if(predVal.compareTo(succVal) > 0){ if((chrdNode.getNodeId().compareTo(predVal) > 0) || (chrdNode.getNodeId().compareTo(succVal) < 0)) bool = 1; }else{ if((chrdNode.getNodeId().compareTo(predVal) > 0) && (chrdNode.getNodeId().compareTo(succVal) < 0)) bool = 1; } if(bool == 1) break; pred = succ; predVal = succVal; if(succ == this.getSerialNo()){ succ = this.getSuccId(); succVal = this.getSuccNodeId(); }else{ int temp = succ; Request req1 = new Request(succ, message1); succ = req1.IdRequest(); Request req2 = new Request(temp, message2); succVal = req2.NodeIdRequest(); } } //Succ's HashTable String message = "getNodeMap" + "\n"; Request req = new Request(succ, message); Hashtable <String, String> tbl = req.queryRequest(); Enumeration<String> enumer = tbl.keys(); //Succ's last in chain int succLast = findInChain(ChordNode.k - 1, succ); while (enumer.hasMoreElements()) { String key = (String) enumer.nextElement(); if (key.compareTo(chrdNode.getNodeId()) <= 0 || key.compareTo(chrdNode.getPredNodeId()) > 0) { String value = tbl.get(key); String msg = "deleteWH, " + key + "\n"; Request request = new Request(succ, msg); request.sendReceiveRequest(); // put key in new node's hashTable chrdNodeMap.put(key, value); if(ChordNode.k != 1){ //insert keys to succ's replicaMap msg = "insertRepWH, " + key + ", " + value + "\n"; request = new Request(succ, msg); request.sendReceiveRequest(); //delete keys to succ's lastSucc replicaMap msg = "deleteRepWH, " + key + "\n"; request = new Request(succLast, msg); request.sendReceiveRequest(); } } } chrdNode.setHashTable(chrdNodeMap); if(ChordNode.k != 1){ int currK = 0; int predK = pred; while(currK != ChordNode.k - 1){ //Get NodeMap from k-1 predecessors String msg = "getNodeMap, " + "\n"; Request request = new Request(predK, msg); chrdNode.replicaMap.putAll(request.queryRequest()); //(k-1) predecessors must delete their NodeMap from their lastSucc's replicasMap msg = "deleteTableFromLastInChain, " + "\n"; request = new Request(predK, msg); request.sendReceiveRequest(); msg = "find predId, " + "\n"; request = new Request(predK, msg); predK = request.IdRequest(); currK++; } } // Set new neighbors chrdNode.setPredId(pred); chrdNode.setPredNodeId(predVal); chrdNode.setSuccId(succ); chrdNode.setSuccNodeId(succVal); String msg1 = "Set Pred, " + chrdNode.getSerialNo() + ", " + chrdNode.getNodeId() + "\n"; Request request1 = new Request(succ, msg1); request1.sendReceiveRequest(); String msg2 = "Set Succ, " + chrdNode.getSerialNo() + ", " + chrdNode.getNodeId() + "\n"; Request request2 = new Request(pred, msg2); request2.sendReceiveRequest(); return response; } public void deleteTableFromLast()throws UnknownHostException, ClassNotFoundException, IOException{ int last = findInChain(k-2, this.succId); Set<String> keys = this.nodeMap.keySet(); Iterator<String> itr = keys.iterator(); // Delete without hashing the key while(itr.hasNext()){ String str = itr.next(); String msg = "deleteRepWH, " + str + "\n"; Request request = new Request(last, msg); request.sendReceiveRequest(); } } /* * Depart request */ public String departNode(int nodeId) throws NoSuchAlgorithmException, IOException, ClassNotFoundException, InterruptedException { String response = new String("OK"); /* * Get successor and hashtable of deleted node * Release node from chord and set the new neighbors * Transfer hashtable to successor */ int succLast = findInChain(ChordNode.k - 1, this.succId); Set<String> keys = this.nodeMap.keySet(); Iterator<String> itr = keys.iterator(); // Insert without hashing the key while(itr.hasNext()){ String str = itr.next(); String msg = "insertWH, " + str + ", " + this.nodeMap.get(str) + "\n"; Request request = new Request(this.succId, msg); request.sendReceiveRequest(); if(ChordNode.k != 1){ // Delete replicas from successor msg = "deleteRepWH, " + str + "\n"; request = new Request(this.succId, msg); request.sendReceiveRequest(); // Insert keys in replicaMap to the last node in successor's chain msg = "insertRepWH, " + str + ", " + this.nodeMap.get(str) + "\n"; request = new Request(succLast, msg); request.sendReceiveRequest(); } } this.chord.nodeList.remove(this); // Just for debug String msg1 = "Set Pred, " + this.predId + ", " + this.predNodeId + "\n"; Request request1 = new Request(this.succId, msg1); request1.sendReceiveRequest(); String msg2 = "Set Succ, " + this.succId + ", " + this.succNodeId + "\n"; Request request2 = new Request(this.predId, msg2); request2.sendReceiveRequest(); if(ChordNode.k != 1){ //Predecessors must transfer their table to new lastSucc in their chain int pr = this.predId; int currK = 0; String message = "find predId" + "\n"; while(currK != ChordNode.k - 1){ String msg3 = "transferTableToLastInChain" + "\n"; Request request3 = new Request(pr, msg3); request3.sendReceiveRequest(); Request req2 = new Request(pr, message); pr = req2.IdRequest(); currK++; } } this.alive = 0; // the thread dies return response; } public void transferTableToLast() throws UnknownHostException, ClassNotFoundException, IOException{ int last = findInChain(k-2, this.succId); Set<String> keys = this.nodeMap.keySet(); Iterator<String> itr = keys.iterator(); // Insert without hashing the key while(itr.hasNext()){ String str = itr.next(); String msg = "insertRepWH, " + str + ", " + this.nodeMap.get(str) + "\n"; Request request = new Request(last, msg); request.sendReceiveRequest(); } } public int findInChain(int kth, int succR) throws UnknownHostException, ClassNotFoundException, IOException{ if(kth < 1) return 0; int currK = 0; int succ = succR; String message = "find succId" + "\n"; while (currK != kth) { Request req = new Request(succ, message); succ = req.IdRequest(); currK++; } return succ; } public String putReplicas(String key, String value, int k, int s) throws UnknownHostException, ClassNotFoundException, IOException { synchronized(this.getLock()){ if(this.replicaMap.containsKey(key)){ this.replicaMap.remove(key); } this.replicaMap.put(key, value); } if(k == 1){ return new String("OK"); }else{ String message = "insertRep, " + key + ", " + value + ", " + (k-1) + "\n"; Request req = new Request(this.getSuccId(), message); req.sendRequest(s); return new String("NOT"); } } public String removeReplicas(String key, int k, int s) throws UnknownHostException, ClassNotFoundException, IOException { Boolean flag; synchronized(this.getLock()){ flag = this.replicaMap.containsKey(key); } if(!flag){ return new String("ERROR"); } String value; synchronized(this.getLock()){ value = this.replicaMap.remove(key); } if(k == 1){ return value; }else{ String message = "deleteRep, " + key + ", " + (k-1) + "\n"; Request req = new Request(this.succId, message); req.sendRequest(s); return new String("NOT"); } } public void setPredId(int pred) { this.predId = pred; } public int getPredId() { return this.predId; } public void setSuccId(int succ) { this.succId = succ; } public int getSuccId() { return this.succId; } public void setPredNodeId(String pred) { this.predNodeId = pred; } public String getPredNodeId() { return this.predNodeId; } public void setSuccNodeId(String succ) { this.succNodeId = succ; } public String getSuccNodeId() { return this.succNodeId; } public void setSerialNo(int serialNo) { this.id = serialNo; } public int getSerialNo() { return this.id; } public String getNodeId() { return this.nodeId; } public void setHashTable(Hashtable<String, String> hash) { this.nodeMap = hash; } public Hashtable<String, String> getHashTable() { return this.nodeMap; } public void setRepTable(Hashtable<String, String> rep) { this.replicaMap = rep; } public Hashtable<String, String> getRepTable() { return this.replicaMap; } public void setClient(Socket incoming) { this.client.add(incoming); } public Socket getClient(int i){ Socket ret; synchronized(this.getLock()){ ret = this.client.get(i); } return ret; } public ArrayList<Socket> getClientList(){ return this.client; } public Object getLock(){ return this.lock; } @Override public int compareTo(Object arg0) { // TODO Auto-generated method stub ChordNode s = (ChordNode) arg0; return this.nodeId.compareTo(s.getNodeId()); } }
mit
greatjapa/halfcab
src/main/java/skatepark/halfcab/redis/AbstractAgg.java
1522
package skatepark.halfcab.redis; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import redis.clients.jedis.Jedis; import redis.clients.jedis.Pipeline; import skatepark.halfcab.agg.IAgg; abstract class AbstractAgg implements IAgg { RedisKey redisKey; Jedis jedis; AbstractAgg(RedisKey redisKey, Jedis jedis) { Objects.requireNonNull(redisKey, "redisKey should not be null."); Objects.requireNonNull(jedis, "jedis should not be null."); this.redisKey = redisKey; this.jedis = jedis; } @Override public boolean exists() { String key = redisKey.toString(); String control = redisKey.toControl(); return jedis.exists(key) || jedis.scard(control) > 0; } @Override public void delete() { Pipeline pipelined = jedis.pipelined(); String key = redisKey.toString(); for (String c : redisKey.controls()) { pipelined.srem(c, key); } pipelined.del(key); pipelined.del(redisKey.toControl()); pipelined.sync(); } @Override public String toString() { Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(toJson()); } List<RedisKey> getNestedKeys() { return jedis.smembers(redisKey.toControl()).stream() .map(RedisKey::parse) .collect(Collectors.toList()); } }
mit
oleflohic/formation-dta
pizzeria-dao/src/main/java/fr/pizzeria/dao/factory/GenericDaoFactoryImpl.java
891
package fr.pizzeria.dao.factory; import org.apache.commons.lang3.NotImplementedException; import fr.pizzeria.dao.client.IClientDao; import fr.pizzeria.dao.pizza.IPizzaDao; public class GenericDaoFactoryImpl implements DaoFactory { private IPizzaDao pizzaDao; private IClientDao clientDao; public GenericDaoFactoryImpl(IPizzaDao pizzaDao, IClientDao clientDao) { // TODO ajouter ICommandeDao super(); this.pizzaDao = pizzaDao; this.clientDao = clientDao; } @Override public IPizzaDao getPizzaDao() { check(pizzaDao); return pizzaDao; } private void check(Object implementation) { if (implementation == null) { throw new NotImplementedException("Dao non implémenté"); } } @Override public IClientDao getClientDao() { check(clientDao); return clientDao; } // TODO getters pour client et commande DAO }
mit
juniormesquitadandao/report4all
lib/src/net/sf/jasperreports/repo/FileRepositoryServiceExtensionsRegistryFactory.java
2952
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.repo; import net.sf.jasperreports.engine.DefaultJasperReportsContext; import net.sf.jasperreports.engine.JRPropertiesMap; import net.sf.jasperreports.engine.JRPropertiesUtil; import net.sf.jasperreports.extensions.DefaultExtensionsRegistry; import net.sf.jasperreports.extensions.ExtensionsRegistry; import net.sf.jasperreports.extensions.ExtensionsRegistryFactory; import net.sf.jasperreports.extensions.SingletonExtensionRegistry; /** * @author Teodor Danciu (teodord@users.sourceforge.net) * @version $Id: FileRepositoryServiceExtensionsRegistryFactory.java 7199 2014-08-27 13:58:10Z teodord $ */ public class FileRepositoryServiceExtensionsRegistryFactory implements ExtensionsRegistryFactory { /** * */ public final static String FILE_REPOSITORY_PROPERTY_PREFIX = DefaultExtensionsRegistry.PROPERTY_REGISTRY_PREFIX + "file.repository."; /** * Specifies the file repository root location. */ public final static String PROPERTY_FILE_REPOSITORY_ROOT = FILE_REPOSITORY_PROPERTY_PREFIX + "root"; /** * Flag property that indicates whether the absolute path to be used instead, when resources are not found in the file repository. */ public final static String PROPERTY_FILE_REPOSITORY_RESOLVE_ABSOLUTE_PATH = FILE_REPOSITORY_PROPERTY_PREFIX + "resolve.absolute.path"; /** * */ public ExtensionsRegistry createRegistry(String registryId, JRPropertiesMap properties) { String root = JRPropertiesUtil.getInstance(DefaultJasperReportsContext.getInstance()).getProperty(properties, PROPERTY_FILE_REPOSITORY_ROOT); boolean resolveAbsolutePath = JRPropertiesUtil.getInstance(DefaultJasperReportsContext.getInstance()).getBooleanProperty(properties, PROPERTY_FILE_REPOSITORY_RESOLVE_ABSOLUTE_PATH, false); return new SingletonExtensionRegistry<RepositoryService>(RepositoryService.class, new FileRepositoryService(DefaultJasperReportsContext.getInstance(), root, resolveAbsolutePath)); } }
mit
wolfgang-lausenhammer/Okeanos
okeanos.model.impl/src/test/java/okeanos/model/internal/drivers/readers/StaticLoadLoadProfileReaderTest.java
2750
package okeanos.model.internal.drivers.readers; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNull.notNullValue; import static org.junit.Assert.assertThat; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentSkipListMap; import okeanos.data.services.Constants; import okeanos.model.internal.drivers.readers.StaticLoadLoadProfileReader.XYEntity; import org.joda.time.DateTime; import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; /** * The Class StaticLoadLoadProfileReaderTest. * * @author Wolfgang Lausenhammer */ public class StaticLoadLoadProfileReaderTest { /** The Constant FOUR. */ private static final int FOUR = 4; /** The Constant HUNDRED. */ private static final double HUNDRED = 100.0; /** * Test get xy from load profile. */ @Test public void testGetXYFromLoadProfile() { Map<DateTime, Double> loadProfile = new ConcurrentSkipListMap<>(); DateTime dateTime1 = DateTime.now(); DateTime dateTime2 = dateTime1.plusMinutes(Constants.SLOT_INTERVAL); DateTime dateTime3 = dateTime2.plusMinutes(Constants.SLOT_INTERVAL); DateTime dateTime4 = dateTime3.plusMinutes(Constants.SLOT_INTERVAL); loadProfile.put(dateTime1, 0.0); loadProfile.put(dateTime2, 0.0); loadProfile.put(dateTime3, HUNDRED); loadProfile.put(dateTime4, HUNDRED); XYEntity<double[]> xy = StaticLoadLoadProfileReader .getXYFromLoadProfile(loadProfile); assertThat(xy, is(notNullValue())); assertThat( xy.getX(), is(equalTo(new double[] { dateTime1.getMillis(), dateTime2.getMillis(), dateTime3.getMillis(), dateTime4.getMillis() }))); assertThat(xy.getY(), is(equalTo(new double[] { 0, 0, HUNDRED, HUNDRED }))); } /** * Test read load profile. * * @throws IOException * Signals that an I/O exception has occurred. */ @Test public void testReadLoadProfile() throws IOException { Resource loadProfileResource = new ClassPathResource( "test-load-profile.json"); Map<DateTime, Double> loadProfile = StaticLoadLoadProfileReader .readLoadProfile(loadProfileResource); assertThat(loadProfile.entrySet(), hasSize(equalTo(FOUR))); assertThat(loadProfile.get(DateTime.parse("2014-04-25T00:00:00Z")), is(equalTo(0.0))); assertThat(loadProfile.get(DateTime.parse("2014-04-25T00:15:00Z")), is(equalTo(0.0))); assertThat(loadProfile.get(DateTime.parse("2014-04-25T00:30:00Z")), is(equalTo(HUNDRED))); assertThat(loadProfile.get(DateTime.parse("2014-04-25T00:45:00Z")), is(equalTo(HUNDRED))); } }
mit
SyedShaheryar/OOP-Programs
src/Practice/Rectangle.java
458
package Practice; public class Rectangle { private float length; private float width; public Rectangle(){ //default constructor this.length = 13.33f; //why its showing error when its a float type? this.width = 33.31f; } public Rectangle (float l, float r){ this.length = l; this.width = r; } public Rectangle (Rectangle r){ //copy constructor this.length = r.length; this.width = r.width; } public double getArea(){ return length * width; } }
mit
LandvibeDev/codefolio
codefolio/src/main/java/com/codefolio/logger/LoggerAspect.java
1115
package com.codefolio.logger; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; @Aspect public class LoggerAspect { protected Log log = LogFactory.getLog(LoggerAspect.class); static String name = ""; static String type = ""; @Around("execution(* com..controller.*Controller.*(..)) or execution(* com..service.*Impl.*(..)) or execution(* com..dao.*DAO.*(..))") public Object logPrint(ProceedingJoinPoint joinPoint) throws Throwable { type = joinPoint.getSignature().getDeclaringTypeName(); if (type.indexOf("Controller") > -1) { name = "Controller \t: "; } else if (type.indexOf("Service") > -1) { name = "ServiceImpl \t: "; } else if (type.indexOf("DAO") > -1) { name = "DAO \t\t: "; } log.debug(name + type + "." + joinPoint.getSignature().getName() + "()"); return joinPoint.proceed(); } }
mit
zsxwing/jappblog
src/zblog/config/ZblogConfig.java
738
package zblog.config; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; public class ZblogConfig { private static Logger logger = Logger .getLogger(ZblogConfig.class.getName()); private static Configuration instance; static { try { instance = new PropertiesConfiguration(ZblogConfig.class .getResource("config.properties")); } catch (ConfigurationException e) { logger.log(Level.SEVERE, e.getMessage()); } } public static Configuration getInstance() { return instance; } }
mit
Meronat/Guilds
src/main/java/com/ichorpowered/guilds/command/command/officer/teleportation/package-info.java
1368
/* * This file is part of Guilds, licensed under the MIT License. * * Copyright (c) 2017 IchorPowered <http://ichorpowered.com> * 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. */ @org.spongepowered.api.util.annotation.NonnullByDefault package com.ichorpowered.guilds.command.command.officer.teleportation;
mit
oroca/oroca_rov
Software/ROV_IMU/RovDrawModel/Processing/libraries/G4P/src/g4p_controls/GPanel.java
29615
<<<<<<< HEAD /* Part of the G4P library for Processing http://www.lagers.org.uk/g4p/index.html http://sourceforge.net/projects/g4p/files/?source=navbar Copyright (c) 2012 Peter Lager This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package g4p_controls; import g4p_controls.HotSpot.HSrect; import java.awt.Font; import java.awt.Graphics2D; import java.awt.font.TextLayout; import java.util.LinkedList; import processing.core.PApplet; import processing.event.MouseEvent; /** * A component that can be used to group GUI components that can be * dragged, collapsed (leaves title tab only) and un-collapsed. * * When created the Panel is collapsed by default. To open the panel * use setCollapsed(true); after creating it. <br> * * Once a component has been added the x/y coordinates of the control are * calculated to be the centre of the panel to the centre of the control. This * is to facilitate rotating of controls on panels * * @author Peter Lager * */ public class GPanel extends GTextBase { static protected int COLLAPSED_BAR_SPOT = 1; static protected int EXPANDED_BAR_SPOT = 2; static protected int SURFACE_SPOT = 0; /** Whether the panel is displayed in full or tab only */ protected boolean tabOnly = false; /** The height of the tab calculated from font height + padding */ protected int tabHeight, tabWidth; /** Used to restore position when closing panel */ protected float dockX, dockY; // Defines the area that the panel must fit inside. protected float lowX, highX, lowY, highY; /** true if the panel is being dragged */ protected boolean beingDragged = false; protected boolean draggable = true; protected boolean collapsible = true; /** * Create a Panel that comprises of 2 parts the tab which is used to * select and move the panel and the container window below the tab which * is used to hold other components. <br> * If the panel fits inside the display window then its position will be * constrained so that it can't be dragged outside the viewable area. * Otherwise no constraint is applied. * * @param theApplet the PApplet reference * @param p0 horizontal position * @param p1 vertical position * @param p2 width of the panel * @param p3 height of the panel (excl. tab) */ public GPanel(PApplet theApplet, float p0, float p1, float p2, float p3) { this(theApplet, p0, p1, p2, p3, "Panel "); } /** * Create a Panel that comprises of 2 parts the tab which is used to * select and move the panel and the container window below the tab which * is used to hold other components. <br> * If the panel fits inside the display window then its position will be * constrained so that it can't be dragged outside the viewable area. * Otherwise no constraint is applied. * * @param theApplet the PApplet reference * @param p0 horizontal position * @param p1 vertical position * @param p2 width of the panel * @param p3 height of the panel (excl. tab) * @param text to appear on tab */ public GPanel(PApplet theApplet, float p0, float p1, float p2, float p3, String text) { super(theApplet, p0, p1, p2, p3); // Set the values used to constrain movement of the panel if(x < 0 || y < 0 || x + width > winApp.width || y+ height > winApp.height) clearDragArea(); else setDragArea(); // Create the list of children children = new LinkedList<GAbstractControl>(); setText(text); calcHotSpots(); constrainPanelPosition(); opaque = true; dockX = x; dockY = y; z = Z_PANEL; createEventHandler(G4P.sketchWindow, "handlePanelEvents", new Class<?>[]{ GPanel.class, GEvent.class }, new String[]{ "panel", "event" } ); registeredMethods = DRAW_METHOD | MOUSE_METHOD; cursorOver = HAND; G4P.registerControl(this); } /** * This needs to be called if the tab text is changed */ private void calcHotSpots(){ hotspots = new HotSpot[]{ new HSrect(COLLAPSED_BAR_SPOT, 0, 0, tabWidth, tabHeight), // tab text area new HSrect(EXPANDED_BAR_SPOT, 0, 0, width, tabHeight), // tab non-text area new HSrect(SURFACE_SPOT, 0, tabHeight, width, height - tabHeight) // panel content surface }; } /** * This panel is being added to another additional changes that need to be made this control * is added to another. <br> * * In this case we need to set the constraint limits to keep inside the parent. * * @param p the parent */ protected void addToParent(GAbstractControl p){ // Will this fit inside the parent panel if(width > p.width || height > p.height){ //No draggable = false; } else { lowX = -p.width/2; highX = p.width/2; lowY = -p.height/2; highY = p.height/2; } } public void setText(String text){ super.setText(text); buffer.beginDraw(); stext.getLines(buffer.g2); buffer.endDraw(); tabHeight = (int) (stext.getMaxLineHeight() + 4); tabWidth = (int) (stext.getMaxLineLength() + 8); calcHotSpots(); bufferInvalid = true; } public void setFont(Font font) { if(font != null) localFont = font; tabHeight = (int) (1.2f * localFont.getSize() + 2); buffer.g2.setFont(localFont); bufferInvalid = true; calcHotSpots(); bufferInvalid = true; } /** * What to do when the FPanel loses focus. */ protected void loseFocus(GAbstractControl grabber){ focusIsWith = null; beingDragged = false; } /** * Draw the panel. * If tabOnly == true * then display the tab only * else * draw tab and all child (added) components */ public void draw(){ if(!visible) return; winApp.pushStyle(); // Update buffer if invalid updateBuffer(); winApp.pushMatrix(); // Perform the rotation winApp.translate(cx, cy); winApp.rotate(rotAngle); // If opaque draw the panel tab and back if(opaque){ winApp.pushMatrix(); // Move matrix to line up with top-left corner winApp.translate(-halfWidth, -halfHeight); // Draw buffer winApp.imageMode(PApplet.CORNER); if(alphaLevel < 255) winApp.tint(TINT_FOR_ALPHA, alphaLevel); winApp.image(buffer, 0, 0); winApp.popMatrix(); } // Draw the children System.out.println(tabOnly); if(!tabOnly){ if(children != null){ for(GAbstractControl c : children) c.draw(); } } winApp.popMatrix(); winApp.popStyle(); } protected void updateBuffer(){ if(bufferInvalid) { bufferInvalid = false; buffer.beginDraw(); Graphics2D g2d = buffer.g2; g2d.setFont(localFont); buffer.clear(); // Draw tab buffer.noStroke(); buffer.fill(palette[4].getRGB()); if(tabOnly){ buffer.rect(0, 0, tabWidth, tabHeight); } else { buffer.rect(0, 0, width, tabHeight); } // Draw tab text (panel name) stext.getLines(g2d); g2d.setColor(palette[2]); TextLayout tl = stext.getTLIforLineNo(0).layout; tl.draw(g2d, 4, 2 + tl.getAscent()); // Draw extended panel background if(!tabOnly){ buffer.noStroke(); buffer.fill(palette[5].getRGB()); buffer.rect(0, tabHeight, width, height - tabHeight); } buffer.endDraw(); } } /** * Determines if a particular pixel position is over the panel taking * into account whether it is collapsed or not. */ public boolean isOver(float x, float y){ calcTransformedOrigin(winApp.mouseX, winApp.mouseY); currSpot = whichHotSpot(ox, oy); return (tabOnly)? currSpot == COLLAPSED_BAR_SPOT : currSpot == EXPANDED_BAR_SPOT | currSpot == COLLAPSED_BAR_SPOT; } /** * All GUI components are registered for mouseEvents */ public void mouseEvent(MouseEvent event){ if(!visible || !enabled || !available) return; calcTransformedOrigin(winApp.mouseX, winApp.mouseY); currSpot = whichHotSpot(ox, oy); // Is mouse over the panel tab (taking into account extended with when not collapsed) boolean mouseOver = (tabOnly)? currSpot == COLLAPSED_BAR_SPOT : currSpot == EXPANDED_BAR_SPOT | currSpot == COLLAPSED_BAR_SPOT; if(mouseOver || focusIsWith == this) cursorIsOver = this; else if(cursorIsOver == this) cursorIsOver = null; switch(event.getAction()){ case MouseEvent.PRESS: if(focusIsWith != this && mouseOver && z >= focusObjectZ()){ takeFocus(); beingDragged = false; } break; case MouseEvent.CLICK: if(focusIsWith == this && collapsible){ tabOnly = !tabOnly; // Perform appropriate action depending on collapse state setCollapsed(tabOnly); if(tabOnly){ x = dockX; y = dockY; } else { dockX = x; dockY = y; // Open panel move on screen if needed if(y + height > winApp.height) y = winApp.height - height; if(x + width > winApp.width) x = winApp.width - width; } // Maintain centre for drawing purposes cx = x + width/2; cy = y + height/2; constrainPanelPosition(); if(tabOnly) fireEvent(this, GEvent.COLLAPSED); else fireEvent(this, GEvent.EXPANDED); bufferInvalid = true; beingDragged = false; // This component does not keep the focus when clicked loseFocus(null); } break; case MouseEvent.RELEASE: // After dragging NOT clicking if(focusIsWith == this){ if(beingDragged){ // Remember the dock position when the mouse has // been released after the panel has been dragged dockX = x; dockY = y; beingDragged = false; loseFocus(null); } } break; case MouseEvent.DRAG: if(focusIsWith == this && draggable ){//&& parent == null){ // Maintain centre for drawing purposes cx += (winApp.mouseX - winApp.pmouseX); cy += (winApp.mouseY - winApp.pmouseY); // Update x and y positions x = cx - width/2; y = cy - height/2; constrainPanelPosition(); beingDragged = true; fireEvent(this, GEvent.DRAGGED); } break; } } /** * Determines whether to show the tab and panel back colour. If the * parameter is the same as the current state then no changes will * be made. <br> * If the parameter is false then the panel will be <br> * <ul> * <li>expanded</li> * <li>made non-collasible</li> * <li>made unavailable to mouse control (so can't be dragged)</li> * </ul> * If the parameter is true then the panel will remain non-collapsible * and the user must change this if required. <br> * @param opaque */ public void setOpaque(boolean opaque){ if(this.opaque == opaque) return; // no change if(!opaque){ setCollapsed(false); setCollapsible(false); } available = opaque; this.opaque = opaque; } /** * This method is used to discover whether the panel is being * dragged to a new position on the screen. * @return true if being dragged to a new position */ public boolean isDragging(){ return beingDragged; } /** * Sets whether the panel can be dragged by the mouse or not. * @param draggable */ public void setDraggable(boolean draggable){ this.draggable = draggable; } /** * Can we drag this panel with the mouse? * @return true if draggable */ public boolean isDraggable(){ return draggable; } /** * Collapse or open the panel * @param collapse */ public void setCollapsed(boolean collapse){ if(collapsible){ tabOnly = collapse; // If we open the panel make sure it fits on the screen but if we collapse // the panel disable the panel controls but leave the panel available if(tabOnly){ setAvailable(false); available = true; // Needed so we can click on the title bar } else { setAvailable(true); } } bufferInvalid = true; } /** * Find out if the panel is collapsed * @return true if collapsed */ public boolean isCollapsed(){ return tabOnly; } /** * Determine whether the panel can be collapsed when the title bar is clicked. <br> * * If this is set to false then the panel will be expanded and it will * not be possible to collapse it until set back to true. * */ public void setCollapsible(boolean c){ collapsible = c; if(c == false){ tabOnly = false; setAvailable(true); bufferInvalid = true; } } /** * Is this panel collapsible */ public boolean isCollapsible(){ return collapsible; } public int getTabHeight(){ return tabHeight; } /** * Provided the panel is physically small enough this method will set the area * within which the panel can be dragged and move the panel inside the area if * not already inside. <br> * * @param xMin * @param yMin * @param xMax * @param yMax * @return true if the constraint was applied successfully else false */ public boolean setDragArea(float xMin, float yMin, float xMax, float yMax){ if(xMax - xMin < width || yMax - yMin < height){ if(G4P.showMessages) System.out.println("The constraint area is too small for this panel - request ignored"); return false; } lowX = xMin; lowY = yMin; highX = xMax; highY = yMax; constrainPanelPosition(); return true; } /** * Provided the panel is small enough to fit inside the display area then * the panel will be constrained to fit inside the display area. * * @return true if the constraint was applied successfully else false */ public boolean setDragArea(){ return setDragArea(0, 0, winApp.width, winApp.height); } /** * Remove any drag constraint from this panel. */ public void clearDragArea(){ lowX = lowY = -Float.MAX_VALUE; highX = highY = Float.MAX_VALUE; } /** * Ensures that the panel tab and panel body if open does not * extend off the screen. */ private void constrainPanelPosition(){ // Calculate the size of the visible part of the panel int w = (int) ((tabOnly)? tabWidth : width); int h = (int) ((tabOnly)? tabHeight : height); // Constrain horizontally if(x < lowX) x = lowX; else if(x + w > highX) x = (int) (highX - w); // Constrain vertically if(y < lowY) y = lowY; else if(y + h > highY) y = highY - h; // Maintain centre for cx = x + width/2; cy = y + height/2; } public String toString(){ return tag + " [" + x + ", " + y+"]" + " [" + cx + ", " + cy+"]"+ " [" + dockX + ", " + dockY+"]"; } } ======= /* Part of the G4P library for Processing http://www.lagers.org.uk/g4p/index.html http://sourceforge.net/projects/g4p/files/?source=navbar Copyright (c) 2012 Peter Lager This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package g4p_controls; import g4p_controls.HotSpot.HSrect; import java.awt.Font; import java.awt.Graphics2D; import java.awt.font.TextLayout; import java.util.LinkedList; import processing.core.PApplet; import processing.event.MouseEvent; /** * A component that can be used to group GUI components that can be * dragged, collapsed (leaves title tab only) and un-collapsed. * * When created the Panel is collapsed by default. To open the panel * use setCollapsed(true); after creating it. <br> * * Once a component has been added the x/y coordinates of the control are * calculated to be the centre of the panel to the centre of the control. This * is to facilitate rotating of controls on panels * * @author Peter Lager * */ public class GPanel extends GTextBase { static protected int COLLAPSED_BAR_SPOT = 1; static protected int EXPANDED_BAR_SPOT = 2; static protected int SURFACE_SPOT = 0; /** Whether the panel is displayed in full or tab only */ protected boolean tabOnly = false; /** The height of the tab calculated from font height + padding */ protected int tabHeight, tabWidth; /** Used to restore position when closing panel */ protected float dockX, dockY; // Defines the area that the panel must fit inside. protected float lowX, highX, lowY, highY; /** true if the panel is being dragged */ protected boolean beingDragged = false; protected boolean draggable = true; protected boolean collapsible = true; /** * Create a Panel that comprises of 2 parts the tab which is used to * select and move the panel and the container window below the tab which * is used to hold other components. <br> * If the panel fits inside the display window then its position will be * constrained so that it can't be dragged outside the viewable area. * Otherwise no constraint is applied. * * @param theApplet the PApplet reference * @param p0 horizontal position * @param p1 vertical position * @param p2 width of the panel * @param p3 height of the panel (excl. tab) */ public GPanel(PApplet theApplet, float p0, float p1, float p2, float p3) { this(theApplet, p0, p1, p2, p3, "Panel "); } /** * Create a Panel that comprises of 2 parts the tab which is used to * select and move the panel and the container window below the tab which * is used to hold other components. <br> * If the panel fits inside the display window then its position will be * constrained so that it can't be dragged outside the viewable area. * Otherwise no constraint is applied. * * @param theApplet the PApplet reference * @param p0 horizontal position * @param p1 vertical position * @param p2 width of the panel * @param p3 height of the panel (excl. tab) * @param text to appear on tab */ public GPanel(PApplet theApplet, float p0, float p1, float p2, float p3, String text) { super(theApplet, p0, p1, p2, p3); // Set the values used to constrain movement of the panel if(x < 0 || y < 0 || x + width > winApp.width || y+ height > winApp.height) clearDragArea(); else setDragArea(); // Create the list of children children = new LinkedList<GAbstractControl>(); setText(text); calcHotSpots(); constrainPanelPosition(); opaque = true; dockX = x; dockY = y; z = Z_PANEL; createEventHandler(G4P.sketchWindow, "handlePanelEvents", new Class<?>[]{ GPanel.class, GEvent.class }, new String[]{ "panel", "event" } ); registeredMethods = DRAW_METHOD | MOUSE_METHOD; cursorOver = HAND; G4P.registerControl(this); } /** * This needs to be called if the tab text is changed */ private void calcHotSpots(){ hotspots = new HotSpot[]{ new HSrect(COLLAPSED_BAR_SPOT, 0, 0, tabWidth, tabHeight), // tab text area new HSrect(EXPANDED_BAR_SPOT, 0, 0, width, tabHeight), // tab non-text area new HSrect(SURFACE_SPOT, 0, tabHeight, width, height - tabHeight) // panel content surface }; } /** * This panel is being added to another additional changes that need to be made this control * is added to another. <br> * * In this case we need to set the constraint limits to keep inside the parent. * * @param p the parent */ protected void addToParent(GAbstractControl p){ // Will this fit inside the parent panel if(width > p.width || height > p.height){ //No draggable = false; } else { lowX = -p.width/2; highX = p.width/2; lowY = -p.height/2; highY = p.height/2; } } public void setText(String text){ super.setText(text); buffer.beginDraw(); stext.getLines(buffer.g2); buffer.endDraw(); tabHeight = (int) (stext.getMaxLineHeight() + 4); tabWidth = (int) (stext.getMaxLineLength() + 8); calcHotSpots(); bufferInvalid = true; } public void setFont(Font font) { if(font != null) localFont = font; tabHeight = (int) (1.2f * localFont.getSize() + 2); buffer.g2.setFont(localFont); bufferInvalid = true; calcHotSpots(); bufferInvalid = true; } /** * What to do when the FPanel loses focus. */ protected void loseFocus(GAbstractControl grabber){ focusIsWith = null; beingDragged = false; } /** * Draw the panel. * If tabOnly == true * then display the tab only * else * draw tab and all child (added) components */ public void draw(){ if(!visible) return; winApp.pushStyle(); // Update buffer if invalid updateBuffer(); winApp.pushMatrix(); // Perform the rotation winApp.translate(cx, cy); winApp.rotate(rotAngle); // If opaque draw the panel tab and back if(opaque){ winApp.pushMatrix(); // Move matrix to line up with top-left corner winApp.translate(-halfWidth, -halfHeight); // Draw buffer winApp.imageMode(PApplet.CORNER); if(alphaLevel < 255) winApp.tint(TINT_FOR_ALPHA, alphaLevel); winApp.image(buffer, 0, 0); winApp.popMatrix(); } // Draw the children System.out.println(tabOnly); if(!tabOnly){ if(children != null){ for(GAbstractControl c : children) c.draw(); } } winApp.popMatrix(); winApp.popStyle(); } protected void updateBuffer(){ if(bufferInvalid) { bufferInvalid = false; buffer.beginDraw(); Graphics2D g2d = buffer.g2; g2d.setFont(localFont); buffer.clear(); // Draw tab buffer.noStroke(); buffer.fill(palette[4].getRGB()); if(tabOnly){ buffer.rect(0, 0, tabWidth, tabHeight); } else { buffer.rect(0, 0, width, tabHeight); } // Draw tab text (panel name) stext.getLines(g2d); g2d.setColor(palette[2]); TextLayout tl = stext.getTLIforLineNo(0).layout; tl.draw(g2d, 4, 2 + tl.getAscent()); // Draw extended panel background if(!tabOnly){ buffer.noStroke(); buffer.fill(palette[5].getRGB()); buffer.rect(0, tabHeight, width, height - tabHeight); } buffer.endDraw(); } } /** * Determines if a particular pixel position is over the panel taking * into account whether it is collapsed or not. */ public boolean isOver(float x, float y){ calcTransformedOrigin(winApp.mouseX, winApp.mouseY); currSpot = whichHotSpot(ox, oy); return (tabOnly)? currSpot == COLLAPSED_BAR_SPOT : currSpot == EXPANDED_BAR_SPOT | currSpot == COLLAPSED_BAR_SPOT; } /** * All GUI components are registered for mouseEvents */ public void mouseEvent(MouseEvent event){ if(!visible || !enabled || !available) return; calcTransformedOrigin(winApp.mouseX, winApp.mouseY); currSpot = whichHotSpot(ox, oy); // Is mouse over the panel tab (taking into account extended with when not collapsed) boolean mouseOver = (tabOnly)? currSpot == COLLAPSED_BAR_SPOT : currSpot == EXPANDED_BAR_SPOT | currSpot == COLLAPSED_BAR_SPOT; if(mouseOver || focusIsWith == this) cursorIsOver = this; else if(cursorIsOver == this) cursorIsOver = null; switch(event.getAction()){ case MouseEvent.PRESS: if(focusIsWith != this && mouseOver && z >= focusObjectZ()){ takeFocus(); beingDragged = false; } break; case MouseEvent.CLICK: if(focusIsWith == this && collapsible){ tabOnly = !tabOnly; // Perform appropriate action depending on collapse state setCollapsed(tabOnly); if(tabOnly){ x = dockX; y = dockY; } else { dockX = x; dockY = y; // Open panel move on screen if needed if(y + height > winApp.height) y = winApp.height - height; if(x + width > winApp.width) x = winApp.width - width; } // Maintain centre for drawing purposes cx = x + width/2; cy = y + height/2; constrainPanelPosition(); if(tabOnly) fireEvent(this, GEvent.COLLAPSED); else fireEvent(this, GEvent.EXPANDED); bufferInvalid = true; beingDragged = false; // This component does not keep the focus when clicked loseFocus(null); } break; case MouseEvent.RELEASE: // After dragging NOT clicking if(focusIsWith == this){ if(beingDragged){ // Remember the dock position when the mouse has // been released after the panel has been dragged dockX = x; dockY = y; beingDragged = false; loseFocus(null); } } break; case MouseEvent.DRAG: if(focusIsWith == this && draggable ){//&& parent == null){ // Maintain centre for drawing purposes cx += (winApp.mouseX - winApp.pmouseX); cy += (winApp.mouseY - winApp.pmouseY); // Update x and y positions x = cx - width/2; y = cy - height/2; constrainPanelPosition(); beingDragged = true; fireEvent(this, GEvent.DRAGGED); } break; } } /** * Determines whether to show the tab and panel back colour. If the * parameter is the same as the current state then no changes will * be made. <br> * If the parameter is false then the panel will be <br> * <ul> * <li>expanded</li> * <li>made non-collasible</li> * <li>made unavailable to mouse control (so can't be dragged)</li> * </ul> * If the parameter is true then the panel will remain non-collapsible * and the user must change this if required. <br> * @param opaque */ public void setOpaque(boolean opaque){ if(this.opaque == opaque) return; // no change if(!opaque){ setCollapsed(false); setCollapsible(false); } available = opaque; this.opaque = opaque; } /** * This method is used to discover whether the panel is being * dragged to a new position on the screen. * @return true if being dragged to a new position */ public boolean isDragging(){ return beingDragged; } /** * Sets whether the panel can be dragged by the mouse or not. * @param draggable */ public void setDraggable(boolean draggable){ this.draggable = draggable; } /** * Can we drag this panel with the mouse? * @return true if draggable */ public boolean isDraggable(){ return draggable; } /** * Collapse or open the panel * @param collapse */ public void setCollapsed(boolean collapse){ if(collapsible){ tabOnly = collapse; // If we open the panel make sure it fits on the screen but if we collapse // the panel disable the panel controls but leave the panel available if(tabOnly){ setAvailable(false); available = true; // Needed so we can click on the title bar } else { setAvailable(true); } } bufferInvalid = true; } /** * Find out if the panel is collapsed * @return true if collapsed */ public boolean isCollapsed(){ return tabOnly; } /** * Determine whether the panel can be collapsed when the title bar is clicked. <br> * * If this is set to false then the panel will be expanded and it will * not be possible to collapse it until set back to true. * */ public void setCollapsible(boolean c){ collapsible = c; if(c == false){ tabOnly = false; setAvailable(true); bufferInvalid = true; } } /** * Is this panel collapsible */ public boolean isCollapsible(){ return collapsible; } public int getTabHeight(){ return tabHeight; } /** * Provided the panel is physically small enough this method will set the area * within which the panel can be dragged and move the panel inside the area if * not already inside. <br> * * @param xMin * @param yMin * @param xMax * @param yMax * @return true if the constraint was applied successfully else false */ public boolean setDragArea(float xMin, float yMin, float xMax, float yMax){ if(xMax - xMin < width || yMax - yMin < height){ if(G4P.showMessages) System.out.println("The constraint area is too small for this panel - request ignored"); return false; } lowX = xMin; lowY = yMin; highX = xMax; highY = yMax; constrainPanelPosition(); return true; } /** * Provided the panel is small enough to fit inside the display area then * the panel will be constrained to fit inside the display area. * * @return true if the constraint was applied successfully else false */ public boolean setDragArea(){ return setDragArea(0, 0, winApp.width, winApp.height); } /** * Remove any drag constraint from this panel. */ public void clearDragArea(){ lowX = lowY = -Float.MAX_VALUE; highX = highY = Float.MAX_VALUE; } /** * Ensures that the panel tab and panel body if open does not * extend off the screen. */ private void constrainPanelPosition(){ // Calculate the size of the visible part of the panel int w = (int) ((tabOnly)? tabWidth : width); int h = (int) ((tabOnly)? tabHeight : height); // Constrain horizontally if(x < lowX) x = lowX; else if(x + w > highX) x = (int) (highX - w); // Constrain vertically if(y < lowY) y = lowY; else if(y + h > highY) y = highY - h; // Maintain centre for cx = x + width/2; cy = y + height/2; } public String toString(){ return tag + " [" + x + ", " + y+"]" + " [" + cx + ", " + cy+"]"+ " [" + dockX + ", " + dockY+"]"; } } >>>>>>> origin/master
mit
jmreyes/tutela-server
src/test/java/net/jmreyes/tutelaserver/integration/test/UnsafeHttpsClient.java
1183
package net.jmreyes.tutelaserver.integration.test; import org.apache.http.client.HttpClient; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; /** * This is an example of an HTTP client that does not properly * validate SSL certificates that are used for HTTPS. You should * NEVER use a client like this in a production application. Self-signed * certificates are usually only OK for testing purposes, such as * this use case. * * @author jules * */ public class UnsafeHttpsClient { public static HttpClient createUnsafeClient() { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( builder.build()); CloseableHttpClient httpclient = HttpClients.custom() .setSSLSocketFactory(sslsf).build(); return httpclient; } catch (Exception e) { throw new RuntimeException(e); } } }
mit
Sharpjaws/SharpSK
src/main/java/me/sharpjaws/sharpSK/hooks/Towny/EffTownyDeleteTown.java
1291
package me.sharpjaws.sharpSK.hooks.Towny; import javax.annotation.Nullable; import org.bukkit.Bukkit; import org.bukkit.event.Event; import com.palmergames.bukkit.towny.exceptions.NotRegisteredException; import com.palmergames.bukkit.towny.object.TownyUniverse; import ch.njol.skript.lang.Effect; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser; import ch.njol.util.Kleenean; import me.sharpjaws.sharpSK.main;; public class EffTownyDeleteTown extends Effect { private Expression<String> s; @SuppressWarnings("unchecked") @Override public boolean init(Expression<?>[] expr, int matchedPattern, Kleenean paramKleenean, SkriptParser.ParseResult paramParseResult) { s = (Expression<String>) expr[0]; return true; } @Override public String toString(@Nullable Event paramEvent, boolean paramBoolean) { return "[towny] delete town %string%"; } @Override protected void execute(Event e) { main core = (main) Bukkit.getPluginManager().getPlugin("SharpSK"); try { TownyUniverse.getDataSource().removeTown(TownyUniverse.getDataSource().getTown(s.getSingle(e))); } catch (NotRegisteredException e1) { core.getLogger().warning("Could not delete town: " + "\"" + s.getSingle(e) + "\"" + " Town does not exist"); return; } } }
mit
zhangqiang110/my4j
pms/src/main/java/com/swfarm/biz/paypal/web/RefundTransactionController.java
1385
package com.swfarm.biz.paypal.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; import com.swfarm.biz.paypal.bo.PayPalAccount; import com.swfarm.biz.paypal.srv.PayPalNvpService; public class RefundTransactionController extends AbstractController { private PayPalNvpService payPalNvpService; public void setPayPalNvpService(PayPalNvpService payPalNvpService) { this.payPalNvpService = payPalNvpService; } protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse res) throws Exception { String account = req.getParameter("account"); String transactionId = req.getParameter("transactionId"); String invoiceId = req.getParameter("invoiceId"); String refundType = req.getParameter("refundType"); String amount = req.getParameter("amount"); String currency = req.getParameter("currency"); String note = req.getParameter("note"); PayPalAccount payPalAccount = this.payPalNvpService .findPayPalAccountByEmail(account); this.payPalNvpService.refundTransaction(payPalAccount, transactionId, invoiceId, refundType, new Double(amount), currency, note); return new ModelAndView("redirect:/paypal/transactions.shtml"); } }
mit
szszss/MigoCraft
net/hakugyokurou/migocraft/asm/TransformerRenderManager.java
1974
package net.hakugyokurou.migocraft.asm; import java.util.List; import net.hakugyokurou.migocraft.util.RenderHelper; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.VarInsnNode; abstract class TransformerRenderManager { static byte[] transformRenderEntity(String name,byte[] bytes){ ClassNode classNode = ASMHelper.makeClassNode(bytes); String methodRenderEntityWithPosYaw = ASMHelper.getActualName("renderEntityWithPosYaw", "func_78719_a"); String methodDoRenderShadowAndFire = ASMHelper.getActualName("doRenderShadowAndFire", "func_76979_b"); for(MethodNode methodNode : (List<MethodNode>)classNode.methods) { if(methodNode.name.equals(methodRenderEntityWithPosYaw)) { int hit = 0; for(AbstractInsnNode insnNode : methodNode.instructions.toArray()) { if(insnNode.getOpcode() == Opcodes.ALOAD && ((VarInsnNode)insnNode).var==10) { if(++hit==2) { //rotateModele(entity); methodNode.instructions.insert(insnNode, new MethodInsnNode(Opcodes.INVOKESTATIC, RenderHelper.CLASS_NAME, "rotateModel", "(Lnet/minecraft/entity/Entity;)V")); methodNode.instructions.insert(insnNode, new VarInsnNode(Opcodes.ALOAD, 1)); //GL11.glPushMatrix() methodNode.instructions.insert(insnNode, new MethodInsnNode(Opcodes.INVOKESTATIC, "org/lwjgl/opengl/GL11", "glPushMatrix", "()V")); } } if(insnNode.getOpcode() == Opcodes.INVOKEVIRTUAL && ((MethodInsnNode)insnNode).name.equals(methodDoRenderShadowAndFire)) { //GL11.glPopMatrix() methodNode.instructions.insert(insnNode, new MethodInsnNode(Opcodes.INVOKESTATIC, "org/lwjgl/opengl/GL11", "glPopMatrix", "()V")); } } } } return ASMHelper.makeBytes(classNode); } }
mit
rakawestu/explore-jogja
app/src/main/java/com/github/rakawestu/explorejogja/ui/fragment/CategoryListFragment.java
5842
package com.github.rakawestu.explorejogja.ui.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import com.github.rakawestu.explorejogja.R; import com.github.rakawestu.explorejogja.app.BaseFragment; import com.github.rakawestu.explorejogja.ui.adapter.CategoryModelAdapter; import com.github.rakawestu.explorejogja.ui.adapter.PlaceModelAdapter; import com.github.rakawestu.explorejogja.ui.custom.recycler.ClickRecyclerView; import com.github.rakawestu.explorejogja.ui.presenter.CategoryListPresenter; import com.github.rakawestu.explorejogja.ui.presenter.PlaceListPresenter; import com.github.rakawestu.explorejogja.ui.view.CategoryListView; import com.github.rakawestu.explorejogja.ui.viewmodel.PlaceModel; import com.nispok.snackbar.Snackbar; import com.nispok.snackbar.SnackbarManager; import java.util.List; import javax.inject.Inject; import butterknife.InjectView; import timber.log.Timber; /** * @author rakawm */ public class CategoryListFragment extends BaseFragment implements CategoryListView{ private static final String EXTRA_PLACE_COLLECTION = "extraPlaceCollection"; @Inject CategoryListPresenter categoryListPresenter; @InjectView(R.id.collection_view) ClickRecyclerView collectionView; @InjectView(R.id.loading) ProgressBar loading; @InjectView(R.id.swipe_refresh) SwipeRefreshLayout swipeRefreshLayout; private CategoryModelAdapter modelAdapter; private LinearLayoutManager mLayoutManager; @Override public void onCreate(Bundle savedInstanceState) { Timber.i("on create()"); super.onCreate(savedInstanceState); modelAdapter = new CategoryModelAdapter(); mLayoutManager = new LinearLayoutManager(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_place_list, container, false); } @Override public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initializeCollectionView(); categoryListPresenter.setView(this); categoryListPresenter.onViewCreate(); if (savedInstanceState == null) { Timber.i("First time running"); categoryListPresenter.initialize(); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { categoryListPresenter.onRefresh(false); } }); } addClickListenerToCharacterList(); } private void initializeCollectionView() { collectionView.setAdapter(modelAdapter); collectionView.setLayoutManager(mLayoutManager); collectionView.setItemAnimator(new DefaultItemAnimator()); } @Override public int getModelsRenderer() { return modelAdapter.getItemCount(); } @Override public void showLoading() { loading.setVisibility(View.VISIBLE); } @Override public void hideLoading() { loading.setVisibility(View.GONE); } @Override public void activateLastCategoryViewListener() { enableSearchOnFinish(); } @Override public void disableLastCategoryViewListener() { disableSearchOnFinish(); } @Override public void onError() { SnackbarManager.show( Snackbar.with(getActivity()) .text("Connection Error") .animation(true) .actionLabel("Tutup") .dismissOnActionClicked(true) .duration(Snackbar.SnackbarDuration.LENGTH_SHORT) ); } @Override public void add(PlaceModel model) { modelAdapter.add(model); } @Override public void add(List<PlaceModel> models) { modelAdapter.add(models); } @Override public void remove(PlaceModel model) { } @Override public void refresh(boolean needProgress) { modelAdapter = new CategoryModelAdapter(); } @Override public void hideSwipeRefresh() { swipeRefreshLayout.setRefreshing(false); } private class FinishScrollListener extends RecyclerView.OnScrollListener { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { int lastVisibleItemPosition = mLayoutManager.findLastVisibleItemPosition() + 1; int modelsCount = modelAdapter.getItemCount(); if (lastVisibleItemPosition == modelsCount) { Timber.i("finish scroll!"); categoryListPresenter.onLastCategoryShowed(); } } } private class CharacterClickListener implements ClickRecyclerView.OnItemClickListener { @Override public void onItemClick(RecyclerView parent, View view, int position, long id) { categoryListPresenter.onCategorySelected(position); } } private void addClickListenerToCharacterList() { collectionView.setOnItemClickListener(new CharacterClickListener()); } private void enableSearchOnFinish() { collectionView.setOnScrollListener(new FinishScrollListener()); } private void disableSearchOnFinish() { collectionView.setOnScrollListener(null); } }
mit
Chark/undead-ninja-cop
src/main/java/io/chark/undead_ninja_cop/core/event/EventDispatcher.java
384
package io.chark.undead_ninja_cop.core.event; public interface EventDispatcher { /** * Register a new event listener. * * @param listener event listener to register. */ void register(EventListener<? extends Event> listener); /** * Dispatch a generic event. * * @param event event to dispatch. */ void dispatch(Event event); }
mit
sogyf/trial_examples
nanjing12336/src/main/java/org/mumu/swoop/analysis/QaListLink.java
559
/* * Copyright (c) 2010-2011 NOO. All Rights Reserved. * [Id:QaListLink.java 2011-11-02 下午10:00 poplar.yfyang ] */ package org.mumu.swoop.analysis; import java.util.List; /** * <p> * 分析列表页面获取QA连接的接口. * </p> * * @author poplar.yfyang * @version 1.0 2011-11-02 下午10:00 * @since JDK 1.5 */ public interface QaListLink { /** * 根据列表页面获取对应问答的URL列表。 * @param listUrl 列表URL * @return 对应问答的URL列表 */ List<String> getQaLinks(String listUrl); }
mit
awesommist/Electrodynamics
src/main/java/electrodynamics/Config.java
48
package electrodynamics; public class Config {}
mit
shanmugass/CricketScore
CricketScore/src/sss/cricket/scorer/database/CricketPlayerDataSource.java
3878
package sss.cricket.scorer.database; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.util.Log; public class CricketPlayerDataSource { // Database fields private SQLiteDatabase database; private MySQLiteHelper dbHelper; public CricketPlayerDataSource(Context context) { dbHelper = new MySQLiteHelper(context); } private void open() throws SQLException { database = dbHelper.getWritableDatabase(); } private void close() { dbHelper.close(); } public void createPlayer(CricketPlayer player) { open(); ContentValues values = new ContentValues(); values.put(CricketPlayer.COLUMN_PLAYER_NAME, player.PlayerName); values.put("BattingSkill", player.getBattingSkill()); values.put("BowlingSkill", player.getBattingSkill()); long insertId = database.insert(CricketPlayer.TABLE_NAME, null, values); player.PlayerId = insertId; close(); } public void updatePlayer(CricketPlayer player) { open(); ContentValues values = new ContentValues(); values.put(CricketPlayer.COLUMN_PLAYER_NAME, player.PlayerName); values.put("BattingSkill", player.getBattingSkill()); values.put("BowlingSkill", player.getBattingSkill()); database.update(CricketPlayer.TABLE_NAME, values, "PlayerId=" + player.PlayerId, null); close(); } public void createPlayers(List<CricketPlayer> players) { open(); for (CricketPlayer player : players) { String playerDetails = player.PlayerName; String[] details = playerDetails.split("-"); int battingSkill = Integer.valueOf(details[0]); int bowlingSkill = Integer.valueOf(details[1]); String playerName = details[2]; player.PlayerName = playerName; ContentValues values = new ContentValues(); values.put(CricketPlayer.COLUMN_PLAYER_NAME, playerName); values.put("BattingSkill", battingSkill); values.put("BowlingSkill", bowlingSkill); long insertId = database.insert(CricketPlayer.TABLE_NAME, null, values); Log.i("Player Created", playerName + "-" + battingSkill + "-" + bowlingSkill); player.PlayerId = insertId; if (player.TeamId > 0) { ContentValues assoc_values = new ContentValues(); assoc_values.put(CricketPlayer.COLUMN_ID, player.PlayerId); assoc_values.put(CricketPlayer.COLUMN_TEAM_ID, player.TeamId); database.insert(CricketPlayer.ASSOCIATION_TABLE_NAME, null, assoc_values); } } close(); } public void addAssociation(long playerId, long teamId) { open(); ContentValues values = new ContentValues(); values.put(CricketPlayer.COLUMN_ID, playerId); values.put(CricketPlayer.COLUMN_TEAM_ID, teamId); database.insert(CricketPlayer.ASSOCIATION_TABLE_NAME, null, values); close(); } public List<CricketPlayer> getPlayers(long teamId, String orderBy) { open(); List<CricketPlayer> matches = new ArrayList<CricketPlayer>(); String query = "Select p.playerId, p.playerName, p.battingSkill, p.bowlingSkill from CricketPlayer p JOIN CricketTeamAssociation A ON A.playerid=p.PlayerId Where TeamId=" + teamId + " Order By p." + orderBy; Cursor cursor = database.rawQuery(query, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { CricketPlayer match = cursorToCricketPlayer(cursor); matches.add(match); cursor.moveToNext(); } // Make sure to close the cursor cursor.close(); cursor.close(); close(); return matches; } private CricketPlayer cursorToCricketPlayer(Cursor cursor) { CricketPlayer newmatch = new CricketPlayer(); newmatch.PlayerId = cursor.getLong(0); newmatch.PlayerName = cursor.getString(1); newmatch.setBattingSkill(cursor.getInt(2)); newmatch.setBowlingSkill(cursor.getInt(3)); return newmatch; } }
mit
selvasingh/azure-sdk-for-java
sdk/subscription/mgmt-v2020_09_01/src/main/java/com/microsoft/azure/management/subscription/v2020_09_01/implementation/EnabledSubscriptionIdInner.java
829
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.subscription.v2020_09_01.implementation; import com.fasterxml.jackson.annotation.JsonProperty; /** * The ID of the subscriptions that is being enabled. */ public class EnabledSubscriptionIdInner { /** * The ID of the subscriptions that is being enabled. */ @JsonProperty(value = "value", access = JsonProperty.Access.WRITE_ONLY) private String value; /** * Get the ID of the subscriptions that is being enabled. * * @return the value value */ public String value() { return this.value; } }
mit
codecentric/conference-app
acceptance-tests/src/test/java/de/codecentric/selenium/OpenSpaceSessionsPageTest.java
683
package de.codecentric.selenium; import static org.junit.Assert.assertTrue; import org.junit.Ignore; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; @Ignore public class OpenSpaceSessionsPageTest extends AbstractPageTest { private String pageLink = "/allSessions"; @Test public void openPageAndValidateTitle() { open(pageLink); assertTrue("Page title does not match", PAGE_TITLE.equalsIgnoreCase(driver.getTitle())); } @Test public void openCurrentSessionsPage() { open(pageLink); WebElement title = driver.findElement(By.className("panel-title")); assertTrue(title.isDisplayed()); } }
mit
VerkhovtsovPavel/BSUIR_Labs
Labs/ADB/ADB-4/src/by/bsuir/verkpavel/adb/atm_client/resources/ProjectProperties.java
1312
package by.bsuir.verkpavel.adb.atm_client.resources; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; import javax.swing.text.MaskFormatter; import javax.swing.text.NumberFormatter; public class ProjectProperties { public static MaskFormatter getPhoneNumberFormatter() { MaskFormatter phoneNumberFormater = null; try { phoneNumberFormater = new MaskFormatter("+(###)-##-###-####"); } catch (ParseException e) { } return phoneNumberFormater; } public static MaskFormatter getCardNumberFormatter() { MaskFormatter phoneNumberFormater = null; try { phoneNumberFormater = new MaskFormatter("#### #### #### ####"); } catch (ParseException e) { } return phoneNumberFormater; } public static NumberFormatter getBYRFormatter(){ NumberFormat format = NumberFormat.getCurrencyInstance(Locale.forLanguageTag("be-BY")); format.setMaximumFractionDigits(0); NumberFormatter formatter = new NumberFormatter(format); formatter.setMinimum(1.0); formatter.setMaximum(10000000.0); formatter.setAllowsInvalid(false); formatter.setOverwriteMode(true); return formatter; } }
mit
AgileEAP/aglieEAP
agileEAP-workflow/src/main/java/com/agileEAP/workflow/viewModel/ProcessInstModel.java
3363
package com.agileEAP.workflow.viewModel; public class ProcessInstModel { private String id; public final String getID() { return id; } public final void setID(String value) { id = value; } java.util.Date CreateTime = new java.util.Date(0); public final java.util.Date getCreateTime() { return CreateTime; } public final void setCreateTime(java.util.Date value) { CreateTime = value; } private String Creator; public final String getCreator() { return Creator; } public final void setCreator(String value) { Creator = value; } private String CurrentState; public final String getCurrentState() { return CurrentState; } public final void setCurrentState(String value) { CurrentState = value; } private String Description; public final String getDescription() { return Description; } public final void setDescription(String value) { Description = value; } java.util.Date EndTime = new java.util.Date(0); public final java.util.Date getEndTime() { return EndTime; } public final void setEndTime(java.util.Date value) { EndTime = value; } java.util.Date FinalTime = new java.util.Date(0); public final java.util.Date getFinalTime() { return FinalTime; } public final void setFinalTime(java.util.Date value) { FinalTime = value; } short IsTimeOut; public final short getIsTimeOut() { return IsTimeOut; } public final void setIsTimeOut(short value) { IsTimeOut = value; } java.util.Date LimitTime = new java.util.Date(0); public final java.util.Date getLimitTime() { return LimitTime; } public final void setLimitTime(java.util.Date value) { LimitTime = value; } private String Name; public final String getName() { return Name; } public final void setName(String value) { Name = value; } private String ParentActivityID; public final String getParentActivityID() { return ParentActivityID; } public final void setParentActivityID(String value) { ParentActivityID = value; } private String ParentProcessID; public final String getParentProcessID() { return ParentProcessID; } public final void setParentProcessID(String value) { ParentProcessID = value; } private String ProcessDefID; public final String getProcessDefID() { return ProcessDefID; } public final void setProcessDefID(String value) { ProcessDefID = value; } private String ProcessDefName; public final String getProcessDefName() { return ProcessDefName; } public final void setProcessDefName(String value) { ProcessDefName = value; } private String ProcessVersion; public final String getProcessVersion() { return ProcessVersion; } public final void setProcessVersion(String value) { ProcessVersion = value; } java.util.Date RemindTime = new java.util.Date(0); public final java.util.Date getRemindTime() { return RemindTime; } public final void setRemindTime(java.util.Date value) { RemindTime = value; } java.util.Date StartTime = new java.util.Date(0); public final java.util.Date getStartTime() { return StartTime; } public final void setStartTime(java.util.Date value) { StartTime = value; } java.util.Date TimeOutTime = new java.util.Date(0); public final java.util.Date getTimeOutTime() { return TimeOutTime; } public final void setTimeOutTime(java.util.Date value) { TimeOutTime = value; } }
mit
nithinvnath/PAVProject
com.ibm.wala.shrike/src/com/ibm/wala/shrikeCT/StackMapTableReader.java
4144
package com.ibm.wala.shrikeCT; import java.util.ArrayList; import java.util.List; import com.ibm.wala.shrikeCT.ClassReader.AttrIterator; import com.ibm.wala.shrikeCT.StackMapConstants.Item; import com.ibm.wala.shrikeCT.StackMapConstants.ObjectType; import com.ibm.wala.shrikeCT.StackMapConstants.StackMapFrame; import com.ibm.wala.shrikeCT.StackMapConstants.StackMapType; import com.ibm.wala.shrikeCT.StackMapConstants.UninitializedType; public class StackMapTableReader extends AttributeReader { private List<StackMapFrame> frames; public List<StackMapFrame> frames() { return frames; } private StackMapType item(int offset) throws InvalidClassFileException { Item item = StackMapConstants.items[cr.getByte(offset)]; if (Item.ITEM_Uninitalized == item) { return new UninitializedType("#" + cr.getUShort(offset+1) + "#unknown"); } else if (Item.ITEM_Object == item) { return new ObjectType(cr.getCP().getCPClass(cr.getUShort(offset+1))); } else { return item; } } public StackMapTableReader(AttrIterator iter) throws InvalidClassFileException { super(iter, "StackMapTable"); frames = new ArrayList<StackMapFrame>(); int entries = cr.getUShort(attr+6); int ptr = attr + 8; for(int i = 0; i < entries; i++) { int frameType = (0x000000ff & cr.getByte(ptr++)); if (frameType < 64) { int offset = frameType; frames.add(new StackMapFrame(frameType, offset, new StackMapType[0], new StackMapType[0])); } else if (frameType < 128) { int offset = frameType - 64; StackMapType stack1 = item(ptr); ptr += (stack1 instanceof ObjectType)? 3: 1; frames.add(new StackMapFrame(frameType, offset, new StackMapType[0], new StackMapType[]{ stack1 })); } else if (frameType == 247) { int offset = cr.getUShort(ptr); ptr += 2; StackMapType stack1 = item(ptr); ptr += (stack1 instanceof ObjectType)? 3: 1; frames.add(new StackMapFrame(frameType, offset, new StackMapType[0], new StackMapType[]{ stack1 })); } else if (frameType >= 248 && frameType <= 250) { int offset = cr.getUShort(ptr); ptr += 2; frames.add(new StackMapFrame(frameType, offset, new StackMapType[0], new StackMapType[0])); } else if (frameType == 251) { int offset = cr.getUShort(ptr); ptr += 2; frames.add(new StackMapFrame(frameType, offset, new StackMapType[0], new StackMapType[0])); } else if (frameType >= 252 && frameType <= 254) { StackMapType[] locals = new StackMapType[ frameType - 251 ]; int offset = cr.getUShort(ptr); ptr += 2; for(int j = 0; j < locals.length; j++) { locals[j] = item(ptr); ptr += (locals[j] instanceof ObjectType)? 3: 1; } frames.add(new StackMapFrame(frameType, offset, locals, new StackMapType[0])); } else if (frameType == 255) { int offset = cr.getUShort(ptr); ptr += 2; int numLocals = cr.getUShort(ptr); ptr += 2; StackMapType[] locals = new StackMapType[ numLocals ]; for(int j = 0; j < numLocals; j++) { locals[j] = item(ptr); ptr += (locals[j] instanceof ObjectType)? 3: 1; } int numStack = cr.getUShort(ptr); ptr += 2; StackMapType[] stack = new StackMapType[ numStack ]; for(int j = 0; j < numStack; j++) { stack[j] = item(ptr); ptr += (stack[j].isObject())? 3: 1; } frames.add(new StackMapFrame(frameType, offset, locals, stack)); } } } public static List<StackMapFrame> readStackMap(CodeReader code) throws InvalidClassFileException, IllegalArgumentException { ClassReader.AttrIterator iter = new ClassReader.AttrIterator(); code.initAttributeIterator(iter); for (; iter.isValid(); iter.advance()) { if (iter.getName().equals("StackMapTable")) { StackMapTableReader r = new StackMapTableReader(iter); return r.frames(); } } return null; } }
mit
sherxon/AlgoDS
src/problems/medium/MaximumWidthofBinaryTree.java
1026
package problems.medium; import problems.utils.TreeNode; import java.util.LinkedList; /** * @author Sherali Obidov. */ public class MaximumWidthofBinaryTree { public int widthOfBinaryTree(TreeNode root) { if(root==null)return 0; LinkedList<TreeNode> q= new LinkedList<>(); q.add(root); int count=1; int level=1; while(!q.isEmpty()){ level--; TreeNode current=q.removeFirst(); if(current!=null){ q.add(current.left); q.add(current.right); }else{ q.add(null); q.add(null); } if(level==0){ while(!q.isEmpty()){ if(q.getFirst()==null)q.removeFirst(); else if(q.getLast()==null)q.removeLast(); else break; } level+=q.size(); count=Math.max(count, q.size()); } } return count; } }
mit
phoenixshow/Socket
Wifi/app/src/main/java/com/phoenix/wifi/MainActivity.java
3490
package com.phoenix.wifi; import android.Manifest; import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.net.wifi.WifiManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private static final int WIFI_SCAN_PERMISSION_CODE = 0; private TextView tv; private WifiUtils wifiUtils; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); wifiUtils = new WifiUtils(this); } public void start(View view){ wifiUtils.startWifi(); } public void stop(View view){ wifiUtils.stopWifi(); } public void check(View view){ tv.append(getString(R.string.current_state, new Object[]{wifiUtils.checkWifiState()})); } public void scan(View view){ if (ContextCompat.checkSelfPermission(this, Manifest.permission_group.LOCATION)!= PackageManager.PERMISSION_GRANTED){ // 获取wifi连接需要定位权限,没有获取权限 ActivityCompat.requestPermissions(this,new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE, },WIFI_SCAN_PERMISSION_CODE); return; } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode){ case WIFI_SCAN_PERMISSION_CODE: if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ // 允许 // initData(); tv.setText(wifiUtils.scan()); }else{ // 不允许 Toast.makeText(this,getString(R.string.permisstion_deny),Toast.LENGTH_SHORT).show(); } break; } } public void settings(View view){ startActivity(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS)); } public void connect(View view){ tv.setText(wifiUtils.connect()); } public void disconnect(View view){ wifiUtils.disconnectWifi(); } public void checkNetworkState(View view){ tv.setText(wifiUtils.checkNetWorkState()); } protected void onPause() { unregisterReceiver(receiver); super.onPause(); } protected void onResume() { registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); super.onResume(); } private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { tv.setText(wifiUtils.getScanResult()); } }; }
mit
HenrikSamuelsson/Android-Programming-The-BNRG
Chapter_02/GeoQuiz/app/src/main/java/com/bignerdranch/android/geoquiz/QuizActivity.java
4199
package com.bignerdranch.android.geoquiz; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; public class QuizActivity extends AppCompatActivity { private Button mTrueButton; private Button mFalseButton; private ImageButton mNextButton; private ImageButton mPrevButton; private TextView mQuestionTextView; private Question[] mQuestionBank = new Question[] { new Question(R.string.question_oceans, true), new Question(R.string.question_mideast, false), new Question(R.string.question_africa, false), new Question(R.string.question_americas, true), new Question(R.string.question_asia, true), }; private int mCurrentIndex = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quiz); mQuestionTextView = (TextView) findViewById(R.id.question_text_view); mQuestionTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length; displayQuestion(mCurrentIndex); } }); mTrueButton = (Button) findViewById(R.id.true_button); mTrueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkAnswer(true); } }); mFalseButton = (Button) findViewById(R.id.false_button); mFalseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkAnswer(false); } }); mNextButton = (ImageButton) findViewById(R.id.next_button); mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length; displayQuestion(mCurrentIndex); } }); mPrevButton = (ImageButton) findViewById(R.id.previous_button); mPrevButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (0 == mCurrentIndex) { mCurrentIndex = mQuestionBank.length - 1; } else { mCurrentIndex--; } displayQuestion(mCurrentIndex); } }); displayQuestion(mCurrentIndex); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void displayQuestion(int questionIndex) { int question = mQuestionBank[questionIndex].getTextResId(); mQuestionTextView.setText(question); } private void checkAnswer(boolean userPressedTrue) { boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue(); int messageResId = 0; if(userPressedTrue == answerIsTrue) { messageResId = R.string.correct_toast_text; } else { messageResId = R.string.incorrect_toast_text; } Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show(); } }
mit
ValQuev/Tuto4
app/src/main/java/fr/valquev/tuto4/Personne.java
342
package fr.valquev.tuto4; public class Personne { private String nomPrenom; private int age; public Personne(String nomPrenom, int age) { this.nomPrenom = nomPrenom; this.age = age; } public int getAge() { return age; } public String getNomPrenom() { return nomPrenom; } }
mit
bacta/swg
game-server/src/main/java/com/ocdsoft/bacta/swg/server/game/controller/object/GameControllerMessage.java
497
package com.ocdsoft.bacta.swg.server.game.controller.object; import com.ocdsoft.bacta.swg.server.game.message.object.GameControllerMessageType; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by crush on 5/29/2016. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface GameControllerMessage { GameControllerMessageType[] value(); }
mit
kzm4269/scenography
app/src/main/java/jp/plen/scenography/fragments/NavigationDrawerFragment.java
6829
package jp.plen.scenography.fragments; import android.app.Activity; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import jp.plen.scenography.R; /** * スワイプすると横から出てくるよくあるメニュー */ public class NavigationDrawerFragment extends Fragment { private static final String PREF_USER_LEARNED_DRAWER = "user_learned_drawer"; private static final String PREF_CURRENT_POSITION = "user_current_position"; /** * A pointer to the current callbacks instance (the Activity). */ private Callbacks mCallbacks; /** * Helper component that ties the action bar to the navigation drawer. */ private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private ListView mDrawerListView; private View mFragmentContainerView; private boolean mUserLearnedDrawer; private int mCurrentPosition; public NavigationDrawerFragment() { } /** * Users of this fragment must call this method to set up the navigation drawer interactions. * * @param fragmentId The android:id of this fragment in its activity's layout. * @param drawerLayout The DrawerLayout containing this fragment's UI. */ public void setUp(int fragmentId, DrawerLayout drawerLayout, String[] titles, int position) { mFragmentContainerView = getActivity().findViewById(fragmentId); mDrawerLayout = drawerLayout; // ActionBar actionBar = getActionBar(); // actionBar.setDisplayHomeAsUpEnabled(true); // actionBar.setHomeButtonEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the navigation drawer and the action bar app icon. mDrawerToggle = new ActionBarDrawerToggle( getActivity(), /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) { @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); if (!isAdded()) { return; } if (!mUserLearnedDrawer) { mUserLearnedDrawer = true; SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, mUserLearnedDrawer).apply(); } } }; // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer, // per the navigation drawer design guidelines. if (!mUserLearnedDrawer) { mDrawerLayout.openDrawer(mFragmentContainerView); } // Defer code dependent on restoration of previous instance state. mDrawerLayout.post(mDrawerToggle::syncState); mDrawerLayout.setDrawerListener(mDrawerToggle); mDrawerListView.setAdapter(new ArrayAdapter<>( getActivity(), R.layout.item_navigation_drawer, android.R.id.text1, titles)); mCurrentPosition = position; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallbacks = (Callbacks) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement Callbacks."); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false); mCurrentPosition = sp.getInt(PREF_CURRENT_POSITION, 0); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mDrawerListView = (ListView) inflater.inflate( R.layout.fragment_navigation_drawer, container, false); mDrawerListView.setOnItemClickListener((parent, view, position, id) -> selectItem(position)); return mDrawerListView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Indicate that this fragment would like to influence the set of actions in the action bar. setHasOptionsMenu(true); selectItem(mCurrentPosition); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Forward the new configuration the drawer toggle component. mDrawerToggle.onConfigurationChanged(newConfig); } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public boolean onOptionsItemSelected(MenuItem item) { //noinspection SimplifiableIfStatement if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } private void selectItem(int position) { if (mDrawerListView != null) { mDrawerListView.setItemChecked(position, true); } if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(mFragmentContainerView); } if (mCallbacks != null) { mCallbacks.onNavigationDrawerItemSelected(position); } mCurrentPosition = position; SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); sp.edit().putInt(PREF_CURRENT_POSITION, mCurrentPosition).apply(); } /** * Callbacks interface that all activities using this fragment must implement. */ public interface Callbacks { /** * Called when an item in the navigation drawer is selected. */ void onNavigationDrawerItemSelected(int position); } }
mit
Lucas3oo/jicunit
src/jicunit-framework/src/test/java/org/jicunit/framework/BasicIntegrationTest.java
1947
package org.jicunit.framework; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Arrays; import org.jicunit.framework.samples.TestSampleJunit3; import org.jicunit.framework.samples.TestSampleJunit4; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; /** * Test both Junit3 and Junit4 support end to end using Jetty web container * * @author lucas * */ @RunWith(Parameterized.class) public class BasicIntegrationTest extends IntegrationTestBase { @Parameter(0) public Class<?> mTestClass; @Parameters(name = "{index}: Class {0}") public static Iterable<Object[]> data() { return Arrays.asList( new Object[][] { { TestSampleJunit3.class }, { TestSampleJunit4.class } }); } @Test public void testDoSomething() { String methodName = "testDoSomething"; try { runTest(mTestClass, methodName); } catch (Throwable e) { e.printStackTrace(); fail("There should not be an exception but was " + e); } } @Test public void testThatFailes() { String methodName = "testDoSomethingThatFailes"; try { runTest(mTestClass, methodName); fail("There should have been an exception"); } catch (Throwable e) { assertTrue("The exception must be of AssertionError but was " + e, e instanceof AssertionError); } } @Test public void testThatErrors() throws Throwable { String methodName = "testDoSomethingThatErrors"; try { runTest(mTestClass, methodName); fail("There should have been an exception"); } catch (Throwable e) { assertEquals("The exception message should be 'The value is illegal'", "The value is illegal", e.getMessage()); } } }
mit
nonkr/tiams
src/main/java/tiams/service/impl/RoleServiceImpl.java
6851
package tiams.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.apache.log4j.Logger; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import tiams.dao.BaseDaoI; import tiams.dto.DataGrid; import tiams.dto.RoleDto; import tiams.model.Auth; import tiams.model.Role; import tiams.model.Roleauth; import tiams.model.Userrole; import tiams.service.RoleServiceI; import tiams.util.MyException; @Service("roleService") public class RoleServiceImpl implements RoleServiceI { private static final Logger logger = Logger.getLogger(RoleServiceImpl.class); private BaseDaoI<Role> roleDao; private BaseDaoI<Auth> authDao; private BaseDaoI<Roleauth> roleauthDao; private BaseDaoI<Userrole> userroleDao; public BaseDaoI<Userrole> getUserroleDao() { return userroleDao; } @Autowired public void setUserroleDao(BaseDaoI<Userrole> userroleDao) { this.userroleDao = userroleDao; } public BaseDaoI<Auth> getAuthDao() { return authDao; } @Autowired public void setAuthDao(BaseDaoI<Auth> authDao) { this.authDao = authDao; } public BaseDaoI<Roleauth> getRoleauthDao() { return roleauthDao; } @Autowired public void setRoleauthDao(BaseDaoI<Roleauth> roleauthDao) { this.roleauthDao = roleauthDao; } public BaseDaoI<Role> getRoleDao() { return roleDao; } @Autowired public void setRoleDao(BaseDaoI<Role> roleDao) { this.roleDao = roleDao; } @Override public DataGrid datagrid(RoleDto roleDto) { int page = roleDto.getPage(); int rows = roleDto.getRows(); String name = roleDto.getName(); String sort = roleDto.getSort(); String order = roleDto.getOrder(); DataGrid dg = new DataGrid(); Map<String, Object> params = new HashMap<String, Object>(); String hql = "from Role r"; hql = addHqlWhere(name, params, hql); String countHql = "select count(*) " + hql; hql = addHqlOrder(sort, order, hql); List<Role> roles = roleDao.find(hql, params, page, rows); List<RoleDto> roleDtos = new ArrayList<RoleDto>(); if (roles != null && roles.size() > 0) { for (Role r : roles) { RoleDto rd = new RoleDto(); BeanUtils.copyProperties(r, rd); Set<Roleauth> roleauths = r.getRoleauths(); String authIds = ""; String authNames = ""; if (roleauths != null && roleauths.size() > 0) { for (Roleauth ra : roleauths) { authIds += "," + ra.getAuth().getId(); authNames += "," + ra.getAuth().getName(); } } if (authIds.equals("")) { rd.setAuthIds(""); rd.setAuthNames(""); } else { rd.setAuthIds(authIds.substring(1)); rd.setAuthNames(authNames.substring(1)); } roleDtos.add(rd); } } dg.setTotal(roleDao.count(countHql, params)); dg.setRows(roleDtos); return dg; } private String addHqlWhere(String name, Map<String, Object> params, String hql) { if (name != null && !name.trim().equals("")) { hql += " where r.name like :name"; params.put("name", "%%" + name.trim() + "%%"); } return hql; } private String addHqlOrder(String sort, String order, String hql) { if (sort != null && !sort.equals("") && order != null && !order.equals("")) { hql += " order by " + sort + " " + order; } return hql; } @Override public RoleDto add(RoleDto roleDto) throws MyException { Map<String, Object> params = new HashMap<String, Object>(); params.put("name", roleDto.getName()); Long cnt = roleDao.count("select count(*) from Role r where r.name = :name", params); if (cnt > 0) { throw new MyException("角色名已存在!"); } else { Role r = new Role(); BeanUtils.copyProperties(roleDto, r); r.setId(UUID.randomUUID().toString()); roleDao.save(r); BeanUtils.copyProperties(r, roleDto); return saveRoleAuth(roleDto, r); } } /** * 保存Role和Auth的关系 * * @param roleDto * @param r */ private RoleDto saveRoleAuth(RoleDto roleDto, Role r) { if (roleDto.getAuthIds() != null) { String authNames = ""; for (String id : roleDto.getAuthIds().split(",")) { Roleauth roleauth = new Roleauth(); roleauth.setId(UUID.randomUUID().toString()); Auth auth = authDao.get(Auth.class, id.trim()); authNames += "," + auth.getName(); roleauth.setAuth(auth); roleauth.setRole(r); roleauthDao.save(roleauth); } roleDto.setAuthNames(authNames.substring(1)); } else { roleDto.setAuthIds(""); roleDto.setAuthNames(""); } return roleDto; } @Override public void delete(RoleDto roleDto) { String ids = roleDto.getIds(); if (ids != null && !ids.trim().equals("")) { roleauthDao.execute("delete Roleauth t where t.role.id in (" + ids + ")"); userroleDao.execute("delete Userrole t where t.role.id in (" + ids + ")"); roleDao.execute("delete Role r where r.id in (" + ids + ")"); } } @Override public RoleDto modify(RoleDto roleDto) throws MyException { Map<String, Object> params = new HashMap<String, Object>(); params.put("name", roleDto.getName()); params.put("id", roleDto.getId()); Long cnt = roleDao.count( "select count(*) from Role r where r.name = :name and r.id != :id", params); if (cnt > 0) { throw new MyException("角色名已存在!"); } else { Role r = roleDao.get(Role.class, roleDto.getId()); BeanUtils.copyProperties(roleDto, r, new String[] { "id" }); BeanUtils.copyProperties(r, roleDto); Map<String, Object> params2 = new HashMap<String, Object>(); params2.put("role", r); roleauthDao.execute("delete Roleauth r where r.role = :role", params2); return saveRoleAuth(roleDto, r); } } }
mit
navneetzz/Hackerrank
src/Java/DataStructures/JavaPriorityQueue.java
2134
package Java.DataStructures; import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; /** * Created by ryu on 1/3/17. */ class Student{ private int token; private String fname; private double cgpa; public Student(int id, String fname, double cgpa) { super(); this.token = id; this.fname = fname; this.cgpa = cgpa; } public int getToken() { return token; } public String getFname() { return fname; } public double getCgpa() { return cgpa; } } public class JavaPriorityQueue { public static void main(String[] args) { Scanner in = new Scanner(System.in); int totalEvents = Integer.parseInt(in.nextLine()); PriorityQueue<Student> studentList = new PriorityQueue<Student>(totalEvents, new StudentComparator()); while(totalEvents-- > 0){ String event = in.next(); switch (event) { case "ENTER": String fname = in.next(); double cgpa=in.nextDouble(); int token = in.nextInt(); Student st = new Student(token, fname, cgpa); studentList.add(st); break; case "SERVED": studentList.poll(); break; } } in.close(); if(studentList.isEmpty()) System.out.println("EMPTY"); else { while (!studentList.isEmpty()) { Student s = studentList.remove(); System.out.println(s.getFname()); } } } } class StudentComparator implements Comparator<Student> { @Override public int compare(Student s2, Student s1) { if ((Double.compare(s2.getCgpa(), s1.getCgpa())==0) && s2.getFname().equals(s1.getFname())==true) return s1.getToken()-s2.getToken(); else if(Double.compare(s2.getCgpa(), s1.getCgpa())==0) return s2.getFname().compareTo(s1.getFname()); else return s2.getCgpa() < s1.getCgpa() ? 1 : -1; } }
mit
hkdobrev/softuni-java-homework
2-java-basics/1-rectangle-area/RectangleArea.java
356
import java.util.Scanner; class RectangleArea { public static void main(String[] args) { int a, b; Scanner scanIn = new Scanner(System.in); a = Integer.parseInt(scanIn.nextLine()); b = Integer.parseInt(scanIn.nextLine()); scanIn.close(); int area = a * b; System.out.println(area); } }
mit
Snorremd/INFO233
Oblig2-kladding/losningsforslag-haakon/src/main/Main.java
2400
package main; import game.controller.Game; import game.io.ConnectionHolder; import game.io.ResourceLoader; import game.io.ResourceLoaderCSV; import game.io.ResourceLoaderSQL; public class Main { /** * Dette laster inn en ResourceLoader som kan hente ut brett og slikt. * Deretter lager det et nytt Game-objekt som det kjører start på. * @param args blir ignorert * @throws Throwable Vi kaster alle exceptions. Dette er egentlig en dum ting. */ public static void main(String[] args) throws Throwable { if(args.length > 0){ boolean exit0 = false; String arg = args[0]; switch(arg){ case "--rebuild": System.out.println("Rebuilding database"); ResourceLoaderSQL.reBuildDataBase(); exit0 = true; break; case "--version": System.out.println("Kjips Kylling v0.1 - løsningsforslag Haakon"); exit0 = true; break; case "--help": displayHelp(); exit0 = true; break; case "--dev-run": ResourceLoaderSQL.reBuildDataBase(); exit0 = false; break; default: System.out.printf("Unknown command %s%n", arg); displayHelp(); System.exit(1); } if(exit0){ System.exit(0); } } /* * Når dere er ferdig med ResourceLoaderSQL-klassen, kan dere gjøre: * ResourceLoader loader = new ResourceLoaderSQL() istedenfor. * Det blir den eneste forskjellen for resten av spillet. */ ResourceLoader loader = new ResourceLoaderSQL(); Game game = new Game(loader); game.start(); System.out.println("Spill over, avslutter"); game.shutdown(); ConnectionHolder.shutDown(); System.exit(0); // Fordi ordentlig kode for å slå av ting er for vanskelig... :) } private static void displayHelp(){ System.out.println("Kjips Kylling: A simple tile-based game reminiscent of Chip's Challenge."); System.out.println("Only the first argument is parsed"); System.out.println(" arg\t\t\tmeaning"); System.out.println("--rebuild\t\trebuild the database from csv-files and exit. If you mod the game through the CSV-files, this is the command to call."); System.out.println("--version\t\tdisplay the version of the game and exit."); System.out.println("--help\t\t\tdisplay this helpful text"); System.out.println("--dev-run\t\trebuild the database and then runs the game. If you are a developer this is probably the one you want Eclipse to run."); } }
mit
jrbeaumont/workcraft
WtgPlugin/src/org/workcraft/plugins/wtg/interop/WtgFormat.java
771
package org.workcraft.plugins.wtg.interop; import java.util.UUID; import org.workcraft.interop.Format; public final class WtgFormat implements Format { private static WtgFormat instance = null; private WtgFormat() { } public static WtgFormat getInstance() { if (instance == null) { instance = new WtgFormat(); } return instance; } @Override public UUID getUuid() { return UUID.fromString("ff127612-f14d-4afd-90dc-8c74daa4083c"); } @Override public String getName() { return "WTG"; } @Override public String getExtension() { return ".wtg"; } @Override public String getDescription() { return "Waveform Transition Graph"; } }
mit
BoyanAtMentormate/VolleyEclipse
VolleySample/src/com/example/volleysample/common/Thumbnails.java
801
package com.example.volleysample.common; public class Thumbnails { private String large; private String medium; private String small; private String thumb; public Thumbnails(String large, String medium, String small, String thumb) { super(); this.large = large; this.medium = medium; this.small = small; this.thumb = thumb; } public String getLarge() { return large; } public void setLarge(String large) { this.large = large; } public String getMedium() { return medium; } public void setMedium(String medium) { this.medium = medium; } public String getSmall() { return small; } public void setSmall(String small) { this.small = small; } public String getThumb() { return thumb; } public void setThumb(String thumb) { this.thumb = thumb; } }
mit
bdragan/takes
src/main/java/org/takes/facets/fork/TkMethods.java
1813
/** * The MIT License (MIT) * * Copyright (c) 2015 Yegor Bugayenko * * 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 NON-INFRINGEMENT. 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.takes.facets.fork; import java.util.Arrays; import lombok.ToString; import org.takes.Take; import org.takes.tk.TkWrap; /** * Take that acts on request with specified methods only. * <p>The class is immutable and thread-safe. * * @author Aleksey Popov (alopen@yandex.ru) * @version $Id$ */ @ToString(callSuper = true) public class TkMethods extends TkWrap { /** * Ctor. * * @param take Original take * @param methods Methods the take should act */ public TkMethods(final Take take, final String ...methods) { super( new TkFork(new FkMethods(Arrays.asList(methods), take)) ); } }
mit
sridevibaskaran/ontology
src/main/java/ontologyisa/OntologyISA.java
1658
package ontologyisa; import static ontologyisa.IO.THRESHOLD; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.logging.Logger; import graph.Vertex; public class OntologyISA implements IOntology { private final static Logger LOGGER = Logger.getLogger(OntologyISA.class.getName()); @Override public boolean isWithinThreshold(Vertex lca, List<Vertex> vertices) { for (Vertex v : vertices) { if (!(Math.abs(v.getDistance() - lca.getDistance()) <= THRESHOLD)) { //LOGGER.info("NOT WITHIN THRESHHOLD"); return false; } } //LOGGER.info("WITHIN THRESHHOLD"); return true; } @Override public Vertex findLCA(List<Vertex> vertices) { Vertex result = null; List<Vertex> listOfAncestors = getListOfAncestors(vertices.get(0)); ArrayList<Vertex> intersection = new ArrayList<Vertex>(listOfAncestors); for (Vertex vertex : vertices.subList(1, vertices.size())) { intersection.retainAll(getListOfAncestors(vertex)); } Comparator<Vertex> byDistance = (e1, e2) -> Integer.compare(e1.getDistance(), e2.getDistance()); intersection.stream().sorted(byDistance); result = intersection.get(0); //LOGGER.info(("LCA: " + result.getValue())); return result; } // TODO: Try to write a recursive function private static List<Vertex> getListOfAncestors(Vertex startVertex) { Vertex ancestor = startVertex.getAncestor(); List<Vertex> ansList = new ArrayList<Vertex>(); if (ancestor != null) ansList.add(ancestor); while (ancestor != null) { ancestor = ancestor.getAncestor(); if (ancestor == null) break; ansList.add(ancestor); } return ansList; } }
mit
CMPUT301W17T02/JenaPlus
Mood+/app/src/androidTest/java/com/mood/jenaPlus/WelcomeActivityTest.java
1331
package com.mood.jenaPlus; import android.app.Activity; import android.test.ActivityInstrumentationTestCase2; import android.widget.EditText; import com.robotium.solo.Solo; /** * Created by carrotji on 2017-03-13. */ public class WelcomeActivityTest extends ActivityInstrumentationTestCase2 { private Solo solo; public WelcomeActivityTest() { super(WelcomeActivity.class); } public void setUp() throws Exception{ solo = new Solo(getInstrumentation(),getActivity()); } public void testStart() throws Exception { Activity activity = getActivity(); } public void testLoginParticipant(){ solo.assertCurrentActivity("Wrong Activity", WelcomeActivity.class); solo.enterText((EditText) solo.getView(R.id.loginUserName),"josefina"); solo.clickOnButton("Log in"); solo.assertCurrentActivity("Wrong Activity", MoodPlusActivity.class); } public void testNonExistParticipant(){ solo.assertCurrentActivity("Wrong Activity", WelcomeActivity.class); solo.enterText((EditText) solo.getView(R.id.loginUserName),"Non-Exist"); solo.clickOnButton("Log in"); solo.waitForActivity("WelcomeActivity"); } @Override public void tearDown() throws Exception{ solo.finishOpenedActivities(); } }
mit
kokorin/vk-java-sdk
sdk/src/main/java/com/vk/api/sdk/objects/base/BaseCount.java
890
package com.vk.api.sdk.objects.base; import com.google.gson.annotations.SerializedName; import java.util.Objects; /** * BaseCount object */ public class BaseCount { /** * Items count */ @SerializedName("count") private Integer count; public Integer getCount() { return count; } @Override public int hashCode() { return Objects.hash(count); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BaseCount baseObject = (BaseCount) o; return Objects.equals(count, baseObject.count); } @Override public String toString() { final StringBuilder sb = new StringBuilder("BaseObject{"); sb.append("count=").append(count); sb.append('}'); return sb.toString(); } }
mit
ekondrashev/takes
src/main/java/org/takes/tk/TkFixed.java
1891
/** * The MIT License (MIT) * * Copyright (c) 2015 Yegor Bugayenko * * 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 NON-INFRINGEMENT. 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.takes.tk; import lombok.EqualsAndHashCode; import org.takes.Response; import org.takes.Take; /** * Take with fixed response. * * <p>This class always returns the same response, provided via * constructor and encapsulated. * * <p>The class is immutable and thread-safe. * * @author Yegor Bugayenko (yegor@teamed.io) * @version $Id$ * @since 0.1 */ @EqualsAndHashCode(callSuper = true) public final class TkFixed extends TkWrap { /** * Ctor. * @param res Response */ public TkFixed(final Response res) { super( new Take() { @Override public Response act() { return res; } } ); } }
mit
nickolayrusev/trackteam
migrator/src/main/java/com/nrusev/processor/ItalyProcessor.java
1591
package com.nrusev.processor; import com.nrusev.domain.Country; import com.nrusev.domain.Team; import com.nrusev.service.CountryService; import com.nrusev.service.MatchesService; import com.nrusev.service.TeamService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import static java.util.stream.Collectors.toList; /** * Created by Nikolay Rusev on 12.10.2016 г.. */ @Component public class ItalyProcessor extends AbstractProcessor{ private static final String COUNTRY = "Italy"; @Autowired public ItalyProcessor(MatchesService matchesService, TeamService teamService, CountryService countryService) { super(matchesService, teamService, countryService); } @Override public void process() { List<String> missingTeams = findSQLiteTeams(); printTeams(missingTeams); Country italy = this.countryService.findByName(COUNTRY).get(0); missingTeams.forEach(t->{ Team newTeam = new Team(); newTeam.setCountry(italy); newTeam.setClub(true); newTeam.setTitle(t); newTeam.setKey(t.toLowerCase()); newTeam.setNational(false); teamService.save(newTeam); }); } public List<String> findSQLiteTeams(){ List<String> allTeams = matchesService.findAllTeams(COUNTRY); return allTeams.stream().filter(t-> !teamService.findTeam(t,COUNTRY).isPresent()).collect(toList()); } }
mit
jcuda/jcuda-vec
JCudaVec/src/test/java/jcuda/vec/TestVecDoubleMath1.java
28759
/* * JCudaVec - Vector operations for JCuda * http://www.jcuda.org * * Copyright (c) 2013-2015 Marco Hutter - http://www.jcuda.org * * 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 jcuda.vec; import org.junit.Test; import jcuda.driver.CUdeviceptr; /* * NOTE: Many of these tests are commented out, because they don't * have a simple translation to java.lang.Math methods. They may * be extended in future. */ /** * Tests for the 1-argument vector math methods */ public class TestVecDoubleMath1 extends AbstractTestVecDouble { @Test public void testAcos() { runTest(new AbstractCoreDouble("acos") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.acos(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.acos(n, result, x); } }); } // @Test // public void testAcosh() // { // runTest(new AbstractTestCoreDouble("acosh") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.acosh(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.acosh(n, result, x); // } // }); // } @Test public void testAsin() { runTest(new AbstractCoreDouble("asin") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.asin(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.asin(n, result, x); } }); } // @Test // public void testAsinh() // { // runTest(new AbstractTestCoreDouble("asinh") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.asinh(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.asinh(n, result, x); // } // }); // } @Test public void testAtan() { runTest(new AbstractCoreDouble("atan") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.atan(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.atan(n, result, x); } }); } // @Test // public void testAtanh() // { // runTest(new AbstractTestCoreDouble("atanh") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.atanh(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.atanh(n, result, x); // } // }); // } @Test public void testCbrt() { runTest(new AbstractCoreDouble("cbrt") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.cbrt(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.cbrt(n, result, x); } }); } @Test public void testCeil() { runTest(new AbstractCoreDouble("ceil") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.ceil(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.ceil(n, result, x); } }); } @Test public void testCos() { runTest(new AbstractCoreDouble("cos") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.cos(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.cos(n, result, x); } }); } @Test public void testCosh() { runTest(new AbstractCoreDouble("cosh") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.cosh(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.cosh(n, result, x); } }); } @Test public void testCospi() { runTest(new AbstractCoreDouble("cospi") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.cos(x*Math.PI); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.cospi(n, result, x); } }); } // @Test // public void testErfc() // { // runTest(new AbstractTestCoreDouble("erfc") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.erfc(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.erfc(n, result, x); // } // }); // } // @Test // public void testErfcinv() // { // runTest(new AbstractTestCoreDouble("erfcinv") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.erfcinv(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.erfcinv(n, result, x); // } // }); // } // @Test // public void testErfcx() // { // runTest(new AbstractTestCoreDouble("erfcx") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.erfcx(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.erfcx(n, result, x); // } // }); // } // @Test // public void testErf() // { // runTest(new AbstractTestCoreDouble("erf") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.erf(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.erf(n, result, x); // } // }); // } // @Test // public void testErfinv() // { // runTest(new AbstractTestCoreDouble("erfinv") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.erfinv(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.erfinv(n, result, x); // } // }); // } // @Test // public void testExp10() // { // runTest(new AbstractTestCoreDouble("exp10") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.exp10(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.exp10(n, result, x); // } // }); // } // @Test // public void testExp2() // { // runTest(new AbstractTestCoreDouble("exp2") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.exp2(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.exp2(n, result, x); // } // }); // } @Test public void testExp() { runTest(new AbstractCoreDouble("exp") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.exp(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.exp(n, result, x); } }); } @Test public void testExpm1() { runTest(new AbstractCoreDouble("expm1") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.expm1(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.expm1(n, result, x); } }); } @Test public void testFabs() { runTest(new AbstractCoreDouble("fabs") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.abs(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.fabs(n, result, x); } }); } @Test public void testFloor() { runTest(new AbstractCoreDouble("floor") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.floor(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.floor(n, result, x); } }); } // @Test // public void testJ0() // { // runTest(new AbstractTestCoreDouble("j0") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.j0(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.j0(n, result, x); // } // }); // } // @Test // public void testJ1() // { // runTest(new AbstractTestCoreDouble("j1") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.j1(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.j1(n, result, x); // } // }); // } // @Test // public void testLgamma() // { // runTest(new AbstractTestCoreDouble("lgamma") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.lgamma(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.lgamma(n, result, x); // } // }); // } @Test public void testLog10() { runTest(new AbstractCoreDouble("log10") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.log10(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.log10(n, result, x); } }); } @Test public void testLog1p() { runTest(new AbstractCoreDouble("log1p") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.log1p(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.log1p(n, result, x); } }); } @Test public void testLog2() { runTest(new AbstractCoreDouble("log2") { @Override protected double computeHostElement( double x, double y, double scalar) { return (Math.log(x) / Math.log(2)); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.log2(n, result, x); } }); } // @Test // public void testLogb() // { // runTest(new AbstractTestCoreDouble("logb") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.logb(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.logb(n, result, x); // } // }); // } @Test public void testLog() { runTest(new AbstractCoreDouble("log") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.log(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.log(n, result, x); } }); } // @Test // public void testNormcdf() // { // runTest(new AbstractTestCoreDouble("normcdf") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.normcdf(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.normcdf(n, result, x); // } // }); // } // @Test // public void testNormcdfinv() // { // runTest(new AbstractTestCoreDouble("normcdfinv") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.normcdfinv(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.normcdfinv(n, result, x); // } // }); // } // @Test // public void testRcbrt() // { // runTest(new AbstractTestCoreDouble("rcbrt") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.rcbrt(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.rcbrt(n, result, x); // } // }); // } @Test public void testRint() { runTest(new AbstractCoreDouble("rint") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.rint(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.rint(n, result, x); } }); } @Test public void testRound() { runTest(new AbstractCoreDouble("round") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.round(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.round(n, result, x); } }); } @Test public void testRsqrt() { runTest(new AbstractCoreDouble("rsqrt") { @Override protected double computeHostElement( double x, double y, double scalar) { return (1.0 / Math.sqrt(x)); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.rsqrt(n, result, x); } }); } @Test public void testSin() { runTest(new AbstractCoreDouble("sin") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.sin(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.sin(n, result, x); } }); } @Test public void testSinh() { runTest(new AbstractCoreDouble("sinh") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.sinh(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.sinh(n, result, x); } }); } @Test public void testSinpi() { runTest(new AbstractCoreDouble("sinpi") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.sin(x*Math.PI); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.sinpi(n, result, x); } }); } @Test public void testSqrt() { runTest(new AbstractCoreDouble("sqrt") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.sqrt(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.sqrt(n, result, x); } }); } @Test public void testTan() { runTest(new AbstractCoreDouble("tan") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.tan(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.tan(n, result, x); } }); } @Test public void testTanh() { runTest(new AbstractCoreDouble("tanh") { @Override protected double computeHostElement( double x, double y, double scalar) { return Math.tanh(x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.tanh(n, result, x); } }); } // @Test // public void testTgamma() // { // runTest(new AbstractTestCoreDouble("tgamma") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.tgamma(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.tgamma(n, result, x); // } // }); // } @Test public void testTrunc() { runTest(new AbstractCoreDouble("trunc") { @Override protected double computeHostElement( double x, double y, double scalar) { return ((long)x); } @Override protected void computeDevice(long n, CUdeviceptr result, CUdeviceptr x, CUdeviceptr y, double scalar) { VecDouble.trunc(n, result, x); } }); } // @Test // public void testY0() // { // runTest(new AbstractTestCoreDouble("y0") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.y0(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.y0(n, result, x); // } // }); // } // @Test // public void testY1() // { // runTest(new AbstractTestCoreDouble("y1") // { // @Override // protected double computeHostElement( // double x, double y, double scalar) // { // return Math.y1(x); // } // // @Override // protected void computeDevice(CUdeviceptr result, CUdeviceptr x, // CUdeviceptr y, double scalar, long n) // { // VecDouble.y1(n, result, x); // } // }); // } }
mit
ShoukriKattan/ForgedUI-Eclipse
com.forgedui.editor/src/com/forgedui/editor/dnd/MyTemplateTransferDropTargetListener.java
1109
package com.forgedui.editor.dnd; import org.eclipse.gef.EditPartViewer; import org.eclipse.gef.dnd.TemplateTransferDropTargetListener; import org.eclipse.gef.requests.CreationFactory; import com.forgedui.editor.palette.TitaniumUIElementFactory; import com.forgedui.model.Diagram; import com.forgedui.model.Element; public class MyTemplateTransferDropTargetListener extends TemplateTransferDropTargetListener { private Diagram diagram; public MyTemplateTransferDropTargetListener(EditPartViewer viewer, Diagram diagram) { super(viewer); this.diagram = diagram; } @Override protected CreationFactory getFactory(Object template) { if (template instanceof Element) { //how this happened??? return new TitaniumUIElementFactory( (Class<? extends Element>) template.getClass(), diagram); } else if (template instanceof Class){ if (Element.class.isAssignableFrom((Class<?>) template)){ return new TitaniumUIElementFactory( (Class<? extends Element>) template, diagram); } } throw new IllegalArgumentException("Can't create factory for " + template); } }
mit
steve1rm/flighttrack
app/src/androidTest/java/me/androidbox/flighttrack/ApplicationTest.java
356
package me.androidbox.flighttrack; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
mit
hea3ven/CommonUtils
src/main/java/com/hea3ven/tools/commonutils/mod/ModComposite.java
4534
package com.hea3ven.tools.commonutils.mod; import net.fabricmc.loader.launch.common.FabricLauncherBase; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import com.hea3ven.tools.commonutils.mod.info.BlockInfo; import com.hea3ven.tools.commonutils.mod.info.ContainerInfo; import com.hea3ven.tools.commonutils.mod.info.EnchantmentInfo; import com.hea3ven.tools.commonutils.mod.info.ItemGroupInfo; import com.hea3ven.tools.commonutils.mod.info.ItemInfo; import com.hea3ven.tools.commonutils.mod.info.ScreenInfo; public class ModComposite extends Mod { private Map<String, ModModule> children = new HashMap<>(); public ModComposite(String modId) { super(modId); } public final void addModule(String name, String modId, String clsName) { // TODO: Conditional loading // if (!Loader.isModLoaded(modId)) // return; addModule(name, clsName); } public final void addModule(String name, String clsName) { boolean singleton = false; if (clsName.endsWith(".INSTANCE")) { singleton = true; clsName = clsName.substring(0, clsName.length() - 9); } Class<? extends ModModule> cls; try { // cls = Loader.instance().getModClassLoader().loadClass(clsName).asSubclass(ModModule.class); ClassLoader targetClassLoader = FabricLauncherBase.getLauncher().getTargetClassLoader(); cls = targetClassLoader.loadClass(clsName).asSubclass(ModModule.class); } catch (ClassNotFoundException e) { throw new ModuleLoadingException(e); } ModModule child; try { if (!singleton) { child = cls.getConstructor().newInstance(); } else { child = (ModModule) cls.getField("INSTANCE").get(null); } } catch (Exception e) { throw new ModuleLoadingException("Could not build the module " + name, e); } children.put(name, child); child.setParent(this); } public ModModule getModule(String name) { return children.get(name); } public String getModuleName(ModModule module) { return children.entrySet() .stream() .filter(e -> e.getValue() == module) .findAny() .map(Entry::getKey) .orElse(null); } @Override public void onPreInit() { children.values().forEach(Mod::onPreInit); } @Override public void onInit() { children.values().forEach(Mod::onInit); } @Override public void onPostInit() { children.values().forEach(Mod::onPostInit); } @Override public Map<String, BlockInfo> getBlocks() { return children.values() .stream() .flatMap(module -> module.getBlocks().entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @Override public Map<String, ContainerInfo> getContainers() { return children.values() .stream() .flatMap(module -> module.getContainers().entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @Override public Map<String, ScreenInfo> getScreens() { return children.values() .stream() .flatMap(module -> module.getScreens().entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @Override public Map<String, ItemInfo> getItems() { return children.values() .stream() .flatMap(module -> module.getItems().entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @Override public Map<String, EnchantmentInfo> getEnchantments() { return children.values() .stream() .flatMap(module -> module.getEnchantments().entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @Override public Map<String, ItemGroupInfo> getCreativeTabs() { return children.values() .stream() .flatMap(module -> module.getCreativeTabs().entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } }
mit
prakashversion1/ServiceSharingLiferay
portlets/Employee-portlet-service/src/main/java/com/test/portlets/NoSuchEmployeeException.java
1051
/** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.test.portlets; import com.liferay.portal.NoSuchModelException; /** * @author Brian Wing Shun Chan */ public class NoSuchEmployeeException extends NoSuchModelException { public NoSuchEmployeeException() { super(); } public NoSuchEmployeeException(String msg) { super(msg); } public NoSuchEmployeeException(String msg, Throwable cause) { super(msg, cause); } public NoSuchEmployeeException(Throwable cause) { super(cause); } }
mit
bobbylight/rak
src/test/java/org/sgc/rak/exceptions/ForbiddenExceptionTest.java
411
package org.sgc.rak.exceptions; import org.junit.Assert; import org.junit.Test; import org.springframework.http.HttpStatus; public class ForbiddenExceptionTest { @Test public void testConstructor() { ForbiddenException e = new ForbiddenException("forbidden"); Assert.assertEquals(HttpStatus.FORBIDDEN, e.getStatus()); Assert.assertEquals("forbidden", e.getMessage()); } }
mit
gjambet/hibrice
src/main/java/net/guillaume/maven/plugin/parsing/ItemsXmlParser.java
1463
package net.guillaume.maven.plugin.parsing; import net.guillaume.maven.plugin.model.HibriceModel; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; public class ItemsXmlParser { protected final Logger logger = LoggerFactory.getLogger(getClass()); private final HibriceModel model; public ItemsXmlParser(File file) { model = parse(file); } private HibriceModel parse(File file) { HibriceModel model = new HibriceModel(); SAXBuilder sxb = new SAXBuilder(); try { Document document = sxb.build(file); Element root = document.getRootElement(); for (Element element : root.getChildren()) { switch (element.getName()) { case "itemtypes": model.addAll(new ItemTypesParser(element).getClazz()); break; case "relations": model.addAll(new RelationsParser(element).getClazz()); break; } } } catch (JDOMException | IOException e) { logger.debug(e.getMessage(), e); model = null; } return model; } public HibriceModel getModel() { return model; } }
mit
Nedelosk/OreRegistry
src/main/java/oreregistry/integration/package-info.java
403
/* * Copyright (c) 2017 Nedelosk, Mezz * * This work (the MOD) is licensed under the "MIT" License, see LICENSE for details. */ @ParametersAreNonnullByDefault @FieldsAreNonnullByDefault @MethodsReturnNonnullByDefault package oreregistry.integration; import mcp.MethodsReturnNonnullByDefault; import oreregistry.util.FieldsAreNonnullByDefault; import javax.annotation.ParametersAreNonnullByDefault;
mit
RyanFehr/HackerRank
Algorithms/Strings/Mars Exploration/Solution.java
761
//Problem: https://www.hackerrank.com/challenges/mars-exploration //Java 8 import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); String S = in.next(); int count = 0; int currentPos = 0; for(char letter : S.toCharArray()) { if(currentPos % 3 == 1) { count += (letter != 'O') ? 1 : 0; } else { count += (letter != 'S') ? 1 : 0; } currentPos++; } System.out.println(count); } }
mit
TranThiNha/MySimpleTweets
app/src/main/java/com/codepath/apps/mysimpletweets/models/Tweet.java
5158
package com.codepath.apps.mysimpletweets.models; import android.provider.MediaStore; import android.text.format.DateUtils; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import cz.msebera.android.httpclient.ParseException; /** * Created by ThiNha on 10/29/2016. */ public class Tweet implements Serializable { @SerializedName("retweeted") private boolean retweeted; @SerializedName("favorited") private boolean favourited; @SerializedName("text") String body; @SerializedName("id") long uid; @SerializedName("location") String location; @SerializedName("retweet_count") int retweetCount; @SerializedName("favorite_count") int favouritesCount; @SerializedName("created_at") String createAt; @SerializedName("user") private User user; @SerializedName("url") private String Url; String avatarUrl; String userScreenName; String relativeTimestamp = ""; String mediaUrl; long userId; @SerializedName("entities") private JsonObject entities; private List<Media>medias; public void setAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl; } public void setUserScreenName(String userScreenName) { this.userScreenName = userScreenName; } public void setMediaUrl(String mediaUrl) { this.mediaUrl = mediaUrl; } public void setRetweeted(boolean retweeted) { this.retweeted = retweeted; } public void setFavourited(boolean favourited) { this.favourited = favourited; } public void setBody(String body) { this.body = body; } public void setUid(long uid) { this.uid = uid; } public void setRetweetCount(int retweetCount) { this.retweetCount = retweetCount; } public void setFavouritesCount(int favouritesCount) { this.favouritesCount = favouritesCount; } public void setUrl(String url) { Url = url; } public void setRelativeTimestamp(String relativeTimestamp) { this.relativeTimestamp = relativeTimestamp; } public String getLocation() { return location; } public List<Media>getMedias(){ medias = new ArrayList<>(); Gson gson = new Gson(); if(entities!=null) { medias = gson.fromJson(entities.getAsJsonArray("media"),new TypeToken<List<Media>>(){}.getType()); } if (medias!=null && medias.size()>0){ mediaUrl = medias.get(0).getMediaUrl(); }else { mediaUrl = ""; } return medias; } public String getMediaUrl() { return mediaUrl; } public int getRetweetCount() { return retweetCount; } public String getRelativeTimestamp() { return relativeTimestamp; } public String getBody() { return body; } public long getUid() { return uid; } public boolean isRetweeted() { return retweeted; } public boolean isFavourited() { return favourited; } public User getUser() { if(user!=null) { avatarUrl = user.getProfileImageUrl(); userScreenName = user.getScreenName(); userId = user.getUid(); } return user; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getAvatarUrl() { return avatarUrl; } public String getUserScreenName() { return userScreenName; } public String getUrl() { return Url; } public int getFavouritesCount() { return favouritesCount; } public String getCreateAt() { return createAt; } public String _getRelativeTimeAgo(){ return relativeTimestamp; } // getRelativeTimeAgo("Mon Apr 01 21:16:23 +0000 2014"); public String getRelativeTimeAgo(String rawJsonDate) { String twitterFormat = "EEE MMM dd HH:mm:ss ZZZZZ yyyy"; SimpleDateFormat sf = new SimpleDateFormat(twitterFormat, Locale.ENGLISH); sf.setLenient(true); String relativeDate = ""; try { if (rawJsonDate!=null) { long dateMillis = sf.parse(rawJsonDate).getTime(); relativeDate = DateUtils.getRelativeTimeSpanString(dateMillis, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS).toString(); relativeTimestamp = relativeDate; } } catch (ParseException e) { e.printStackTrace(); } catch (java.text.ParseException e) { e.printStackTrace(); } return relativeDate; } }
mit
ChengCorp/robolectric
robolectric/src/test/java/org/robolectric/shadows/ShadowScrollerTest.java
2558
package org.robolectric.shadows; import static org.assertj.core.api.Assertions.assertThat; import android.view.animation.BounceInterpolator; import android.widget.Scroller; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RuntimeEnvironment; import org.robolectric.TestRunners; @RunWith(TestRunners.MultiApiSelfTest.class) public class ShadowScrollerTest { private Scroller scroller; @Before public void setup() throws Exception { scroller = new Scroller(RuntimeEnvironment.application, new BounceInterpolator()); } @Test public void shouldScrollOverTime() throws Exception { scroller.startScroll(0, 0, 12, 36, 1000); assertThat(scroller.getStartX()).isEqualTo(0); assertThat(scroller.getStartY()).isEqualTo(0); assertThat(scroller.getFinalX()).isEqualTo(12); assertThat(scroller.getFinalY()).isEqualTo(36); assertThat(scroller.getDuration()).isEqualTo(1000); assertThat(scroller.getCurrX()).isEqualTo(0); assertThat(scroller.getCurrY()).isEqualTo(0); assertThat(scroller.isFinished()).isFalse(); assertThat(scroller.timePassed()).isEqualTo(0); ShadowLooper.idleMainLooper(334); assertThat(scroller.getCurrX()).isEqualTo(4); assertThat(scroller.getCurrY()).isEqualTo(12); assertThat(scroller.isFinished()).isFalse(); assertThat(scroller.timePassed()).isEqualTo(334); ShadowLooper.idleMainLooper(166); assertThat(scroller.getCurrX()).isEqualTo(6); assertThat(scroller.getCurrY()).isEqualTo(18); assertThat(scroller.isFinished()).isFalse(); assertThat(scroller.timePassed()).isEqualTo(500); ShadowLooper.idleMainLooper(500); assertThat(scroller.getCurrX()).isEqualTo(12); assertThat(scroller.getCurrY()).isEqualTo(36); assertThat(scroller.isFinished()).isFalse(); assertThat(scroller.timePassed()).isEqualTo(1000); ShadowLooper.idleMainLooper(1); assertThat(scroller.isFinished()).isTrue(); assertThat(scroller.timePassed()).isEqualTo(1001); } @Test public void computeScrollOffsetShouldCalculateWhetherScrollIsFinished() throws Exception { assertThat(scroller.computeScrollOffset()).isFalse(); scroller.startScroll(0, 0, 12, 36, 1000); assertThat(scroller.computeScrollOffset()).isTrue(); ShadowLooper.idleMainLooper(500); assertThat(scroller.computeScrollOffset()).isTrue(); ShadowLooper.idleMainLooper(500); assertThat(scroller.computeScrollOffset()).isTrue(); assertThat(scroller.computeScrollOffset()).isFalse(); } }
mit
mikolajs/java-teaching
spring-mvc-hotel/src/main/java/pl/edu/osp/config/Config.java
507
package pl.edu.osp.config; import java.util.ArrayList; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import pl.edu.osp.api.*; import pl.edu.osp.impl.*; @Configuration public class Config { @Bean public IRoom room() { ArrayList<RoomOption> rooms = new ArrayList<RoomOption>(); rooms.add(new RoomOption( 2, 40)); rooms.add(new RoomOption(3, 45)); rooms.add(new RoomOption(2, 40)); return new Room(1, "Jaśminowy", rooms); } }
mit
EDACC/edacc_gui
src/edacc/parameterspace/domain/Domain.java
894
package edacc.parameterspace.domain; import java.io.Serializable; import java.util.List; import java.util.Random; import javax.xml.bind.annotation.XmlSeeAlso; @XmlSeeAlso({ CategoricalDomain.class, FlagDomain.class, IntegerDomain.class, MixedDomain.class, OptionalDomain.class, RealDomain.class, OrdinalDomain.class}) public abstract class Domain implements Serializable { public static final String[] names = {CategoricalDomain.name, FlagDomain.name, IntegerDomain.name, MixedDomain.name, OptionalDomain.name, OrdinalDomain.name, RealDomain.name}; public abstract boolean contains(Object value); public abstract Object randomValue(Random rng); public abstract String toString(); public abstract Object mutatedValue(Random rng, Object value); public abstract List<Object> getDiscreteValues(); public abstract String getName(); }
mit
luodeng/test
frame/src/main/java/com/drew/SampleUsage.java
4959
package com.drew;/* * Copyright 2002-2016 Drew Noakes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ import com.drew.imaging.ImageMetadataReader; import com.drew.imaging.ImageProcessingException; import com.drew.imaging.jpeg.JpegMetadataReader; import com.drew.imaging.jpeg.JpegProcessingException; import com.drew.imaging.jpeg.JpegSegmentMetadataReader; import com.drew.metadata.Directory; import com.drew.metadata.Metadata; import com.drew.metadata.Tag; import com.drew.metadata.exif.ExifReader; import com.drew.metadata.iptc.IptcReader; import java.io.File; import java.io.IOException; import java.util.Arrays; /** * Showcases the most popular ways of using the metadata-extractor library. * <p> * For more information, see the project wiki: https://github.com/drewnoakes/metadata-extractor/wiki/GettingStarted * * @author Drew Noakes https://drewnoakes.com */ public class SampleUsage { /** * Executes the sample usage program. * * @param args command line parameters */ public static void main(String[] args) { File file = new File("G:\\BaiduYunDownload\\2016-07-03 143102.jpg"); // There are multiple ways to get a Metadata object for a file // // SCENARIO 1: UNKNOWN FILE TYPE // // This is the most generic approach. It will transparently determine the file type and invoke the appropriate // readers. In most cases, this is the most appropriate usage. This will handle JPEG, TIFF, GIF, BMP and RAW // (CRW/CR2/NEF/RW2/ORF) files and extract whatever metadata is available and understood. // try { Metadata metadata = ImageMetadataReader.readMetadata(file); print(metadata); } catch (ImageProcessingException e) { // handle exception } catch (IOException e) { // handle exception } // // SCENARIO 2: SPECIFIC FILE TYPE // // If you know the file to be a JPEG, you may invoke the JpegMetadataReader, rather than the generic reader // used in approach 1. Similarly, if you knew the file to be a TIFF/RAW image you might use TiffMetadataReader, // PngMetadataReader for PNG files, BmpMetadataReader for BMP files, or GifMetadataReader for GIF files. // // Using the specific reader offers a very, very slight performance improvement. // try { Metadata metadata = JpegMetadataReader.readMetadata(file); print(metadata); } catch (JpegProcessingException e) { // handle exception } catch (IOException e) { // handle exception } // // APPROACH 3: SPECIFIC METADATA TYPE // // If you only wish to read a subset of the supported metadata types, you can do this by // passing the set of readers to use. // // This currently only applies to JPEG file processing. // try { // We are only interested in handling Iterable<JpegSegmentMetadataReader> readers = Arrays.asList(new ExifReader(), new IptcReader()); Metadata metadata = JpegMetadataReader.readMetadata(file, readers); print(metadata); } catch (JpegProcessingException e) { // handle exception } catch (IOException e) { // handle exception } } private static void print(Metadata metadata) { System.out.println("-------------------------------------"); // Iterate over the data and print to System.out // // A Metadata object contains multiple Directory objects // for (Directory directory : metadata.getDirectories()) { // // Each Directory stores values in Tag objects // for (Tag tag : directory.getTags()) { System.out.println(tag); } // // Each Directory may also contain error messages // if (directory.hasErrors()) { for (String error : directory.getErrors()) { System.err.println("ERROR: " + error); } } } } }
mit
ftp27/HelmetManager
src/main/java/ftp27/apps/helmet/managers/res.java
3064
package ftp27.apps.helmet.managers; import android.util.Log; import ftp27.apps.helmet.server.NanoHTTPD; import ftp27.apps.helmet.server.NanoHTTPD.Response; import java.io.*; import java.util.Map; import java.util.Properties; /** * Created by ftp27 on 05.05.14. */ public class res { private static String LOG_TAG = "Class [res]"; public Response request(String uri, NanoHTTPD.Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) { String[] uris = uri.split("/"); String Address = "/site"+getAddress(uri);//File.pathSeparator; Log.d(LOG_TAG, "Checking file "+Address); InputStream in = getClass().getResourceAsStream(Address); String mime = getMimeType(uris[uris.length-1],NanoHTTPD.MIME_HTML); return new Response(Response.Status.OK, mime, in); } public NanoHTTPD.Response download(String uri, NanoHTTPD.Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) { String[] uris = uri.split("/"); String Address = getAddress(uri); try { InputStream in = new FileInputStream(Address); String mime = getMimeType(uris[uris.length-1],NanoHTTPD.MIME_DEFAULT_BINARY); return new NanoHTTPD.Response(Response.Status.OK, mime, in); } catch (FileNotFoundException e) { e.printStackTrace(); } return new NanoHTTPD.Response(Response.Status.NOT_FOUND, NanoHTTPD.MIME_DEFAULT_BINARY, ""); } public static String getAddress(String uri) { String[] uris = uri.split("/"); String Address = "/";//File.pathSeparator; if (uris.length > 2) { for (int i = 2; i < uris.length; i++) { Address += uris[i];//File.pathSeparator; if (i != uris.length - 1) { Address += "/"; } } } return Address; } public static String getMimeType(String fileName, String defaultType) { String mime = defaultType; String[] nameFile = fileName.split("\\."); if (nameFile.length > 0) { String extension = nameFile[nameFile.length - 1]; if (extension.equals("js")) { mime = NanoHTTPD.MIME_JAVASCRIPT; } else if (extension.equals("css")) { mime = NanoHTTPD.MIME_CSS; } else if (extension.equals("png")) { mime = NanoHTTPD.MIME_PNG; } else if ((extension.equals("jpg")) || (extension.equals("jpeg"))) { mime = NanoHTTPD.MIME_JPEG; } else if ((extension.equals("gif"))) { mime = NanoHTTPD.MIME_GIF; } else if ((extension.equals("tiff"))) { mime = NanoHTTPD.MIME_TIFF; } else if ((extension.equals("pdf"))) { mime = NanoHTTPD.MIME_PDF; } } return mime; } }
mit
a11n/bruteforce
src/main/java/de/ad/kata/bruteforce/BruteForcer.java
2013
package de.ad.kata.bruteforce; import java.util.Arrays; public class BruteForcer { private final char[] alphabet; private final int alphabetLength; private int[] indices; private char[] combination; private static final String NUMERIC_ALPHABET = "0123456789"; private static final String LOWER_CASE_ALPHABET = "abcdefghijklmnopqrstuvwxyz"; private static final String UPPER_CASE_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private BruteForcer(String alphabet) { this.alphabet = alphabet.toCharArray(); this.alphabetLength = alphabet.length(); indices = new int[1]; combination = new char[1]; } public static BruteForcer createNumericBruteForcer(){ return new BruteForcer(NUMERIC_ALPHABET); } public static BruteForcer createAlphaBruteForcer(){ return new BruteForcer(LOWER_CASE_ALPHABET + UPPER_CASE_ALPHABET); } public static BruteForcer createAlphaNumericBruteForcer(){ return new BruteForcer(LOWER_CASE_ALPHABET + UPPER_CASE_ALPHABET + NUMERIC_ALPHABET); } public static BruteForcer createGenericBruteForcer(String alphabet){ return new BruteForcer(alphabet); } public String computeNextCombination() { combination[0] = alphabet[indices[0]]; String nextCombination = String.valueOf(combination); if (indices[0] < alphabetLength - 1) { indices[0]++; } else { for (int i = 0; i < indices.length; i++) { if (indices[i] < alphabetLength - 1) { indices[i]++; combination[i] = alphabet[indices[i]]; break; } else { indices[i] = 0; combination[i] = alphabet[indices[i]]; if (i == indices.length - 1) { indices = Arrays.copyOf(indices, indices.length + 1); combination = Arrays.copyOf(combination, combination.length + 1); combination[combination.length - 1] = alphabet[indices[indices.length - 1]]; break; } } } } return nextCombination; } }
mit
tlenaic/zap-plugin
src/main/java/org/jenkinsci/plugins/zap/report/ZAPReportXML.java
1903
/* * The MIT License (MIT) * * Copyright (c) 2016 Goran Sarenkapa (JordanGS), and a number of other of 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.jenkinsci.plugins.zap.report; import org.zaproxy.clientapi.core.ClientApi; import org.zaproxy.clientapi.core.ClientApiException; /** * Used to generate ZAP report in xml. * * @author Goran Sarenkapa * @author Mostafa AbdelMoez * @author Tanguy de Lignières * @author Abdellah Azougarh * @author Thilina Madhusanka * @author Johann Ollivier-Lapeyre * @author Ludovic Roucoux * */ @SuppressWarnings("serial") public class ZAPReportXML extends ZAPReport { public ZAPReportXML() { this.format = ZAPReport.REPORT_FORMAT_XML; } @Override public byte[] generateReport(ClientApi clientApi, String apikey) throws ClientApiException { return clientApi.core.xmlreport(); } }
mit
RAVURISREESAIHARIKRISHNA/Hackerrank
Algorithms/Strings/Alternating Characters/Solution.java
625
import java.util.Scanner; public class Solution{ public static void main(String args[]){ Scanner s = new Scanner(System.in); int n; n = s.nextInt(); s.nextLine(); int arr[] = new int[n]; String temp; for(int i=0;i<=n-1;i++){ temp = s.nextLine(); int count=0; for(int j=0;j<=temp.length()-2;j++){ if(temp.charAt(j)==temp.charAt(j+1)){ count++; } } arr[i] = count; } for(int i : arr){ System.out.println(i); } } }
mit
Chistaen/Project-Alpha
src/user/User.java
654
/** * PROJECT ALPHA * Open source hotel management software * * @version 1.0 Alpha 1 * @author Rick Nieborg, Mark Nieborg, Robert Monden * @copyright Project Alpha, 2016-2017 * @license MIT * * Class information: * @package User * @since 1.0 Alpha 1 * @author Project Alpha development team */ package user; public class User { private String _username; private int _rank; public User(String username, int rank) { _username = username; _rank = rank; } public String getUsername() { return _username; } public int getRank() { return _rank; } }
mit
simonpercic/AirCycle
example/src/main/java/com/github/simonpercic/example/aircycle/activity/a08/BindConfigActivity.java
1533
package com.github.simonpercic.example.aircycle.activity.a08; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.github.simonpercic.aircycle.ActivityLifecycle; import com.github.simonpercic.aircycle.AirCycle; import com.github.simonpercic.aircycle.AirCycleConfig; import com.github.simonpercic.example.aircycle.R; import com.github.simonpercic.example.aircycle.listener.BundleListener; /** * Example Activity showing usage of a custom AirCycleConfig passed while binding. * * @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a> */ public class BindConfigActivity extends AppCompatActivity { @AirCycle final BundleListener bundleListener = new BundleListener(); @Override protected void onCreate(Bundle savedInstanceState) { AirCycleConfig airCycleConfig = AirCycleConfig.builder() .passIntentBundleOnCreate(true) .ignoreLifecycleCallback(ActivityLifecycle.RESUME) .ignoreLifecycleCallback(ActivityLifecycle.PAUSE) .build(); BindConfigActivityAirCycle.bind(this, airCycleConfig); super.onCreate(savedInstanceState); setContentView(R.layout.activity_base); } public static Intent getIntent(Context context) { Intent intent = new Intent(context, BindConfigActivity.class); intent.putExtra(BundleListener.EXTRA_INT, 7); return intent; } }
mit
dowobeha/thrax
src/edu/jhu/thrax/datatypes/Rule.java
10735
package edu.jhu.thrax.datatypes; import edu.jhu.thrax.util.Vocabulary; import edu.jhu.thrax.ThraxConfig; import java.util.Arrays; import java.util.ArrayList; /** * This class represents a synchronous context-free production rule. */ public class Rule { /** * The left-hand side symbol. */ int lhs; /** * A PhrasePair describing the boundaries of the right-hand side of this * rule relative to the source and target sentences. */ public PhrasePair rhs; // backing data, from sentence. shared among all rules extracted from // this sentence. /** * The source-side sentence. */ public int [] source; /** * The target-side sentence. */ public int [] target; /** * Alignment between the source- and target-side sentences. */ public Alignment alignment; /** * Labels for nonterminals of this rule. */ int [] nts; /** * Number of nonterminals in this rule. */ public byte numNTs; /** * Whether or not the source right-hand side ends with a nonterminal * symbol. */ public boolean sourceEndsWithNT; /** * The point at which a new symbol should be attached on the source side * of the right-hand side. */ public int appendPoint; /** * Array describing the lexicality of the source side. A value less than * zero means that the source word is not present in the rule. Zero means * the word is present as a terminal symbol. Greater than zero indicates * the NT that the word is part of. */ public byte [] sourceLex; /** * Array describing the lexicality of the target side. */ public byte [] targetLex; /** * Number of aligned words on the source side of the right-hand side of * this rule. */ public int alignedWords; /** * Total number of terminal symbols on the source side of the right-hand * side of this rule. */ public int numTerminals; /** * The textual yield of source side of this rule. */ ArrayList<Integer> sourceYield; /** * The textual yield of the target side of this rule. */ ArrayList<Integer> targetYield; private Rule() { } /** * Constructor. * * @param f the source side sentence * @param e the target side sentence * @param a the Alignment between source and target side * @param start the starting index of the source side of this Rule's RHS * @param arity maximum number of nonterminals */ public Rule(int [] f, int [] e, Alignment a, int start, int arity) { source = f; target = e; alignment = a; nts = new int[arity]; Arrays.fill(nts, -1); numNTs = 0; sourceEndsWithNT = false; sourceLex = new byte[f.length]; Arrays.fill(sourceLex, (byte) -1); targetLex = new byte[e.length]; Arrays.fill(targetLex, (byte) -1); appendPoint = start; alignedWords = 0; numTerminals = 0; rhs = new PhrasePair(start, start + 1, -1, -1); sourceYield = new ArrayList<Integer>(); targetYield = new ArrayList<Integer>(); } /** * Makes an almost-deep copy of this rule, where the backing datatypess are * not cloned, but the rule-specific data is cloned so that it can be * modified. * * @return a copy of this Rule, suitable for modifying */ public Rule copy() { Rule ret = new Rule(); ret.lhs = this.lhs; ret.rhs = (PhrasePair) this.rhs.clone(); ret.source = this.source; ret.target = this.target; ret.alignment = this.alignment; ret.nts = (int []) this.nts.clone(); ret.numNTs = this.numNTs; ret.sourceEndsWithNT = this.sourceEndsWithNT; ret.sourceLex = (byte []) this.sourceLex.clone(); ret.targetLex = (byte []) this.targetLex.clone(); ret.appendPoint = this.appendPoint; ret.alignedWords = this.alignedWords; ret.numTerminals = this.numTerminals; ret.sourceYield = new ArrayList<Integer>(); ret.targetYield = new ArrayList<Integer>(); for (int x : this.sourceYield()) ret.sourceYield.add(x); for (int y : this.targetYield()) ret.targetYield.add(y); return ret; } /** * Gets the left-hand side symbol for this rule. * * @return the LHS symbol */ public int getLhs() { return lhs; } /** * Sets the left-hand side symbol for this rule. * * @param label the new label for the left-hand side */ public void setLhs(int label) { lhs = label; } /** * Gets the label for a nonterminal symbol in this rule. * * @param index the number of the NT to return */ public int getNT(int index) { return nts[index]; } /** * Sets the label for a nonterminal symbol in this rule. * * @param index the number of the NT to modify * @param label the new label for the NT */ public void setNT(int index, int label) { nts[index] = label; } /** * Attaches a nonterminal symbol to the yield of this Rule. The terminal's * extent is defined by the given PhrasePair. The symbol for the * nonterminal is not set. * * @param pp the spans of this new NT */ public void extendWithNonterminal(PhrasePair pp) { numNTs++; for (; appendPoint < pp.sourceEnd; appendPoint++) sourceLex[appendPoint] = numNTs; for (int idx = pp.targetStart; idx < pp.targetEnd; idx++) targetLex[idx] = numNTs; rhs.sourceEnd = pp.sourceEnd; if (rhs.targetStart < 0 || pp.targetStart < rhs.targetStart) rhs.targetStart = pp.targetStart; if (pp.targetEnd > rhs.targetEnd) rhs.targetEnd = pp.targetEnd; sourceEndsWithNT = true; } /** * Attaches a terminal symbol to the source-side yield of this Rule. Also * attaches any terminals for the target side that are aligned to the * source side symbol. */ public void extendWithTerminal() { sourceLex[appendPoint] = 0; numTerminals++; sourceEndsWithNT = false; if (!alignment.sourceIsAligned(appendPoint)) { appendPoint++; rhs.sourceEnd = appendPoint; return; } for (int j : alignment.f2e[appendPoint]) { targetLex[j] = 0; if (rhs.targetEnd < 0 || j + 1 > rhs.targetEnd) rhs.targetEnd = j + 1; if (rhs.targetStart < 0 || j < rhs.targetStart) rhs.targetStart = j; } alignedWords++; appendPoint++; rhs.sourceEnd = appendPoint; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("[%s]", Vocabulary.getWord(lhs))); sb.append(String.format( " %s", ThraxConfig.DELIMITER)); int last = -1; for (int i = rhs.sourceStart; i < rhs.sourceEnd; i++) { int x = sourceLex[i]; if (x < 0) continue; if (x == 0) sb.append(String.format(" %s", Vocabulary.getWord(source[i]))); else if (x != last) { sb.append(String.format(" [%s,%d]", Vocabulary.getWord(nts[x-1]), x)); last = x; } } sb.append(String.format(" %s", ThraxConfig.DELIMITER)); last = -1; for (int i = rhs.targetStart; i < rhs.targetEnd; i++) { int x = targetLex[i]; if (x < 0) continue; if (x == 0) sb.append(String.format(" %s", Vocabulary.getWord(target[i]))); else if (x != last) { sb.append(String.format(" [%s,%d]", Vocabulary.getWord(nts[x-1]), x)); last = x; } } return sb.toString(); } /** * Two rules are considered equal if they have the same textual * representation. * * @param o the object to compare to * @return true if these objects are equal, false otherwise */ public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Rule)) return false; Rule other = (Rule) o; return (this.lhs == other.lhs && this.sourceYield().equals(other.sourceYield()) && this.targetYield().equals(other.targetYield())); } /** * An integer representation of the textual representation of this Rule. * Useful because equality is defined in terms of the yield. */ public ArrayList<Integer> sourceYield() { sourceYield.clear(); int last = -1; for (int i = rhs.sourceStart; i < rhs.sourceEnd; i++) { int x = sourceLex[i]; if (x == 0) sourceYield.add(source[i]); if (x > 0 && x != last) { last = x; sourceYield.add(nts[last-1]); } } return sourceYield; } public ArrayList<Integer> targetYield() { targetYield.clear(); int last = -1; for (int j = rhs.targetStart; j < rhs.targetEnd; j++) { int y = targetLex[j]; if (y < 0) targetYield.add(y); if (y == 0) targetYield.add(target[j]); if (y > 0 && y != last) { last = y; targetYield.add(nts[last-1]); } } return targetYield; } public int hashCode() { int result = 17; result = result * 37 + lhs; result = result * 37 + sourceYield().hashCode(); result = result * 37 + targetYield().hashCode(); return result; } /** * Returns the target-side span of the indexed nonterminal symbol. * * @param index the number of the NT whose span we want * @return an IntPair describing the target span of the NT */ public IntPair ntSpan(int index) { if (index < 0 || index > numNTs - 1) return null; int start = -1; for (int i = rhs.targetStart; i < rhs.targetEnd; i++) { int x = targetLex[i]; if (x == index + 1 && start == -1) start = i; if (start != -1 && x != index + 1) return new IntPair(start, i); } return new IntPair(start, rhs.targetEnd); } }
mit
thombergs/code-examples
spring-cloud/feign-with-spring-data-rest/src/main/java/com/example/demo/AddressClient.java
1110
package com.example.demo; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.hateoas.Resource; import org.springframework.hateoas.Resources; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @FeignClient(value = "addresses", path = "/addresses_mto") public interface AddressClient { @RequestMapping(method = RequestMethod.GET, path = "/") Resources<Address> getAddresses(); @RequestMapping(method = RequestMethod.GET, path = "/{id}") Resource<Address> getAddress(@PathVariable("id") long id); @RequestMapping(method = RequestMethod.PUT, consumes = "text/uri-list", path="/{addressId}/customer") Resource<Address> associateWithCustomer(@PathVariable("addressId") long addressId, @RequestBody String customerUri); @RequestMapping(method = RequestMethod.GET, path="/{addressId}/customer") Resource<Customer> getCustomer(@PathVariable("addressId") long addressId); }
mit
ranian129/webworkbook
webworkbook/src/spms/servlets/MemberAddServlet.java
1486
package spms.servlets; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import spms.dao.MemberDao; import spms.vo.Member; // 프론트 컨트롤러 적용 @WebServlet("/member/add") public class MemberAddServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setAttribute("viewUrl", "/member/MemberForm.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int result = 0; try { ServletContext sc = this.getServletContext(); Member member = (Member) req.getAttribute("member"); MemberDao memberDao = (MemberDao) sc.getAttribute("memberDao"); result = memberDao.insert(member); if (result != 1) { throw new ServletException("Failed in insert, result:" + result); } req.setAttribute("viewUrl", "redirect:list.do"); } catch (Exception e) { throw new ServletException(e); } } }
mit
eduardodaluz/xfire
xfire-spring/src/main/org/codehaus/xfire/spring/config/Soap12BindingBean.java
170
package org.codehaus.xfire.spring.config; /** * @org.apache.xbean.XBean element="soap12Binding" */ public class Soap12BindingBean extends AbstractSoapBindingBean { }
mit
kalpas-team/hackaton
src/main/java/mygalaxy/inst/api/Relations.java
2280
package mygalaxy.inst.api; import mygalaxy.inst.domain.InstResponse; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; @Component public class Relations { public InstResponse getFollowers(String userId, String accessToken) { MultiValueMap<String, String> headers = new HttpHeaders(); HttpEntity<Object> httpEntity = new HttpEntity<Object>(headers); RestTemplate template = new RestTemplate(); ResponseEntity<InstResponse> response = template.exchange(("https://api.instagram.com/v1/users/" + userId + "/follows?access_token=" + accessToken), HttpMethod.GET, httpEntity, InstResponse.class); InstResponse toReturn = new InstResponse(); do { if (response.getBody() != null) { toReturn.data.addAll(response.getBody().data); if (response.getBody().pagination != null && response.getBody().pagination.next_url != null) { response = template.exchange(response.getBody().pagination.next_url, HttpMethod.GET, httpEntity, InstResponse.class); } else { response = null; } } } while (response != null); return toReturn; } public InstResponse getFollowedBy(String userId, String accessToken) { MultiValueMap<String, String> headers = new HttpHeaders(); HttpEntity<Object> httpEntity = new HttpEntity<Object>(headers); RestTemplate template = new RestTemplate(); return template.exchange( ("https://api.instagram.com/v1/users/" + userId + "/followed-by?access_token=" + accessToken), HttpMethod.GET, httpEntity, InstResponse.class).getBody(); } public InstResponse getRequestedBy(String userId, String accessToken) { MultiValueMap<String, String> headers = new HttpHeaders(); HttpEntity<Object> httpEntity = new HttpEntity<Object>(headers); RestTemplate template = new RestTemplate(); return template.exchange( ("https://api.instagram.com/v1/users/" + userId + "/requested-by?access_token=" + accessToken), HttpMethod.GET, httpEntity, InstResponse.class).getBody(); } }
mit
Luiz-Mnix/MazinRPCaiser
mazinrpcaiser-server/src/test/java/br/com/mnix/mazinrpcaiser/server/data/DataGridTest.java
3309
package br.com.mnix.mazinrpcaiser.server.data; import com.hazelcast.core.Message; import com.hazelcast.core.MessageListener; import org.junit.Test; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; public class DataGridTest { @Test public void testRetrieveContext() throws Exception { // Arrange final IDataGrid dataGrid = new DataGrid(); final String contextId = "context"; // Act dataGrid.raise(); IContext context = dataGrid.retrieveContext(contextId, true); // Assert assertEquals(0, context.size()); context.putObject("foo", "foo"); assertEquals(1, dataGrid.retrieveContext(contextId, false).size()); assertEquals(0, dataGrid.retrieveContext(contextId, true).size()); dataGrid.shutdown(); } @Test public void testDeleteContext() throws Exception { // Arrange final IDataGrid dataGrid = new DataGrid(); final String contextId = "context2"; // Act dataGrid.raise(); IContext context = dataGrid.retrieveContext(contextId, true); context.putObject("foo", "foo"); // Assert assertEquals(1, dataGrid.retrieveContext(contextId, false).size()); dataGrid.deleteContext(contextId); assertEquals(0, dataGrid.retrieveContext(contextId, false).size()); dataGrid.shutdown(); } @Test public void testGetCommandQueue() throws Exception { // Arrange final IDataGrid dataGrid = new DataGrid(); final String queueId = "queue"; final Runnable putter = new Runnable() { @Override public void run() { BlockingQueue<String> queue = dataGrid.getCommandQueue(queueId); try { Thread.sleep(1000); queue.put("foo"); } catch (InterruptedException e) { e.printStackTrace(); } } }; // Act dataGrid.raise(); new Thread(putter).start(); final BlockingQueue<String> queue = dataGrid.getCommandQueue(queueId); String command = queue.poll(2, TimeUnit.SECONDS); // Assert assertEquals("foo", command); dataGrid.shutdown(); } @Test public void testPostNotification() throws Exception { // Arrange final IDataGrid dataGrid = new DataGrid(); final String topicId = "topic"; final Semaphore semaphore = new Semaphore(0); final String[] data = new String[1]; final MessageListener listener = new MessageListener() { @Override public void onMessage(Message message) { data[0] = message.getMessageObject().toString(); semaphore.release(); } }; final TimerTask timeout = new TimerTask() { @Override public void run() { semaphore.release(); } }; // Act dataGrid.raise(); final String listenerId = dataGrid.addListener(topicId, listener); dataGrid.postNotification(topicId, "foo"); semaphore.acquire(); // Assert assertEquals("foo", data[0]); dataGrid.removeListener(topicId, listenerId); new Timer().schedule(timeout, 1000); dataGrid.postNotification(topicId, "bar"); semaphore.acquire(); assertEquals("foo", data[0]); dataGrid.shutdown(); } @Test(expected = IllegalStateException.class) public void testCheckIfIsOn() throws Exception { // Arrange final IDataGrid dataGrid = new DataGrid(); // Act & Assert dataGrid.retrieveContext("foo", false); } }
mit
wolfgangimig/joa
java/joa-im/src-gen/com/wilutions/mslib/uccollaborationlib/impl/IWorkingHoursImpl.java
1218
/* ** GENEREATED FILE - DO NOT MODIFY ** */ package com.wilutions.mslib.uccollaborationlib.impl; import com.wilutions.com.*; @SuppressWarnings("all") @CoClass(guid="{93478DAA-F0B8-99F2-0053-E7C4BB053FAC}") public class IWorkingHoursImpl extends Dispatch implements com.wilutions.mslib.uccollaborationlib.IWorkingHours { @DeclDISPID(1610743808) public String getEmailAddress() throws ComException { final Object obj = this._dispatchCall(1610743808,"EmailAddress", DISPATCH_PROPERTYGET,null); if (obj == null) return null; return (String)obj; } @DeclDISPID(1610743809) public com.wilutions.mslib.uccollaborationlib.IWorkingPeriod[] getWorkingPeriods() throws ComException { final Object obj = this._dispatchCall(1610743809,"WorkingPeriods", DISPATCH_PROPERTYGET,null); if (obj == null) return null; return (com.wilutions.mslib.uccollaborationlib.IWorkingPeriod[])obj; } public IWorkingHoursImpl(String progId) throws ComException { super(progId, "{53D014C1-54DB-42B3-9DFD-8E231EF2C356}"); } protected IWorkingHoursImpl(long ndisp) { super(ndisp); } public String toString() { return "[IWorkingHoursImpl" + super.toString() + "]"; } }
mit
franziheck/Paulette
src/Main.java
1186
import org.paulette.res.PropsHandler; import org.telegram.telegrambots.ApiContextInitializer; import org.telegram.telegrambots.TelegramBotsApi; import org.telegram.telegrambots.exceptions.TelegramApiException; import java.io.File; public class Main { public static void main (String[] args){ ApiContextInitializer.init(); initializeServer(); registerBots(); } private static void initializeServer(){ if(new File("config.properties").isFile()){ System.out.println("Welcome Back"); }else{ PropsHandler.createProperties("", false); System.out.println("Created config.properties.... Please enter BotToken to connect to Telegram"); System.exit(0); } } private static void registerBots(){ TelegramBotsApi botsApi = new TelegramBotsApi(); try{ botsApi.registerBot(new Paulette()); System.out.println("Success! BotServer connected to Telegram Server"); } catch (TelegramApiException e) { System.out.println("Unable to connect to Telegram Server. Please check BotToken and Internet Settings"); } } }
mit
FTC7393/state-machine-framework
src/ftc/electronvolts/test/util/UtilityTest.java
5105
package ftc.electronvolts.test.util; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.junit.Test; import ftc.electronvolts.util.Utility; public class UtilityTest { @Test public void testLimit() { assertEquals(-2, Utility.limit(-5, -2, 3), 0); assertEquals(-2, Utility.limit(-5, 3, -2), 0); assertEquals(3, Utility.limit(3.2, -2, 3), 0); assertEquals(3, Utility.limit(3.2, 3, -2), 0); assertEquals(1, Utility.limit(1, -2, 3), 0); assertEquals(1, Utility.limit(1, 3, -2), 0); assertEquals(Double.NaN, Utility.limit(Double.NaN, -2, 3), 0); } @Test public void testMirrorLimit() { assertEquals(-1.5, Utility.mirrorLimit(-2, 1.5), 0); assertEquals(-1.5, Utility.mirrorLimit(-2, -1.5), 0); assertEquals(1.5, Utility.mirrorLimit(3, 1.5), 0); assertEquals(1.5, Utility.mirrorLimit(3, -1.5), 0); assertEquals(1, Utility.mirrorLimit(1, 1.5), 0); assertEquals(1, Utility.mirrorLimit(1, -1.5), 0); } @Test public void testMotorLimit() { assertEquals(-1, Utility.motorLimit(-1.0001), 0); assertEquals(-1, Utility.motorLimit(-1.5), 0); assertEquals(-1, Utility.motorLimit(-1), 0); assertEquals(-0.5, Utility.motorLimit(-0.5), 0); assertEquals(0, Utility.motorLimit(0), 0); assertEquals(0.5, Utility.motorLimit(0.5), 0); assertEquals(1, Utility.motorLimit(1), 0); assertEquals(1, Utility.motorLimit(1.5), 0); assertEquals(1, Utility.motorLimit(1.0001), 0); } @Test public void testServoLimit() { assertEquals(0, Utility.servoLimit(-1.5), 0); assertEquals(0, Utility.servoLimit(-1), 0); assertEquals(0, Utility.servoLimit(-0.5), 0); assertEquals(0, Utility.servoLimit(0), 0); assertEquals(0.5, Utility.servoLimit(0.5), 0); assertEquals(1, Utility.servoLimit(1), 0); assertEquals(1, Utility.servoLimit(1.5), 0); } @Test public void testJoinListOfTString() { List<String> list = new ArrayList<>(); assertEquals("", Utility.join(list, "djhfaejlaekwrbfjladjv")); list.add("item 1"); list.add("item 2"); list.add("item 3"); assertEquals("item 1, item 2, item 3", Utility.join(list, ", ")); List<Integer> list1 = new ArrayList<>(); list1.add(1); list1.add(2); list1.add(3); assertEquals("1;2;3", Utility.join(list1, ";")); } @Test public void testJoinBooleanArrayString() { assertEquals("", Utility.join(new boolean[] {}, "32458y")); assertEquals("true", Utility.join(new boolean[] { true }, "34857028")); assertEquals("true-false-true-true", Utility.join(new boolean[] { true, false, true, true }, "-")); } @Test public void testJoinByteArrayString() { assertEquals("", Utility.join(new byte[] {}, "32458y")); assertEquals("100", Utility.join(new byte[] { 100 }, "34857028")); assertEquals("100 + 20 + -3 + -5 + -100", Utility.join(new byte[] { 100, 20, -3, -5, -100 }, " + ")); } @Test public void testJoinCharArrayString() { assertEquals("", Utility.join(new char[] {}, "32458y")); assertEquals("a", Utility.join(new char[] { 'a' }, "34857028")); assertEquals("q//w//e//r//t//y", Utility.join(new char[] { 'q', 'w', 'e', 'r', 't', 'y' }, "//")); } @Test public void testJoinShortArrayString() { assertEquals("", Utility.join(new short[] {}, "32458y")); assertEquals("800", Utility.join(new short[] { 800 }, "34857028")); assertEquals("1 Mississippi 2 Mississippi 3 Mississippi 4 Mississippi 5", Utility.join(new short[] { 1, 2, 3, 4, 5 }, " Mississippi ")); } @Test public void testJoinIntArrayString() { assertEquals("", Utility.join(new int[] {}, "32458y")); assertEquals("200000", Utility.join(new int[] { 200000 }, "34857028")); assertEquals("2345~567~123~678~43~67~789", Utility.join(new int[] { 2345, 567, 123, 678, 43, 67, 789 }, "~")); } @Test public void testJoinLongArrayString() { assertEquals("", Utility.join(new long[] {}, "32458y")); assertEquals("492843750", Utility.join(new long[] { 492843750 }, "34857028")); assertEquals("44#55#66", Utility.join(new long[] { 44, 55, 66 }, "#")); } @Test public void testJoinFloatArrayString() { assertEquals("", Utility.join(new float[] {}, "32458y")); assertEquals("1.23456", Utility.join(new float[] { 1.23456f }, "34857028")); assertEquals("3.3<>400.0<>123.123<>456.789", Utility.join(new float[] { 3.3f, 400f, 123.123f, 456.789f }, "<>")); } @Test public void testJoinDoubleArrayString() { assertEquals("", Utility.join(new double[] {}, "32458y")); assertEquals("55.1", Utility.join(new double[] { 55.1 }, "34857028")); assertEquals("123.0&33.5&10005.0&234.555", Utility.join(new double[] { 123, 33.5, 10005, 234.555 }, "&")); } }
mit
ArcticWarriors/snobot-2017
Testbed/VisionTestSuite/src/com/snobot/vision/standalone/panels/HslTuningPanel.java
6550
package com.snobot.vision.standalone.panels; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import com.snobot.vision.HslThreshold; import com.snobot.vision.standalone.SetThresholdListener; public class HslTuningPanel extends JPanel { private SliderWithTextboxPanel minHueWidget; private SliderWithTextboxPanel maxHueWidget; private SliderWithTextboxPanel minSatWidget; private SliderWithTextboxPanel maxSatWidget; private SliderWithTextboxPanel minLumWidget; private SliderWithTextboxPanel maxLumWidget; private SetThresholdListener listener; public HslTuningPanel() { initComponents(); minHueWidget.setValue(0); maxHueWidget.setValue(255); minSatWidget.setValue(0); maxSatWidget.setValue(255); minLumWidget.setValue(0); maxLumWidget.setValue(255); minHueWidget.addChangeListener(changeListener); maxHueWidget.addChangeListener(changeListener); minSatWidget.addChangeListener(changeListener); maxSatWidget.addChangeListener(changeListener); minLumWidget.addChangeListener(changeListener); maxLumWidget.addChangeListener(changeListener); changeListener.stateChanged(null); } public void setListener(SetThresholdListener aListener) { listener = aListener; } public HslThreshold getMinThreshold() { return new HslThreshold(minHueWidget.getValue(), minSatWidget.getValue(), minLumWidget.getValue()); } public HslThreshold getMaxThreshold() { return new HslThreshold(maxHueWidget.getValue(), maxSatWidget.getValue(), maxLumWidget.getValue()); } public void setThresholds(HslThreshold minThreshold, HslThreshold maxThreshold) { minHueWidget.setValue(minThreshold.hue); minSatWidget.setValue(minThreshold.sat); minLumWidget.setValue(minThreshold.lum); maxHueWidget.setValue(maxThreshold.hue); maxSatWidget.setValue(maxThreshold.sat); maxLumWidget.setValue(maxThreshold.lum); } private ChangeListener changeListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (listener != null) { listener.setThresholds(getMinThreshold(), getMaxThreshold()); } } }; private void initComponents() { GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[] { 43, 358, 346, 0 }; gridBagLayout.rowHeights = new int[] { 27, 0, 26, 0, 0 }; gridBagLayout.columnWeights = new double[] { 0.0, 1.0, 1.0, Double.MIN_VALUE }; gridBagLayout.rowWeights = new double[] { 0.0, 1.0, 1.0, 1.0, Double.MIN_VALUE }; setLayout(gridBagLayout); JLabel lblMin = new JLabel("min"); GridBagConstraints gbc_lblMin = new GridBagConstraints(); gbc_lblMin.insets = new Insets(0, 0, 5, 5); gbc_lblMin.gridx = 1; gbc_lblMin.gridy = 0; add(lblMin, gbc_lblMin); JLabel lblMax = new JLabel("max"); GridBagConstraints gbc_lblMax = new GridBagConstraints(); gbc_lblMax.insets = new Insets(0, 0, 5, 0); gbc_lblMax.gridx = 2; gbc_lblMax.gridy = 0; add(lblMax, gbc_lblMax); JLabel lblHue = new JLabel("Hue"); GridBagConstraints gbc_lblHue = new GridBagConstraints(); gbc_lblHue.fill = GridBagConstraints.BOTH; gbc_lblHue.insets = new Insets(0, 0, 5, 5); gbc_lblHue.gridx = 0; gbc_lblHue.gridy = 1; add(lblHue, gbc_lblHue); JLabel lblSat = new JLabel("Sat"); GridBagConstraints gbc_lblSat = new GridBagConstraints(); gbc_lblSat.fill = GridBagConstraints.BOTH; gbc_lblSat.insets = new Insets(0, 0, 5, 5); gbc_lblSat.gridx = 0; gbc_lblSat.gridy = 2; add(lblSat, gbc_lblSat); JLabel lblLum = new JLabel("Lum"); GridBagConstraints gbc_lblLum = new GridBagConstraints(); gbc_lblLum.fill = GridBagConstraints.HORIZONTAL; gbc_lblLum.insets = new Insets(0, 0, 0, 5); gbc_lblLum.gridx = 0; gbc_lblLum.gridy = 3; add(lblLum, gbc_lblLum); minHueWidget = new SliderWithTextboxPanel(); GridBagConstraints gbc_minHueWidget = new GridBagConstraints(); gbc_minHueWidget.insets = new Insets(0, 0, 5, 5); gbc_minHueWidget.fill = GridBagConstraints.BOTH; gbc_minHueWidget.gridx = 1; gbc_minHueWidget.gridy = 1; add(minHueWidget, gbc_minHueWidget); maxHueWidget = new SliderWithTextboxPanel(); GridBagConstraints gbc_maxHueWidget = new GridBagConstraints(); gbc_maxHueWidget.insets = new Insets(0, 0, 5, 0); gbc_maxHueWidget.fill = GridBagConstraints.BOTH; gbc_maxHueWidget.gridx = 2; gbc_maxHueWidget.gridy = 1; add(maxHueWidget, gbc_maxHueWidget); minSatWidget = new SliderWithTextboxPanel(); GridBagConstraints gbc_minSatWidget = new GridBagConstraints(); gbc_minSatWidget.insets = new Insets(0, 0, 5, 5); gbc_minSatWidget.fill = GridBagConstraints.BOTH; gbc_minSatWidget.gridx = 1; gbc_minSatWidget.gridy = 2; add(minSatWidget, gbc_minSatWidget); maxSatWidget = new SliderWithTextboxPanel(); GridBagConstraints gbc_maxSatWidget = new GridBagConstraints(); gbc_maxSatWidget.insets = new Insets(0, 0, 5, 0); gbc_maxSatWidget.fill = GridBagConstraints.BOTH; gbc_maxSatWidget.gridx = 2; gbc_maxSatWidget.gridy = 2; add(maxSatWidget, gbc_maxSatWidget); minLumWidget = new SliderWithTextboxPanel(); GridBagConstraints gbc_minLumWidget = new GridBagConstraints(); gbc_minLumWidget.insets = new Insets(0, 0, 0, 5); gbc_minLumWidget.fill = GridBagConstraints.BOTH; gbc_minLumWidget.gridx = 1; gbc_minLumWidget.gridy = 3; add(minLumWidget, gbc_minLumWidget); maxLumWidget = new SliderWithTextboxPanel(); GridBagConstraints gbc_maxLumWidget = new GridBagConstraints(); gbc_maxLumWidget.fill = GridBagConstraints.BOTH; gbc_maxLumWidget.gridx = 2; gbc_maxLumWidget.gridy = 3; add(maxLumWidget, gbc_maxLumWidget); } }
mit
ravis411/SimCity201
src/mikeRestaurant/test/mock/Mock.java
313
package mikeRestaurant.test.mock; public class Mock { private String name; public Mock(String name) { this.name = name; } public String getName() { return name; } public String toString() { return this.getClass().getName() + ": " + name; } }
mit
saqibmasood/GroupDocs.Viewer-for-Java
Showcase/GroupDocs.Viewer-for-Java-using-Struts2/src/main/java/com/viewer/actions/GetPdfDownloadUrl.java
3403
package com.viewer.actions; import com.fasterxml.jackson.databind.ObjectMapper; import com.viewer.model.ViewDocumentParameters; import com.viewer.model.WatermarkPosition; import org.apache.struts2.ServletActionContext; import javax.servlet.http.HttpServletRequest; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.LinkedHashMap; import java.util.Map; public class GetPdfDownloadUrl { private InputStream result; public String execute() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); ViewDocumentParameters parameters = new ObjectMapper().readValue(request.getInputStream(), ViewDocumentParameters.class); String r = GetFileUrl(parameters.getPath(), true, false, parameters.getFileDisplayName(), parameters.getWatermarkText(), parameters.getWatermarkColor(), parameters.getWatermarkPostion(), parameters.getWatermarkWidth(), parameters.getIgnoreDocumentAbsence(), parameters.getUseHtmlBasedEngine(), parameters.getSupportPageRotation()); this.result = new ByteArrayInputStream(r.getBytes()); return "success"; } public InputStream getResult() { return this.result; } public final String GetFileUrl(String path, boolean getPdf, boolean isPrintable, String fileDisplayName, String watermarkText, Integer watermarkColor, WatermarkPosition watermarkPosition, Float watermarkWidth, boolean ignoreDocumentAbsence, boolean useHtmlBasedEngine, boolean supportPageRotation) { Map<String, String> queryString = new LinkedHashMap<String, String>(); String myUrl = "path=" + path; queryString.put("path", path); if (!isPrintable) { queryString.put("getPdf", String.valueOf(getPdf).toLowerCase()); myUrl = myUrl + "&getPdf=" + String.valueOf(getPdf).toLowerCase(); if (fileDisplayName != null) { queryString.put("displayName", fileDisplayName); } } if (watermarkText != null) { queryString.put("watermarkText", watermarkText); queryString.put("watermarkColor", watermarkColor.toString()); if (watermarkPosition != null) { queryString.put("watermarkPosition", watermarkPosition.toString()); } if (watermarkWidth != null) { queryString.put("watermarkWidth", (new Float((float) watermarkWidth)).toString()); } } if (ignoreDocumentAbsence) { queryString.put("ignoreDocumentAbsence", String.valueOf(ignoreDocumentAbsence).toLowerCase()); } queryString.put("useHtmlBasedEngine", String.valueOf(useHtmlBasedEngine).toLowerCase()); myUrl = myUrl + "&useHtmlBasedEngine=" + String.valueOf(useHtmlBasedEngine).toLowerCase(); queryString.put("supportPageRotation", String.valueOf(supportPageRotation).toLowerCase()); myUrl = myUrl + "&supportPageRotation=" + String.valueOf(supportPageRotation).toLowerCase(); String handlerName = isPrintable ? "GetPdfWithPrintDialog" : "GetFile"; String baseUrl = "http://localhost:8080/" + handlerName + "?" + myUrl; String fileUrl = baseUrl + handlerName + queryString; return baseUrl; } }
mit
fvasquezjatar/fermat-unused
fermat-dap-api/src/main/java/com/bitdubai/fermat_dap_api/layer/dap_wallet/asset_issuer_wallet/interfaces/AssetIssuerWalletBalance.java
1333
package com.bitdubai.fermat_dap_api.layer.dap_wallet.asset_issuer_wallet.interfaces; import com.bitdubai.fermat_dap_api.layer.dap_wallet.asset_issuer_wallet.exceptions.CantCalculateBalanceException; import com.bitdubai.fermat_dap_api.layer.dap_wallet.asset_issuer_wallet.exceptions.CantRegisterCreditException; import com.bitdubai.fermat_dap_api.layer.dap_wallet.asset_issuer_wallet.exceptions.CantRegisterDebitException; import com.bitdubai.fermat_dap_api.layer.dap_wallet.common.enums.BalanceType; import java.util.List; /** * Created by franklin on 04/09/15. */ public interface AssetIssuerWalletBalance { //TODO: Documentar long getBalance() throws CantCalculateBalanceException; List<AssetIssuerWalletList> getAssetIssuerWalletBalancesAvailable() throws CantCalculateBalanceException; List<AssetIssuerWalletList> getAssetIssuerWalletBalancesBook() throws CantCalculateBalanceException; void debit(AssetIssuerWalletTransactionRecord assetIssuerWalletTransactionRecord, BalanceType balanceType) throws CantRegisterDebitException; //TODO: Debemos de definir la estructura de la transaccion void credit(AssetIssuerWalletTransactionRecord assetIssuerWalletTransactionRecord, BalanceType balanceType) throws CantRegisterCreditException; //TODO: Debemos de definir la estructura de la transaccion }
mit
praneetloke/AzureStorageExplorerAndroid
app/src/main/java/com/pl/azurestorageexplorer/fragments/interfaces/IBlobItemNavigateListener.java
363
package com.pl.azurestorageexplorer.fragments.interfaces; import com.microsoft.azure.storage.blob.ListBlobItem; import com.pl.azurestorageexplorer.storage.models.AzureStorageAccount; /** * Created by Praneet Loke on 4/23/2016. */ public interface IBlobItemNavigateListener { void onBlobItemClick(AzureStorageAccount account, ListBlobItem listBlobItem); }
mit
gracedigital/gmote-android
PlugPlayer/src/com/plugplayer/plugplayer/activities/FixedTabHost.java
619
package com.plugplayer.plugplayer.activities; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.TabHost; //XXX Fixes a bug in Android 2.1; remove this when we drop support public class FixedTabHost extends TabHost { public FixedTabHost( Context context ) { super( context ); } public FixedTabHost( Context context, AttributeSet attrs ) { super( context, attrs ); } @Override public void dispatchWindowFocusChanged( boolean hasFocus ) { View v = getCurrentView(); if ( v != null ) super.dispatchWindowFocusChanged( hasFocus ); } }
mit
ashiishsharma/PracticeCode
sorts/src/main/java/com/ashish/HeapNode.java
569
package com.ashish; /** * @author Ashish Sharma * Created on 7/29/2015. */ public class HeapNode<Integer, Value> { private Integer index; private Value value; public HeapNode(Integer index, Value value) { this.index = index; this.value = value; } public Integer getIndex() { return index; } public Value getValue() { return value; } public void setIndex(Integer index) { this.index = index; } public void setValue(Value value) { this.value = value; } }
mit
NewEconomyMovement/nem.core
src/test/java/org/nem/core/crypto/ed25519/Ed25519KeyGeneratorTest.java
1235
package org.nem.core.crypto.ed25519; import org.hamcrest.core.IsEqual; import org.junit.*; import org.nem.core.crypto.*; import org.nem.core.crypto.ed25519.arithmetic.*; public class Ed25519KeyGeneratorTest extends KeyGeneratorTest { @Test public void derivedPublicKeyIsValidPointOnCurve() { // Arrange: final KeyGenerator generator = this.getKeyGenerator(); for (int i = 0; i < 100; i++) { final KeyPair kp = generator.generateKeyPair(); // Act: final PublicKey publicKey = generator.derivePublicKey(kp.getPrivateKey()); // Assert (throws if not on the curve): new Ed25519EncodedGroupElement(publicKey.getRaw()).decode(); } } @Test public void derivePublicKeyReturnsExpectedPublicKey() { // Arrange: final KeyGenerator generator = this.getKeyGenerator(); for (int i = 0; i < 100; i++) { final KeyPair kp = generator.generateKeyPair(); // Act: final PublicKey publicKey1 = generator.derivePublicKey(kp.getPrivateKey()); final PublicKey publicKey2 = MathUtils.derivePublicKey(kp.getPrivateKey()); // Assert: Assert.assertThat(publicKey1, IsEqual.equalTo(publicKey2)); } } @Override protected CryptoEngine getCryptoEngine() { return CryptoEngines.ed25519Engine(); } }
mit
thiagorogelio/RoboControl
src/robocontrol/graphinterface/graphSobre.java
5699
/* * 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 robocontrol.graphinterface; /** * * @author Maxx */ public class graphSobre extends javax.swing.JFrame { /** * Creates new form graphSobre */ public graphSobre() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jLabel7 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Sobre"); setType(java.awt.Window.Type.UTILITY); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Universidade Estadual de Maringá"); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("Departamento de Informática - DIN"); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("Ciência da Computação"); jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel4.setText("Programa: Robo Control"); jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel6.setText("Thiago Rogelio Ramos"); jButton1.setText("Sair"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel7.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel7.setText("thiago.rogelio.r@gmail.com"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1) .addGap(182, 182, 182)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3) .addGap(24, 24, 24) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1) .addContainerGap(26, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; // End of variables declaration//GEN-END:variables }
mit
nithinvnath/PAVProject
com.ibm.wala.util/src/com/ibm/wala/fixpoint/IFixedPointSolver.java
1182
/******************************************************************************* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.wala.fixpoint; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.MonitorUtil.IProgressMonitor; /** * Solves a set of constraints */ public interface IFixedPointSolver<T extends IVariable> { /** * @return the set of statements solved by this {@link IFixedPointSolver} */ public IFixedPointSystem<T> getFixedPointSystem(); /** * Solve the problem. * <p> * PRECONDITION: graph is set up * * @return true iff the evaluation of some constraint caused a change in the * value of some variable. */ public boolean solve(IProgressMonitor monitor) throws CancelException; }
mit
CS2103AUG2016-W11-C1/main
src/main/java/linenux/command/FreeTimeCommand.java
8826
package linenux.command; import java.time.Clock; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import linenux.command.parser.FreeTimeArgumentParser; import linenux.command.result.CommandResult; import linenux.control.TimeParserManager; import linenux.model.Schedule; import linenux.model.Task; import linenux.time.parser.ISODateWithTimeParser; import linenux.time.parser.StandardDateWithTimeParser; import linenux.time.parser.TodayWithTimeParser; import linenux.time.parser.TomorrowWithTimeParser; import linenux.util.ArrayListUtil; import linenux.util.Either; import linenux.util.LocalDateTimeUtil; import linenux.util.TimeInterval; //@@author A0144915A public class FreeTimeCommand extends AbstractCommand { private static final String TRIGGER_WORD = "freetime"; private static final String DESCRIPTION = "Find a free time slot."; private static final String COMMAND_FORMAT = "freetime [st/START_TIME] et/END_TIME"; private Schedule schedule; private TimeParserManager timeParserManager; private FreeTimeArgumentParser argumentParser; /** * Constructs an {@code FreeTimeCommand}. * @param schedule The {@code Schedule} to look for free time. */ public FreeTimeCommand(Schedule schedule) { this(schedule, Clock.systemDefaultZone()); } /** * Constructs an {@code FreeTimeCommand}. * @param schedule The {@code Schedule} to look for free time. * @param clock The {@code Clock} used to determine the current time. */ public FreeTimeCommand(Schedule schedule, Clock clock) { this.schedule = schedule; this.timeParserManager = new TimeParserManager(new ISODateWithTimeParser(), new StandardDateWithTimeParser(), new TodayWithTimeParser(), new TomorrowWithTimeParser()); this.argumentParser = new FreeTimeArgumentParser(this.timeParserManager, clock); this.TRIGGER_WORDS.add(TRIGGER_WORD); } /** * Executes the command based on {@code userInput}. This method operates under the assumption that * {@code respondTo(userInput)} is {@code true}. * @param userInput A {@code String} representing the user input. * @return A {@code CommandResult} representing the result of the command. */ @Override public CommandResult execute(String userInput) { assert userInput.matches(getPattern()); assert this.schedule != null; String argument = extractArgument(userInput); Either<TimeInterval, CommandResult> queryInterval = this.argumentParser.parse(argument); if (queryInterval.isRight()) { return queryInterval.getRight(); } ArrayList<TimeInterval> freetime = getFreeTime(queryInterval.getLeft()); if (freetime.isEmpty()) { return this.makeNoFreeTimeResult(); } else { return makeResult(freetime); } } /** * @return A {@code String} representing the default command word. */ @Override public String getTriggerWord() { return TRIGGER_WORD; } /** * @return A {@code String} describing what this {@code Command} does. */ @Override public String getDescription() { return DESCRIPTION; } /** * @return A {@code String} describing the format that this {@code Command} expects. */ @Override public String getCommandFormat() { return COMMAND_FORMAT; } /** * Compute available free time in the {@code queryInterval}. * @param queryInterval The {@code TimeInterval} to look for free time. * @return An {@code ArrayList} of free time represented by {@code TimeInterval}. */ private ArrayList<TimeInterval> getFreeTime(TimeInterval queryInterval) { ArrayList<TimeInterval> eventIntervals = eventIntervals(queryInterval, this.schedule.getTaskList()); ArrayList<TimeInterval> busyIntervals = flattenIntervals(eventIntervals); return timeIntervalSubtraction(queryInterval, busyIntervals); } /** * Return the time intervals of all events happening within {@code queryInterval}. It is guaranteed that all * intervals are bounded by queryInterval, that is, for all x in output, x intersect queryInterval == x. * @param queryInterval The {@code TimeInterval} to bound the query. * @param tasks The {@code ArrayList} of tasks. * @return An {@code ArrayList} of {@code TimeInterval} for the events. */ private ArrayList<TimeInterval> eventIntervals(TimeInterval queryInterval, ArrayList<Task> tasks) { return new ArrayListUtil.ChainableArrayListUtil<>(tasks) .filter(Task::isEvent) .filter(task -> { boolean endsBefore = task.getEndTime().compareTo(queryInterval.getFrom()) <= 0; boolean startsAfter = task.getStartTime().compareTo(queryInterval.getTo()) >= 0; return !(endsBefore || startsAfter); }) .map(task -> { LocalDateTime startTime = LocalDateTimeUtil.max(queryInterval.getFrom(), task.getStartTime()); LocalDateTime endTime = LocalDateTimeUtil.min(queryInterval.getTo(), task.getEndTime()); return new TimeInterval(startTime, endTime); }) .value(); } /** * Merge time intervals that intersect. The output is ordered. * @param input The input time intervals. * @return The output time intervals. */ private ArrayList<TimeInterval> flattenIntervals(ArrayList<TimeInterval> input) { ArrayList<TimeInterval> sortedIntervals = new ArrayListUtil.ChainableArrayListUtil<>(input) .sortBy(TimeInterval::getFrom) .value(); ArrayList<TimeInterval> output = new ArrayList<>(); if (sortedIntervals.size() == 0) { return output; } TimeInterval interval = new TimeInterval(sortedIntervals.get(0).getFrom(), sortedIntervals.get(0).getTo()); for (TimeInterval currentInterval: sortedIntervals) { if (interval.inInterval(currentInterval.getFrom())) { interval = new TimeInterval(interval.getFrom(), LocalDateTimeUtil.max(interval.getTo(), currentInterval.getTo())); } else { output.add(interval); interval = new TimeInterval(currentInterval.getFrom(), currentInterval.getTo()); } } output.add(interval); return output; } /** * Mathematically, returns {@code query} - {@code intervals}. * @param query The superset. * @param intervals The smaller subsets. * @return Return an {@code ArrayList} of time intervals that are not in {@code intervals} but in {@code query}. */ private ArrayList<TimeInterval> timeIntervalSubtraction(TimeInterval query, ArrayList<TimeInterval> intervals) { if (intervals.size() == 0) { return ArrayListUtil.fromSingleton(query); } ArrayList<TimeInterval> output = new ArrayList<>(); TimeInterval firstInterval = new TimeInterval(query.getFrom(), intervals.get(0).getFrom()); if (!firstInterval.isTrivial()) { output.add(firstInterval); } for (int i = 1; i < intervals.size(); i++) { output.add(new TimeInterval(intervals.get(i-1).getTo(), intervals.get(i).getFrom())); } TimeInterval lastInterval = new TimeInterval(intervals.get(intervals.size() - 1).getTo(), query.getTo()); if (!lastInterval.isTrivial()) { output.add(lastInterval); } return output; } /** * @param freetimes The {@code ArrayList} of free time. * @return A {@code CommandResult} displaying {@code freetimes}. */ private CommandResult makeResult(ArrayList<TimeInterval> freetimes) { return () -> { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd h.mma"); StringBuilder builder = new StringBuilder(); builder.append("You are free at the following time slots:\n"); for (TimeInterval freetime: freetimes) { builder.append(" - "); builder.append(freetime.getFrom().format(formatter)); builder.append(" - "); builder.append(freetime.getTo().format(formatter)); builder.append("\n"); } return builder.toString(); }; } /** * @return A {@code CommandResult} indicating that the user has no free time. */ private CommandResult makeNoFreeTimeResult() { return () -> "You don't have any free time in that period."; } }
mit
nqzero/kilim
src/kilim/Task.java
23909
/* Copyright (c) 2006, Sriram Srinivasan * * You may distribute this software under the terms of the license * specified in the file "License" */ package kilim; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.LinkedList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * A base class for tasks. A task is a lightweight thread (it contains its own * stack in the form of a fiber). A concrete subclass of Task must provide a * pausable execute method. * */ public abstract class Task<TT> implements Runnable, EventSubscriber, Fiber.Worker { static PauseReason yieldReason = new YieldReason(); /** * Task id, automatically generated */ public final int id; static final AtomicInteger idSource = new AtomicInteger(); /** * The stack manager in charge of rewinding and unwinding the stack when * Task.pause() is called. */ protected Fiber fiber; /** * The reason for pausing (duh) and performs the role of a await condition * in CCS. This object is responsible for resuming the task. * * @see kilim.PauseReason */ protected PauseReason pauseReason; /** * running = true when it is put on the schdulers run Q (by Task.resume()). * The Task.runExecute() method is called at some point; 'running' remains * true until the end of runExecute (where it is reset), at which point a * fresh decision is made whether the task needs to continue running. */ protected AtomicBoolean running = new AtomicBoolean(false); protected volatile boolean done = false; /** * The thread in which to resume this task. Ideally, we shouldn't have any * preferences, but using locks in pausable methods will require the task to * be pinned to a thread. * * @see kilim.ReentrantLock */ volatile int preferredResumeThread = -1; private int tid; /** * @see Task#preferredResumeThread */ int numActivePins; /** * @see #informOnExit(Mailbox) */ private LinkedList<Mailbox<ExitMsg<TT>>> exitMBs; /** * The object responsible for handing this task to a thread when the task is * runnable. */ protected Scheduler scheduler; public volatile Object exitResult = "OK"; // new timer service public kilim.timerservice.Timer timer; // for debugging Task.resume race conditions private static boolean debugRunning = false; public Task() { id = idSource.incrementAndGet(); fiber = new Fiber(this); timer = new kilim.timerservice.Timer(this); } Task(boolean dummy) { id = idSource.incrementAndGet(); } public int id() { return id; } public synchronized Task<TT> setScheduler(Scheduler s) { // if (running) { // throw new // AssertionError("Attempt to change task's scheduler while it is running"); // } scheduler = s; return this; } public synchronized Scheduler getScheduler() { return scheduler; } public void resumeOnScheduler(Scheduler s) throws Pausable { if (scheduler == s) return; scheduler = s; Task.yield(); } /** * Used to start the task; the task doesn't resume on its own. Custom * schedulers must be set (@see #setScheduler(Scheduler)) before start() is * called. * * @return */ public Task<TT> start() { if (scheduler == null) { setScheduler(Scheduler.getDefaultScheduler()); } resume(); return this; } private static Fiber.MethodRef runnerInfo = new Fiber.MethodRef("kilim.Task","run"); Fiber.MethodRef getRunnerInfo() { return runnerInfo; } /* * fix https://github.com/kilim/kilim/issues/40 * ie, merge https://github.com/hyleeon/kilim/tree/fix-invoke * specifically https://github.com/hyleeon/kilim/commit/3e14940a59c1df1e07a6a56f060b012866f20b57 * which is also https://github.com/kilim/kilim/pull/42 * * When we called a Pausable-Method * such as ExCatch.pausableInvokeCatch() -> ExCatch.pausableInvokeCatch0()) by Task.invoke() * The stack will like: * at kilim.test.ex.ExCatch.pausableInvokeCatch0(ExCatch.java:178) * at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) * at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) * at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) * at java.lang.reflect.Method.invoke(Method.java:606)at kilim.Task.invoke(Task.java:285) * at kilim.test.ex.ExCatch.pausableInvokeCatch(ExCatch.java:166) * at kilim.test.ex.ExCatch.test(ExCatch.java:36) * at kilim.test.ex.ExCatch.execute(ExCatch.java:26) * at kilim.Task._runExecute(Task.java:442) * at kilim.WorkerThread.run(WorkerThread.java:32) * If method pausableInvokeCatch0 try-catch a exception, we will call Fiber.upEx() to re-calculate * the stack size by this method. But we should discount "sun.reflect.*" and "java.lang.reflect.Method.invoke" */ private static boolean skipInvoke(String klass,String name) { return klass.startsWith("sun.reflect.") | klass.startsWith("jdk.internal.reflect.") | ("java.lang.reflect.Method".equals(klass) & "invoke".equals(name)); } /** * The generated code calls Fiber.upEx, which in turn calls this to find out * out where the current method is w.r.t the closest _runExecute method. * * @return the number of stack frames above _runExecute(), not including * this method */ public static int getStackDepth(Task task) { Fiber.MethodRef mr = task.getRunnerInfo(); StackTraceElement[] stes; stes = new Exception().getStackTrace(); int len = stes.length; int num = 0; for (int i = 0; i < len; i++) { StackTraceElement ste = stes[i]; String name = ste.getMethodName(); String klass = ste.getClassName(); // ignore synthetic shim methods from SAM weaver - they don't get stack state allocated // fixme: should any other synthetic methods be skipped ? // fixme: could other vendors be using the same name for synthetic methods that shouldn't be skipped ? if (ste.getLineNumber() < 0 & Constants.Util.isSamShim(name)) continue; if (skipInvoke(klass,name)) continue; num++; if (name.equals(mr.methodname) & klass.equals(mr.classname)) { // discounting WorkerThread.run, Task._runExecute, and // Scheduler.getStackDepth // and convert count to index return num-2; } } throw new AssertionError("Expected task to be run by WorkerThread"); } boolean checkTimeout() { return timer.getExecutionTime()==-2; } public void onEvent(EventPublisher ep, Event e) { if (e==kilim.timerservice.Timer.timedOut) timer.setLiteral(-2); boolean sched = resume(); } public Thread getExecutionThread() { return Thread.currentThread(); } /** * Add itself to scheduler if it is neither already running nor done. * * @return True if it scheduled itself. */ public boolean resume() { if (scheduler == null) return false; boolean doSchedule = false; // We don't check pauseReason while resuming (to verify whether // it is worth returning to a pause state. The code at the top of stack // will be doing that anyway. if (!done) if (running.compareAndSet(/* expected */false, /* update */true)) doSchedule = true; else if (debugRunning) System.out.println("Task.pause.running: " + this); if (doSchedule) { if (preferredResumeThread == -1) scheduler.schedule(this); else scheduler.schedule(preferredResumeThread, this); } return doSchedule; } public synchronized void informOnExit(Mailbox<ExitMsg<TT>> exit) { if (done) { exit.putnb(new ExitMsg(this, exitResult)); return; } if (exitMBs == null) { exitMBs = new LinkedList(); } exitMBs.add(exit); } /** * This is a placeholder that doesn't do anything useful. Weave replaces the * call in the bytecode from invokestateic Task.getCurrentTask to load fiber * getfield task */ public static Task getCurrentTask() throws Pausable { return null; } /** * Analogous to System.exit, except an Object can be used as the exit value */ public static void exit(Object aExitValue) throws Pausable { } public static void exit(Object aExitValue, Fiber f) { assert f.pc == 0 : "f.pc != 0"; f.task.setPauseReason(new TaskDoneReason(aExitValue)); f.togglePause(); } /** * Exit the task with a throwable indicating an error condition. The value * is conveyed through the exit mailslot (see informOnExit). All exceptions * trapped by the task scheduler also set the error result. */ public static void errorExit(Throwable ex) throws Pausable { } public static void errorExit(Throwable ex, Fiber f) { assert f.pc == 0 : "fc.pc != 0"; f.task.setPauseReason(new TaskDoneReason(ex)); f.togglePause(); } public static void errNotWoven() { System.err.println("############################################################"); System.err.println("Task has either not been woven or the classpath is incorrect"); System.err.println("############################################################"); Thread.dumpStack(); System.exit(0); } public static void errNotWoven(Task t) { System.err.println("############################################################"); System.err.println("Task " + t.getClass() + " has either not been woven or the classpath is incorrect"); System.err.println("############################################################"); Thread.dumpStack(); System.exit(0); } static class ArgState extends kilim.State { Object mthd; Object obj; Object[] fargs; } /** * Invoke a pausable method via reflection. Equivalent to Method.invoke(). * * @param method * : The method to be invoked. (Implementation note: the corresponding woven * method is invoked instead). * @param obj * : The object on which the method is invoked. Can be null if the method is * static. * @param args * : Arguments to the method * @return * @throws Pausable * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException */ public static Object invoke(Method method, Object obj, Object... args) throws Pausable, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Fiber f = getCurrentTask().fiber; Object[] fargs; if (f.pc == 0) { method = getWovenMethod(method); // Normal invocation. if (args == null) { fargs = new Object[1]; } else { fargs = new Object[args.length + 1]; // for fiber System.arraycopy(args, 0, fargs, 0, args.length); } fargs[fargs.length - 1] = f; } else { // Resuming from a previous yield ArgState as = (ArgState) f.getState(); method = (Method) as.mthd; obj = as.obj; fargs = as.fargs; } f.down(); Object ret = method.invoke(obj, fargs); switch (f.up()) { case Fiber.NOT_PAUSING__NO_STATE: case Fiber.NOT_PAUSING__HAS_STATE: return ret; case Fiber.PAUSING__NO_STATE: ArgState as = new ArgState(); as.obj = obj; as.fargs = fargs; as.pc = 1; as.mthd = method; f.setState(as); return null; case Fiber.PAUSING__HAS_STATE: return null; } throw new IllegalAccessException("Internal Error"); } // Given a method corresp. to "f(int)", return the equivalent woven method // for "f(int, kilim.Fiber)" private static Method getWovenMethod(Method m) { Class<?>[] ptypes = m.getParameterTypes(); if (!(ptypes.length > 0 && ptypes[ptypes.length - 1].getName().equals("kilim.Fiber"))) { // The last param is not "Fiber", so m is not woven. // Get the woven method corresponding to m(..., Fiber) boolean found = false; LOOP: for (Method wm : m.getDeclaringClass().getDeclaredMethods()) { if (wm != m && wm.getName().equals(m.getName())) { // names match. Check if the wm has the exact parameter // types as m, plus a fiber. Class<?>[] wptypes = wm.getParameterTypes(); if (wptypes.length != ptypes.length + 1 || !(wptypes[wptypes.length - 1].getName().equals("kilim.Fiber"))) continue LOOP; for (int i = 0; i < ptypes.length; i++) { if (ptypes[i] != wptypes[i]) continue LOOP; } m = wm; found = true; break; } } if (!found) { throw new IllegalArgumentException("Found no pausable method corresponding to supplied method: " + m); } } return m; } /** * @param millis * to sleep. Like thread.sleep, except it doesn't throw an interrupt, and it * doesn't hog the java thread. */ public static void sleep(final long millis) throws Pausable { // create a temp mailbox, and wait on it. final Mailbox<Integer> sleepmb = new Mailbox<Integer>(1); // TODO: will // need a // better // mechanism // for // monitoring // later on. sleepmb.get(millis); } public static void shutdown() { } /** * Yield cooperatively to the next task waiting to use the thread. */ public static void yield() throws Pausable { errNotWoven(); } public static void yield(Fiber f) { if (f.task instanceof Continuation.FakeTask) { f.togglePause(); return; } if (f.pc == 0) { f.task.setPauseReason(yieldReason); } else { f.task.setPauseReason(null); } f.togglePause(); f.task.checkKill(); } /** * Ask the current task to pause with a reason object, that is responsible * for resuming the task when the reason (for pausing) is not valid any * more. * * @param pauseReason * the reason */ public static void pause(PauseReason pauseReason) throws Pausable { errNotWoven(); } public static void pause(PauseReason pauseReason, Fiber f) { if (f.pc == 0) { f.task.setPauseReason(pauseReason); } else { f.task.setPauseReason(null); } f.togglePause(); f.task.checkKill(); } /* * This is the fiber counterpart to the execute() method that allows us to * detec when a subclass has not been woven. * * If the subclass has not been woven, it won't have an execute method of * the following form, and this method will be called instead. */ public void execute() throws Pausable, Exception { errNotWoven(this); } public void execute(Fiber f) throws Exception { errNotWoven(this); } public String toString() { return "" + id + "(running=" + running + ",pr=" + pauseReason + ")"; } public String dump() { synchronized (this) { return "" + id + "(running=" + running + ", pr=" + pauseReason + ")"; } } public void prePin() throws Pausable { if (scheduler.isPinnable()) return; scheduler = scheduler.getPinnable(); yield(); } void checkPin() { if (! scheduler.isPinnable()) throw new AssertionError("attempt to pin and unpinnable scheduler - must call `prePin()` first"); } public void pinToThread() { checkPin(); numActivePins++; } public void unpinFromThread() { numActivePins--; } final protected void setPauseReason(PauseReason pr) { pauseReason = pr; } public final PauseReason getPauseReason() { return pauseReason; } public boolean isDone() { return done; } protected void setTid(int tid) { this.tid = tid; } /** return the thread ID that the task is currently running on, valid only during execute */ public int getTid() { return tid; } /** * Called by WorkerThread, it is the wrapper that performs pre and post * execute processing (in addition to calling the execute(fiber) method of * the task. */ public void run() throws NotPausable { Scheduler.setCurrentTask(this); Fiber f = fiber; boolean isDone = false; try { assert (preferredResumeThread == -1 || preferredResumeThread == tid) : "Resumed " + id + " in incorrect thread. "; // start execute. fiber is wound to the beginning. execute(f.begin()); // execute() done. Check fiber if it is pausing and reset it. isDone = f.end() || (pauseReason instanceof TaskDoneReason); } catch (Throwable th) { getScheduler().log(this,th); // Definitely done setPauseReason(new TaskDoneReason(th)); isDone = true; } if (isDone) { // inform on exit if (numActivePins > 0) { throw new AssertionError("Task ended but has active locks"); } if (pauseReason instanceof TaskDoneReason) { exitResult = ((TaskDoneReason)pauseReason).exitObj; } preferredResumeThread = -1; synchronized(this){ done = true; if (exitMBs != null) { ExitMsg msg = new ExitMsg(this, exitResult); for (Mailbox<ExitMsg<TT>> exitMB: exitMBs) { exitMB.putnb(msg); } } } } else { if (tid >= 0) { // it is null for generators if (numActivePins > 0) { preferredResumeThread = tid; } else { assert numActivePins == 0 : "numActivePins == " + numActivePins; preferredResumeThread = -1; } } PauseReason pr = this.pauseReason; running.set(false); // The task has been in "running" mode until now, and may have // missed // notifications to the pauseReason object (that is, it would have // resisted calls to resume(). If the pauseReason is not valid any // more, we'll resume. if (!pr.isValid(this)) { // NOTE: At this point, another event could trigger resumption // before the following resume() can kick in. Additionally, // it is possible that the task could process all pending // events, so the following call to resume() may be spurious. // Cell/Mailbox's get/put watch out for spurious resumptions. resume(); } } } public ExitMsg<TT> joinb() { Mailbox<ExitMsg<TT>> mb = new Mailbox(); informOnExit(mb); return mb.getb(); } public ExitMsg<TT> join() throws Pausable { Mailbox<ExitMsg<TT>> mb = new Mailbox(); informOnExit(mb); return mb.get(); } @Override public boolean equals(Object obj) { return obj == this; } @Override public int hashCode() { return id; } public void checkKill() { } public boolean getState() { return running.get(); } public static class Spawn<TT> extends Task<TT> { Pausable.Spawn<TT> body; public Spawn() {} public Spawn(Pausable.Spawn<TT> body) { this.body = body; } public void execute() throws Pausable, Exception { TT val = body.execute(); exit(val); } } public static class Fork extends Task { Pausable.Fork body; public Fork(Pausable.Fork body) { this.body = body; } public void execute() throws Pausable, Exception { body.execute(); } } public static class Invoke<TT> extends Task<TT> { Method method; Object obj; Object [] args; public Invoke(Method method,Object obj,Object...args) { this.method = method; this.obj = obj; this.args = args; } public void execute() throws Pausable, Exception { Object val = Task.invoke(method,obj,args); exit(val); } } /** * Wraps the given object or lambda expression in a Task and starts that task. * Beware of inadvertent sharing when multiple lambdas are created in the same context * * @param body the lambda to delegate to * @return the spawned task. */ public static Task fork(final Pausable.Fork body) { return new Fork(body).start(); } /** * Wraps the given object or lambda expression in a Task and starts that task. * Beware of inadvertent sharing when multiple lambdas are created in the same context * * @param body the lambda to delegate to * @return the spawned task. */ public static <TT> Spawn<TT> spawn(final Pausable.Spawn<TT> body) { Spawn<TT> spawn = new Spawn(body); spawn.start(); return spawn; } public static Invoke spawn(Method method,Object obj,Object... args) { Invoke spawn = new Invoke(method,obj,args); spawn.start(); return spawn; } /** * idledown the default scheduler * @see Scheduler#idledown() */ public static void idledown() { if (Scheduler.defaultScheduler != null) Scheduler.defaultScheduler.idledown(); } }
mit
byronlai/Nickel
src/main/java/com/byronlai/nickel/logic/GameResult.java
626
package com.byronlai.nickel.logic; /* * Represent the result of a game. The result includes the move that the bot * made and the outcome (win, loss or tie). */ public class GameResult { private Shape computerChoice; private Outcome outcome; public GameResult(Shape computerChoice, Outcome outcome) { this.computerChoice = computerChoice; this.outcome = outcome; } /* Get the move that the bot made. */ public Shape getComputerChoice() { return computerChoice; } /* Get the outcome of the game. */ public Outcome getOutcome() { return outcome; } }
mit
GojaFramework/goja
goja-web/src/main/java/goja/mvc/controller/ControllerBindRoutes.java
3880
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2013-2014 sagyf Yang. The Four Group. */ package goja.mvc.controller; import goja.core.StringPool; import goja.core.app.GojaConfig; import goja.core.kits.reflect.ClassPathScanning; import com.jfinal.config.Routes; import com.jfinal.core.Controller; import com.jfinal.kit.StrKit; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Set; public class ControllerBindRoutes extends Routes { private static final Logger logger = LoggerFactory.getLogger(ControllerBindRoutes.class); private static final String CONTROLLER_SUFFIX = "Controller"; private static String controllerKey(Class<? extends Controller> clazz) { final String simpleName = clazz.getSimpleName(); Preconditions.checkArgument(simpleName.endsWith(CONTROLLER_SUFFIX), " does not has a @ControllerBind annotation and it's name is not end with " + CONTROLLER_SUFFIX); // 得到 /helloController String controllerKey = StringPool.SLASH + StrKit.firstCharToLowerCase(simpleName); // 得到 /hello controllerKey = controllerKey.substring(0, controllerKey.indexOf(CONTROLLER_SUFFIX)); String packName = clazz.getPackage().getName(); final String controllersFlag = "controllers"; final List<String> appScans = GojaConfig.getAppScans(); for (String appScan : appScans) { if (StringUtils.startsWith(packName, appScan)) { // 增加一些新的路由机制 // prefix com.mo008 // controller1 com.mo008.controllers // controller2 com.mo008.sys.controllers // controller3 com.mo008.sys.controllers.admin // com.mo008.controllers.HelloController -> /hello // com.mo008.sys.controllers.HelloController -> /sys/hello // com.mo008.sys.controllers.admin.HelloController -> sys/admin/hello // com.mo008.sys.controllers.admin.me.HelloController -> sys/admin/me/hello final String removePrefixPack = StringUtils.replace(packName, appScan, StringPool.EMPTY); final String removeControllerPack = StringUtils.replace(removePrefixPack, StringPool.DOT + controllersFlag, StringPool.EMPTY); return StringUtils.replace(removeControllerPack, StringPool.DOT, StringPool.SLASH) + controllerKey; } } return null; } @Override public void config() { final Set<Class<? extends Controller>> controllerList = ClassPathScanning.scan(Controller.class); if (CollectionUtils.isNotEmpty(controllerList)) { ControllerBind controllerBind; for (Class<? extends Controller> controller : controllerList) { controllerBind = controller.getAnnotation(ControllerBind.class); if (controllerBind == null) { final String controllerKey = controllerKey(controller); if (Strings.isNullOrEmpty(controllerKey)) { logger.warn("控制器类{},路由生成失败!", controller.getName()); continue; } this.add(controllerKey, controller); } else if (StrKit.isBlank(controllerBind.viewPath())) { this.add(controllerBind.value(), controller); } else { this.add(controllerBind.value(), controller, controllerBind.viewPath()); } } } } }
mit
danschultequb/qub-java
sources/qub/CharacterEncoding.java
12710
package qub; /** * An encoding that converts between characters and bytes. */ public interface CharacterEncoding { USASCIICharacterEncoding US_ASCII = new USASCIICharacterEncoding(); UTF8CharacterEncoding UTF_8 = new UTF8CharacterEncoding(); /** * Encode the provided character as a byte[]. * @param character The character to encode. * @return The encoded character as bytes. */ default Result<byte[]> encodeCharacter(char character) { return Result.create(() -> { final InMemoryByteStream byteStream = InMemoryByteStream.create(); this.encodeCharacter(character, byteStream).await(); return byteStream.getBytes(); }); } /** * Encode the provided character and write the encoded bytes to the provided ByteWriteStream. * Return the number of bytes that were written. * @param character The character to encode. * @param byteWriteStream The ByteWriteStream to write the encoded bytes to. * @return The number of bytes that were written. */ Result<Integer> encodeCharacter(char character, ByteWriteStream byteWriteStream); /** * Encode the provided String of characters into a byte[]. * @param text The text to encode. * @return The encoded text as bytes. */ default Result<byte[]> encodeCharacters(String text) { PreCondition.assertNotNull(text, "text"); return Result.create(() -> { final InMemoryByteStream byteStream = InMemoryByteStream.create(); this.encodeCharacters(text, byteStream).await(); return byteStream.getBytes(); }); } /** * Encode the provided String of characters and write the encoded bytes to the provided * ByteWriteStream. Return the number of bytes that were written. * @param text The String of characters to encode. * @param byteWriteStream The ByteWriteStream to write the encoded bytes to. * @return The number of bytes that were written. */ default Result<Integer> encodeCharacters(String text, ByteWriteStream byteWriteStream) { PreCondition.assertNotNull(text, "text"); PreCondition.assertNotNull(byteWriteStream, "byteWriteStream"); PreCondition.assertNotDisposed(byteWriteStream, "byteWriteStream"); return this.encodeCharacters(Strings.iterable(text), byteWriteStream); } /** * Encode the provided character array into a byte[]. * @param characters The characters to encode. * @return The encoded characters as bytes. */ default Result<byte[]> encodeCharacters(char[] characters) { PreCondition.assertNotNull(characters, "characters"); return this.encodeCharacters(characters, 0, characters.length); } /** * Encode the provided character array and write the encoded bytes to the provided * ByteWriteStream. Return the number of bytes that were written. * @param characters The character array to encode. * @param byteWriteStream The ByteWriteStream to write the encoded bytes to. * @return The number of bytes that were written. */ default Result<Integer> encodeCharacters(char[] characters, ByteWriteStream byteWriteStream) { PreCondition.assertNotNull(characters, "characters"); PreCondition.assertNotNull(byteWriteStream, "byteWriteStream"); return this.encodeCharacters(characters, 0, characters.length, byteWriteStream); } default Result<byte[]> encodeCharacters(char[] characters, int startIndex, int length) { PreCondition.assertNotNull(characters, "characters"); PreCondition.assertStartIndex(startIndex, characters.length); PreCondition.assertLength(length, startIndex, characters.length); return Result.create(() -> { final InMemoryByteStream byteStream = InMemoryByteStream.create(); this.encodeCharacters(characters, startIndex, length, byteStream).await(); return byteStream.getBytes(); }); } default Result<Integer> encodeCharacters(char[] characters, int startIndex, int length, ByteWriteStream byteWriteStream) { PreCondition.assertNotNull(characters, "characters"); PreCondition.assertStartIndex(startIndex, characters.length); PreCondition.assertLength(length, startIndex, characters.length); PreCondition.assertNotNull(byteWriteStream, "byteWriteStream"); PreCondition.assertNotDisposed(byteWriteStream, "byteWriteStream"); return Result.create(() -> { int result = 0; final int endIndex = startIndex + length; for (int i = startIndex; i < endIndex; ++i) { result += this.encodeCharacter(characters[i], byteWriteStream).await(); } return result; }); } /** * Write the encoded byte representations of the provided characters to the provided * byteWriteStream. * @param characters The characters to encode. * @return The encoded bytes. */ default Result<byte[]> encodeCharacters(Iterable<Character> characters) { PreCondition.assertNotNull(characters, "characters"); return Result.create(() -> { final InMemoryByteStream byteStream = InMemoryByteStream.create(); this.encodeCharacters(characters, byteStream).await(); return byteStream.getBytes(); }); } /** * Write the encoded byte representations of the provided characters to the provided * byteWriteStream. * @param characters The characters to encode. * @param byteWriteStream The ByteWriteStream to write the encoded characters to. * @return The number of bytes that were written. */ default Result<Integer> encodeCharacters(Iterable<Character> characters, ByteWriteStream byteWriteStream) { PreCondition.assertNotNull(characters, "characters"); PreCondition.assertNotNull(byteWriteStream, "byteWriteStream"); PreCondition.assertNotDisposed(byteWriteStream, "byteWriteStream"); return this.encodeCharacters(characters.iterate(), byteWriteStream); } /** * Write the encoded byte representations of the provided characters to the provided * byteWriteStream. * @param characters The characters to encode. * @return The encoded bytes. */ default Result<byte[]> encodeCharacters(Iterator<Character> characters) { PreCondition.assertNotNull(characters, "characters"); return Result.create(() -> { final InMemoryByteStream byteStream = InMemoryByteStream.create(); this.encodeCharacters(characters, byteStream).await(); return byteStream.getBytes(); }); } /** * Write the encoded byte representations of the provided characters to the provided * byteWriteStream. * @param characters The characters to encode. * @param byteWriteStream The ByteWriteStream to write the encoded characters to. * @return The number of bytes that were written. */ default Result<Integer> encodeCharacters(Iterator<Character> characters, ByteWriteStream byteWriteStream) { PreCondition.assertNotNull(characters, "characters"); PreCondition.assertNotNull(byteWriteStream, "byteWriteStream"); PreCondition.assertNotDisposed(byteWriteStream, "byteWriteStream"); return Result.create(() -> { int result = 0; for (final Character character : characters) { if (character == null) { throw new IllegalArgumentException("Can't encode a null character."); } result += this.encodeCharacter(character, byteWriteStream).await(); } return result; }); } /** * Decode the provided byte[] into a char[]. * @param bytes The byte[] to decode. * @return The characters create the decoded byte[]. */ default Result<char[]> decodeAsCharacters(byte[] bytes) { PreCondition.assertNotNull(bytes, "bytes"); return this.decodeAsCharacters(bytes, 0, bytes.length); } default Result<char[]> decodeAsCharacters(byte[] bytes, int startIndex, int length) { PreCondition.assertNotNull(bytes, "bytes"); PreCondition.assertStartIndex(startIndex, bytes.length); PreCondition.assertLength(length, startIndex, bytes.length); return Result.create(() -> { final Iterator<Byte> byteIterator = Iterator.create(bytes, startIndex, length); return Array.toCharArray(CharacterList.create(this.iterateDecodedCharacters(byteIterator))).await(); }); } /** * Decode the provided byte[] into a String. * @param bytes The byte[] to decode. * @return The String create the decoded byte[]. */ default Result<String> decodeAsString(byte[] bytes) { return this.decodeAsCharacters(bytes) .then((char[] characters) -> String.valueOf(characters)); } /** * Decode the provided byte[] into a String. * @param bytes The byte[] to decode. * @return The String create the decoded byte[]. */ default Result<String> decodeAsString(byte[] bytes, int startIndex, int length) { return this.decodeAsCharacters(bytes, startIndex, length) .then((char[] characters) -> String.valueOf(characters)); } /** * Decode the provided bytes into a char[]. * @param bytes The bytes to decode. * @return The decoded characters. */ default Result<char[]> decodeAsCharacters(Iterable<Byte> bytes) { PreCondition.assertNotNull(bytes, "bytes"); return this.decodeAsCharacters(bytes.iterate()); } /** * Decode the provided bytes into a char[]. * @param bytes The bytes to decode. * @return The decoded characters. */ default Result<char[]> decodeAsCharacters(Iterator<Byte> bytes) { PreCondition.assertNotNull(bytes, "bytes"); return Result.create(() -> { return Array.toCharArray(CharacterList.create(this.iterateDecodedCharacters(bytes))).await(); }); } /** * Decode the provided bytes into a String. * @param bytes The bytes to decode. * @return The decoded characters. */ default Result<String> decodeAsString(Iterable<Byte> bytes) { return this.decodeAsCharacters(bytes) .then((char[] characters) -> String.valueOf(characters)); } /** * Decode the provided bytes into a String. * @param bytes The bytes to decode. * @return The decoded characters. */ default Result<String> decodeAsString(Iterator<Byte> bytes) { PreCondition.assertNotNull(bytes, "bytes"); return this.decodeAsCharacters(bytes) .then((char[] characters) -> String.valueOf(characters)); } /** * Get an Iterator that will decode the provided bytes as it iterates. * @param bytes The bytes to decode. * @return An Iterator that will decode the provided bytes as it iterates. */ default Iterator<Character> iterateDecodedCharacters(ByteReadStream bytes) { PreCondition.assertNotNull(bytes, "bytes"); PreCondition.assertNotDisposed(bytes, "bytes"); return this.iterateDecodedCharacters(ByteReadStream.iterate(bytes)); } /** * Get an Iterator that will decode the provided bytes as it iterates. * @param bytes The bytes to decode. * @return An Iterator that will decode the provided bytes as it iterates. */ Iterator<Character> iterateDecodedCharacters(Iterator<Byte> bytes); /** * Get whether or not the provided CharacterEncoding equals the provided Object. * @param lhs The CharacterEncoding. * @param rhs The Object. * @return Whether or not the provided values are equal. */ static boolean equals(CharacterEncoding lhs, Object rhs) { return rhs instanceof CharacterEncoding && lhs.equals((CharacterEncoding)rhs); } /** * Get whether or not this CharacterEncoding equals the provided CharacterEncoding. * @param rhs The CharacterEncoding to compare against this CharacterEncoding. * @return Whether or not this CharacterEncoding equals the provided CharacterEncoding. */ default boolean equals(CharacterEncoding rhs) { return rhs != null && this.getClass().equals(rhs.getClass()); } }
mit
YoungChrisV/lifeInvader
src/net/lifeinvader/app/model/Event.java
5248
/* * The MIT License * * Copyright 2016 Christophe Van Waesberghe <contact@chrisv.be> & Danielle Delfosse <delfosse.da@gmail.com> (Groupe 17, 2016/17) * * 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 net.lifeinvader.app.model; import java.util.Observable; /** * Represents an Abstract event who take place during the game * * @author <a href="mailto:contact@chrisv.be">Christophe Van Waesberghe * (contact@chrisv.be)</a> * @author <a href="mailto:delfosse.da@gmail.com">Danielle Delfosse * (delfosse.da@gmail.com)</a> */ public abstract class Event extends Observable { protected int viralityCoef = 0; protected int reputationCoef = 0; protected int privacyCoef = 0; protected double reward = 0; /** * Create a new Event object who represent an Event with a reputation * coefficent, a privacy coefficient, a virality coefficient and a reward * * @param reputationCoef int Reputation coefficient * @param privacyCoef int Privacy coefficient * @param viralityCoef int Virality coefficient * @param reward double Reward */ public Event(int viralityCoef, int reputationCoef, int privacyCoef, double reward) { this.reputationCoef = reputationCoef; this.privacyCoef = privacyCoef; this.viralityCoef = viralityCoef; this.reward = reward; } /** * Get the reputation coefficient * * @return int reputationCoef */ public int getReputationCoef() { return reputationCoef; } /** * Get the privacy coefficient * * @return int privacyCoef */ public int getPrivacyCoef() { return privacyCoef; } /** * Get the virality coefficient * * @return int viralityCoef */ public int getViralityCoef() { return viralityCoef; } /** * Get the reward * * @return double reward */ public double getReward() { return reward; } /** * Set the reputation coefficient * * @param reputationCoef int */ public void setReputationCoef(int reputationCoef) { this.reputationCoef = reputationCoef; this.setChanged(); this.notifyObservers(); } /** * Set the privacy coefficient * * @param privacyCoef int */ public void setPrivacyCoef(int privacyCoef) { this.privacyCoef = privacyCoef; this.setChanged(); this.notifyObservers(); } /** * Set the virality coefficient * * @param viralityCoef int */ public void setViralityCoef(int viralityCoef) { this.viralityCoef = viralityCoef; this.setChanged(); this.notifyObservers(); } /** * Set the reward * * @param reward double */ public void setReward(double reward) { this.reward = reward; this.setChanged(); this.notifyObservers(); } @Override public String toString() { return "Event[" + this.reputationCoef + ", " + this.privacyCoef + " ," + this.viralityCoef + "," + this.reward + " ]"; } @Override public int hashCode() { int hash = 3; hash = 83 * hash + this.reputationCoef; hash = 83 * hash + this.privacyCoef; hash = 83 * hash + this.viralityCoef; hash = 83 * hash + (int) (Double.doubleToLongBits(this.reward) ^ (Double.doubleToLongBits(this.reward) >>> 32)); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Event other = (Event) obj; if (this.reputationCoef != other.reputationCoef) { return false; } if (this.privacyCoef != other.privacyCoef) { return false; } if (this.viralityCoef != other.viralityCoef) { return false; } if (Double.doubleToLongBits(this.reward) != Double.doubleToLongBits(other.reward)) { return false; } return true; } }
mit
cilogi/cilogi-base
src/main/java/com/cilogi/util/path/PathUtil.java
4963
// Copyright (c) 2011 Tim Niblett All Rights Reserved. // // File: PathUtil.java (04-Jun-2011) // Author: tim // $Id$ // // Copyright in the whole and every part of this source file belongs to // Tim Niblett (the Author) and may not be used, // sold, licenced, transferred, copied or reproduced in whole or in // part in any manner or form or in or on any media to any person // other than in accordance with the terms of The Author's agreement // or otherwise without the prior written consent of The Author. All // information contained in this source file is confidential information // belonging to The Author and as such may not be disclosed other // than in accordance with the terms of The Author's agreement, or // otherwise, without the prior written consent of The Author. As // confidential information this source file must be kept fully and // effectively secure at all times. // package com.cilogi.util.path; import lombok.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.LinkedList; import java.util.List; @SuppressWarnings({"unused"}) public class PathUtil { static final Logger LOG = LoggerFactory.getLogger(PathUtil.class); private PathUtil() {} public static boolean isExternalURL(@NonNull String path) { String lp = path.toLowerCase(); return lp.startsWith("http://") || lp.startsWith("https://"); } public static String rootPathFrom(String path) { String[] subs = path.split("/"); String out = ""; for (int i = 0; i < subs.length - 1; i++) { out += "../"; } return out; } public static String extensionOf(String path) { int idx = path.lastIndexOf("."); return (idx == -1) ? null : path.substring(idx+1); } public static String changeExtension(String path, String extension) { String end = (extension == null || "".equals(extension)) ? "" : "." + extension; int idx = path.lastIndexOf("."); if (idx == -1) { return path + end; } else { return path.substring(0, idx) + end; } } /** * Change the name component of a path, from say <pre>a/b/fred.txt</pre> to <pre>a/b/wilma.txt</pre> * * @param path The original path, including name * @param name The new name * @return The path with the name component replaced. */ public static String changeName(String path, String name) { int index = path.lastIndexOf("/"); return (index == -1) ? name : path.substring(0, index + 1) + name; } public static String name(String path) { int index = path.lastIndexOf("/"); return (index == -1) ? path : path.substring(index + 1); } public static String dir(String path) { int index = path.lastIndexOf("/"); return (index == -1) ? "" : path.substring(0, index); } /** * Given a full path like a/b/c.txt and a relative path such as ../fred.txt * compute the result, which is a/fred.txt * @param fullPath The full path * @param relativePath The relative path * @return The new full path for the relative path */ @SuppressWarnings({"unchecked"}) public static String changeRelative(String fullPath, String relativePath) { List<String> fSub = new LinkedList(Arrays.asList(fullPath.split("/"))); List<String> rSub = new LinkedList(Arrays.asList(relativePath.split("/"))); if (rSub.size() == 0) { return fullPath; } if (fSub.size() == 1) { return relativePath; } // get rid of initial ./ in the relative path if (".".equals(rSub.get(0))) { rSub.remove(0); } while ("..".equals(rSub.get(0)) && rSub.size() > 0) { if (fSub.size() < 2) { throw new RuntimeException("Can't change " + fullPath + " with " + relativePath); } fSub.remove(fSub.size()-1); rSub.remove(0); } if (fSub.size() == 0) { return join("/", rSub); } if (rSub.size() == 0) { if (fSub.size() == 0) { throw new RuntimeException("Can't change " + fullPath + " with " + relativePath); } fSub.remove(fSub.size()-1); return join("/", fSub); } fSub.remove(fSub.size()-1); for (String s : rSub) { fSub.add(s); } return join("/", fSub); } private static String join(@NonNull String join, @NonNull List<String> elements) { boolean had = false; StringBuilder builder = new StringBuilder(); for (String element : elements) { if (had) { builder.append(join); } builder.append(element); had = true; } return builder.toString(); } }
mit
fcpietra/TPOProg2
src/Implementaciones/NodoCiudades.java
139
package Implementaciones; import tda.DMMedicionesTDA; public class NodoCiudades { String ciudad; DMMedicionesTDA mediciones; }
mit
arvast/317refactor
src/com/jagex/runescape/TextInput.java
3147
package com.jagex.runescape; /* * This file is part of the RuneScape client * revision 317, which was publicly released * on the 13th of June 2005. * * This file has been refactored in order to * restore readability to the codebase for * educational purposes, primarility to those * with an interest in game development. * * It may be a criminal offence to run this * file. This file is the intellectual property * of Jagex Ltd. */ /* * This file was renamed as part of the 317refactor project. */ final class TextInput { private static final char[] characterList = new char[100]; private static final Buffer stream = new Buffer(new byte[100]); private static final char[] validChars = { ' ', 'e', 't', 'a', 'o', 'i', 'h', 'n', 's', 'r', 'd', 'l', 'u', 'm', 'w', 'c', 'y', 'f', 'g', 'p', 'b', 'v', 'k', 'x', 'j', 'q', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ', '!', '?', '.', ',', ':', ';', '(', ')', '-', '&', '*', '\\', '\'', '@', '#', '+', '=', '\243', '$', '%', '"', '[', ']' }; public static String processText(String s) { stream.position = 0; writeToStream(s, stream); int offset = stream.position; stream.position = 0; String text = readFromStream(offset, stream); return text; } public static String readFromStream(int length, Buffer stream) { int pointer = 0; int l = -1; for (int c = 0; c < length; c++) { int encodedLetter = stream.getUnsignedByte(); int letter = encodedLetter >> 4 & 0xf; if (l == -1) { if (letter < 13) characterList[pointer++] = validChars[letter]; else l = letter; } else { characterList[pointer++] = validChars[((l << 4) + letter) - 195]; l = -1; } letter = encodedLetter & 0xf; if (l == -1) { if (letter < 13) characterList[pointer++] = validChars[letter]; else l = letter; } else { characterList[pointer++] = validChars[((l << 4) + letter) - 195]; l = -1; } } boolean endOfSentence = true; for (int c = 0; c < pointer; c++) { char character = characterList[c]; if (endOfSentence && character >= 'a' && character <= 'z') { characterList[c] += '\uFFE0'; endOfSentence = false; } if (character == '.' || character == '!' || character == '?') endOfSentence = true; } return new String(characterList, 0, pointer); } public static void writeToStream(String text, Buffer stream) { if (text.length() > 80) text = text.substring(0, 80); text = text.toLowerCase(); int i = -1; for (int c = 0; c < text.length(); c++) { char character = text.charAt(c); int characterCode = 0; for (int l = 0; l < validChars.length; l++) { if (character != validChars[l]) continue; characterCode = l; break; } if (characterCode > 12) characterCode += 195; if (i == -1) { if (characterCode < 13) i = characterCode; else stream.put(characterCode); } else if (characterCode < 13) { stream.put((i << 4) + characterCode); i = -1; } else { stream.put((i << 4) + (characterCode >> 4)); i = characterCode & 0xf; } } if (i != -1) stream.put(i << 4); } }
mit
CCI-MIT/XCoLab
view/src/main/java/org/xcolab/view/config/sentry/SentryUserInfoFilter.java
1530
package org.xcolab.view.config.sentry; import io.sentry.Sentry; import io.sentry.event.UserBuilder; import org.springframework.web.filter.GenericFilterBean; import org.xcolab.client.user.pojo.wrapper.UserWrapper; import org.xcolab.view.auth.AuthenticationContext; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class SentryUserInfoFilter extends GenericFilterBean { private final AuthenticationContext authenticationContext = new AuthenticationContext(); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new ServletException("SentryUserInfoFilter just supports HTTP requests"); } final UserWrapper realMemberOrNull = authenticationContext.getRealMemberOrNull(); if (realMemberOrNull != null) { //noinspection UnnecessaryLocalVariable final UserWrapper member = realMemberOrNull; Sentry.getContext().setUser(new UserBuilder() .setId(Long.toString(member.getId())) .setUsername(member.getScreenName()) .setIpAddress(request.getRemoteAddr()) .build()); } chain.doFilter(request, response); } }
mit
Davidx1337/UxNetIO
java/main/com/uxsoft/net/io/protocol/EncoderOutput.java
275
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.uxsoft.net.io.protocol; import com.uxsoft.net.io.common.ByteBuffer; /** * * @author David */ public interface EncoderOutput { void write(ByteBuffer out); }
mit
itsgreco/VirtueRS3
src/org/virtue/network/event/GameEventDispatcher.java
20165
/** * Copyright (c) 2014 Virtue Studios * * 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.virtue.network.event; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import java.util.Timer; import java.util.TimerTask; import org.virtue.Constants; import org.virtue.Virtue; import org.virtue.cache.utility.crypto.BKDR; import org.virtue.game.content.chat.ChannelType; import org.virtue.game.content.chat.OnlineStatus; import org.virtue.game.content.ignores.Ignore; import org.virtue.game.entity.Entity; import org.virtue.game.entity.combat.CombatMode; import org.virtue.game.entity.player.GameState; import org.virtue.game.entity.player.LoginDispatcher; import org.virtue.game.entity.player.Player; import org.virtue.game.entity.player.inv.Item; import org.virtue.game.entity.player.stat.PlayerStat; import org.virtue.game.entity.player.stat.Stat; import org.virtue.game.world.region.MapSize; import org.virtue.game.world.region.Tile; import org.virtue.network.event.buffer.OutboundBuffer; import org.virtue.network.event.context.GameEventContext; import org.virtue.network.event.context.impl.EmptyEventContext; import org.virtue.network.event.context.impl.in.OptionButton; import org.virtue.network.event.context.impl.out.ClientScriptEventContext; import org.virtue.network.event.context.impl.out.CutsceneEventContext; import org.virtue.network.event.context.impl.out.EnumEventContext; import org.virtue.network.event.context.impl.out.FriendListEventContext; import org.virtue.network.event.context.impl.out.IgnoreListEventContext; import org.virtue.network.event.context.impl.out.InvEventContext; import org.virtue.network.event.context.impl.out.LogoutEventContext; import org.virtue.network.event.context.impl.out.MapFlagEventContext; import org.virtue.network.event.context.impl.out.MessageEventContext; import org.virtue.network.event.context.impl.out.MusicEventContext; import org.virtue.network.event.context.impl.out.PlayerOptionEventContext; import org.virtue.network.event.context.impl.out.RunEnergyEventContext; import org.virtue.network.event.context.impl.out.RunWeightEventContext; import org.virtue.network.event.context.impl.out.SceneGraphEventContext; import org.virtue.network.event.context.impl.out.SystemUpdateEventContext; import org.virtue.network.event.context.impl.out.VarcEventContext; import org.virtue.network.event.context.impl.out.VarcStringEventContext; import org.virtue.network.event.context.impl.out.WorldListEventContext; import org.virtue.network.event.context.impl.out.widget.HideWidgetEventContext; import org.virtue.network.event.context.impl.out.widget.WidgetHttpSpriteEventContext; import org.virtue.network.event.context.impl.out.widget.WidgetModelEventContext; import org.virtue.network.event.context.impl.out.widget.WidgetModelEventContext.ModelType; import org.virtue.network.event.context.impl.out.widget.WidgetSettingsEventContext; import org.virtue.network.event.context.impl.out.widget.WidgetSubEventContext; import org.virtue.network.event.context.impl.out.widget.WidgetTextEventContext; import org.virtue.network.event.context.impl.out.widget.WidgetTopEventContext; import org.virtue.network.event.encoder.EventEncoder; import org.virtue.network.event.encoder.ServerProtocol; import org.virtue.network.event.encoder.impl.ClientScriptEventEncoder; import org.virtue.network.event.encoder.impl.CutsceneEventEncoder; import org.virtue.network.event.encoder.impl.EnumEventEncoder; import org.virtue.network.event.encoder.impl.FriendListEventEncoder; import org.virtue.network.event.encoder.impl.IgnoreListEventEncoder; import org.virtue.network.event.encoder.impl.InvEventEncoder; import org.virtue.network.event.encoder.impl.KeepAliveEventEncoder; import org.virtue.network.event.encoder.impl.LogoutEventEncoder; import org.virtue.network.event.encoder.impl.MapFlagEventEncoder; import org.virtue.network.event.encoder.impl.MessageEventEncoder; import org.virtue.network.event.encoder.impl.MusicEventEncoder; import org.virtue.network.event.encoder.impl.NpcUpdateEventEncoder; import org.virtue.network.event.encoder.impl.PlayerOptionEventEncoder; import org.virtue.network.event.encoder.impl.PlayerUpdateEventEncoder; import org.virtue.network.event.encoder.impl.ResetVarEventEncoder; import org.virtue.network.event.encoder.impl.RunEnergyEventEncoder; import org.virtue.network.event.encoder.impl.RunWeightEventEncoder; import org.virtue.network.event.encoder.impl.SceneGraphEventEncoder; import org.virtue.network.event.encoder.impl.SkillEventEncoder; import org.virtue.network.event.encoder.impl.SystemUpdateEventEncoder; import org.virtue.network.event.encoder.impl.UnlockFriendsEventEncoder; import org.virtue.network.event.encoder.impl.VarcEventEncoder; import org.virtue.network.event.encoder.impl.VarcStringEventEncoder; import org.virtue.network.event.encoder.impl.WorldListEventEncoder; import org.virtue.network.event.encoder.impl.widget.WidgetEventsEventEncoder; import org.virtue.network.event.encoder.impl.widget.WidgetHideEventEncoder; import org.virtue.network.event.encoder.impl.widget.WidgetHttpSpriteEventEncoder; import org.virtue.network.event.encoder.impl.widget.WidgetModelEventEncoder; import org.virtue.network.event.encoder.impl.widget.WidgetSubEventEncoder; import org.virtue.network.event.encoder.impl.widget.WidgetTextEventEncoder; import org.virtue.network.event.encoder.impl.widget.WidgetTopEventEncoder; import org.virtue.network.protocol.message.login.LoginTypeMessage; import org.virtue.utility.SerialisableEnum; /** * @author Im Frizzy <skype:kfriz1998> * @since Oct 9, 2014 */ public class GameEventDispatcher { /** * The player to dispatch game events */ private Player player; /** * The {@link GameEventDispatcher} constructor */ public GameEventDispatcher(Player player) { this.player = player; } /** * Dispatches the login type * * @param type * - type of login */ public void dispatchLogin(LoginTypeMessage type) { switch (type) { case LOGIN_LOBBY: player.setGameState(GameState.LOBBY); if (Virtue.getInstance().hasUpdate()) { sendSystemUpdate(Virtue.getInstance().getUpdateTime() * 12); } sendGameMessage("Welcome to " + Constants.FRAME_NAME + "."); LoginDispatcher.onLobbyLogin(player); break; case LOGIN_WORLD: case LOGIN_CONTINUE: player.setGameState(GameState.WORLD); sendSceneGraph(5, player.getCurrentTile(), MapSize.DEFAULT, true, true); if (Virtue.getInstance().hasUpdate()) { sendSystemUpdate(Virtue.getInstance().getUpdateTime() - 2); // Subtract a couple of ticks to account for delay } player.setGameState(GameState.WORLD_READY); player.getViewport().onMapLoaded(); sendGameMessage("Welcome to " + Constants.FRAME_NAME + "."); player.getEquipment().refresh(true); player.getModel().refresh(); player.updateWeight(); player.getSkills().sendAllSkills(); player.updateWeight(); sendRunEnergy(player.getRunEnergy()); if (player.getClanHash() != 0L) { Virtue.getInstance().getClans().getSettings().registerPlayer(player.getChat(), false); } LoginDispatcher.onGameLogin(player); player.getInteractions().initialise(); player.getExchangeOffers().init(); if (player.getMode() != CombatMode.LEGACY) { player.getCombatSchedule().increaseAdrenaline(0); player.getCombatSchedule().getActionBar().refresh(); } player.getImpactHandler() .setMaximumLifepoints(player.getSkills().getBaseLevel(Stat.CONSTITUTION) * 100); player.getImpactHandler().restoreLifepoints(); player.getVars().processLogin(player.getLastLogin()); //sendMusic(36067, 100); break; } sendOnlineStatus(player.getChat().getFriendsList().getOnlineStatus()); sendUnlockFriends(); player.getChat().getFriendsList().sendFriendsMyStatus(false); player.getChat().getIgnoreList().sendIgnores(); player.getChat().getFriendsList().sendFriendsList(); if (player.getClanHash() != 0L) { Virtue.getInstance().getClans().getChannels().joinMyChannel(player.getChat()); } } /** * Sends the cutscene. */ public void sendCutscene() { new Timer().schedule(new TimerTask() { @Override public void run() { player.getWidgets().openWidget(1477, 19, 548, true); } }, 2000); } public void sendVarReset() { sendEvent(ResetVarEventEncoder.class, new EmptyEventContext()); } public void sendVarc(int key, int value) { sendEvent(VarcEventEncoder.class, new VarcEventContext(key, value)); } public void sendVarcBit(int key, int value) { sendEvent(VarcEventEncoder.class, new VarcEventContext(key, value, true)); } public void sendVarcString(int key, String value) { sendEvent(VarcStringEventEncoder.class, new VarcStringEventContext(key, value)); } public void sendRootWidget(int widget) { sendEvent(WidgetTopEventEncoder.class, new WidgetTopEventContext( widget)); } public void sendWidget(int window, int component, int widgetId, boolean alwaysOpen) { sendEvent(WidgetSubEventEncoder.class, new WidgetSubEventContext( window, component, widgetId, alwaysOpen)); } public void openWidget(int window, int component, int widgetId, boolean alwaysOpen, Entity parent) { sendEvent(WidgetSubEventEncoder.class, new WidgetSubEventContext( window, component, widgetId, alwaysOpen, parent)); } public void sendHideWidget(int widget, int component, boolean hidden) { sendEvent(WidgetHideEventEncoder.class, new HideWidgetEventContext( widget, component, hidden)); } public void sendWidgetText(int widget, int component, String text) { sendEvent(WidgetTextEventEncoder.class, new WidgetTextEventContext( widget, component, text)); } public void sendWidgetModel(ModelType type, int widget, int component) { sendEvent(WidgetModelEventEncoder.class, new WidgetModelEventContext( type, widget, component)); } public void sendOtherPlayerWidgetModel(int widget, int component, Entity otherPlayer) { int namehash = BKDR.hash(otherPlayer.getName()); sendEvent(WidgetModelEventEncoder.class, new WidgetModelEventContext( ModelType.PLAYER_MODEL_OTHER, widget, component, otherPlayer.getIndex(), namehash)); } public void sendWidgetModel(ModelType type, int widget, int component, int modelID) { sendEvent(WidgetModelEventEncoder.class, new WidgetModelEventContext( type, widget, component, modelID)); } /** * Adds an object (item) to the specified widget component * @param widget The widget/interface ID * @param component The component ID * @param objectId The object type ID * @param count The number of objects to appear in the count */ public void sendWidgetObject (int widget, int component, int objectId, int count) { sendEvent(WidgetModelEventEncoder.class, new WidgetModelEventContext( ModelType.PLAYER_MODEL_OTHER, widget, component, objectId, count)); } public void sendWidgetEvents(int root, int component, int from, int to, int settings) { sendEvent(WidgetEventsEventEncoder.class, new WidgetSettingsEventContext(root, component, from, to, settings)); } public void sendWidgetExtarnalSprite(int widget, int component, int i) { sendEvent(WidgetHttpSpriteEventEncoder.class, new WidgetHttpSpriteEventContext(widget, component, i)); } public void sendKeepAlive(EmptyEventContext context) { sendEvent(KeepAliveEventEncoder.class, context); } public void sendWorldList(WorldListEventContext context) { sendEvent(WorldListEventEncoder.class, context); } public void sendSceneGraph(int sceneRadius, Tile tile, MapSize mapSize, boolean init, boolean isStatic) { sendEvent(SceneGraphEventEncoder.class, new SceneGraphEventContext(sceneRadius, tile, mapSize, init, isStatic)); } public void sendLogout(boolean toLobby) { sendEvent(LogoutEventEncoder.class, new LogoutEventContext(toLobby)); } public void sendMessage(String message, ChannelType type) { sendEvent(MessageEventEncoder.class, new MessageEventContext(type, message)); } public void sendMessage(MessageEventContext message) { sendEvent(MessageEventEncoder.class, message); } public void sendGameMessage(String message) { sendEvent(MessageEventEncoder.class, new MessageEventContext( ChannelType.GAME, message)); } public void sendConsoleMessage(String message) { sendEvent(MessageEventEncoder.class, new MessageEventContext( ChannelType.CONSOLE, message)); } public void sendTrayMessage(String message) { // sendEvent(TrayMessageEventEncoder.class, new // TrayMessageEventContext(message)); } /** * Sends the online status of the player */ public void sendOnlineStatus(OnlineStatus status) { sendEnum(ServerProtocol.ONLINE_STATUS, status); } /** * Unlocks the friends/ignores list */ public void sendUnlockFriends() { sendEvent(UnlockFriendsEventEncoder.class, new EmptyEventContext()); } /** * Generates the friends list if the play has no friends */ public void generateFriendsBlock(boolean empty) { sendEvent(FriendListEventEncoder.class, new FriendListEventContext( empty)); } /** * Sends the ignores list */ public void sendIgnoresList(Ignore ignore, boolean warned) { sendEvent(IgnoreListEventEncoder.class, new IgnoreListEventContext( ignore, warned)); } /** * Sends a system update timer * * @param delay * - the delay in ticks */ public void sendSystemUpdate(int delay) { sendEvent(SystemUpdateEventEncoder.class, new SystemUpdateEventContext( delay)); } /** * Sends the player's current run energy level * * @param energy * The energy level */ public void sendRunEnergy(int energy) { sendEvent(RunEnergyEventEncoder.class, new RunEnergyEventContext(energy)); } /** * Sends the player's current weight * * @param weight * The weight of the player */ public void sendRunWeight(int weight) { sendEvent(RunWeightEventEncoder.class, new RunWeightEventContext(weight)); } /** * Sends an update for the specified skill * * @param skill * The skill to update */ public void sendStat(PlayerStat skill) { sendEvent(SkillEventEncoder.class, skill); } /** * Sends the prayer points varp * * @param pray */ public void sendPrayer(int pray) { player.getVars().setVarValueInt(3274, pray); } /** * Sends the player update event */ public void sendPlayerUpdate() { sendEvent(PlayerUpdateEventEncoder.class, player.getViewport()); } /** * Sends the npc update event */ public void sendNPCUpdate() { sendEvent(NpcUpdateEventEncoder.class, player.getViewport()); } /** * Resets the position of the minimap flag (to the player's current * position) */ public void sendResetMapFlag() { sendMapFlag(-1, -1); } /** * Sends the location of the client minimap flag. * * @param posX * The local x-coordinate of the map flag * @param posY * The local y-coordinate of the map flag */ public void sendMapFlag(int posX, int posY) { sendEvent(MapFlagEventEncoder.class, new MapFlagEventContext(posX, posY)); } /** * Sends an inventory items * * @param id * @param items */ public void sendItems(int id, Item[] items) { sendEvent(InvEventEncoder.class, new InvEventContext(id, items)); } /** * Sends iventory items * * @param id * @param items * @param slots */ public void sendItems(int id, Item[] items, int... slots) { sendEvent(InvEventEncoder.class, new InvEventContext(id, items, slots)); } /** * Sends a cs2 scripts (client script) * * @param id * @param params */ public void sendCS2Script(int id, Object... params) { sendEvent(ClientScriptEventEncoder.class, new ClientScriptEventContext( id, params)); } //FIXME: remove... public void sendCS2Script2(int id, Object... params) { Object[] buff = new Object[params.length]; for(int i=params.length-1,j=0; i >= 0; i--,j++) buff[j] = params[i]; sendEvent(ClientScriptEventEncoder.class, new ClientScriptEventContext(id, buff)); } /** * Sends a serialisable enumeration value */ public void sendEnum(ServerProtocol type, SerialisableEnum value) { sendEvent(EnumEventEncoder.class, new EnumEventContext(type, value)); } /** * Sets a client-side right-click option for all other players * * @param option * The option to set * @param text * The text for the option * @param cursor * The cursor ID * @param isTop * Whether the option sits at the top of the menu or not */ public void sendPlayerOption(OptionButton option, String text, int cursor, boolean isTop) { sendEvent(PlayerOptionEventEncoder.class, new PlayerOptionEventContext( option, text, cursor, isTop)); } /** * Plays the cutscene in the player's client * * @param id * The id of the cutscene to play */ public void sendCutscene(int id) { sendEvent(CutsceneEventEncoder.class, new CutsceneEventContext(id, player.getModel().getData())); } public void sendMusic(int id, int vol) { sendEvent(MusicEventEncoder.class, new MusicEventContext(id, vol)); } /** * Sends a EventEncoder over the network * * @param clazz * @param context */ public <T extends EventEncoder<?>> ChannelFuture sendEvent( Class<T> clazz, GameEventContext context) { if (player.getChannel().isActive()) { OutboundBuffer packet = Virtue.getInstance().getEventRepository() .encode(player, clazz, context); ByteBuf buffer = Unpooled.copiedBuffer(packet.buffer(), 0, packet.offset()); synchronized (player.getChannel()) { return player.getChannel().writeAndFlush(buffer); } } return null; } /** * Sens a OutBuffer over the network * * @param buffer */ public ChannelFuture sendBuffer(OutboundBuffer packet) { if (player.getChannel().isActive()) { ByteBuf buffer = Unpooled.copiedBuffer(packet.buffer(), 0, packet.offset()); synchronized (player.getChannel()) { return player.getChannel().writeAndFlush(buffer); } } return null; } /** * Send a ByteBuf over the network * * @param buffer */ public ChannelFuture sendByteBuf(ByteBuf buffer) { if (player.getChannel().isActive()) { synchronized (player.getChannel()) { return player.getChannel().writeAndFlush( Unpooled.copiedBuffer(buffer)); } } return null; } public void sendMusic(int song) { sendEvent(MusicEventEncoder.class, new MusicEventContext(song, 100)); } }
mit
SpongePowered/Sponge
vanilla/src/mixins/java/org/spongepowered/vanilla/mixin/core/server/level/ServerPlayerMixin_Vanilla.java
4691
/* * This file is part of Sponge, 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.vanilla.mixin.core.server.level; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.dimension.DimensionType; import org.checkerframework.checker.nullness.qual.NonNull; import org.spongepowered.api.entity.living.player.server.ServerPlayer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.bridge.server.level.ServerPlayerBridge; import org.spongepowered.common.entity.player.ClientType; import org.spongepowered.common.event.tracking.PhaseContext; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.event.tracking.context.transaction.EffectTransactor; import org.spongepowered.common.event.tracking.context.transaction.TransactionalCaptureSupplier; import org.spongepowered.common.event.tracking.context.transaction.inventory.PlayerInventoryTransaction; import org.spongepowered.common.network.packet.ChangeViewerEnvironmentPacket; import org.spongepowered.common.network.packet.SpongePacketHandler; import org.spongepowered.common.world.portal.PortalLogic; import org.spongepowered.vanilla.mixin.core.world.entity.EntityMixin_Vanilla; import org.spongepowered.vanilla.mixin.core.world.entity.LivingEntityMixin_Vanilla; import javax.annotation.Nullable; @Mixin(net.minecraft.server.level.ServerPlayer.class) public abstract class ServerPlayerMixin_Vanilla extends LivingEntityMixin_Vanilla implements ServerPlayerBridge { @Override public void bridge$sendViewerEnvironment(final DimensionType dimensionType) { if (this.bridge$getClientType() == ClientType.SPONGE_VANILLA) { SpongePacketHandler.getChannel().sendTo((ServerPlayer) this, new ChangeViewerEnvironmentPacket(dimensionType)); } } /** * @author dualspiral - 18th December 2020 - 1.16.4 * @reason Redirects the vanilla changeDimension method to our own * to support our event and other logic (see * ServerPlayerEntityMixin on the common mixin sourceset for * details). * * This method does not explicitly exist on SeverPlayerEntity * on Forge, it is an overridden method in Vanilla so needs doing * here as well as in EntityMixin_Vanilla. * * This will get called on the nether dimension changes, as the * end portal teleport call itself has been redirected to provide * the correct type. */ @Overwrite @Nullable public net.minecraft.world.entity.Entity changeDimension(final ServerLevel target) { return this.bridge$changeDimension(target, (PortalLogic) target.getPortalForcer()); } // override from LivingEntityMixin_Vanilla @Override protected void vanilla$onElytraUse(final CallbackInfo ci) { final PhaseContext<@NonNull ?> context = PhaseTracker.SERVER.getPhaseContext(); final TransactionalCaptureSupplier transactor = context.getTransactor(); final net.minecraft.server.level.ServerPlayer player = (net.minecraft.server.level.ServerPlayer) (Object) this; try (final EffectTransactor ignored = transactor.logPlayerInventoryChangeWithEffect(player, PlayerInventoryTransaction.EventCreator.STANDARD)) { player.inventoryMenu.broadcastChanges(); // capture } } }
mit
jeikerxiao/SpringBootStudy
spring-boot-druid/src/test/java/com/jeiker/demo/mapper/CityMapperTest.java
699
package com.jeiker.demo.mapper; import com.jeiker.demo.entity.City; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; /** * @Author : xiao * @Date : 17/3/21 上午10:56 */ @RunWith(SpringRunner.class) @SpringBootTest public class CityMapperTest { @Autowired CityMapper cityMapper; @Test public void findCityById() throws Exception { City city = cityMapper.selectByPrimaryKey(1); assertEquals(city.getId(), Integer.valueOf(1)); } }
mit
jmue/Gitskarios
app/src/main/java/com/alorma/github/ui/fragment/commit/CommitFilesFragment.java
3903
package com.alorma.github.ui.fragment.commit; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.alorma.github.R; import com.alorma.github.sdk.bean.dto.response.CommitFile; import com.alorma.github.sdk.bean.info.CommitInfo; import com.alorma.github.ui.adapter.commit.CommitFilesAdapter; import com.alorma.github.ui.fragment.base.BaseFragment; import com.alorma.gitskarios.core.client.BaseClient; import java.util.List; /** * Created by Bernat on 22/12/2014. */ public class CommitFilesFragment extends BaseFragment { public static final String INFO = "INFO"; private RecyclerView recyclerView; private UpdateReceiver updateReceiver; private CommitInfo info; private CommitFilesAdapter.OnFileRequestListener onFileRequestListener; public static CommitFilesFragment newInstance(CommitInfo info) { CommitFilesFragment f = new CommitFilesFragment(); Bundle b = new Bundle(); b.putParcelable(INFO, info); f.setArguments(b); return f; } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.files_fragment, null); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (getArguments() != null) { info = getArguments().getParcelable(INFO); recyclerView = (RecyclerView) view.findViewById(R.id.recycler); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); getContent(); } } private void getContent() { } public void setFiles(List<CommitFile> files) { if (getActivity() != null) { CommitFilesAdapter adapter = new CommitFilesAdapter(LayoutInflater.from(getActivity())); adapter.addAll(files); adapter.setOnFileRequestListener(onFileRequestListener); recyclerView.setAdapter(adapter); } } public void reload() { getContent(); } @Override public void onStart() { super.onStart(); updateReceiver = new UpdateReceiver(); IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); getActivity().registerReceiver(updateReceiver, intentFilter); } @Override public void onStop() { super.onStop(); getActivity().unregisterReceiver(updateReceiver); } public void setOnFileRequestListener(CommitFilesAdapter.OnFileRequestListener onFileRequestListener) { this.onFileRequestListener = onFileRequestListener; } public class UpdateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (isOnline(context)) { reload(); } } public boolean isOnline(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfoMob = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo netInfoWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); return (netInfoMob != null && netInfoMob.isConnectedOrConnecting()) || (netInfoWifi != null && netInfoWifi.isConnectedOrConnecting()); } } }
mit
ssdwa/android
dConnectDevicePlugin/dConnectDevicePebble/src/org/deviceconnect/android/deviceplugin/pebble/profile/PebbleKeyEventProfile.java
17601
/* PebbleKeyEventProfile.java Copyright (c) 2015 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.deviceplugin.pebble.profile; import java.util.List; import org.deviceconnect.android.deviceplugin.pebble.PebbleDeviceService; import org.deviceconnect.android.deviceplugin.pebble.util.PebbleManager; import org.deviceconnect.android.deviceplugin.pebble.util.PebbleManager.OnReceivedEventListener; import org.deviceconnect.android.deviceplugin.pebble.util.PebbleManager.OnSendCommandListener; import org.deviceconnect.android.event.Event; import org.deviceconnect.android.event.EventError; import org.deviceconnect.android.event.EventManager; import org.deviceconnect.android.message.MessageUtils; import org.deviceconnect.android.profile.KeyEventProfile; import org.deviceconnect.message.DConnectMessage; import org.deviceconnect.profile.KeyEventProfileConstants; import android.content.Intent; import android.os.Bundle; import com.getpebble.android.kit.util.PebbleDictionary; /** * Pebble Key Event Profile. * * @author NTT DOCOMO, INC. */ public class PebbleKeyEventProfile extends KeyEventProfile { /** Error message for not setting sessionKey. */ private static final String ERROR_MESSAGE = "sessionKey must be specified."; /** KeyEvent profile onDown cache. */ Bundle mOnDownCache = null; /** KeyEvent profile onDown cache time. */ long mOnDownCacheTime = 0; /** KeyEvent profile onUp cache. */ Bundle mOnUpCache = null; /** KeyEvent profile onUp cache time. */ long mOnUpCacheTime = 0; /** KeyEvent profile cache retention time (mSec). */ static final long CACHE_RETENTION_TIME = 10000; /** * Get KeyEvent cache data. * * @param attr Attribute. * @return KeyEvent cache data. */ public Bundle getKeyEventCache(final String attr) { long lCurrentTime = System.currentTimeMillis(); if (attr.equals(KeyEventProfile.ATTRIBUTE_ON_DOWN)) { if (lCurrentTime - mOnDownCacheTime <= CACHE_RETENTION_TIME) { return mOnDownCache; } else { return null; } } else if (attr.equals(KeyEventProfile.ATTRIBUTE_ON_UP)) { if (lCurrentTime - mOnUpCacheTime <= CACHE_RETENTION_TIME) { return mOnUpCache; } else { return null; } } else { return null; } } /** * Set KeyEvent data to cache. * * @param attr Attribute. * @param keyeventData Touch data. */ public void setKeyEventCache(final String attr, final Bundle keyeventData) { long lCurrentTime = System.currentTimeMillis(); if (attr.equals(KeyEventProfile.ATTRIBUTE_ON_DOWN)) { mOnDownCache = keyeventData; mOnDownCacheTime = lCurrentTime; } else if (attr.equals(KeyEventProfile.ATTRIBUTE_ON_UP)) { mOnUpCache = keyeventData; mOnUpCacheTime = lCurrentTime; } } /** * Constructor. * * @param service Pebble device service. */ public PebbleKeyEventProfile(final PebbleDeviceService service) { service.getPebbleManager().addEventListener(PebbleManager.PROFILE_KEY_EVENT, new OnReceivedEventListener() { @Override public void onReceivedEvent(final PebbleDictionary dic) { // Set event data. Bundle keyevent = new Bundle(); Long lKeyId = dic.getInteger(PebbleManager.KEY_PARAM_KEY_EVENT_ID); int nKeyId = Integer.valueOf(lKeyId.toString()); Long lKeyType = dic.getInteger(PebbleManager.KEY_PARAM_KEY_EVENT_KEY_TYPE); int nKeyType = Integer.valueOf(lKeyType.toString()); setConfig(keyevent, getConfig(nKeyType, nKeyId)); setId(keyevent, nKeyId + getKeyTypeFlagValue(nKeyType)); // Get event list from event listener. List<Event> evts = null; Long lAttribute = dic.getInteger(PebbleManager.KEY_ATTRIBUTE); if (lAttribute == PebbleManager.KEY_EVENT_ATTRIBUTE_ON_UP) { evts = EventManager.INSTANCE.getEventList(service.getServiceId(), PROFILE_NAME, null, ATTRIBUTE_ON_UP); } else if (lAttribute == PebbleManager.KEY_EVENT_ATTRIBUTE_ON_DOWN) { evts = EventManager.INSTANCE.getEventList(service.getServiceId(), PROFILE_NAME, null, ATTRIBUTE_ON_DOWN); } else { return; } for (Event evt : evts) { String attr = evt.getAttribute(); // Notify each to the event listener. Intent intent = EventManager.createEventMessage(evt); intent.putExtra(KeyEventProfile.PARAM_KEYEVENT, keyevent); ((PebbleDeviceService) getContext()).sendEvent(intent, evt.getAccessToken()); setKeyEventCache(attr, keyevent); } } }); } @Override protected boolean onGetOnDown(final Intent request, final Intent response, final String serviceId) { if (serviceId == null) { MessageUtils.setEmptyServiceIdError(response); } else if (!PebbleUtil.checkServiceId(serviceId)) { MessageUtils.setNotFoundServiceError(response); } else { Bundle keyevent = getKeyEventCache(KeyEventProfile.ATTRIBUTE_ON_DOWN); if (keyevent == null) { response.putExtra(KeyEventProfile.PARAM_KEYEVENT, ""); } else { response.putExtra(KeyEventProfile.PARAM_KEYEVENT, keyevent); } setResult(response, DConnectMessage.RESULT_OK); } return true; } @Override protected boolean onGetOnUp(final Intent request, final Intent response, final String serviceId) { if (serviceId == null) { MessageUtils.setEmptyServiceIdError(response); } else if (!PebbleUtil.checkServiceId(serviceId)) { MessageUtils.setNotFoundServiceError(response); } else { Bundle keyevent = getKeyEventCache(KeyEventProfile.ATTRIBUTE_ON_UP); if (keyevent == null) { response.putExtra(KeyEventProfile.PARAM_KEYEVENT, ""); } else { response.putExtra(KeyEventProfile.PARAM_KEYEVENT, keyevent); } setResult(response, DConnectMessage.RESULT_OK); } return true; } @Override protected boolean onPutOnDown(final Intent request, final Intent response, final String serviceId, final String sessionKey) { if (serviceId == null) { MessageUtils.setEmptyServiceIdError(response); return true; } else if (!PebbleUtil.checkServiceId(serviceId)) { MessageUtils.setNotFoundServiceError(response); return true; } else if (sessionKey == null) { MessageUtils.setInvalidRequestParameterError(response, ERROR_MESSAGE); return true; } else { PebbleManager mgr = ((PebbleDeviceService) getContext()).getPebbleManager(); // To Pebble, Send registration request of key event. PebbleDictionary dic = new PebbleDictionary(); dic.addInt8(PebbleManager.KEY_PROFILE, (byte) PebbleManager.PROFILE_KEY_EVENT); dic.addInt8(PebbleManager.KEY_ATTRIBUTE, (byte) PebbleManager.KEY_EVENT_ATTRIBUTE_ON_DOWN); dic.addInt8(PebbleManager.KEY_ACTION, (byte) PebbleManager.ACTION_PUT); mgr.sendCommandToPebble(dic, new OnSendCommandListener() { @Override public void onReceivedData(final PebbleDictionary dic) { if (dic == null) { MessageUtils.setUnknownError(response); } else { // Registration event listener. EventError error = EventManager.INSTANCE.addEvent(request); if (error == EventError.NONE) { setResult(response, DConnectMessage.RESULT_OK); } else if (error == EventError.INVALID_PARAMETER) { MessageUtils.setInvalidRequestParameterError(response); } else { MessageUtils.setUnknownError(response); } } getContext().sendBroadcast(response); } }); // Since returning the response asynchronously, it returns false. return false; } } @Override protected boolean onPutOnUp(final Intent request, final Intent response, final String serviceId, final String sessionKey) { if (serviceId == null) { MessageUtils.setEmptyServiceIdError(response); return true; } else if (!PebbleUtil.checkServiceId(serviceId)) { MessageUtils.setNotFoundServiceError(response); return true; } else if (sessionKey == null) { MessageUtils.setInvalidRequestParameterError(response, ERROR_MESSAGE); return true; } else { PebbleManager mgr = ((PebbleDeviceService) getContext()).getPebbleManager(); // To Pebble, Send registration request of key event. PebbleDictionary dic = new PebbleDictionary(); dic.addInt8(PebbleManager.KEY_PROFILE, (byte) PebbleManager.PROFILE_KEY_EVENT); dic.addInt8(PebbleManager.KEY_ATTRIBUTE, (byte) PebbleManager.KEY_EVENT_ATTRIBUTE_ON_UP); dic.addInt8(PebbleManager.KEY_ACTION, (byte) PebbleManager.ACTION_PUT); mgr.sendCommandToPebble(dic, new OnSendCommandListener() { @Override public void onReceivedData(final PebbleDictionary dic) { if (dic == null) { MessageUtils.setUnknownError(response); } else { // Registration event listener. EventError error = EventManager.INSTANCE.addEvent(request); if (error == EventError.NONE) { setResult(response, DConnectMessage.RESULT_OK); } else if (error == EventError.INVALID_PARAMETER) { MessageUtils.setInvalidRequestParameterError(response); } else { MessageUtils.setUnknownError(response); } } getContext().sendBroadcast(response); } }); // Since returning the response asynchronously, it returns false. return false; } } @Override protected boolean onDeleteOnDown(final Intent request, final Intent response, final String serviceId, final String sessionKey) { if (serviceId == null) { MessageUtils.setEmptyServiceIdError(response); return true; } else if (!PebbleUtil.checkServiceId(serviceId)) { MessageUtils.setNotFoundServiceError(response); return true; } else if (sessionKey == null) { MessageUtils.setInvalidRequestParameterError(response, ERROR_MESSAGE); return true; } else { PebbleManager mgr = ((PebbleDeviceService) getContext()).getPebbleManager(); // To Pebble, Send cancellation request of key event. PebbleDictionary dic = new PebbleDictionary(); dic.addInt8(PebbleManager.KEY_PROFILE, (byte) PebbleManager.PROFILE_KEY_EVENT); dic.addInt8(PebbleManager.KEY_ATTRIBUTE, (byte) PebbleManager.KEY_EVENT_ATTRIBUTE_ON_DOWN); dic.addInt8(PebbleManager.KEY_ACTION, (byte) PebbleManager.ACTION_DELETE); mgr.sendCommandToPebble(dic, new OnSendCommandListener() { @Override public void onReceivedData(final PebbleDictionary dic) { } }); // Remove event listener. EventError error = EventManager.INSTANCE.removeEvent(request); if (error == EventError.NONE) { setResult(response, DConnectMessage.RESULT_OK); } else if (error == EventError.INVALID_PARAMETER) { MessageUtils.setInvalidRequestParameterError(response); } else { MessageUtils.setUnknownError(response); } return true; } } @Override protected boolean onDeleteOnUp(final Intent request, final Intent response, final String serviceId, final String sessionKey) { if (serviceId == null) { MessageUtils.setEmptyServiceIdError(response); return true; } else if (!PebbleUtil.checkServiceId(serviceId)) { MessageUtils.setNotFoundServiceError(response); return true; } else if (sessionKey == null) { MessageUtils.setInvalidRequestParameterError(response, ERROR_MESSAGE); return true; } else { PebbleManager mgr = ((PebbleDeviceService) getContext()).getPebbleManager(); // To Pebble, Send cancellation request of key event. PebbleDictionary dic = new PebbleDictionary(); dic.addInt8(PebbleManager.KEY_PROFILE, (byte) PebbleManager.PROFILE_KEY_EVENT); dic.addInt8(PebbleManager.KEY_ATTRIBUTE, (byte) PebbleManager.KEY_EVENT_ATTRIBUTE_ON_UP); dic.addInt8(PebbleManager.KEY_ACTION, (byte) PebbleManager.ACTION_DELETE); mgr.sendCommandToPebble(dic, new OnSendCommandListener() { @Override public void onReceivedData(final PebbleDictionary dic) { } }); // Remove event listener. EventError error = EventManager.INSTANCE.removeEvent(request); if (error == EventError.NONE) { setResult(response, DConnectMessage.RESULT_OK); } else if (error == EventError.INVALID_PARAMETER) { MessageUtils.setInvalidRequestParameterError(response); } else { MessageUtils.setUnknownError(response); } return true; } } /** * Get configuration string. * * @param nType Key Type. * @param nCode Key Code. * @return Configure string. */ private String getConfig(final int nType, final int nCode) { switch (nType) { case PebbleManager.KEY_EVENT_KEY_TYPE_MEDIA: switch (nCode) { case PebbleManager.KEY_EVENT_KEY_ID_UP: return "MEDIA_NEXT"; case PebbleManager.KEY_EVENT_KEY_ID_SELECT: return "MEDIA_PLAY"; case PebbleManager.KEY_EVENT_KEY_ID_DOWN: return "MEDIA_PREVIOUS"; case PebbleManager.KEY_EVENT_KEY_ID_BACK: return "MEDIA_BACK"; default: return ""; } case PebbleManager.KEY_EVENT_KEY_TYPE_DPAD_BUTTON: switch (nCode) { case PebbleManager.KEY_EVENT_KEY_ID_UP: return "DPAD_UP"; case PebbleManager.KEY_EVENT_KEY_ID_SELECT: return "DPAD_CENTER"; case PebbleManager.KEY_EVENT_KEY_ID_DOWN: return "DPAD_DOWN"; case PebbleManager.KEY_EVENT_KEY_ID_BACK: return "DPAD_BACK"; default: return ""; } case PebbleManager.KEY_EVENT_KEY_TYPE_USER: switch (nCode) { case PebbleManager.KEY_EVENT_KEY_ID_UP: return "USER_CANCEL"; case PebbleManager.KEY_EVENT_KEY_ID_SELECT: return "USER_SELECT"; case PebbleManager.KEY_EVENT_KEY_ID_DOWN: return "USER_OK"; case PebbleManager.KEY_EVENT_KEY_ID_BACK: return "USER_BACK"; default: return ""; } case PebbleManager.KEY_EVENT_KEY_TYPE_STD_KEY: default: switch (nCode) { case PebbleManager.KEY_EVENT_KEY_ID_UP: return "UP"; case PebbleManager.KEY_EVENT_KEY_ID_SELECT: return "SELECT"; case PebbleManager.KEY_EVENT_KEY_ID_DOWN: return "DOWN"; case PebbleManager.KEY_EVENT_KEY_ID_BACK: return "BACK"; default: return ""; } } } /** * Get key type flag value. * * @param nType Key Type. * @return Key Type Flag Value. */ private int getKeyTypeFlagValue(final int nType) { switch (nType) { case PebbleManager.KEY_EVENT_KEY_TYPE_MEDIA: return KeyEventProfileConstants.KEYTYPE_MEDIA_CTRL; case PebbleManager.KEY_EVENT_KEY_TYPE_DPAD_BUTTON: return KeyEventProfileConstants.KEYTYPE_DPAD_BUTTON; case PebbleManager.KEY_EVENT_KEY_TYPE_USER: return KeyEventProfileConstants.KEYTYPE_USER; case PebbleManager.KEY_EVENT_KEY_TYPE_STD_KEY: default: return KeyEventProfileConstants.KEYTYPE_STD_KEY; } } }
mit
SpongePowered/Sponge
src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/WitherSkullMixin.java
5981
/* * This file is part of Sponge, 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.common.mixin.core.world.entity.projectile; import org.spongepowered.api.data.Keys; import org.spongepowered.api.entity.projectile.Projectile; import org.spongepowered.api.entity.projectile.explosive.WitherSkull; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.EventContextKeys; import org.spongepowered.api.world.explosion.Explosion; import org.spongepowered.api.world.server.ServerLocation; import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.accessor.world.entity.projectile.ProjectileAccessor; import org.spongepowered.common.bridge.world.entity.GrieferBridge; import org.spongepowered.common.bridge.world.entity.projectile.WitherSkullBridge; import org.spongepowered.common.bridge.explosives.ExplosiveBridge; import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.util.Constants; import java.util.Optional; import javax.annotation.Nullable; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.Explosion.BlockInteraction; @Mixin(net.minecraft.world.entity.projectile.WitherSkull.class) public abstract class WitherSkullMixin extends AbstractHurtingProjectileMixin implements WitherSkullBridge, ExplosiveBridge { private int impl$explosionRadius = Constants.Entity.WitherSkull.DEFAULT_EXPLOSION_RADIUS; // TODO Key not implemented private float impl$damage = 0.0f; private boolean impl$damageSet = false; @ModifyArg(method = "onHitEntity", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/Entity;hurt(Lnet/minecraft/world/damagesource/DamageSource;F)Z")) private float impl$onAttackEntityFrom(final float amount) { if (this.impl$damageSet) { return this.impl$damage; } if (((ProjectileAccessor) this).accessor$ownerUUID() != null) { return Constants.Entity.WitherSkull.DEFAULT_WITHER_CREATED_SKULL_DAMAGE; } return Constants.Entity.WitherSkull.DEFAULT_NO_SOURCE_SKULL_DAMAGE; } // Explosive Impl @Override public Optional<Integer> bridge$getExplosionRadius() { return Optional.of(this.impl$explosionRadius); } @Override public void bridge$setExplosionRadius(final @Nullable Integer explosionRadius) { this.impl$explosionRadius = explosionRadius == null ? Constants.Entity.WitherSkull.DEFAULT_EXPLOSION_RADIUS : explosionRadius; } @Nullable @Redirect(method = "onHit", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;explode(Lnet/minecraft/world/entity/Entity;DDDFZLnet/minecraft/world/level/Explosion$BlockInteraction;)Lnet/minecraft/world/level/Explosion;")) public net.minecraft.world.level.Explosion impl$CreateAndProcessExplosionEvent(final net.minecraft.world.level.Level worldObj, final Entity self, final double x, final double y, final double z, final float strength, final boolean flaming, final BlockInteraction mode) { return this.bridge$throwExplosionEventAndExplosde(worldObj, self, x, y, z, strength, flaming, mode); } @Override public net.minecraft.world.level.Explosion bridge$throwExplosionEventAndExplosde( final net.minecraft.world.level.Level worldObj, final Entity self, final double x, final double y, final double z, final float strength, final boolean flaming, final net.minecraft.world.level.Explosion.BlockInteraction mode) { final boolean griefer = ((GrieferBridge) this).bridge$canGrief(); try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { frame.pushCause(this); ((Projectile) this).get(Keys.SHOOTER).ifPresent(shooter -> { frame.addContext(EventContextKeys.PROJECTILE_SOURCE, shooter); frame.pushCause(shooter); }); return SpongeCommonEventFactory.detonateExplosive(this, Explosion.builder() .location(ServerLocation.of((ServerWorld) worldObj, x, y, z)) .sourceExplosive(((WitherSkull) this)) .radius(this.impl$explosionRadius) .canCauseFire(flaming) .shouldPlaySmoke(mode != BlockInteraction.NONE && griefer) .shouldBreakBlocks(mode != BlockInteraction.NONE && griefer)) .orElse(null); } } }
mit
FlexSeries/FlexMotd
src/main/java/me/st28/flexseries/flexmotd/commands/arguments/PingGroupArgument.java
1958
/** * FlexMotd - Licensed under the MIT License (MIT) * * Copyright (c) Stealth2800 <http://stealthyone.com/> * Copyright (c) contributors <https://github.com/FlexSeries> * * 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 me.st28.flexseries.flexmotd.commands.arguments; import me.st28.flexseries.flexlib.command.CommandContext; import me.st28.flexseries.flexlib.command.argument.DummyArgument; import me.st28.flexseries.flexlib.plugin.FlexPlugin; import me.st28.flexseries.flexmotd.backend.PingManager; import java.util.ArrayList; import java.util.List; public class PingGroupArgument extends DummyArgument { public PingGroupArgument(String name, boolean isRequired) { super(name, isRequired); } @Override public List<String> getSuggestions(CommandContext context, String input) { return new ArrayList<>(FlexPlugin.getGlobalModule(PingManager.class).getGroups().keySet()); } }
mit