repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
ckaestne/LEADT
workspace/argouml_critics/argouml-app/src/org/argouml/notation/providers/uml/AssociationRoleNotationUml.java
9087
// $Id: AssociationRoleNotationUml.java 127 2010-09-25 22:23:13Z marcusvnac $ // Copyright (c) 2006-2009 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.notation.providers.uml; import java.text.ParseException; import java.util.Collection; import java.util.Iterator; import java.util.Map; import org.argouml.application.events.ArgoEventPump; import org.argouml.application.events.ArgoEventTypes; import org.argouml.application.events.ArgoHelpEvent; import org.argouml.i18n.Translator; import org.argouml.model.Model; import org.argouml.notation.NotationSettings; import org.argouml.notation.providers.AssociationRoleNotation; import org.argouml.util.MyTokenizer; /** * The UML notation for an AssociationRole. * * @author michiel */ public class AssociationRoleNotationUml extends AssociationRoleNotation { /** * The constructor. * * @param role the given association-role */ public AssociationRoleNotationUml(Object role) { super(role); } /* * @see org.argouml.notation.providers.NotationProvider#getParsingHelp() */ public String getParsingHelp() { return "parsing.help.fig-association-role"; } /* * @see org.argouml.notation.providers.NotationProvider#parse(java.lang.Object, java.lang.String) */ public void parse(Object modelElement, String text) { try { parseRole(modelElement, text); } catch (ParseException pe) { String msg = "statusmsg.bar.error.parsing.association-role"; Object[] args = { pe.getLocalizedMessage(), Integer.valueOf(pe.getErrorOffset()), }; ArgoEventPump.fireEvent(new ArgoHelpEvent( ArgoEventTypes.HELP_CHANGED, this, Translator.messageFormat(msg, args))); } } /** * Parse the string that represents an AssociationRole: <pre> * ["/" name] [":" name_of_the_base_association] * </pre> * * @param role The AssociationRole <em>text</em> describes. * @param text A String on the above format. * @throws ParseException * when it detects an error in the role string. See also * ParseError.getErrorOffset(). */ protected void parseRole(Object role, String text) throws ParseException { String token; boolean hasColon = false; boolean hasSlash = false; String rolestr = null; String basestr = null; MyTokenizer st = new MyTokenizer(text, " ,\t,/,:"); while (st.hasMoreTokens()) { token = st.nextToken(); if (" ".equals(token) || "\t".equals(token)) { /* Do nothing. */ } else if ("/".equals(token)) { hasSlash = true; hasColon = false; } else if (":".equals(token)) { hasColon = true; hasSlash = false; } else if (hasColon) { if (basestr != null) { String msg = "parsing.error.association-role.association-extra-text"; throw new ParseException(Translator.localize(msg), st .getTokenIndex()); } basestr = token; } else if (hasSlash) { if (rolestr != null) { String msg = "parsing.error.association-role.association-extra-text"; throw new ParseException(Translator.localize(msg), st .getTokenIndex()); } rolestr = token; } else { String msg = "parsing.error.association-role.association-extra-text"; throw new ParseException(Translator.localize(msg), st.getTokenIndex()); } } if (basestr == null) { /* If no base was typed, then only set the name: */ if (rolestr != null) { Model.getCoreHelper().setName(role, rolestr.trim()); } return; } /* If the base was not changed, then only set the name: */ Object currentBase = Model.getFacade().getBase(role); if (currentBase != null) { String currentBaseStr = Model.getFacade().getName(currentBase); if (currentBaseStr == null) { /* TODO: Is this needed? */ currentBaseStr = ""; } if (currentBaseStr.equals(basestr)) { if (rolestr != null) { Model.getCoreHelper().setName(role, rolestr.trim()); } return; } } //#if defined(COLLABORATIONDIAGRAM) or defined(SEQUENCEDIAGRAM) //@#$LPS-COLLABORATIONDIAGRAM:GranularityType:Statement //@#$LPS-SEQUENCEDIAGRAM:GranularityType:Statement Collection c = Model.getCollaborationsHelper().getAllPossibleBases(role); Iterator i = c.iterator(); while (i.hasNext()) { Object candidate = i.next(); if (basestr.equals(Model.getFacade().getName(candidate))) { if (Model.getFacade().getBase(role) != candidate) { /* If the base is already set to this assoc, * then do not set it again. * This check is needed, otherwise the setbase() * below gives an exception.*/ Model.getCollaborationsHelper().setBase(role, candidate); } /* Only set the name if the base was found: */ if (rolestr != null) { Model.getCoreHelper().setName(role, rolestr.trim()); } return; } } //#endif String msg = "parsing.error.association-role.base-not-found"; throw new ParseException(Translator.localize(msg), 0); } /** * Generate the name of an association role of the form: * ["/" name] [":" name_of_the_base_association] * <p> * Remark: * So, if both names are empty, then nothing is shown! * See issue 2712. * * {@inheritDoc} * @deprecated */ @SuppressWarnings("deprecation") @Deprecated public String toString(Object modelElement, Map args) { return toString(modelElement); } private String toString(final Object modelElement) { //get the associationRole name String name = Model.getFacade().getName(modelElement); if (name == null) { name = ""; } if (name.length() > 0) { name = "/" + name; } //get the base association name Object assoc = Model.getFacade().getBase(modelElement); if (assoc != null) { String baseName = Model.getFacade().getName(assoc); if (baseName != null && baseName.length() > 0) { name = name + ":" + baseName; } } return name; } @Override public String toString(final Object modelElement, final NotationSettings settings) { return toString(modelElement); } }
gpl-3.0
Keidan/CellHistory
src/org/kei/android/phone/cellhistory/towers/SignalStrengthReflect.java
2796
package org.kei.android.phone.cellhistory.towers; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** ******************************************************************************* * @file SignalStrengthReflect.java * @author Keidan * @date 04/12/2015 * @par Project CellHistory * * @par Copyright 2015 Keidan, all right reserved * * This software is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY. * * License summary : You can modify and redistribute the sources code and * binaries. You can send me the bug-fix * * Term of the license in in the file license.txt. * ******************************************************************************* */ public class SignalStrengthReflect { private static Class<?> mCls; private static Method mGetLevel; private static Method mGetAsuLevel; private static Method mGetDbm; private static Method mGetLteLevel; private static Method mGetGsmAsuLevel; private static Method mGetLteAsuLevel; static { try { mCls = Class.forName("android.telephony.SignalStrength"); mGetLevel = mCls.getMethod("getLevel"); mGetAsuLevel = mCls.getMethod("getAsuLevel"); mGetDbm = mCls.getMethod("getDbm"); mGetLteLevel = mCls.getMethod("getLteLevel"); mGetGsmAsuLevel = mCls.getMethod("getGsmAsuLevel"); mGetLteAsuLevel = mCls.getMethod("getLteAsuLevel"); } catch (final ClassNotFoundException e) { } catch (final NoSuchMethodException e) { } } private final Object mObj; public SignalStrengthReflect(final Object obj) { mObj = obj; } public int getLevel() throws IllegalAccessException, InvocationTargetException { return ((Integer) mGetLevel.invoke(mObj)).intValue(); } public int getAsuLevel() throws IllegalAccessException, InvocationTargetException { return ((Integer) mGetAsuLevel.invoke(mObj)).intValue(); } public int getDbm() throws IllegalAccessException, InvocationTargetException { return ((Integer) mGetDbm.invoke(mObj)).intValue(); } public int getLteLevel() throws IllegalAccessException, InvocationTargetException { return ((Integer) mGetLteLevel.invoke(mObj)).intValue(); } public int getGsmAsuLevel() throws IllegalAccessException, InvocationTargetException { return ((Integer) mGetGsmAsuLevel.invoke(mObj)).intValue(); } public int getLteAsuLevel() throws IllegalAccessException, InvocationTargetException { return ((Integer) mGetLteAsuLevel.invoke(mObj)).intValue(); } public double getAsuLimit() throws IllegalAccessException, InvocationTargetException { if (getLteLevel() == 0) { return 31.0; } else { return 70.0; } } }
gpl-3.0
petebrew/tellervo
src/main/java/org/tellervo/desktop/odk/fields/ODKTridasElementAuthenticity.java
650
package org.tellervo.desktop.odk.fields; import org.tellervo.desktop.tridasv2.doc.Documentation; import org.tridas.interfaces.ITridas; import org.tridas.schema.TridasElement; public class ODKTridasElementAuthenticity extends AbstractODKField { private static final long serialVersionUID = 1L; public ODKTridasElementAuthenticity() { super(ODKDataType.STRING, "tridas_element_authenticity", "Authenticity", Documentation.getDocumentation("element.authenticity"), null); } @Override public Boolean isFieldRequired() { return false; } @Override public Class<? extends ITridas> getTridasClass() { return TridasElement.class; } }
gpl-3.0
marks5/Brinquedoteca
app/src/main/java/br/com/marks/brinquedoteca/a/fragment/TelaContatoFragment.java
723
package br.com.marks.brinquedoteca.a.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import br.com.marks.brinquedoteca.R; /** * A simple {@link Fragment} subclass. */ public class TelaContatoFragment extends Fragment { public TelaContatoFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_tela_contato, container, false); } }
gpl-3.0
trickl/trickl-graph
src/main/java/com/trickl/graph/planar/xml/XmlDoublyConnectedEdgeListAdapter.java
4135
/* * This file is part of the Trickl Open Source Libraries. * * Trickl Open Source Libraries - http://open.trickl.com/ * * Copyright (C) 2011 Tim Gee. * * Trickl Open Source Libraries are free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Trickl Open Source Libraries are distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this project. If not, see <http://www.gnu.org/licenses/>. */ package com.trickl.graph.planar.xml; import com.trickl.graph.planar.DcelFace; import com.trickl.graph.planar.DcelHalfEdge; import com.trickl.graph.planar.DcelVertex; import com.trickl.graph.planar.DoublyConnectedEdgeList; import com.trickl.graph.planar.FaceFactory; import javax.xml.bind.annotation.adapters.XmlAdapter; import org.jgrapht.EdgeFactory; public class XmlDoublyConnectedEdgeListAdapter<V, E, F> extends XmlAdapter<XmlDoublyConnectedEdgeList<V, E, F>, DoublyConnectedEdgeList<V, E, F>> { /** * This function is called before the IDResolver finishes resolving. At this point, * only idrefs that reference ids earlier in the document are resolved. The other * idrefs will be resolved after this method. * @param xmlDcel * @return * @throws Exception */ @Override public DoublyConnectedEdgeList<V, E, F> unmarshal(XmlDoublyConnectedEdgeList<V, E, F> xmlDcel) throws Exception { EdgeFactory<V, E> edgeFactory = xmlDcel.getEdgeFactory(); FaceFactory<V, F> faceFactory = xmlDcel.getFaceFactory(); DoublyConnectedEdgeList<V, E, F> dcel = new DoublyConnectedEdgeList<>(edgeFactory, faceFactory); return unmarshal(xmlDcel, dcel); } /** * This function is called before the IDResolver finishes resolving. At this point, * only idrefs that reference ids earlier in the document are resolved. The other * idrefs will be resolved after this method. * @param xmlDcel * @param dcel * @return * @throws Exception */ public DoublyConnectedEdgeList<V, E, F> unmarshal(XmlDoublyConnectedEdgeList<V, E, F> xmlDcel, DoublyConnectedEdgeList<V, E, F> dcel) throws Exception { for (DcelVertex<V, E, F> vertex : xmlDcel.getDcelVertices()) { dcel.getVertexMap().put(vertex.getVertex(), vertex); } for (DcelHalfEdge<V, E, F> halfEdge : xmlDcel.getDcelHalfEdges()) { if (!dcel.getEdgeMap().containsKey(halfEdge.getEdge())) { dcel.getEdgeMap().put(halfEdge.getEdge(), halfEdge); } } dcel.getFaceMap().clear(); for (DcelFace<V, E, F> face : xmlDcel.getDcelFaces()) { dcel.getFaceMap().put(face.getFace(), face); } dcel.setBoundaryFace(xmlDcel.getDcelBoundaryFace().getFace()); return dcel; } @Override public XmlDoublyConnectedEdgeList<V, E, F> marshal(DoublyConnectedEdgeList<V, E, F> dcel) throws Exception { XmlDoublyConnectedEdgeList<V, E, F> xmlDcel = new XmlDoublyConnectedEdgeList<V, E, F>(); xmlDcel.getFaces().addAll(dcel.getFaceMap().keySet()); xmlDcel.getEdges().addAll(dcel.getEdgeMap().keySet()); xmlDcel.getVertices().addAll(dcel.getVertexMap().keySet()); xmlDcel.getDcelFaces().addAll(dcel.getFaceMap().values()); for (DcelHalfEdge<V, E, F> dcelHalfEdge : dcel.getEdgeMap().values()) { xmlDcel.getDcelHalfEdges().add(dcelHalfEdge); xmlDcel.getDcelHalfEdges().add(dcelHalfEdge.getTwin()); } xmlDcel.getDcelVertices().addAll(dcel.getVertexMap().values()); xmlDcel.setDcelBoundaryFace(dcel.getFaceMap().get(dcel.getBoundaryFace())); xmlDcel.setEdgeFactory(dcel.getEdgeFactory()); xmlDcel.setFaceFactory(dcel.getFaceFactory()); return xmlDcel; } }
gpl-3.0
X-rayLaser/EasyAdmin
com/github/easyadmin/gui/ClipboardReceiveListener.java
623
package com.github.easyadmin.gui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import com.github.easyadmin.request.ClipboardSendRequest; import com.github.easyadmin.util.FlavorHandler; public class ClipboardReceiveListener implements ActionListener { private String hostName; public ClipboardReceiveListener(String hostName) { this.hostName = hostName; } @Override public void actionPerformed(ActionEvent e) { ClipboardSendRequest request = ClipboardSendRequest.makeClipboardRequest(hostName); FlavorHandler handler = request.getFlavorHandler(); handler.setClipboard(); } }
gpl-3.0
spartan2015/kata
test/src/main/java/test/A.java
196
package test; import static org.junit.Assert.*; import java.text.DateFormat; import java.util.Date; import org.junit.Test; public class A{ void say(){ System.out.println("A"); } }
gpl-3.0
fredorange/JLInX
src/jlinx-phaSample/java/com/orange/jlinx/sample/pha/package-info.java
891
/** * Copyright (c) 2010 France Telecom / Orange Labs * * This file is part of JLInX, Java Lib for Indivo X. * * JLInX 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, version 3 (LGPLv3). * * JLInX is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JLInX. If not, see <http://www.gnu.org/licenses/>. * */ /** * This package contains a demo PHA based on JLInX. * * @author dev-indivo@brialon.com */ package com.orange.jlinx.sample.pha;
gpl-3.0
onironaut/GeNN
GeNN/src/basic/Layer.java
5100
/* Copyright (c) 2016 David Wagg This program is released under the "GNU GPL v3" License Please see the file License in this distribution for license terms */ package basic; import java.util.ArrayList; import java.util.Random; import org.la4j.Vector; import org.la4j.matrix.sparse.CRSMatrix; import org.la4j.vector.dense.BasicVector; public class Layer { protected ArrayList<Neuron> neurons; protected CRSMatrix input; protected int incomingSignals; protected int numOfNeurons; //protected BasicVector values; protected ArrayList<Double> weights; public Layer(int numOfNeurons, int incomingSignals) { this.neurons = new ArrayList<>(); this.weights = new ArrayList<>(); this.numOfNeurons = numOfNeurons; this.incomingSignals = incomingSignals; } public void initLayer(CRSMatrix input) { setInput(input); generateWeights(); buildNeurons(); } public void setNeuronInputs() { for (Neuron neuron: neurons) { neuron.setInSignal(input); } } public void generateWeights() { Random rand = new Random(); for (int i = 0; i < numOfNeurons * incomingSignals;i++) { weights.add(rand.nextDouble()/100); } System.out.print(""); } public void buildNeurons() { for (int i =0; i < numOfNeurons; i++) { ArrayList<Double> neuronWeights = new ArrayList<Double>(); for (int j = 0; j < incomingSignals; j++) { neuronWeights.add(weights.get((incomingSignals * i + j))); } neurons.add(new Neuron(neuronWeights,this)); } } //For each one of the neurons calculate a value vector then make a matrix out of all of the value Vectors as the output signal public CRSMatrix prepOutSignal() { ArrayList<BasicVector> listOfVectors = new ArrayList<BasicVector>(); setNeuronInputs(); for (int i = 0; i < numOfNeurons; i++) { listOfVectors.add(neurons.get(i).fire(input)); } CRSMatrix matrix = CRSMatrix.zero(listOfVectors.get(0).length(),listOfVectors.size()); for (int i = 0; i < listOfVectors.size(); i++) { matrix.setColumn(i, listOfVectors.get(i)); } return matrix; } public void setInput(CRSMatrix input) { this.input = input; this.incomingSignals = input.columns(); } public int getNumOfNeurons() { return numOfNeurons; } public CRSMatrix getInput() { return input; } public boolean isOutputLayer() { return false; } public boolean isInputLayer() { return false; } public ArrayList<Double> getWeights() { return weights; } public ArrayList<Neuron> getNeurons() { return neurons; } public ArrayList<BasicVector> getErrosList(ArrayList<BasicVector> targetOutput) { if (!isOutputLayer()) { return null; } CRSMatrix output = prepOutSignal(); int length = numOfNeurons; ArrayList<BasicVector> errorsList = new ArrayList<>(); for(int j = 0; j < length; j++) { BasicVector neuronErrors = new BasicVector(targetOutput.size()); for (int i = 0; i < targetOutput.size();i++) { double expected = targetOutput.get(i).get(j); neuronErrors.set(i, expected - output.get(i,j)); } errorsList.add(neuronErrors); } return errorsList; } public BasicVector getAverageError(ArrayList<BasicVector> targetOutput) { ArrayList<BasicVector> errorsList = getErrosList(targetOutput); BasicVector meanErrors = new BasicVector(errorsList.size()); int length = errorsList.get(0).length(); for(int i = 0; i < errorsList.size();i++) { double error = errorsList.get(i).sum()/length; meanErrors.set(i, error); } return meanErrors; } public ArrayList<BasicVector> getdOutdNetList() { ArrayList<BasicVector> dOutdNetList = new ArrayList<>(); for (int i = 0; i < numOfNeurons; i++) { dOutdNetList.add(neurons.get(i).getdOutdNet()); } return dOutdNetList; } public BasicVector calculateDelta(Layer prev, BasicVector targetValueVector) { BasicVector deltas = new BasicVector(numOfNeurons); if (isOutputLayer()) { for (int i = 0; i < numOfNeurons; i++) { deltas.set(i, neurons.get(i).nodeDelta(targetValueVector.get(i))); } } else if(!isInputLayer()) { } return deltas; } private void pullNodeWeights() { for(int i = 0; i < numOfNeurons; i++) { BasicVector neuronWeights = neurons.get(i).getInWeights(); for (int j = 0; j < neuronWeights.length();j++ ) { weights.set(i * numOfNeurons + j, neuronWeights.get(j)); } } } public void updateWeights(Layer prev, double learningRate, ArrayList<BasicVector> deltas) { for (int k = 0; k < deltas.size(); k++) { for (int i = 0; i < numOfNeurons; i++) { BasicVector updateBy = new BasicVector(prev.getNumOfNeurons()); for(int j = 0; j < prev.getNumOfNeurons(); j++) { updateBy.set(j,learningRate * deltas.get(k).get(i) * input.get(k, j)); } neurons.get(i).updateWeights(updateBy); } } pullNodeWeights(); } }
gpl-3.0
ersh112356/ConversationEngine
src/engine/detector/TopicDetector.java
5414
/* * 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 engine.detector; import engine.model.state.Keyword; import engine.utils.Response; import engine.functions.Function; import engine.functions.util.FunctionsStorage; import java.util.List; import java.util.Map; import logging.utils.Verbose; /** * * @author Eran */ public class TopicDetector implements Verbose{ /** Holds the Keyword objects that belong to the given ConversationState. */ protected List<Keyword> stateKeywords; /** Holds the general purpose Keyword objects. */ protected List<Keyword> generalKeywords; /** Holds the storage on the Function Objects. */ protected FunctionsStorage functions; /** Store all regular expression matches. */ protected Map<String,String> dictionary; /** * The constructor. * * @param dictionary- holds all regular expression matches. */ public TopicDetector(Map<String,String> dictionary){ this.dictionary = dictionary; } /** * introduces a new Function storage here. * * @param functions- a storage of read to be used of Function Objects. */ public void setFunctionStorage(FunctionsStorage functions){ this.functions = functions; } /** * Introduces new Keyword Objects that belong to a given ConversationState. * * @param keywords- Keyword Objects that belong to a given ConversationState. */ public void setConversationFunctions(List<Keyword> keywords){ this.stateKeywords = keywords; } /** * Introduces new Keyword Objects that should be invoked regardless a given ConversationState. * * @param keywords- Keyword Objects that belong to a given ConversationState. */ public void setLargeScaleKeyword(List<Keyword> keywords){ this.generalKeywords = keywords; } /** * Try to match a proper response to the given text. * * @param text- the text to analyze. * * @return a proper response, on null if no such was found. */ public Response getResponse(String text){ int bestMatch = -1; Keyword match = null; String responseText = null; // 1. look at the ones that belong to ConversationState. int len = stateKeywords.size(); for(int i=0;i<len;i++) { Keyword keyword = stateKeywords.get(i); Function function = fetchFunctionObject(text,keyword); if(function==null) { // A bad function, just move on. continue; } int score = function.getScore(); if(score>-1 && score>bestMatch) { // If this match is better than best match, replace it. match = keyword; bestMatch = score; responseText = function.getResponse(); verbose("found a match for text("+text+"): "+match); } } verbose("message: "+text+", state functions- match:"+match); if(generalKeywords!=null) { // 2. look at the ones that belong to the general Keyword Objects. len = generalKeywords.size(); for(int i=0;i<len;i++) { Keyword keyword = generalKeywords.get(i); Function function = fetchFunctionObject(text,keyword); if(function==null) { continue; } int score = function.getScore(); if(score>-1 && score>bestMatch) { // If this match is better than best match, replace it. match = keyword; bestMatch = score; responseText = function.getResponse(); } } } verbose("message: "+text+", default functions- match:"+match); if(match==null) { return null; } Response response = new Response(bestMatch,match.getNext(),match.get("nextHappyID"),match.get("nextUnhappyID"),responseText); return response; } /** * Return a Function Object ready to be used. * * @param text- the text to match. * @param keyword- the keyword to use. * * @return a Function Object ready to be used. */ protected Function fetchFunctionObject(String text, Keyword keyword){ String functionname = keyword.getClassOfFunction(); Function function = functions.getOrCreate(functionname); if(function==null) { return null; } Map<String,String> parameters = keyword.getParameters(); function.setParameters(parameters); function.setDictionary(dictionary); function.setText(text); return function; } }
gpl-3.0
noodlewiz/xjavab
xjavab-ext/src/main/java/com/noodlewiz/xjavab/ext/dri2/internal/ReplyDispatcher.java
2264
// // DO NOT MODIFY!!! This file was machine generated. DO NOT MODIFY!!! // // Copyright (c) 2014 Vincent W. Chen. // // This file is part of XJavaB. // // XJavaB 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. // // XJavaB 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 XJavaB. If not, see <http://www.gnu.org/licenses/>. // package com.noodlewiz.xjavab.ext.dri2.internal; import java.nio.ByteBuffer; import com.noodlewiz.xjavab.core.XReply; public class ReplyDispatcher implements com.noodlewiz.xjavab.core.internal.ReplyDispatcher { @Override public XReply dispatch(final ByteBuffer __xjb_buf, final short __xjb_opcode) { switch (__xjb_opcode) { case 0 : return ReplyUnpacker.unpackQueryVersion(__xjb_buf); case 1 : return ReplyUnpacker.unpackConnect(__xjb_buf); case 2 : return ReplyUnpacker.unpackAuthenticate(__xjb_buf); case 5 : return ReplyUnpacker.unpackGetBuffers(__xjb_buf); case 6 : return ReplyUnpacker.unpackCopyRegion(__xjb_buf); case 7 : return ReplyUnpacker.unpackGetBuffersWithFormat(__xjb_buf); case 8 : return ReplyUnpacker.unpackSwapBuffers(__xjb_buf); case 9 : return ReplyUnpacker.unpackGetMSC(__xjb_buf); case 10 : return ReplyUnpacker.unpackWaitMSC(__xjb_buf); case 11 : return ReplyUnpacker.unpackWaitSBC(__xjb_buf); case 13 : return ReplyUnpacker.unpackGetParam(__xjb_buf); default: throw new IllegalArgumentException(("Invalid reply opcode: "+ __xjb_opcode)); } } }
gpl-3.0
dolpphins/EasyWord
EasyWord/src/com/mao/widget/ColorPickerView.java
5381
package com.mao.widget; import android.R.integer; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.SweepGradient; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * 颜色选择View * * @author mao * */ public class ColorPickerView extends View { private Paint mPaint; private Paint mCenterPaint; private int innerRadius;//环形内半径 private int outerRadius;//环形外半径 private int[] mColors; private int mCurrentColor;//当前选择的颜色 //监听器 private OnColorPickerListener mOnColorPickerListener; public ColorPickerView(Context context) { this(context, null); } public ColorPickerView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { mPaint = new Paint(); mColors = new int[] {0xFF000000, 0xFFFFFFFF, 0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000}; SweepGradient sweepGradient = new SweepGradient(0, 0, mColors, null); mPaint.setShader(sweepGradient); mPaint.setStyle(Paint.Style.STROKE); mPaint.setAntiAlias(true); mCenterPaint = new Paint(); mCurrentColor = Color.TRANSPARENT; mCenterPaint.setColor(mCurrentColor); mCenterPaint.setAntiAlias(true); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int measuredWidth = MeasureSpec.getSize(widthMeasureSpec); int measuredHeight = measuredWidth; setMeasuredDimension(measuredWidth, measuredHeight); } @Override protected void onDraw(Canvas canvas) { //平移画布 int translateX = getWidth() / 2; int translateY = translateX; canvas.translate(translateX, translateY); //设置线宽 mPaint.setStrokeWidth(getWidth() / 5); //画圆环 int radius = getWidth() * 3 / 10; canvas.drawCircle(0, 0, radius, mPaint);//这里半径的终点为线宽的中点 //画中心圆 canvas.drawCircle(0, 0, getWidth() / 8, mCenterPaint); //保存圆环内半径和外半径信息 innerRadius = (int)(radius - mPaint.getStrokeWidth() / 2); outerRadius = (int)(innerRadius + mPaint.getStrokeWidth()); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_UP: updateColor(event); break; } return true; } private void updateColor(MotionEvent event) { float x = event.getX(); float y = event.getY(); //转换坐标,以View中心为原点 x -= getWidth() / 2; y -= getHeight() / 2; //如果是点击环形 float distance2 = x * x + y * y; if(distance2 > innerRadius * innerRadius && distance2 < outerRadius * outerRadius) { int preColor = mCurrentColor; mCurrentColor = calculateColor(x, y); mCenterPaint.setColor(mCurrentColor); invalidate(); if(mOnColorPickerListener != null) { mOnColorPickerListener.onColorChanged(preColor, mCurrentColor); } } } private int calculateColor(float x, float y) { //计算角度,这里以x正方向为角的一条边,逆时针旋转 double radian = Math.atan2(y, x); if(radian < 0) { radian += 2 * Math.PI; } double angle = Math.toDegrees(radian); int index = Math.round((float)angle) / 45; int remainder = Math.round((float)angle) % 45; int startColor = mColors[index]; int endColor = mColors[index + 1]; float delta = remainder / 45.0f; int alpha = calculateLinearGradient(Color.alpha(startColor), Color.alpha(endColor), delta); int red = calculateLinearGradient(Color.red(startColor), Color.red(endColor), delta); int green = calculateLinearGradient(Color.green(startColor), Color.green(endColor), delta); int blue = calculateLinearGradient(Color.blue(startColor), Color.blue(endColor), delta); return Color.argb(alpha, red, green, blue); } //delta范围0..1 private int calculateLinearGradient(int start, int end, float delta) { return start + Math.round((end - start) * delta); } /** * 获取当前选择的颜色,注意如果没有选择返回{@link Color#TRANSPARENT} * * @return 返回当前选择的颜色 */ public int getColor() { return mCurrentColor; } /** * 设置颜色 * * @param color 要设置的颜色 */ public void setColor(int color) { int preColor = mCurrentColor; mCurrentColor = color; // mCenterPaint.setColor(mCurrentColor); invalidate(); if(mOnColorPickerListener != null) { mOnColorPickerListener.onColorChanged(preColor, mCurrentColor); } } /** * 设置颜色监听器 * * @param listener 要设置的监听器 */ public void setOnColorPickerListener(OnColorPickerListener listener) { mOnColorPickerListener = listener; } /** * 获取颜色监听器 * * @return 返回颜色监听器 */ public OnColorPickerListener getOnColorPickerListener() { return mOnColorPickerListener; } /** * 监听接口 * */ public interface OnColorPickerListener { /** * 当颜色发生改变时回调该方法 * * @param oldColor 改变之前的颜色值 * @param newColor 改变之后的颜色值 */ void onColorChanged(int preColor, int newColor); } }
gpl-3.0
ntenhoeve/Introspect-Apps
SoftwareDocumentationGenerator/src/main/java/nth/reflect/app/swdocgen/dom/page/web/FancyWebPage.java
6217
package nth.reflect.app.swdocgen.dom.page.web; import java.util.List; import org.jsoup.nodes.DataNode; import org.jsoup.nodes.Document; import org.jsoup.nodes.DocumentType; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.select.Elements; import nth.reflect.app.swdocgen.dom.documentation.GitHubWebInfo; import nth.reflect.app.swdocgen.dom.html.ElementUtil; import nth.reflect.fw.generic.util.StringUtil; public class FancyWebPage extends WebPage { public FancyWebPage(GitHubWebInfo info, Document javaDoc) { super(info.getGithubWebProjectLocation(), info.getClassName(), javaDoc); } @Override public Document createContents() { String title = getTitle(); Document doc = createDocument(title); createHead(doc); Element body = doc.body(); Element divPage = body.appendElement("div").attr("id", "page"); createTitleBar(title, divPage); createContents(getJavaDoc(), divPage); createMenu(getJavaDoc(), divPage); return doc; } private Document createDocument(String title) { Document doc = new Document(""); doc.appendChild(new DocumentType("html", "", "", "")); Element html = doc.appendElement("html"); html.appendElement("head"); html.appendElement("body"); doc.title(title); return doc; } private void createTitleBar(String title, Element divPage) { Element divHeader = divPage.appendElement("div").attr("class", "header Fixed"); divHeader.appendElement("a").attr("href", "#menu"); divHeader.append(title); } private void createContents(Document javaDoc, Element divPage) { Element divContent = divPage.appendElement("div").attr("class", "content").attr("id", "content"); Elements h1Elements = javaDoc.select("h1"); for (Element h1 : h1Elements) { List<Node> chapterNodes = ElementUtil.findChapterNodes(h1); ElementUtil.addAllNodes(divContent, chapterNodes); } } private void createHead(Document doc) { Element head = doc.head(); head.appendElement("meta").attr("charset", "utf-8"); head.appendElement("meta").attr("name", "viewport").attr("content", "width=device-width initial-scale=1.0 maximum-scale=1.0 user-scalable=yes"); head.appendElement("link").attr("type", "text/css").attr("rel", "stylesheet").attr("href", "css/demo.css"); head.appendElement("link").attr("type", "text/css").attr("rel", "stylesheet").attr("href", "dist/core/css/jquery.mmenu.all.css"); head.appendElement("link").attr("type", "text/css").attr("rel", "stylesheet").attr("href", "dist/addons/css/jquery.mmenu.dragopen.css"); head.appendElement("script").attr("type", "text/javascript").attr("src", "http://hammerjs.github.io/dist/hammer.min.js"); head.appendElement("script").attr("type", "text/javascript").attr("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"); head.appendElement("script").attr("type", "text/javascript").attr("src", "dist/core/js/jquery.mmenu.min.js"); head.appendElement("script").attr("type", "text/javascript").attr("src", "dist/addons/js/jquery.mmenu.dragopen.min.js"); head.appendElement("script").attr("type", "text/javascript").attr("src", "dist/addons/js/jquery.mmenu.fixedelements.min.js"); head.appendElement("script").attr("type", "text/javascript") .appendChild(new DataNode(getJavaScriptToEnsureTitleVisibilityForBookmarks(), "")); head.appendElement("script").attr("type", "text/javascript") .appendChild(new DataNode(getJavaScriptToHandleMenu(), "")); } private void createMenu(Document javaDoc, Element divPage) { Element nav = divPage.appendElement("nav").attr("id", "menu"); Element ulh1 = nav.appendElement("ul"); Element ulh2 = null; Elements chaptersAndParagraph = javaDoc.select("h1,h2"); for (Element chapterOrParagraph : chaptersAndParagraph) { if ("h1".equals(chapterOrParagraph.tagName())) { Element lih1 = ulh1.appendElement("li").appendElement("a").attr("href", "#" + chapterOrParagraph.id()) .html(chapterOrParagraph.html()); ulh2 = lih1.appendElement("ul"); } if ("h2".equals(chapterOrParagraph.tagName())) { ulh2.appendElement("li").appendElement("a").attr("href", "#" + chapterOrParagraph.id()) .html(chapterOrParagraph.html()); } } } private String getJavaScriptToEnsureTitleVisibilityForBookmarks() { StringBuilder js = new StringBuilder(); // see: https://github.com/twbs/bootstrap/issues/1768 js.append("var shiftWindow = function() { scrollBy(0, -50) };"); js.append("if (location.hash) shiftWindow();"); js.append("window.addEventListener('hashchange', shiftWindow);"); return js.toString(); } private String getJavaScriptToHandleMenu() { StringBuilder js = new StringBuilder(); js.append("$(function() {"); js.append(" var $menu = $('nav#menu'),"); js.append(" $html = $('html, body');"); js.append(""); js.append(" $menu.mmenu({"); js.append(" dragOpen: true"); js.append(" });"); js.append(""); js.append(" var $anchor = false;"); js.append(" $menu.find( 'li > a' ).on("); js.append(" 'click',"); js.append(" function( e )"); js.append(" {"); js.append(" $anchor = $(this);"); js.append(" }"); js.append(" );"); js.append(""); js.append(" var api = $menu.data( 'mmenu' );"); js.append(" api.bind( 'closed',"); js.append(" function()"); js.append(" {"); js.append(" if ( $anchor )"); js.append(" {"); js.append(" var href = $anchor.attr( 'href' );"); js.append(" $anchor = false;"); js.append(""); js.append(" if ( href.slice( 0, 1 ) == '#' )"); js.append(" {"); js.append(" $html.animate({"); js.append(" scrollTop: $( href ).offset().top -50"); js.append(" }); "); js.append(" }"); js.append(" }"); js.append(" }"); js.append(" );"); js.append("});"); return js.toString(); } @Override protected String createFileName(String title) { StringBuilder fileName = new StringBuilder(); fileName.append(StringUtil.convertToCamelCase(title, true)); fileName.append(".html"); return fileName.toString(); } }
gpl-3.0
tberg12/ocular
src/test/java/edu/berkeley/cs/nlp/ocular/data/textreader/CharIndexerTests.java
1994
package edu.berkeley.cs.nlp.ocular.data.textreader; import static edu.berkeley.cs.nlp.ocular.data.textreader.Charset.TILDE_COMBINING; import static edu.berkeley.cs.nlp.ocular.data.textreader.Charset.TILDE_ESCAPE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import tberg.murphy.indexer.Indexer; /** * @author Dan Garrette (dhgarrette@gmail.com) */ public class CharIndexerTests { @Test public void test() { Indexer<String> i = new CharIndexer(); String ae = TILDE_ESCAPE + "a"; String ac = "a" + TILDE_COMBINING; String ee = TILDE_ESCAPE + "e"; String ec = "e" + TILDE_COMBINING; String ne = TILDE_ESCAPE + "n"; String nc = "n" + TILDE_COMBINING; String np = "ñ"; i.index(new String[] { "a", "b", ec }); assertTrue(i.contains("a")); assertTrue(i.contains("b")); assertTrue(i.contains(ec)); assertTrue(i.contains(ee)); assertEquals(0, i.getIndex("a")); assertEquals("a", i.getObject(0)); assertEquals(1, i.getIndex("b")); assertEquals("b", i.getObject(1)); assertEquals(2, i.getIndex(ec)); assertEquals(ec, i.getObject(2)); assertEquals(2, i.getIndex(ec)); assertEquals(3, i.size()); assertFalse(i.contains(ae)); assertFalse(i.contains(ac)); assertEquals(3, i.getIndex(ae)); assertTrue(i.contains(ae)); assertTrue(i.contains(ac)); assertEquals(3, i.getIndex(ac)); assertTrue(i.contains(ae)); assertTrue(i.contains(ac)); assertEquals(4, i.size()); assertFalse(i.contains(ne)); assertFalse(i.contains(nc)); assertFalse(i.contains(np)); assertEquals(4, i.getIndex(np)); assertEquals(nc, i.getObject(4)); assertTrue(i.contains(ne)); assertTrue(i.contains(nc)); assertTrue(i.contains(np)); assertEquals(4, i.getIndex(ne)); assertEquals(4, i.getIndex(nc)); assertEquals(nc, i.getObject(4)); assertEquals(5, i.size()); assertFalse(i.locked()); i.lock(); assertTrue(i.locked()); } }
gpl-3.0
CreativeMD/VoiceChat
src/main/java/com/creativemd/voicechat/client/PlayThread.java
376
package com.creativemd.voicechat.client; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class PlayThread extends Thread{ public AudioConsumer consumer; public PlayThread(AudioConsumer consumer) { this.consumer = consumer; } @Override public void run() { consumer.run(); } }
gpl-3.0
beynet/jnote
src/main/java/org/beynet/jnote/gui/dialogs/Dialog.java
1381
package org.beynet.jnote.gui.dialogs; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import org.beynet.jnote.gui.Styles; /** * Created with IntelliJ IDEA. * User: beynet * Date: 12/10/13 * Time: 15:49 * To change this template use File | Settings | File Templates. */ public abstract class Dialog extends Stage { public Dialog(Stage parent,Double with,Double height) { init(parent,with,height); } protected void init(Stage parent,Double with,Double height) { this.parent = parent; root = new Group(); if (with!=null && height!=null) { scene = new Scene(root, with.doubleValue(), height.doubleValue()); }else { scene = new Scene(root); } scene.getStylesheets().add(getClass().getResource("/default.css").toExternalForm()); root.getStyleClass().add(Styles.CHILD_WINDOW); setScene(scene); setX(parent.getX() + parent.getWidth() /2); setY(parent.getY() + parent.getHeight()/2); initOwner(parent); } protected final Scene getCurrentScene() { return scene; } protected final Group getRootGroup() { return root; } protected final Stage getParentStage() { return parent; } private Group root; private Stage parent ; private Scene scene ; }
gpl-3.0
danielhuson/megan-ce
src/megan/viewer/gui/ViewerJTable.java
13815
/* * ViewerJTable.java Copyright (C) 2021. Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package megan.viewer.gui; import jloda.graph.Edge; import jloda.graph.Node; import jloda.graph.NodeData; import jloda.swing.util.PopupMenu; import jloda.swing.window.IPopupMenuModifier; import jloda.util.Basic; import jloda.util.Pair; import jloda.util.ProgramProperties; import megan.viewer.ClassificationViewer; import megan.viewer.GUIConfiguration; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; /** * jtable representation of the data at leaves of tree * Daniel Huson, 10.2010 */ public class ViewerJTable extends JTable { private final ClassificationViewer classificationViewer; private final DefaultTableModel model; private final MyCellRender cellRenderer; private final Map<Integer, Integer> id2row = new HashMap<>(); private final JPopupMenu popupMenu; private IPopupMenuModifier popupMenuModifier; private boolean inSelection = false; // use this to prevent bouncing when selecting from viewer /** * constructor * * @param classificationViewer */ public ViewerJTable(ClassificationViewer classificationViewer) { this.classificationViewer = classificationViewer; model = new DefaultTableModel() { public Class getColumnClass(int col) { if (col >= 0 && col < getColumnCount()) { if (col == 0) return Pair.class; else return Integer.class; } else return Object.class; } }; setModel(model); addMouseListener(new MyMouseListener()); getSelectionModel().addListSelectionListener(new MyListSelectionListener()); cellRenderer = new MyCellRender(); getTableHeader().setReorderingAllowed(true); setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); setShowGrid(false); setRowSorter(new TableRowSorter<TableModel>(model)); popupMenu = new PopupMenu(this, GUIConfiguration.getJTablePopupConfiguration(), classificationViewer.getCommandManager()); // ToolTipManager.sharedInstance().unregisterComponent(this); // rescan(); } /** * rescan the heatmap */ public void update() { clear(); // setup column names final String[] columnNames = new String[classificationViewer.getNumberOfDatasets() + 1]; columnNames[0] = classificationViewer.getClassName(); for (int i = 1; i <= classificationViewer.getNumberOfDatasets(); i++) { columnNames[i] = "Reads [" + i + "]"; } model.setColumnIdentifiers(columnNames); // setup cellRenderer: for (int i = 0; i < getColumnCount(); i++) { TableColumn col = getColumnModel().getColumn(i); col.setCellRenderer(cellRenderer); } if (classificationViewer.getTree().getRoot() != null) { buildHeatMapRec(classificationViewer.getTree().getRoot(), new HashSet<>()); } float[] maxCounts = new float[classificationViewer.getNumberOfDatasets()]; for (Node v = classificationViewer.getTree().getFirstNode(); v != null; v = v.getNext()) { if (v.getOutDegree() == 0) { NodeData data = classificationViewer.getNodeData(v); if (data != null) { float[] summarized = data.getSummarized(); int top = Math.min(summarized.length, maxCounts.length); for (int i = 0; i < top; i++) { maxCounts[i] = Math.max(maxCounts[i], summarized[i]); } } } } cellRenderer.setMaxCounts(maxCounts); } /** * recursively build the table * * @param v * @return total count so far */ private void buildHeatMapRec(Node v, HashSet<Integer> seen) { if (v.getOutDegree() == 0) { NodeData data = classificationViewer.getNodeData(v); if (data != null) { float[] summarized = data.getSummarized(); Comparable[] rowData = new Comparable[summarized.length + 1]; int id = (Integer) v.getInfo(); if (!seen.contains(id)) { seen.add(id); String name = classificationViewer.getClassification().getName2IdMap().get(id); rowData[0] = new Pair<>(name, id) { public String toString() { return getFirst(); } }; for (int i = 0; i < summarized.length; i++) { rowData[i + 1] = summarized[i]; } id2row.put(id, model.getRowCount()); model.addRow(rowData); } } } else { for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) { Node w = e.getTarget(); buildHeatMapRec(w, seen); } } } /** * erase the table */ private void clear() { id2row.clear(); clearSelection(); while (model.getRowCount() > 0) model.removeRow(model.getRowCount() - 1); model.getDataVector().clear(); } /** * don't allow editing of anything * * @param row * @param column * @return false */ public boolean isCellEditable(int row, int column) { return false; } public boolean isInSelection() { return inSelection; } /** * select nodes by their ids * * @param ids */ public void setSelected(Collection<Integer> ids, boolean select) { if (!inSelection) { inSelection = true; int first = -1; for (Integer id : ids) { Integer row = id2row.get(id); if (row != null) { row = convertRowIndexToView(row); if (first == -1) first = row; if (select) addRowSelectionInterval(row, row); else removeRowSelectionInterval(row, row); } } if (first != -1) { final int firstf = first; final Runnable runnable = () -> scrollRectToVisible(new Rectangle(getCellRect(firstf, 0, true))); if (SwingUtilities.isEventDispatchThread()) runnable.run(); else SwingUtilities.invokeLater(runnable); } } inSelection = false; } class MyMouseListener extends MouseAdapter { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { try { classificationViewer.getDir().executeImmediately("zoom what=full;zoom what=selected;", classificationViewer.getCommandManager()); } catch (Exception e1) { Basic.caught(e1); } } } public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { showPopupMenu(e); } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { showPopupMenu(e); } } } private void showPopupMenu(MouseEvent e) { if (popupMenuModifier != null) { popupMenuModifier.apply(popupMenu, classificationViewer.getCommandManager()); popupMenuModifier = null; } popupMenu.show(ViewerJTable.this, e.getX(), e.getY()); } /** * selection listener */ class MyListSelectionListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { if (!inSelection) { inSelection = true; if (!classificationViewer.isLocked()) { if (!e.getValueIsAdjusting()) { boolean originallyEmptySelectionInViewer = classificationViewer.getSelectedNodes().isEmpty(); classificationViewer.selectAllNodes(false); classificationViewer.selectAllEdges(false); // selection event if (getSelectedRowCount() > 0) { int[] selectedRowIndices = getSelectedRows(); // first deselect all nodes and edges for (int row : selectedRowIndices) { row = convertRowIndexToModel(row); int col = convertColumnIndexToModel(0); if (row > model.getDataVector().size() - 1) { return; } if (getModel().getValueAt(row, 0) != null) { int id = ((Pair<String, Integer>) getModel().getValueAt(row, col)).getSecond(); if (classificationViewer.getNodes(id) != null) { for (Node v : classificationViewer.getNodes(id)) { classificationViewer.setSelected(v, true); classificationViewer.repaint(); } } } } if (originallyEmptySelectionInViewer != classificationViewer.getSelectedNodes().isEmpty()) classificationViewer.getCommandManager().updateEnableState(); } } } inSelection = false; } } } public IPopupMenuModifier getPopupMenuModifier() { return popupMenuModifier; } public void setPopupMenuModifier(IPopupMenuModifier popupMenuModifier) { this.popupMenuModifier = popupMenuModifier; } } class MyCellRender implements TableCellRenderer { private GreenGradient[] greenGradients; public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { // in case of reorder columns: col = table.convertColumnIndexToModel(col); if (col == 0) { Pair<String, Integer> pair = (Pair<String, Integer>) value; if (pair == null) return new JLabel(""); JLabel label = new JLabel(pair.getFirst()); if (isSelected) label.setBorder(BorderFactory.createLineBorder(ProgramProperties.SELECTION_COLOR_DARKER)); else label.setBorder(null); label.setPreferredSize(new Dimension(label.getPreferredSize().width + 100, label.getPreferredSize().height)); label.setMinimumSize(label.getPreferredSize()); return label; } else { int number; try { number = Math.round(Float.parseFloat(String.valueOf(value))); } catch (NumberFormatException nfe) { return new JLabel("?"); } JLabel label = new JLabel(String.valueOf(number)); label.setFont(new Font("SansSerif", Font.PLAIN, 11)); try { if (greenGradients != null && greenGradients[col - 1] != null) { Color color = greenGradients[col - 1].getLogColor(number); label.setBackground(color); if (color.getRed() + color.getGreen() + color.getBlue() < 250) label.setForeground(Color.WHITE); } } catch (IllegalArgumentException iae) { // -1 ? } label.setOpaque(true); if (isSelected) label.setBorder(BorderFactory.createLineBorder(ProgramProperties.SELECTION_COLOR)); else if (hasFocus) label.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY)); else label.setBorder(null); label.setToolTipText(label.getText()); return label; } } public void setMaxCounts(float[] maxCounts) { greenGradients = new GreenGradient[maxCounts.length]; for (int i = 0; i < maxCounts.length; i++) greenGradients[i] = new GreenGradient(Math.round(maxCounts[i])); } }
gpl-3.0
isnuryusuf/ingress-indonesia-dev
apk/classes-ekstartk/org/codehaus/jackson/map/ser/BeanSerializerFactory$ConfigImpl.java
2927
package org.codehaus.jackson.map.ser; import org.codehaus.jackson.map.SerializerFactory.Config; import org.codehaus.jackson.map.Serializers; import org.codehaus.jackson.map.util.ArrayBuilders; public class BeanSerializerFactory$ConfigImpl extends SerializerFactory.Config { protected static final BeanSerializerModifier[] NO_MODIFIERS = new BeanSerializerModifier[0]; protected static final Serializers[] NO_SERIALIZERS = new Serializers[0]; protected final Serializers[] _additionalKeySerializers; protected final Serializers[] _additionalSerializers; protected final BeanSerializerModifier[] _modifiers; public BeanSerializerFactory$ConfigImpl() { this(null, null, null); } protected BeanSerializerFactory$ConfigImpl(Serializers[] paramArrayOfSerializers1, Serializers[] paramArrayOfSerializers2, BeanSerializerModifier[] paramArrayOfBeanSerializerModifier) { if (paramArrayOfSerializers1 == null) paramArrayOfSerializers1 = NO_SERIALIZERS; this._additionalSerializers = paramArrayOfSerializers1; if (paramArrayOfSerializers2 == null) paramArrayOfSerializers2 = NO_SERIALIZERS; this._additionalKeySerializers = paramArrayOfSerializers2; if (paramArrayOfBeanSerializerModifier == null) paramArrayOfBeanSerializerModifier = NO_MODIFIERS; this._modifiers = paramArrayOfBeanSerializerModifier; } public boolean hasKeySerializers() { return this._additionalKeySerializers.length > 0; } public boolean hasSerializerModifiers() { return this._modifiers.length > 0; } public Iterable<Serializers> keySerializers() { return ArrayBuilders.arrayAsIterable(this._additionalKeySerializers); } public Iterable<BeanSerializerModifier> serializerModifiers() { return ArrayBuilders.arrayAsIterable(this._modifiers); } public Iterable<Serializers> serializers() { return ArrayBuilders.arrayAsIterable(this._additionalSerializers); } public SerializerFactory.Config withAdditionalKeySerializers(Serializers paramSerializers) { if (paramSerializers == null) throw new IllegalArgumentException("Can not pass null Serializers"); Serializers[] arrayOfSerializers = (Serializers[])ArrayBuilders.insertInListNoDup(this._additionalKeySerializers, paramSerializers); return new ConfigImpl(this._additionalSerializers, arrayOfSerializers, this._modifiers); } public SerializerFactory.Config withAdditionalSerializers(Serializers paramSerializers) { if (paramSerializers == null) throw new IllegalArgumentException("Can not pass null Serializers"); return new ConfigImpl((Serializers[])ArrayBuilders.insertInListNoDup(this._additionalSerializers, paramSerializers), this._additionalKeySerializers, this._modifiers); } } /* Location: classes_dex2jar.jar * Qualified Name: org.codehaus.jackson.map.ser.BeanSerializerFactory.ConfigImpl * JD-Core Version: 0.6.2 */
gpl-3.0
micromacer/Player-by-TweekProject
src/com/andrew/apollo/widgets/SquareImageView.java
1573
/* * Copyright (C) 2012 Andrew Neal Licensed under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package com.andrew.apollo.widgets; import android.content.Context; import android.util.AttributeSet; import android.widget.ImageView; /** * A custom {@link ImageView} that is sized to be a perfect square, otherwise * functions like a typical {@link ImageView}. * * @author Andrew Neal (andrewdneal@gmail.com) */ public class SquareImageView extends LayoutSuppressingImageView { /** * @param context The {@link Context} to use * @param attrs The attributes of the XML tag that is inflating the view. */ public SquareImageView(final Context context, final AttributeSet attrs) { super(context, attrs); } /** * {@inheritDoc} */ @Override public void onMeasure(final int widthSpec, final int heightSpec) { super.onMeasure(widthSpec, heightSpec); final int mSize = Math.min(getMeasuredWidth(), getMeasuredHeight()); setMeasuredDimension(mSize, mSize); } }
gpl-3.0
abeym/incubator
Trials/webservices/SimpleSOAPExample/src/com/ab/webservices/HelloWorld.java
141
package com.ab.webservices; public class HelloWorld { public String sayHelloWorld(String name) { return "Hello world from " + name; } }
gpl-3.0
NiuYongjie/coderepo
java8/Promote.java
467
/** * 演示了表达式中自动类型转换 * 从每个子表达式进行自动类型转换到整个表达式进行自动类型转换 */ class Promote{ public static void main(String[] args){ byte b = 42; char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = .1234; double result = (f * b) + (i / c) - (d * s); System.out.println((f * b) + " + " + (i / c) + " - " + (d * s)); System.out.println("result = " + result); } }
gpl-3.0
derkaiserreich/structr
structr-modules/structr-signed-jar-module/src/main/java/org/structr/jar/CreateJarFileFunction.java
14384
/** * Copyright (C) 2010-2016 Structr GmbH * * This file is part of Structr <http://structr.org>. * * Structr is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Structr is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Structr. If not, see <http://www.gnu.org/licenses/>. */ package org.structr.jar; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.math.BigInteger; import java.security.DigestOutputStream; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.MessageDigest; import java.security.PrivateKey; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.logging.Level; import javax.security.auth.x500.X500Principal; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.DEROutputStream; import org.bouncycastle.cert.jcajce.JcaCertStore; import org.bouncycastle.cms.CMSException; import org.bouncycastle.cms.CMSProcessableByteArray; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.cms.CMSSignedDataGenerator; import org.bouncycastle.cms.CMSTypedData; import org.bouncycastle.cms.SignerInfoGenerator; import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.x509.X509V3CertificateGenerator; import org.structr.common.error.FrameworkException; import org.structr.core.GraphObject; import org.structr.schema.action.ActionContext; import org.structr.web.function.UiFunction; /** * */ public class CreateJarFileFunction extends UiFunction { @Override public String getName() { return "create_jar_file"; } @Override public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { if (sources[0] instanceof OutputStream) { try { final String algorithm = "SHA1"; final String signAlgorithm = "SHA1withRSA"; final String keygenAlgorithm = "RSA"; final String srngAlgorithm = "SHA1PRNG"; final JarOutputStream jos = new JarOutputStream((OutputStream)sources[0]); final MessageDigest md = MessageDigest.getInstance(algorithm); final Manifest manifest = new Manifest(); final Attributes mainAttributes = manifest.getMainAttributes(); final PrivateKey privateKey = getOrCreatePrivateKey(keygenAlgorithm, srngAlgorithm, signAlgorithm); final X509Certificate cert = getOrCreateCertificate(keygenAlgorithm, srngAlgorithm, signAlgorithm); System.out.println("This is the fingerprint of the keystore: " + hex(cert)); // if (false) { // // // this code loads an existing keystore // final String keystorePath = StructrApp.getConfigurationValue("application.keystore.path", null); // final String keystorePassword = StructrApp.getConfigurationValue("application.keystore.password", null); // // X509Certificate cert = null; // PrivateKey privateKey = null; // // if (StringUtils.isNoneBlank(keystorePath, keystorePassword)) { // // try (final FileInputStream fis = new FileInputStream(keystorePath)) { // // final KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); // // keystore.load(fis, keystorePassword.toCharArray()); // // for (final Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) { // // final String alias = aliases.nextElement(); // // if (keystore.isCertificateEntry(alias)) { // // System.out.println("Using certificate entry " + alias); // cert = (X509Certificate)keystore.getCertificate(alias); // // } else if (keystore.isKeyEntry(alias)) { // // System.out.println("Using private key entry " + alias); // privateKey = (PrivateKey)keystore.getKey(alias, keystorePassword.toCharArray()); // // } // } // // // } catch (Throwable t) { // // logger.log(Level.WARNING, "", t); // } // } // } // maximum compression jos.setLevel(9); // initialize manifest mainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); // add entries from scripting context for (final Object source : sources) { if (source != null && source instanceof NameAndContent) { final NameAndContent content = (NameAndContent)source; final JarEntry entry = new JarEntry(content.getName()); final byte[] data = content.getContent().getBytes("utf-8"); entry.setTime(System.currentTimeMillis()); // write JarEntry jos.putNextEntry(entry); jos.write(data); jos.closeEntry(); jos.flush(); // update message digest with data md.update(data); // create new attribute with the entry's name Attributes attr = manifest.getAttributes(entry.getName()); if (attr == null) { attr = new Attributes(); manifest.getEntries().put(entry.getName(), attr); } // store SHA1-Digest for the new entry attr.putValue(algorithm + "-Digest", new String(Base64.encode(md.digest()), "ASCII")); } } // add manifest entry jos.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME)); manifest.write(jos); // add signature entry final byte[] signedData = getSignatureForManifest(manifest, algorithm); jos.putNextEntry(new JarEntry("META-INF/CERT.SF")); jos.write(signedData); if (privateKey != null && cert != null) { // add certificate entry jos.putNextEntry(new JarEntry("META-INF/CERT." + privateKey.getAlgorithm())); writeSignatureBlock(jos, algorithm, new CMSProcessableByteArray(signedData), cert, privateKey); } else { System.out.println("No certificate / key found, signinig disabled."); } // use finish() here to avoid an "already closed" exception later jos.flush(); jos.finish(); } catch (Throwable t) { logException(entity, t, sources); } } else { logger.log(Level.WARNING, "First parameter of create_jar_file() must be an output stream. Parameters: {0}", getParametersAsString(sources)); return "First parameter of create_jar_file() must be an output stream."; } } else { logParameterError(entity, sources, ctx.isJavaScriptContext()); } return ""; } @Override public String usage(boolean inJavaScriptContext) { return "create_jar_file()"; } @Override public String shortDescription() { return "Creates a signed JAR file from the given contents."; } // ----- private methods ----- private byte[] getSignatureForManifest(final Manifest forManifest, final String algorithm) throws IOException, GeneralSecurityException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final Manifest signatureFile = new Manifest(); final Attributes main = signatureFile.getMainAttributes(); final MessageDigest md = MessageDigest.getInstance(algorithm); final PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true, "UTF-8"); main.putValue("Signature-Version", "1.0"); forManifest.write(print); print.flush(); main.putValue(algorithm + "-Digest-Manifest", new String(Base64.encode(md.digest()), "ASCII")); final Map<String, Attributes> entries = forManifest.getEntries(); for (Map.Entry<String, Attributes> entry : entries.entrySet()) { // Digest of the manifest stanza for this entry. print.print("Name: " + entry.getKey() + "\r\n"); for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) { print.print(att.getKey() + ": " + att.getValue() + "\r\n"); } print.print("\r\n"); print.flush(); final Attributes sfAttr = new Attributes(); sfAttr.putValue(algorithm + "-Digest", new String(Base64.encode(md.digest()), "ASCII")); signatureFile.getEntries().put(entry.getKey(), sfAttr); } signatureFile.write(bos); return bos.toByteArray(); } private void writeSignatureBlock(final JarOutputStream jos, final String algorithm, final CMSTypedData data, final X509Certificate publicKey, final PrivateKey privateKey) throws IOException, CertificateEncodingException, OperatorCreationException, CMSException { final List<X509Certificate> certList = new ArrayList<>(); certList.add(publicKey); final JcaCertStore certs = new JcaCertStore(certList); final CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); final ContentSigner signer = new JcaContentSignerBuilder(algorithm + "with" + privateKey.getAlgorithm()).build(privateKey); final SignerInfoGenerator infoGenerator = new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).setDirectSignature(true).build(signer, publicKey); gen.addSignerInfoGenerator(infoGenerator); gen.addCertificates(certs); final CMSSignedData sigData = gen.generate(data, false); final ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded()); final DEROutputStream dos = new DEROutputStream(jos); final ASN1Primitive obj = asn1.readObject(); dos.writeObject(obj); } private PrivateKey getOrCreatePrivateKey(final String keygenAlgorithm, final String srngAlgorithm, final String signAlgorithm) { final KeyStore keyStore = getOrCreateKeystore(keygenAlgorithm, srngAlgorithm, signAlgorithm); final String keystorePass = "test"; if (keyStore != null) { try { return (PrivateKey)keyStore.getKey("priv", keystorePass.toCharArray()); } catch (Throwable t) { logger.log(Level.WARNING, "", t); } } return null; } private X509Certificate getOrCreateCertificate(final String keygenAlgorithm, final String srngAlgorithm, final String signAlgorithm) { final KeyStore keyStore = getOrCreateKeystore(keygenAlgorithm, srngAlgorithm, signAlgorithm); if (keyStore != null) { try { return (X509Certificate)keyStore.getCertificate("cert"); } catch (Throwable t) { logger.log(Level.WARNING, "", t); } } return null; } private KeyStore getOrCreateKeystore(final String keygenAlgorithm, final String srngAlgorithm, final String signAlgorithm) { final String keystorePath = "test.keystore"; final String keystorePass = "test"; final java.io.File keystoreFile = new java.io.File(keystorePath); if (keystoreFile.exists()) { try (final FileInputStream fis = new FileInputStream(keystoreFile)) { final KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(fis, keystorePass.toCharArray()); return keystore; } catch (Throwable t) { logger.log(Level.WARNING, "", t); } } else { try (final FileOutputStream fos = new FileOutputStream(keystoreFile)) { final KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, keystorePass.toCharArray()); final KeyPairGenerator gen = KeyPairGenerator.getInstance(keygenAlgorithm); gen.initialize(1024, SecureRandom.getInstance(srngAlgorithm)); final KeyPair keyPair = gen.generateKeyPair(); final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy"); final Date startDate = dateFormat.parse("01.01.2015"); final Date expiryDate = dateFormat.parse("01.01.2017"); final BigInteger serialNumber = BigInteger.valueOf(1234); final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); final X500Principal dnName = new X500Principal("CN=Test CA Certificate"); certGen.setSerialNumber(serialNumber); certGen.setIssuerDN(dnName); certGen.setNotBefore(startDate); certGen.setNotAfter(expiryDate); certGen.setSubjectDN(dnName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm(signAlgorithm); final X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC"); keystore.setCertificateEntry("cert", cert); keystore.setKeyEntry("priv", keyPair.getPrivate(), keystorePass.toCharArray(), new Certificate[] { cert } ); keystore.store(fos, keystorePass.toCharArray()); fos.flush(); return keystore; } catch (Throwable t) { logger.log(Level.WARNING, "", t); } } return null; } public String hex(final Certificate cert) { byte[] encoded; try { encoded = cert.getEncoded(); } catch (CertificateEncodingException e) { encoded = new byte[0]; } return hex(encoded); } public String hex(byte[] sig) { byte[] csig = new byte[sig.length * 2]; for (int j = 0; j < sig.length; j++) { byte v = sig[j]; int d = (v >> 4) & 0xf; csig[j * 2] = (byte) (d >= 10 ? ('a' + d - 10) : ('0' + d)); d = v & 0xf; csig[j * 2 + 1] = (byte) (d >= 10 ? ('a' + d - 10) : ('0' + d)); } return new String(csig); } }
gpl-3.0
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/spring-boot-bootstrap/src/test/java/com/baeldung/SpringContextIntegrationTest.java
343
package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringContextIntegrationTest { @Test public void contextLoads() { } }
gpl-3.0
natrolite/natrolite
natrolite-api/src/main/java/org/natrolite/text/Text.java
30695
/* * This file is part of SpongeAPI, 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.natrolite.text; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Locale; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import org.natrolite.dictionary.TranslationDictionaries; import org.natrolite.dictionary.TranslationDictionary; import org.natrolite.plugin.NeoJavaPlugin; import org.natrolite.text.action.ClickAction; import org.natrolite.text.action.HoverAction; import org.natrolite.text.action.ShiftClickAction; import org.natrolite.text.format.TextColor; import org.natrolite.text.format.TextFormat; import org.natrolite.text.format.TextStyle; import org.natrolite.text.serialisation.TextSerializers; public abstract class Text { /** * The empty, unformatted {@link Text} instance. */ public static final Text EMPTY = LiteralText.EMPTY; static final char NEW_LINE_CHAR = '\n'; static final String NEW_LINE_STRING = "\n"; /** * An unformatted {@link Text} that will start a new line (if supported). */ public static final LiteralText NEW_LINE = new LiteralText(NEW_LINE_STRING); final TextFormat format; final ImmutableList<Text> children; final Optional<ClickAction<?>> clickAction; final Optional<HoverAction<?>> hoverAction; final Optional<ShiftClickAction<?>> shiftClickAction; final Object[] args; /** * An {@link Iterable} providing an {@link Iterator} over this {@link Text} * as well as all children text and their children. */ final Iterable<Text> childrenIterable; Text() { this.format = TextFormat.NONE; this.clickAction = Optional.empty(); this.hoverAction = Optional.empty(); this.shiftClickAction = Optional.empty(); this.args = new Object[0]; this.children = ImmutableList.of(); this.childrenIterable = () -> Iterators.singletonIterator(this); } /** * Constructs a new immutable {@link Text} with the specified formatting and * text actions applied. * * @param format The format of the text * @param children The immutable list of children of the text * @param clickAction The click action of the text, or {@code null} for none * @param hoverAction The hover action of the text, or {@code null} for none * @param shiftClickAction The shift click action of the text, or * {@code null} for none */ Text(TextFormat format, ImmutableList<Text> children, @Nullable ClickAction<?> clickAction, @Nullable HoverAction<?> hoverAction, @Nullable ShiftClickAction<?> shiftClickAction, Object[] args) { this.format = checkNotNull(format, "format"); this.children = checkNotNull(children, "children"); this.clickAction = Optional.ofNullable(clickAction); this.hoverAction = Optional.ofNullable(hoverAction); this.shiftClickAction = Optional.ofNullable(shiftClickAction); this.args = checkNotNull(args, "args"); this.childrenIterable = () -> new TextIterator(this); } /** * Returns an empty, unformatted {@link Text} instance. * * @return An empty text */ public static Text of() { return EMPTY; } /** * Returns the style of this {@link Text}. This will return a compound * {@link TextStyle} if multiple different styles have been set. * * @return The style of this text */ public final TextStyle getStyle() { return this.format.getStyle(); } /** * Creates a {@link Text} with the specified plain text. The created text * won't have any formatting or events configured. * * @param content The content of the text * @return The created text * @see LiteralText */ public static LiteralText of(String content) { if (checkNotNull(content, "content").isEmpty()) { return LiteralText.EMPTY; } else if (content.equals(NEW_LINE_STRING)) { return NEW_LINE; } else { return new LiteralText(content); } } /** * Returns the immutable list of children appended after the content of this * {@link Text}. * * @return The immutable list of children */ public final ImmutableList<Text> getChildren() { return this.children; } /** * Creates a {@link Text} with the specified char as plain text. The created * text won't have any formatting or events configured. * * @param content The contant of the text as char * @return The created text * @see LiteralText */ public static LiteralText of(char content) { if (content == NEW_LINE_CHAR) { return NEW_LINE; } return new LiteralText(String.valueOf(content)); } /** * Gets an optional {@link Text} from the provided * {@link TranslationDictionary} by key. * * @param dictionary The translation dictionary to retrieve from * @param key The translation key * @return The text, if present, {@link Optional#empty()} otherwise */ public static Optional<Text> get(TranslationDictionary dictionary, String key) { return dictionary.get(key).map(Text::of); } /** * Gets an optional {@link Text} from the provided * {@link TranslationDictionary} by key and locale. * * @param dictionary The translation dictionary to retrieve from * @param key The translation key * @param locale The locale under which the value should be obtained in * @return The text, if present, {@link Optional#empty()} otherwise */ public static Optional<Text> get(TranslationDictionary dictionary, String key, Locale locale) { return dictionary.get(key, locale).map(Text::of); } /** * Gets an optional {@link Text} from the provided * plugin's {@link TranslationDictionary} by key. * * @param plugin The plugin to retrieve the translation dictionary from * @param key The translation key * @return The text, if present, {@link Optional#empty()} otherwise */ public static Optional<Text> get(NeoJavaPlugin plugin, String key) { return TranslationDictionaries.plugin(plugin) .map(dictionary -> dictionary.get(key).map(Text::of).orElse(null)); } /** * Returns whether this {@link Text} is empty. * * @return {@code true} if this text is empty */ public final boolean isEmpty() { return this == EMPTY; } /** * Gets an optional {@link Text} from the provided * plugin's {@link TranslationDictionary} by key and locale. * * @param plugin The plugin to retrieve the translation dictionary from * @param key The translation key * @param locale The locale under which the value should be obtained in * @return The text, if present, {@link Optional#empty()} otherwise */ public static Optional<Text> get(NeoJavaPlugin plugin, String key, Locale locale) { return TranslationDictionaries.plugin(plugin) .map(dictionary -> dictionary.get(key, locale).map(Text::of).orElse(null)); } public static Text un(NeoJavaPlugin plugin, String key) { return get(plugin, key).orElseThrow(IllegalStateException::new); } public final void info(Logger logger) { logger.log(Level.INFO, toPlain()); } public final void info(Logger logger, Throwable throwable) { logger.log(Level.INFO, toPlain(), throwable); } public final void warn(Logger logger) { logger.log(Level.WARNING, toPlain()); } public final void warn(Logger logger, Throwable throwable) { logger.log(Level.WARNING, toPlain(), throwable); } public final void severe(Logger logger) { logger.log(Level.SEVERE, toPlain()); } public final void severe(Logger logger, Throwable throwable) { logger.log(Level.SEVERE, toPlain(), throwable); } public static Text un(NeoJavaPlugin plugin, String key, Locale locale) { return get(plugin, key, locale).orElseThrow(IllegalStateException::new); } public static Text.Builder unb(NeoJavaPlugin plugin, String key) { return get(plugin, key).orElseThrow(IllegalStateException::new).toBuilder(); } /** * Concatenates the specified {@link Text} to this Text and returns the * result. * * @param other To concatenate * @return Concatenated text */ public final Text concat(Text other) { return toBuilder().append(other).build(); } /** * Removes all empty texts from the beginning and end of this * text. * * @return Text result */ public final Text trim() { return toBuilder().trim().build(); } public static Text.Builder unb(NeoJavaPlugin plugin, String key, Locale locale) { return get(plugin, key, locale).orElseThrow(IllegalStateException::new).toBuilder(); } /** * Creates a {@link Text.Builder} with empty text. * * @return A new text builder with empty text */ public static Text.Builder builder() { return new LiteralText.Builder(); } /** * Creates a new unformatted {@link LiteralText.Builder} with the specified * content. * * @param content The content of the text * @return The created text builder * @see LiteralText * @see LiteralText.Builder */ public static LiteralText.Builder builder(String content) { return new LiteralText.Builder(content); } @Override public final String toString() { return toStringHelper().toString(); } /** * Creates a new unformatted {@link LiteralText.Builder} with the specified * content. * * @param content The content of the text as char * @return The created text builder * @see LiteralText * @see LiteralText.Builder */ public static LiteralText.Builder builder(char content) { return builder(String.valueOf(content)); } /** * Creates a new {@link LiteralText.Builder} with the formatting and actions * of the specified {@link Text} and the given content. * * @param text The text to apply the properties from * @param content The content for the text builder * @return The created text builder * @see LiteralText * @see LiteralText.Builder */ public static LiteralText.Builder builder(Text text, String content) { return new LiteralText.Builder(text, content); } /** * Joins a sequence of text objects together. * * @param texts The texts to join * @return A text object that joins the given text objects */ public static Text join(Text... texts) { return builder().append(texts).build(); } /** * Joins a sequence of text objects together. * * @param texts The texts to join * @return A text object that joins the given text objects */ public static Text join(Iterable<? extends Text> texts) { return builder().append(texts).build(); } /** * Joins a sequence of text objects together. * * @param texts The texts to join * @return A text object that joins the given text objects */ public static Text join(Iterator<? extends Text> texts) { return builder().append(texts).build(); } /** * Joins a sequence of text objects together along with a separator. * * @param separator The separator * @param texts The texts to join * @return A text object that joins the given text objects */ public static Text joinWith(Text separator, Text... texts) { switch (texts.length) { case 0: return EMPTY; case 1: return texts[0]; default: Text.Builder builder = builder(); boolean appendSeparator = false; for (Text text : texts) { if (appendSeparator) { builder.append(separator); } else { appendSeparator = true; } builder.append(text); } return builder.build(); } } /** * Joins a sequence of text objects together along with a separator. * * @param separator The separator * @param texts The texts to join * @return A text object that joins the given text objects */ public static Text joinWith(Text separator, Iterable<? extends Text> texts) { return joinWith(separator, texts.iterator()); } /** * Joins a sequence of text objects together along with a separator. * * @param separator The separator * @param texts An iterator for the texts to join * @return A text object that joins the given text objects */ public static Text joinWith(Text separator, Iterator<? extends Text> texts) { if (!texts.hasNext()) { return EMPTY; } Text first = texts.next(); if (!texts.hasNext()) { return first; } Text.Builder builder = builder().append(first); do { builder.append(separator); builder.append(texts.next()); } while (texts.hasNext()); return builder.build(); } /** * Returns the color of this {@link Text}. * * @return The color of this text */ public final Optional<TextColor> getColor() { return this.format.getColor(); } /** * Returns the format of this {@link Text}. * * @return The format of this text */ public final TextFormat getFormat() { return this.format; } /** * Returns the {@link ClickAction} executed on the client when this * {@link Text} gets clicked. * * @return The click action of this text, or {@link Optional#empty()} if not set */ public final Optional<ClickAction<?>> getClickAction() { return this.clickAction; } /** * Returns the {@link HoverAction} executed on the client when this * {@link Text} gets hovered. * * @return The hover action of this text, or {@link Optional#empty()} if not set */ public final Optional<HoverAction<?>> getHoverAction() { return this.hoverAction; } /** * Returns the {@link ShiftClickAction} executed on the client when this * {@link Text} gets shift-clicked. * * @return The shift-click action of this text, or {@link Optional#empty()} if not set */ public final Optional<ShiftClickAction<?>> getShiftClickAction() { return this.shiftClickAction; } /** * Returns an immutable {@link Iterable} over this text and all of its * children. This is recursive, the children of the children will be also * included. * * @return An iterable over this text and the children texts */ public final Iterable<Text> withChildren() { return this.childrenIterable; } public final Object[] getArgs() { return args; } /* public final void to(CommandSender... senders) { to(ChatMessageType.CHAT, senders); } /** * Sends this {@link Text} to an {@link CommandSender}. * * @param senders the senders that should receive the message public final void to(ChatMessageType type, CommandSender... senders) { for (CommandSender sender : senders) { if (sender instanceof Player) { Odium.sendJsonMessage((Player) sender, toJson(), type); continue; } sender.sendMessage(toPlain()); } } */ public final String toPlain() { return TextSerializers.PLAIN.serialize(this); } public final String toJson() { return TextSerializers.JSON.serialize(this); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (!(o instanceof Text)) { return false; } Text that = (Text) o; return this.format.equals(that.format) && this.children.equals(that.children) && this.clickAction.equals(that.clickAction) && this.hoverAction.equals(that.hoverAction) && this.shiftClickAction.equals(that.shiftClickAction); } @Override public int hashCode() { return Objects.hashCode(this.format, this.children, this.clickAction, this.hoverAction, this.shiftClickAction); } MoreObjects.ToStringHelper toStringHelper() { return MoreObjects.toStringHelper(Text.class) .omitNullValues() .add("format", this.format.isEmpty() ? null : this.format) .add("children", this.children.isEmpty() ? null : this.children) .add("clickAction", this.clickAction.orElse(null)) .add("hoverAction", this.hoverAction.orElse(null)) .add("shiftClickAction", this.shiftClickAction.orElse(null)); } /** * Returns a new {@link Builder} with the content, formatting and actions of * this text. This can be used to edit an otherwise immutable {@link Text} * instance. * * @return A new message builder with the content of this text */ public abstract Builder toBuilder(); /** * Represents a builder class to create immutable {@link Text} instances. * * @see Text */ public abstract static class Builder { TextFormat format = TextFormat.NONE; List<Text> children = new ArrayList<>(); Object[] args = new Object[0]; @Nullable ClickAction<?> clickAction; @Nullable HoverAction<?> hoverAction; @Nullable ShiftClickAction<?> shiftClickAction; /** * Constructs a new empty {@link Builder}. */ Builder() {} /** * Constructs a new {@link Builder} with the properties of the given * {@link Text} as initial values. * * @param text The text to copy the values from */ Builder(Text text) { this.format = text.format; this.children = new ArrayList<>(text.children); this.clickAction = text.clickAction.orElse(null); this.hoverAction = text.hoverAction.orElse(null); this.shiftClickAction = text.shiftClickAction.orElse(null); this.args = text.args; } /** * Returns the current format of the {@link Text} in this builder. * * @return The current format * @see Text#getFormat() */ public final TextFormat getFormat() { return this.format; } /** * Sets the {@link TextFormat} of this text. * * @param format The new text format for this text * @return The text builder * @see Text#getFormat() */ public Builder format(TextFormat format) { this.format = checkNotNull(format, "format"); return this; } /** * Returns the current color of the {@link Text} in this builder. * * @return The current color * @see Text#getColor() */ public final Optional<TextColor> getColor() { return this.format.getColor(); } /** * Sets the {@link TextColor} of this text. * * @param color The new text color for this text * @return This text builder * @see Text#getColor() */ public Builder color(TextColor color) { this.format = this.format.color(color); return this; } public Builder args(Object... args) { this.args = args; return this; } /** * Returns the current style of the {@link Text} in this builder. * * @return The current style * @see Text#getStyle() */ public final TextStyle getStyle() { return this.format.getStyle(); } /** * Sets the text styles of this text. This will construct a composite * {@link TextStyle} of the current style and the specified styles first * and set it to the text. * * @param styles The text styles to apply * @return This text builder * @see Text#getStyle() */ // TODO: Make sure this is the correct behaviour public Builder style(TextStyle... styles) { this.format = this.format.style(this.format.getStyle().and(styles)); return this; } /** * Returns the current {@link ClickAction} of this builder. * * @return The current click action or {@link Optional#empty()} if none * @see Text#getClickAction() */ public final Optional<ClickAction<?>> getClickAction() { return Optional.ofNullable(this.clickAction); } /** * Sets the {@link ClickAction} that will be executed if the text is * clicked in the chat. * * @param clickAction The new click action for the text * @return This text builder * @see Text#getClickAction() */ public Builder onClick(@Nullable ClickAction<?> clickAction) { this.clickAction = clickAction; return this; } /** * Returns the current {@link HoverAction} of this builder. * * @return The current hover action or {@link Optional#empty()} if none * @see Text#getHoverAction() */ public final Optional<HoverAction<?>> getHoverAction() { return Optional.ofNullable(this.hoverAction); } /** * Sets the {@link HoverAction} that will be executed if the text is * hovered in the chat. * * @param hoverAction The new hover action for the text * @return This text builder * @see Text#getHoverAction() */ public Builder onHover(@Nullable HoverAction<?> hoverAction) { this.hoverAction = hoverAction; return this; } /** * Returns the current {@link ShiftClickAction} of this builder. * * @return The current shift click action or {@link Optional#empty()} if none * @see Text#getShiftClickAction() */ public final Optional<ShiftClickAction<?>> getShiftClickAction() { return Optional.ofNullable(this.shiftClickAction); } /** * Sets the {@link ShiftClickAction} that will be executed if the text * is shift-clicked in the chat. * * @param shiftClickAction The new shift click action for the text * @return This text builder * @see Text#getShiftClickAction() */ public Builder onShiftClick(@Nullable ShiftClickAction<?> shiftClickAction) { this.shiftClickAction = shiftClickAction; return this; } /** * Returns a view of the current children of this builder. * * <p>The returned list is unmodifiable, but not immutable. It will * change if new children get added through this builder.</p> * * @return An unmodifiable list of the current children * @see Text#getChildren() */ public final List<Text> getChildren() { return Collections.unmodifiableList(this.children); } /** * Appends the specified {@link Text} to the end of this text. * * @param children The texts to append * @return This text builder * @see Text#getChildren() */ public Builder append(Text... children) { Collections.addAll(this.children, children); return this; } /** * Appends the specified {@link Text} to the end of this text. * * @param children The texts to append * @return This text builder * @see Text#getChildren() */ public Builder append(Collection<? extends Text> children) { this.children.addAll(children); return this; } /** * Appends the specified {@link Text} to the end of this text. * * @param children The texts to append * @return This text builder * @see Text#getChildren() */ public Builder append(Iterable<? extends Text> children) { for (Text child : children) { this.children.add(child); } return this; } /** * Appends the specified {@link Text} to the end of this text. * * @param children The texts to append * @return This text builder * @see Text#getChildren() */ public Builder append(Iterator<? extends Text> children) { while (children.hasNext()) { this.children.add(children.next()); } return this; } /** * Inserts the specified {@link Text} at the given position of this * builder. * * @param pos The position to insert the texts to * @param children The texts to insert * @return This text builder * @throws IndexOutOfBoundsException If the position is out of bounds * @see Text#getChildren() */ public Builder insert(int pos, Text... children) { this.children.addAll(pos, Arrays.asList(children)); return this; } /** * Inserts the specified {@link Text} at the given position of this * builder. * * @param pos The position to insert the texts to * @param children The texts to insert * @return This text builder * @throws IndexOutOfBoundsException If the position is out of range * @see Text#getChildren() */ public Builder insert(int pos, Collection<? extends Text> children) { this.children.addAll(pos, children); return this; } /** * Inserts the specified {@link Text} at the given position of this * builder. * * @param pos The position to insert the texts to * @param children The texts to insert * @return This text builder * @throws IndexOutOfBoundsException If the position is out of range * @see Text#getChildren() */ public Builder insert(int pos, Iterable<? extends Text> children) { for (Text child : children) { this.children.add(pos++, child); } return this; } /** * Inserts the specified {@link Text} at the given position of this * builder. * * @param pos The position to insert the texts to * @param children The texts to insert * @return This text builder * @throws IndexOutOfBoundsException If the position is out of range * @see Text#getChildren() */ public Builder insert(int pos, Iterator<? extends Text> children) { while (children.hasNext()) { this.children.add(pos++, children.next()); } return this; } /** * Removes the specified {@link Text} from this builder. * * @param children The texts to remove * @return This text builder * @see Text#getChildren() */ public Builder remove(Text... children) { this.children.removeAll(Arrays.asList(children)); return this; } /** * Removes the specified {@link Text} from this builder. * * @param children The texts to remove * @return This text builder * @see Text#getChildren() */ public Builder remove(Collection<? extends Text> children) { this.children.removeAll(children); return this; } /** * Removes the specified {@link Text} from this builder. * * @param children The texts to remove * @return This text builder * @see Text#getChildren() */ public Builder remove(Iterable<? extends Text> children) { for (Text child : children) { this.children.remove(child); } return this; } /** * Removes the specified {@link Text} from this builder. * * @param children The texts to remove * @return This text builder * @see Text#getChildren() */ public Builder remove(Iterator<? extends Text> children) { while (children.hasNext()) { this.children.remove(children.next()); } return this; } /** * Removes all children from this builder. * * @return This text builder * @see Text#getChildren() */ public Builder removeAll() { this.children.clear(); return this; } /** * Removes all empty texts from the beginning and end of this * builder. * * @return This builder */ public Builder trim() { Iterator<Text> front = this.children.iterator(); while (front.hasNext()) { if (front.next().isEmpty()) { front.remove(); } else { break; } } ListIterator<Text> back = this.children.listIterator(this.children.size()); while (back.hasPrevious()) { if (back.previous().isEmpty()) { back.remove(); } else { break; } } return this; } /** * Builds an immutable instance of the current state of this text * builder. * * @return An immutable {@link Text} with the current properties of this builder */ public abstract Text build(); @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (!(o instanceof Builder)) { return false; } Builder that = (Builder) o; return Objects.equal(this.format, that.format) && Objects.equal(this.clickAction, that.clickAction) && Objects.equal(this.hoverAction, that.hoverAction) && Objects.equal(this.shiftClickAction, that.shiftClickAction) && Objects.equal(this.children, that.children); } @Override public int hashCode() { return Objects.hashCode(this.format, this.clickAction, this.hoverAction, this.shiftClickAction, this.children); } MoreObjects.ToStringHelper toStringHelper() { return MoreObjects.toStringHelper(Builder.class) .omitNullValues() .add("format", this.format.isEmpty() ? null : this.format) .add("children", this.children.isEmpty() ? null : this.children) .add("clickAction", this.clickAction) .add("hoverAction", this.hoverAction) .add("shiftClickAction", this.shiftClickAction); } @Override public final String toString() { return toStringHelper().toString(); } } }
gpl-3.0
isc-konstanz/OpenMUC
projects/lib/osgi/src/main/java/org/openmuc/framework/lib/osgi/deployment/ServiceAccess.java
1029
/* * Copyright 2011-2021 Fraunhofer ISE * * This file is part of OpenMUC. * For more information visit http://www.openmuc.org * * OpenMUC is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenMUC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenMUC. If not, see <http://www.gnu.org/licenses/>. * */ package org.openmuc.framework.lib.osgi.deployment; /** * Helper interface to set services */ public interface ServiceAccess { /** * @param serviceRef * The service to set */ public void setService(Object serviceRef); }
gpl-3.0
vruano/maltools
src/java/main/net/malariagen/gatk/walker/MultiWindowSequenceComplexity.java
4383
package net.malariagen.gatk.walker; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.utils.GenomeLoc; public class MultiWindowSequenceComplexity { protected SequenceComplexity[] complexities; protected Map<Integer, SequenceComplexity> byWs; protected int maxWindow = 0; protected PriorityQueue<WindowSet> windows = new PriorityQueue<WindowSet>(); protected Map<GenomeLoc, WindowSet> windowByLoc = new HashMap<GenomeLoc, WindowSet>( 100); private GenomeLoc lastLocus; private GenomeLoc lastEmited; public List<Map<Integer, SequenceComplexity.LocusComplexity>> flush() { for (Integer i : byWs.keySet()) for (SequenceComplexity.LocusComplexity slc : byWs.get(i).flush()) { GenomeLoc loc = slc.getLocus(); if (windowByLoc.get(loc) == null) System.err.println(" " + lastLocus + " " + lastEmited + " " + loc); windowByLoc.get(loc).bySize.put(i,slc); } List<Map<Integer, SequenceComplexity.LocusComplexity>> result = new LinkedList<Map<Integer, SequenceComplexity.LocusComplexity>>(); while (!windows.isEmpty()) { WindowSet ws2 = windows.remove(); if (ws2.bySize.size() < byWs.size()) throw new IllegalStateException("some window size did not flush to the end"); result.add(ws2.bySize); windowByLoc.remove(ws2.start); } return result; } public List<Map<Integer, SequenceComplexity.LocusComplexity>> count(ReferenceContext ref, Integer exaustiveRef, int refMQ) { GenomeLoc loc = ref.getLocus(); lastLocus = loc; WindowSet ws = windowByLoc.get(loc); if (ws == null) { if (!windows.isEmpty() && !windows.element().start.getContig().equals(loc.getContig())) { if (true) throw new IllegalArgumentException("what tha"); windowByLoc.clear(); windows.clear(); } windowByLoc.put(loc, ws = new WindowSet(loc)); windows.add(ws); } for (Integer i : byWs.keySet()) { SequenceComplexity.LocusComplexity lc; if (exaustiveRef != null && exaustiveRef.intValue() == i) lc = byWs.get(i).count(ref,refMQ); else lc = byWs.get(i).count(ref,0); if (lc == null) continue; ws = windowByLoc.get(lc.getLocus()); if (ws == null) throw new RuntimeException("complexity at locus " + loc + " seen before locus being visited!!!"); ws.bySize.put(i, lc); } if (windows.element().bySize.size() == byWs.size()) { List<Map<Integer, SequenceComplexity.LocusComplexity>> result = new LinkedList<Map<Integer, SequenceComplexity.LocusComplexity>>(); while (!windows.isEmpty()) { WindowSet ws2 = windows.element(); if (ws2.bySize.size() < byWs.size()) break; result.add(ws2.bySize); windowByLoc.remove(ws2.start); windows.remove(); lastEmited = ws2.start; } return result; } else { return Collections.emptyList(); } } MultiWindowSequenceComplexity(int... ws) { for (int i : ws) if (i <= 0) throw new IllegalArgumentException( "the requiested windows size cannot be less or equal to 0"); byWs = new HashMap<Integer, SequenceComplexity>(ws.length); for (int i : ws) { if (i > maxWindow) maxWindow = i; if (byWs.get(i) == null) byWs.put(i, SequenceComplexity.create(i)); } complexities = byWs.values().toArray( new SequenceComplexity[byWs.size()]); } protected class WindowSet implements Comparable<WindowSet> { GenomeLoc start; Map<Integer, SequenceComplexity.LocusComplexity> bySize; public WindowSet(GenomeLoc loc) { start = loc; bySize = new HashMap<Integer, SequenceComplexity.LocusComplexity>(); } public boolean equal(Object o) { if (o == null) return false; else if (o instanceof WindowSet) return equal((WindowSet)o); else return false; } public int hashCode() { return start.hashCode(); } public boolean equal(WindowSet o) { return compareTo(o) == 0; } @Override public int compareTo(WindowSet o) { return start.compareTo(o.start); } } public GenomeLoc lastLocus() { // TODO Auto-generated method stub return lastLocus; } }
gpl-3.0
timernsberger/sepia
SepiaAgents/src/edu/cwru/sepia/agent/planner/CompoundActionPlanner.java
3185
package edu.cwru.sepia.agent.planner; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import edu.cwru.sepia.action.Action; import edu.cwru.sepia.action.ActionResult; import edu.cwru.sepia.action.ActionResultType; import edu.cwru.sepia.action.TargetedAction; import edu.cwru.sepia.model.history.History.HistoryView; import edu.cwru.sepia.model.state.State.StateView; import edu.cwru.sepia.model.state.Unit.UnitView; public class CompoundActionPlanner { private List<ActionResultType> dontReplan = Arrays.asList(ActionResultType.COMPLETED, ActionResultType.INCOMPLETE); private Map<Integer, Plan> plans = new HashMap<>(); /** * Returns the actions each planned unit should take on the current turn. * Re-plans if actions failed or will be infeasible. Will not return actions * for units if they are in the middle of executing an action. * * @param state * @param history * @return */ public Collection<Action> getActions(StateView state, HistoryView history) { Collection<Action> actions = new ArrayList<>(); for(Integer unitId : new HashSet<Integer>(plans.keySet())) { UnitView unit = state.getUnit(unitId); if(unit == null) { plans.remove(unitId); continue; } // if agent is idle if(unit.getCurrentDurativeAction() == null) { Plan plan = plans.get(unitId); ActionResult feedback = history.getCommandFeedback(unit.getTemplateView().getPlayer(), state.getTurnNumber() - 1).get(unitId); // if action is targeted or last primitive failed, re-plan if(plan.getCompoundAction() instanceof TargetedAction || !dontReplan.contains(feedback.getFeedback())) { try { createOrUpdatePlan(state, plan.getCompoundAction()); } catch(PlanInfeasibleException ex) { plans.remove(unitId); continue; } } actions.add(plan.getNextAction(state)); } } return actions; } /** * Registers the given action for planning. Causes a plan to be generated. * Overwrites the current plan for the action's unit. * * @param state * @param unit * @param action * @return the old plan */ public Plan createOrUpdatePlan(StateView state, Action action) throws PlanInfeasibleException { Plan plan = generatePlan(state, action); return plans.put(action.getUnitId(), plan); } /** * Stops execution of the current plan for the given unit. Removes the plan. * * @param unit * @return */ public Plan removePlan(int unitId) { return plans.remove(unitId); } public Plan getPlan(int unitId) { Plan plan = plans.get(unitId); if(plan == null) return null; return plan.getCopy(); } /** * Plans for the given compound action using #{@code PlanningContext#generatePlan()} * * @param state * @param action * @return * @throws PlanInfeasibleException */ public Plan generatePlan(StateView state, Action action) throws PlanInfeasibleException { return new PlanningContext(action, state).generatePlan(); } }
gpl-3.0
potty-dzmeia/db4o
src/db4oj.tests/src/com/db4o/db4ounit/common/concurrency/IsStoredTestCase.java
1537
/* This file is part of the db4o object database http://www.db4o.com Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com db4o is free software; you can redistribute it and/or modify it under the terms of version 3 of the GNU General Public License as published by the Free Software Foundation. db4o is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ package com.db4o.db4ounit.common.concurrency; import com.db4o.ext.*; import db4ounit.*; import db4ounit.extensions.*; public class IsStoredTestCase extends Db4oClientServerTestCase { public static void main(String[] args) { new IsStoredTestCase().runConcurrency(); } public String myString; public void conc(ExtObjectContainer oc) { IsStoredTestCase isStored = new IsStoredTestCase(); isStored.myString = "isStored"; oc.store(isStored); Assert.isTrue(oc.isStored(isStored)); oc.commit(); oc.delete(isStored); Assert.isFalse(oc.isStored(isStored)); oc.rollback(); Assert.isTrue(oc.isStored(isStored)); oc.delete(isStored); Assert.isFalse(oc.isStored(isStored)); oc.commit(); Assert.isFalse(oc.isStored(isStored)); } public void check(ExtObjectContainer oc) { assertOccurrences(oc, IsStoredTestCase.class, 0); } }
gpl-3.0
Stormister/Rediscovered-Mod-1.6.4
source/main/RediscoveredMod/EntityMountableBlock.java
3651
// Copyright 2012-2014 Matthew Karcz // // This file is part of The Rediscovered Mod. // // The Rediscovered Mod is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The Rediscovered Mod is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with The Rediscovered Mod. If not, see <http://www.gnu.org/licenses/>. package RediscoveredMod; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; /*ITOS: *This class acts as a bridge between the mountable block and the player. *This entity is what the player actually mounts instead of the block. *An entity of this class is created by the mountable block upon activation *and is killed when it's no longer used. */ public class EntityMountableBlock extends Entity { //These variables keep track of the block that created the entity. protected int orgBlockPosX; protected int orgBlockPosY; protected int orgBlockPosZ; protected int orgBlockID; public EntityMountableBlock (World world) { super(world); noClip = true; preventEntitySpawning = true; width = 0F; height = 0F; } public EntityMountableBlock (World world, double d, double d1, double d2) { super(world); noClip = true; preventEntitySpawning = true; width = 0F; height = 0F; setPosition(d, d1, d2); } //This constructor is called by the mountable block. public EntityMountableBlock (World world, EntityPlayer entityplayer, int i, int j, int k, float mountingX, float mountingY, float mountingZ) { super(world); noClip = true; preventEntitySpawning = true; width = 0.0F; height = 0.0F; orgBlockPosX = i; orgBlockPosY = j; orgBlockPosZ = k; orgBlockID = world.getBlockId(i, j, k); setPosition(mountingX, mountingY, mountingZ); } //This method handles mounting and dismounting. public boolean interact(EntityPlayer entityplayer) { if (this.riddenByEntity != null && this.riddenByEntity instanceof EntityPlayer && this.riddenByEntity != entityplayer) { return true; } else { if (!this.worldObj.isRemote) { entityplayer.mountEntity(this); } return true; } } //This method is mostly a simplified version of the one in Entity but it also deletes unused EMBs. @Override public void onEntityUpdate() { this.worldObj.theProfiler.startSection("entityBaseTick"); if(riddenByEntity == null || riddenByEntity.isDead || worldObj.getBlockId(orgBlockPosX, orgBlockPosY, orgBlockPosZ) != orgBlockID) { this.setDead(); } ticksExisted++; this.worldObj.theProfiler.endSection(); } //The following methods are required by the Entity class but I don't know what they are for. @Override public void entityInit() {} @Override public void readEntityFromNBT(NBTTagCompound nbttagcompound) {} @Override public void writeEntityToNBT(NBTTagCompound nbttagcompound) {} }
gpl-3.0
EterniaLogic/TekkitRestrict
TekkitRestrict/src/nl/taico/tekkitrestrict/TRListener.java
5529
package nl.taico.tekkitrestrict; //import net.minecraft.server.TileEntity; //import net.minecraft.server.WorldServer; import nl.taico.tekkitrestrict.Log.Warning; import nl.taico.tekkitrestrict.TRConfigCache.Listeners; import nl.taico.tekkitrestrict.commands.TRCmdOpenAlc; import nl.taico.tekkitrestrict.commands.TRCmdOpenInv; import nl.taico.tekkitrestrict.functions.TRLWCProtect; import nl.taico.tekkitrestrict.functions.TRLimiter; import nl.taico.tekkitrestrict.functions.TRNoDupeProjectTable; import nl.taico.tekkitrestrict.functions.TRNoInteract; import nl.taico.tekkitrestrict.functions.TRNoItem; import nl.taico.tekkitrestrict.objects.TRItem; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; //import org.bukkit.craftbukkit.CraftWorld; //import eloraam.core.TileCovered; public class TRListener implements Listener { //private int lastdata = 0; public static boolean errorBlockPlace = false; public static boolean errorInteract = false; //for covers, the event is called twice. //first one is 136:itemdata //second one is 136:0 /** * @return <b>True</b> if id < 7 or id = 12 (sand), 13 (gravel), 17 (logs), 20 (glass), 24 (sandstone), 35 (wool), 44, 98 (stonebricks) or 142 (marble). * <b>False</b> otherwise. */ private static boolean exempt(int id){ return ((id < 7) || (id == 12) || (id == 13) || (id == 17) || (id == 20) || (id == 24) || (id == 35) || (id == 44) || (id == 98) || (id == 142)); } @EventHandler(priority=EventPriority.HIGH, ignoreCancelled = true) public void onBlockPlace(BlockPlaceEvent event) { final Block block = event.getBlock(); final int id = block.getTypeId(); if (exempt(id)) return; final Player player; if ((player = event.getPlayer()) == null) return; final String pname = player.getName(); try { if ((id != 136) && !TRLWCProtect.checkLWCAllowed(event)) return; final int data = block.getData(); if (Listeners.UseBlockLimit && !pname.equals("[BuildCraft]") && !pname.equals("[RedPower]")){ if (!player.hasPermission("tekkitrestrict.bypass.limiter")) { final TRLimiter il = TRLimiter.getOnlineLimiter(player); String limited = il.checkLimit(event, false); if (limited != null) { if (limited.isEmpty()) limited = ChatColor.RED + "[TRItemLimiter] You cannot place down any more of that block!"; TRItem.sendBannedMessage(player, limited); event.setCancelled(true); } } } String msg = TRNoItem.isItemBanned(player, id, data, true); if (msg != null) { if (msg.isEmpty()) msg = ChatColor.RED + "[TRItemDisabler] You are not allowed to place down this type of block!"; TRItem.sendBannedMessage(player, msg); event.setCancelled(true); } } catch(Exception ex){ if (!errorBlockPlace){ Warning.other("An error occurred in the BlockPlace Listener! Please inform the author (This error will only be logged once).", false); Log.Exception(ex, false); errorBlockPlace = true; } } } @EventHandler(priority = EventPriority.MONITOR) public void onInventoryCloseEvent(InventoryCloseEvent e) { final Player player; if ((player = (Player) e.getPlayer()) == null) return; TRNoDupeProjectTable.playerUnuse(player.getName()); TRCmdOpenAlc.setPlayerInv(player, true); TRCmdOpenInv.closeInv(player); } // /////// START INTERACT ////////////// @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = false) public void onPlayerInteract(PlayerInteractEvent event) { final Player player; if ((player = event.getPlayer()) == null) return; // lets do this based on a white-listed approach. // First, lets loop through the DisableClick list to stop clicks. // Perf: 8x if (TRNoInteract.isDisabled(event)){ event.setCancelled(true); return; } final ItemStack str = player.getItemInHand(); if (str == null) return; if ((TRConfigCache.LWC.lwc || !TRLWCProtect.init) && (event.getAction() == Action.RIGHT_CLICK_BLOCK) && (str.getTypeId() == 136)){ //cover = (data >> 8 == 0 v >=16 && <=45 if (!TRLWCProtect.isLWCAllowed(event)) return; } if (player.getGameMode() != GameMode.CREATIVE) return; String msg; try { msg = TRNoItem.isItemBannedInCreative(player, str.getTypeId(), str.getDurability(), true); } catch (Exception ex) { if (!errorInteract){ Warning.other("An error occurred in the InteractListener for LimitedCreative!", false); Log.Exception(ex, false); errorInteract = true; } return; } if (msg != null) { if (msg.isEmpty()) msg = ChatColor.RED + "[TRLimitedCreative] You may not interact with this item."; TRItem.sendBannedMessage(player, msg); event.setCancelled(true); player.setItemInHand(null); return; } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerInteract2(PlayerInteractEvent event){ if (TRNoDupeProjectTable.isTableUseAllowed(event.getClickedBlock(), event.getPlayer())) return; event.getPlayer().sendMessage(ChatColor.RED + "Someone else is already using this project table!"); event.setCancelled(true); return; } // /////////// END INTERACT ///////////// }
gpl-3.0
lveci/nest
nest-op-sar-tools/src/main/java/org/esa/nest/gpf/ImportVectorOp.java
16863
/* * Copyright (C) 2013 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.nest.gpf; import com.bc.ceres.core.ProgressMonitor; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import org.esa.beam.dataio.geometry.VectorDataNodeIO; import org.esa.beam.framework.datamodel.*; import org.esa.beam.framework.gpf.Operator; import org.esa.beam.framework.gpf.OperatorException; import org.esa.beam.framework.gpf.OperatorSpi; import org.esa.beam.framework.gpf.annotations.OperatorMetadata; import org.esa.beam.framework.gpf.annotations.Parameter; import org.esa.beam.framework.gpf.annotations.SourceProduct; import org.esa.beam.framework.gpf.annotations.TargetProduct; import org.esa.beam.jai.ImageManager; import org.esa.beam.util.Debug; import org.esa.beam.util.FeatureUtils; import org.esa.beam.util.ProductUtils; import org.esa.beam.util.io.FileUtils; import org.esa.beam.visat.toolviews.layermanager.layersrc.shapefile.SLDUtils; import org.geotools.feature.DefaultFeatureCollection; import org.geotools.feature.FeatureCollection; import org.geotools.geometry.jts.GeometryCoordinateSequenceTransformer; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.geotools.referencing.operation.transform.AffineTransform2D; import org.geotools.styling.Style; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.TransformException; import javax.swing.*; import java.awt.geom.AffineTransform; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; /** * The import vector operator. */ @OperatorMetadata(alias = "Import-Vector", category = "Utilities", authors = "Jun Lu, Luis Veci", copyright = "Copyright (C) 2013 by Array Systems Computing Inc.", description = "Imports a shape file into a product") public class ImportVectorOp extends Operator { @SourceProduct(alias="source") private Product sourceProduct; @TargetProduct private Product targetProduct = null; @Parameter(label = "Vector File") private File vectorFile = null; @Parameter(label = "Separate Shapes", defaultValue = "true") private boolean separateShapes = true; @Override public void initialize() throws OperatorException { try { targetProduct = new Product(sourceProduct.getName(), sourceProduct.getProductType(), sourceProduct.getSceneRasterWidth(), sourceProduct.getSceneRasterHeight()); OperatorUtils.copyProductNodes(sourceProduct, targetProduct); for(String bandName : sourceProduct.getBandNames()) { ProductUtils.copyBand(bandName, sourceProduct, targetProduct, true); } if(vectorFile != null) { importGeometry(targetProduct, vectorFile); } } catch (Throwable e) { OperatorUtils.catchOperatorException(getId(), e); } } private void importGeometry(final Product product, final File file) { final GeoCoding geoCoding = product.getGeoCoding(); if (isShapefile(file) && (geoCoding == null || !geoCoding.canGetPixelPos())) { throw new OperatorException("Current geo-coding cannot convert from geographic to pixel coordinates."); /* I18N */ } final VectorDataNodeReader reader; if (isShapefile(file)) { reader = new VdnShapefileReader(); } else { reader = new VdnTextReader(); } VectorDataNode vectorDataNode; try { vectorDataNode = reader.readVectorDataNode(file, product, null, ProgressMonitor.NULL); } catch (Exception e) { throw new OperatorException("Failed to import geometry.\n" + "An I/O Error occurred:\n" + e.getMessage()); /* I18N */ } VectorDataNode[] vectorDataNodes = VectorDataNodeIO.getVectorDataNodes(vectorDataNode, separateShapes, "importedVector"); for (VectorDataNode vectorDataNode1 : vectorDataNodes) { product.getVectorDataGroup().add(vectorDataNode1); } } private static String findUniqueVectorDataNodeName(final String suggestedName, final ProductNodeGroup<VectorDataNode> vectorDataGroup) { String name = suggestedName; int index = 1; while (vectorDataGroup.contains(name)) { name = suggestedName + '_' + index; index++; } return name; } private static boolean isShapefile(final File file) { return file.getName().toLowerCase().endsWith(".shp"); } interface VectorDataNodeReader { VectorDataNode readVectorDataNode(File file, Product product, String helpId, ProgressMonitor pm) throws IOException; } static class VdnShapefileReader implements VectorDataNodeReader { @Override public VectorDataNode readVectorDataNode(File file, Product product, String helpId, ProgressMonitor pm) throws IOException { MyFeatureCrsProvider crsProvider = new MyFeatureCrsProvider(helpId); FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = FeatureUtils.loadShapefileForProduct(file, product, crsProvider, pm); Style[] styles = SLDUtils.loadSLD(file); ProductNodeGroup<VectorDataNode> vectorDataGroup = product.getVectorDataGroup(); String name = findUniqueVectorDataNodeName(featureCollection.getSchema().getName().getLocalPart(), vectorDataGroup); if (styles.length > 0) { SimpleFeatureType featureType = SLDUtils.createStyledFeatureType(featureCollection.getSchema()); VectorDataNode vectorDataNode = new VectorDataNode(name, featureType); FeatureCollection<SimpleFeatureType, SimpleFeature> styledCollection = vectorDataNode.getFeatureCollection(); String defaultCSS = vectorDataNode.getDefaultStyleCss(); SLDUtils.applyStyle(styles[0], defaultCSS, featureCollection, styledCollection); return vectorDataNode; } else { return new VectorDataNode(name, featureCollection); } } private class MyFeatureCrsProvider implements FeatureUtils.FeatureCrsProvider { private final String helpId; public MyFeatureCrsProvider(String helpId) { this.helpId = helpId; } @Override public CoordinateReferenceSystem getFeatureCrs(final Product product) { final CoordinateReferenceSystem[] featureCrsBuffer = new CoordinateReferenceSystem[1]; Runnable runnable = new Runnable() { @Override public void run() { featureCrsBuffer[0] = product.getGeoCoding().getMapCRS(); } }; if (!SwingUtilities.isEventDispatchThread()) { try { SwingUtilities.invokeAndWait(runnable); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } else { runnable.run(); } CoordinateReferenceSystem featureCrs = featureCrsBuffer[0]; return featureCrs != null ? featureCrs : DefaultGeographicCRS.WGS84; } } } static class VdnTextReader implements VectorDataNodeReader { @Override public VectorDataNode readVectorDataNode(File file, Product product, String helpId, ProgressMonitor pm) throws IOException { final ArrayList<PixelPos> pixelPositions = new ArrayList<PixelPos>(256); final GeoCoding geoCoding = product.getGeoCoding(); final FileReader fileReader = new FileReader(file); final LineNumberReader reader = new LineNumberReader(fileReader); try { final StreamTokenizer st = createConfiguredTokenizer(reader); final float[] values = new float[]{0.0F, 0.0F, 0.0F, 0.0F}; // values for {x, y, lat, lon} final boolean[] valid = new boolean[]{false, false, false, false}; // {x, y, lat, lon} columns valid? final int[] indices = new int[]{0, 1, 2, 3}; // indexes of {x, y, lat, lon} columns boolean headerAvailable = false; int column = 0; while (true) { final int tt = st.nextToken(); if (tt == StreamTokenizer.TT_EOF || tt == StreamTokenizer.TT_EOL) { final boolean xyAvailable = valid[0] && valid[1]; final boolean latLonAvailable = valid[2] && valid[3] && geoCoding != null && geoCoding.canGetPixelPos(); if (xyAvailable || latLonAvailable) { PixelPos pixelPos; if (latLonAvailable) { pixelPos = geoCoding.getPixelPos(new GeoPos(values[2], values[3]), null); } else { pixelPos = new PixelPos(values[0], values[1]); } // Do not add positions which are out of bounds, it leads to scrambled shapes if (pixelPos.x != -1 && pixelPos.y != -1) { pixelPositions.add(pixelPos); } } Arrays.fill(values, 0.0f); Arrays.fill(valid, false); if (tt == StreamTokenizer.TT_EOF) { break; } else if (tt == StreamTokenizer.TT_EOL) { column = 0; } } else if (tt == StreamTokenizer.TT_WORD) { final String token = st.sval; int headerText = -1; if ("x".equalsIgnoreCase(token) || "pixel-x".equalsIgnoreCase(token) || "pixel_x".equalsIgnoreCase(token)) { indices[0] = column; headerText = 0; } else if ("y".equalsIgnoreCase(token) || "pixel-y".equalsIgnoreCase(token) || "pixel_y".equalsIgnoreCase(token)) { indices[1] = column; headerText = 1; } else if ("lat".equalsIgnoreCase(token) || "latitude".equalsIgnoreCase(token)) { indices[2] = column; headerText = 2; } else if ("lon".equalsIgnoreCase(token) || "long".equalsIgnoreCase(token) || "longitude".equalsIgnoreCase(token)) { indices[3] = column; headerText = 3; } else { for (int i = 0; i < 4; i++) { if (column == indices[i]) { try { values[i] = Float.parseFloat(token); valid[i] = true; break; } catch (NumberFormatException ignore) { } } } } if (!headerAvailable && headerText >= 0) { for (int i = 0; i < indices.length; i++) { if (headerText != i) { indices[i] = -1; } } headerAvailable = true; } column++; } else { Debug.assertTrue(false); } } } finally { reader.close(); fileReader.close(); } Geometry geometry = null; if (!pixelPositions.isEmpty()) { geometry = createGeometry(pixelPositions); } if (geometry == null) { return null; } CoordinateReferenceSystem modelCrs = ImageManager.getModelCrs(geoCoding); AffineTransform imageToModelTransform = ImageManager.getImageToModelTransform(geoCoding); GeometryCoordinateSequenceTransformer transformer = new GeometryCoordinateSequenceTransformer(); transformer.setMathTransform(new AffineTransform2D(imageToModelTransform)); transformer.setCoordinateReferenceSystem(modelCrs); try { geometry = transformer.transform(geometry); } catch (TransformException ignored) { return null; } String name = FileUtils.getFilenameWithoutExtension(file); findUniqueVectorDataNodeName(name, product.getVectorDataGroup()); SimpleFeatureType simpleFeatureType = PlainFeatureFactory.createDefaultFeatureType(modelCrs); DefaultFeatureCollection featureCollection = new DefaultFeatureCollection(name, simpleFeatureType); VectorDataNode vectorDataNode = new VectorDataNode(name, featureCollection); String style = vectorDataNode.getDefaultStyleCss(); SimpleFeature simpleFeature = PlainFeatureFactory.createPlainFeature(simpleFeatureType, name, geometry, style); featureCollection.add(simpleFeature); return vectorDataNode; } private static Geometry createGeometry(ArrayList<PixelPos> pixelPositions) { GeometryFactory geometryFactory = new GeometryFactory(); ArrayList<Coordinate> coordinates = new ArrayList<Coordinate>(); PixelPos pixelPos0 = pixelPositions.get(0); coordinates.add(new Coordinate(pixelPos0.x, pixelPos0.y)); PixelPos pixelPos1 = null; for (int i = 1; i < pixelPositions.size(); i++) { pixelPos1 = pixelPositions.get(i); coordinates.add(new Coordinate(pixelPos1.x, pixelPos1.y)); } if (pixelPos1 != null && pixelPos1.distanceSq(pixelPos0) < 1.0e-5) { coordinates.add(coordinates.get(0)); } if (coordinates.get(0).equals(coordinates.get(coordinates.size() - 1))) { return geometryFactory.createLinearRing(coordinates.toArray(new Coordinate[coordinates.size()])); } else { return geometryFactory.createLineString(coordinates.toArray(new Coordinate[coordinates.size()])); } } private static StreamTokenizer createConfiguredTokenizer(LineNumberReader reader) { final StreamTokenizer st = new StreamTokenizer(reader); st.resetSyntax(); st.eolIsSignificant(true); st.lowerCaseMode(true); st.commentChar('#'); st.whitespaceChars(' ', ' '); st.whitespaceChars('\t', '\t'); st.wordChars(33, 255); return st; } } /** * Operator SPI. */ public static class Spi extends OperatorSpi { public Spi() { super(ImportVectorOp.class); } } }
gpl-3.0
DavidServn/RESTfulWS
src/main/java/org/davidservin/restfulws/utm/config/RootContextConfig.java
4557
package org.davidservin.restfulws.utm.config; import java.util.Properties; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.stereotype.Controller; import org.springframework.util.ErrorHandler; import org.springframework.web.bind.annotation.ControllerAdvice; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; @Configuration @EnableAsync @EnableScheduling @ComponentScan( basePackageClasses = { org.davidservin.restfulws.utm.web.ComponentPackageMaker.class, org.davidservin.restfulws.utm.repository.ComponentPackageMaker.class, org.davidservin.restfulws.utm.service.ComponentPackageMaker.class, org.davidservin.restfulws.utm.component.ComponentPackageMaker.class }, excludeFilters = @ComponentScan.Filter({ Controller.class, ControllerAdvice.class})) public class RootContextConfig implements AsyncConfigurer, SchedulingConfigurer { private static final Logger logger = LogManager.getLogger(); private static final Logger schedulingLogger = LogManager.getLogger(String.format("%s-schedue", logger.getName())); @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.findAndRegisterModules(); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false); return mapper; } @Bean public Jaxb2Marshaller jaxb2Marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setPackagesToScan(new String[] { "org.davidservin.restfulws.utm.model" }); return marshaller; } @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { TaskScheduler taskScheduler = this.taskScheduler(); taskRegistrar.setTaskScheduler(taskScheduler); } @Override public Executor getAsyncExecutor() { Executor executor = this.taskScheduler(); return executor; } @Bean public ThreadPoolTaskScheduler taskScheduler() { ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setPoolSize(20); taskScheduler.setThreadNamePrefix("job-"); taskScheduler.setAwaitTerminationSeconds(60); taskScheduler.setWaitForTasksToCompleteOnShutdown(true); taskScheduler.setErrorHandler(new ErrorHandler() { @Override public void handleError(Throwable t) { schedulingLogger.error("Unknown handling job {}", t); } }); taskScheduler.setRejectedExecutionHandler(new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { schedulingLogger.error("Job rejected {}", r); } }); return taskScheduler; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return null; } @Bean public JavaMailSender javaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost("smtp-mail.outlook.com"); mailSender.setPort(587); mailSender.setUsername("puchipupul@hotmail.com"); mailSender.setPassword("DESPDESP123"); Properties mailProperties = mailSender.getJavaMailProperties(); mailProperties.put("mail.transport.protocol", "smtp"); mailProperties.put("mail.smtp.auth", "true"); mailProperties.put("mail.smtp.starttls.enable", "true"); mailProperties.put("mail.debug", "false"); return mailSender; } }
gpl-3.0
lucasmauricio/service-discovery
src/main/java/br/com/macs/poc/registration/controller/dto/AssetDto.java
722
package br.com.macs.poc.registration.controller.dto; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.URL; public class AssetDto { private String id; @NotNull private String name; @NotNull @URL private String address; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "[id=\"" + id + "\", name=\"" + name + "\", address=\"" + address + "\"]"; } }
gpl-3.0
onemoonsci/nmrfxprocessor
src/main/java/org/nmrfx/processor/datasets/peaks/PeakNetworkMatch.java
21601
/* * NMRFx Processor : A Program for Processing NMR Data * Copyright (C) 2004-2017 One Moon Scientific, Inc., Westfield, N.J., USA * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.nmrfx.processor.datasets.peaks; import org.nmrfx.processor.optimization.BipartiteMatcher; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.optim.InitialGuess; import org.apache.commons.math3.optim.MaxEval; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.optim.SimpleBounds; import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; import org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction; import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.BOBYQAOptimizer; /** * * @author brucejohnson */ public class PeakNetworkMatch { final PeakList iList; final PeakList jList; final double[][] positions; double[] optOffset = null; MatchResult matchResult = null; public PeakNetworkMatch(final PeakList iList, final PeakList jList) { this.iList = iList; this.jList = jList; this.positions = null; } public PeakNetworkMatch(final PeakList iList, double[][] positions) { this.iList = iList; this.jList = null; this.positions = positions; } public PeakNetworkMatch(final String iListName, final String jListName) { this.iList = PeakList.get(iListName); this.jList = PeakList.get(jListName); this.positions = null; } public double[] getOptOffset() { return optOffset; } public void bpMatchPeaks() { double[] initialOffset = new double[2]; bpMatchPeaks("H1", "13C", 0.1, 3.0, initialOffset, false, null); } // fixme need to pass in array of dimNames to allow for varying dimensions public void bpMatchPeaks(final String dimName0, final String dimName1, final double tol0, final double tol1, double[] initialOffset, boolean optimizeMatch, final double[][] boundary) { String[][] dimNames = new String[2][2]; dimNames[0][0] = dimName0; dimNames[0][1] = dimName1; dimNames[1][0] = dimName0; dimNames[1][1] = dimName1; double[][] tols = new double[2][2]; tols[0][0] = tol0; tols[0][1] = tol1; tols[1][0] = tol0; tols[1][1] = tol1; double[][] offsets = new double[2][2]; System.arraycopy(initialOffset, 0, offsets[0], 0, offsets[0].length); bpMatchPeaks(dimNames, tols, offsets, optimizeMatch, 1.0, boundary); optOffset = new double[offsets[0].length]; System.arraycopy(offsets[0], 0, optOffset, 0, optOffset.length); } void bpMatchPeaks(String[][] dimNames, double[][] tols, double[][] offsets, boolean optimizeMatch, double tolMul, final double[][] boundary) { // should check for "deleted" peaks String[] dimNamesI, dimNamesJ; int nDim = iList.nDim; dimNamesI = dimNames[0]; dimNamesJ = dimNames[1]; boolean matched = true; int[] dimsI; int[] dimsJ; double[] tol = new double[nDim]; int nDimJ = jList.nDim; if ((dimNamesI == null) || (dimNamesI.length == 0)) { dimsI = new int[nDim]; dimsJ = new int[nDimJ]; for (int k = 0; k < dimsI.length; k++) { dimsI[k] = dimsJ[k] = k; } } else { if ((dimNamesJ == null) || (dimNamesJ.length == 0)) { dimNamesJ = dimNamesI; } else if (dimNamesJ.length != dimNamesI.length) { throw new IllegalArgumentException("Number of dims specified for first list not same as for second list"); } dimsI = new int[dimNamesI.length]; dimsJ = new int[dimNamesI.length]; for (int k = 0; k < dimsI.length; k++) { dimsI[k] = -1; dimsJ[k] = -1; tol[k] = tols[0][k] > tols[1][k] ? tols[0][k] : tols[1][k]; for (int i = 0; i < nDim; i++) { if (dimNamesI[k].equals(iList.getSpectralDim(i).getDimName())) { dimsI[k] = i; } } for (int i = 0; i < nDimJ; i++) { if (dimNamesJ[k].equals(jList.getSpectralDim(i).getDimName())) { dimsJ[k] = i; } } if ((dimsI[k] == -1) || (dimsJ[k] == -1)) { matched = false; break; } } if (!matched) { throw new IllegalArgumentException("Peak Label doesn't match template label"); } } List<MatchItem> iMList = getMatchingItems(iList, dimsI, boundary); List<MatchItem> jMList = getMatchingItems(jList, dimsJ, boundary); if (optimizeMatch) { optimizeMatch(iMList, offsets[0], jMList, offsets[1], tol, 0, 0.0, 1.0); } matchResult = doBPMatch(iMList, offsets[0], jMList, offsets[1], tol, true); System.out.println(matchResult.score); // int[] matching = matchResult.matching; // TclObject resultList = TclList.newInstance(); // for (int i = 0; i < iMList.size(); i++) { // MatchItem iItem = iMList.get(i); // if ((matching[i] >= 0) && (matching[i] < jMList.size())) { // MatchItem jItem = jMList.get(matching[i]); // Peak iPeak = (Peak) iList.getPeak(iItem.itemIndex); // Peak jPeak = (Peak) jList.getPeak(jItem.itemIndex); // double deltaSqSum = getMatchingDistanceSq(iItem, offsets[0], jItem, offsets[1], tol); // double delta = Math.sqrt(deltaSqSum); // TclList.append(interp, resultList, TclString.newInstance(iPeak.getIdNum() + " " + jPeak.getIdNum() + " " + delta)); // } // // } // TclObject result = TclList.newInstance(); // TclList.append(interp, result, TclString.newInstance("score")); // TclList.append(interp, result, TclDouble.newInstance(matchResult.score)); // TclList.append(interp, result, TclString.newInstance("nMatches")); // TclList.append(interp, result, TclInteger.newInstance(matchResult.nMatches)); // TclList.append(interp, result, TclString.newInstance("offsets")); // TclObject offsetList = TclList.newInstance(); // for (int k = 0; k < dimsI.length; k++) { // TclList.append(interp, offsetList, TclDouble.newInstance(offsets[0][k])); // } // // TclList.append(interp, result, offsetList); // TclList.append(interp, result, TclString.newInstance("matches")); // TclList.append(interp, result, resultList); } void bpMatchList(String[] dimNamesI, double[][] tols, double[][] offsets, boolean optimizeMatch, double tolMul, final double[][] boundary) { // should check for "deleted" peaks boolean matched = true; int[] dimsI; int nDim = dimNamesI.length; double[] tol = new double[nDim]; if (dimNamesI.length == 0) { dimsI = new int[nDim]; for (int k = 0; k < dimsI.length; k++) { dimsI[k] = k; } } else { dimsI = new int[dimNamesI.length]; for (int k = 0; k < dimsI.length; k++) { dimsI[k] = -1; tol[k] = tols[0][k]; for (int i = 0; i < nDim; i++) { if (dimNamesI[k].equals(iList.getSpectralDim(i).getDimName())) { dimsI[k] = i; } } if (dimsI[k] == -1) { matched = false; break; } } if (!matched) { throw new IllegalArgumentException("Peak Label doesn't match template label"); } } List<MatchItem> iMList = getMatchingItems(iList, dimsI, boundary); List<MatchItem> jMList = getMatchingItems(positions); if (optimizeMatch) { for (int iCycle = 0; iCycle < 2; iCycle++) { double searchMin = -tolMul * tol[0] / (iCycle + 1); double searchMax = tolMul * tol[0] / (iCycle + 1); optimizeMatch(iMList, offsets[0], jMList, offsets[1], tol, 0, searchMin, searchMax); searchMin = -tolMul * tol[1] / (iCycle + 1); searchMax = tolMul * tol[1] / (iCycle + 1); optimizeMatch(iMList, offsets[0], jMList, offsets[1], tol, 1, searchMin, searchMax); } } matchResult = doBPMatch(iMList, offsets[0], jMList, offsets[1], tol, false); int[] matching = matchResult.matching; for (int i = 0; i < iMList.size(); i++) { MatchItem iItem = iMList.get(i); Peak iPeak = (Peak) iList.getPeak(iItem.itemIndex); if ((matching[i] >= 0) && (matching[i] < jMList.size())) { MatchItem jItem = jMList.get(matching[i]); double deltaSqSum = getMatchingDistanceSq(iItem, offsets[0], jItem, offsets[1], tol); double delta = Math.sqrt(deltaSqSum); String matchString = iPeak.getIdNum() + " " + jItem.itemIndex + " " + delta; } else { String matchString = iPeak.getIdNum() + " -1 0"; } } } double getPeakDistanceSq(Peak iPeak, int[] dimsI, double[] iOffsets, Peak jPeak, int[] dimsJ, double[] tol, double[] jOffsets) { double deltaSqSum = 0.0; for (int k = 0; k < dimsI.length; k++) { double iCtr = iPeak.getPeakDim(dimsI[k]).getChemShift(); double jCtr = jPeak.getPeakDim(dimsJ[k]).getChemShift(); double delta = ((iCtr + iOffsets[k]) - (jCtr + jOffsets[k])) / tol[k]; deltaSqSum += delta * delta; } return deltaSqSum; } public double getLinkedSum(final int iIndex, final int jIndex) { double deltaSqSum = 0.0; Peak iPeak = iList.getPeak(iIndex); Peak jPeak = jList.getPeak(jIndex); int iDim = 0; int iDim2 = 1; int jDim = 0; int jDim2 = 1; PeakDim iPeakDim = iPeak.getPeakDim(iDim); PeakDim jPeakDim = jPeak.getPeakDim(jDim); List<PeakDim> iPeakDims = PeakList.getLinkedPeakDims(iPeak, iDim); List<PeakDim> jPeakDims = PeakList.getLinkedPeakDims(jPeak, jDim); List<MatchItem> iPPMs = new ArrayList<>(); int i = 0; for (PeakDim peakDim : iPeakDims) { if ((peakDim != iPeakDim) && (peakDim.getSpectralDim() == iDim)) { Peak peak = peakDim.getPeak(); PeakDim peakDim2 = peak.getPeakDim(iDim2); MatchItem matchItem = new MatchItem(i, peakDim2.getChemShift()); //System.out.println(i + " " + peak.getIdNum() + " " + peakDim2.getChemShift()); iPPMs.add(matchItem); } i++; } i = 0; List<MatchItem> jPPMs = new ArrayList<>(); for (PeakDim peakDim : jPeakDims) { if ((peakDim != jPeakDim) && (peakDim.getSpectralDim() == jDim)) { Peak peak = peakDim.getPeak(); PeakDim peakDim2 = peak.getPeakDim(jDim2); MatchItem matchItem = new MatchItem(i, peakDim2.getChemShift()); //System.out.println(i + " " + peak.getIdNum() + " " + peakDim2.getChemShift()); jPPMs.add(matchItem); } i++; } //System.out.println(iIndex + " nI " + iPeakDims.size() + " " + iPPMs.size() + " " + jIndex + " nJ " + jPeakDims.size() + " " + jPPMs.size()); double[] iOffsets = {0.0}; double[] jOffsets = {0.0}; double[] tol = {0.1}; MatchResult result = doBPMatch(iPPMs, iOffsets, jPPMs, jOffsets, tol, false); //System.out.println(matchResult.score + " " + matchResult.nMatches); return result.score; } double getMatchingDistanceSq(MatchItem iItem, double[] iOffsets, MatchItem jItem, double[] jOffsets, double[] tol) { double deltaSqSum = 0.0; for (int k = 0; k < iItem.values.length; k++) { double iCtr = iItem.values[k]; double jCtr = jItem.values[k]; double delta = ((iCtr + iOffsets[k]) - (jCtr + jOffsets[k])) / tol[k]; deltaSqSum += delta * delta; } return deltaSqSum; } static class MatchItem { final int itemIndex; final double[] values; MatchItem(final int itemIndex, final double[] values) { this.itemIndex = itemIndex; this.values = values; } MatchItem(final int itemIndex, final double value) { this.itemIndex = itemIndex; double[] valueArray = {value}; this.values = valueArray; } } List<MatchItem> getMatchingItems(PeakList peakList, int[] dims, final double[][] boundary) { List<MatchItem> matchList = new ArrayList<>(); int nPeaks = peakList.size(); HashSet usedPeaks = new HashSet(); for (int j = 0; j < nPeaks; j++) { Peak peak = (Peak) peakList.getPeak(j); if (peak.getStatus() < 0) { usedPeaks.add(peak); } else if (boundary != null) { for (int iDim = 0; iDim < dims.length; iDim++) { double ppm = peak.getPeakDim(iDim).getChemShiftValue(); if ((ppm < boundary[iDim][0]) || (ppm > boundary[iDim][1])) { usedPeaks.add(peak); break; } } } } for (int j = 0; j < nPeaks; j++) { Peak peak = (Peak) peakList.getPeak(j); if (usedPeaks.contains(peak)) { continue; } double[] values = new double[dims.length]; for (int iDim = 0; iDim < dims.length; iDim++) { List<PeakDim> linkedPeakDims = PeakList.getLinkedPeakDims(peak, dims[iDim]); double ppmCenter = 0.0; for (PeakDim peakDim : linkedPeakDims) { Peak peak2 = peakDim.getPeak(); usedPeaks.add(peak2); ppmCenter += peakDim.getChemShiftValue(); } values[iDim] = ppmCenter / linkedPeakDims.size(); } MatchItem matchItem = new MatchItem(j, values); matchList.add(matchItem); } return matchList; } List<MatchItem> getMatchingItems(double[][] positions) { List<MatchItem> matchList = new ArrayList<>(); for (int j = 0; j < positions.length; j++) { MatchItem matchItem = new MatchItem(j, positions[j]); matchList.add(matchItem); } return matchList; } class MatchResult { final double score; final int nMatches; final int[] matching; MatchResult(final int[] matching, final int nMatches, final double score) { this.matching = matching; this.score = score; this.nMatches = nMatches; } } private MatchResult doBPMatch(List<MatchItem> iMList, final double[] iOffsets, List<MatchItem> jMList, final double[] jOffsets, double[] tol, final boolean doLinkMatch) { int iNPeaks = iMList.size(); int jNPeaks = jMList.size(); int nPeaks = iNPeaks + jNPeaks; BipartiteMatcher bpMatch = new BipartiteMatcher(); bpMatch.reset(nPeaks, true); // fixme should we add reciprocol match for (int iPeak = 0; iPeak < iNPeaks; iPeak++) { bpMatch.setWeight(iPeak, jNPeaks + iPeak, -1.0); } for (int jPeak = 0; jPeak < jNPeaks; jPeak++) { bpMatch.setWeight(iNPeaks + jPeak, jPeak, -1.0); } double minDelta = 10.0; int nMatches = 0; // fixme // check for deleted peaks // check for peaks outside of a specified region for (int iPeak = 0; iPeak < iNPeaks; iPeak++) { double minDeltaSq = Double.MAX_VALUE; for (int jPeak = 0; jPeak < jNPeaks; jPeak++) { double weight = Double.NEGATIVE_INFINITY; MatchItem matchI = iMList.get(iPeak); MatchItem matchJ = jMList.get(jPeak); double deltaSqSum = getMatchingDistanceSq(matchI, iOffsets, matchJ, jOffsets, tol); if (deltaSqSum < minDeltaSq) { minDeltaSq = deltaSqSum; } if (deltaSqSum < minDelta) { weight = Math.exp(-deltaSqSum); } if (weight != Double.NEGATIVE_INFINITY) { if (doLinkMatch) { //System.out.println("weigh"); double linkedSum = getLinkedSum(matchI.itemIndex, matchJ.itemIndex); weight += linkedSum / 10.0; //System.out.println(iPeak + " " + jPeak + " " + deltaSqSum + " " + linkedSum); } bpMatch.setWeight(iPeak, jPeak, weight); nMatches++; } } } int[] matching = bpMatch.getMatching(); double score = 0.0; nMatches = 0; for (int i = 0; i < iNPeaks; i++) { MatchItem matchI = iMList.get(i); if ((matching[i] >= 0) && (matching[i] < jMList.size())) { MatchItem matchJ = jMList.get(matching[i]); double deltaSqSum = getMatchingDistanceSq(matchI, iOffsets, matchJ, jOffsets, tol); //System.out.println(i + " " + Math.sqrt(deltaSqSum)); if (deltaSqSum < minDelta) { score += 1.0 - Math.exp(-deltaSqSum); } else { score += 1.0; } nMatches++; } else { score += 1.0; } } MatchResult result = new MatchResult(matching, nMatches, score); return result; } private void optimizeMatch(final List<MatchItem> iMList, final double[] iOffsets, final List<MatchItem> jMList, final double[] jOffsets, final double[] tol, int minDim, double min, double max) { class MatchFunction implements MultivariateFunction { double[] bestMatch = null; double bestValue; MatchFunction() { bestValue = Double.MAX_VALUE; } @Override public double value(double[] x) { double[] minOffsets = new double[iOffsets.length]; for (int i = 0; i < minOffsets.length; i++) { minOffsets[i] = iOffsets[i] + x[i]; } MatchResult matchResult = doBPMatch(iMList, minOffsets, jMList, jOffsets, tol, true); // System.out.println("score " + matchResult.score); if (matchResult.score < bestValue) { bestValue = matchResult.score; if (bestMatch == null) { bestMatch = new double[x.length]; } System.arraycopy(x, 0, bestMatch, 0, bestMatch.length); } return matchResult.score; } } MatchFunction f = new MatchFunction(); int n = iOffsets.length; double initialTrust = 0.5; double stopTrust = 1.0e-4; int nInterp = n + 2; int nSteps = 100; double[][] boundaries = new double[2][n]; for (int i = 0; i < n; i++) { boundaries[0][i] = -max; boundaries[1][i] = max; } BOBYQAOptimizer optimizer = new BOBYQAOptimizer(nInterp, initialTrust, stopTrust); double[] initialGuess = new double[iOffsets.length]; PointValuePair result; try { result = optimizer.optimize( new MaxEval(nSteps), new ObjectiveFunction(f), GoalType.MINIMIZE, new SimpleBounds(boundaries[0], boundaries[1]), new InitialGuess(initialGuess)); } catch (TooManyEvaluationsException e) { result = new PointValuePair(f.bestMatch, f.bestValue); } int nEvaluations = optimizer.getEvaluations(); double finalValue = result.getValue(); double[] finalPoint = result.getPoint(); for (int i = 0; i < finalPoint.length; i++) { iOffsets[i] += finalPoint[i]; } System.out.println("n " + nEvaluations + " " + finalValue); for (double v : iOffsets) { System.out.println(v); } } }
gpl-3.0
vemacs/Skype4J
src/main/java/com/samczsun/skype4j/internal/UserImpl.java
2277
package com.samczsun.skype4j.internal; import com.samczsun.skype4j.chat.Chat; import com.samczsun.skype4j.chat.ChatMessage; import com.samczsun.skype4j.user.User; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; public class UserImpl implements User { private String username; private final Chat chat; private Role role = Role.USER; private final List<ChatMessage> messages = new CopyOnWriteArrayList<>(); private final Map<String, ChatMessage> messageMap = new ConcurrentHashMap<>(); public UserImpl(String username, Chat chat) { this.username = username; this.chat = chat; } public UserImpl(Chat chat) { this.chat = chat; } @Override public String getUsername() { return username; } @Override public String getDisplayName() { return null; } @Override public Role getRole() { return this.role; } @Override public void setRole(Role role) { this.role = role; } @Override public Chat getChat() { return this.chat; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((username == null) ? 0 : username.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UserImpl other = (UserImpl) obj; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; return true; } @Override public List<ChatMessage> getSentMessages() { return Collections.unmodifiableList(messages); } @Override public ChatMessage getMessageById(String id) { return messageMap.get(id); } public void onMessage(ChatMessage message) { this.messages.add(message); this.messageMap.put(message.getClientId(), message); } }
gpl-3.0
classfoo/onyx
org.classfoo.onyx/src/main/java/org/classfoo/onyx/impl/OnyxUtils.java
7803
package org.classfoo.onyx.impl; import java.awt.Color; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.commons.codec.binary.Base64; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; /** * Onyx Utility Class * @author ClassFoo * */ public class OnyxUtils { public static final Logger logger = LoggerFactory.getLogger(OnyxUtils.class); /** * return error information map to front ends * @param message * @param params * @return */ public static Map<String, Object> returnError(String message, Object... params) { HashMap<String, Object> error = new HashMap<String, Object>(2); error.put("type", "error"); error.put("message", message); logger.error(message); return error; } /** * return error information map to front ends * @param args * @param message * @param params * @return */ public static Map<String, Object> returnError(Map<String, Object> args, String message, Object... params) { HashMap<String, Object> error = new HashMap<String, Object>(args.size() + 2); error.putAll(args); error.put("type", "error"); error.put("message", message); logger.error(message); return error; } /** * 获取压缩后的uuid * @return */ public static String getCompressedUUID() { UUID uuid = UUID.randomUUID(); return getCompressedUUID(uuid); } private static String getCompressedUUID(UUID uuid) { byte[] byUuid = new byte[16]; long least = uuid.getLeastSignificantBits(); long most = uuid.getMostSignificantBits(); long2bytes(most, byUuid, 0); long2bytes(least, byUuid, 8); return Base64.encodeBase64URLSafeString(byUuid); } private static void long2bytes(long value, byte[] bytes, int offset) { for (int i = 7; i > -1; i--) { bytes[offset++] = (byte) ((value >> 8 * i) & 0xFF); } } /** * create random uuid with given prefix * @param prefix * @return */ public static String getRandomUUID(String prefix) { return prefix + UUID.randomUUID().toString().replaceAll("-", ""); } /** * read json object from web request parameter map * @param options * @param key * @param type * @return */ public static <T> T readJson(Map<String, Object> options, String key, Class<T> type) { try { String v = MapUtils.getString(options, key); if (String.class.equals(type)) { return type.cast(v); } ObjectMapper om = new ObjectMapper(); T list = om.readValue(v, type); return list; } catch (Exception e) { throw new RuntimeException("parse json failed!", e); } } private static final String[] COLORRGBS = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF" }; /** * get random color string for html css * @return */ public static final String getRandomColor() { Random rand = new Random(); float r = rand.nextFloat(); float g = rand.nextFloat(); float b = rand.nextFloat(); Color randomColor = new Color(r, g, b); return '#' + int2hex(randomColor.getRed()) + int2hex(randomColor.getGreen()) + int2hex(randomColor.getBlue()); } private static String int2hex(int c) { return COLORRGBS[c]; } /** * remove blanks in text * @param text * @return */ public static String removeBlank(String text) { if (StringUtils.isBlank(text)) { return text; } return text.replaceAll("/s*", ""); } /** * Integer.SIZE = 32; */ static int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2); /** * smallest hash map size */ static int SMALLEST_HASHMAP_SIZE = 3; /** * Guaua like HashMap initialCapacity size,base on default 0.75 loadFactor,in order to avoid rehash * @param expectedSize * @return */ public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) { return new HashMap<K, V>(capacity(expectedSize)); } static int capacity(int expectedSize) {//expectedSize = 7,return 10 if (expectedSize < SMALLEST_HASHMAP_SIZE) { checkNonnegative(expectedSize); return expectedSize + 1; } if (expectedSize < MAX_POWER_OF_TWO) { // This is the calculation used in JDK8 to resize when a putAll // happens; it seems to be the most conservative calculation we // can make. 0.75 is the default load factor. return (int) ((float) expectedSize / 0.75F + 1.0F); } // any large value return Integer.MAX_VALUE; } private static int checkNonnegative(int expectedSize) { if (expectedSize < 0) { throw new RuntimeException("expectedSize<0!"); } return expectedSize; } /** * global thread pool */ private static ExecutorService THREADPOOL = null; static { ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("pool-%d").build(); THREADPOOL = new ThreadPoolExecutor(4, 8, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(64), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); } /** * Run single runnable * @param runnable */ public static void run(Runnable runnable) { THREADPOOL.execute(runnable); } }
gpl-3.0
bichong/bichong
src/xi/zhao/wallet/ui/AddressBookActivity.java
4275
/* * Copyright 2011-2013 the original author or authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package xi.zhao.wallet.ui; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.MenuItem; import com.google.bitcoin.core.Address; import com.google.bitcoin.core.ECKey; import xi.zhao.wallet.Constants; import xi.zhao.wallet.R; import xi.zhao.wallet.util.ViewPagerTabs; /** * @author Andreas Schildbach */ public final class AddressBookActivity extends AbstractWalletActivity { public static void start(final Context context, final boolean sending) { final Intent intent = new Intent(context, AddressBookActivity.class); intent.putExtra(EXTRA_SENDING, sending); context.startActivity(intent); } private static final String EXTRA_SENDING = "sending"; private WalletAddressesFragment walletAddressesFragment; private SendingAddressesFragment sendingAddressesFragment; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.address_book_content); final ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); final ViewPager pager = (ViewPager) findViewById(R.id.address_book_pager); final FragmentManager fm = getSupportFragmentManager(); if (pager != null) { final ViewPagerTabs pagerTabs = (ViewPagerTabs) findViewById(R.id.address_book_pager_tabs); pagerTabs.addTabLabels(R.string.address_book_list_receiving_title, R.string.address_book_list_sending_title); final PagerAdapter pagerAdapter = new PagerAdapter(fm); pager.setAdapter(pagerAdapter); pager.setOnPageChangeListener(pagerTabs); final int position = getIntent().getBooleanExtra(EXTRA_SENDING, true) == true ? 1 : 0; pager.setCurrentItem(position); pager.setPageMargin(2); pager.setPageMarginDrawable(R.color.bg_less_bright); pagerTabs.onPageSelected(position); pagerTabs.onPageScrolled(position, 0, 0); walletAddressesFragment = new WalletAddressesFragment(); sendingAddressesFragment = new SendingAddressesFragment(); } else { walletAddressesFragment = (WalletAddressesFragment) fm.findFragmentById(R.id.wallet_addresses_fragment); sendingAddressesFragment = (SendingAddressesFragment) fm.findFragmentById(R.id.sending_addresses_fragment); } updateFragments(); } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } /* private */void updateFragments() { final List<ECKey> keys = getWalletApplication().getWallet().getKeys(); final ArrayList<Address> addresses = new ArrayList<Address>(keys.size()); for (final ECKey key : keys) { final Address address = key.toAddress(Constants.NETWORK_PARAMETERS); addresses.add(address); } sendingAddressesFragment.setWalletAddresses(addresses); } private class PagerAdapter extends FragmentStatePagerAdapter { public PagerAdapter(final FragmentManager fm) { super(fm); } @Override public int getCount() { return 2; } @Override public Fragment getItem(final int position) { if (position == 0) return walletAddressesFragment; else return sendingAddressesFragment; } } }
gpl-3.0
MarvinMenzerath/WebCrawler
src/main/java/eu/menzerath/webcrawler/Main.java
4087
package eu.menzerath.webcrawler; import javax.net.ssl.*; import java.awt.*; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; public class Main { public static final String APPLICATION_NAME = "WebCrawler"; public static final String APPLICATION_VERSION = "1.3"; public static final String APPLICATION_URL = "https://github.com/MarvinMenzerath/WebCrawler"; public static final String APPLICATION_UA = Main.APPLICATION_NAME + "/" + Main.APPLICATION_VERSION + " (" + Main.APPLICATION_URL + ")"; public static final List<String> fileRegEx = new ArrayList<>(); public static final String noPageRegEx = ".*?\\#.*"; /** * Start: Open GUI or start on the console * @param args [0] --> URL to crawl */ public static void main(String[] args) { init(); sayHello(); if (args.length == 0) { if (GraphicsEnvironment.isHeadless()) { // Running on a setup without graphical desktop and no arguments passed: show the needed arguments System.out.println("Please pass the URL to crawl as an argument to this application: \"java -jar WebCrawler.jar http://my-website.com\""); System.exit(1); } else { // Otherwise: Open the GUI GuiApplication.startGUI(); } } else if (args.length == 1) { new WebCrawler(args[0].trim(), null).start(); } } /** * Init some important variables and allow usage of any SSL-certificate */ private static void init() { /** * Add some File-RegExs */ fileRegEx.add(".*?\\.png"); fileRegEx.add(".*?\\.jpg"); fileRegEx.add(".*?\\.jpeg"); fileRegEx.add(".*?\\.gif"); fileRegEx.add(".*?\\.zip"); fileRegEx.add(".*?\\.7z"); fileRegEx.add(".*?\\.rar"); fileRegEx.add(".*?\\.css.*"); fileRegEx.add(".*?\\.js.*"); /** * Allow usage of _any_ SSL-certificate */ // Create a all-trusting TrustManager TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) {} public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; // Install the all-trusting TrustManager SSLContext sc; try { sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (NoSuchAlgorithmException | KeyManagementException e) { System.out.println("Unable to install the all-trusting TrustManager"); } // Create & Install a all-trusting HostnameVerifier HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting HostnameVerifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); } /** * Show information about this program to the user */ private static void sayHello() { String lineVersion = APPLICATION_NAME + " v" + APPLICATION_VERSION; for (int i = lineVersion.length(); i < 37; i++) lineVersion += " "; System.out.println("#############################################"); System.out.println("### " + lineVersion + " ###"); System.out.println("### ###"); System.out.println("### © 2014: Marvin Menzerath ###"); System.out.println("### " + APPLICATION_URL.substring(8) + " ###"); System.out.println("#############################################\n"); } }
gpl-3.0
joseoliv/Cyan
error/ErrorInMetaobjectException.java
322
package error; public class ErrorInMetaobjectException extends RuntimeException { public ErrorInMetaobjectException(String message) { this.message = message; } @Override public String getMessage() { return message; } /** * */ private static final long serialVersionUID = 1L; private String message; }
gpl-3.0
irq0/jext2
src/fusejext2/Util.java
2118
/* * Copyright (c) 2011 Marcel Lauhoff. * * This file is part of jext2. * * jext2 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jext2 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jext2. If not, see <http://www.gnu.org/licenses/>. */ package fusejext2; import java.util.Date; import jext2.DataInode; import jext2.Inode; import jext2.Superblock; import fuse.EntryParam; import fuse.Stat; import fuse.Timespec; public class Util { public static Timespec dateToTimespec(Date date) { Timespec tim = new Timespec(); tim.setSec((int)(date.getTime() / 1000)); tim.setNsec(0); return tim; } public static Date timespecToDate(Timespec time) { return new Date(time.getSec()*1000 + time.getNsec()/1000); } public static Stat inodeToStat(Superblock superblock, Inode inode) { Stat s = new Stat(); s.setUid(inode.getUidLow()); s.setGid(inode.getGidLow()); s.setIno(inode.getIno()); s.setMode(inode.getMode().numeric()); s.setBlksize(superblock.getBlocksize()); s.setNlink(inode.getLinksCount()); s.setSize(inode.getSize()); if (inode.hasDataBlocks()) s.setBlocks(((DataInode)inode).getBlocks()); else s.setBlocks(0); s.setAtim(dateToTimespec(inode.getAccessTime())); s.setCtim(dateToTimespec(inode.getStatusChangeTime())); s.setMtim(dateToTimespec(inode.getModificationTime())); return s; } public static EntryParam inodeToEntryParam(Superblock superblock, Inode inode) { EntryParam e = new EntryParam(); e.setAttr(inodeToStat(superblock, inode)); e.setGeneration(inode.getGeneration()); e.setAttr_timeout(0.0); e.setEntry_timeout(0.0); e.setIno(inode.getIno()); return e; } }
gpl-3.0
desht/pnc-repressurized
src/main/java/me/desht/pneumaticcraft/client/render/pneumatic_armor/upgrade_handler/JetBootsUpgradeHandler.java
5483
package me.desht.pneumaticcraft.client.render.pneumatic_armor.upgrade_handler; import me.desht.pneumaticcraft.api.client.IGuiAnimatedStat; import me.desht.pneumaticcraft.api.client.pneumaticHelmet.IOptionPage; import me.desht.pneumaticcraft.api.client.pneumaticHelmet.IUpgradeRenderHandler; import me.desht.pneumaticcraft.api.item.IItemRegistry; import me.desht.pneumaticcraft.client.gui.pneumatic_armor.GuiJetBootsOptions; import me.desht.pneumaticcraft.client.gui.widget.GuiAnimatedStat; import me.desht.pneumaticcraft.common.config.ArmorHUDLayout; import me.desht.pneumaticcraft.common.item.Itemss; import me.desht.pneumaticcraft.common.recipes.CraftingRegistrator; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class JetBootsUpgradeHandler extends IUpgradeRenderHandler.SimpleToggleableRenderHandler { private static final String[] HEADINGS = new String[] { "S", "SW", "W", "NW", "N", "NE", "E", "SE" }; private String l1, l2, l3, r1, r2, r3; private int widestR; @SideOnly(Side.CLIENT) private IGuiAnimatedStat jbStat; @Override public String getUpgradeName() { return "jetBoots"; } @Override public Item[] getRequiredUpgrades() { return new Item[] { Itemss.upgrades.get(IItemRegistry.EnumUpgrade.JET_BOOTS) }; } @Override public IOptionPage getGuiOptionsPage() { return new GuiJetBootsOptions(this); } @Override public EntityEquipmentSlot getEquipmentSlot() { return EntityEquipmentSlot.FEET; } @Override public void update(EntityPlayer player, int rangeUpgrades) { super.update(player, rangeUpgrades); String g1 = TextFormatting.WHITE.toString(); String g2 = TextFormatting.GREEN.toString(); if (jbStat.isClicked()) { double mx = player.posX - player.lastTickPosX; double my = player.posY - player.lastTickPosY; double mz = player.posZ - player.lastTickPosZ; double v = Math.sqrt(mx * mx + my * my + mz * mz); double vg = Math.sqrt(mx * mx + mz * mz); int heading = MathHelper.floor((double)(player.rotationYaw * 8.0F / 360.0F) + 0.5D) & 0x7; int yaw = ((int)player.rotationYaw + 180) % 360; if (yaw < 0) yaw += 360; BlockPos pos = player.getPosition(); l1 = String.format(" %sSpd: %s%05.2fm/s", g1, g2, v * 20); l2 = String.format(" %sAlt: %s%03dm", g1, g2, pos.getY()); l3 = String.format("%sHead: %s%d° (%s)", g1, g2, yaw, HEADINGS[heading]); r1 = String.format("%sGnd: %s%05.2f", g1, g2, vg * 20); r2 = String.format("%sGnd: %s%dm", g1, g2, pos.getY() - player.world.getHeight(pos.getX(), pos.getZ())); r3 = String.format("%sPch: %s%d°", g1, g2, (int)-player.rotationPitch); FontRenderer fr = Minecraft.getMinecraft().fontRenderer; int wl = Math.max(fr.getStringWidth(l1), Math.max(fr.getStringWidth(l2), fr.getStringWidth(l3))); int wr = Math.max(fr.getStringWidth(r1), Math.max(fr.getStringWidth(r2), fr.getStringWidth(r3))); if (wl + wr + 16 > jbStat.getWidth()) { jbStat.setForcedDimensions(wl + wr + 16, 5 * fr.FONT_HEIGHT); } widestR = Math.max(wr, widestR); } } @Override public void render2D(float partialTicks, boolean helmetEnabled) { super.render2D(partialTicks, helmetEnabled); if (helmetEnabled && jbStat.isClicked()) { FontRenderer fr = Minecraft.getMinecraft().fontRenderer; int xl = jbStat.getBaseX() + 5; int y = jbStat.getBaseY() + fr.FONT_HEIGHT + 8; int xr = jbStat.getBaseX() + jbStat.getWidth() - 5; if (jbStat.isLeftSided()) { xl -= jbStat.getWidth(); xr -= jbStat.getWidth(); } fr.drawStringWithShadow(l1, xl, y, 0x404040); fr.drawStringWithShadow(l2, xl, y + fr.FONT_HEIGHT, 0x404040); fr.drawStringWithShadow(l3, xl, y + fr.FONT_HEIGHT * 2, 0x404040); fr.drawStringWithShadow(r1, xr - widestR, y, 0x404040); fr.drawStringWithShadow(r2, xr - widestR, y + fr.FONT_HEIGHT, 0x404040); fr.drawStringWithShadow(r3, xr - widestR, y + fr.FONT_HEIGHT * 2, 0x404040); } } @Override public IGuiAnimatedStat getAnimatedStat() { if (jbStat == null) { jbStat = new GuiAnimatedStat(null, "Jet Boots", GuiAnimatedStat.StatIcon.of(CraftingRegistrator.getUpgrade(IItemRegistry.EnumUpgrade.JET_BOOTS)), 0x3000AA00, null, ArmorHUDLayout.INSTANCE.jetBootsStat); jbStat.setMinDimensionsAndReset(0, 0); FontRenderer fr = Minecraft.getMinecraft().fontRenderer; int n = fr.getStringWidth(" Spd: 00.00m/s Gnd: 00.00"); jbStat.addPadding(3, n / fr.getStringWidth(" ")); } return jbStat; } @Override public void onResolutionChanged() { jbStat = null; } }
gpl-3.0
djr4488/camera-notifier
src/test/java/org/djr/securus/camera/rest/CameraAuthorizationFilterTest.java
4659
package org.djr.securus.camera.rest; import junit.framework.TestCase; import org.apache.commons.codec.binary.Base64; import org.djr.securus.cdi.logs.LoggerProducer; import org.jglue.cdiunit.AdditionalClasses; import org.jglue.cdiunit.CdiRunner; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.slf4j.Logger; import javax.inject.Inject; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Created by djr4488 on 1/4/17. */ @RunWith(CdiRunner.class) @AdditionalClasses({LoggerProducer.class}) public class CameraAuthorizationFilterTest extends TestCase { @Inject private CameraAuthorizationFilter cameraAuthorizationFilter; @Inject private Logger log; @Test public void testDoFilter() { HttpServletRequest httpReq = mock(HttpServletRequest.class); HttpServletResponse httpResp = mock(HttpServletResponse.class); FilterChain fltChn = mock(FilterChain.class); String base64Auth = "BASIC " + Base64.encodeBase64String("test:test".getBytes()); when(httpReq.getHeader("authorization")).thenReturn(base64Auth); try { cameraAuthorizationFilter.doFilter(httpReq, httpResp, fltChn); verify(fltChn, times(1)).doFilter(httpReq, httpResp); } catch (Exception ex) { log.error("error: ", ex); fail("failed test"); } } @Test public void testDoFilterAuthorizationNull() { HttpServletRequest httpReq = mock(HttpServletRequest.class); HttpServletResponse httpResp = mock(HttpServletResponse.class); FilterChain fltChn = mock(FilterChain.class); String base64Auth = null; when(httpReq.getHeader("authorization")).thenReturn(base64Auth); ArgumentCaptor<HttpServletRequest> httpServletRequestArgumentCaptor = ArgumentCaptor.forClass(HttpServletRequest.class); try { cameraAuthorizationFilter.doFilter(httpReq, httpResp, fltChn); verify(fltChn, times(1)).doFilter(httpServletRequestArgumentCaptor.capture(), any(HttpServletResponse.class)); HttpServletRequest captured = httpServletRequestArgumentCaptor.getValue(); assertNull(captured.getAttribute("userName")); } catch (Exception ex) { log.error("error: ", ex); fail("failed test"); } } @Test public void testDoFilterAuthorizationEmptyString() { HttpServletRequest httpReq = mock(HttpServletRequest.class); HttpServletResponse httpResp = mock(HttpServletResponse.class); FilterChain fltChn = mock(FilterChain.class); String base64Auth = ""; when(httpReq.getHeader("authorization")).thenReturn(base64Auth); ArgumentCaptor<HttpServletRequest> httpServletRequestArgumentCaptor = ArgumentCaptor.forClass(HttpServletRequest.class); try { cameraAuthorizationFilter.doFilter(httpReq, httpResp, fltChn); verify(fltChn, times(1)).doFilter(httpServletRequestArgumentCaptor.capture(), any(HttpServletResponse.class)); HttpServletRequest captured = httpServletRequestArgumentCaptor.getValue(); assertNull(captured.getAttribute("userName")); } catch (Exception ex) { log.error("error: ", ex); fail("failed test"); } } @Test(expected = ServletException.class) public void testDoFilterException() throws IOException, ServletException { HttpServletRequest httpReq = mock(HttpServletRequest.class); HttpServletResponse httpResp = mock(HttpServletResponse.class); FilterChain fltChn = mock(FilterChain.class); String base64Auth = "BASIC " + Base64.encodeBase64String("test:test".getBytes()); when(httpReq.getHeader("authorization")).thenReturn(base64Auth); try { doThrow(new ServletException("test")).when(fltChn).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); cameraAuthorizationFilter.doFilter(httpReq, httpResp, fltChn); verify(fltChn, times(1)).doFilter(httpReq, httpResp); } catch (IOException ex) { log.error("error: ", ex); fail("expected servlet exception"); } } }
gpl-3.0
DJVUpp/Desktop
djuvpp-djvureader-_linux-f9cd57d25c2f/DjVuReader++/src/com/lizardtech/djview/Applet.java
25745
//C- ------------------------------------------------------------------- //C- Java DjVu (r) (v. 0.8) //C- Copyright (c) 2004-2005 LizardTech, Inc. All Rights Reserved. //C- Java DjVu is protected by U.S. Pat. No.C- 6,058,214 and patents //C- pending. //C- //C- This software is subject to, and may be distributed under, the //C- GNU General Public License, Version 2. The license should have //C- accompanied the software or you may obtain a copy of the license //C- from the Free Software Foundation at http://www.fsf.org . //C- //C- The computer code originally released by LizardTech under this //C- license and unmodified by other parties is deemed "the LIZARDTECH //C- ORIGINAL CODE." Subject to any third party intellectual property //C- claims, LizardTech grants recipient a worldwide, royalty-free, //C- non-exclusive license to make, use, sell, or otherwise dispose of //C- the LIZARDTECH ORIGINAL CODE or of programs derived from the //C- LIZARDTECH ORIGINAL CODE in compliance with the terms of the GNU //C- General Public License. This grant only confers the right to //C- infringe patent claims underlying the LIZARDTECH ORIGINAL CODE to //C- the extent such infringement is reasonably necessary to enable //C- recipient to make, have made, practice, sell, or otherwise dispose //C- of the LIZARDTECH ORIGINAL CODE (or portions thereof) and not to //C- any greater extent that may be necessary to utilize further //C- modifications or combinations. //C- //C- The LIZARDTECH ORIGINAL CODE is provided "AS IS" WITHOUT WARRANTY //C- OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED //C- TO ANY WARRANTY OF NON-INFRINGEMENT, OR ANY IMPLIED WARRANTY OF //C- MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. //C- //C- In addition, as a special exception, LizardTech Inc. gives permission //C- to link the code of this program with the proprietary Java //C- implementation provided by Sun (or other vendors as well), and //C- distribute linked combinations including the two. You must obey the //C- GNU General Public License in all respects for all of the code used //C- other than the proprietary Java implementation. If you modify this //C- file, you may extend this exception to your version of the file, but //C- you are not obligated to do so. If you do not wish to do so, delete //C- this exception statement from your version. //C- ------------------------------------------------------------------- //C- Developed by Bill C. Riemers, Foxtrot Technologies Inc. as work for //C- hire under US copyright laws. //C- ------------------------------------------------------------------- // package com.lizardtech.djview; import com.lizardtech.djview.frame.Frame; import com.lizardtech.djvu.*; import com.lizardtech.djvubean.*; import com.lizardtech.djvubean.outline.*; import com.lizardtech.djview.frame.DjvuStart; import java.awt.*; import java.awt.event.*; import java.beans.*; import java.io.*; import java.net.*; import java.util.Properties; import java.lang.reflect.*; /** * A class for displaying djvu documents. Very simmular to the LizardTech DjVu * plugin. * * @author Bill C. Riemers * @version $Revision: 1.22 $ */ public class Applet extends java.applet.Applet implements PropertyChangeListener, Runnable { //~ Static fields/initializers --------------------------------------------- /** * Magic scale value used to zoom to fit width. */ public static final int FIT_WIDTH = -1; /** * Magic scale value used to zoom to fit page. */ public static final int FIT_PAGE = -2; /** * Constant string indicating the image should be displayed. */ public static final String IMAGE_STRING = "Image"; /** * Constant string indicating the hidden text should be displayed. */ public static final String TEXT_STRING = "Text"; /** * The jar file which we should run, if main is invoked. */ public final String jarName = "djvuframe.jar"; /** * The main class to use, if main is invoked and the jar file is not * available. */ public final String mainClass = "com.lizardtech.djview.frame.Frame"; //~ Instance fields -------------------------------------------------------- /** * The cardlayout which displays either the image or the hidden text. */ public CardLayout cardLayout = null; /** * This container will contain a scrollable DjVu Image */ protected Container scrollPane = null; /** * The current document being displayed. */ protected Document document = null; /** * The current URL being displayed. */ protected URL url = null; /** * True until the first time the mouse is moved over the applet. */ protected boolean first = true; /** * True if a scrollpane should be used. This is intended for debug purposes. */ protected boolean useScrollPane = false; /** * The current zoom factor. */ protected int scale = 100; private Component splitPane = null; // This container will be the center pane. private Container centerPane = null; /** * The panel which displays the DjVu page. */ public DjVuBean djvuBean = null; private Object parentRef = null; private boolean validDjVu = false; private static Object console = null; //~ Constructors ----------------------------------------------------------- /** * Creates a new Applet object. */ public Applet() { } //~ Methods ---------------------------------------------------------------- /** * This applet may also be invoked as a program using javaw. In that event * we first try running a jar file. If that fails we try the mainClass. * * @param args Should contain the target URL to view. */ public static void main(final String[] args) { try { Class c = null; try { final String name = "/" + Applet.class.getName().replace('.', '/') + ".class"; String r = Applet.class.getResource(name).toString(); if (r.startsWith("jar:")) { r = r.substring(4, r.lastIndexOf('!')); r = r.substring(0, r.lastIndexOf("/") + 1) + "djvuframe.jar"; final URL u = new URL("jar", "", r + "!/"); final URLConnection uc = u.openConnection(); final Object attr = uc.getClass().getMethod("getMainAttributes", null).invoke(uc, null); final Object o = Class.forName("java.util.jar.Attributes$Name").getField("MAIN_CLASS").get(null); final String className = (String) attr.getClass().getMethod("getValue", new Class[]{o.getClass()}).invoke(attr, new Object[]{o}); c = (new URLClassLoader(new URL[]{new URL(r)})).loadClass(className); } } catch (final Throwable ignored) { } if (c == null) { c = Class.forName("com.lizardtech.djview.frame.Frame"); } c.getMethod("main", new Class[]{args.getClass()}).invoke(null, new Object[]{args}); } catch (Throwable exp) { if (DjVuObject.hasReferences) { DjVuOptions.err.println( DjVuObject.hasReferences ? "The package has been built without application support." : "The version of Java is only supported when running as an applet."); } //exp.printStackTrace(DjVuOptions.err); } } /** * Query and/or create the cardlayout for displaying text or image. * * @return the cardlayout. * * @throws IOException if an error occures decoding the document */ public CardLayout getCardLayout() throws IOException { CardLayout retval = cardLayout; if (retval == null) { getCenterPane(); retval = cardLayout; } return retval; } /** * Query and/or create the center pane. * * @return the center pane. * * @throws IOException if an error occures decoding the document */ public Container getCenterPane() throws IOException { Container retval = centerPane; if (retval == null) { synchronized (this) { retval = centerPane; if (retval == null) { retval = new Panel(); retval.setBackground(new Color(128, 128, 128)); final CardLayout cardLayout = new CardLayout(); retval.setLayout(cardLayout); retval.add(IMAGE_STRING, getScrollPane()); retval.add(TEXT_STRING, getDjVuBean().getTextArea()); centerPane = retval; this.cardLayout = cardLayout; } } } Frame.Bean = getDjVuBean(); return retval; } /** * Query and/or create the DjVuBean being displayed. * * @return the DjVuBean. * * @throws IOException if an error occures decoding the document */ public DjVuBean getDjVuBean() throws IOException { DjVuBean retval = djvuBean; if (retval == null) { try { djvuBean = retval = useScrollPane ? (new DjVuBean()) : (new DjVuViewport()); final Properties properties = retval.getProperties(); String[][] pinfo = getParameterInfo(); for (int i = 0; i < pinfo.length;) { final String name = pinfo[i++][0]; final String value = getParameter(name); if (value != null) { properties.put( name.toLowerCase(), value); } } final URL[] bases = {getDocumentBase(), getCodeBase()}; String src = properties.getProperty( "data", properties.getProperty("src")); Throwable lastExp = null; for (int i = 0; i < bases.length; i++) { try { if (src != null) { try { if (bases[i] != null) { setURL(new URL(bases[i], src)); } else if (src != null) { setURL(new URL(src)); } } catch (Throwable exp) { src = null; exp.printStackTrace(DjVuOptions.err); } } else if (i > 0) { break; } URL url = getURL(); try { DjVuOptions.out.println("Trying " + url); retval.setURL(url); } catch (final IOException exp) { System.gc(); URL nurl = new URL(url, "directory.djvu"); if (nurl.equals(url)) { setURL(new URL(url, "index.djvu")); } else if (url.equals(new URL(url, "index.djvu"))) { setURL(nurl); } else { lastExp = exp; continue; } url = getURL(); DjVuOptions.out.println("Trying " + url); retval.setURL(url); } lastExp = null; break; } catch (final java.lang.SecurityException exp) { lastExp = exp; } } if (lastExp != null) { throw lastExp; } } catch (final IOException exp) { throw exp; } catch (final RuntimeException exp) { throw exp; } catch (final Throwable exp) { final ByteArrayOutputStream s = new ByteArrayOutputStream(); final PrintStream p = new PrintStream(s); exp.printStackTrace(p); throw new RuntimeException(new String(s.toByteArray())); } } return retval; } /** * Method to obtain an array of parameters accepted by this applet. * * @return array of parameters accepted by this applet. */ public String[][] getParameterInfo() { final String[][] pinfo = { {"data", "url", "DjVu Document to load"}, {"AboutURL", "url", "URL to load for about"}, {"Cache", "boolean", "False if last and next page should not be cached"}, {"Console", "boolean", "Used to enable the DjVu Java Console"}, {"HelpURL", "url", "URL to load for help"}, {"Keys", "boolean", "False if keyboard shortcuts"}, {"LogoURL", "url", "URL to load when clicking on the logo"}, {"MouseMode", "pan,zoom,text", "Initial mouse mode"}, {"Menu", "boolean", "False if the menu should not be used"}, {"NavPane", "outline,none", "Navigation mode"}, {"Page", "number", "Initial page number"}, {"PageLayout", "single,book,cover", "Page layout"}, {"Prefetch", "boolean", "True if indirect pages should be prefetched"}, {"SearchText", "string", "Text to initially search for"}, {"Toolbar", "boolean", "False if the toolbar should not be used"}, { "Zoom", "number,width,page", "Initial zoom value False if the toolbar should not be used" }, { "ZoomFast", "boolean", "True if fit page and fit width sizes should be rounded down for faster viewing." } }; return pinfo; } /** * Query and/or create the component to use as scroll pane by the DjVuBean. * * @return the component to use as a scroll pane. * * @throws IOException if an error occures decoding the document */ public Component getScrollPane() throws IOException { Container retval = scrollPane; if (retval == null) { final DjVuBean page = getDjVuBean(); if (page instanceof DjVuViewport) { retval = new Panel(); retval.setLayout(new BorderLayout()); retval.add( "East", ((DjVuViewport) page).getScrollbar(Scrollbar.VERTICAL)); retval.add( "South", ((DjVuViewport) page).getScrollbar(Scrollbar.HORIZONTAL)); retval.add("Center", page); } else { retval = scrollPane = new ScrollPane(); retval.setBackground(new Color(128, 128, 128)); retval.add(page); } } return retval; } /** * Called to create a split pane for displaying outline navigation along * side of the DjVuBean. * * @param leftPane outline navigation. * @param centerPane DjVuBean. * * @return the component to display. */ public Component getSplitPane( final Component leftPane, final Component centerPane) { if (leftPane == null) { return centerPane; } if (centerPane == null) { return leftPane; } Container retval = null; try { final Class jsplitClass = Class.forName("javax.swing.JSplitPane"); final Class[] params = {Integer.TYPE, Component.class, Component.class}; final Constructor jsplitConstructor = jsplitClass.getConstructor(params); final Field horizontalField = jsplitClass.getField("HORIZONTAL_SPLIT"); final Object horizontal = horizontalField.get(jsplitClass); final Object[] args = {horizontal, leftPane, centerPane}; retval = (Container) jsplitConstructor.newInstance(args); } catch (final Throwable ignored) { retval = new Panel(new BorderLayout()); retval.add(leftPane, BorderLayout.WEST); retval.add(centerPane, BorderLayout.CENTER); } return retval; } /** * Set the url to be rendered. The page will not be updated until init() is * called. * * @param url to render. */ public void setURL(final URL url) { if ((url != this.url) && ((url == null) || !url.equals(this.url))) { synchronized (this) { this.url = url; document = null; } } } /** * Query the URL displayed by this applet. * * @return URL to display. */ public URL getURL() { URL retval = url; if (url == null) { try { retval = getDocumentBase(); url = retval = (retval == null) ? (new URL( "http://www.lizardtech.com/download/files/win/djvuplugin/en_US/welcome.djvu")) : (new URL(retval, "index.djvu")); } catch (Throwable ignored) { } } return retval; } /** * Query if a DjVu document has been successfully initialized. * * @return True if init() was successfull. */ public boolean isValidDjVu() { return validDjVu; } /** * Initialize the currently selected url, and render the first page of the * document. */ public void init() { validDjVu = false; try { final long startTime = System.currentTimeMillis(); DjVuOptions.out.println(Applet.class.getName() + " loaded"); final DjVuBean djvuBean = getDjVuBean(); final Properties properties = djvuBean.getProperties(); String[][] pinfo = getParameterInfo(); properties.setProperty("navpane", "Outline"); for (int i = 0; i < pinfo.length;) { final String name = pinfo[i++][0]; final String value = getParameter(name); if (value != null) { properties.put(name, value); } } if ((console == null) && System.getProperty("java.version").startsWith("1.1.") && DjVuBean.stringToBoolean( properties.getProperty("console"), false)) { try { console = Class.forName("DjVuConsole").newInstance(); } catch (final Throwable ignored) { } } final Dimension screenSize = getToolkit().getScreenSize(); djvuBean.addPropertyChangeListener(this); if (screenSize.width < 640) { final DjVuImage image = djvuBean.getImageWait(); } setLayout(new BorderLayout()); // // final Component toolbar = djvuBean.getToolbar(); // //final RibbonMenu Ribbon=djvuBean.getRibbon(); // // if(toolbar != null) // { // add(toolbar, BorderLayout.SOUTH); // } // String surl = getDjVuBean().getURL().toString(); String url2=surl.substring(5, surl.length()); String filename = DjvuStart.url_name.get(url2); DjvuStart.beanMap.put(url2, getDjVuBean()); add( getCenterPane(), BorderLayout.CENTER); final Dimension size = getSize(); if (size != null) { djvuBean.setTargetWidth(size.width); } final long t = System.currentTimeMillis() - startTime; final String d = "000" + t; DjVuOptions.out.println( Applet.class.getName() + " initialized in " + (t / 1000L) + "." + d.substring(d.length() - 3) + " seconds"); validDjVu = true; } catch (Throwable exp) { validDjVu = false; removeAll(); setLayout(new BorderLayout()); final ByteArrayOutputStream s = new ByteArrayOutputStream(); final PrintStream p = new PrintStream(s); exp.printStackTrace(p); add( new TextArea(new String(s.toByteArray())), BorderLayout.CENTER); exp.printStackTrace(DjVuOptions.err); System.gc(); } final Applet runnable = new Applet(); runnable.parentRef = DjVuObject.createWeakReference(this, this); new Thread(runnable).start(); } /** * Called when a DjVuBean propery has changed. * * @param event describing the property change. */ public void propertyChange(final PropertyChangeEvent event) { try { final String name = event.getPropertyName(); if ("status".equalsIgnoreCase(name)) { final Object value = event.getNewValue(); if (isShowing()) { getAppletContext().showStatus((value != null) ? value.toString() : ""); } } else if ("mode".equalsIgnoreCase(name)) { switch (((Number) event.getNewValue()).intValue()) { case DjVuBean.TEXT_MODE: { getDjVuBean().getTextArea(); getCardLayout().show( getCenterPane(), TEXT_STRING); break; } default: { getCardLayout().show( getCenterPane(), IMAGE_STRING); break; } } } else if ("page".equalsIgnoreCase(name)) { final Object object = event.getNewValue(); DjVuOptions.out.println("Page " + object); final DjVuBean djvuBean = getDjVuBean(); if (djvuBean.getMode() == DjVuBean.TEXT_MODE) { getDjVuBean().getTextArea(); } } else if ("submit".equalsIgnoreCase(name)) { Object object = event.getNewValue(); DjVuOptions.out.println("Submit " + object); if (object instanceof String) { getAppletContext().showDocument( new URL( getURL(), (String) object), Integer.toString(object.hashCode())); } else if (object instanceof URL) { getAppletContext().showDocument( (URL) object, Integer.toString(object.hashCode())); } else if (object instanceof Number) { getDjVuBean().setPage(((Number) object).intValue()); } else if (object instanceof Hyperlink) { Hyperlink rect = (Hyperlink) object; // DjVuOptions.out.println("submit "+rect.getURL()); final String url = rect.getURL(); if ((url != null) && (url.length() > 0)) { final String target = rect.getTarget(); if (target != null) { getAppletContext().showDocument( new URL( getURL(), url), target); } else { getAppletContext().showDocument(new URL( getURL(), url)); } } } } } catch (final Throwable exp) { exp.printStackTrace(DjVuOptions.err); System.gc(); } } /** * Perform regular garbage collection... */ public void run() { while (DjVuObject.getFromReference(parentRef) != null) { // final Runtime run = Runtime.getRuntime(); // final long used = run.totalMemory() - run.freeMemory(); // DjVuOptions.out.println("memory=" + used); try { Thread.sleep(5000L); } catch (final Throwable ignored) { } System.gc(); } } }
gpl-3.0
nickbattle/vdmj
vdmj/src/main/java/com/fujitsu/vdmj/in/statements/INNotYetSpecifiedStatement.java
3734
/******************************************************************************* * * Copyright (c) 2016 Fujitsu Services Ltd. * * Author: Nick Battle * * This file is part of VDMJ. * * VDMJ is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VDMJ is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with VDMJ. If not, see <http://www.gnu.org/licenses/>. * SPDX-License-Identifier: GPL-3.0-or-later * ******************************************************************************/ package com.fujitsu.vdmj.in.statements; import com.fujitsu.vdmj.Settings; import com.fujitsu.vdmj.in.definitions.INCPUClassDefinition; import com.fujitsu.vdmj.in.definitions.INClassDefinition; import com.fujitsu.vdmj.in.modules.INModule; import com.fujitsu.vdmj.in.statements.visitors.INStatementVisitor; import com.fujitsu.vdmj.lex.Dialect; import com.fujitsu.vdmj.lex.LexLocation; import com.fujitsu.vdmj.lex.Token; import com.fujitsu.vdmj.runtime.ClassInterpreter; import com.fujitsu.vdmj.runtime.Context; import com.fujitsu.vdmj.runtime.Interpreter; import com.fujitsu.vdmj.runtime.ModuleInterpreter; import com.fujitsu.vdmj.runtime.ValueException; import com.fujitsu.vdmj.values.ObjectValue; import com.fujitsu.vdmj.values.Value; public class INNotYetSpecifiedStatement extends INStatement { private static final long serialVersionUID = 1L; public INNotYetSpecifiedStatement(LexLocation location) { super(location); location.executable(false); // ie. ignore coverage for these } @Override public String toString() { return "is not yet specified"; } @Override public Value eval(Context ctxt) { breakpoint.check(location, ctxt); if (Settings.dialect == Dialect.VDM_SL) { ModuleInterpreter i = (ModuleInterpreter)Interpreter.getInstance(); INModule module = i.findModule(location.module); if (module != null) { if (module.hasDelegate()) { return module.invokeDelegate(ctxt, Token.OPERATIONS); } } } else { ObjectValue self = ctxt.getSelf(); if (self == null) { ClassInterpreter i = (ClassInterpreter)Interpreter.getInstance(); INClassDefinition cls = i.findClass(location.module); if (cls != null) { if (cls.hasDelegate()) { return cls.invokeDelegate(ctxt, Token.OPERATIONS); } } } else { if (self.hasDelegate()) { return self.invokeDelegate(ctxt, Token.OPERATIONS); } } } if (location.module.equals("CPU")) { try { if (ctxt.title.equals("deploy(obj)")) { return INCPUClassDefinition.deploy(ctxt); } else if (ctxt.title.equals("deploy(obj, name)")) { return INCPUClassDefinition.deploy(ctxt); } else if (ctxt.title.equals("setPriority(opname, priority)")) { return INCPUClassDefinition.setPriority(ctxt); } } catch (ValueException e) { abort(e); } } return abort(4041, "'is not yet specified' statement reached", ctxt); } @Override public <R, S> R apply(INStatementVisitor<R, S> visitor, S arg) { return visitor.caseNotYetSpecifiedStatement(this, arg); } }
gpl-3.0
wiki2014/Learning-Summary
alps/cts/hostsidetests/shortcuts/deviceside/backup/launcher3/src/android/content/pm/cts/shortcut/backup/launcher3/ShortcutManagerPreBackupTest.java
1813
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.content.pm.cts.shortcut.backup.launcher3; import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.list; import android.content.pm.cts.shortcut.device.common.ShortcutManagerDeviceTestBase; import android.test.suitebuilder.annotation.SmallTest; @SmallTest public class ShortcutManagerPreBackupTest extends ShortcutManagerDeviceTestBase { static final String PUBLISHER1_PKG = "android.content.pm.cts.shortcut.backup.publisher1"; static final String PUBLISHER2_PKG = "android.content.pm.cts.shortcut.backup.publisher2"; static final String PUBLISHER3_PKG = "android.content.pm.cts.shortcut.backup.publisher3"; @Override protected void setUp() throws Exception { super.setUp(); setAsDefaultLauncher(MainActivity.class); } public void testPreBackup() { getLauncherApps().pinShortcuts(PUBLISHER1_PKG, list("s3", "ms1", "ms2"), getUserHandle()); getLauncherApps().pinShortcuts(PUBLISHER2_PKG, list("s1", "s3", "ms2"), getUserHandle()); getLauncherApps().pinShortcuts(PUBLISHER3_PKG, list("s1", "s3", "ms1"), getUserHandle()); } }
gpl-3.0
acgtun/leetcode
algorithms/java/Fraction Addition and Subtraction.java
2031
public class Solution { private class Fraction { int a; int b; int sign; public Fraction(int a, int b, int sign) { this.a = a; this.b = b; this.sign = sign; } } private int gcd(int a, int b) { if (a < b) { return gcd(b, a); } if (b == 0) { return a; } return gcd(b, a % b); } private int lcm(int a, int b) { return a * b / gcd(a, b); } private int lcm(ArrayList<Fraction> list) { int lcmDenominator = list.get(0).b; for (int i = 1; i < list.size(); ++i) { lcmDenominator = lcm(lcmDenominator, list.get(i).b); } return lcmDenominator; } public String fractionAddition(String expression) { if (expression.length() == 0) { return "0/1"; } ArrayList<Fraction> list = new ArrayList<>(); String[] adds = expression.split("\\+"); for (int i = 0; i < adds.length; ++i) { String s = adds[i]; int firstSign = 1; if (s.charAt(0) == '-') { firstSign = -1; } String[] sub = s.split("-"); for (int j = 0; j < sub.length; ++j) { int pos = sub[j].indexOf('/'); if (pos < 0) continue; int a = Integer.parseInt(sub[j].substring(0, pos)); int b = Integer.parseInt(sub[j].substring(pos + 1)); int sign = -1; if (j == 0) { sign = firstSign; } list.add(new Fraction(a, b, sign)); } } int lcmDenominator = lcm(list); for(int i = 0;i < list.size();++i) { Fraction f = list.get(i); if(f.b != lcmDenominator) { f.a = f.a * (lcmDenominator / f.b); f.b = lcmDenominator; } } Fraction ret = new Fraction(0, lcmDenominator, 1); for(int i = 0;i < list.size();++i) { Fraction f = list.get(i); if(f.sign == 1) { ret.a += f.a; } else { ret.a -= f.a; } } if(ret.a < 0) { ret.a = -ret.a; ret.sign = -1; } int g = gcd(ret.a, ret.b); ret.a = ret.a / g; ret.b = ret.b / g; StringBuilder sb = new StringBuilder(); if(ret.sign == -1) { sb.append('-'); } sb.append(ret.a); sb.append('/'); sb.append(ret.b); return sb.toString(); } }
gpl-3.0
wwu-pi/muggl
muggl-core/junit/de/wwu/muggl/test/real/java8/TestLambda.java
1678
package de.wwu.muggl.test.real.java8; import de.wwu.muggl.NotYetSupported; import de.wwu.muggl.configuration.Globals; import de.wwu.muggl.test.TestSkeleton; import de.wwu.muggl.test.real.vm.TestVMNormalMethodRunnerHelper; import de.wwu.muggl.vm.classfile.ClassFileException; import de.wwu.muggl.vm.initialization.InitializationException; import de.wwu.muggl.vm.loading.MugglClassLoader; import org.apache.log4j.Level; import org.junit.*; import org.junit.experimental.categories.Category; import java.lang.invoke.MethodType; import static org.junit.Assert.assertEquals; /** * * @author Max Schulze * */ public class TestLambda extends TestSkeleton { @BeforeClass public static void setUpBeforeClass() throws Exception { if (!isForbiddenChangingLogLevel) { Globals.getInst().changeLogLevel(Level.ALL); Globals.getInst().parserLogger.setLevel(Level.WARN); } } @AfterClass public static void tearDownAfterClass() throws Exception { } private MugglClassLoader classLoader; @Before public void setUp() throws Exception { classLoader = new MugglClassLoader(mugglClassLoaderPaths); } @After public void tearDown() throws Exception { } @Test @Category(NotYetSupported.class) public final void testMugglLambdaFiltering() throws ClassFileException, InitializationException, InterruptedException { assertEquals(3, TestVMNormalMethodRunnerHelper.runMethod(classLoader, de.wwu.muggl.binaryTestSuite.lambda.LambdaFiltering.class.getCanonicalName(), de.wwu.muggl.binaryTestSuite.lambda.LambdaFiltering.METHOD_helperExecute_countPersons, MethodType.methodType(int.class, int.class), (Object[]) new Integer[] { 25 })); } }
gpl-3.0
mstritt/orbit-image-analysis
src/main/java/com/actelion/research/orbit/imageAnalysis/components/icons/lmproulx_eraser.java
16104
package com.actelion.research.orbit.imageAnalysis.components.icons; import java.awt.*; import java.awt.geom.*; import java.awt.image.BufferedImage; import java.io.*; import java.lang.ref.WeakReference; import java.util.Base64; import java.util.Stack; import javax.imageio.ImageIO; import javax.swing.SwingUtilities; import javax.swing.plaf.UIResource; import org.pushingpixels.neon.api.icon.ResizableIcon; import org.pushingpixels.neon.api.icon.ResizableIconUIResource; /** * This class has been automatically generated using <a * href="https://github.com/kirill-grouchnikov/radiance">Photon SVG transcoder</a>. */ public class lmproulx_eraser implements ResizableIcon { private Shape shape = null; private GeneralPath generalPath = null; private Paint paint = null; private Stroke stroke = null; private Shape clip = null; private Stack<AffineTransform> transformsStack = new Stack<>(); private void _paint0(Graphics2D g,float origAlpha) { transformsStack.push(g.getTransform()); // g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, -319.3961486816406f, -587.111328125f)); // _0_0 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 243.9641876220703f, 64.42566680908203f)); // _0_0_0 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_0_0_0 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(111.41357f, 583.0844f); generalPath.lineTo(232.79573f, 524.732f); generalPath.lineTo(307.32678f, 553.4565f); generalPath.lineTo(199.95718f, 637.96375f); generalPath.lineTo(111.41357f, 583.0844f); generalPath.closePath(); shape = generalPath; paint = new Color(255, 255, 255, 255); g.setPaint(paint); g.fill(shape); paint = new Color(0, 0, 0, 255); stroke = new BasicStroke(4.092603f,1,0,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(111.41357f, 583.0844f); generalPath.lineTo(232.79573f, 524.732f); generalPath.lineTo(307.32678f, 553.4565f); generalPath.lineTo(199.95718f, 637.96375f); generalPath.lineTo(111.41357f, 583.0844f); generalPath.closePath(); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_0_0_1 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(109.30667f, 586.08954f); generalPath.lineTo(108.54177f, 660.302f); generalPath.lineTo(197.55443f, 709.6002f); generalPath.lineTo(199.06966f, 636.6884f); generalPath.lineTo(109.30667f, 586.08954f); generalPath.closePath(); shape = generalPath; paint = new Color(255, 255, 255, 255); g.setPaint(paint); g.fill(shape); paint = new Color(0, 0, 0, 255); stroke = new BasicStroke(4.092603f,1,0,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(109.30667f, 586.08954f); generalPath.lineTo(108.54177f, 660.302f); generalPath.lineTo(197.55443f, 709.6002f); generalPath.lineTo(199.06966f, 636.6884f); generalPath.lineTo(109.30667f, 586.08954f); generalPath.closePath(); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_0_0_2 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(201.0293f, 708.3478f); generalPath.lineTo(307.72977f, 618.7247f); generalPath.lineTo(308.87906f, 556.7068f); generalPath.lineTo(199.0789f, 639.90204f); generalPath.curveTo(198.67691f, 662.5531f, 200.12698f, 683.7606f, 201.0293f, 708.3478f); generalPath.closePath(); shape = generalPath; paint = new Color(255, 255, 255, 255); g.setPaint(paint); g.fill(shape); paint = new Color(0, 0, 0, 255); stroke = new BasicStroke(4.092603f,1,0,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(201.0293f, 708.3478f); generalPath.lineTo(307.72977f, 618.7247f); generalPath.lineTo(308.87906f, 556.7068f); generalPath.lineTo(199.0789f, 639.90204f); generalPath.curveTo(198.67691f, 662.5531f, 200.12698f, 683.7606f, 201.0293f, 708.3478f); generalPath.closePath(); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_0_0_3 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(191.12642f, 699.0212f); generalPath.lineTo(164.21848f, 718.4453f); generalPath.curveTo(157.70485f, 720.08386f, 149.67596f, 720.3957f, 143.16232f, 718.1717f); generalPath.lineTo(86.57702f, 688.39545f); generalPath.curveTo(78.621574f, 685.76807f, 78.78098f, 681.60913f, 77.87787f, 675.083f); generalPath.lineTo(77.43377f, 627.2067f); generalPath.curveTo(79.79582f, 618.4826f, 86.51426f, 614.07245f, 93.4218f, 611.0024f); generalPath.lineTo(115.18328f, 599.95404f); generalPath.lineTo(190.23819f, 642.30615f); generalPath.lineTo(191.12642f, 699.0212f); generalPath.closePath(); shape = generalPath; paint = new Color(255, 255, 255, 255); g.setPaint(paint); g.fill(shape); paint = new Color(0, 0, 0, 255); stroke = new BasicStroke(4.003575f,1,0,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(191.12642f, 699.0212f); generalPath.lineTo(164.21848f, 718.4453f); generalPath.curveTo(157.70485f, 720.08386f, 149.67596f, 720.3957f, 143.16232f, 718.1717f); generalPath.lineTo(86.57702f, 688.39545f); generalPath.curveTo(78.621574f, 685.76807f, 78.78098f, 681.60913f, 77.87787f, 675.083f); generalPath.lineTo(77.43377f, 627.2067f); generalPath.curveTo(79.79582f, 618.4826f, 86.51426f, 614.07245f, 93.4218f, 611.0024f); generalPath.lineTo(115.18328f, 599.95404f); generalPath.lineTo(190.23819f, 642.30615f); generalPath.lineTo(191.12642f, 699.0212f); generalPath.closePath(); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_0_0_4 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(141.24146f, 570.7651f); generalPath.lineTo(228.38431f, 617.1936f); generalPath.lineTo(286.24146f, 572.9079f); generalPath.lineTo(206.95573f, 537.1936f); generalPath.lineTo(141.24146f, 570.7651f); generalPath.closePath(); shape = generalPath; paint = new Color(0, 0, 255, 255); g.setPaint(paint); g.fill(shape); paint = new Color(0, 0, 0, 255); stroke = new BasicStroke(5.0f,1,0,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(141.24146f, 570.7651f); generalPath.lineTo(228.38431f, 617.1936f); generalPath.lineTo(286.24146f, 572.9079f); generalPath.lineTo(206.95573f, 537.1936f); generalPath.lineTo(141.24146f, 570.7651f); generalPath.closePath(); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_0_0_5 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(227.63992f, 618.93396f); generalPath.lineTo(227.63992f, 685.79517f); generalPath.lineTo(283.41217f, 640.52454f); generalPath.lineTo(285.55725f, 576.4492f); shape = generalPath; paint = new Color(0, 0, 255, 255); g.setPaint(paint); g.fill(shape); paint = new Color(0, 0, 0, 255); stroke = new BasicStroke(4.939821f,1,0,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(227.63992f, 618.93396f); generalPath.lineTo(227.63992f, 685.79517f); generalPath.lineTo(283.41217f, 640.52454f); generalPath.lineTo(285.55725f, 576.4492f); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_0_0_6 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(148.49242f, 715.2385f); generalPath.lineTo(148.49243f, 657.6598f); generalPath.lineTo(155.05841f, 658.67f); generalPath.lineTo(153.54318f, 715.2385f); generalPath.lineTo(148.49242f, 715.2385f); generalPath.closePath(); shape = generalPath; paint = new Color(242, 242, 242, 255); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_0_0_7 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(150.39917f, 662.15283f); generalPath.lineTo(80.78478f, 629.0029f); generalPath.lineTo(88.958954f, 619.7707f); generalPath.lineTo(154.92482f, 654.55334f); generalPath.lineTo(150.39917f, 662.15283f); generalPath.closePath(); shape = generalPath; paint = new Color(242, 242, 242, 255); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_0_0_8 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(186.66434f, 643.77136f); generalPath.lineTo(155.12787f, 662.9714f); generalPath.lineTo(153.23944f, 655.55524f); generalPath.lineTo(184.78612f, 641.4339f); generalPath.lineTo(186.66434f, 643.77136f); generalPath.closePath(); shape = generalPath; paint = new Color(242, 242, 242, 255); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); } @SuppressWarnings("unused") private void innerPaint(Graphics2D g) { float origAlpha = 1.0f; Composite origComposite = g.getComposite(); if (origComposite instanceof AlphaComposite) { AlphaComposite origAlphaComposite = (AlphaComposite)origComposite; if (origAlphaComposite.getRule() == AlphaComposite.SRC_OVER) { origAlpha = origAlphaComposite.getAlpha(); } } _paint0(g, origAlpha); shape = null; generalPath = null; paint = null; stroke = null; clip = null; transformsStack.clear(); } /** * Returns the X of the bounding box of the original SVG image. * * @return The X of the bounding box of the original SVG image. */ public static double getOrigX() { return 0.0; } /** * Returns the Y of the bounding box of the original SVG image. * * @return The Y of the bounding box of the original SVG image. */ public static double getOrigY() { return 0.0; } /** * Returns the width of the bounding box of the original SVG image. * * @return The width of the bounding box of the original SVG image. */ public static double getOrigWidth() { return 235.49339294433594; } /** * Returns the height of the bounding box of the original SVG image. * * @return The height of the bounding box of the original SVG image. */ public static double getOrigHeight() { return 199.07310485839844; } /** The current width of this resizable icon. */ private int width; /** The current height of this resizable icon. */ private int height; /** * Creates a new transcoded SVG image. This is marked as private to indicate that app * code should be using the {@link #of(int, int)} method to obtain a pre-configured instance. */ private lmproulx_eraser() { this.width = (int) getOrigWidth(); this.height = (int) getOrigHeight(); } @Override public int getIconHeight() { return height; } @Override public int getIconWidth() { return width; } @Override public synchronized void setDimension(Dimension newDimension) { this.width = newDimension.width; this.height = newDimension.height; } @Override public synchronized void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2d = (Graphics2D) g.create(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.translate(x, y); double coef1 = (double) this.width / getOrigWidth(); double coef2 = (double) this.height / getOrigHeight(); double coef = Math.min(coef1, coef2); g2d.clipRect(0, 0, this.width, this.height); g2d.scale(coef, coef); g2d.translate(-getOrigX(), -getOrigY()); if (coef1 != coef2) { if (coef1 < coef2) { int extraDy = (int) ((getOrigWidth() - getOrigHeight()) / 2.0); g2d.translate(0, extraDy); } else { int extraDx = (int) ((getOrigHeight() - getOrigWidth()) / 2.0); g2d.translate(extraDx, 0); } } Graphics2D g2ForInner = (Graphics2D) g2d.create(); innerPaint(g2ForInner); g2ForInner.dispose(); g2d.dispose(); } /** * Returns a new instance of this icon with specified dimensions. * * @param width Required width of the icon * @param height Required height of the icon * @return A new instance of this icon with specified dimensions. */ public static ResizableIcon of(int width, int height) { lmproulx_eraser base = new lmproulx_eraser(); base.width = width; base.height = height; return base; } /** * Returns a new {@link UIResource} instance of this icon with specified dimensions. * * @param width Required width of the icon * @param height Required height of the icon * @return A new {@link UIResource} instance of this icon with specified dimensions. */ public static ResizableIconUIResource uiResourceOf(int width, int height) { lmproulx_eraser base = new lmproulx_eraser(); base.width = width; base.height = height; return new ResizableIconUIResource(base); } /** * Returns a factory that returns instances of this icon on demand. * * @return Factory that returns instances of this icon on demand. */ public static Factory factory() { return lmproulx_eraser::new; } }
gpl-3.0
swapUniba/lodrecsys_eswc2017tutorial
RecSysLodTutorial/src/main/java/recsyslod/utils/CutUserByRatings.java
2041
package recsyslod.utils; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import recsyslod.RatingsReader; import recsyslod.data.Rate; /** * * @author pierpaolo */ public class CutUserByRatings { /** * * Filter users that have a number of ratings less than a specified threshold * * First argument: ratings file * Second argument: output file * Third argument: threshold * */ public static void main(String[] args) { if (args.length == 3) { try { RatingsReader ratings = new RatingsReader(new File(args[0])); BufferedWriter writer = new BufferedWriter(new FileWriter(args[1])); int cut = Integer.parseInt(args[2]); int prevUser = 0; List<Rate> list = new ArrayList<>(); if (ratings.hasNext()) { Rate rate = ratings.next(); prevUser = rate.getUser(); list.add(rate); } while (ratings.hasNext()) { Rate rate = ratings.next(); if (prevUser == rate.getUser()) { list.add(rate); } else { if (list.size() < cut) { for (Rate r : list) { writer.write(r.outString()); writer.newLine(); } } prevUser = rate.getUser(); list.clear(); list.add(rate); } } writer.close(); } catch (IOException ex) { Logger.getLogger(CutUserByRatings.class.getName()).log(Level.SEVERE, null, ex); } } } }
gpl-3.0
itszootime/emulatorization-api
src/main/java/uk/ac/aston/uncertws/emulatorization/impl/DesignInputTypeImpl.java
11117
/* * XML Type: DesignInputType * Namespace: http://uncertws.aston.ac.uk/emulatorization * Java type: uk.ac.aston.uncertws.emulatorization.DesignInputType * * Automatically generated - do not modify. */ package uk.ac.aston.uncertws.emulatorization.impl; /** * An XML DesignInputType(@http://uncertws.aston.ac.uk/emulatorization). * * This is a complex type. */ public class DesignInputTypeImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements uk.ac.aston.uncertws.emulatorization.DesignInputType { private static final long serialVersionUID = 1L; public DesignInputTypeImpl(org.apache.xmlbeans.SchemaType sType) { super(sType); } private static final javax.xml.namespace.QName IDENTIFIER$0 = new javax.xml.namespace.QName("http://uncertws.aston.ac.uk/emulatorization", "identifier"); private static final javax.xml.namespace.QName POINTS$2 = new javax.xml.namespace.QName("http://uncertws.aston.ac.uk/emulatorization", "points"); private static final javax.xml.namespace.QName MEAN$4 = new javax.xml.namespace.QName("http://uncertws.aston.ac.uk/emulatorization", "mean"); private static final javax.xml.namespace.QName STDDEV$6 = new javax.xml.namespace.QName("http://uncertws.aston.ac.uk/emulatorization", "stdDev"); /** * Gets the "identifier" element */ public java.lang.String getIdentifier() { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.SimpleValue target = null; target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(IDENTIFIER$0, 0); if (target == null) { return null; } return target.getStringValue(); } } /** * Gets (as xml) the "identifier" element */ public org.apache.xmlbeans.XmlString xgetIdentifier() { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.XmlString target = null; target = (org.apache.xmlbeans.XmlString)get_store().find_element_user(IDENTIFIER$0, 0); return target; } } /** * Sets the "identifier" element */ public void setIdentifier(java.lang.String identifier) { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.SimpleValue target = null; target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(IDENTIFIER$0, 0); if (target == null) { target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(IDENTIFIER$0); } target.setStringValue(identifier); } } /** * Sets (as xml) the "identifier" element */ public void xsetIdentifier(org.apache.xmlbeans.XmlString identifier) { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.XmlString target = null; target = (org.apache.xmlbeans.XmlString)get_store().find_element_user(IDENTIFIER$0, 0); if (target == null) { target = (org.apache.xmlbeans.XmlString)get_store().add_element_user(IDENTIFIER$0); } target.set(identifier); } } /** * Gets the "points" element */ public java.util.List getPoints() { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.SimpleValue target = null; target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(POINTS$2, 0); if (target == null) { return null; } return target.getListValue(); } } /** * Gets (as xml) the "points" element */ public uk.ac.aston.uncertws.emulatorization.DesignInputType.Points xgetPoints() { synchronized (monitor()) { check_orphaned(); uk.ac.aston.uncertws.emulatorization.DesignInputType.Points target = null; target = (uk.ac.aston.uncertws.emulatorization.DesignInputType.Points)get_store().find_element_user(POINTS$2, 0); return target; } } /** * Sets the "points" element */ public void setPoints(java.util.List points) { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.SimpleValue target = null; target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(POINTS$2, 0); if (target == null) { target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(POINTS$2); } target.setListValue(points); } } /** * Sets (as xml) the "points" element */ public void xsetPoints(uk.ac.aston.uncertws.emulatorization.DesignInputType.Points points) { synchronized (monitor()) { check_orphaned(); uk.ac.aston.uncertws.emulatorization.DesignInputType.Points target = null; target = (uk.ac.aston.uncertws.emulatorization.DesignInputType.Points)get_store().find_element_user(POINTS$2, 0); if (target == null) { target = (uk.ac.aston.uncertws.emulatorization.DesignInputType.Points)get_store().add_element_user(POINTS$2); } target.set(points); } } /** * Gets the "mean" element */ public double getMean() { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.SimpleValue target = null; target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(MEAN$4, 0); if (target == null) { return 0.0; } return target.getDoubleValue(); } } /** * Gets (as xml) the "mean" element */ public org.apache.xmlbeans.XmlDouble xgetMean() { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.XmlDouble target = null; target = (org.apache.xmlbeans.XmlDouble)get_store().find_element_user(MEAN$4, 0); return target; } } /** * True if has "mean" element */ public boolean isSetMean() { synchronized (monitor()) { check_orphaned(); return get_store().count_elements(MEAN$4) != 0; } } /** * Sets the "mean" element */ public void setMean(double mean) { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.SimpleValue target = null; target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(MEAN$4, 0); if (target == null) { target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(MEAN$4); } target.setDoubleValue(mean); } } /** * Sets (as xml) the "mean" element */ public void xsetMean(org.apache.xmlbeans.XmlDouble mean) { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.XmlDouble target = null; target = (org.apache.xmlbeans.XmlDouble)get_store().find_element_user(MEAN$4, 0); if (target == null) { target = (org.apache.xmlbeans.XmlDouble)get_store().add_element_user(MEAN$4); } target.set(mean); } } /** * Unsets the "mean" element */ public void unsetMean() { synchronized (monitor()) { check_orphaned(); get_store().remove_element(MEAN$4, 0); } } /** * Gets the "stdDev" element */ public double getStdDev() { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.SimpleValue target = null; target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(STDDEV$6, 0); if (target == null) { return 0.0; } return target.getDoubleValue(); } } /** * Gets (as xml) the "stdDev" element */ public org.apache.xmlbeans.XmlDouble xgetStdDev() { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.XmlDouble target = null; target = (org.apache.xmlbeans.XmlDouble)get_store().find_element_user(STDDEV$6, 0); return target; } } /** * True if has "stdDev" element */ public boolean isSetStdDev() { synchronized (monitor()) { check_orphaned(); return get_store().count_elements(STDDEV$6) != 0; } } /** * Sets the "stdDev" element */ public void setStdDev(double stdDev) { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.SimpleValue target = null; target = (org.apache.xmlbeans.SimpleValue)get_store().find_element_user(STDDEV$6, 0); if (target == null) { target = (org.apache.xmlbeans.SimpleValue)get_store().add_element_user(STDDEV$6); } target.setDoubleValue(stdDev); } } /** * Sets (as xml) the "stdDev" element */ public void xsetStdDev(org.apache.xmlbeans.XmlDouble stdDev) { synchronized (monitor()) { check_orphaned(); org.apache.xmlbeans.XmlDouble target = null; target = (org.apache.xmlbeans.XmlDouble)get_store().find_element_user(STDDEV$6, 0); if (target == null) { target = (org.apache.xmlbeans.XmlDouble)get_store().add_element_user(STDDEV$6); } target.set(stdDev); } } /** * Unsets the "stdDev" element */ public void unsetStdDev() { synchronized (monitor()) { check_orphaned(); get_store().remove_element(STDDEV$6, 0); } } /** * An XML points(@http://uncertws.aston.ac.uk/emulatorization). * * This is a list type whose items are org.apache.xmlbeans.XmlDouble. */ public static class PointsImpl extends org.apache.xmlbeans.impl.values.XmlListImpl implements uk.ac.aston.uncertws.emulatorization.DesignInputType.Points { private static final long serialVersionUID = 1L; public PointsImpl(org.apache.xmlbeans.SchemaType sType) { super(sType, false); } protected PointsImpl(org.apache.xmlbeans.SchemaType sType, boolean b) { super(sType, b); } } }
gpl-3.0
emsedano/cio-figure
src/com/ibm/cio/ws/EchoServer.java
2316
package com.ibm.cio.ws; import java.io.IOException; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import com.ibm.cio.model.Paint; import com.ibm.cio.ws.helper.JSONParser; /** * @ServerEndpoint gives the relative name for the end point * This will be accessed via ws://localhost:8080/EchoChamber/echo * Where "localhost" is the address of the host, * "EchoChamber" is the name of the package * and "echo" is the address to access this class from the server */ @ServerEndpoint("/echo") public class EchoServer { /** * @OnOpen allows us to intercept the creation of a new session. * The session class allows us to send data to the user. * In the method onOpen, we'll let the user know that the handshake was * successful. */ @OnOpen public void onOpen(Session session){ System.out.println(session.getId() + " has opened a connection"); try { session.getBasicRemote().sendText("Connection Established"); } catch (IOException ex) { ex.printStackTrace(); } } /** * When a user sends a message to the server, this method will intercept the message * and allow us to react to it. For now the message is read as a String. */ @OnMessage public void onMessage(String message, Session session){ System.out.println("Message from " + session.getId() + ": " + message); try { if(message.equalsIgnoreCase("doArtist")){ Paint paint = new Paint(); //TODO Factory.getInstance().drawPicture(); //or something similar String responseMessage = JSONParser.createJson(paint); session.getBasicRemote().sendText(responseMessage); }else{ session.getBasicRemote().sendText(message); } } catch (IOException ex) { ex.printStackTrace(); } } /** * The user closes the connection. * * Note: you can't send messages to the client from this method */ @OnClose public void onClose(Session session){ System.out.println("Session " +session.getId()+" has ended"); } }
gpl-3.0
solo5star/SOLOLand_Nukkit
src/main/java/solo/sololand/command/defaults/world/args/WorldMove.java
1197
package solo.sololand.command.defaults.world.args; import cn.nukkit.Player; import cn.nukkit.command.CommandSender; import cn.nukkit.command.data.CommandParameter; import solo.sololand.command.SubCommand; import solo.sololand.world.World; import solo.solobasepackage.util.Message; public class WorldMove extends SubCommand{ public WorldMove(){ super("이동", "해당 월드로 이동합니다."); this.setPermission("sololand.command.world.move"); this.addCommandParameters(new CommandParameter[]{ new CommandParameter("월드 이름", CommandParameter.ARG_TYPE_STRING, false) }); } @Override public boolean execute(CommandSender sender, String[] args){ Player player = (Player) sender; if(args.length < 1){ return false; } World target; target = World.getByName(args[0]); if(target == null){ target = World.get(args[0]); if(target == null){ Message.alert(player, args[0] + "은(는) 존재하지 않는 월드입니다."); return true; } } player.teleport(target.getLevel().getSpawnLocation()); Message.normal(player, target.getCustomName() + " 월드로 이동하였습니다."); return true; } }
gpl-3.0
LeoTremblay/activityinfo
server/src/main/java/org/activityinfo/core/shared/importing/strategy/MissingColumn.java
537
package org.activityinfo.core.shared.importing.strategy; import org.activityinfo.core.shared.importing.source.SourceRow; public class MissingColumn implements ColumnAccessor { public final static MissingColumn INSTANCE = new MissingColumn(); private MissingColumn() { } @Override public String getHeading() { return null; } @Override public String getValue(SourceRow row) { return null; } @Override public boolean isMissing(SourceRow row) { return true; } }
gpl-3.0
shionn/MtgDb
src/test/java/tcg/price/mkm/MkmCrawlerTest.java
3729
package tcg.price.mkm; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.math.BigDecimal; import java.util.List; import org.junit.Before; import org.junit.Test; import tcg.db.dbo.Card; import tcg.db.dbo.Card.Foil; import tcg.db.dbo.CardLayout; import tcg.db.dbo.CardPrice; import tcg.db.dbo.Edition; import tcg.security.MailSender; public class MkmCrawlerTest { private MkmCrawler crawler = new MkmCrawler(); @Before public void setup() { crawler.setMailSender(mock(MailSender.class)); } @Test public void testPrice() throws Exception { Edition edition = new Edition(); edition.setMkmName("Battle for Zendikar"); Card card = new Card(); card.setEdition(edition); card.setLayout(CardLayout.normal); card.setName("Ob Nixilis Reignited"); List<CardPrice> prices = crawler.priceForNotFoil(card); prices.addAll(crawler.priceForFoil(card)); BigDecimal paper = prices.get(0).getPrice(); assertThat(paper).isPositive(); BigDecimal foil = prices.get(1).getPrice(); assertThat(foil).isPositive().isGreaterThan(paper); } @Test public void testDoublePrice() throws Exception { Card card = doubleFace("Rivals of Ixalan", "Journey to Eternity", "Atzal, Cave of Eternity"); assertThat(crawler.priceForNotFoil(card).get(0).getPrice()).as("double // url") .isPositive(); card = doubleFace("Ixalan", "Search for Azcanta", "Azcanta, the Sunken Ruin"); assertThat(crawler.priceForNotFoil(card).get(0).getPrice()).as("double / url").isPositive(); card = doubleFace("Magic Origins", "Jace, Vryn's Prodigy", "Jace, Telepath Unbound"); assertThat(crawler.priceForNotFoil(card).get(0).getPrice()).as("double / url").isPositive(); card = doubleFace("Shadows over Innistrad", "Arlinn Kord", "Arlinn, Embraced by the Moon"); assertThat(crawler.priceForNotFoil(card).get(0).getPrice()).as("double / url").isPositive(); } @Test public void testPriceDivers() throws Exception { testOne("Commander", "Serra Angel"); testOne("Kaladesh", "Torrential Gearhulk"); testOne("Alliances", "Force of Will"); // dans le cas thalia le 's est remplacé par -s alors que pour jace le ' est supprimé testOne("Shadows over Innistrad", "Thalia's Lieutenant"); testOne("Urza's Legacy", "Mother of Runes"); testOne("Duel Decks: Elves vs. Goblins", "Akki Coalflinger"); testOne("Commander 2017", "Earthquake"); } private void testOne(String edition, String name) { List<CardPrice> prices = crawler.priceForNotFoil(card(edition, name, Foil.nofoil)); assertThat(prices).isNotEmpty(); assertThat(prices.get(0).getPrice()).isPositive(); } @Test public void testPriceFromMail() throws Exception { // testOne("Alliances", "Soldevi Sentry"); // TODO carte avec version testOne("Shadowmoor", "Cinderbones"); testOne("Future Sight", "Haze of Rage"); } @Test public void testPriceDiversFoil() throws Exception { Card card = card("Judge Rewards Promos", "Argothian Enchantress", Foil.onlyfoil); assertThat(crawler.priceForFoil(card).get(0).getPrice()).isPositive(); } private Card card(String editionName, String cardName, Foil foil) { Edition edition = new Edition(); edition.setName(editionName); Card card = new Card(); card.setFoil(foil); card.setEdition(edition); card.setLayout(CardLayout.normal); card.setName(cardName); return card; } private Card doubleFace(String edition, String front, String back) { Card otherFace = new Card(); otherFace.setName(back); Edition ed = new Edition(); ed.setMkmName(edition); Card card = new Card(); card.setLayout(CardLayout.doublefaced); card.setEdition(ed); card.setName(front); card.setLinkCard(otherFace); return card; } }
gpl-3.0
LokkaCocca/NKVD-bot
src/utils/updates/UpdateResolver.java
7043
package utils.updates; import org.telegram.telegrambots.api.objects.*; import org.telegram.telegrambots.api.objects.stickers.Sticker; import org.telegram.telegrambots.exceptions.TelegramApiException; import utils.Crutches; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.List; public class UpdateResolver { public static String resolveMessages(Message message) throws TelegramApiException, IOException, InterruptedException { long timeRaw = message.getDate(); timeRaw *= 1000; SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("dd/MM/yyyy' 'HH:mm:ss"); String text = dateTimeFormatter.format(timeRaw) + "|" + message.getChat().getTitle() + "(" + message.getChatId() + ")" + "->" + Crutches.tg_getUser(message) + ": "; if (message.hasText()) { return text + resolveTextMessage(message); } if (message.getSticker() != null) { return text + resolveStickers(message.getSticker()); } if (message.hasPhoto()) { return text + resolvePhotos(message.getPhoto(), message.getCaption()); } if (message.hasDocument()) { return text + resolveDocuments(message.getDocument(), message.getCaption()); } if (message.getAudio() != null) { return text + resolveAudios(message.getAudio(), message.getCaption()); } if (message.getVideo() != null) { return text + resolveVideo(message.getVideo()); } if (message.getDeleteChatPhoto()) { return text + "Chat photo deleted"; } if (message.getNewChatMembers() != null) { return text + resolveNewUsers(message.getNewChatMembers()); } if (message.getNewChatPhoto() != null) { return text + "Chat photo changed:" + resolvePhotos(message.getNewChatPhoto(), null); } if (message.getNewChatTitle() != null) { return text + "Chat title changed to \"" + message.getNewChatTitle() + "\""; } if (message.getChannelChatCreated() != null) { return text + "Channel created"; } if (message.getGroupchatCreated()) { return text + "Chat created"; } if (message.getSuperGroupCreated()) { return text + "Supergroup created"; } if (message.getMigrateToChatId() != null) { return text + "The chat has become a supergroup with this id: " + message.getMigrateToChatId(); } return null; } private static String resolveTextMessage(Message message) { return message.getText(); } private static String resolvePhotos(List<PhotoSize> photos, String caption) { String resolvedText; resolvedText = photos.size() + " photos total:\n"; for (int i = 0; i < photos.size(); i++) { resolvedText += "Photo №" + i + ": Id:" + photos.get(i).getFileId() + "\n"; resolvedText += "Resolution: " + photos.get(i).getWidth() + "x" + photos.get(i).getHeight() + "\n"; resolvedText += "Size: " + photos.get(i).getFileSize() / 1000 + "kb" + "\n"; } if (caption != null) resolvedText += "Caption: " + caption; return resolvedText; } private static String resolveDocuments(Document document, String caption) { String resolvedText; resolvedText = "Document: " + document.getFileName() + "\n"; resolvedText += "Id: " + document.getFileId() + "\n"; resolvedText += "Size: " + document.getFileSize() / 1000 + "kb" + "\n"; resolvedText += "Mimetype: " + document.getMimeType() + "\n"; if (document.getThumb() != null) { resolvedText += resolveThumbnails(document.getThumb()); } if (caption != null) resolvedText += "Caption: " + caption; return resolvedText; } private static String resolveAudios(Audio audio, String caption) { String resolvedText; resolvedText = "Audio file: " + audio.getPerformer() + " - " + audio.getTitle() + "\n"; resolvedText += "Id: " + audio.getFileId() + "\n"; resolvedText += "Size: " + audio.getFileSize() / 1000 + "kb" + "\n"; resolvedText += "Duration: " + Crutches.secsToTime(audio.getDuration()) + "\n"; resolvedText += "Mimetype: " + audio.getMimeType() + "\n"; if (caption != null) resolvedText += "Caption: " + caption; return resolvedText; } private static String resolveStickers(Sticker sticker) { String resolvedText; resolvedText = "Sticker: " + sticker.getEmoji() + "\n"; resolvedText += "Id: " + sticker.getFileId() + "\n"; resolvedText += "Size: " + sticker.getFileSize() / 1000 + "kb" + "\n"; resolvedText += "Set name: " + sticker.getSetName() + "\n"; resolvedText += "Mask position: " + sticker.getMaskPosition() + "\n"; resolvedText += "Resolution: " + sticker.getHeight() + "x" + sticker.getWidth() + "\n"; if (sticker.getThumb() != null) { resolvedText += resolveThumbnails(sticker.getThumb()); } return resolvedText; } private static String resolveThumbnails(PhotoSize thumbnail) { String resolvedText = "Thumbnail: \n"; resolvedText += " Id: " + thumbnail.getFileId() + "\n"; resolvedText += " Resolution: " + thumbnail.getWidth() + "x" + thumbnail.getHeight() + "\n"; resolvedText += " Size: " + thumbnail.getFileSize() / 1000 + "kb" + "\n"; return resolvedText; } private static String resolveNewUsers(List<User> userList) { String resolvedText = "New users added:\n"; for (int i = 0; i < userList.size(); i++) { resolvedText += i + ". @" + userList.get(i).getUserName() + ":\nName: "; if (userList.get(i).getFirstName() != null) { resolvedText += userList.get(i).getFirstName() + " "; } if (userList.get(i).getLastName() != null) { resolvedText += userList.get(i).getLastName() + " "; } resolvedText += "\nId:" + userList.get(i).getId() + "\n"; resolvedText += "Bot?:" + userList.get(i).getBot(); } return resolvedText; } private static String resolveVideo(Video video) { String resolvedText; resolvedText = "Video: "; resolvedText += "Id: " + video.getFileId() + "\n"; resolvedText += "Size: " + video.getFileSize() / 1000 + "kb" + "\n"; resolvedText += "Resolution: " + video.getWidth() + "x" + video.getHeight() + "\n"; resolvedText += "Duration: " + Crutches.secsToTime(video.getDuration()) + "\n"; resolvedText += "Mimetype: " + video.getMimeType() + "\n"; if (video.getThumb() != null) { resolvedText += resolveThumbnails(video.getThumb()); } return resolvedText; } }
gpl-3.0
scott181182/NeoCraft
NeoCraft_common/MMC/neocraft/network/packet/NCpacket.java
1382
package MMC.neocraft.network.packet; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import net.minecraft.network.INetworkManager; import cpw.mods.fml.common.network.Player; import MMC.neocraft.network.PacketTypeHandler; public class NCpacket { public PacketTypeHandler packetType; public boolean isChunkDataPacket; public NCpacket(PacketTypeHandler packetType, boolean isChunkDataPacket) { this.packetType = packetType; this.isChunkDataPacket = isChunkDataPacket; } public byte[] populate() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); try { dos.writeByte(packetType.ordinal()); this.writeData(dos); } catch (IOException e) { e.printStackTrace(System.err); } return bos.toByteArray(); } public void readPopulate(DataInputStream data) { try { this.readData(data); } catch (IOException e) { e.printStackTrace(System.err); } } public void readData(DataInputStream data) throws IOException { } public void writeData(DataOutputStream dos) throws IOException { } public void execute(INetworkManager network, Player player) { } public void setKey(int key) { } }
gpl-3.0
TristenCocking/PneumaticCraft-Unofficial
src/main/java/com/imancus/pneumaticcraftunofficial/common/moditem/ItemMachineUpgrade.java
98
package com.imancus.pneumaticcraftunofficial.common.moditem; public class ItemMachineUpgrade{ }
gpl-3.0
konamith/wm-bus-api
wm-bus-dao/wm-bus-dao-support/src/main/java/com/hundsun/wm/api/dao/support/t2/config/DaoConfig.java
318
package com.hundsun.wm.api.dao.support.t2.config; import com.hundsun.wm.api.dao.support.annotation.ExternalInterface; /** * Dao 配置类 * @author gavin * @create 13-7-26 * @since 1.0.0 */ public interface DaoConfig { Class<?> getDaoClass(); MapperConfig getMapperConfig(ExternalInterface inter); }
gpl-3.0
wiki2014/Learning-Summary
alps/cts/tests/tests/content/src/android/content/cts/ContentResolverTest.java
43956
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.content.cts; import android.content.cts.R; import android.accounts.Account; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.cts.util.PollingCheck; import android.database.ContentObserver; import android.database.Cursor; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.os.Bundle; import android.os.CancellationSignal; import android.os.OperationCanceledException; import android.os.ParcelFileDescriptor; import android.os.RemoteException; import android.test.AndroidTestCase; import android.util.Log; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; public class ContentResolverTest extends AndroidTestCase { private final static String COLUMN_ID_NAME = "_id"; private final static String COLUMN_KEY_NAME = "key"; private final static String COLUMN_VALUE_NAME = "value"; private static final String AUTHORITY = "ctstest"; private static final Uri TABLE1_URI = Uri.parse("content://" + AUTHORITY + "/testtable1/"); private static final Uri TABLE1_CROSS_URI = Uri.parse("content://" + AUTHORITY + "/testtable1/cross"); private static final Uri TABLE2_URI = Uri.parse("content://" + AUTHORITY + "/testtable2/"); private static final Uri SELF_URI = Uri.parse("content://" + AUTHORITY + "/self/"); private static final Uri CRASH_URI = Uri.parse("content://" + AUTHORITY + "/crash/"); private static final Uri LEVEL1_URI = Uri.parse("content://" + AUTHORITY + "/level/"); private static final Uri LEVEL2_URI = Uri.parse("content://" + AUTHORITY + "/level/child"); private static final Uri LEVEL3_URI = Uri.parse("content://" + AUTHORITY + "/level/child/grandchild/"); private static final String REMOTE_AUTHORITY = "remotectstest"; private static final Uri REMOTE_TABLE1_URI = Uri.parse("content://" + REMOTE_AUTHORITY + "/testtable1/"); private static final Uri REMOTE_SELF_URI = Uri.parse("content://" + REMOTE_AUTHORITY + "/self/"); private static final Uri REMOTE_CRASH_URI = Uri.parse("content://" + REMOTE_AUTHORITY + "/crash/"); private static final Account ACCOUNT = new Account("cts", "cts"); private static final String KEY1 = "key1"; private static final String KEY2 = "key2"; private static final String KEY3 = "key3"; private static final int VALUE1 = 1; private static final int VALUE2 = 2; private static final int VALUE3 = 3; private static final String TEST_PACKAGE_NAME = "android.content.cts"; private Context mContext; private ContentResolver mContentResolver; private Cursor mCursor; @Override protected void setUp() throws Exception { super.setUp(); mContext = getContext(); mContentResolver = mContext.getContentResolver(); MockContentProvider.setCrashOnLaunch(mContext, false); // add three rows to database when every test case start. ContentValues values = new ContentValues(); values.put(COLUMN_KEY_NAME, KEY1); values.put(COLUMN_VALUE_NAME, VALUE1); mContentResolver.insert(TABLE1_URI, values); mContentResolver.insert(REMOTE_TABLE1_URI, values); values.put(COLUMN_KEY_NAME, KEY2); values.put(COLUMN_VALUE_NAME, VALUE2); mContentResolver.insert(TABLE1_URI, values); mContentResolver.insert(REMOTE_TABLE1_URI, values); values.put(COLUMN_KEY_NAME, KEY3); values.put(COLUMN_VALUE_NAME, VALUE3); mContentResolver.insert(TABLE1_URI, values); mContentResolver.insert(REMOTE_TABLE1_URI, values); } @Override protected void tearDown() throws Exception { mContentResolver.delete(TABLE1_URI, null, null); if ( null != mCursor && !mCursor.isClosed() ) { mCursor.close(); } mContentResolver.delete(REMOTE_TABLE1_URI, null, null); if ( null != mCursor && !mCursor.isClosed() ) { mCursor.close(); } super.tearDown(); } public void testConstructor() { assertNotNull(mContentResolver); } public void testCrashOnLaunch() { // This test is going to make sure that the platform deals correctly // with a content provider process going away while a client is waiting // for it to come up. // First, we need to make sure our provider process is gone. Goodbye! ContentProviderClient client = mContentResolver.acquireContentProviderClient( REMOTE_AUTHORITY); // We are going to do something wrong here... release the client first, // so the act of killing it doesn't kill our own process. client.release(); try { client.delete(REMOTE_SELF_URI, null, null); } catch (RemoteException e) { } // Now make sure the thing is actually gone. boolean gone = true; try { client.getType(REMOTE_TABLE1_URI); gone = false; } catch (RemoteException e) { } if (!gone) { fail("Content provider process is not gone!"); } try { MockContentProvider.setCrashOnLaunch(mContext, true); String type1 = mContentResolver.getType(REMOTE_TABLE1_URI); assertFalse(MockContentProvider.getCrashOnLaunch(mContext)); assertTrue(type1.startsWith(ContentResolver.CURSOR_DIR_BASE_TYPE, 0)); } finally { MockContentProvider.setCrashOnLaunch(mContext, false); } } public void testUnstableToStableRefs() { // Get an unstable refrence on the remote content provider. ContentProviderClient uClient = mContentResolver.acquireUnstableContentProviderClient( REMOTE_AUTHORITY); // Verify we can access it. String type1 = mContentResolver.getType(REMOTE_TABLE1_URI); assertTrue(type1.startsWith(ContentResolver.CURSOR_DIR_BASE_TYPE, 0)); // Get a stable reference on the remote content provider. ContentProviderClient sClient = mContentResolver.acquireContentProviderClient( REMOTE_AUTHORITY); // Verify we can still access it. type1 = mContentResolver.getType(REMOTE_TABLE1_URI); assertTrue(type1.startsWith(ContentResolver.CURSOR_DIR_BASE_TYPE, 0)); // Release unstable reference. uClient.release(); // Verify we can still access it. type1 = mContentResolver.getType(REMOTE_TABLE1_URI); assertTrue(type1.startsWith(ContentResolver.CURSOR_DIR_BASE_TYPE, 0)); // Release stable reference, removing last ref. sClient.release(); // Kill it. Note that a bug at this point where it causes our own // process to be killed will result in the entire test failing. try { Log.i("ContentResolverTest", "Killing remote client -- if test process goes away, that is why!"); uClient.delete(REMOTE_SELF_URI, null, null); } catch (RemoteException e) { } // Make sure the remote client is actually gone. boolean gone = true; try { sClient.getType(REMOTE_TABLE1_URI); gone = false; } catch (RemoteException e) { } if (!gone) { fail("Content provider process is not gone!"); } } public void testStableToUnstableRefs() { // Get a stable reference on the remote content provider. ContentProviderClient sClient = mContentResolver.acquireContentProviderClient( REMOTE_AUTHORITY); // Verify we can still access it. String type1 = mContentResolver.getType(REMOTE_TABLE1_URI); assertTrue(type1.startsWith(ContentResolver.CURSOR_DIR_BASE_TYPE, 0)); // Get an unstable refrence on the remote content provider. ContentProviderClient uClient = mContentResolver.acquireUnstableContentProviderClient( REMOTE_AUTHORITY); // Verify we can access it. type1 = mContentResolver.getType(REMOTE_TABLE1_URI); assertTrue(type1.startsWith(ContentResolver.CURSOR_DIR_BASE_TYPE, 0)); // Release stable reference, leaving only an unstable ref. sClient.release(); // Kill it. Note that a bug at this point where it causes our own // process to be killed will result in the entire test failing. try { Log.i("ContentResolverTest", "Killing remote client -- if test process goes away, that is why!"); uClient.delete(REMOTE_SELF_URI, null, null); } catch (RemoteException e) { } // Make sure the remote client is actually gone. boolean gone = true; try { uClient.getType(REMOTE_TABLE1_URI); gone = false; } catch (RemoteException e) { } if (!gone) { fail("Content provider process is not gone!"); } // Release unstable reference. uClient.release(); } public void testGetType() { String type1 = mContentResolver.getType(TABLE1_URI); assertTrue(type1.startsWith(ContentResolver.CURSOR_DIR_BASE_TYPE, 0)); String type2 = mContentResolver.getType(TABLE2_URI); assertTrue(type2.startsWith(ContentResolver.CURSOR_DIR_BASE_TYPE, 0)); Uri invalidUri = Uri.parse("abc"); assertNull(mContentResolver.getType(invalidUri)); try { mContentResolver.getType(null); fail("did not throw NullPointerException when Uri is null."); } catch (NullPointerException e) { //expected. } } public void testUnstableGetType() { // Get an unstable refrence on the remote content provider. ContentProviderClient client = mContentResolver.acquireUnstableContentProviderClient( REMOTE_AUTHORITY); // Verify we can access it. String type1 = mContentResolver.getType(REMOTE_TABLE1_URI); assertTrue(type1.startsWith(ContentResolver.CURSOR_DIR_BASE_TYPE, 0)); // Kill it. Note that a bug at this point where it causes our own // process to be killed will result in the entire test failing. try { Log.i("ContentResolverTest", "Killing remote client -- if test process goes away, that is why!"); client.delete(REMOTE_SELF_URI, null, null); } catch (RemoteException e) { } // Make sure the remote client is actually gone. boolean gone = true; try { client.getType(REMOTE_TABLE1_URI); gone = false; } catch (RemoteException e) { } if (!gone) { fail("Content provider process is not gone!"); } // Now the remote client is gone, can we recover? // Release our old reference. client.release(); // Get a new reference. client = mContentResolver.acquireUnstableContentProviderClient(REMOTE_AUTHORITY); // Verify we can access it. type1 = mContentResolver.getType(REMOTE_TABLE1_URI); assertTrue(type1.startsWith(ContentResolver.CURSOR_DIR_BASE_TYPE, 0)); } public void testQuery() { mCursor = mContentResolver.query(TABLE1_URI, null, null, null, null); assertNotNull(mCursor); assertEquals(3, mCursor.getCount()); assertEquals(3, mCursor.getColumnCount()); mCursor.moveToLast(); assertEquals(3, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(KEY3, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(VALUE3, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.moveToPrevious(); assertEquals(2, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(KEY2, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(VALUE2, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.close(); String selection = COLUMN_ID_NAME + "=1"; mCursor = mContentResolver.query(TABLE1_URI, null, selection, null, null); assertNotNull(mCursor); assertEquals(1, mCursor.getCount()); assertEquals(3, mCursor.getColumnCount()); mCursor.moveToFirst(); assertEquals(1, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(KEY1, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(VALUE1, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.close(); selection = COLUMN_KEY_NAME + "=\"" + KEY3 + "\""; mCursor = mContentResolver.query(TABLE1_URI, null, selection, null, null); assertNotNull(mCursor); assertEquals(1, mCursor.getCount()); assertEquals(3, mCursor.getColumnCount()); mCursor.moveToFirst(); assertEquals(3, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(KEY3, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(VALUE3, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.close(); try { mContentResolver.query(null, null, null, null, null); fail("did not throw NullPointerException when uri is null."); } catch (NullPointerException e) { //expected. } } public void testCrashingQuery() { try { MockContentProvider.setCrashOnLaunch(mContext, true); mCursor = mContentResolver.query(REMOTE_CRASH_URI, null, null, null, null); assertFalse(MockContentProvider.getCrashOnLaunch(mContext)); } finally { MockContentProvider.setCrashOnLaunch(mContext, false); } assertNotNull(mCursor); assertEquals(3, mCursor.getCount()); assertEquals(3, mCursor.getColumnCount()); mCursor.moveToLast(); assertEquals(3, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(KEY3, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(VALUE3, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.moveToPrevious(); assertEquals(2, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(KEY2, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(VALUE2, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.close(); } public void testCancelableQuery_WhenNotCanceled_ReturnsResultSet() { CancellationSignal cancellationSignal = new CancellationSignal(); Cursor cursor = mContentResolver.query(TABLE1_URI, null, null, null, null, cancellationSignal); assertEquals(3, cursor.getCount()); cursor.close(); } public void testCancelableQuery_WhenCanceledBeforeQuery_ThrowsImmediately() { CancellationSignal cancellationSignal = new CancellationSignal(); cancellationSignal.cancel(); try { mContentResolver.query(TABLE1_URI, null, null, null, null, cancellationSignal); fail("Expected OperationCanceledException"); } catch (OperationCanceledException ex) { // expected } } public void testCancelableQuery_WhenCanceledDuringLongRunningQuery_CancelsQueryAndThrows() { // Populate a table with a bunch of integers. mContentResolver.delete(TABLE1_URI, null, null); ContentValues values = new ContentValues(); for (int i = 0; i < 100; i++) { values.put(COLUMN_KEY_NAME, i); values.put(COLUMN_VALUE_NAME, i); mContentResolver.insert(TABLE1_URI, values); } for (int i = 0; i < 5; i++) { final CancellationSignal cancellationSignal = new CancellationSignal(); Thread cancellationThread = new Thread() { @Override public void run() { try { Thread.sleep(300); } catch (InterruptedException ex) { } cancellationSignal.cancel(); } }; try { // Build an unsatisfiable 5-way cross-product query over 100 values but // produces no output. This should force SQLite to loop for a long time // as it tests 10^10 combinations. cancellationThread.start(); final long startTime = System.nanoTime(); try { mContentResolver.query(TABLE1_CROSS_URI, null, "a.value + b.value + c.value + d.value + e.value > 1000000", null, null, cancellationSignal); fail("Expected OperationCanceledException"); } catch (OperationCanceledException ex) { // expected } // We want to confirm that the query really was running and then got // canceled midway. final long waitTime = System.nanoTime() - startTime; if (waitTime > 150 * 1000000L && waitTime < 600 * 1000000L) { return; // success! } } finally { try { cancellationThread.join(); } catch (InterruptedException e) { } } } // Occasionally we might miss the timing deadline due to factors in the // environment, but if after several trials we still couldn't demonstrate // that the query was canceled, then the test must be broken. fail("Could not prove that the query actually canceled midway during execution."); } public void testOpenInputStream() throws IOException { final Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + TEST_PACKAGE_NAME + "/" + R.drawable.pass); InputStream is = mContentResolver.openInputStream(uri); assertNotNull(is); is.close(); final Uri invalidUri = Uri.parse("abc"); try { mContentResolver.openInputStream(invalidUri); fail("did not throw FileNotFoundException when uri is invalid."); } catch (FileNotFoundException e) { //expected. } } public void testOpenOutputStream() throws IOException { Uri uri = Uri.parse(ContentResolver.SCHEME_FILE + "://" + getContext().getCacheDir().getAbsolutePath() + "/temp.jpg"); OutputStream os = mContentResolver.openOutputStream(uri); assertNotNull(os); os.close(); os = mContentResolver.openOutputStream(uri, "wa"); assertNotNull(os); os.close(); uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + TEST_PACKAGE_NAME + "/" + R.raw.testimage); try { mContentResolver.openOutputStream(uri); fail("did not throw FileNotFoundException when scheme is not accepted."); } catch (FileNotFoundException e) { //expected. } try { mContentResolver.openOutputStream(uri, "w"); fail("did not throw FileNotFoundException when scheme is not accepted."); } catch (FileNotFoundException e) { //expected. } Uri invalidUri = Uri.parse("abc"); try { mContentResolver.openOutputStream(invalidUri); fail("did not throw FileNotFoundException when uri is invalid."); } catch (FileNotFoundException e) { //expected. } try { mContentResolver.openOutputStream(invalidUri, "w"); fail("did not throw FileNotFoundException when uri is invalid."); } catch (FileNotFoundException e) { //expected. } } public void testOpenAssetFileDescriptor() throws IOException { Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + TEST_PACKAGE_NAME + "/" + R.raw.testimage); AssetFileDescriptor afd = mContentResolver.openAssetFileDescriptor(uri, "r"); assertNotNull(afd); afd.close(); try { mContentResolver.openAssetFileDescriptor(uri, "d"); fail("did not throw FileNotFoundException when mode is unknown."); } catch (FileNotFoundException e) { //expected. } Uri invalidUri = Uri.parse("abc"); try { mContentResolver.openAssetFileDescriptor(invalidUri, "r"); fail("did not throw FileNotFoundException when uri is invalid."); } catch (FileNotFoundException e) { //expected. } } private String consumeAssetFileDescriptor(AssetFileDescriptor afd) throws IOException { FileInputStream stream = null; try { stream = afd.createInputStream(); InputStreamReader reader = new InputStreamReader(stream, "UTF-8"); // Got it... copy the stream into a local string and return it. StringBuilder builder = new StringBuilder(128); char[] buffer = new char[8192]; int len; while ((len=reader.read(buffer)) > 0) { builder.append(buffer, 0, len); } return builder.toString(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { } } } } public void testCrashingOpenAssetFileDescriptor() throws IOException { AssetFileDescriptor afd = null; try { MockContentProvider.setCrashOnLaunch(mContext, true); afd = mContentResolver.openAssetFileDescriptor(REMOTE_CRASH_URI, "rw"); assertFalse(MockContentProvider.getCrashOnLaunch(mContext)); assertNotNull(afd); String str = consumeAssetFileDescriptor(afd); afd = null; assertEquals(str, "This is the openAssetFile test data!"); } finally { MockContentProvider.setCrashOnLaunch(mContext, false); if (afd != null) { afd.close(); } } // Make sure a content provider crash at this point won't hurt us. ContentProviderClient uClient = mContentResolver.acquireUnstableContentProviderClient( REMOTE_AUTHORITY); // Kill it. Note that a bug at this point where it causes our own // process to be killed will result in the entire test failing. try { Log.i("ContentResolverTest", "Killing remote client -- if test process goes away, that is why!"); uClient.delete(REMOTE_SELF_URI, null, null); } catch (RemoteException e) { } uClient.release(); } public void testCrashingOpenTypedAssetFileDescriptor() throws IOException { AssetFileDescriptor afd = null; try { MockContentProvider.setCrashOnLaunch(mContext, true); afd = mContentResolver.openTypedAssetFileDescriptor( REMOTE_CRASH_URI, "text/plain", null); assertFalse(MockContentProvider.getCrashOnLaunch(mContext)); assertNotNull(afd); String str = consumeAssetFileDescriptor(afd); afd = null; assertEquals(str, "This is the openTypedAssetFile test data!"); } finally { MockContentProvider.setCrashOnLaunch(mContext, false); if (afd != null) { afd.close(); } } // Make sure a content provider crash at this point won't hurt us. ContentProviderClient uClient = mContentResolver.acquireUnstableContentProviderClient( REMOTE_AUTHORITY); // Kill it. Note that a bug at this point where it causes our own // process to be killed will result in the entire test failing. try { Log.i("ContentResolverTest", "Killing remote client -- if test process goes away, that is why!"); uClient.delete(REMOTE_SELF_URI, null, null); } catch (RemoteException e) { } uClient.release(); } public void testOpenFileDescriptor() throws IOException { Uri uri = Uri.parse(ContentResolver.SCHEME_FILE + "://" + getContext().getCacheDir().getAbsolutePath() + "/temp.jpg"); ParcelFileDescriptor pfd = mContentResolver.openFileDescriptor(uri, "w"); assertNotNull(pfd); pfd.close(); try { mContentResolver.openFileDescriptor(uri, "d"); fail("did not throw IllegalArgumentException when mode is unknown."); } catch (IllegalArgumentException e) { //expected. } Uri invalidUri = Uri.parse("abc"); try { mContentResolver.openFileDescriptor(invalidUri, "w"); fail("did not throw FileNotFoundException when uri is invalid."); } catch (FileNotFoundException e) { //expected. } uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + TEST_PACKAGE_NAME + "/" + R.raw.testimage); try { mContentResolver.openFileDescriptor(uri, "w"); fail("did not throw FileNotFoundException when scheme is not accepted."); } catch (FileNotFoundException e) { //expected. } } public void testInsert() { String key4 = "key4"; String key5 = "key5"; int value4 = 4; int value5 = 5; String key4Selection = COLUMN_KEY_NAME + "=\"" + key4 + "\""; mCursor = mContentResolver.query(TABLE1_URI, null, key4Selection, null, null); assertEquals(0, mCursor.getCount()); mCursor.close(); ContentValues values = new ContentValues(); values.put(COLUMN_KEY_NAME, key4); values.put(COLUMN_VALUE_NAME, value4); Uri uri = mContentResolver.insert(TABLE1_URI, values); assertNotNull(uri); mCursor = mContentResolver.query(TABLE1_URI, null, key4Selection, null, null); assertNotNull(mCursor); assertEquals(1, mCursor.getCount()); mCursor.moveToFirst(); assertEquals(4, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(key4, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(value4, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.close(); values.put(COLUMN_KEY_NAME, key5); values.put(COLUMN_VALUE_NAME, value5); uri = mContentResolver.insert(TABLE1_URI, values); assertNotNull(uri); // check returned uri mCursor = mContentResolver.query(uri, null, null, null, null); assertNotNull(mCursor); assertEquals(1, mCursor.getCount()); mCursor.moveToLast(); assertEquals(5, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(key5, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(value5, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.close(); try { mContentResolver.insert(null, values); fail("did not throw NullPointerException when uri is null."); } catch (NullPointerException e) { //expected. } } public void testBulkInsert() { String key4 = "key4"; String key5 = "key5"; int value4 = 4; int value5 = 5; mCursor = mContentResolver.query(TABLE1_URI, null, null, null, null); assertNotNull(mCursor); assertEquals(3, mCursor.getCount()); mCursor.close(); ContentValues[] cvs = new ContentValues[2]; cvs[0] = new ContentValues(); cvs[0].put(COLUMN_KEY_NAME, key4); cvs[0].put(COLUMN_VALUE_NAME, value4); cvs[1] = new ContentValues(); cvs[1].put(COLUMN_KEY_NAME, key5); cvs[1].put(COLUMN_VALUE_NAME, value5); assertEquals(2, mContentResolver.bulkInsert(TABLE1_URI, cvs)); mCursor = mContentResolver.query(TABLE1_URI, null, null, null, null); assertNotNull(mCursor); assertEquals(5, mCursor.getCount()); mCursor.moveToLast(); assertEquals(5, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(key5, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(value5, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.moveToPrevious(); assertEquals(4, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(key4, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(value4, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.close(); try { mContentResolver.bulkInsert(null, cvs); fail("did not throw NullPointerException when uri is null."); } catch (NullPointerException e) { //expected. } } public void testDelete() { mCursor = mContentResolver.query(TABLE1_URI, null, null, null, null); assertNotNull(mCursor); assertEquals(3, mCursor.getCount()); mCursor.close(); assertEquals(3, mContentResolver.delete(TABLE1_URI, null, null)); mCursor = mContentResolver.query(TABLE1_URI, null, null, null, null); assertNotNull(mCursor); assertEquals(0, mCursor.getCount()); mCursor.close(); // add three rows to database. ContentValues values = new ContentValues(); values.put(COLUMN_KEY_NAME, KEY1); values.put(COLUMN_VALUE_NAME, VALUE1); mContentResolver.insert(TABLE1_URI, values); values.put(COLUMN_KEY_NAME, KEY2); values.put(COLUMN_VALUE_NAME, VALUE2); mContentResolver.insert(TABLE1_URI, values); values.put(COLUMN_KEY_NAME, KEY3); values.put(COLUMN_VALUE_NAME, VALUE3); mContentResolver.insert(TABLE1_URI, values); // test delete row using selection String selection = COLUMN_ID_NAME + "=2"; assertEquals(1, mContentResolver.delete(TABLE1_URI, selection, null)); mCursor = mContentResolver.query(TABLE1_URI, null, null, null, null); assertNotNull(mCursor); assertEquals(2, mCursor.getCount()); mCursor.moveToFirst(); assertEquals(1, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(KEY1, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(VALUE1, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.moveToNext(); assertEquals(3, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(KEY3, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(VALUE3, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.close(); selection = COLUMN_VALUE_NAME + "=3"; assertEquals(1, mContentResolver.delete(TABLE1_URI, selection, null)); mCursor = mContentResolver.query(TABLE1_URI, null, null, null, null); assertNotNull(mCursor); assertEquals(1, mCursor.getCount()); mCursor.moveToFirst(); assertEquals(1, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(KEY1, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(VALUE1, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.close(); selection = COLUMN_KEY_NAME + "=\"" + KEY1 + "\""; assertEquals(1, mContentResolver.delete(TABLE1_URI, selection, null)); mCursor = mContentResolver.query(TABLE1_URI, null, null, null, null); assertNotNull(mCursor); assertEquals(0, mCursor.getCount()); mCursor.close(); try { mContentResolver.delete(null, null, null); fail("did not throw NullPointerException when uri is null."); } catch (NullPointerException e) { //expected. } } public void testUpdate() { ContentValues values = new ContentValues(); String key10 = "key10"; String key20 = "key20"; int value10 = 10; int value20 = 20; values.put(COLUMN_KEY_NAME, key10); values.put(COLUMN_VALUE_NAME, value10); // test update all the rows. assertEquals(3, mContentResolver.update(TABLE1_URI, values, null, null)); mCursor = mContentResolver.query(TABLE1_URI, null, null, null, null); assertNotNull(mCursor); assertEquals(3, mCursor.getCount()); mCursor.moveToFirst(); assertEquals(1, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(key10, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(value10, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.moveToNext(); assertEquals(2, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(key10, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(value10, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.moveToLast(); assertEquals(3, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(key10, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(value10, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.close(); // test update one row using selection. String selection = COLUMN_ID_NAME + "=1"; values.put(COLUMN_KEY_NAME, key20); values.put(COLUMN_VALUE_NAME, value20); assertEquals(1, mContentResolver.update(TABLE1_URI, values, selection, null)); mCursor = mContentResolver.query(TABLE1_URI, null, null, null, null); assertNotNull(mCursor); assertEquals(3, mCursor.getCount()); mCursor.moveToFirst(); assertEquals(1, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(key20, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(value20, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.moveToNext(); assertEquals(2, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(key10, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(value10, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.moveToLast(); assertEquals(3, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_ID_NAME))); assertEquals(key10, mCursor.getString(mCursor.getColumnIndexOrThrow(COLUMN_KEY_NAME))); assertEquals(value10, mCursor.getInt(mCursor.getColumnIndexOrThrow(COLUMN_VALUE_NAME))); mCursor.close(); try { mContentResolver.update(null, values, null, null); fail("did not throw NullPointerException when uri is null."); } catch (NullPointerException e) { //expected. } // javadoc says it will throw NullPointerException when values are null, // but actually, it throws IllegalArgumentException here. try { mContentResolver.update(TABLE1_URI, null, null, null); fail("did not throw IllegalArgumentException when values are null."); } catch (IllegalArgumentException e) { //expected. } } public void testRegisterContentObserver() { final MockContentObserver mco = new MockContentObserver(); mContentResolver.registerContentObserver(TABLE1_URI, true, mco); assertFalse(mco.hadOnChanged()); ContentValues values = new ContentValues(); values.put(COLUMN_KEY_NAME, "key10"); values.put(COLUMN_VALUE_NAME, 10); mContentResolver.update(TABLE1_URI, values, null, null); new PollingCheck() { @Override protected boolean check() { return mco.hadOnChanged(); } }.run(); mco.reset(); mContentResolver.unregisterContentObserver(mco); assertFalse(mco.hadOnChanged()); mContentResolver.update(TABLE1_URI, values, null, null); assertFalse(mco.hadOnChanged()); try { mContentResolver.registerContentObserver(null, false, mco); fail("did not throw NullPointerException or IllegalArgumentException when uri is null."); } catch (NullPointerException e) { //expected. } catch (IllegalArgumentException e) { // also expected } try { mContentResolver.registerContentObserver(TABLE1_URI, false, null); fail("did not throw NullPointerException when register null content observer."); } catch (NullPointerException e) { //expected. } try { mContentResolver.unregisterContentObserver(null); fail("did not throw NullPointerException when unregister null content observer."); } catch (NullPointerException e) { //expected. } } public void testRegisterContentObserverDescendantBehavior() throws Exception { final MockContentObserver mco1 = new MockContentObserver(); final MockContentObserver mco2 = new MockContentObserver(); // Register one content observer with notifyDescendants set to false, and // another with true. mContentResolver.registerContentObserver(LEVEL2_URI, false, mco1); mContentResolver.registerContentObserver(LEVEL2_URI, true, mco2); // Initially nothing has happened. assertFalse(mco1.hadOnChanged()); assertFalse(mco2.hadOnChanged()); // Fire a change with the exact URI. // Should signal both observers due to exact match, notifyDescendants doesn't matter. mContentResolver.notifyChange(LEVEL2_URI, null); Thread.sleep(200); assertTrue(mco1.hadOnChanged()); assertTrue(mco2.hadOnChanged()); mco1.reset(); mco2.reset(); // Fire a change with a descendant URI. // Should only signal observer with notifyDescendants set to true. mContentResolver.notifyChange(LEVEL3_URI, null); Thread.sleep(200); assertFalse(mco1.hadOnChanged()); assertTrue(mco2.hadOnChanged()); mco2.reset(); // Fire a change with an ancestor URI. // Should signal both observers due to ancestry, notifyDescendants doesn't matter. mContentResolver.notifyChange(LEVEL1_URI, null); Thread.sleep(200); assertTrue(mco1.hadOnChanged()); assertTrue(mco2.hadOnChanged()); mco1.reset(); mco2.reset(); // Fire a change with an unrelated URI. // Should signal neither observer. mContentResolver.notifyChange(TABLE1_URI, null); Thread.sleep(200); assertFalse(mco1.hadOnChanged()); assertFalse(mco2.hadOnChanged()); } public void testNotifyChange1() { final MockContentObserver mco = new MockContentObserver(); mContentResolver.registerContentObserver(TABLE1_URI, true, mco); assertFalse(mco.hadOnChanged()); mContentResolver.notifyChange(TABLE1_URI, mco); new PollingCheck() { @Override protected boolean check() { return mco.hadOnChanged(); } }.run(); mContentResolver.unregisterContentObserver(mco); } public void testNotifyChange2() { final MockContentObserver mco = new MockContentObserver(); mContentResolver.registerContentObserver(TABLE1_URI, true, mco); assertFalse(mco.hadOnChanged()); mContentResolver.notifyChange(TABLE1_URI, mco, false); new PollingCheck() { @Override protected boolean check() { return mco.hadOnChanged(); } }.run(); mContentResolver.unregisterContentObserver(mco); } public void testStartCancelSync() { Bundle extras = new Bundle(); extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync(ACCOUNT, AUTHORITY, extras); //FIXME: how to get the result to assert. ContentResolver.cancelSync(ACCOUNT, AUTHORITY); //FIXME: how to assert. } public void testStartSyncFailure() { try { ContentResolver.requestSync(null, null, null); fail("did not throw IllegalArgumentException when extras is null."); } catch (IllegalArgumentException e) { //expected. } } public void testValidateSyncExtrasBundle() { Bundle extras = new Bundle(); extras.putInt("Integer", 20); extras.putLong("Long", 10l); extras.putBoolean("Boolean", true); extras.putFloat("Float", 5.5f); extras.putDouble("Double", 2.5); extras.putString("String", "cts"); extras.putCharSequence("CharSequence", null); ContentResolver.validateSyncExtrasBundle(extras); extras.putChar("Char", 'a'); // type Char is invalid try { ContentResolver.validateSyncExtrasBundle(extras); fail("did not throw IllegalArgumentException when extras is invalide."); } catch (IllegalArgumentException e) { //expected. } } private class MockContentObserver extends ContentObserver { private boolean mHadOnChanged = false; public MockContentObserver() { super(null); } @Override public boolean deliverSelfNotifications() { return true; } @Override public synchronized void onChange(boolean selfChange) { super.onChange(selfChange); mHadOnChanged = true; } public synchronized boolean hadOnChanged() { return mHadOnChanged; } public synchronized void reset() { mHadOnChanged = false; } } }
gpl-3.0
eadgyo/GX-Script
src/main/java/org/eadge/gxscript/test/validator/TestValidateNoInterdependency.java
4551
package org.eadge.gxscript.test.validator; import org.eadge.gxscript.data.entity.classic.entity.displayer.PrintGXEntity; import org.eadge.gxscript.data.entity.classic.entity.imbrication.conditionals.IfGXEntity; import org.eadge.gxscript.data.entity.classic.entity.types.number.RealGXEntity; import org.eadge.gxscript.data.entity.classic.entity.types.number.comparison.EqualToNumberGXEntity; import org.eadge.gxscript.data.compile.script.RawGXScript; import org.eadge.gxscript.test.CreateGXScript; import org.eadge.gxscript.test.PrintTest; import org.eadge.gxscript.tools.check.validator.ValidateNoInterdependency; import org.eadge.gxscript.tools.check.ValidatorModel; import java.io.IOException; /** * Created by eadgyo on 12/08/16. * * Test detection of interdependency */ public class TestValidateNoInterdependency { public static void main(String[] args) throws IOException { System.out.println("Test validate no interdependency"); PrintTest.printResult(testCorrect(), "Check valid script"); PrintTest.printResult(testInterdependency0(), "Check script with interdependency 0"); PrintTest.printResult(testInterdependency1(), "Check script with interdependency 1"); } public static boolean testCorrect() { RawGXScript scriptIf = CreateGXScript.createScriptIf(); ValidatorModel validator = new ValidateNoInterdependency(); return validator.validate(scriptIf); } public static boolean testInterdependency0() { RawGXScript script = new RawGXScript(); // Create new GXEntity RealGXEntity realEntity = new RealGXEntity(); // Create start GXEntity PrintGXEntity printEntity = new PrintGXEntity("Test"); // Add direct self interdependency link realEntity.linkAsInput(RealGXEntity.SET_INPUT_INDEX, RealGXEntity.REAL_OUTPUT_INDEX, realEntity); realEntity.linkAsInput(RealGXEntity.NEXT_INPUT_INDEX, PrintGXEntity.CONTINUE_OUTPUT_INDEX, printEntity); // Update starting entities script.addEntity(printEntity); script.addEntity(realEntity); script.updateEntities(); ValidatorModel validator = new ValidateNoInterdependency(); return !validator.validate(script); } public static boolean testInterdependency1() { // Create entities RawGXScript script = new RawGXScript(); // Create 3 real variables RealGXEntity realEntity1 = new RealGXEntity(20f); RealGXEntity realEntity2 = new RealGXEntity(10f); RealGXEntity realEntity3 = new RealGXEntity(); // Link realEntity2 on realEntity3 script realEntity3.linkAsInput(RealGXEntity.SET_INPUT_INDEX, RealGXEntity.REAL_OUTPUT_INDEX, realEntity2); // Create real comparison EqualToNumberGXEntity equalToNumberEntity = new EqualToNumberGXEntity(); equalToNumberEntity.linkAsInput(EqualToNumberGXEntity.V0_INPUT_INDEX, RealGXEntity.REAL_OUTPUT_INDEX, realEntity1); equalToNumberEntity.linkAsInput(EqualToNumberGXEntity.V1_INPUT_INDEX, RealGXEntity.REAL_OUTPUT_INDEX, realEntity2); // Create if GXEntity block control IfGXEntity ifEntity = new IfGXEntity(); ifEntity.linkAsInput(IfGXEntity.TEST_INPUT_INDEX, EqualToNumberGXEntity.RESULT_OUTPUT_INDEX, equalToNumberEntity); // Create 3 prints for each path PrintGXEntity success = new PrintGXEntity("Success"); success.linkAsInput(PrintGXEntity.NEXT_INPUT_INDEX, IfGXEntity.SUCCESS_OUTPUT_INDEX, ifEntity); PrintGXEntity fail = new PrintGXEntity("Fail"); fail.linkAsInput(PrintGXEntity.NEXT_INPUT_INDEX, IfGXEntity.FAIL_OUTPUT_INDEX, ifEntity); PrintGXEntity continueP = new PrintGXEntity("Continue"); continueP.linkAsInput(PrintGXEntity.NEXT_INPUT_INDEX, IfGXEntity.CONTINUE_OUTPUT_INDEX, ifEntity); // Add all created entities to raw gx script script.addEntity(realEntity1); script.addEntity(realEntity2); script.addEntity(realEntity3); script.addEntity(equalToNumberEntity); script.addEntity(ifEntity); script.addEntity(success); script.addEntity(fail); script.addEntity(continueP); // Addd interdepency one imbricated and the first added GXEntity realEntity1.linkAsInput(RealGXEntity.NEXT_INPUT_INDEX, PrintGXEntity.CONTINUE_OUTPUT_INDEX, success); ValidatorModel validator = new ValidateNoInterdependency(); return !validator.validate(script); } }
gpl-3.0
AKSW/DL-Learner
interfaces/src/main/java/org/dllearner/cli/CLIBase2.java
4499
package org.dllearner.cli; import org.apache.commons.lang.exception.ExceptionUtils; import org.dllearner.configuration.IConfiguration; import org.dllearner.configuration.spring.ApplicationContextBuilder; import org.dllearner.configuration.spring.DefaultApplicationContextBuilder; import org.dllearner.confparser.ConfParserConfiguration; import org.dllearner.core.AbstractReasonerComponent; import org.dllearner.core.ComponentInitException; import org.dllearner.core.config.ConfigOption; import org.dllearner.reasoning.ClosedWorldReasoner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Base CLI class. */ public abstract class CLIBase2 { static { if (System.getProperty("log4j.configuration") == null) System.setProperty("log4j.configuration", "log4j.properties"); } private static Logger logger = LoggerFactory.getLogger(CLIBase2.class); protected ApplicationContext context; protected File confFile; protected IConfiguration configuration; @ConfigOption(defaultValue = "INFO", description = "Configure logger log level from conf file. Available levels: \"FATAL\", \"ERROR\", \"WARN\", \"INFO\", \"DEBUG\", \"TRACE\". " + "Note, to see results, at least \"INFO\" is required.") protected String logLevel = "INFO"; protected static boolean createIfNotExists(File f) { if (f.exists()) return true; File p = f.getParentFile(); if (p != null && !p.exists()) p.mkdirs(); try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } /** * Find the primary cause of the specified exception. * * @param e The exception to analyze * @return The primary cause of the exception. */ protected static Throwable findPrimaryCause(Exception e) { // The throwables from the stack of the exception Throwable[] throwables = ExceptionUtils.getThrowables(e); //Look For a Component Init Exception and use that as the primary cause of failure, if we find it int componentInitExceptionIndex = ExceptionUtils.indexOfThrowable(e, ComponentInitException.class); Throwable primaryCause; if(componentInitExceptionIndex > -1) { primaryCause = throwables[componentInitExceptionIndex]; }else { //No Component Init Exception on the Stack Trace, so we'll use the root as the primary cause. primaryCause = ExceptionUtils.getRootCause(e); } return primaryCause; } // separate init methods, because some scripts may want to just get the application // context from a conf file without actually running it public void init() throws IOException { Resource confFileR = new FileSystemResource(confFile); List<Resource> springConfigResources = new ArrayList<>(); configuration = new ConfParserConfiguration(confFileR); ApplicationContextBuilder builder = new DefaultApplicationContextBuilder(); context = builder.buildApplicationContext(configuration, springConfigResources); } public abstract void run(); public void close() { ((ConfigurableApplicationContext)context).close(); } public void setContext(ApplicationContext context) { this.context = context; } public ApplicationContext getContext() { return context; } public File getConfFile() { return confFile; } public void setConfFile(File confFile) { this.confFile = confFile; } public void setLogLevel(String logLevel) { this.logLevel = logLevel; } public String getLogLevel() { return logLevel; } protected AbstractReasonerComponent getMainReasonerComponent() { AbstractReasonerComponent rc = null; // there can be 2 reasoner beans Map<String, AbstractReasonerComponent> reasonerBeans = context.getBeansOfType(AbstractReasonerComponent.class); if (reasonerBeans.size() > 1) { for (Map.Entry<String, AbstractReasonerComponent> entry : reasonerBeans.entrySet()) { String key = entry.getKey(); AbstractReasonerComponent value = entry.getValue(); if (value instanceof ClosedWorldReasoner) { rc = value; } } } else { rc = context.getBean(AbstractReasonerComponent.class); } return rc; } }
gpl-3.0
yyxhdy/ManyEAs
src/jmetal/operators/mutation/UniformMutation.java
3874
// UniformMutation.java // // Author: // Antonio J. Nebro <antonio@lcc.uma.es> // Juan J. Durillo <durillo@lcc.uma.es> // // Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo // // This program 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. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package jmetal.operators.mutation; import jmetal.core.Solution; import jmetal.encodings.solutionType.ArrayRealSolutionType; import jmetal.encodings.solutionType.BinaryRealSolutionType; import jmetal.encodings.solutionType.RealSolutionType; import jmetal.util.Configuration; import jmetal.util.JMException; import jmetal.util.PseudoRandom; import jmetal.util.wrapper.XReal; import java.util.Arrays; import java.util.HashMap; import java.util.List; /** * This class implements a uniform mutation operator. */ public class UniformMutation extends Mutation { /** * Valid solution types to apply this operator */ private static final List VALID_TYPES = Arrays.asList( RealSolutionType.class, ArrayRealSolutionType.class, BinaryRealSolutionType.class); /** * Stores the value used in a uniform mutation operator */ private Double perturbation_; private Double mutationProbability_ = null; /** * Constructor Creates a new uniform mutation operator instance */ public UniformMutation(HashMap<String, Object> parameters) { super(parameters); if (parameters.get("probability") != null) mutationProbability_ = (Double) parameters.get("probability"); if (parameters.get("perturbation") != null) perturbation_ = (Double) parameters.get("perturbation"); } // UniformMutation /** * Constructor Creates a new uniform mutation operator instance */ // public UniformMutation(Properties properties) { // this(); // } // UniformMutation /** * Performs the operation * * @param probability * Mutation probability * @param solution * The solution to mutate * @throws JMException */ public void doMutation(double probability, Solution solution) throws JMException { XReal x = new XReal(solution); for (int var = 0; var < solution.getDecisionVariables().length; var++) { if (PseudoRandom.randDouble() < probability) { double rand = PseudoRandom.randDouble(); double tmp = (rand - 0.5) * perturbation_.doubleValue(); tmp += x.getValue(var); if (tmp < x.getLowerBound(var)) tmp = x.getLowerBound(var); else if (tmp > x.getUpperBound(var)) tmp = x.getUpperBound(var); x.setValue(var, tmp); } // if } // for } // doMutation /** * Executes the operation * * @param object * An object containing the solution to mutate * @throws JMException */ public Object execute(Object object) throws JMException { Solution solution = (Solution) object; if (!VALID_TYPES.contains(solution.getType().getClass())) { Configuration.logger_ .severe("UniformMutation.execute: the solution " + "is not of the right type. The type should be 'Real', but " + solution.getType() + " is obtained"); Class cls = java.lang.String.class; String name = cls.getName(); throw new JMException("Exception in " + name + ".execute()"); } // if doMutation(mutationProbability_, solution); return solution; } // execute } // UniformMutation
gpl-3.0
alex1788/javaRush
src/com/javarush/test/level06/lesson08/task01/Cat.java
459
package com.javarush.test.level06.lesson08.task01; /* Класс Cat и статическая переменная catCount Создать статическую переменную int catCount в классе Cat. Создай конструктор [public Cat()], в котором увеличивай данную переменную на 1. */ public class Cat { public static int catCount = 0; public Cat(){ catCount++; } }
gpl-3.0
OOP-Team-11/RoadsAndBoats
src/main/game/model/movement/River.java
870
package game.model.movement; import game.model.direction.TileCompartmentDirection; import game.model.direction.TileEdgeDirection; import game.model.tile.TileCompartment; public class River { private TileCompartment destination; private TileCompartmentDirection compartmentDirection; public River(TileCompartmentDirection compartmentDirection) { this.compartmentDirection = compartmentDirection; } public void setDestination(TileCompartment destination) { this.destination=destination; } public TileCompartment getDestination() { return destination; } public TileCompartmentDirection getCompartmentDirection() { return compartmentDirection; } public TileEdgeDirection getEdgeDirection() { return new TileEdgeDirection(compartmentDirection.getAngle()); } }
gpl-3.0
SuperMap-iDesktop/SuperMap-iDesktop-Cross
Controls/src/main/java/com/supermap/desktop/process/parameters/ParameterPanels/ParameterDatasetChooserPanel.java
5467
package com.supermap.desktop.process.parameters.ParameterPanels; import com.supermap.data.Dataset; import com.supermap.data.Datasource; import com.supermap.data.Datasources; import com.supermap.desktop.Application; import com.supermap.desktop.process.enums.ParameterType; import com.supermap.desktop.process.parameter.interfaces.IParameter; import com.supermap.desktop.process.parameter.interfaces.IParameterPanel; import com.supermap.desktop.process.parameter.interfaces.ParameterPanelDescribe; import com.supermap.desktop.process.parameter.ipls.ParameterDatasetChooser; import com.supermap.desktop.process.util.ParameterUtil; import com.supermap.desktop.properties.CommonProperties; import com.supermap.desktop.ui.controls.DialogResult; import com.supermap.desktop.ui.controls.GridBagConstraintsHelper; import com.supermap.desktop.ui.controls.datasetChoose.DatasetChooser; import com.supermap.desktop.utilities.DatasourceUtilities; import com.supermap.desktop.utilities.StringUtilities; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * Created by xie on 2017/6/27. */ @ParameterPanelDescribe(parameterPanelType = ParameterType.DATASET_CHOOSER) public class ParameterDatasetChooserPanel extends SwingPanel implements IParameterPanel { private ParameterDatasetChooser datasetChooser; private JLabel labelDatasetName; private JTextField textFieldDatasetName; private JButton buttonChooseDataset; private boolean isSelectingItem = false; public ParameterDatasetChooserPanel(IParameter datasetChooser) { super(datasetChooser); this.datasetChooser = (ParameterDatasetChooser) datasetChooser; init(); } private void init() { initComponents(); initResources(); initLayout(); registEvents(); } private void initComponents() { this.labelDatasetName = new JLabel(); this.textFieldDatasetName = new JTextField(); this.buttonChooseDataset = new JButton(); if (null != datasetChooser.getSelectedItem()) { this.textFieldDatasetName.setText(((Dataset) datasetChooser.getSelectedItem()).getName()); } this.labelDatasetName.setEnabled(this.datasetChooser.isEnabled()); this.textFieldDatasetName.setEnabled(this.datasetChooser.isEnabled()); this.buttonChooseDataset.setEnabled(this.datasetChooser.isEnabled()); } private void initResources() { this.labelDatasetName.setText(CommonProperties.getString("String_Dataset")); this.buttonChooseDataset.setText(CommonProperties.getString("String_Choose")); } private void initLayout() { this.labelDatasetName.setPreferredSize(ParameterUtil.LABEL_DEFAULT_SIZE); this.textFieldDatasetName.setPreferredSize(new Dimension(20, 23)); this.panel.setLayout(new GridBagLayout()); this.panel.add(this.labelDatasetName, new GridBagConstraintsHelper(0, 0, 1, 1).setAnchor(GridBagConstraints.WEST).setFill(GridBagConstraints.NONE).setWeight(0, 0)); this.panel.add(this.textFieldDatasetName, new GridBagConstraintsHelper(1, 0, 2, 1).setAnchor(GridBagConstraints.WEST).setFill(GridBagConstraints.HORIZONTAL).setInsets(0, 5, 0, 0).setWeight(1, 0)); this.panel.add(this.buttonChooseDataset, new GridBagConstraintsHelper(3, 0, 1, 1).setAnchor(GridBagConstraints.WEST).setFill(GridBagConstraints.NONE).setInsets(0, 5, 0, 0)); } private void registEvents() { this.buttonChooseDataset.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (isSelectingItem == false) { isSelectingItem = true; DatasetChooser tempDatasetChooser = new DatasetChooser(null) { @Override protected boolean isSupportDatasource(Datasource datasource) { return !DatasourceUtilities.isWebDatasource(datasource.getEngineType()) && super.isSupportDatasource(datasource); } }; tempDatasetChooser.setSupportDatasetTypes(datasetChooser.getSupportTypes()); tempDatasetChooser.setSelectionModel(ListSelectionModel.SINGLE_SELECTION); if (tempDatasetChooser.showDialog() == DialogResult.OK) { datasetChooser.setSelectedItem(tempDatasetChooser.getSelectedDatasets().get(0)); textFieldDatasetName.setText(tempDatasetChooser.getSelectedDatasets().get(0).getName()); } isSelectingItem = false; } } }); this.textFieldDatasetName.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { setDataset(); } @Override public void removeUpdate(DocumentEvent e) { setDataset(); } @Override public void changedUpdate(DocumentEvent e) { setDataset(); } private void setDataset() { if (!isSelectingItem) { isSelectingItem = true; String datasetName = textFieldDatasetName.getText(); if (!StringUtilities.isNullOrEmpty(datasetName)) { Datasources datasources = Application.getActiveApplication().getWorkspace().getDatasources(); for (int i = 0; i < datasources.getCount(); i++) { Datasource tempDatasource = datasources.get(i); if (null != DatasourceUtilities.getDataset(datasetName, tempDatasource)) { datasetChooser.setSelectedItem(DatasourceUtilities.getDataset(datasetName, tempDatasource)); } } } isSelectingItem = false; } } }); } public static void main(String[] args) { new ParameterDatasetChooserPanel(new ParameterDatasetChooser()); } }
gpl-3.0
hcmlab/ssj
libssj/src/main/java/hcm/ssj/signal/Envelope.java
5380
/* * Envelope.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This 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 General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj.signal; import hcm.ssj.core.Cons; import hcm.ssj.core.Log; import hcm.ssj.core.SSJFatalException; import hcm.ssj.core.Transformer; import hcm.ssj.core.option.Option; import hcm.ssj.core.option.OptionList; import hcm.ssj.core.stream.Stream; /** * Computes the envelope of the input signal * * An envelope detector is an electronic circuit that takes a high-frequency signal as input and provides * an output which is the envelope of the original signal. * The capacitor in the circuit stores up charge on the rising edge, and releases it slowly through the * resistor when the signal falls. The diode in series rectifies the incoming signal, allowing current * flow only when the positive input terminal is at a higher potential than the negative input terminal. * (Wikipedia) * * Created by Johnny on 01.04.2015. */ public class Envelope extends Transformer { @Override public OptionList getOptions() { return options; } public class Options extends OptionList { public final Option<Float> attackSlope = new Option<>("attackSlope", 0.1f, Float.class, "increment by which the envelope should increase each sample"); public final Option<Float> releaseSlope = new Option<>("releaseSlope", 0.1f, Float.class, "increment by which the envelope should decrease each sample"); /** * */ private Options() { addOptions(); } } public final Options options = new Options(); float[] _lastValue; public Envelope() { _name = "Envelope"; } @Override public void enter(Stream[] stream_in, Stream stream_out) throws SSJFatalException { _lastValue = new float[stream_in[0].dim]; for (int i = 0; i < _lastValue.length; ++i) { _lastValue[i] = 0; } } @Override public void transform(Stream[] stream_in, Stream stream_out) throws SSJFatalException { float[] data = stream_in[0].ptrF(); float[] out = stream_out.ptrF(); int dim = stream_in[0].dim; float valNew, valOld; for(int j = 0; j < stream_in[0].dim; ++j) { for(int i = 0; i < stream_in[0].num; ++i) { valNew = data[i * dim + j]; valOld = (i > 1) ? out[(i-1) * dim + j] : _lastValue[j]; if (valNew > valOld) { out[i * dim + j] = (valOld + options.attackSlope.get() > valNew) ? valNew : valOld + options.attackSlope.get(); } else if (valNew < valOld) { out[i * dim + j] = (valOld - options.releaseSlope.get() < valNew) ? valNew : valOld - options.releaseSlope.get(); } else if (valNew == valOld) { out[i * dim + j] = valOld; } } _lastValue[j] = out[(stream_in[0].num -1) * dim + j]; } } @Override public void flush(Stream[] stream_in, Stream stream_out) throws SSJFatalException {} @Override public int getSampleDimension(Stream[] stream_in) { if(stream_in[0].dim != 1) Log.e("can only handle 1-dimensional streams"); return 1; } @Override public int getSampleNumber(int sampleNumber_in) { return sampleNumber_in; } @Override public int getSampleBytes(Stream[] stream_in) { if(stream_in[0].bytes != 4) //float Log.e("Unsupported input stream type"); return 4; //float } @Override public Cons.Type getSampleType(Stream[] stream_in) { if(stream_in[0].type != Cons.Type.FLOAT) Log.e("Unsupported input stream type"); return Cons.Type.FLOAT; } @Override public void describeOutput(Stream[] stream_in, Stream stream_out) { stream_out.desc = new String[stream_in[0].dim]; System.arraycopy(stream_in[0].desc, 0, stream_out.desc, 0, stream_in[0].desc.length); } }
gpl-3.0
greenaddress/GreenBits
app/src/main/java/com/greenaddress/greenbits/ui/SignUpActivity.java
14885
package com.greenaddress.greenbits.ui; import android.app.Dialog; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.BitmapDrawable; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.Ndef; import android.nfc.tech.NdefFormatable; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import com.afollestad.materialdialogs.MaterialDialog; import com.afollestad.materialdialogs.Theme; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.greenaddress.greenapi.CryptoHelper; import com.greenaddress.greenapi.LoginData; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; public class SignUpActivity extends LoginActivity implements View.OnClickListener { private static final int PINSAVE = 1337; private static final int VERIFY_COUNT = 4; private boolean mWriteMode; private Dialog mMnemonicDialog; private Dialog mNfcDialog; private Dialog mVerifyDialog; private NfcAdapter mNfcAdapter; private PendingIntent mNfcPendingIntent; private View mNfcView; private ImageView mNfcSignupIcon; private TextView mMnemonicText; private CheckBox mAcceptCheckBox; private CircularButton mContinueButton; private TextView mQrCodeIcon; private ImageView mQrCodeBitmap; private ArrayList<Integer> mWordChoices; private boolean[] mChoiceIsValid; private ListenableFuture<LoginData> mOnSignUp; private final Runnable mNfcDialogCB = new Runnable() { public void run() { mWriteMode = false; } }; private final Runnable mVerifyDialogCB = new Runnable() { public void run() { onVerifyDismissed(); } }; @Override protected int getMainViewId() { return R.layout.activity_sign_up; } @Override protected void onCreateWithService(final Bundle savedInstanceState) { setTitleWithNetwork(R.string.title_activity_sign_up); mNfcAdapter = NfcAdapter.getDefaultAdapter(this); mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, SignUpActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); mNfcView = UI.inflateDialog(SignUpActivity.this, R.layout.dialog_nfc_write); mMnemonicText = UI.find(this, R.id.signupMnemonicText); mQrCodeIcon = UI.find(this, R.id.signupQrCodeIcon); mAcceptCheckBox = UI.find(this, R.id.signupAcceptCheckBox); mContinueButton = UI.find(this, R.id.signupContinueButton); mNfcSignupIcon = UI.find(this, R.id.signupNfcIcon); mMnemonicText.setText(mService.getSignUpMnemonic()); if (mOnSignUp != null) { UI.disable(mAcceptCheckBox); mAcceptCheckBox.setChecked(true); UI.enable(mContinueButton); } final TextView termsText = UI.find(this, R.id.textTosLink); termsText.setMovementMethod(LinkMovementMethod.getInstance()); mQrCodeIcon.setOnClickListener(this); mContinueButton.setOnClickListener(this); mNfcSignupIcon.setOnClickListener(this); mWordChoices = new ArrayList<>(24); for (int i = 0; i < 24; ++i) mWordChoices.add(i); mChoiceIsValid = new boolean[VERIFY_COUNT]; } @Override public void onResumeWithService() { if (mNfcAdapter != null) { final IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED); final IntentFilter[] filters = new IntentFilter[]{filter}; mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent, filters, null); } UI.showIf(mNfcAdapter != null && mNfcAdapter.isEnabled(), mNfcSignupIcon); } @Override public void onPauseWithService() { if (mNfcAdapter != null) mNfcAdapter.disableForegroundDispatch(this); if (mContinueButton != null) { mContinueButton.stopLoading(); } } @Override public void onDestroy() { super.onDestroy(); UI.unmapClick(mQrCodeIcon); UI.unmapClick(mContinueButton); UI.unmapClick(mNfcSignupIcon); mMnemonicDialog = UI.dismiss(this, mMnemonicDialog); mNfcDialog = UI.dismiss(this, mNfcDialog); mNfcView = null; if (mChoiceIsValid != null) mChoiceIsValid[0] = false; mVerifyDialog = UI.dismiss(this, mVerifyDialog); } @Override public void onClick(final View v) { if (v == mQrCodeIcon) onQrCodeButtonClicked(); else if (v == mContinueButton) onContinueButtonClicked(); else if (v == mNfcSignupIcon) onNfcSignupButtonClicked(); } private void onQrCodeButtonClicked() { if (mMnemonicDialog == null) { final View v = UI.inflateDialog(this, R.layout.dialog_qrcode); mQrCodeBitmap = UI.find(v, R.id.qrInDialogImageView); mQrCodeBitmap.setLayoutParams(UI.getScreenLayout(SignUpActivity.this, 0.8)); mMnemonicDialog = new Dialog(SignUpActivity.this); mMnemonicDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE); mMnemonicDialog.setContentView(v); } mMnemonicDialog.show(); final BitmapDrawable bd = new BitmapDrawable(getResources(), mService.getSignUpQRCode()); bd.setFilterBitmap(false); mQrCodeBitmap.setImageDrawable(bd); } private void onContinueButtonClicked() { int errorId = 0; if (!mService.isConnected()) errorId = R.string.notConnected; else if (!mAcceptCheckBox.isChecked()) errorId = R.string.securePassphraseMsg; else if (mOnSignUp != null) errorId = R.string.signupInProgress; if (errorId != 0) { toast(errorId); return; } mContinueButton.startLoading(); UI.hide(mMnemonicText, mQrCodeIcon); // Create a random shuffle of word orders; the user will be asked // to verify the first VERIFY_COUNT words. Collections.shuffle(mWordChoices); for (int i = 0; i < mChoiceIsValid.length; ++i) mChoiceIsValid[i] = false; // Show the verification dialog final View v = UI.inflateDialog(this, R.layout.dialog_verify_words); mVerifyDialog = new MaterialDialog.Builder(SignUpActivity.this) .title(R.string.enter_matching_words) .customView(v, true) .titleColorRes(R.color.white) .contentColorRes(android.R.color.white) .theme(Theme.DARK) .build(); UI.setDialogCloseHandler(mVerifyDialog, mVerifyDialogCB, false); final String[] words = UI.getText(mMnemonicText).split(" "); setupWord(v, R.id.verify_label_1, R.id.verify_word_1, words, 0); setupWord(v, R.id.verify_label_2, R.id.verify_word_2, words, 1); setupWord(v, R.id.verify_label_3, R.id.verify_word_3, words, 2); setupWord(v, R.id.verify_label_4, R.id.verify_word_4, words, 3); mVerifyDialog.show(); } private void onMnemonicVerified() { mOnSignUp = mService.signup(UI.getText(mMnemonicText)); Futures.addCallback(mOnSignUp, new FutureCallback<LoginData>() { @Override public void onSuccess(final LoginData result) { onSignUpCompleted(); } @Override public void onFailure(final Throwable t) { setComplete(false); mOnSignUp = null; t.printStackTrace(); toast(t.getMessage()); } }, mService.getExecutor()); } private void onNfcSignupButtonClicked() { if (mNfcDialog == null) { mNfcDialog = new MaterialDialog.Builder(SignUpActivity.this) .title(R.string.nfcDialogMessage) .customView(mNfcView, true) .titleColorRes(R.color.white) .contentColorRes(android.R.color.white) .theme(Theme.DARK).build(); UI.setDialogCloseHandler(mNfcDialog, mNfcDialogCB, true /* cancelOnly */); } mWriteMode = true; mNfcDialog.show(); } private void setComplete(final boolean isComplete) { runOnUiThread(new Runnable() { public void run() { mContinueButton.setComplete(isComplete); } }); } private void onSignUpCompleted() { setComplete(true); mService.resetSignUp(); mOnSignUp = null; final Intent savePin = PinSaveActivity.createIntent(SignUpActivity.this, mService.getMnemonic()); startActivityForResult(savePin, PINSAVE); } private void incrementTagsWritten() { final TextView tagsWrittenText = UI.find(mNfcView, R.id.nfcTagsWrittenText); final Integer written = Integer.parseInt(UI.getText(tagsWrittenText)); tagsWrittenText.setText(String.valueOf(written + 1)); } @Override protected void onNewIntent(final Intent intent) { super.onNewIntent(intent); if (!mWriteMode || !NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) return; final Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); final byte[] seed = CryptoHelper.mnemonic_to_bytes(UI.getText(mMnemonicText)); final NdefRecord[] record = new NdefRecord[1]; record[0] = NdefRecord.createMime("x-gait/mnc", seed); final NdefMessage message = new NdefMessage(record); final int size = message.toByteArray().length; try { final Ndef ndef = Ndef.get(detectedTag); if (ndef != null) { ndef.connect(); if (!ndef.isWritable()) shortToast(R.string.err_sign_up_nfc_not_writable); if (ndef.getMaxSize() < size) shortToast(R.string.err_sign_up_nfc_too_small); ndef.writeNdefMessage(message); incrementTagsWritten(); } else { final NdefFormatable format = NdefFormatable.get(detectedTag); if (format != null) try { format.connect(); format.format(message); incrementTagsWritten(); } catch (final IOException e) { } } } catch (final Exception e) { } } @Override public void onBackPressed() { if (mOnSignUp != null) { mService.resetSignUp(); mOnSignUp = null; mService.disconnect(true); } super.onBackPressed(); } @Override public boolean onCreateOptionsMenu(final Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.common_menu, menu); return true; } @Override public boolean onOptionsItemSelected(final 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. return item.getItemId() == R.id.action_settings || super.onOptionsItemSelected(item); } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case PINSAVE: onLoginSuccess(); break; } } void setupWord(final View v, final int labelId, final int spinnerId, final String[] words, final int index) { final int wordIndex = mWordChoices.get(index); final String validWord = words[wordIndex]; final TextView label = UI.find(v, labelId); final AutoCompleteTextView text = UI.find(v, spinnerId); label.setText(getString(R.string.hash_number, wordIndex + 1)); final ArrayAdapter<String> adapter; adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, MnemonicHelper.mWordsArray); text.setAdapter(adapter); text.setThreshold(1); text.addTextChangedListener(new UI.TextWatcher() { @Override public void onTextChanged(final CharSequence t, final int start, final int before, final int count) { final AutoCompleteTextView tv = UI.find(v, spinnerId); onWordChanged(label, tv, index, validWord, true); } }); text.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { final AutoCompleteTextView tv = UI.find(v, spinnerId); onWordChanged(label, tv, index, validWord, false); } }); } private void onWordChanged(final TextView label, final AutoCompleteTextView text, final int index, final String validWord, final boolean isTextChange) { if (isTextChange && text.isPerformingCompletion()) return; // Let the call from onItemClick handle it final boolean isValid = UI.getText(text).equals(validWord); mChoiceIsValid[index] = isValid; if (isValid) { UI.hide(label, text); if (areAllChoicesValid()) UI.dismiss(this, mVerifyDialog); // Dismiss callback will continue } } private boolean areAllChoicesValid() { if (mChoiceIsValid == null) return false; for (final boolean isValid : mChoiceIsValid) if (!isValid) return false; return true; } private void onVerifyDismissed() { if (mVerifyDialog != null) { UI.show(mMnemonicText, mQrCodeIcon); mContinueButton.stopLoading(); mVerifyDialog = null; if (areAllChoicesValid()) onMnemonicVerified(); } } }
gpl-3.0
theAprel/Archive
src/aprel/optical/Isoifier.java
17106
/* * Copyright (C) 2017 Aprel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package aprel.optical; import aprel.ArchiveDatabase; import aprel.db.beans.FileBean; import aprel.jdbi.Insert; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.zip.GZIPOutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.bind.util.JAXBSource; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; /** * * @author Aprel */ public class Isoifier { public static final String FILENAME_ORDINAL_SEPARATOR = "-"; public static final String CHECKSUMS_FILENAME = "java-archive-generated-3bc62bbb2cf99142-checksums.md5.gz"; private static final String TEMPORARY_DIR_PREFIX = "java-archive-udf"; private static final String OPTION_TEMP_DIRECTORY = "t"; private static final String OPTION_ISO_OUTPUT = "o"; private static final String OPTION_CREATE_FIRST_DISC_IN_CATALOG = "create-first-disc"; private static final String OPTION_MAX_OPTICAL = "max"; private static final String OPTION_LEFTOVER_XML_FILE = "l"; private static final String OPTION_NO_LEFTOVERS_OUTSTANDING = "no-leftovers-outstanding"; public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(Option.builder(OPTION_TEMP_DIRECTORY).longOpt("temp") .desc("directory where temporary files will be stored prior to " + "their inclusion in the UDF image. If not specified, " + "the default temporary directory provided by the " + "filesystem will be used.").numberOfArgs(1).build()); options.addOption(Option.builder().longOpt(OPTION_CREATE_FIRST_DISC_IN_CATALOG) .desc("set this option if there are no discs in this catalog yet.") .numberOfArgs(0).build()); options.addOption(Option.builder(OPTION_ISO_OUTPUT).required() .desc("directory for UDF image files").numberOfArgs(1).build()); options.addOption(Option.builder(OPTION_MAX_OPTICAL) .desc("maximum number of image files to create. If not set, this" + " will keep creating UDF images until all files not yet" + " on optical in the database have been copied.") .numberOfArgs(1).build()); options.addOption(Option.builder(OPTION_LEFTOVER_XML_FILE).longOpt("leftovers") .desc("XML for file chunks that should be included when more" + " data is available to fill the optical medium.") .required().numberOfArgs(1).build()); options.addOption(Option.builder().longOpt(OPTION_NO_LEFTOVERS_OUTSTANDING) .desc("set this option if there are no leftover file chunks to be" + " written to optical. This can only occur when a catalog" + " has no discs yet, or with extremely intelligent " + "packing algorithms.").numberOfArgs(0).build()); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp(Isoifier.class.getSimpleName(), options); System.exit(1); return; } final int maxOptical = cmd.hasOption(OPTION_MAX_OPTICAL) ? Integer.parseInt(cmd.getOptionValue(OPTION_MAX_OPTICAL)) : Integer.MAX_VALUE; final boolean createFirstDiscInCatalog = cmd.hasOption( OPTION_CREATE_FIRST_DISC_IN_CATALOG); String udfDir = cmd.getOptionValue(OPTION_ISO_OUTPUT); if(!new File(udfDir).isDirectory()) { System.err.println(udfDir + " is not a directory"); System.exit(1); return; } udfDir += udfDir.endsWith(File.separator) ? "" : File.separator; String leftoverXmlFile = cmd.getOptionValue(OPTION_LEFTOVER_XML_FILE); if(new File(leftoverXmlFile).isDirectory()) { System.err.println(leftoverXmlFile + " is a directory."); System.exit(1); return; } if(!new File(leftoverXmlFile).exists()) { if(!cmd.hasOption(OPTION_NO_LEFTOVERS_OUTSTANDING)) { System.err.println(leftoverXmlFile + " does not exist. Use --" + OPTION_NO_LEFTOVERS_OUTSTANDING + " if there really are " + "no leftover file chunks waiting to be written to optical."); System.exit(1); return; } } if(cmd.hasOption(OPTION_NO_LEFTOVERS_OUTSTANDING) && new File(leftoverXmlFile).exists()) { System.err.println("There are leftover file chunks outstanding. " + "Do not use --" + OPTION_NO_LEFTOVERS_OUTSTANDING); System.exit(1); return; } List<Leftover> leftoverList = new ArrayList<>(); final JAXBContext jaxbContext = JAXBContext.newInstance(Refrigerator.class); if(new File(leftoverXmlFile).exists()) { Unmarshaller unmarsh = jaxbContext.createUnmarshaller(); Refrigerator fridge = (Refrigerator) unmarsh.unmarshal(new File(leftoverXmlFile)); leftoverList = fridge.getLeftovers(); leftoverList.forEach(lo -> { Part p = lo.getPart(); p.setPartFilename("part" + p.getPartFilename()); //to not clobber new files FileBean partParent = p.getParent(); partParent.setId(lo.getParentFilename()); partParent.setLocalStoragePath(lo.getParentLocalStoragePath()); partParent.setId(lo.getParentId()); }); } //all these operations are on empty lists if no XML file was read final List<Part> leftoverParts = leftoverList.stream().map(Leftover::getPart) .collect(Collectors.toList()); final List<Optical> startingOpticals = new ArrayList<>(); //it doesn't make sense to have leftovers in excess of a single optical if(!leftoverParts.isEmpty()) { PrivilegedOptical privOpt = new PrivilegedOptical(leftoverParts); startingOpticals.add(privOpt); } Path temporaryDirectory; if(cmd.hasOption(OPTION_TEMP_DIRECTORY)) { final Path pathGiven = Paths.get(cmd.getOptionValue(OPTION_TEMP_DIRECTORY)); if(!Files.exists(pathGiven)) { System.err.println("Temp directory does not exist."); System.exit(1); return; } else if(!Files.isDirectory(pathGiven)) { System.err.println("Temporary location is not a directory."); System.exit(1); return; } temporaryDirectory = Paths.get(pathGiven.toAbsolutePath().toString() + File.separator + TEMPORARY_DIR_PREFIX); } else { temporaryDirectory = Files.createTempDirectory(TEMPORARY_DIR_PREFIX); } temporaryDirectory.toFile().deleteOnExit(); final String temporaryBasePath = temporaryDirectory + File.separator; ArchiveDatabase db = ArchiveDatabase.createDefaultDatabase(); final List<FileBean> notOnOptical = db.getQueryObject().getAllFilesNotOnOptical(); if(notOnOptical.isEmpty()) { System.out.println("All files in archive have been written to optical images."); System.out.println("Nothing to do. Exit."); System.exit(0); } Packer packer = new SimplePacker(); List<Optical> opticals = packer.packFilesIntoOpticals(notOnOptical, maxOptical, startingOpticals); //set properties ordinal and totalInSet final Map<FileBean,List<Part>> fileToParts = new HashMap<>(); opticals.forEach(op -> { op.getParts().forEach(p -> { FileBean file = p.getParent(); if(!fileToParts.containsKey(file)) fileToParts.put(file, new ArrayList<>()); //set catalog here p.setCatalog(file.getCatalog()); fileToParts.get(file).add(p); }); }); //since all parts are placed in the same directory prior to writing, //we need to give them a temp unique id to prevent overwriting files //that used to be in different directories but have the same name //this temp unique id will be stripped when the parts acquire their db ids long uniqueId = 0; for(Map.Entry<FileBean,List<Part>> entry : fileToParts.entrySet()) { FileBean file = entry.getKey(); List<Part> parts = entry.getValue(); final int length = parts.size(); if(length == 1) { // this is where all singleton parts (unsplit files) have their props set final Part singleton = parts.get(0); singleton.setMd5(file.getMd5()); singleton.setPartFilename(uniqueId++ + FILENAME_ORDINAL_SEPARATOR + file.getFilename()); singleton.setOrdinal(1); singleton.setTotalInSet(1); } else { for(int i = 1; i <= length; i++) { Part p = parts.get(i-1); p.setOrdinal(i); p.setTotalInSet(length); p.setPartFilename(uniqueId++ + FILENAME_ORDINAL_SEPARATOR + file.getFilename()); } } } final String partsDir = temporaryDirectory.toString(); final Insert ins = db.getInsertObject(); final String catalog = opticals.stream().findAny().get().getParts() .stream().findAny().get().getCatalog(); int discNumber = db.getQueryObject().getLastDiscNumberInSeries(catalog); if(createFirstDiscInCatalog) { if(discNumber == 0) { discNumber = 1; } else { System.err.println("Received --" + OPTION_CREATE_FIRST_DISC_IN_CATALOG + " but there are already discs in this catalog. Exit."); System.exit(1); return; } } else if(discNumber == 0) { System.err.println("Catalog has no discs. Use --" + OPTION_CREATE_FIRST_DISC_IN_CATALOG + " to create the first disc."); System.exit(1); return; } else discNumber++; final Optical leftoverOptical = opticals.get(opticals.size()-1) .getAvailableSpace() != 0 ? opticals.remove(opticals.size()-1) : null; final Set<FileBean> filesAddedToOptical = new HashSet<>(); for(Optical opt : opticals) { if(opt instanceof PrivilegedOptical) ((PrivilegedOptical)opt).becomeNormal(); //now is the time! opt.writePartsToDir(partsDir); //at this point, parts should have all their database fields set //commit to database final BufferedWriter md5FileWriter = new BufferedWriter(new OutputStreamWriter( new GZIPOutputStream(new FileOutputStream( temporaryBasePath + CHECKSUMS_FILENAME)),Charset.forName("utf-8"))); final List<Part> parts = opt.getParts(); for(Part p : parts) { if(!p.getCatalog().equals(catalog)) { System.err.println("Multiple catalogs detected. Exit."); System.exit(1); return; } p.setOnOptical(true); p.setMd5Verified(false); p.setDiscNumber(discNumber); //"clever" hack final String holdFilename = p.getPartFilename(); p.setPartFilename(holdFilename.split(FILENAME_ORDINAL_SEPARATOR,2)[1]); final String id = ins.insertPart(p); p.setPartFilename(holdFilename); //end "clever" hack p.setId(id); //now that parts have db ids, rename them to conform to "id-filename-ordinal" final String newFilename = p.getId() + FILENAME_ORDINAL_SEPARATOR /*strip temp uniqid-->*/ + p.getPartFilename().split(FILENAME_ORDINAL_SEPARATOR,2)[1] + FILENAME_ORDINAL_SEPARATOR + p.getOrdinal() + FILENAME_ORDINAL_SEPARATOR + p.getTotalInSet(); com.google.common.io.Files.move( new File(temporaryBasePath + p.getPartFilename()), new File(temporaryBasePath + newFilename)); md5FileWriter.write(p.getMd5() + " " + newFilename); md5FileWriter.newLine(); p.setPartFilename(newFilename); filesAddedToOptical.add(p.getParent()); } md5FileWriter.close(); //now, package the contents of the temp directory to a udf image, then clear the temp files final String udfFilename = catalog + FILENAME_ORDINAL_SEPARATOR + discNumber; ProcessBuilder pb = new ProcessBuilder("mkisofs", "-R", "-J", "-udf", "-iso-level", "3", "-V", udfFilename, "-o", udfDir + udfFilename + ".iso", temporaryBasePath) .inheritIO(); System.out.println("Starting mkisofs..."); Process p = pb.start(); p.waitFor(); System.out.println("Successfully saved to " + udfFilename + ".iso"); ins.updateFilesOnOptical(filesAddedToOptical.stream().map(FileBean::getId) .collect(Collectors.toList())); Arrays.asList(temporaryDirectory.toFile().listFiles()).forEach(f -> f.delete()); discNumber++; } //now, handle the leftovers new File(leftoverXmlFile).delete(); if(leftoverOptical != null) { Marshaller marsh = jaxbContext.createMarshaller(); JAXBSource jsource = new JAXBSource(marsh, new Refrigerator( Leftover.createLeftovers(leftoverOptical.getParts()))); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); StreamResult result = new StreamResult(leftoverXmlFile); transformer.transform(jsource, result); //leftovers have to be marked as onOptical; otherwise, they will be //gathered again on the next invocation and written twice. This only //happens when leftovers are from small files that do not span //multiple disks List<Part> leftoversOnLastOptical = leftoverOptical.getParts(); ins.updateFilesOnOptical(leftoversOnLastOptical.stream().map(Part::getParentFileId) .collect(Collectors.toList())); } db.close(); } }
gpl-3.0
akardapolov/ASH-Viewer
jfreechart-fse/src/main/java/org/jfree/chart/date/SpreadsheetDate.java
15332
/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2006, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * SpreadsheetDate.java * -------------------- * (C) Copyright 2000-2006, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: SpreadsheetDate.java,v 1.10 2006/08/29 13:59:30 mungady Exp $ * * Changes * ------- * 11-Oct-2001 : Version 1 (DG); * 05-Nov-2001 : Added getDescription() and setDescription() methods (DG); * 12-Nov-2001 : Changed name from ExcelDate.java to SpreadsheetDate.java (DG); * Fixed a bug in calculating day, month and year from serial * number (DG); * 24-Jan-2002 : Fixed a bug in calculating the serial number from the day, * month and year. Thanks to Trevor Hills for the report (DG); * 29-May-2002 : Added equals(Object) method (SourceForge ID 558850) (DG); * 03-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 13-Mar-2003 : Implemented Serializable (DG); * 04-Sep-2003 : Completed isInRange() methods (DG); * 05-Sep-2003 : Implemented Comparable (DG); * 21-Oct-2003 : Added hashCode() method (DG); * 29-Aug-2006 : Removed redundant description attribute (DG); * */ package org.jfree.chart.date; import java.util.Calendar; import java.util.Date; /** * Represents a date using an integer, in a similar fashion to the * implementation in Microsoft Excel. The range of dates supported is * 1-Jan-1900 to 31-Dec-9999. * <P> * Be aware that there is a deliberate bug in Excel that recognises the year * 1900 as a leap year when in fact it is not a leap year. You can find more * information on the Microsoft website in article Q181370: * <P> * http://support.microsoft.com/support/kb/articles/Q181/3/70.asp * <P> * Excel uses the convention that 1-Jan-1900 = 1. This class uses the * convention 1-Jan-1900 = 2. * The result is that the day number in this class will be different to the * Excel figure for January and February 1900...but then Excel adds in an extra * day (29-Feb-1900 which does not actually exist!) and from that point forward * the day numbers will match. * * @author David Gilbert */ public class SpreadsheetDate extends SerialDate { /** For serialization. */ private static final long serialVersionUID = -2039586705374454461L; /** * The day number (1-Jan-1900 = 2, 2-Jan-1900 = 3, ..., 31-Dec-9999 = * 2958465). */ private final int serial; /** The day of the month (1 to 28, 29, 30 or 31 depending on the month). */ private final int day; /** The month of the year (1 to 12). */ private final int month; /** The year (1900 to 9999). */ private final int year; /** * Creates a new date instance. * * @param day the day (in the range 1 to 28/29/30/31). * @param month the month (in the range 1 to 12). * @param year the year (in the range 1900 to 9999). */ public SpreadsheetDate(final int day, final int month, final int year) { if ((year >= 1900) && (year <= 9999)) { this.year = year; } else { throw new IllegalArgumentException( "The 'year' argument must be in range 1900 to 9999." ); } if ((month >= MonthConstants.JANUARY) && (month <= MonthConstants.DECEMBER)) { this.month = month; } else { throw new IllegalArgumentException( "The 'month' argument must be in the range 1 to 12." ); } if ((day >= 1) && (day <= SerialDate.lastDayOfMonth(month, year))) { this.day = day; } else { throw new IllegalArgumentException("Invalid 'day' argument."); } // the serial number needs to be synchronised with the day-month-year... this.serial = calcSerial(day, month, year); } /** * Standard constructor - creates a new date object representing the * specified day number (which should be in the range 2 to 2958465. * * @param serial the serial number for the day (range: 2 to 2958465). */ public SpreadsheetDate(final int serial) { if ((serial >= SERIAL_LOWER_BOUND) && (serial <= SERIAL_UPPER_BOUND)) { this.serial = serial; } else { throw new IllegalArgumentException( "SpreadsheetDate: Serial must be in range 2 to 2958465."); } // the day-month-year needs to be synchronised with the serial number... // get the year from the serial date final int days = this.serial - SERIAL_LOWER_BOUND; // overestimated because we ignored leap days final int overestimatedYYYY = 1900 + (days / 365); final int leaps = SerialDate.leapYearCount(overestimatedYYYY); final int nonleapdays = days - leaps; // underestimated because we overestimated years int underestimatedYYYY = 1900 + (nonleapdays / 365); if (underestimatedYYYY == overestimatedYYYY) { this.year = underestimatedYYYY; } else { int ss1 = calcSerial(1, 1, underestimatedYYYY); while (ss1 <= this.serial) { underestimatedYYYY = underestimatedYYYY + 1; ss1 = calcSerial(1, 1, underestimatedYYYY); } this.year = underestimatedYYYY - 1; } final int ss2 = calcSerial(1, 1, this.year); int[] daysToEndOfPrecedingMonth = AGGREGATE_DAYS_TO_END_OF_PRECEDING_MONTH; if (isLeapYear(this.year)) { daysToEndOfPrecedingMonth = LEAP_YEAR_AGGREGATE_DAYS_TO_END_OF_PRECEDING_MONTH; } // get the month from the serial date int mm = 1; int sss = ss2 + daysToEndOfPrecedingMonth[mm] - 1; while (sss < this.serial) { mm = mm + 1; sss = ss2 + daysToEndOfPrecedingMonth[mm] - 1; } this.month = mm - 1; // what's left is d(+1); this.day = this.serial - ss2 - daysToEndOfPrecedingMonth[this.month] + 1; } /** * Returns the serial number for the date, where 1 January 1900 = 2 * (this corresponds, almost, to the numbering system used in Microsoft * Excel for Windows and Lotus 1-2-3). * * @return The serial number of this date. */ @Override public int toSerial() { return this.serial; } /** * Returns a <code>java.util.Date</code> equivalent to this date. * * @return The date. */ @Override public Date toDate() { final Calendar calendar = Calendar.getInstance(); calendar.set(getYYYY(), getMonth() - 1, getDayOfMonth(), 0, 0, 0); return calendar.getTime(); } /** * Returns the year (assume a valid range of 1900 to 9999). * * @return The year. */ @Override public int getYYYY() { return this.year; } /** * Returns the month (January = 1, February = 2, March = 3). * * @return The month of the year. */ @Override public int getMonth() { return this.month; } /** * Returns the day of the month. * * @return The day of the month. */ @Override public int getDayOfMonth() { return this.day; } /** * Returns a code representing the day of the week. * <P> * The codes are defined in the {@link SerialDate} class as: * <code>SUNDAY</code>, <code>MONDAY</code>, <code>TUESDAY</code>, * <code>WEDNESDAY</code>, <code>THURSDAY</code>, <code>FRIDAY</code>, and * <code>SATURDAY</code>. * * @return A code representing the day of the week. */ @Override public int getDayOfWeek() { return (this.serial + 6) % 7 + 1; } /** * Tests the equality of this date with an arbitrary object. * <P> * This method will return true ONLY if the object is an instance of the * {@link SerialDate} base class, and it represents the same day as this * {@link SpreadsheetDate}. * * @param object the object to compare (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(final Object object) { if (object instanceof SerialDate) { final SerialDate s = (SerialDate) object; return (s.toSerial() == this.toSerial()); } else { return false; } } /** * Returns a hash code for this object instance. * * @return A hash code. */ @Override public int hashCode() { return toSerial(); } /** * Returns the difference (in days) between this date and the specified * 'other' date. * * @param other the date being compared to. * * @return The difference (in days) between this date and the specified * 'other' date. */ @Override public int compare(final SerialDate other) { return this.serial - other.toSerial(); } /** * Implements the method required by the Comparable interface. * * @param other the other object (usually another SerialDate). * * @return A negative integer, zero, or a positive integer as this object * is less than, equal to, or greater than the specified object. */ @Override public int compareTo(final Object other) { return compare((SerialDate) other); } /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return <code>true</code> if this SerialDate represents the same date as * the specified SerialDate. */ @Override public boolean isOn(final SerialDate other) { return (this.serial == other.toSerial()); } /** * Returns true if this SerialDate represents an earlier date compared to * the specified SerialDate. * * @param other the date being compared to. * * @return <code>true</code> if this SerialDate represents an earlier date * compared to the specified SerialDate. */ @Override public boolean isBefore(final SerialDate other) { return (this.serial < other.toSerial()); } /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return <code>true</code> if this SerialDate represents the same date * as the specified SerialDate. */ @Override public boolean isOnOrBefore(final SerialDate other) { return (this.serial <= other.toSerial()); } /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return <code>true</code> if this SerialDate represents the same date * as the specified SerialDate. */ @Override public boolean isAfter(final SerialDate other) { return (this.serial > other.toSerial()); } /** * Returns true if this SerialDate represents the same date as the * specified SerialDate. * * @param other the date being compared to. * * @return <code>true</code> if this SerialDate represents the same date as * the specified SerialDate. */ @Override public boolean isOnOrAfter(final SerialDate other) { return (this.serial >= other.toSerial()); } /** * Returns <code>true</code> if this {@link SerialDate} is within the * specified range (INCLUSIVE). The date order of d1 and d2 is not * important. * * @param d1 a boundary date for the range. * @param d2 the other boundary date for the range. * * @return A boolean. */ @Override public boolean isInRange(final SerialDate d1, final SerialDate d2) { return isInRange(d1, d2, SerialDate.INCLUDE_BOTH); } /** * Returns true if this SerialDate is within the specified range (caller * specifies whether or not the end-points are included). The order of d1 * and d2 is not important. * * @param d1 one boundary date for the range. * @param d2 a second boundary date for the range. * @param include a code that controls whether or not the start and end * dates are included in the range. * * @return <code>true</code> if this SerialDate is within the specified * range. */ @Override public boolean isInRange(final SerialDate d1, final SerialDate d2, final int include) { final int s1 = d1.toSerial(); final int s2 = d2.toSerial(); final int start = Math.min(s1, s2); final int end = Math.max(s1, s2); final int s = toSerial(); if (include == SerialDate.INCLUDE_BOTH) { return (s >= start && s <= end); } else if (include == SerialDate.INCLUDE_FIRST) { return (s >= start && s < end); } else if (include == SerialDate.INCLUDE_SECOND) { return (s > start && s <= end); } else { return (s > start && s < end); } } /** * Calculate the serial number from the day, month and year. * <P> * 1-Jan-1900 = 2. * * @param d the day. * @param m the month. * @param y the year. * * @return the serial number from the day, month and year. */ private int calcSerial(final int d, final int m, final int y) { final int yy = ((y - 1900) * 365) + SerialDate.leapYearCount(y - 1); int mm = SerialDate.AGGREGATE_DAYS_TO_END_OF_PRECEDING_MONTH[m]; if (m > MonthConstants.FEBRUARY) { if (SerialDate.isLeapYear(y)) { mm = mm + 1; } } final int dd = d; return yy + mm + dd + 1; } }
gpl-3.0
craftercms/studio
src/main/java/org/craftercms/studio/impl/v1/web/security/access/StudioWorkflowAPIAccessDecisionVoter.java
8147
/* * Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.craftercms.studio.impl.v1.web.security.access; import net.sf.json.JSONArray; import net.sf.json.JSONException; import net.sf.json.JSONObject; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.craftercms.studio.api.v1.log.Logger; import org.craftercms.studio.api.v1.log.LoggerFactory; import org.craftercms.studio.api.v2.dal.User; import org.springframework.http.HttpMethod; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.core.Authentication; import org.springframework.security.web.FilterInvocation; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; public class StudioWorkflowAPIAccessDecisionVoter extends StudioAbstractAccessDecisionVoter { private final static Logger logger = LoggerFactory.getLogger(StudioWorkflowAPIAccessDecisionVoter.class); private final static String GO_LIVE = "/api/1/services/api/1/workflow/go-live.json"; private final static String REJECT = "/api/1/services/api/1/workflow/reject.json"; private final static String GO_DELETE = "/api/1/services/api/1/workflow/go-delete.json"; private final static Set<String> URIS_TO_VOTE = new HashSet<String>() {{ add(GO_LIVE); add(REJECT); add(GO_DELETE); }}; private final static String PUBLISH_PERMISSION = "publish"; private final static String DELETE_PERMISSION = "delete"; private final static String DELETE_CONTENT_PERMISSION = "delete_content"; private final static String CANCEL_PUBLISH_PERMISSION = "cancel_publish"; private final static Set<String> DELETE_PERMISSIONS = new HashSet<String>() {{ add(DELETE_PERMISSION); add(DELETE_CONTENT_PERMISSION); }}; private final static Set<String> REJECT_PERMISSIONS = new HashSet<String>() {{ add(PUBLISH_PERMISSION); add(CANCEL_PUBLISH_PERMISSION); }}; @Override public boolean supports(ConfigAttribute configAttribute) { return true; } @Override public int voteInternal(Authentication authentication, Object o, Collection collection) { int toRet = ACCESS_ABSTAIN; String requestUri = ""; if (o instanceof FilterInvocation) { FilterInvocation filterInvocation = (FilterInvocation) o; HttpServletRequest request = filterInvocation.getRequest(); requestUri = request.getRequestURI().replace(request.getContextPath(), ""); if (URIS_TO_VOTE.contains(requestUri)) { String userParam = request.getParameter("username"); String siteParam = request.getParameter("site_id"); List<String> paths = new ArrayList<String>(); if (StringUtils.isEmpty(siteParam)) { siteParam = request.getParameter("site"); } if (StringUtils.isEmpty(userParam) && StringUtils.equalsIgnoreCase(request.getMethod(), HttpMethod.POST.name()) && !ServletFileUpload.isMultipartContent(request)) { try { InputStream is = request.getInputStream(); is.mark(0); String jsonString = IOUtils.toString(is, StandardCharsets.UTF_8); if (StringUtils.isNoneEmpty(jsonString)) { JSONObject jsonObject = JSONObject.fromObject(jsonString); if (jsonObject.has("site")) { siteParam = jsonObject.getString("site"); } if (jsonObject.has("site_id")) { siteParam = jsonObject.getString("site_id"); } if (jsonObject.has("items")) { JSONArray jsonArray = jsonObject.getJSONArray("items"); for (int i = 0; i < jsonArray.size(); i++) { paths.add(jsonArray.optString(i)); } } } is.reset(); } catch (IOException | JSONException e) { logger.debug("Failed to extract username from POST request"); } } User currentUser = (User) authentication.getPrincipal(); switch (requestUri) { case GO_LIVE: if (siteService.exists(siteParam)) { for (String path : paths) { if (currentUser != null && isSiteMember(siteParam, currentUser) && hasPermission(siteParam, path, currentUser.getUsername(), PUBLISH_PERMISSION)) { toRet = ACCESS_GRANTED; } else { toRet = ACCESS_DENIED; break; } } } break; case REJECT: if (siteService.exists(siteParam)) { for (String path : paths) { if (currentUser != null && isSiteMember(siteParam, currentUser) && hasAnyPermission(siteParam, path, currentUser.getUsername(), REJECT_PERMISSIONS)) { toRet = ACCESS_GRANTED; } else { toRet = ACCESS_DENIED; break; } } } else { toRet = ACCESS_ABSTAIN; } break; case GO_DELETE: if (siteService.exists(siteParam)) { for (String path : paths) { if (currentUser != null && isSiteMember(siteParam, currentUser) && hasAnyPermission(siteParam, path, currentUser.getUsername(), DELETE_PERMISSIONS)) { toRet = ACCESS_GRANTED; } else { toRet = ACCESS_DENIED; break; } } } else { toRet = ACCESS_ABSTAIN; } break; default: toRet = ACCESS_ABSTAIN; break; } } } logger.debug("Request: " + requestUri + " - Access: " + toRet); return toRet; } @Override public boolean supports(Class aClass) { return true; } }
gpl-3.0
alex73/chdkptpJ
src/org/alex73/chdkptpj/lua/libs/ALuaBaseLib.java
2108
/************************************************************************** chdkptpJ - Java CHDK PTP framework. Copyright (C) 2015 Aleś Bułojčyk (alex73mail@gmail.com) This file is part of chdkptpJ. chdkptpJ is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. chdkptpJ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ package org.alex73.chdkptpj.lua.libs; import java.lang.reflect.Field; import org.luaj.vm2.LuaFunction; import org.luaj.vm2.LuaTable; import org.luaj.vm2.LuaValue; import org.luaj.vm2.lib.TwoArgFunction; /** * Base for all chdk native modules for Lua. It registers functions by reflection. */ public abstract class ALuaBaseLib extends TwoArgFunction { private final String registerName; public ALuaBaseLib(String registerName) { this.registerName = registerName; } @Override public LuaValue call(LuaValue modname, LuaValue env) { LuaTable table = new LuaTable(); for (Field f : this.getClass().getFields()) { if (LuaFunction.class.isAssignableFrom(f.getType())) { try { registerCall(table, f.getName(), (LuaFunction) f.get(this)); } catch (Exception ex) { throw new RuntimeException(ex); } } } if (registerName != null) { env.set(registerName, table); } return table; } protected void registerCall(LuaTable table, String name, LuaFunction function) { table.set(name, function); } }
gpl-3.0
Standa631/fUmlStudio
src/main/java/net/belehradek/umleditor/Arrow.java
3923
package net.belehradek.umleditor; import de.tesis.dynaware.grapheditor.utils.GeometryUtils; import javafx.geometry.Point2D; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.shape.ArcTo; import javafx.scene.shape.Line; /** * An arrow shape. * * <p> * This is a {@link Node} subclass and can be added to the JavaFX scene graph in the usual way. Styling can be achieved * via the CSS classes <em>arrow-line</em> and <em>arrow-head</em>. * <p> * * <p> * Example: * * <pre> * <code>Arrow arrow = new Arrow(); * arrow.setStart(10, 20); * arrow.setEnd(100, 150); * arrow.draw();</code> * </pre> * * </p> * */ public class Arrow extends Group { private static final String STYLE_CLASS_LINE = "arrow-line"; private static final String STYLE_CLASS_HEAD = "arrow-head"; private final Line line = new Line(); private final ArrowHead head = new ArrowHead(); private double startX; private double startY; private double endX; private double endY; /** * Creates a new {@link Arrow}. */ public Arrow() { line.getStyleClass().add(STYLE_CLASS_LINE); head.getStyleClass().add(STYLE_CLASS_HEAD); getChildren().addAll(line, head); } /** * Sets the width of the arrow-head. * * @param width the width of the arrow-head */ public void setHeadWidth(final double width) { head.setWidth(width); } /** * Sets the length of the arrow-head. * * @param length the length of the arrow-head */ public void setHeadLength(final double length) { head.setLength(length); } /** * Sets the radius of curvature of the {@link ArcTo} at the base of the arrow-head. * * <p> * If this value is less than or equal to zero, a straight line will be drawn instead. The default is -1. * </p> * * @param radius the radius of curvature of the arc at the base of the arrow-head */ public void setHeadRadius(final double radius) { head.setRadiusOfCurvature(radius); } /** * Gets the start point of the arrow. * * @return the start {@link Point2D} of the arrow */ public Point2D getStart() { return new Point2D(startX, startY); } /** * Sets the start position of the arrow. * * @param startX the x-coordinate of the start position of the arrow * @param startY the y-coordinate of the start position of the arrow */ public void setStart(final double startX, final double startY) { this.startX = startX; this.startY = startY; } /** * Gets the start point of the arrow. * * @return the start {@link Point2D} of the arrow */ public Point2D getEnd() { return new Point2D(endX, endY); } /** * Sets the end position of the arrow. * * @param endX the x-coordinate of the end position of the arrow * @param endY the y-coordinate of the end position of the arrow */ public void setEnd(final double endX, final double endY) { this.endX = endX; this.endY = endY; } /** * Draws the arrow for its current size and position values. */ public void draw() { final double deltaX = endX - startX; final double deltaY = endY - startY; final double angle = Math.atan2(deltaX, deltaY); final double headX = endX - head.getLength() / 2 * Math.sin(angle); final double headY = endY - head.getLength() / 2 * Math.cos(angle); line.setStartX(GeometryUtils.moveOffPixel(startX)); line.setStartY(GeometryUtils.moveOffPixel(startY)); line.setEndX(GeometryUtils.moveOffPixel(headX)); line.setEndY(GeometryUtils.moveOffPixel(headY)); head.setCenter(headX, headY); head.setAngle(Math.toDegrees(-angle)); head.draw(); } }
gpl-3.0
rlewczuk/slac
slac-core/src/main/java/com/jitlogic/slac/data/slac/Transform.java
1848
/** * Copyright 2012-2015 Rafal Lewczuk <rafal.lewczuk@jitlogic.com> * <p/> * This is free software. You can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * <p/> * This software is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * <p/> * You should have received a copy of the GNU General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. */ package com.jitlogic.slac.data.slac; import org.codehaus.jackson.annotate.JsonProperty; import java.io.Serializable; public class Transform implements Serializable { public static final int MAP_TYPE = 0; public static final int CONST_TYPE = 1; public static final int MULT_TYPE = 2; @JsonProperty int id; @JsonProperty int type; @JsonProperty String name; @JsonProperty String code; @JsonProperty String comment; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } }
gpl-3.0
SanderMertens/opensplice
src/api/dcps/java/saj/code/DDS/LIVELINESS_QOS_POLICY_NAME.java
407
/* * OpenSplice DDS * * This software and documentation are Copyright 2006 to 2013 PrismTech * Limited and its licensees. All rights reserved. See file: * * $OSPL_HOME/LICENSE * * for full copyright notice and license terms. * */ package DDS; public interface LIVELINESS_QOS_POLICY_NAME { public static final String value = "Liveliness"; }
gpl-3.0
Sharknoon/dfMASTER
dfMASTER/src/main/java/dfmaster/json/JSONUtils.java
6234
/* * Copyright (C) 2017 Josua Frank * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package dfmaster.json; import java.util.Arrays; /** * This class provides some useful Utilities for the JSON-Creating and -Parsing * * @author Josua Frank */ public class JSONUtils { /** * parsees a Number according to to ECMA-Standard for JSON-Numbers * * @param string The String to be parsed * @return The parsed Number or 0 if any errors occur. */ public static Number parse(String string) { if (string == null || string.isEmpty()) { return DEFAULTVALUE;//Expecting chars to parse(no char available) } int i; JSONUtils number = new JSONUtils(); number.negativeState(string.toCharArray(), 0); double result = 0; int length = number.decimal.length; for (i = 0; i < length; i++) { result += Math.pow(10, i) * ((number.decimal[length - i - 1]) - 48); } if (number.expo != null) { int expo = 0; int lengthExpo = number.expo.length; for (i = 0; i < lengthExpo; i++) { expo += Math.pow(10, i) * ((number.expo[lengthExpo - i - 1]) - 48); } if (number.expoNegative) { expo = -expo; } result = Math.pow(result, expo); } if (number.fraction != null) { double fraction = 0; int lengthFraction = number.fraction.length; for (i = 0; i < lengthFraction; i++) { fraction += Math.pow(10, i) * ((number.fraction[lengthFraction - i - 1]) - 48); } result = result + (fraction <= 0 ? 0 : fraction / Math.pow(10, (int) (1 + Math.log10(fraction)))); } if (number.isNegative) { result = -result; } if ((result % 1) == 0) { return (int) result; } else { return result; } } static final byte DEFAULTVALUE = 0; boolean isNegative = false;//must char[] decimal;//must char[] fraction;//can boolean expoNegative = false;//can char[] expo;//can private boolean negativeState(char[] string, int index) { if (string.length <= index) { return false;//Expecting digit (no char available) } if (string[index] == '-') { isNegative = true; return decimalState(string, index + 1); } return decimalState(string, index); } private boolean decimalState(char[] string, int index) { if (string.length <= index) { return false;//Expecting digit (no char available) } if (string[index] == '0') { decimal = new char[]{'0'}; return fractionState(string, index + 1); } if (isDigitWithourZero(string[index])) { int startindex = index;//inclusive index++; while (string.length > index && isDigit(string[index])) { index++; } decimal = Arrays.copyOfRange(string, startindex, index); return fractionState(string, index); } return false;//Expecting Digit (wrong char available) } private boolean fractionState(char[] string, int index) { if (string.length <= index) { return true; } if (string[index] == '.') { index++; if (string.length > index && isDigit(string[index])) { int startIndex = index; index++; while (string.length > index && isDigit(string[index])) { index++; } fraction = Arrays.copyOfRange(string, startIndex, index); return exponentState(string, index); } else { return false;//Expecting digit after point } } return exponentState(string, index); } private boolean exponentState(char[] string, int index) { if (string.length <= index) { return true; } if (string[index] == 'e' || string[index] == 'E') { index++; if (string.length <= index) { return false;//Expecting -, + or digit after e } if (string[index] == '-') { expoNegative = true; index++; } else if (string[index] == '+') { index++; } if (string.length <= index) { return false;//Expecting digit after +/- } if (isDigit(string[index])) { int startIndex = index; index++; while (string.length > index && isDigit(string[index])) { index++; } expo = Arrays.copyOfRange(string, startIndex, index); return index == string.length; } return false; //Expecting digit after e/E or +/- } return false;//Expecting end of number } private static boolean isDigit(char achar) { return achar == '0' || achar == '1' || achar == '2' || achar == '3' || achar == '4' || achar == '5' || achar == '6' || achar == '7' || achar == '8' || achar == '9'; } private static boolean isDigitWithourZero(char achar) { return achar == '1' || achar == '2' || achar == '3' || achar == '4' || achar == '5' || achar == '6' || achar == '7' || achar == '8' || achar == '9'; } }
gpl-3.0
silviafranceschi/jgrasstools
hortonmachine/src/main/java/org/jgrasstools/hortonmachine/modules/hydrogeomorphology/energyindexcalculator/OmsEnergyIndexCalculator.java
36022
/* * JGrass - Free Open Source Java GIS http://www.jgrass.org * (C) HydroloGIS - www.hydrologis.com * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Library General Public License as published by the Free * Software Foundation; either version 2 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 Library General Public License for more * details. * * You should have received a copy of the GNU Library General Public License * along with this library; if not, write to the Free Foundation, Inc., 59 * Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jgrasstools.hortonmachine.modules.hydrogeomorphology.energyindexcalculator; import static java.lang.Math.PI; import static java.lang.Math.acos; import static java.lang.Math.asin; import static java.lang.Math.cos; import static java.lang.Math.sin; import static java.lang.Math.tan; import static org.jgrasstools.gears.libs.modules.JGTConstants.intNovalue; import static org.jgrasstools.gears.libs.modules.JGTConstants.isNovalue; import static org.jgrasstools.gears.libs.modules.JGTConstants.omega; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_AUTHORCONTACTS; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_AUTHORNAMES; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_KEYWORDS; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_LABEL; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_LICENSE; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_NAME; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_STATUS; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_inAspect_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_inBasins_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_inCurvatures_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_inElev_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_inSlope_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_outAltimetry_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_outArea_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_outEnergy_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_pDt_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_pEi_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSENERGYINDEXCALCULATOR_pEs_DESCRIPTION; import java.awt.image.RenderedImage; import java.awt.image.WritableRaster; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import javax.media.jai.iterator.RandomIter; import javax.media.jai.iterator.RandomIterFactory; import oms3.annotations.Author; import oms3.annotations.Description; import oms3.annotations.Execute; import oms3.annotations.In; import oms3.annotations.Keywords; import oms3.annotations.Label; import oms3.annotations.License; import oms3.annotations.Name; import oms3.annotations.Out; import oms3.annotations.Status; import org.geotools.coverage.grid.GridCoverage2D; import org.geotools.geometry.jts.JTS; import org.geotools.referencing.CRS; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.jgrasstools.gears.io.eicalculator.EIAltimetry; import org.jgrasstools.gears.io.eicalculator.EIAreas; import org.jgrasstools.gears.io.eicalculator.EIEnergy; import org.jgrasstools.gears.libs.exceptions.ModelsIllegalargumentException; import org.jgrasstools.gears.libs.modules.JGTModel; import org.jgrasstools.gears.utils.coverage.CoverageUtilities; import org.jgrasstools.hortonmachine.i18n.HortonMessageHandler; import org.opengis.referencing.operation.MathTransform; import com.vividsolutions.jts.geom.Coordinate; @Description(OMSENERGYINDEXCALCULATOR_DESCRIPTION) @Author(name = OMSENERGYINDEXCALCULATOR_AUTHORNAMES, contact = OMSENERGYINDEXCALCULATOR_AUTHORCONTACTS) @Keywords(OMSENERGYINDEXCALCULATOR_KEYWORDS) @Label(OMSENERGYINDEXCALCULATOR_LABEL) @Name(OMSENERGYINDEXCALCULATOR_NAME) @Status(OMSENERGYINDEXCALCULATOR_STATUS) @License(OMSENERGYINDEXCALCULATOR_LICENSE) public class OmsEnergyIndexCalculator extends JGTModel { @Description(OMSENERGYINDEXCALCULATOR_inElev_DESCRIPTION) @In public GridCoverage2D inElev = null; @Description(OMSENERGYINDEXCALCULATOR_inBasins_DESCRIPTION) @In public GridCoverage2D inBasins = null; @Description(OMSENERGYINDEXCALCULATOR_inCurvatures_DESCRIPTION) @In public GridCoverage2D inCurvatures = null; @Description(OMSENERGYINDEXCALCULATOR_inAspect_DESCRIPTION) @In public GridCoverage2D inAspect = null; @Description(OMSENERGYINDEXCALCULATOR_inSlope_DESCRIPTION) @In public GridCoverage2D inSlope = null; @Description(OMSENERGYINDEXCALCULATOR_pEs_DESCRIPTION) @In public int pEs = -1; @Description(OMSENERGYINDEXCALCULATOR_pEi_DESCRIPTION) @In public int pEi = -1; @Description(OMSENERGYINDEXCALCULATOR_pDt_DESCRIPTION) @In public double pDt = -1; @Description(OMSENERGYINDEXCALCULATOR_outAltimetry_DESCRIPTION) @Out public List<EIAltimetry> outAltimetry; @Description(OMSENERGYINDEXCALCULATOR_outEnergy_DESCRIPTION) @Out public List<EIEnergy> outEnergy; @Description(OMSENERGYINDEXCALCULATOR_outArea_DESCRIPTION) @Out public List<EIAreas> outArea; private static final int NOVALUE = intNovalue; private HashMap<Integer, Integer> id2indexMap = null; private HashMap<Integer, Integer> index2idMap = null; private double avgLatitude = -1; private double dx; private double dy; private int[][] eibasinID; private int[][] outputShadow; private double[][][] eibasinEmonth; private double[][] eibasinESrange; private double[][] eibasinES; private double[][] eibasinEI_mean; private double[][][] eibasinEI; private double[][] eibasinE; private double[][][] eibasinA; private final GeomorphUtilities geomorphUtilities = new GeomorphUtilities(); private int eibasinNum; private RandomIter idbasinImageIterator; private RandomIter elevImageIterator; private WritableRaster curvatureImage; private RandomIter aspectImageIterator; private RandomIter slopeImageIterator; private int rows; private int cols; private HortonMessageHandler msg = HortonMessageHandler.getInstance(); @Execute public void process() throws Exception { HashMap<String, Double> regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inBasins); cols = regionMap.get(CoverageUtilities.COLS).intValue(); rows = regionMap.get(CoverageUtilities.ROWS).intValue(); dx = regionMap.get(CoverageUtilities.XRES); dy = regionMap.get(CoverageUtilities.YRES); double n = regionMap.get(CoverageUtilities.NORTH); double s = regionMap.get(CoverageUtilities.SOUTH); double w = regionMap.get(CoverageUtilities.WEST); double e = regionMap.get(CoverageUtilities.EAST); double meanX = w + (e - w) / 2.0; double meanY = s + (n - s) / 2.0; Coordinate tmp = new Coordinate(meanX, meanY); MathTransform mathTransform = CRS.findMathTransform(inAspect.getCoordinateReferenceSystem(), DefaultGeographicCRS.WGS84); Coordinate newC = JTS.transform(tmp, null, mathTransform); avgLatitude = newC.y; RenderedImage idbasinImage = inBasins.getRenderedImage(); idbasinImageIterator = RandomIterFactory.create(idbasinImage, null); RenderedImage elevImage = inElev.getRenderedImage(); elevImageIterator = RandomIterFactory.create(elevImage, null); RenderedImage tmpImage = inCurvatures.getRenderedImage(); curvatureImage = CoverageUtilities .createDoubleWritableRaster(tmpImage.getWidth(), tmpImage.getHeight(), null, null, null); RandomIter tmpIterator = RandomIterFactory.create(tmpImage, null); // TODO check what this is for?!?!? for( int i = 0; i < tmpImage.getHeight(); i++ ) { for( int j = 0; j < tmpImage.getWidth(); j++ ) { double value = tmpIterator.getSampleDouble(j, i, 0); curvatureImage.setSample(j, i, 0, value); } } RenderedImage aspectImage = inAspect.getRenderedImage(); aspectImageIterator = RandomIterFactory.create(aspectImage, null); RenderedImage slopeImage = inSlope.getRenderedImage(); slopeImageIterator = RandomIterFactory.create(slopeImage, null); avgLatitude *= (PI / 180.0); pm.message(msg.message("eicalculator.preparing_inputs")); //$NON-NLS-1$ eibasinNum = prepareInputsOutputs(); pm.beginTask(msg.message("eicalculator.computing"), 6); //$NON-NLS-1$ for( int m = 0; m < 6; m++ ) { pm.worked(1); compute_EI(m + 1); } pm.done(); average_EI(10, 6); pm.beginTask(msg.message("eicalculator.calc_areas"), eibasinNum); //$NON-NLS-1$ for( int i = 0; i < eibasinNum; i++ ) { pm.worked(1); area(i); } pm.done(); /* * putting the results together */ outAltimetry = new ArrayList<EIAltimetry>(); outEnergy = new ArrayList<EIEnergy>(); outArea = new ArrayList<EIAreas>(); for( int i = 0; i < eibasinNum; i++ ) { int realBasinId = index2idMap.get(i + 1); /* * ENERGY BANDS * * Cycle over the virtual months: * 0: 22 DICEMBRE - 20 GENNAIO * 1: 21 GENNAIO - 20 FEBBRAIO * 2: 21 FEBBRAIO - 22 MARZO * 3: 23 MARZO - 22 APRILE * 4: 23 APRILE - 22 MAGGIO * 5: 23 MAGGIO - 22 GIUGNO */ for( int j = 0; j < 6; j++ ) { for( int k = 0; k < pEi; k++ ) { EIEnergy tmpEi = new EIEnergy(); // the basin id tmpEi.basinId = realBasinId; tmpEi.energeticBandId = k; tmpEi.virtualMonth = j; tmpEi.energyValue = eibasinEI[0][k][i]; outEnergy.add(tmpEi); } } /* * ALTIMETRIC BANDS */ for( int k = 0; k < pEs; k++ ) { EIAltimetry tmpAl = new EIAltimetry(); tmpAl.basinId = realBasinId; tmpAl.altimetricBandId = k; tmpAl.elevationValue = eibasinES[k][i]; tmpAl.bandRange = eibasinESrange[k][i]; outAltimetry.add(tmpAl); } /* * AREAS */ for( int j = 0; j < pEs; j++ ) { for( int k = 0; k < pEi; k++ ) { EIAreas tmpAr = new EIAreas(); tmpAr.basinId = realBasinId; tmpAr.altimetricBandId = j; tmpAr.energyBandId = k; tmpAr.areaValue = eibasinA[j][k][i]; outArea.add(tmpAr); } } } } private int prepareInputsOutputs() { List<Integer> idList = new ArrayList<Integer>(); eibasinID = new int[rows][cols]; for( int r = 0; r < rows; r++ ) { for( int c = 0; c < cols; c++ ) { // get the value if (isNovalue(idbasinImageIterator.getSampleDouble(c, r, 0))) { eibasinID[r][c] = NOVALUE; } else { eibasinID[r][c] = (int) idbasinImageIterator.getSampleDouble(c, r, 0); // put the value in the id list, if it isn't already there if (!idList.contains(eibasinID[r][c])) { idList.add(eibasinID[r][c]); } } } } // sort the id list Collections.sort(idList); /* * now the number of involved subbasins is known */ int eibasinNum = idList.size(); /* * now substitute the numbers in the ID matrix with a sequential index without wholes */ // first create the mapping id2indexMap = new HashMap<Integer, Integer>(); index2idMap = new HashMap<Integer, Integer>(); for( int i = 1; i <= idList.size(); i++ ) { id2indexMap.put(idList.get(i - 1), i); index2idMap.put(i, idList.get(i - 1)); } for( int r = 0; r < eibasinID.length; r++ ) { for( int c = 0; c < eibasinID[0].length; c++ ) { if (eibasinID[r][c] != NOVALUE) { eibasinID[r][c] = id2indexMap.get(eibasinID[r][c]); } } } pm.message(msg.message("eicalculator.subbasinsnum") + eibasinNum); //$NON-NLS-1$ /* * prepare outputs */ outputShadow = new int[rows][cols]; for( int r = 0; r < outputShadow.length; r++ ) { for( int c = 0; c < outputShadow[0].length; c++ ) { outputShadow[r][c] = NOVALUE; } } eibasinE = new double[rows][cols]; for( int r = 0; r < eibasinE.length; r++ ) { for( int c = 0; c < eibasinE[0].length; c++ ) { eibasinE[r][c] = NOVALUE; } } eibasinEmonth = new double[6][rows][cols]; for( int r = 0; r < eibasinEmonth.length; r++ ) { for( int c = 0; c < eibasinEmonth[0].length; c++ ) { for( int t = 0; t < eibasinEmonth[0][0].length; t++ ) { eibasinEmonth[r][c][t] = NOVALUE; } } } eibasinES = new double[pEs][eibasinNum]; eibasinESrange = new double[pEs][eibasinNum]; eibasinEI_mean = new double[pEi][eibasinNum]; eibasinEI = new double[6][pEi][eibasinNum]; eibasinA = new double[pEs][pEi][eibasinNum]; return eibasinNum; } private void compute_EI( int month ) { int[] day_beg = new int[1], day_end = new int[1], daymonth = new int[1], monthyear = new int[1]; int day; double hour; double[] Rad_morpho = new double[1], Rad_flat = new double[1]; double[] E0 = new double[1], alpha = new double[1], direction = new double[1]; double[][] Rad_morpho_cum, Rad_flat_cum; find_days(month, day_beg, day_end); hour = 0.5 * pDt; day = day_beg[0]; Rad_morpho_cum = new double[rows][cols]; Rad_flat_cum = new double[rows][cols]; get_date(day, monthyear, daymonth); printReport(daymonth, monthyear, hour); do { sun(hour, day, E0, alpha, direction); for( int r = 0; r < eibasinID.length; r++ ) { for( int c = 0; c < eibasinID[0].length; c++ ) { if (eibasinID[r][c] != NOVALUE) { radiation(Rad_morpho, Rad_flat, E0[0], alpha[0], direction[0], aspectImageIterator.getSampleDouble(c, r, 0), slopeImageIterator.getSampleDouble(c, r, 0), outputShadow[r][c]); Rad_morpho_cum[r][c] += Rad_morpho[0]; Rad_flat_cum[r][c] += Rad_flat[0]; } } } hour += pDt; if (hour >= 24) { hour -= 24.0; day += 1; } get_date(day, monthyear, daymonth); printReport(daymonth, monthyear, hour); } while( day <= day_end[0] ); for( int r = 0; r < eibasinID.length; r++ ) { for( int c = 0; c < eibasinID[0].length; c++ ) { if (eibasinID[r][c] != NOVALUE) { pm.message("Bacino: " + index2idMap.get(eibasinID[r][c])); if (Rad_flat_cum[r][c] == 0) { pm.message("Rad flat nulla"); Rad_morpho_cum[r][c] = 1; Rad_flat_cum[r][c] = 1; } eibasinEmonth[month - 1][r][c] = Rad_morpho_cum[r][c] / Rad_flat_cum[r][c]; pm.message("Rad morfo: " + Rad_morpho_cum[r][c]); pm.message("Rad flat: " + Rad_flat_cum[r][c]); } else { eibasinEmonth[month - 1][r][c] = NOVALUE; } } } } private void printReport( int[] daymonth, int[] monthyear, double hour ) { StringBuilder sb = new StringBuilder(); sb.append(msg.message("hm.day")); //$NON-NLS-1$ sb.append(": "); //$NON-NLS-1$ sb.append(daymonth[0]); sb.append("/"); //$NON-NLS-1$ sb.append(monthyear[0]); sb.append(msg.message("hm.hour")); //$NON-NLS-1$ sb.append(": "); //$NON-NLS-1$ sb.append(hour); if ((hour - (long) hour) * 60 < 10) { sb.append(":0"); //$NON-NLS-1$ } else { sb.append(":"); //$NON-NLS-1$ } sb.append(((hour - (long) hour) * 60)); pm.message(sb.toString()); } private void find_days( int month, int[] day_begin, int[] day_end ) { if (month == 1) { day_begin[0] = -9; day_end[0] = 20; } else if (month == 2) { day_begin[0] = 21; day_end[0] = 51; } else if (month == 3) { day_begin[0] = 52; day_end[0] = 81; } else if (month == 4) { day_begin[0] = 82; day_end[0] = 112; } else if (month == 5) { day_begin[0] = 113; day_end[0] = 142; } else if (month == 6) { day_begin[0] = 143; day_end[0] = 173; } else { throw new ModelsIllegalargumentException("Incorrect in find_days", "OmsEnergyIndexCalculator", pm); } } private void get_date( int julianday, int[] month, int[] daymonth ) { if (julianday <= 0) { month[0] = 12; daymonth[0] = 31 + julianday; } else if (julianday >= 1 && julianday <= 31) { month[0] = 1; daymonth[0] = julianday; } else if (julianday >= 32 && julianday <= 59) { month[0] = 2; daymonth[0] = julianday - 31; } else if (julianday >= 60 && julianday <= 90) { month[0] = 3; daymonth[0] = julianday - 59; } else if (julianday >= 91 && julianday <= 120) { month[0] = 4; daymonth[0] = julianday - 90; } else if (julianday >= 121 && julianday <= 151) { month[0] = 5; daymonth[0] = julianday - 120; } else if (julianday >= 152 && julianday <= 181) { month[0] = 6; daymonth[0] = julianday - 151; } else if (julianday >= 182 && julianday <= 212) { month[0] = 7; daymonth[0] = julianday - 181; } else if (julianday >= 213 && julianday <= 243) { month[0] = 8; daymonth[0] = julianday - 212; } else if (julianday >= 244 && julianday <= 273) { month[0] = 9; daymonth[0] = julianday - 243; } else if (julianday >= 274 && julianday <= 304) { month[0] = 10; daymonth[0] = julianday - 273; } else if (julianday >= 305 && julianday <= 334) { month[0] = 11; daymonth[0] = julianday - 304; } else if (julianday >= 335 && julianday <= 365) { month[0] = 12; daymonth[0] = julianday - 334; } } private void sun( double hour, int day, double[] E0, double[] alpha, double[] direction ) { // latitudine, longitudine in [rad] double G, Et, local_hour, D, Thr, beta; // correction sideral time G = 2.0 * PI * (day - 1) / 365.0; Et = 0.000075 + 0.001868 * cos(G) - 0.032077 * sin(G) - 0.014615 * cos(2 * G) - 0.04089 * sin(2 * G); // local time local_hour = hour + Et / omega; // Iqbal: formula 1.4.2 // earth-sun distance correction E0[0] = 1.00011 + 0.034221 * cos(G) + 0.00128 * sin(G) + 0.000719 * cos(2 * G) + 0.000077 * sin(2 * G); // solar declination D = 0.006918 - 0.399912 * cos(G) + 0.070257 * sin(G) - 0.006758 * cos(2 * G) + 0.000907 * sin(2 * G) - 0.002697 * cos(3 * G) + 0.00148 * sin(3 * G); // Sunrise and sunset with respect to midday [hour] Thr = (acos(-tan(D) * tan(avgLatitude))) / omega; if (local_hour >= 12.0 - Thr && local_hour <= 12.0 + Thr) { // alpha: solar height (complementar to zenith angle), [rad] alpha[0] = asin(sin(avgLatitude) * sin(D) + cos(avgLatitude) * cos(D) * cos(omega * (12.0 - local_hour))); // direction: azimuth angle (0 Nord, clockwise) [rad] if (local_hour <= 12) { if (alpha[0] == PI / 2.0) { /* sole allo zenit */ direction[0] = PI / 2.0; } else { direction[0] = PI - acos((sin(alpha[0]) * sin(avgLatitude) - sin(D)) / (cos(alpha[0]) * cos(avgLatitude))); } } else { if (alpha[0] == PI / 2.0) { /* sole allo zenit */ direction[0] = 3 * PI / 2.0; } else { direction[0] = PI + acos((sin(alpha[0]) * sin(avgLatitude) - sin(D)) / (cos(alpha[0]) * cos(avgLatitude))); } } // CALCOLO OMBRE /* * Chiama Orizzonte# Inputs: dx: dim. pixel (funziona solo per pixel quadrati) * 2(basin.Z.nch + basin.Z.nrh): dimensione matrice alpha: altezza solare Z: matrice * elevazioni curv: matrice curvature beta: azimuth +#PI/4 NOVALUE: novalue per Z0 * Outputs: shadow: matrice ombre (1 ombra 0 sole) */ if (direction[0] >= 0. && direction[0] <= PI / 4.) { beta = direction[0]; geomorphUtilities.orizzonte1(dx, 2 * (cols + rows), beta, alpha[0], elevImageIterator, curvatureImage, outputShadow); } else if (direction[0] > PI / 4. && direction[0] <= PI / 2.) { beta = (PI / 2. - direction[0]); geomorphUtilities.orizzonte2(dx, 2 * (cols + rows), beta, alpha[0], elevImageIterator, curvatureImage, outputShadow); } else if (direction[0] > PI / 2. && direction[0] <= PI * 3. / 4.) { beta = (direction[0] - PI / 2.); geomorphUtilities.orizzonte3(dx, 2 * (cols + rows), beta, alpha[0], elevImageIterator, curvatureImage, outputShadow); } else if (direction[0] > PI * 3. / 4. && direction[0] <= PI) { beta = (PI - direction[0]); geomorphUtilities.orizzonte4(dx, 2 * (cols + rows), beta, alpha[0], elevImageIterator, curvatureImage, outputShadow); } else if (direction[0] > PI && direction[0] <= PI * 5. / 4.) { beta = (direction[0] - PI); geomorphUtilities.orizzonte5(dx, 2 * (cols + rows), beta, alpha[0], elevImageIterator, curvatureImage, outputShadow); } else if (direction[0] > PI * 5. / 4. && direction[0] <= PI * 3. / 2.) { beta = (PI * 3. / 2. - direction[0]); geomorphUtilities.orizzonte6(dx, 2 * (cols + rows), beta, alpha[0], elevImageIterator, curvatureImage, outputShadow); } else if (direction[0] > PI * 3. / 2. && direction[0] <= PI * 7. / 4.) { beta = (direction[0] - PI * 3. / 2.); geomorphUtilities.orizzonte7(dx, 2 * (cols + rows), beta, alpha[0], elevImageIterator, curvatureImage, outputShadow); } else if (direction[0] > PI * 7. / 4. && direction[0] < 2. * PI) { beta = (2. * PI - direction[0]); /* * here we should have Orizzonte8, but the routine has an error. So the 1 is called. * Explanation: quello è un errore dovuto al fatto che la routine orizzonte8 è * sbagliata e dà errore, allora ci ho messo una pezza e ho richiamato la * orizzonte1, invece che la orizzonte 8. tuttavia le orizzonte 1 e 8 vengono * chiamate solo quando il sole è a nord e da noi questo non capita mai.. quindi * puoi lasciare così com'è */ geomorphUtilities.orizzonte1(dx, 2 * (cols + rows), beta, alpha[0], elevImageIterator, curvatureImage, outputShadow); // error!!! } } else { for( int r = 0; r < eibasinID.length; r++ ) { for( int c = 0; c < eibasinID[0].length; c++ ) { if (eibasinID[r][c] != (int) NOVALUE) outputShadow[r][c] = 1; } } alpha[0] = 0.0; direction[0] = 0.0; } } private void radiation( double[] Rad_morpho, double[] Rad_flat, double E0, double alpha, double direction, double aspect, double slope, int shadow ) { Rad_flat[0] = E0 * sin(alpha); if (shadow == 1 || alpha == 0.0) { // in ombra o di notte Rad_morpho[0] = 0.0; } else { Rad_morpho[0] = E0 * (cos(slope) * sin(alpha) + sin(slope) * cos(alpha) * cos(-aspect + direction)); } if (Rad_morpho[0] < 0) Rad_morpho[0] = 0.0; } private void average_EI( int month_begin, int month_end ) { int m, month; if (month_end < month_begin) month_end += 12; for( int r = 0; r < eibasinID.length; r++ ) { for( int c = 0; c < eibasinID[0].length; c++ ) { if (eibasinID[r][c] != NOVALUE) { eibasinE[r][c] = 0.0; for( m = month_begin - 1; m < month_end; m++ ) { if (m > 11) { month = m - 12; } else { month = m; } if (month < 6) { eibasinE[r][c] += eibasinEmonth[month][r][c]; } else { eibasinE[r][c] += eibasinEmonth[12 - month][r][c]; } } eibasinE[r][c] /= (double) (month_end - month_begin + 1); } } } } private void area( int i ) { double minES, maxES, minEI, maxEI; maxES = Double.NEGATIVE_INFINITY; minES = Double.POSITIVE_INFINITY; maxEI = Double.NEGATIVE_INFINITY; minEI = Double.POSITIVE_INFINITY; for( int r = 0; r < eibasinID.length; r++ ) { for( int c = 0; c < eibasinID[0].length; c++ ) { if (eibasinID[r][c] != NOVALUE) { // System.out.println("Bacino: " + eibasinID[r][c]); if (eibasinID[r][c] == i + 1) { double value = elevImageIterator.getSampleDouble(c, r, 0); if (value < minES) minES = value; if (value > maxES) maxES = value; if (eibasinE[r][c] < minEI) minEI = eibasinE[r][c]; if (eibasinE[r][c] > maxEI) maxEI = eibasinE[r][c]; } } } // System.out.println("minEi: " + minEI); // System.out.println("maxEi: " + maxEI); } for( int r = 0; r < eibasinID.length; r++ ) { for( int c = 0; c < eibasinID[0].length; c++ ) { if (eibasinID[r][c] == (i + 1)) { for( int j = 0; j < pEs; j++ ) { double minCurrentAltimetricBand = minES + (j) * (maxES - minES) / (double) pEs; double maxCurrentAltimetricBand = minES + (j + 1) * (maxES - minES) / (double) pEs; double value = elevImageIterator.getSampleDouble(c, r, 0); if ((value > minCurrentAltimetricBand && value <= maxCurrentAltimetricBand) || (j == 0 && value == minES)) { for( int k = 0; k < pEi; k++ ) { double minCurrentEnergeticBand = minEI + (k) * (maxEI - minEI) / (double) pEi; double maxCurrentEnergeticBand = minEI + (k + 1) * (maxEI - minEI) / (double) pEi; if ((eibasinE[r][c] > minCurrentEnergeticBand && eibasinE[r][c] <= maxCurrentEnergeticBand) || (k == 0 && eibasinE[r][c] == minEI)) { eibasinA[j][k][i] += 1.0; break; } } break; } } } } } for( int j = 0; j < pEs; j++ ) { for( int k = 0; k < pEi; k++ ) { eibasinA[j][k][i] *= (dx * dy * 1.0E-6); // in [km2] } } for( int j = 0; j < pEs; j++ ) { eibasinESrange[j][i] = (maxES - minES) / (double) pEs; eibasinES[j][i] = minES + (j + 1 - 0.5) * (maxES - minES) / (double) pEs; } int cont = 0; for( int m = 0; m < 6; m++ ) { for( int k = 0; k < pEi; k++ ) { cont = 0; for( int r = 0; r < eibasinID.length; r++ ) { for( int c = 0; c < eibasinID[0].length; c++ ) { if (eibasinID[r][c] != NOVALUE) { double test1 = minEI + (k) * (maxEI - minEI) / (double) pEi; double test2 = minEI + (k + 1) * (maxEI - minEI) / (double) pEi; if ((eibasinE[r][c] > test1 && eibasinE[r][c] <= test2) || (k == 0 && eibasinE[r][c] == minEI)) { cont += 1; eibasinEI[m][k][i] += eibasinEmonth[m][r][c]; } } } } if (cont == 0) { eibasinEI[m][k][i] = 0.00001; } else { eibasinEI[m][k][i] /= (double) cont; } } } } // private void output( int i ) { // // String filename = outputPath + formatter.format(reverseidMappings.get(i + 1)) + ".txt"; // // out.println(MessageFormat.format("Writing output {0} to file {1}", i, filename)); // if (new File(filename).exists()) { // // copy file to backup // try { // // Create channel on the source // FileChannel srcChannel = new FileInputStream(filename).getChannel(); // // // Create channel on the destination // FileChannel dstChannel = new FileOutputStream(filename + ".old").getChannel(); // // // Copy file contents from source to destination // dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); // // // Close the channels // srcChannel.close(); // dstChannel.close(); // // // remove the file // boolean success = (new File(filename)).delete(); // if (!success) { // out.println("Cannot remove file: " + filename + "!"); // return; // } // // } catch (IOException e) { // e.printStackTrace(); // return; // } // } // // BufferedWriter bw; // try { // bw = new BufferedWriter(new FileWriter(filename, true)); // // bw.write("# generated by EIcalculator*/"); // bw.write("\n@15"); // bw.write("\n"); // bw // .write("\n# 1 block - INDICE ENERGETICO PER LE BANDE ENERGETICHE PER OGNI MESE DELL'ANNO (-)") // ; // bw.write("\n"); // // bw.write("\n# 22 DICEMBRE - 20 GENNAIO "); // bw.write("\n% " + numEi + "\n"); // for( int k = 0; k < numEi - 1; k++ ) { // bw.write(eibasinEI[0][k][i] + " "); // } // bw.write("" + eibasinEI[0][numEi - 1][i]); // bw.write("\n"); // // bw.write("\n# 21 GENNAIO - 20 FEBBRAIO"); // bw.write("\n% " + numEi + "\n"); // for( int k = 0; k < numEi - 1; k++ ) { // bw.write(eibasinEI[1][k][i] + " "); // } // bw.write("" + eibasinEI[1][numEi - 1][i]); // bw.write("\n"); // // bw.write("\n# 21 FEBBRAIO - 22 MARZO"); // bw.write("\n% " + numEi + "\n"); // for( int k = 0; k < numEi - 1; k++ ) { // bw.write(eibasinEI[2][k][i] + " "); // } // bw.write("" + eibasinEI[2][numEi - 1][i]); // bw.write("\n"); // // bw.write("\n# 23 MARZO - 22 APRILE"); // bw.write("\n% " + numEi + "\n"); // for( int k = 0; k < numEi - 1; k++ ) { // bw.write(eibasinEI[3][k][i] + " "); // } // bw.write("" + eibasinEI[3][numEi - 1][i]); // bw.write("\n"); // // bw.write("\n# 23 APRILE - 22 MAGGIO"); // bw.write("\n% " + numEi + "\n"); // for( int k = 0; k < numEi - 1; k++ ) { // bw.write(eibasinEI[4][k][i] + " "); // } // bw.write("" + eibasinEI[4][numEi - 1][i]); // bw.write("\n"); // // bw.write("\n#23 MAGGIO - 22 GIUGNO"); // bw.write("\n% " + numEi + "\n"); // for( int k = 0; k < numEi - 1; k++ ) { // bw.write(eibasinEI[5][k][i] + " "); // } // bw.write("" + eibasinEI[5][numEi - 1][i]); // bw.write("\n"); // // bw.write("\n"); // bw.write("\n"); // bw.write("\n"); // bw // .write( // "\n# 2 block - QUOTA DEL BARICENTRO DELLE FASCIE ALTIMETRICHE e RANGE DI QUOTA PER OGNI FASCIA (m)" // ); // bw.write("\n"); // // bw.write("\n% " + numEs + "\n"); // for( int j = 0; j < numEs - 1; j++ ) { // bw.write(eibasinES[j][i] + " "); // } // bw.write("" + eibasinES[numEs - 1][i]); // // bw.write("\n% " + numEs + "\n"); // for( int j = 0; j < numEs - 1; j++ ) { // bw.write(eibasinESrange[j][i] + " "); // } // bw.write("" + eibasinESrange[numEs - 1][i]); // // bw.write("\n"); // bw.write("\n"); // bw.write("\n"); // // bw // .write("\n# 3 block - AREE PER FASCIA ALTIMETRICA (riga) E BANDA ENERGETICA (colonna) (km2)"); // bw.write("\n% " + numEs + " " + numEi + "\n"); // for( int j = 0; j < numEs; j++ ) { // for( int k = 0; k < numEi; k++ ) { // bw.write(eibasinA[j][k][i] + " "); // } // bw.write("\n"); // } // // bw.close(); // // } catch (IOException e) { // e.printStackTrace(); // } // // } }
gpl-3.0
robward-scisys/sldeditor
modules/application/src/main/java/com/sldeditor/common/xml/ui/XMLTestSection.java
3487
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference // Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: [TEXT REMOVED by maven-replacer-plugin] // package com.sldeditor.common.xml.ui; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * Configuration describe how to identify SLD attributes using XPATH * * <p>Java class for XMLTestSection complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="XMLTestSection"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="Field" type="{}XMLTestSectionField" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;attribute name="prefix" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="sldtype" use="required" type="{}SelectedTreeItemEnum" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType( name = "XMLTestSection", propOrder = {"field"}) public class XMLTestSection { @XmlElement(name = "Field") protected List<XMLTestSectionField> field; @XmlAttribute(name = "prefix", required = true) protected String prefix; @XmlAttribute(name = "sldtype", required = true) protected SelectedTreeItemEnum sldtype; /** * Gets the value of the field property. * * <p>This accessor method returns a reference to the live list, not a snapshot. Therefore any * modification you make to the returned list will be present inside the JAXB object. This is * why there is not a <CODE>set</CODE> method for the field property. * * <p>For example, to add a new item, do as follows: * * <pre> * getField().add(newItem); * </pre> * * <p>Objects of the following type(s) are allowed in the list {@link XMLTestSectionField } */ public List<XMLTestSectionField> getField() { if (field == null) { field = new ArrayList<XMLTestSectionField>(); } return this.field; } /** * Gets the value of the prefix property. * * @return possible object is {@link String } */ public String getPrefix() { return prefix; } /** * Sets the value of the prefix property. * * @param value allowed object is {@link String } */ public void setPrefix(String value) { this.prefix = value; } /** * Gets the value of the sldtype property. * * @return possible object is {@link SelectedTreeItemEnum } */ public SelectedTreeItemEnum getSldtype() { return sldtype; } /** * Sets the value of the sldtype property. * * @param value allowed object is {@link SelectedTreeItemEnum } */ public void setSldtype(SelectedTreeItemEnum value) { this.sldtype = value; } }
gpl-3.0
Geekhole/Foundations
app/src/main/java/uk/geekhole/foundations/utils/Util.java
1620
package uk.geekhole.foundations.utils; import android.util.Log; import com.google.common.io.Files; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.UUID; import uk.geekhole.foundations.Global.App; public class Util { private static final String APP_TAG = "Foundations"; public static void log(String message) { log(message, null); } public static void log(String message, Throwable e) { Log.d(APP_TAG, message, e); } public static void atomicWrite(String filename, String data) { File temp = new File(App.getContext().getFilesDir(), filename); if (temp.exists()) { temp = new File(App.getContext().getFilesDir(), UUID.randomUUID().toString()); } try { Files.write(data.getBytes(), temp); File finalFile = new File(filename); finalFile.delete(); temp.renameTo(finalFile); } catch (IOException e) { Util.log("Write failed.", e); } } public static String read(String filePath) throws Exception { File fl = new File(App.getContext().getFilesDir(), filePath); FileInputStream fin = new FileInputStream(fl); String ret = convertStreamToString(fin); fin.close(); return ret; } private static String convertStreamToString(InputStream is) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } reader.close(); return sb.toString(); } }
gpl-3.0
maxberger/wmsx
wmsx-common/src/main/java/hu/kfki/grid/wmsx/job/JobWatcher.java
10796
/* * WMSX - Workload Management Extensions for gLite * * Copyright (C) 2007-2009 Max Berger * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see http://www.gnu.org/licenses/. */ /* $Id$ */ package hu.kfki.grid.wmsx.job; import hu.kfki.grid.wmsx.JobInfo; import hu.kfki.grid.wmsx.TransportJobUID; import hu.kfki.grid.wmsx.backends.JobUid; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; /** * Watches currently running jobs. * * @version $Date$ */ public final class JobWatcher implements Runnable { private static final int TIME_BETWEEN_CHECKS_MS = 10000; private static final Logger LOGGER = Logger.getLogger(JobWatcher.class .toString()); private final Set<JobListener> catchAllJobListeners = new HashSet<JobListener>(); private final Map<JobUid, Set<JobListener>> joblisteners = new HashMap<JobUid, Set<JobListener>>(); private final Map<TransportJobUID, JobInfo> jobInfos = new HashMap<TransportJobUID, JobInfo>(); private Thread runThread; private boolean shutdown; private static final class SingletonHolder { private static final JobWatcher INSTANCE = new JobWatcher(); private SingletonHolder() { } } private JobWatcher() { this.runThread = null; this.shutdown = false; } private void doStart() { synchronized (this) { if (this.runThread == null) { JobWatcher.LOGGER.info("Starting new Listener"); this.runThread = new Thread(this); this.runThread.start(); } } } /** * @return Singleton instance. */ public static JobWatcher getInstance() { return JobWatcher.SingletonHolder.INSTANCE; } /** * Retrieve the JobInfo for a given Job. * * @param id * Id of the job. * @return the JobInfo. */ public JobInfo getInfoForJob(final TransportJobUID id) { JobInfo info; synchronized (this.jobInfos) { info = this.jobInfos.get(id); if (info == null) { info = new JobInfo(id); this.jobInfos.put(id, info); } } return info; } /** * Retrieve the JobInfo for a given Job. * * @param id * Id of the job. * @return the JobInfo. */ public JobInfo getInfoForJob(final JobUid id) { return this.getInfoForJob(id.toTransportJobUid()); } /** * Adds a catch-all listener. * * @param listener * Listener to add. */ public void addGenericListener(final JobListener listener) { synchronized (this.catchAllJobListeners) { this.catchAllJobListeners.add(listener); } } /** * Add a watcher for the given JobId. * * @param jobId * JobId to watcher * @param listener * The watcher to add. */ public void addWatch(final JobUid jobId, final JobListener listener) { if (jobId == null) { return; } synchronized (this) { if (!this.shutdown) { Set<JobListener> listeners = this.joblisteners.get(jobId); if (listeners == null) { listeners = new HashSet<JobListener>(); this.joblisteners.put(jobId, listeners); } listeners.add(listener); this.doStart(); this.sendMissedStates(jobId, listener); } } } /** * @param jobId * @param listener */ private void sendMissedStates(final JobUid jobId, final JobListener listener) { final JobState stateNow = this.getInfoForJob(jobId).getStatus(); if (JobState.STARTUP.equals(stateNow)) { listener.startup(jobId); } else if (JobState.RUNNING.equals(stateNow)) { listener.startup(jobId); listener.running(jobId); } else if (JobState.SUCCESS.equals(stateNow)) { listener.startup(jobId); listener.running(jobId); listener.done(jobId, true); } else if (JobState.FAILED.equals(stateNow)) { listener.startup(jobId); listener.running(jobId); listener.done(jobId, false); } } /** * Initiate shutdown. */ public synchronized void shutdown() { this.shutdown = true; if (this.runThread != null) { this.runThread.interrupt(); } } /** Constantly watches jobs. */ public void run() { boolean done = false; while (!done) { try { Thread.sleep(JobWatcher.TIME_BETWEEN_CHECKS_MS); } catch (final InterruptedException e) { JobWatcher.LOGGER.fine(e.getMessage()); } Set<JobUid> jobs; synchronized (this) { jobs = new HashSet<JobUid>(this.joblisteners.keySet()); } final Iterator<JobUid> it = jobs.iterator(); while (it.hasNext()) { final JobUid jobId = it.next(); JobState stateNow; final boolean terminate; synchronized (this) { terminate = this.shutdown; } if (terminate) { stateNow = JobState.FAILED; } else { stateNow = jobId.getBackend().getState(jobId); } if (stateNow == null) { stateNow = JobState.NONE; } this.checkWithState(jobId, stateNow); } synchronized (this) { if (this.joblisteners.isEmpty()) { done = true; this.runThread = null; JobWatcher.LOGGER.info("No more jobs to listen to."); } } } } /** * Push method if state has changed. * * @param jobId * Id of the job * @param stateNow * new state. */ public void checkWithState(final JobUid jobId, final JobState stateNow) { final boolean differs = this.hasStateChanged(jobId, stateNow); if (differs) { final Set<JobListener> listeners = this .getSafeCopyOfJobListeners(jobId); this.notifyListeners(jobId, stateNow, listeners); this.removeDoneStates(jobId, stateNow); } } private void removeDoneStates(final JobUid jobId, final JobState stateNow) { if (JobState.SUCCESS.equals(stateNow) || JobState.FAILED.equals(stateNow)) { synchronized (this) { this.joblisteners.remove(jobId); } } } /** * @return A list of active jobs. */ public Iterable<TransportJobUID> getActiveJobs() { List<TransportJobUID> retVal; synchronized (this) { retVal = new ArrayList<TransportJobUID>(this.joblisteners.size()); for (final JobUid jid : this.joblisteners.keySet()) { retVal.add(jid.toTransportJobUid()); } } return retVal; } private void notifyListeners(final JobUid jobId, final JobState stateNow, final Set<JobListener> listeners) { final Iterator<JobListener> li = listeners.iterator(); while (li.hasNext()) { final JobListener listener = li.next(); this.notifyListener(jobId, stateNow, listener); } synchronized (this.catchAllJobListeners) { for (final JobListener listener : this.catchAllJobListeners) { this.notifyListener(jobId, stateNow, listener); } } } /** * @param jobId * @param stateNow * @param listener */ private void notifyListener(final JobUid jobId, final JobState stateNow, final JobListener listener) { if (JobState.STARTUP.equals(stateNow)) { listener.startup(jobId); } else if (JobState.RUNNING.equals(stateNow)) { listener.running(jobId); } else if (JobState.SUCCESS.equals(stateNow)) { listener.done(jobId, true); } else if (JobState.FAILED.equals(stateNow)) { listener.done(jobId, false); } } private synchronized Set<JobListener> getSafeCopyOfJobListeners( final JobUid jobId) { Set<JobListener> listeners; final Set<JobListener> gset = this.joblisteners.get(jobId); if (gset == null) { listeners = new HashSet<JobListener>(); } else { listeners = new HashSet<JobListener>(gset); } return listeners; } private boolean hasStateChanged(final JobUid jobId, final JobState stateNow) { final boolean differs; synchronized (this.jobInfos) { final JobInfo info = this.getInfoForJob(jobId); JobState oldState = info.getStatus(); if (oldState == null) { oldState = JobState.NONE; } differs = !oldState.equals(stateNow); if (differs) { info.setStatus(stateNow); if (JobState.STARTUP.equals(stateNow)) { info.setCreationTime(new Date()); } else if (JobState.RUNNING.equals(stateNow)) { info.setStartRunningTime(new Date()); } else if (JobState.SUCCESS.equals(stateNow) || JobState.FAILED.equals(stateNow)) { info.setDoneRunningTime(new Date()); } } } return differs; } /** * get the number of running jobs. * * @return number of running jobs. */ public synchronized int getNumJobsRunning() { return this.joblisteners.size(); } }
gpl-3.0
trakem2/TrakEM2
src/main/java/ini/trakem2/display/Connector.java
17310
/*- * #%L * TrakEM2 plugin for ImageJ. * %% * Copyright (C) 2005 - 2021 Albert Cardona, Stephan Saalfeld and others. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ package ini.trakem2.display; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.scijava.vecmath.Point3f; import ij.measure.Calibration; import ij.measure.ResultsTable; import ini.trakem2.Project; import ini.trakem2.utils.M; import ini.trakem2.utils.ProjectToolbar; import ini.trakem2.utils.Utils; /** A one-to-many connection, represented by one source point and one or more target points. The connector is drawn by click+drag+release, defining the origin at click and the target at release. By clicking anywhere else, the connector can be given another target. Points can be dragged and removed. * Connectors are meant to represent synapses, in particular polyadic synapses. */ public class Connector extends Treeline { public Connector(final Project project, final String title) { super(project, title); } public Connector(final Project project, final long id, final String title, final float width, final float height, final float alpha, final boolean visible, final Color color, final boolean locked, final AffineTransform at) { super(project, project.getLoader().getNextId(), title, width, height, alpha, visible, color, locked, at); } /** Reconstruct from XML. */ public Connector(final Project project, final long id, final HashMap<String,String> ht_attr, final HashMap<Displayable,String> ht_links) { super(project, id, ht_attr, ht_links); } @Override public Tree<Float> newInstance() { return new Connector(project, project.getLoader().getNextId(), title, width, height, alpha, visible, color, locked, at); } @Override public Node<Float> newNode(final float lx, final float ly, final Layer la, final Node<?> modelNode) { return new ConnectorNode(lx, ly, la, null == modelNode ? 0 : ((ConnectorNode)modelNode).r); } @Override public Node<Float> newNode(final HashMap<String,String> ht_attr) { return new ConnectorNode(ht_attr); } static public class ConnectorNode extends Treeline.RadiusNode { public ConnectorNode(final float lx, final float ly, final Layer la) { super(lx, ly, la); } public ConnectorNode(final float lx, final float ly, final Layer la, final float radius) { super(lx, ly, la, radius); } /** To reconstruct from XML, without a layer. */ public ConnectorNode(final HashMap<String,String> attr) { super(attr); } @Override public final Node<Float> newInstance(final float lx, final float ly, final Layer layer) { return new ConnectorNode(lx, ly, layer, 0); } @Override public void paintData(final Graphics2D g, final Rectangle srcRect, final Tree<Float> tree, final AffineTransform to_screen, final Color cc, final Layer active_layer) { g.setColor(cc); g.draw(to_screen.createTransformedShape(new Ellipse2D.Float(x -r, y -r, r+r, r+r))); } @Override public boolean intersects(final Area a) { if (0 == r) return a.contains(x, y); return M.intersects(a, getArea()); } @Override public boolean isRoughlyInside(final Rectangle localbox) { final float r = this.r <= 0 ? 1 : this.r; return localbox.intersects(x - r, y - r, r + r, r + r); } @Override public Area getArea() { if (0 == r) return super.getArea(); // a little square return new Area(new Ellipse2D.Float(x-r, y-r, r+r, r+r)); } @Override public void paintHandle(final Graphics2D g, final Rectangle srcRect, final double magnification, final Tree<Float> t) { final Point2D.Double po = t.transformPoint(this.x, this.y); final float x = (float)((po.x - srcRect.x) * magnification); final float y = (float)((po.y - srcRect.y) * magnification); if (null == parent) { g.setColor(brightGreen); g.fillOval((int)x - 6, (int)y - 6, 11, 11); g.setColor(Color.black); g.drawString("o", (int)x -4, (int)y + 3); // TODO ensure Font is proper } else { g.setColor(Color.white); g.fillOval((int)x - 6, (int)y - 6, 11, 11); g.setColor(Color.black); g.drawString("x", (int)x -4, (int)y + 3); // TODO ensure Font is proper } } } static private final Color brightGreen = new Color(33, 255, 0); public void readLegacyXML(final LayerSet ls, final HashMap<String,String> ht_attr, final HashMap<Displayable,String> ht_links) { final String origin = ht_attr.get("origin"); final String targets = ht_attr.get("targets"); if (null != origin) { final String[] o = origin.split(","); String[] t = null; int len = 1; final boolean new_format = 0 == o.length % 4; if (null != targets) { t = targets.split(","); if (new_format) { // new format, with radii len += t.length / 4; } else { // old format, without radii len += t.length / 3; } } final float[] p = new float[len + len]; final long[] lids = new long[len]; final float[] radius = new float[len]; // Origin: /* X */ p[0] = Float.parseFloat(o[0]); /* Y */ p[1] = Float.parseFloat(o[1]); /* LZ */ lids[0] = Long.parseLong(o[2]); if (new_format) { radius[0] = Float.parseFloat(o[3]); } // Targets: if (null != targets && targets.length() > 0) { final int inc = new_format ? 4 : 3; for (int i=0, k=1; i<t.length; i+=inc, k++) { /* X */ p[k+k] = Float.parseFloat(t[i]); /* Y */ p[k+k+1] = Float.parseFloat(t[i+1]); /* LZ */ lids[k] = Long.parseLong(t[i+2]); if (new_format) radius[k] = Float.parseFloat(t[i+3]); } } //if (!new_format) calculateBoundingBox(null); // Now, into nodes: final Node<Float> root = new ConnectorNode(p[0], p[1], ls.getLayer(lids[0]), radius[0]); for (int i=1; i<lids.length; i++) { final Node<Float> nd = new ConnectorNode(p[i+i], p[i+i+1], ls.getLayer(lids[i]), radius[i]); root.add(nd, Node.MAX_EDGE_CONFIDENCE); } setRoot(root); // Above, cannot be done with addNode: would call repaint and thus calculateBoundingBox, which would screw up relative coords. // Fix bounding box to new tree methods: calculateBoundingBox(null); } } public int addTarget(final float x, final float y, final long layer_id, final float r) { if (null == root) return -1; root.add(new ConnectorNode(x, y, layer_set.getLayer(layer_id), r), Node.MAX_EDGE_CONFIDENCE); return root.getChildrenCount() - 1; } public int addTarget(final double x, final double y, final long layer_id, final double r) { return addTarget((float)x, (float)y, layer_id, (float)r); } protected void mergeTargets(final Connector c) throws NoninvertibleTransformException { if (null == c.root) return; if (null == this.root) this.root = newNode(c.root.x, c.root.y, c.root.la, c.root); final AffineTransform aff = new AffineTransform(c.at); aff.preConcatenate(this.at.createInverse()); final float[] f = new float[4]; for (final Map.Entry<Node<Float>,Byte> e : c.root.getChildren().entrySet()) { final ConnectorNode nd = (ConnectorNode)e.getKey(); f[0] = nd.x; f[1] = nd.y; f[2] = nd.x + nd.r; // make the radius be a point to the right of x,y f[3] = nd.y; aff.transform(f, 0, f, 0, 2); this.root.add(new ConnectorNode(f[0],f[1], nd.la, Math.abs(f[2] - f[0])), e.getValue().byteValue()); } } public boolean intersectsOrigin(final Area area, final Layer la) { if (null == root || root.la != la) return false; final Area a = root.getArea(); a.transform(this.at); return M.intersects(area, a); } /** Whether the area of the root node intersects the world coordinates {@code wx}, {@code wy} at {@link Layer} {@code la}. */ public boolean intersectsOrigin(final double wx, final double wy, final Layer la) { if (null == root || root.la != la) return false; final Area a = root.getArea(); a.transform(this.at); return a.contains(wx, wy); } /** Returns the set of Displayable objects under the origin point, or an empty set if none. */ public Set<Displayable> getOrigins(final Class<?> c) { final int m = c.getModifiers(); return getOrigins(c, Modifier.isAbstract(m) || Modifier.isInterface(m)); } public Set<Displayable> getOrigins(final Class<?> c, final boolean instance_of) { if (null == root) return new HashSet<Displayable>(); return getUnder(root, c, instance_of); } private final Set<Displayable> getUnder(final Node<Float> node, final Class<?> c, final boolean instance_of) { final Area a = node.getArea(); a.transform(this.at); final HashSet<Displayable> targets = new HashSet<Displayable>(layer_set.find(c, node.la, a, false, instance_of)); targets.remove(this); return targets; } /** Returns the set of Displayable objects under the origin point, or an empty set if none. */ public Set<Displayable> getOrigins() { if (null == root) return new HashSet<Displayable>(); return getUnder(root, Displayable.class, true); } public List<Set<Displayable>> getTargets(final Class<?> c, final boolean instance_of) { final List<Set<Displayable>> al = new ArrayList<Set<Displayable>>(); if (null == root || !root.hasChildren()) return al; for (final Node<Float> nd : root.getChildrenNodes()) { al.add(getUnder(nd, c, instance_of)); } return al; } /** Returns the list of sets of visible Displayable objects under each target, or an empty list if none. */ public List<Set<Displayable>> getTargets(final Class<?> c) { final int m = c.getModifiers(); return getTargets(c, Modifier.isAbstract(m) || Modifier.isInterface(m)); } /** Returns the list of sets of visible Displayable objects under each target, or an empty list if none. */ public List<Set<Displayable>> getTargets() { return getTargets(Displayable.class, true); } public int getTargetCount() { if (null == root) return 0; return root.getChildrenCount(); } static public void exportDTD(final StringBuilder sb_header, final HashSet<String> hs, final String indent) { Tree.exportDTD(sb_header, hs, indent); final String type = "t2_connector"; if (hs.contains(type)) return; hs.add(type); sb_header.append(indent).append("<!ELEMENT t2_connector (t2_node*,").append(Displayable.commonDTDChildren()).append(")>\n"); Displayable.exportDTD(type, sb_header, hs, indent); } @Override public Connector clone(final Project pr, final boolean copy_id) { final long nid = copy_id ? this.id : pr.getLoader().getNextId(); final Connector copy = new Connector(pr, nid, title, width, height, this.alpha, true, this.color, this.locked, this.at); copy.root = null == this.root ? null : this.root.clone(pr); copy.addToDatabase(); if (null != copy.root) copy.cacheSubtree(copy.root.getSubtreeNodes()); return copy; } private final void insert(final Node<Float> nd, final ResultsTable rt, final int i, final Calibration cal, final float[] f) { f[0] = nd.x; f[1] = nd.y; this.at.transform(f, 0, f, 0, 1); // rt.incrementCounter(); rt.addLabel("units", cal.getUnits()); rt.addValue(0, this.id); rt.addValue(1, i); rt.addValue(2, f[0] * cal.pixelWidth); rt.addValue(3, f[1] * cal.pixelHeight); rt.addValue(4, nd.la.getZ() * cal.pixelWidth); // NOT pixelDepth! rt.addValue(5, ((ConnectorNode)nd).r); rt.addValue(6, nd.confidence); } @Override public ResultsTable measure(ResultsTable rt) { if (null == root) return rt; if (null == rt) rt = Utils.createResultsTable("Connector results", new String[]{"id", "index", "x", "y", "z", "radius", "confidence"}); final Calibration cal = layer_set.getCalibration(); final float[] f = new float[2]; insert(root, rt, 0, cal, f); if (null == root.children) return rt; for (int i=0; i<root.children.length; i++) { insert(root.children[i], rt, i+1, cal, f); } return rt; } public List<Point3f> getTargetPoints(final boolean calibrated) { if (null == root) return null; final List<Point3f> targets = new ArrayList<Point3f>(); if (null == root.children) return targets; final float[] f = new float[2]; for (final Node<Float> nd : root.children) { targets.add(fix(nd.asPoint(), calibrated, f)); } return targets; } public Coordinate<Node<Float>> getCoordinateAtOrigin() { if (null == root) return null; return createCoordinate(root); } /** Get a coordinate for target i. */ public Coordinate<Node<Float>> getCoordinate(final int i) { if (null == root || !root.hasChildren()) return null; return createCoordinate(root.children[i]); } @Override public String getInfo() { if (null == root) return "Empty"; return new StringBuilder("Targets: ").append(root.getChildrenCount()).append('\n').toString(); } /** If the root node is in Layer @param la, then all nodes are removed. */ @Override protected boolean layerRemoved(final Layer la) { if (null == root) return true; if (root.la == la) { super.removeNode(root); // and all its children return true; } // Else, remove any targets return super.layerRemoved(la); } /** Takes the List of Connector instances and adds the targets of all to the first one. * Removes the others from the LayerSet and from the Project. * If any of the Connector instances cannot be removed, returns null. */ static public Connector merge(final List<Connector> col) throws NoninvertibleTransformException { if (null == col || 0 == col.size()) return null; final Connector base = col.get(0); for (final Connector con : col.subList(1, col.size())) { base.mergeTargets(con); if (!con.remove2(false)) { Utils.log("FAILED to merge Connector " + con + " into " + base); return null; } } return base; } /** Add a root or child nodes to root. */ @Override public void mousePressed(final MouseEvent me, final Layer layer, final int x_p, final int y_p, final double mag) { if (ProjectToolbar.PEN != ProjectToolbar.getToolId()) { return; } if (-1 == last_radius) { last_radius = 10 / (float)mag; } if (null != root) { // transform the x_p, y_p to the local coordinates int x_pl = x_p; int y_pl = y_p; if (!this.at.isIdentity()) { final Point2D.Double po = inverseTransformPoint(x_p, y_p); x_pl = (int)po.x; y_pl = (int)po.y; } Node<Float> found = findNode(x_pl, y_pl, layer, mag); setActive(found); if (null != found) { if (2 == me.getClickCount()) { setLastMarked(found); setActive(null); return; } if (me.isShiftDown() && Utils.isControlDown(me)) { if (found == root) { // Remove the whole Connector layer_set.addChangeTreesStep(); if (remove2(true)) { setActive(null); layer_set.addChangeTreesStep(); } else { layer_set.removeLastUndoStep(); // no need } return; } else { // Remove point removeNode(found); } } } else { if (2 == me.getClickCount()) { setLastMarked(null); return; } // Add new target point to root: found = newNode(x_pl, y_pl, layer, root); ((ConnectorNode)found).setData(last_radius); addNode(root, found, Node.MAX_EDGE_CONFIDENCE); setActive(found); repaint(true, layer); } return; } else { // First point root = newNode(x_p, y_p, layer, null); // world coords, so calculateBoundingBox will do the right thing addNode(null, root, (byte)0); ((ConnectorNode)root).setData(last_radius); setActive(root); } } @Override protected boolean requireAltDownToEditRadius() { return false; } @Override protected Rectangle getBounds(final Collection<? extends Node<Float>> nodes) { final Rectangle nb = new Rectangle(); Rectangle box = null; for (final RadiusNode nd : (Collection<RadiusNode>)(Collection)nodes) { final int r = 0 == nd.r ? 1 : (int)nd.r; if (null == box) box = new Rectangle((int)nd.x - r, (int)nd.y - r, r+r, r+r); else { nb.setBounds((int)nd.x - r, (int)nd.y - r, r+r, r+r); box.add(nb); } } return box; } /** If the root node (the origin) does not remain within the range, this Connector is left empty. */ @Override public boolean crop(final List<Layer> range) { if (null == root) return true; // it's empty already if (!range.contains(root.la)) { this.root = null; synchronized (node_layer_map) { clearCache(); } return true; } return super.crop(range); } }
gpl-3.0
kontalk/desktopclient-java
src/main/java/org/kontalk/view/ContactDetails.java
12270
/* * Kontalk Java client * Copyright (C) 2016 Kontalk Devteam <devteam@kontalk.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kontalk.view; import javax.swing.Box; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import java.util.Observable; import java.util.Optional; import com.alee.extended.layout.FormLayout; import com.alee.extended.panel.GroupPanel; import com.alee.extended.panel.GroupingType; import com.alee.laf.button.WebButton; import com.alee.laf.checkbox.WebCheckBox; import com.alee.laf.label.WebLabel; import com.alee.laf.optionpane.WebOptionPane; import com.alee.laf.panel.WebPanel; import com.alee.laf.separator.WebSeparator; import com.alee.laf.text.WebTextArea; import com.alee.laf.text.WebTextField; import com.alee.managers.tooltip.TooltipManager; import org.kontalk.misc.JID; import org.kontalk.model.Contact; import org.kontalk.util.Tr; import org.kontalk.view.AvatarLoader.AvatarImg; import org.kontalk.view.ComponentUtils.LabelTextField; /** * Show and edit contact details. * * @author Alexander Bikadorov {@literal <bikaejkb@mail.tu-berlin.de>} */ final class ContactDetails extends WebPanel implements ObserverTrait { private static final Map<Contact, ContactDetails> CACHE = new HashMap<>(); private final View mView; private final Contact mContact; private final ComponentUtils.EditableAvatarImage mAvatarImage; private final WebTextField mNameField; private final WebLabel mSubscrStatus; private final WebButton mSubscrButton; private final WebLabel mKeyStatus; private final WebLabel mFPLabel; private final WebButton mUpdateButton; private final WebTextArea mFPArea; private final WebCheckBox mEncryptionBox; private ContactDetails(View view, Contact contact) { mView = view; mContact = contact; GroupPanel groupPanel = new GroupPanel(View.GAP_BIG, false); groupPanel.setMargin(View.MARGIN_BIG); groupPanel.add(new WebLabel(Tr.tr("Contact details")).setBoldFont()); groupPanel.add(new WebSeparator(true, true)); WebPanel mainPanel = new WebPanel(new FormLayout(View.GAP_DEFAULT, View.GAP_DEFAULT)); // editable components mAvatarImage = new ComponentUtils.EditableAvatarImage(View.AVATAR_DETAIL_SIZE) { @Override void onImageChange(Optional<BufferedImage> optImage) { if (optImage.isPresent()) mView.getControl().setCustomContactAvatar(mContact, optImage.get()); else mView.getControl().unsetCustomContactAvatar(mContact); } @Override AvatarImg defaultImage() { return AvatarLoader.load(mContact, View.AVATAR_DETAIL_SIZE); } @Override boolean canRemove() { return mContact.hasCustomAvatarSet(); } @Override protected void update() { if (mContact.hasCustomAvatarSet()) return; super.update(); } }; int size = View.AVATAR_DETAIL_SIZE + View.MARGIN_DEFAULT; mainPanel.add(new WebPanel(false, mAvatarImage) .setPreferredWidth(size).setPreferredHeight(size)); mainPanel.add(Box.createGlue()); mainPanel.add(new WebLabel(Tr.tr("Display Name:"))); mNameField = new LabelTextField(View.MAX_NAME_LENGTH, 15, this) { @Override protected String labelText() { return mContact.getName(); } @Override protected String editText() { return mContact.getName(); } @Override protected void onFocusLost() { ContactDetails.this.saveName(this.getText().trim()); } }; mNameField.setFontSizeAndStyle(14, true, false); mainPanel.add(mNameField); mainPanel.add(new WebLabel("Jabber ID:")); LabelTextField jidField = new LabelTextField(View.MAX_JID_LENGTH, 20, this) { @Override protected String labelText() { return Utils.jid(mContact.getJID(), View.PRETTY_JID_LENGTH); } @Override protected String editText() { return mContact.getJID().asUnescapedString(); } @Override protected void onFocusLost() { ContactDetails.this.saveJID(JID.bare(this.getText().trim())); } }; String jidText = Tr.tr("The unique address of this contact"); TooltipManager.addTooltip(jidField, jidText); mainPanel.add(jidField); mainPanel.add(new WebLabel(Tr.tr("Authorization:"))); mSubscrStatus = new WebLabel(); String subscrText = Tr.tr("Permission to view presence status and public key"); TooltipManager.addTooltip(mSubscrStatus, subscrText); mSubscrButton = new WebButton(Tr.tr("Request")); String reqText = Tr.tr("Request status authorization from contact"); TooltipManager.addTooltip(mSubscrButton, reqText); mSubscrButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { mView.getControl().sendSubscriptionRequest(mContact); } }); mainPanel.add(new GroupPanel(GroupingType.fillFirst, View.GAP_DEFAULT, mSubscrStatus, mSubscrButton)); groupPanel.add(mainPanel); groupPanel.add(new WebSeparator(true, true)); WebPanel keyPanel = new WebPanel(new FormLayout(View.GAP_DEFAULT, View.GAP_DEFAULT)); keyPanel.add(new WebLabel(Tr.tr("Public Key")+":")); mKeyStatus = new WebLabel(); mUpdateButton = new WebButton(Utils.getIcon("ic_ui_reload.png")); String updText = Tr.tr("Update key"); TooltipManager.addTooltip(mUpdateButton, updText); mUpdateButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { mView.getControl().requestKey(ContactDetails.this.mContact); } }); keyPanel.add(new GroupPanel(GroupingType.fillFirst, View.GAP_DEFAULT, mKeyStatus, mUpdateButton)); mFPLabel = new WebLabel(Tr.tr("Fingerprint:")); keyPanel.add(mFPLabel); mFPArea = Utils.createFingerprintArea(); String fpText = Tr.tr("The unique ID of this contact's key"); TooltipManager.addTooltip(mFPArea, fpText); mFPLabel.setAlignmentY(Component.TOP_ALIGNMENT); keyPanel.add(mFPArea); // set everything that can change this.updateOnEDT(null, null); groupPanel.add(keyPanel); mEncryptionBox = new WebCheckBox(Tr.tr("Use Encryption")); mEncryptionBox.setAnimated(false); mEncryptionBox.setSelected(mContact.getEncrypted()); String encText = Tr.tr("Encrypt and sign all messages send to this contact"); TooltipManager.addTooltip(mEncryptionBox, encText); mEncryptionBox.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { mContact.setEncrypted(mEncryptionBox.isSelected()); } }); groupPanel.add(new GroupPanel(mEncryptionBox, Box.createGlue())); this.add(groupPanel, BorderLayout.WEST); WebPanel gradientPanel = new WebPanel(false) { @Override public void paintComponent(Graphics g) { super.paintComponent(g); int w = this.getWidth(); int h = this.getHeight(); BufferedImage mCached = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D cachedG = mCached.createGraphics(); GradientPaint p2 = new GradientPaint( 0, 0, this.getBackground(), w, 0, Color.LIGHT_GRAY); cachedG.setPaint(p2); cachedG.fillRect(0, 0, w, h); g.drawImage(mCached, 0, 0, this.getWidth(), this.getHeight(), null); } }; this.add(gradientPanel, BorderLayout.CENTER); } void setRenameFocus() { mNameField.requestFocusInWindow(); } @Override public void updateOnEDT(Observable o, Object arg) { // may have changed: avatar... mAvatarImage.update(); // ...contact name... mNameField.setText(mContact.getName()); mNameField.setInputPrompt(mContact.getName()); Contact.Subscription subscription = mContact.getSubScription(); String auth = Tr.tr("Unknown"); switch(subscription) { case PENDING: auth = Tr.tr("Awaiting reply"); break; case SUBSCRIBED: auth = Tr.tr("Authorized"); break; case UNSUBSCRIBED: auth = Tr.tr("Not authorized"); break; } // ...subscription... mSubscrButton.setVisible(subscription != Contact.Subscription.SUBSCRIBED); mSubscrButton.setEnabled(subscription == Contact.Subscription.UNSUBSCRIBED); mSubscrStatus.setText(auth); // ...and/or key String hasKey = "<html>"; if (mContact.hasKey()) { hasKey += Tr.tr("Available")+"</html>"; TooltipManager.removeTooltips(mKeyStatus); mFPArea.setText(Utils.fingerprint(mContact.getFingerprint())); mFPLabel.setVisible(true); mFPArea.setVisible(true); } else { hasKey += "<font color='red'>"+Tr.tr("Not Available")+"</font></html>"; String keyText = Tr.tr("The public key for this contact could not yet be received"); TooltipManager.addTooltip(mKeyStatus, keyText); mFPLabel.setVisible(false); mFPArea.setVisible(false); } mKeyStatus.setText(hasKey); mUpdateButton.setEnabled(mContact.isKontalkUser() && subscription == Contact.Subscription.SUBSCRIBED); } private void saveName(String name) { if (name.equals(mContact.getName())) return; mView.getControl().changeName(mContact, name); } private void saveJID(JID jid) { if (!jid.isValid() || jid.equals(mContact.getJID())) // TODO feedback for invalid jid return; String warningText = Tr.tr("Changing the JID is only useful in very rare cases. Are you sure?"); int selectedOption = WebOptionPane.showConfirmDialog(this, warningText, Tr.tr("Please Confirm"), WebOptionPane.OK_CANCEL_OPTION, WebOptionPane.WARNING_MESSAGE); if (selectedOption == WebOptionPane.OK_OPTION) mView.getControl().changeJID(mContact, jid); } static ContactDetails instance(View view, Contact contact) { if (!CACHE.containsKey(contact)) { ContactDetails newContactDetails = new ContactDetails(view, contact); contact.addObserver(newContactDetails); CACHE.put(contact, newContactDetails); } return CACHE.get(contact); } }
gpl-3.0
fmichel/MaDKit-demos
MaDKit-ping-pong/src/madkit/pingpong/PingPong.java
3692
/* * Copyright 1997-2012 Fabien Michel, Olivier Gutknecht, Jacques Ferber * * This file is part of MaDKit_Demos. * * MaDKit_Demos is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MaDKit_Demos is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MaDKit_Demos. If not, see <http://www.gnu.org/licenses/>. */ package madkit.pingpong; import java.awt.Color; import javax.swing.JFrame; import javax.swing.JPanel; import madkit.gui.AgentFrame; import madkit.gui.OutputPanel; import madkit.kernel.Agent; import madkit.kernel.AgentAddress; import madkit.kernel.Madkit; import madkit.message.ObjectMessage; /** * @author Fabien Michel, Olivier Gutknecht * @version 5.1 */ public class PingPong extends Agent { private AgentAddress currentPartner = null; private ObjectMessage<Color> ball = null; private JPanel myPanel; private JFrame myFrame; @Override public void activate() { createGroupIfAbsent("ping-pong", "room", true, null); requestRole("ping-pong", "room", "player", null); } @Override public void live() { while (isAlive()) { searching(); playing(); } } private void searching() { currentPartner = null; // searching a new partner changeGUIColor(Color.WHITE); ball = null; while (currentPartner == null) { ball = (ObjectMessage<Color>) waitNextMessage(1000); if (ball != null) { currentPartner = ball.getSender(); } else { currentPartner = getAgentWithRole("ping-pong", "room", "player"); } } getLogger().info("I found someone to play with : " + currentPartner + " !!! "); } private void playing() { Color ballColor; if (ball == null) { ballColor = getRandomColor(); ball = (ObjectMessage<Color>) sendMessageAndWaitForReply(currentPartner, new ObjectMessage<>(ballColor), 1300); if (ball == null) { // nobody replied ! getLogger().info(currentPartner + " did not reply to me :( !! "); currentPartner = null; return; } } else { ballColor = ball.getContent(); } changeGUIColor(ballColor); ObjectMessage<Color> ballMessage = new ObjectMessage<>(ballColor); for (int i = 0; i < 10; i++) {// if ball == null partner is gone !! ball = (ObjectMessage<Color>) sendReplyAndWaitForReply(ball, ballMessage, 1300); if (ball == null) { getLogger().info(currentPartner + " is gone :( !! "); break; } getLogger().info(" Playing :) with " + currentPartner + " ball nb is " + i); pause((int) (Math.random() * 1000)); } purgeMailbox(); // purge mailBox from old playing attempts } @Override public void setupFrame(AgentFrame frame) { myPanel = new OutputPanel(this); frame.add(myPanel); myFrame = frame; } private void changeGUIColor(Color c) { if (myPanel != null) myPanel.setBackground(c); } public void setFrameLocation(int x, int y) { if (myFrame != null) { myFrame.setLocation(x, y); } } private Color getRandomColor() { return new Color((int) (Math.random() * 256), (int) (Math.random() * 256), (int) (Math.random() * 256)); } public static void main(String[] args) { String[] argss = { "--network", "--launchAgents", PingPong.class.getName(), ",true" }; Madkit.main(argss); } }
gpl-3.0
jitlogic/zorka
zorka-common/src/test/java/com/jitlogic/zorka/common/test/http/HttpRequestHandlerUnitTest.java
2186
package com.jitlogic.zorka.common.test.http; import com.jitlogic.zorka.common.http.HttpConfig; import com.jitlogic.zorka.common.http.HttpMessage; import com.jitlogic.zorka.common.http.HttpMethod; import org.junit.Test; public class HttpRequestHandlerUnitTest { // private HttpConfig config = new HttpConfig(); // private TestMessageListener cliListener = new TestMessageListener(); // private HttpMessageHandler cliHandler = new HttpMessageHandler(config, cliListener); // private TestMessageListener svrListener = new TestMessageListener(); // private HttpProtocolHandler serverHandler = new HttpProtocolHandler( // config, new HttpMessageHandler(config, svrListener)); // // private TestBufOutput serverConn = new TestBufOutput(serverHandler); // private TestBufOutput clientConn = new TestBufOutput( // new HttpProtocolHandler(config, // HttpDecoderState.READ_RESP_LINE, // new HttpMessageHandler(config, cliListener))); // // private TestNetExchange exchange = new TestNetExchange(clientConn, serverConn); // // // @Test // public void testSingleGetReq() { // svrListener.addReplies(HttpMessage.RESP(200, null).headers("X-Foo", "bar")); // exchange.submit(new HttpRequest(config, cliHandler, "http://localhost", HttpMethod.GET)); // assertEquals(1, svrListener.getReqs().size()); // assertEquals(1, cliListener.getReqs().size()); // // assertEquals(0, serverConn.getNumCloses()); // assertEquals(0, clientConn.getNumCloses()); // } // // @Test // public void testTwoReqs() { // svrListener.addReplies(HttpMessage.RESP(200).headers("X-Foo", "bar")); // svrListener.addReplies(HttpMessage.RESP(200).headers("X-Foo", "bar")); // exchange.submit(new HttpRequest(config, cliHandler, "http://localhost", HttpMethod.GET)); // exchange.submit(new HttpRequest(config, cliHandler, "http://localhost", HttpMethod.GET)); // assertEquals("server",2, svrListener.getReqs().size()); // assertEquals("client", 2, cliListener.getReqs().size()); // // } // TODO malformed request line - proper handling }
gpl-3.0
taz40/LWJGLPhysics
src/com/samuel/lwjgl/physics/PhysicsObject.java
1822
package com.samuel.lwjgl.physics; import static org.lwjgl.opengl.GL11.*; public class PhysicsObject { float x, y, width, height; int fps, ups; float forceTimer = 0f; float mass = 10; float vy=0; float vx=0; long lastUpdate; float timeModifier = 1; float ForceY = -9.8f*mass; float ForceX = 0; public PhysicsObject(float x, float y, float width, float height){ this.x = x; this.y = y; this.width = width; this.height = height; } public void render(){ glColor3f(1.0f,0f, 0f); glBegin(GL_QUADS); glVertex2f(x,y); glVertex2f(x+width, y); glVertex2f(x+width,y+height); glVertex2f(x,y+height); glEnd(); } public void addForce(float amount, float angle){ float angleRaid = (float) Math.toRadians(angle); ForceX += amount*-Math.cos(angleRaid); ForceY += amount*-Math.sin(angleRaid); } public void update(){ if(lastUpdate == 0){ lastUpdate = System.nanoTime(); }else{ float deltaTime = ((long)System.nanoTime() - (lastUpdate))/1000000000f; deltaTime *= timeModifier; ForceY -= 9.8f*mass; if(forceTimer <= 0.1f){ addForce(700, 270); } float a = ForceY/mass; float newY = ((a/2)*deltaTime*deltaTime)+(vy*deltaTime)+(y/100); float newV = (a*deltaTime)+vy; y = (newY*100); vy = newV; ForceY = 0; if(forceTimer >= 0.5f && forceTimer <= 0.7f){ addForce(500, 180); } a = ForceX/mass; float newX = ((a/2)*deltaTime*deltaTime)+(vx*deltaTime)+(x/100); newV = (a*deltaTime)+vx; x = (newX*100); vx = newV; ForceX = 0; if(y <= 0){ y = 0; vy = 0; } if(x >= 800-width){ x = 800-width; vx = 0; } lastUpdate = System.nanoTime(); forceTimer += deltaTime; } } }
gpl-3.0
csycurry/cloud.group
cloud.group.websys/src/main/java/com/csy/news/domain/dto/NewsPageDto.java
1195
package com.csy.news.domain.dto; import java.io.Serializable; public class NewsPageDto implements Serializable{ /** * */ private static final long serialVersionUID = 1L; // paginate related private String title; private Byte state; private Integer type; private int currentPage = 1; private int pageSize = 20; private String beginTm; private String endTm; public String getBeginTm() { return beginTm; } public void setBeginTm(String beginTm) { this.beginTm = beginTm; } public String getEndTm() { return endTm; } public void setEndTm(String endTm) { this.endTm = endTm; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Byte getState() { return state; } public void setState(Byte state) { this.state = state; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } }
gpl-3.0
TaghiAliyev/BBiCat
src/MetaFramework/MatrixFunctions.java
10612
/* * BBiCat is a toolbox that combines different Bi-Clustering and clustering techniques in it, which * can be applied on a given dataset. This software is the modified version of the original BiCat * Toolbox implemented at ETH Zurich by Simon Barkow, Eckart Zitzler, Stefan Bleuler, Amela * Prelic and Don Frick. * * DOI for citing the release : 10.5281/zenodo.33117 * * Copyright (c) 2015 Taghi Aliyev, Marco Manca, Alberto Di Meglio * * This file is part of BBiCat. * * BBiCat is a free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BBiCat is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BBiCat. If not, see <http://www.gnu.org/licenses/>. * * You can contact the author at the following email address: * taghi.aliyev@cern.ch * * PLEASE NOTE THAT ORIGINAL GROUP AT ETH ZURICH HAS BEEN DISSOLVED AND SO, * CONTACTING TAGHI ALIYEV MIGHT BE MORE BENEFITIAL FOR ANY QUESTIONS. * * IN NO EVENT SHALL THE AUTHORS AND MAINTAINERS OF THIS SOFTWARE BE LIABLE TO * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE * AUTHORS AND MAINTAINERS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * AUTHORS AND THE MAINTAINERS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" * BASIS, AND THE AUTHORS AND THE MAINTAINERS HAS NO OBLIGATION TO PROVIDE * MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS * * COPYRIGHT NOTICE FROM THE ORIGINAL SOFTWARE: * * Copyright notice : Copyright (c) 2005 Swiss Federal Institute of Technology, Computer * Engineering and Networks Laboratory. All rights reserved. * BicAT - A Biclustering Analysis Toolbox * IN NO EVENT SHALL THE SWISS FEDERAL INSTITUTE OF TECHNOLOGY, COMPUTER * ENGINEERING AND NETWORKS LABORATORY BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING * OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE * SWISS FEDERAL INSTITUTE OF TECHNOLOGY, COMPUTER ENGINEERING AND * NETWORKS LABORATORY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE SWISS FEDERAL INSTITUTE OF TECHNOLOGY, COMPUTER ENGINEERING AND * NETWORKS LABORATORY, SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE SWISS FEDERAL INSTITUTE OF TECHNOLOGY, * COMPUTER ENGINEERING AND NETWORKS LABORATORY HAS NO OBLIGATION * TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR * MODIFICATIONS. */ package MetaFramework; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; /** * Class containing the common Matrix Functions needed for this library * * @author Taghi Aliyev, email : taghi.aliyev@cern.ch */ public class MatrixFunctions { /** * Computes the intersection between two sets/lists * * @param geneNames * @param termGenes * @return */ public static Set<String> intersection(ArrayList<String> geneNames, ArrayList<String> termGenes) { Set<String> gene = new HashSet<String>(); Set<String> term = new HashSet<String>(); for (String tmp : geneNames) gene.add(tmp); for (String tmp : termGenes) term.add(tmp); Set<String> intersect = new TreeSet(gene); intersect.retainAll(term); return intersect; } public static Set<String> intersection(Set<String> geneNames, Set<String> termGenes) { Set<String> intersect = new TreeSet(geneNames); intersect.retainAll(termGenes); return intersect; } public static Set<String> intersection(Set<String> geneNames, ArrayList<String> termGenes) { Set<String> tmp = new HashSet<String>(termGenes); Set<String> intersect = new TreeSet(geneNames); intersect.retainAll(tmp); return intersect; } public static Set<String> intersection(ArrayList<String> list1, Set<String> list2) { return intersection(list2, list1); } /** * Computes the set difference between two lists/sets * * @param genesInPathway * @param genesInOther * @return */ // TODO : Test the set difference methods public static Set<String> setDifference(ArrayList<String> genesInPathway, Set<String> genesInOther) { Set<String> res = new HashSet<String>(genesInPathway); res.removeAll(genesInOther); // System.out.println(res.size()); return res; } /** * Computes the element-wise set difference * * @param genesInOther * @param genesInPathway * @return */ public static Set<String> setDifference(Set<String> genesInOther, ArrayList<String> genesInPathway) { Set<String> res = new HashSet<String>(genesInOther); res.removeAll(genesInPathway); // genesInOther.removeAll(genesInPathway); return res; } public static Set<String> setDifference(Set<String> gene1, Set<String> gene2) { Set<String> local = new HashSet<String>(gene1); local.removeAll(gene2); return local; } /** * Element-wise summation of two vectors * * @param a * @param b * @return */ public static int[] vectSum(int[] a, int[] b) { int[] tmp = new int[a.length]; for (int i = 0; i < a.length; i++) tmp[i] = a[i] + b[i]; return tmp; } public static double[] constantMinusVector(int n, ArrayList<Double> vec) { double[] res = new double[vec.size()]; for (int i = 0; i < res.length; i++) res[i] = n - vec.get(i); return res; } /** * Adding a constant to all the elements of a vector * * @param a * @param tmp * @return */ public static int[] matrixConstantSum(int[] a, int tmp) { int[] tmpVec = new int[a.length]; for (int i = 0; i < tmpVec.length; i++) { tmpVec[i] = a[i] + tmp; } return tmpVec; } /** * Adds a constant to a given double vector (element-wise) * * @param a * @param tmp * @return */ public static double[] matrixConstantSum(double[] a, double tmp) { double[] res = new double[a.length]; for (int i = 0; i < a.length; i++) { res[i] = a[i] + tmp; } return res; } /** * Element-wise multiplication of two vectors * * @param a * @param b * @return */ public static int[] vectorMult(int[] a, int[] b) { int[] result = new int[a.length]; for (int i = 0; i < a.length; i++) { result[i] = a[i] * b[i]; } return result; } public static double[] vectorConstantMult(double[] a, double b) { double[] result = new double[a.length]; for (int i = 0; i < a.length; i++) result[i] = a[i] * b; return result; } public static int[] vectorConstantMult(int[] a, int b) { int[] result = new int[a.length]; for (int i = 0; i < a.length; i++) result[i] = a[i] * b; return result; } public static double[] matrixSum(double[] a, double[] b) { double[] res = new double[a.length]; for (int i = 0; i < a.length; i++) res[i] = a[i] + b[i]; return res; } /** * Element-wise division of two vectors * * @param a * @param b * @return */ public static int[] vectorDiv(int[] a, int[] b) { int[] result = new int[a.length]; for (int i = 0; i < a.length; i++) { result[i] = a[i] / b[i]; } return result; } /** * Computes the exponent of each element of a given vector * * @param vec * @return */ public static Double[] expVect(double[] vec) { Double[] result = new Double[vec.length]; for (int i = 0; i < vec.length; i++) result[i] = Math.exp(vec[i]); return result; } }
gpl-3.0
inserpio/neo4j-etl-components
neo4j-etl-cli/src/main/java/org/neo4j/etl/cli/rdbms/ImportFromRdbmsEvents.java
681
package org.neo4j.etl.cli.rdbms; import java.nio.file.Path; public interface ImportFromRdbmsEvents { ImportFromRdbmsEvents EMPTY = new ImportFromRdbmsEvents() { @Override public void onExportingToCsv( Path csvDirectory ) { // Do nothing } @Override public void onCreatingNeo4jStore() { // Do nothing } @Override public void onExportComplete( Path destinationDirectory ) { // Do nothing } }; void onExportingToCsv( Path csvDirectory ); void onCreatingNeo4jStore(); void onExportComplete( Path destinationDirectory ); }
gpl-3.0
HackeaMesta/Android-Google-Endpoint
app/src/androidTest/java/com/appspot/data_base_1298/database/ApplicationTest.java
366
package com.appspot.data_base_1298.database; 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); } }
gpl-3.0
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/spring-core/src/test/java/com/baeldung/beanfactory/BeanFactoryWithClassPathResourceIntegrationTest.java
947
package com.baeldung.beanfactory; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class BeanFactoryWithClassPathResourceIntegrationTest { @Test public void createBeanFactoryAndCheckEmployeeBean() { Resource res = new ClassPathResource("beanfactory-example.xml"); BeanFactory factory = new XmlBeanFactory(res); Employee emp = (Employee) factory.getBean("employee"); assertTrue(factory.isSingleton("employee")); assertTrue(factory.getBean("employee") instanceof Employee); assertTrue(factory.isTypeMatch("employee", Employee.class)); assertTrue(factory.getAliases("employee").length > 0); } }
gpl-3.0
iksoiks/concerto-framework-core
src/com/n_micocci/concerto/filters/FilterVelocity.java
1590
/* * Copyright (c) 2016 Christian Micocci. This file is part of Concerto. * * Concerto is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Concerto is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Concerto. If not, see <http://www.gnu.org/licenses/>. */ package com.n_micocci.concerto.filters; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MidiMessage; import javax.sound.midi.ShortMessage; public class FilterVelocity extends AbstractMidiFilter { private int velocity; public FilterVelocity(int velocity) { this.velocity = velocity; } @Override public void send(MidiMessage midiMessage, long l) { int status = midiMessage.getStatus(); if (status / 16 == 0x8 || status / 16 == 0x9) { byte[] message = midiMessage.getMessage(); int note = message[1]; try { midiMessage = new ShortMessage(status, note, message[2] != 0 ? velocity : 0); } catch (InvalidMidiDataException e) { e.printStackTrace(); } } getReceiver().send(midiMessage, l); } }
gpl-3.0
eriuzo/Conversations
src/main/java/eu/siacs/conversations/ui/EditAccountActivity.java
23901
package eu.siacs.conversations.ui; import android.app.AlertDialog.Builder; import android.app.PendingIntent; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; import org.whispersystems.libaxolotl.IdentityKey; import java.util.Set; import eu.siacs.conversations.Config; import eu.siacs.conversations.R; import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate; import eu.siacs.conversations.ui.adapter.KnownHostsAdapter; import eu.siacs.conversations.utils.CryptoHelper; import eu.siacs.conversations.utils.UIHelper; import eu.siacs.conversations.xmpp.OnKeyStatusUpdated; import eu.siacs.conversations.xmpp.XmppConnection.Features; import eu.siacs.conversations.xmpp.jid.InvalidJidException; import eu.siacs.conversations.xmpp.jid.Jid; import eu.siacs.conversations.xmpp.pep.Avatar; public class EditAccountActivity extends XmppActivity implements OnAccountUpdate, OnKeyStatusUpdated { private AutoCompleteTextView mAccountJid; private EditText mPassword; private EditText mPasswordConfirm; private CheckBox mRegisterNew; private Button mCancelButton; private Button mSaveButton; private TableLayout mMoreTable; private LinearLayout mStats; private TextView mServerInfoSm; private TextView mServerInfoRosterVersion; private TextView mServerInfoCarbons; private TextView mServerInfoMam; private TextView mServerInfoCSI; private TextView mServerInfoBlocking; private TextView mServerInfoPep; private TextView mSessionEst; private TextView mOtrFingerprint; private TextView mAxolotlFingerprint; private TextView mAccountJidLabel; private ImageView mAvatar; private RelativeLayout mOtrFingerprintBox; private RelativeLayout mAxolotlFingerprintBox; private ImageButton mOtrFingerprintToClipboardButton; private ImageButton mAxolotlFingerprintToClipboardButton; private ImageButton mRegenerateAxolotlKeyButton; private LinearLayout keys; private LinearLayout keysCard; private Jid jidToEdit; private Account mAccount; private String messageFingerprint; private boolean mFetchingAvatar = false; private final OnClickListener mSaveButtonClickListener = new OnClickListener() { @Override public void onClick(final View v) { if (mAccount != null && mAccount.getStatus() == Account.State.DISABLED && !accountInfoEdited()) { mAccount.setOption(Account.OPTION_DISABLED, false); xmppConnectionService.updateAccount(mAccount); return; } final boolean registerNewAccount = mRegisterNew.isChecked() && !Config.DISALLOW_REGISTRATION_IN_UI; if (Config.DOMAIN_LOCK != null && mAccountJid.getText().toString().contains("@")) { mAccountJid.setError(getString(R.string.invalid_username)); mAccountJid.requestFocus(); return; } final Jid jid; try { if (Config.DOMAIN_LOCK != null) { jid = Jid.fromParts(mAccountJid.getText().toString(),Config.DOMAIN_LOCK,null); } else { jid = Jid.fromString(mAccountJid.getText().toString()); } } catch (final InvalidJidException e) { if (Config.DOMAIN_LOCK != null) { mAccountJid.setError(getString(R.string.invalid_username)); } else { mAccountJid.setError(getString(R.string.invalid_jid)); } mAccountJid.requestFocus(); return; } if (jid.isDomainJid()) { if (Config.DOMAIN_LOCK != null) { mAccountJid.setError(getString(R.string.invalid_username)); } else { mAccountJid.setError(getString(R.string.invalid_jid)); } mAccountJid.requestFocus(); return; } final String password = mPassword.getText().toString(); final String passwordConfirm = mPasswordConfirm.getText().toString(); if (registerNewAccount) { if (!password.equals(passwordConfirm)) { mPasswordConfirm.setError(getString(R.string.passwords_do_not_match)); mPasswordConfirm.requestFocus(); return; } } if (mAccount != null) { try { mAccount.setUsername(jid.hasLocalpart() ? jid.getLocalpart() : ""); mAccount.setServer(jid.getDomainpart()); } catch (final InvalidJidException ignored) { return; } mAccountJid.setError(null); mPasswordConfirm.setError(null); mAccount.setPassword(password); mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount); xmppConnectionService.updateAccount(mAccount); } else { if (xmppConnectionService.findAccountByJid(jid) != null) { mAccountJid.setError(getString(R.string.account_already_exists)); mAccountJid.requestFocus(); return; } mAccount = new Account(jid.toBareJid(), password); mAccount.setOption(Account.OPTION_USETLS, true); mAccount.setOption(Account.OPTION_USECOMPRESSION, true); mAccount.setOption(Account.OPTION_REGISTER, registerNewAccount); xmppConnectionService.createAccount(mAccount); } if (jidToEdit != null && !mAccount.isOptionSet(Account.OPTION_DISABLED)) { finish(); } else { updateSaveButton(); updateAccountInformation(true); } } }; private final OnClickListener mCancelButtonClickListener = new OnClickListener() { @Override public void onClick(final View v) { finish(); } }; public void refreshUiReal() { invalidateOptionsMenu(); if (mAccount != null && mAccount.getStatus() != Account.State.ONLINE && mFetchingAvatar) { startActivity(new Intent(getApplicationContext(), ManageAccountActivity.class)); finish(); } else if (jidToEdit == null && mAccount != null && mAccount.getStatus() == Account.State.ONLINE) { if (!mFetchingAvatar) { mFetchingAvatar = true; xmppConnectionService.checkForAvatar(mAccount, mAvatarFetchCallback); } } else { updateSaveButton(); } if (mAccount != null) { updateAccountInformation(false); } } @Override public void onAccountUpdate() { refreshUi(); } private final UiCallback<Avatar> mAvatarFetchCallback = new UiCallback<Avatar>() { @Override public void userInputRequried(final PendingIntent pi, final Avatar avatar) { finishInitialSetup(avatar); } @Override public void success(final Avatar avatar) { finishInitialSetup(avatar); } @Override public void error(final int errorCode, final Avatar avatar) { finishInitialSetup(avatar); } }; private final TextWatcher mTextWatcher = new TextWatcher() { @Override public void onTextChanged(final CharSequence s, final int start, final int before, final int count) { updateSaveButton(); } @Override public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) { } @Override public void afterTextChanged(final Editable s) { } }; private final OnClickListener mAvatarClickListener = new OnClickListener() { @Override public void onClick(final View view) { if (mAccount != null) { final Intent intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class); intent.putExtra("account", mAccount.getJid().toBareJid().toString()); startActivity(intent); } } }; protected void finishInitialSetup(final Avatar avatar) { runOnUiThread(new Runnable() { @Override public void run() { final Intent intent; if (avatar != null) { intent = new Intent(getApplicationContext(), StartConversationActivity.class); if (xmppConnectionService != null && xmppConnectionService.getAccounts().size() == 1) { intent.putExtra("init", true); } } else { intent = new Intent(getApplicationContext(), PublishProfilePictureActivity.class); intent.putExtra("account", mAccount.getJid().toBareJid().toString()); intent.putExtra("setup", true); } startActivity(intent); finish(); } }); } protected void updateSaveButton() { if (accountInfoEdited() && jidToEdit != null) { this.mSaveButton.setText(R.string.save); this.mSaveButton.setEnabled(true); this.mSaveButton.setTextColor(getPrimaryTextColor()); } else if (mAccount != null && (mAccount.getStatus() == Account.State.CONNECTING || mFetchingAvatar)) { this.mSaveButton.setEnabled(false); this.mSaveButton.setTextColor(getSecondaryTextColor()); this.mSaveButton.setText(R.string.account_status_connecting); } else if (mAccount != null && mAccount.getStatus() == Account.State.DISABLED) { this.mSaveButton.setEnabled(true); this.mSaveButton.setTextColor(getPrimaryTextColor()); this.mSaveButton.setText(R.string.enable); } else { this.mSaveButton.setEnabled(true); this.mSaveButton.setTextColor(getPrimaryTextColor()); if (jidToEdit != null) { if (mAccount != null && mAccount.isOnlineAndConnected()) { this.mSaveButton.setText(R.string.save); if (!accountInfoEdited()) { this.mSaveButton.setEnabled(false); this.mSaveButton.setTextColor(getSecondaryTextColor()); } } else { this.mSaveButton.setText(R.string.connect); } } else { this.mSaveButton.setText(R.string.next); } } } protected boolean accountInfoEdited() { if (this.mAccount == null) { return false; } final String unmodified; if (Config.DOMAIN_LOCK != null) { unmodified = this.mAccount.getJid().getLocalpart(); } else { unmodified = this.mAccount.getJid().toBareJid().toString(); } return !unmodified.equals(this.mAccountJid.getText().toString()) || !this.mAccount.getPassword().equals(this.mPassword.getText().toString()); } @Override protected String getShareableUri() { if (mAccount!=null) { return mAccount.getShareableUri(); } else { return ""; } } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_account); this.mAccountJid = (AutoCompleteTextView) findViewById(R.id.account_jid); this.mAccountJid.addTextChangedListener(this.mTextWatcher); this.mAccountJidLabel = (TextView) findViewById(R.id.account_jid_label); if (Config.DOMAIN_LOCK != null) { this.mAccountJidLabel.setText(R.string.username); this.mAccountJid.setHint(R.string.username_hint); } this.mPassword = (EditText) findViewById(R.id.account_password); this.mPassword.addTextChangedListener(this.mTextWatcher); this.mPasswordConfirm = (EditText) findViewById(R.id.account_password_confirm); this.mAvatar = (ImageView) findViewById(R.id.avater); this.mAvatar.setOnClickListener(this.mAvatarClickListener); this.mRegisterNew = (CheckBox) findViewById(R.id.account_register_new); this.mStats = (LinearLayout) findViewById(R.id.stats); this.mSessionEst = (TextView) findViewById(R.id.session_est); this.mServerInfoRosterVersion = (TextView) findViewById(R.id.server_info_roster_version); this.mServerInfoCarbons = (TextView) findViewById(R.id.server_info_carbons); this.mServerInfoMam = (TextView) findViewById(R.id.server_info_mam); this.mServerInfoCSI = (TextView) findViewById(R.id.server_info_csi); this.mServerInfoBlocking = (TextView) findViewById(R.id.server_info_blocking); this.mServerInfoSm = (TextView) findViewById(R.id.server_info_sm); this.mServerInfoPep = (TextView) findViewById(R.id.server_info_pep); this.mOtrFingerprint = (TextView) findViewById(R.id.otr_fingerprint); this.mOtrFingerprintBox = (RelativeLayout) findViewById(R.id.otr_fingerprint_box); this.mOtrFingerprintToClipboardButton = (ImageButton) findViewById(R.id.action_copy_to_clipboard); this.mAxolotlFingerprint = (TextView) findViewById(R.id.axolotl_fingerprint); this.mAxolotlFingerprintBox = (RelativeLayout) findViewById(R.id.axolotl_fingerprint_box); this.mAxolotlFingerprintToClipboardButton = (ImageButton) findViewById(R.id.action_copy_axolotl_to_clipboard); this.mRegenerateAxolotlKeyButton = (ImageButton) findViewById(R.id.action_regenerate_axolotl_key); this.keysCard = (LinearLayout) findViewById(R.id.other_device_keys_card); this.keys = (LinearLayout) findViewById(R.id.other_device_keys); this.mSaveButton = (Button) findViewById(R.id.save_button); this.mCancelButton = (Button) findViewById(R.id.cancel_button); this.mSaveButton.setOnClickListener(this.mSaveButtonClickListener); this.mCancelButton.setOnClickListener(this.mCancelButtonClickListener); this.mMoreTable = (TableLayout) findViewById(R.id.server_info_more); final OnCheckedChangeListener OnCheckedShowConfirmPassword = new OnCheckedChangeListener() { @Override public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) { if (isChecked) { mPasswordConfirm.setVisibility(View.VISIBLE); } else { mPasswordConfirm.setVisibility(View.GONE); } updateSaveButton(); } }; this.mRegisterNew.setOnCheckedChangeListener(OnCheckedShowConfirmPassword); if (Config.DISALLOW_REGISTRATION_IN_UI) { this.mRegisterNew.setVisibility(View.GONE); } } @Override public boolean onCreateOptionsMenu(final Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.editaccount, menu); final MenuItem showQrCode = menu.findItem(R.id.action_show_qr_code); final MenuItem showBlocklist = menu.findItem(R.id.action_show_block_list); final MenuItem showMoreInfo = menu.findItem(R.id.action_server_info_show_more); final MenuItem changePassword = menu.findItem(R.id.action_change_password_on_server); final MenuItem clearDevices = menu.findItem(R.id.action_clear_devices); if (mAccount != null && mAccount.isOnlineAndConnected()) { if (!mAccount.getXmppConnection().getFeatures().blocking()) { showBlocklist.setVisible(false); } if (!mAccount.getXmppConnection().getFeatures().register()) { changePassword.setVisible(false); } Set<Integer> otherDevices = mAccount.getAxolotlService().getOwnDeviceIds(); if (otherDevices == null || otherDevices.isEmpty()) { clearDevices.setVisible(false); } } else { showQrCode.setVisible(false); showBlocklist.setVisible(false); showMoreInfo.setVisible(false); changePassword.setVisible(false); clearDevices.setVisible(false); } return true; } @Override protected void onStart() { super.onStart(); if (getIntent() != null) { try { this.jidToEdit = Jid.fromString(getIntent().getStringExtra("jid")); } catch (final InvalidJidException | NullPointerException ignored) { this.jidToEdit = null; } this.messageFingerprint = getIntent().getStringExtra("fingerprint"); if (this.jidToEdit != null) { this.mRegisterNew.setVisibility(View.GONE); if (getActionBar() != null) { getActionBar().setTitle(getString(R.string.account_details)); } } else { this.mAvatar.setVisibility(View.GONE); if (getActionBar() != null) { getActionBar().setTitle(R.string.action_add_account); } } } } @Override protected void onBackendConnected() { if (this.jidToEdit != null) { this.mAccount = xmppConnectionService.findAccountByJid(jidToEdit); updateAccountInformation(true); } else if (this.xmppConnectionService.getAccounts().size() == 0) { if (getActionBar() != null) { getActionBar().setDisplayHomeAsUpEnabled(false); getActionBar().setDisplayShowHomeEnabled(false); getActionBar().setHomeButtonEnabled(false); } this.mCancelButton.setEnabled(false); this.mCancelButton.setTextColor(getSecondaryTextColor()); } if (Config.DOMAIN_LOCK == null) { final KnownHostsAdapter mKnownHostsAdapter = new KnownHostsAdapter(this, android.R.layout.simple_list_item_1, xmppConnectionService.getKnownHosts()); this.mAccountJid.setAdapter(mKnownHostsAdapter); } updateSaveButton(); } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.action_show_block_list: final Intent showBlocklistIntent = new Intent(this, BlocklistActivity.class); showBlocklistIntent.putExtra("account", mAccount.getJid().toString()); startActivity(showBlocklistIntent); break; case R.id.action_server_info_show_more: mMoreTable.setVisibility(item.isChecked() ? View.GONE : View.VISIBLE); item.setChecked(!item.isChecked()); break; case R.id.action_change_password_on_server: final Intent changePasswordIntent = new Intent(this, ChangePasswordActivity.class); changePasswordIntent.putExtra("account", mAccount.getJid().toString()); startActivity(changePasswordIntent); break; case R.id.action_clear_devices: showWipePepDialog(); break; } return super.onOptionsItemSelected(item); } private void updateAccountInformation(boolean init) { if (init) { if (Config.DOMAIN_LOCK != null) { this.mAccountJid.setText(this.mAccount.getJid().getLocalpart()); } else { this.mAccountJid.setText(this.mAccount.getJid().toBareJid().toString()); } this.mPassword.setText(this.mAccount.getPassword()); } if (this.jidToEdit != null) { this.mAvatar.setVisibility(View.VISIBLE); this.mAvatar.setImageBitmap(avatarService().get(this.mAccount, getPixel(72))); } if (this.mAccount.isOptionSet(Account.OPTION_REGISTER)) { this.mRegisterNew.setVisibility(View.VISIBLE); this.mRegisterNew.setChecked(true); this.mPasswordConfirm.setText(this.mAccount.getPassword()); } else { this.mRegisterNew.setVisibility(View.GONE); this.mRegisterNew.setChecked(false); } if (this.mAccount.isOnlineAndConnected() && !this.mFetchingAvatar) { this.mStats.setVisibility(View.VISIBLE); this.mSessionEst.setText(UIHelper.readableTimeDifferenceFull(this, this.mAccount.getXmppConnection() .getLastSessionEstablished())); Features features = this.mAccount.getXmppConnection().getFeatures(); if (features.rosterVersioning()) { this.mServerInfoRosterVersion.setText(R.string.server_info_available); } else { this.mServerInfoRosterVersion.setText(R.string.server_info_unavailable); } if (features.carbons()) { this.mServerInfoCarbons.setText(R.string.server_info_available); } else { this.mServerInfoCarbons .setText(R.string.server_info_unavailable); } if (features.mam()) { this.mServerInfoMam.setText(R.string.server_info_available); } else { this.mServerInfoMam.setText(R.string.server_info_unavailable); } if (features.csi()) { this.mServerInfoCSI.setText(R.string.server_info_available); } else { this.mServerInfoCSI.setText(R.string.server_info_unavailable); } if (features.blocking()) { this.mServerInfoBlocking.setText(R.string.server_info_available); } else { this.mServerInfoBlocking.setText(R.string.server_info_unavailable); } if (features.sm()) { this.mServerInfoSm.setText(R.string.server_info_available); } else { this.mServerInfoSm.setText(R.string.server_info_unavailable); } if (features.pep()) { this.mServerInfoPep.setText(R.string.server_info_available); } else { this.mServerInfoPep.setText(R.string.server_info_unavailable); } final String otrFingerprint = this.mAccount.getOtrFingerprint(); if (otrFingerprint != null) { this.mOtrFingerprintBox.setVisibility(View.VISIBLE); this.mOtrFingerprint.setText(CryptoHelper.prettifyFingerprint(otrFingerprint)); this.mOtrFingerprintToClipboardButton .setVisibility(View.VISIBLE); this.mOtrFingerprintToClipboardButton .setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { if (copyTextToClipboard(otrFingerprint, R.string.otr_fingerprint)) { Toast.makeText( EditAccountActivity.this, R.string.toast_message_otr_fingerprint, Toast.LENGTH_SHORT).show(); } } }); } else { this.mOtrFingerprintBox.setVisibility(View.GONE); } final String axolotlFingerprint = this.mAccount.getAxolotlService().getOwnPublicKey().getFingerprint(); if (axolotlFingerprint != null) { this.mAxolotlFingerprintBox.setVisibility(View.VISIBLE); this.mAxolotlFingerprint.setText(CryptoHelper.prettifyFingerprint(axolotlFingerprint)); this.mAxolotlFingerprintToClipboardButton .setVisibility(View.VISIBLE); this.mAxolotlFingerprintToClipboardButton .setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { if (copyTextToClipboard(axolotlFingerprint, R.string.omemo_fingerprint)) { Toast.makeText( EditAccountActivity.this, R.string.toast_message_omemo_fingerprint, Toast.LENGTH_SHORT).show(); } } }); if (Config.SHOW_REGENERATE_AXOLOTL_KEYS_BUTTON) { this.mRegenerateAxolotlKeyButton .setVisibility(View.VISIBLE); this.mRegenerateAxolotlKeyButton .setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { showRegenerateAxolotlKeyDialog(); } }); } } else { this.mAxolotlFingerprintBox.setVisibility(View.GONE); } final IdentityKey ownKey = mAccount.getAxolotlService().getOwnPublicKey(); boolean hasKeys = false; keys.removeAllViews(); for(final IdentityKey identityKey : xmppConnectionService.databaseBackend.loadIdentityKeys( mAccount, mAccount.getJid().toBareJid().toString())) { if(ownKey.equals(identityKey)) { continue; } boolean highlight = identityKey.getFingerprint().replaceAll("\\s", "").equals(messageFingerprint); hasKeys |= addFingerprintRow(keys, mAccount, identityKey, highlight); } if (hasKeys) { keysCard.setVisibility(View.VISIBLE); } else { keysCard.setVisibility(View.GONE); } } else { if (this.mAccount.errorStatus()) { this.mAccountJid.setError(getString(this.mAccount.getStatus().getReadableId())); if (init || !accountInfoEdited()) { this.mAccountJid.requestFocus(); } } else { this.mAccountJid.setError(null); } this.mStats.setVisibility(View.GONE); } } public void showRegenerateAxolotlKeyDialog() { Builder builder = new Builder(this); builder.setTitle("Regenerate Key"); builder.setIconAttribute(android.R.attr.alertDialogIcon); builder.setMessage("Are you sure you want to regenerate your Identity Key? (This will also wipe all established sessions and contact Identity Keys)"); builder.setNegativeButton(getString(R.string.cancel), null); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mAccount.getAxolotlService().regenerateKeys(); } }); builder.create().show(); } public void showWipePepDialog() { Builder builder = new Builder(this); builder.setTitle(getString(R.string.clear_other_devices)); builder.setIconAttribute(android.R.attr.alertDialogIcon); builder.setMessage(getString(R.string.clear_other_devices_desc)); builder.setNegativeButton(getString(R.string.cancel), null); builder.setPositiveButton(getString(R.string.accept), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mAccount.getAxolotlService().wipeOtherPepDevices(); } }); builder.create().show(); } @Override public void onKeyStatusUpdated() { refreshUi(); } }
gpl-3.0
xperimental/svn-notify
src/net/sourcewalker/svnnotify/data/xmldb/XmlRevision.java
1667
package net.sourcewalker.svnnotify.data.xmldb; import java.util.Date; import net.sourcewalker.svnnotify.data.interfaces.IRevision; /** * Revision class to be used with the flat-file XML database implementation in * {@link XmlDatabase}. * * @author Xperimental */ public class XmlRevision implements IRevision { /** * Contains the revision number. */ private int revision; /** * Contains the revision author. */ private String author; /** * Contains the commit message of the revision. */ private String message; /** * Contains the creation time of the revision. */ private Date timestamp; /** * Create a new instance of the class with the attributes initialized to the * specified values. * * @param revNumber * Revision number. * @param revAuthor * Revision author. * @param revTime * Creation time of revision. * @param revMessage * Commit message of revision. */ public XmlRevision(final int revNumber, final String revAuthor, final Date revTime, final String revMessage) { this.revision = revNumber; this.author = revAuthor; this.timestamp = revTime; this.message = revMessage; } @Override public final int getRevision() { return revision; } @Override public final String getAuthor() { return author; } @Override public final String getMessage() { return message; } @Override public final Date getTimestamp() { return timestamp; } }
gpl-3.0
dhydrated/kan-banana-server
src/main/java/org/dhydrated/kanbanana/server/controller/BaseService.java
1217
package org.dhydrated.kanbanana.server.controller; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.dhydrated.kanbanana.server.repository.BaseRepository; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; public abstract class BaseService<E> { private Logger log = Logger.getLogger(BaseService.class.getName()); public List<E> list(String parentId) { log.log(Level.INFO, "get"); return getRepository().list(parentId); } public E get(@PathVariable("id") String id) throws Exception{ log.log(Level.INFO, "get"); return getRepository().get(id); } public E save(@RequestBody E entity) { log.log(Level.INFO, "save"); log.log(Level.INFO, "Entity: " + entity); getRepository().save(entity); return entity; } public Boolean delete(@PathVariable("id") String id) throws Exception{ log.log(Level.INFO, "delete"); try { getRepository().delete(id); } catch (Exception e) { return false; } return true; } public abstract BaseRepository<E> getRepository(); public abstract void setRepository(BaseRepository<E> repository); }
gpl-3.0
CaptainBern/MinecraftNetLib
src/main/java/com/captainbern/minecraft/game/nbt/NbtTagIntArray.java
976
package com.captainbern.minecraft.game.nbt; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; public class NbtTagIntArray extends NbtTag<int[]> { public NbtTagIntArray() { this(new int[0]); } public NbtTagIntArray(int[] value) { super(value); } @Override public NbtTagType getType() { return NbtTagType.TAG_INT_ARRAY; } @Override public void write(DataOutput dataOutput) throws IOException { dataOutput.writeInt(this.value.length); for (int i : this.value) { dataOutput.writeInt(i); } } @Override public void load(DataInput dataInput, int depth, NbtReadLimiter readLimiter) throws IOException { int length = dataInput.readInt(); readLimiter.allocate(32l * length); this.value = new int[length]; for (int i = 0; i < length; i++) { this.value[i] = dataInput.readInt(); } } }
gpl-3.0
avdata99/SIAT
siat-1.0-SOURCE/src/view/src/WEB-INF/src/ar/gov/rosario/siat/emi/view/struts/AdministrarResLiqDeuDAction.java
14979
//Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda. //This file is part of SIAT. SIAT is licensed under the terms //of the GNU General Public License, version 3. //See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt> package ar.gov.rosario.siat.emi.view.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import ar.gov.rosario.siat.base.iface.util.BaseError; import ar.gov.rosario.siat.base.iface.util.BaseSecurityConstants; import ar.gov.rosario.siat.base.view.struts.BaseDispatchAction; import ar.gov.rosario.siat.base.view.util.BaseConstants; import ar.gov.rosario.siat.base.view.util.UserSession; import ar.gov.rosario.siat.emi.iface.model.ResLiqDeuAdapter; import ar.gov.rosario.siat.emi.iface.model.ResLiqDeuVO; import ar.gov.rosario.siat.emi.iface.service.EmiServiceLocator; import ar.gov.rosario.siat.emi.iface.util.EmiError; import ar.gov.rosario.siat.emi.iface.util.EmiSecurityConstants; import ar.gov.rosario.siat.emi.view.util.EmiConstants; import coop.tecso.demoda.iface.helper.DemodaUtil; import coop.tecso.demoda.iface.model.CommonKey; import coop.tecso.demoda.iface.model.NavModel; public final class AdministrarResLiqDeuDAction extends BaseDispatchAction { private Log log = LogFactory.getLog(AdministrarResLiqDeuDAction.class); public ActionForward inicializar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String funcName = DemodaUtil.currentMethodName(); String act = getCurrentAct(request); if (log.isDebugEnabled()) log.debug("entrando en " + funcName); UserSession userSession = canAccess(request, mapping, EmiSecurityConstants.ABM_RESLIQDEU, act); if (userSession == null) return forwardErrorSession(request); NavModel navModel = userSession.getNavModel(); ResLiqDeuAdapter resLiqDeuAdapterVO = null; String stringServicio = ""; ActionForward actionForward = null; try { CommonKey commonKey = new CommonKey(navModel.getSelectedId()); if (act.equals(BaseConstants.ACT_VER)) { stringServicio = "getResLiqDeuAdapterForView(userSession, commonKey)"; resLiqDeuAdapterVO = EmiServiceLocator.getGeneralService().getResLiqDeuAdapterForView(userSession, commonKey); actionForward = mapping.findForward(EmiConstants.FWD_RESLIQDEU_VIEW_ADAPTER); } if (act.equals(BaseConstants.ACT_MODIFICAR)) { stringServicio = "getResLiqDeuAdapterForUpdate(userSession, commonKey)"; resLiqDeuAdapterVO = EmiServiceLocator.getGeneralService().getResLiqDeuAdapterForUpdate(userSession, commonKey); actionForward = mapping.findForward(EmiConstants.FWD_RESLIQDEU_EDIT_ADAPTER); } if (act.equals(BaseConstants.ACT_ELIMINAR)) { stringServicio = "getResLiqDeuAdapterForView(userSession, commonKey)"; resLiqDeuAdapterVO = EmiServiceLocator.getGeneralService().getResLiqDeuAdapterForView(userSession, commonKey); resLiqDeuAdapterVO.addMessage(BaseError.MSG_ELIMINAR, EmiError.RESLIQDEU_LABEL); actionForward = mapping.findForward(EmiConstants.FWD_RESLIQDEU_VIEW_ADAPTER); } if (act.equals(BaseConstants.ACT_AGREGAR)) { stringServicio = "getResLiqDeuAdapterForCreate(userSession)"; resLiqDeuAdapterVO = EmiServiceLocator.getGeneralService().getResLiqDeuAdapterForCreate(userSession); actionForward = mapping.findForward(EmiConstants.FWD_RESLIQDEU_EDIT_ADAPTER); } if (log.isDebugEnabled()) log.debug(funcName + " salimos de servicio: " + stringServicio + " para " + act ); // Nunca Tiene errores recuperables // Tiene errores no recuperables if (resLiqDeuAdapterVO.hasErrorNonRecoverable()) { log.error("error en: " + funcName + ": servicio: " + stringServicio + ": " + resLiqDeuAdapterVO.errorString()); return forwardErrorNonRecoverable(mapping, request, funcName, ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); } // Seteo los valores de navegacion en el adapter resLiqDeuAdapterVO.setValuesFromNavModel(navModel); if (log.isDebugEnabled()) log.debug(funcName + ": " + ResLiqDeuAdapter.NAME + ": "+ resLiqDeuAdapterVO.infoString()); // Envio el VO al request request.setAttribute(ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); // Subo el apdater al userSession userSession.put(ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); saveDemodaMessages(request, resLiqDeuAdapterVO); return actionForward; } catch (Exception exception) { return baseException(mapping, request, funcName, exception, ResLiqDeuAdapter.NAME); } } public ActionForward agregar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String funcName = DemodaUtil.currentMethodName(); if (log.isDebugEnabled()) log.debug("entrando en " + funcName); UserSession userSession = canAccess(request, mapping, EmiSecurityConstants.ABM_RESLIQDEU, BaseSecurityConstants.AGREGAR); if (userSession==null) return forwardErrorSession(request); try { // Bajo el adapter del userSession ResLiqDeuAdapter resLiqDeuAdapterVO = (ResLiqDeuAdapter) userSession.get(ResLiqDeuAdapter.NAME); // Si es nulo no se puede continuar if (resLiqDeuAdapterVO == null) { log.error("error en: " + funcName + ": " + ResLiqDeuAdapter.NAME + " IS NULL. No se pudo obtener de la sesion"); return forwardErrorSessionNullObject(mapping, request, funcName, ResLiqDeuAdapter.NAME); } // Recuperamos datos del form en el vo DemodaUtil.populateVO(resLiqDeuAdapterVO, request); // Tiene errores recuperables if (resLiqDeuAdapterVO.hasErrorRecoverable()) { log.error("recoverable error en: " + funcName + ": " + resLiqDeuAdapterVO.infoString()); saveDemodaErrors(request, resLiqDeuAdapterVO); return forwardErrorRecoverable(mapping, request, userSession, ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); } // llamada al servicio ResLiqDeuVO resLiqDeuVO = EmiServiceLocator.getGeneralService().createResLiqDeu(userSession, resLiqDeuAdapterVO.getResLiqDeu()); // Tiene errores recuperables if (resLiqDeuVO.hasErrorRecoverable()) { log.error("recoverable error en: " + funcName + ": " + resLiqDeuVO.infoString()); saveDemodaErrors(request, resLiqDeuVO); return forwardErrorRecoverable(mapping, request, userSession, ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); } // Tiene errores no recuperables if (resLiqDeuVO.hasErrorNonRecoverable()) { log.error("error en: " + funcName + ": " + resLiqDeuVO.errorString()); return forwardErrorNonRecoverable(mapping, request, funcName, ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); } // Si tiene permiso lo dirijo al adapter de modificacion, // sino vuelve al searchPage if (hasAccess(userSession, EmiSecurityConstants.ABM_RESLIQDEU, BaseSecurityConstants.MODIFICAR)) { // seteo el id para que lo use el siguiente action userSession.getNavModel().setSelectedId(resLiqDeuVO.getId().toString()); // lo dirijo al adapter de administrar proceso return forwardConfirmarOk(mapping, request, funcName, ResLiqDeuAdapter.NAME, EmiConstants.PATH_ADMINISTRAR_PROCESO_RESLIQDEU, BaseConstants.METHOD_INICIALIZAR, EmiSecurityConstants.ACT_ADMINISTRAR_PROCESO); } // Fue Exitoso, forwardeo al Search Page return forwardConfirmarOk(mapping, request, funcName, ResLiqDeuAdapter.NAME); } catch (Exception exception) { return baseException(mapping, request, funcName, exception, ResLiqDeuAdapter.NAME); } } public ActionForward modificar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String funcName = DemodaUtil.currentMethodName(); if (log.isDebugEnabled()) log.debug("entrando en " + funcName); UserSession userSession = canAccess(request, mapping, EmiSecurityConstants.ABM_RESLIQDEU, BaseSecurityConstants.MODIFICAR); if (userSession==null) return forwardErrorSession(request); try { // Bajo el adapter del userSession ResLiqDeuAdapter resLiqDeuAdapterVO = (ResLiqDeuAdapter) userSession.get(ResLiqDeuAdapter.NAME); // Si es nulo no se puede continuar if (resLiqDeuAdapterVO == null) { log.error("error en: " + funcName + ": " + ResLiqDeuAdapter.NAME + " IS NULL. No se pudo obtener de la sesion"); return forwardErrorSessionNullObject(mapping, request, funcName, ResLiqDeuAdapter.NAME); } // Recuperamos datos del form en el vo DemodaUtil.populateVO(resLiqDeuAdapterVO, request); // Tiene errores recuperables if (resLiqDeuAdapterVO.hasErrorRecoverable()) { log.error("recoverable error en: " + funcName + ": " + resLiqDeuAdapterVO.infoString()); saveDemodaErrors(request, resLiqDeuAdapterVO); return forwardErrorRecoverable(mapping, request, userSession, ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); } // llamada al servicio ResLiqDeuVO resLiqDeuVO = EmiServiceLocator.getGeneralService().updateResLiqDeu(userSession, resLiqDeuAdapterVO.getResLiqDeu()); // Tiene errores recuperables if (resLiqDeuVO.hasErrorRecoverable()) { log.error("recoverable error en: " + funcName + ": " + resLiqDeuAdapterVO.infoString()); saveDemodaErrors(request, resLiqDeuVO); return forwardErrorRecoverable(mapping, request, userSession, ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); } // Tiene errores no recuperables if (resLiqDeuVO.hasErrorNonRecoverable()) { log.error("error en: " + funcName + ": " + resLiqDeuAdapterVO.errorString()); return forwardErrorNonRecoverable(mapping, request, funcName, ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); } // Fue Exitoso return forwardConfirmarOk(mapping, request, funcName, ResLiqDeuAdapter.NAME); } catch (Exception exception) { return baseException(mapping, request, funcName, exception, ResLiqDeuAdapter.NAME); } } public ActionForward eliminar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String funcName = DemodaUtil.currentMethodName(); if (log.isDebugEnabled()) log.debug("entrando en " + funcName); UserSession userSession = canAccess(request, mapping, EmiSecurityConstants.ABM_RESLIQDEU, BaseSecurityConstants.ELIMINAR); if (userSession==null) return forwardErrorSession(request); try { // Bajo el adapter del userSession ResLiqDeuAdapter resLiqDeuAdapterVO = (ResLiqDeuAdapter) userSession.get(ResLiqDeuAdapter.NAME); // Si es nulo no se puede continuar if (resLiqDeuAdapterVO == null) { log.error("error en: " + funcName + ": " + ResLiqDeuAdapter.NAME + " IS NULL. No se pudo obtener de la sesion"); return forwardErrorSessionNullObject(mapping, request, funcName, ResLiqDeuAdapter.NAME); } // llamada al servicio ResLiqDeuVO resLiqDeuVO = EmiServiceLocator.getGeneralService().deleteResLiqDeu (userSession, resLiqDeuAdapterVO.getResLiqDeu()); // Tiene errores recuperables if (resLiqDeuVO.hasErrorRecoverable()) { log.error("recoverable error en: " + funcName + ": " + resLiqDeuAdapterVO.infoString()); saveDemodaErrors(request, resLiqDeuVO); request.setAttribute(ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); return mapping.findForward(EmiConstants.FWD_RESLIQDEU_VIEW_ADAPTER); } // Tiene errores no recuperables if (resLiqDeuVO.hasErrorNonRecoverable()) { log.error("error en: " + funcName + ": " + resLiqDeuAdapterVO.errorString()); return forwardErrorNonRecoverable(mapping, request, funcName, ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); } // Fue Exitoso return forwardConfirmarOk(mapping, request, funcName, ResLiqDeuAdapter.NAME); } catch (Exception exception) { return baseException(mapping, request, funcName, exception, ResLiqDeuAdapter.NAME); } } public ActionForward volver(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return baseVolver(mapping, form, request, response, ResLiqDeuAdapter.NAME); } public ActionForward paramRecurso (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String funcName = DemodaUtil.currentMethodName(); if (log.isDebugEnabled()) log.debug("entrando en " + funcName); UserSession userSession = getCurrentUserSession(request, mapping); if (userSession==null) return forwardErrorSession(request); try { // Bajo el adapter del userSession ResLiqDeuAdapter resLiqDeuAdapterVO = (ResLiqDeuAdapter) userSession.get(ResLiqDeuAdapter.NAME); // Si es nulo no se puede continuar if (resLiqDeuAdapterVO == null) { log.error("error en: " + funcName + ": " + ResLiqDeuAdapter.NAME + " IS NULL. No se pudo obtener de la sesion"); return forwardErrorSessionNullObject(mapping, request, funcName, ResLiqDeuAdapter.NAME); } // Recuperamos datos del form en el vo DemodaUtil.populateVO(resLiqDeuAdapterVO, request); // Tiene errores recuperables if (resLiqDeuAdapterVO.hasErrorRecoverable()) { log.error("recoverable error en: " + funcName + ": " + resLiqDeuAdapterVO.infoString()); saveDemodaErrors(request, resLiqDeuAdapterVO); return forwardErrorRecoverable(mapping, request, userSession, ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); } // llamada al servicio resLiqDeuAdapterVO = EmiServiceLocator.getGeneralService() .getResLiqDeuAdapterParamRecurso(userSession, resLiqDeuAdapterVO); // Tiene errores recuperables if (resLiqDeuAdapterVO.hasErrorRecoverable()) { log.error("recoverable error en: " + funcName + ": " + resLiqDeuAdapterVO.infoString()); saveDemodaErrors(request, resLiqDeuAdapterVO); return forwardErrorRecoverable(mapping, request, userSession, ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); } // Tiene errores no recuperables if (resLiqDeuAdapterVO.hasErrorNonRecoverable()) { log.error("error en: " + funcName + ": " + resLiqDeuAdapterVO.errorString()); return forwardErrorNonRecoverable(mapping, request, funcName, ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); } // Envio el VO al request request.setAttribute(ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); // Subo el apdater al userSession userSession.put(ResLiqDeuAdapter.NAME, resLiqDeuAdapterVO); return mapping.findForward(EmiConstants.FWD_RESLIQDEU_EDIT_ADAPTER); } catch (Exception exception) { return baseException(mapping, request, funcName, exception, ResLiqDeuAdapter.NAME); } } }
gpl-3.0
jcgood/kpaamcam
AndroidApp/UBCollecting/libraries/drag-sort-listview/library/src/com/mobeta/android/dslv/ResourceDragSortCursorAdapter.java
5707
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mobeta.android.dslv; import android.content.Context; import android.database.Cursor; import androidx.cursoradapter.widget.CursorAdapter; //import androidx.core.widget.CursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; // taken from v4 rev. 10 ResourceCursorAdapter.java /** * Static library support version of the framework's {@link android.widget.ResourceCursorAdapter}. * Used to write apps that run on platforms prior to Android 3.0. When running * on Android 3.0 or above, this implementation is still used; it does not try * to switch to the framework's implementation. See the framework SDK * documentation for a class overview. */ public abstract class ResourceDragSortCursorAdapter extends DragSortCursorAdapter { private int mLayout; private int mDropDownLayout; private LayoutInflater mInflater; /** * Constructor the enables auto-requery. * * @deprecated This option is discouraged, as it results in Cursor queries * being performed on the application's UI thread and thus can cause poor * responsiveness or even Application Not Responding errors. As an alternative, * use {@link android.app.LoaderManager} with a {@link android.content.CursorLoader}. * * @param context The context where the ListView associated with this adapter is running * @param layout resource identifier of a layout file that defines the views * for this list item. Unless you override them later, this will * define both the item views and the drop down views. */ @Deprecated public ResourceDragSortCursorAdapter(Context context, int layout, Cursor c) { super(context, c); mLayout = mDropDownLayout = layout; mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } /** * Constructor with default behavior as per * {@link CursorAdapter#CursorAdapter(Context, Cursor, boolean)}; it is recommended * you not use this, but instead {@link #ResourceCursorAdapter(Context, int, Cursor, int)}. * When using this constructor, {@link #FLAG_REGISTER_CONTENT_OBSERVER} * will always be set. * * @param context The context where the ListView associated with this adapter is running * @param layout resource identifier of a layout file that defines the views * for this list item. Unless you override them later, this will * define both the item views and the drop down views. * @param c The cursor from which to get the data. * @param autoRequery If true the adapter will call requery() on the * cursor whenever it changes so the most recent * data is always displayed. Using true here is discouraged. */ public ResourceDragSortCursorAdapter(Context context, int layout, Cursor c, boolean autoRequery) { super(context, c, autoRequery); mLayout = mDropDownLayout = layout; mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } /** * Standard constructor. * * @param context The context where the ListView associated with this adapter is running * @param layout Resource identifier of a layout file that defines the views * for this list item. Unless you override them later, this will * define both the item views and the drop down views. * @param c The cursor from which to get the data. * @param flags Flags used to determine the behavior of the adapter, * as per {@link CursorAdapter#CursorAdapter(Context, Cursor, int)}. */ public ResourceDragSortCursorAdapter(Context context, int layout, Cursor c, int flags) { super(context, c, flags); mLayout = mDropDownLayout = layout; mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } /** * Inflates view(s) from the specified XML file. * * @see android.widget.CursorAdapter#newView(android.content.Context, * android.database.Cursor, ViewGroup) */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return mInflater.inflate(mLayout, parent, false); } @Override public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) { return mInflater.inflate(mDropDownLayout, parent, false); } /** * <p>Sets the layout resource of the item views.</p> * * @param layout the layout resources used to create item views */ public void setViewResource(int layout) { mLayout = layout; } /** * <p>Sets the layout resource of the drop down views.</p> * * @param dropDownLayout the layout resources used to create drop down views */ public void setDropDownViewResource(int dropDownLayout) { mDropDownLayout = dropDownLayout; } }
gpl-3.0
AmauryCarrade/UHPlugin
src/main/java/eu/carrade/amaury/UHCReloaded/commands/commands/categories/Category.java
2057
/* * Copyright or © or Copr. Amaury Carrade (2014 - 2016) * * http://amaury.carrade.eu * * This software is governed by the CeCILL-B license under French law and * abiding by the rules of distribution of free software. You can use, * modify and/ or redistribute the software under the terms of the CeCILL-B * license as circulated by CEA, CNRS and INRIA at the following URL * "http://www.cecill.info". * * As a counterpart to the access to the source code and rights to copy, * modify and redistribute granted by the license, users are provided only * with a limited warranty and the software's author, the holder of the * economic rights, and the successive licensors have only limited * liability. * * In this respect, the user's attention is drawn to the risks associated * with loading, using, modifying and/or developing or reproducing the * software by the user in light of its specific status of free software, * that may mean that it is complicated to manipulate, and that also * therefore means that it is reserved for developers and experienced * professionals having in-depth computer knowledge. Users are therefore * encouraged to load and test the software's suitability as regards their * requirements in conditions enabling the security of their systems and/or * data to be ensured and, more generally, to use and operate it in the * same conditions as regards security. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-B license and that you accept its terms. */ package eu.carrade.amaury.UHCReloaded.commands.commands.categories; import fr.zcraft.zlib.components.i18n.I; public enum Category { GAME(I.t("{aqua}------ Game-related commands ------")), BUGS(I.t("{aqua}------ Bugs-related commands ------")), MISC(I.t("{aqua}------ Miscellaneous commands ------")); private String title; Category(String title) { this.title = title; } public String getTitle() { return title; } }
gpl-3.0
chinashiyu/gfw.press.android
src/main/java/press/gfw/android/CompatActivity.java
3771
/** * GFW.Press * Copyright (C) 2016 chinashiyu ( chinashiyu@gfw.press ; http://gfw.press ) * <p/> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * <p/> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p/> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ package press.gfw.android; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceActivity; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatDelegate; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; /** * GFW.Press Android 客户端组件 * * @author chinashiyu ( chinashiyu@gfw.press ; http://gfw.press ) */ public abstract class CompatActivity extends PreferenceActivity { private AppCompatDelegate mDelegate; @Override protected void onCreate(Bundle savedInstanceState) { getDelegate().installViewFactory(); getDelegate().onCreate(savedInstanceState); super.onCreate(savedInstanceState); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getDelegate().onPostCreate(savedInstanceState); } public ActionBar getSupportActionBar() { return getDelegate().getSupportActionBar(); } @NonNull @Override public MenuInflater getMenuInflater() { return getDelegate().getMenuInflater(); } @Override public void setContentView(@LayoutRes int layoutResID) { getDelegate().setContentView(layoutResID); } @Override public void setContentView(View view) { getDelegate().setContentView(view); } @Override public void setContentView(View view, ViewGroup.LayoutParams params) { getDelegate().setContentView(view, params); } @Override public void addContentView(View view, ViewGroup.LayoutParams params) { getDelegate().addContentView(view, params); } @Override protected void onPostResume() { super.onPostResume(); getDelegate().onPostResume(); } @Override protected void onTitleChanged(CharSequence title, int color) { super.onTitleChanged(title, color); getDelegate().setTitle(title); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); getDelegate().onConfigurationChanged(newConfig); } @Override protected void onStop() { super.onStop(); getDelegate().onStop(); } @Override protected void onDestroy() { super.onDestroy(); getDelegate().onDestroy(); } public void invalidateOptionsMenu() { getDelegate().invalidateOptionsMenu(); } private AppCompatDelegate getDelegate() { if (mDelegate == null) { mDelegate = AppCompatDelegate.create(this, null); } return mDelegate; } }
gpl-3.0
cheetah100/gravity
src/main/java/nz/net/orcon/kanban/automation/plugin/FreemarkerPlugin.java
2280
/** * GRAVITY WORKFLOW AUTOMATION * (C) Copyright 2015 Orcon Limited * * This file is part of Gravity Workflow Automation. * * Gravity Workflow Automation is free software: you can redistribute it * and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * Gravity Workflow Automation is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Gravity Workflow Automation. * If not, see <http://www.gnu.org/licenses/>. */ package nz.net.orcon.kanban.automation.plugin; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.Locale; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import freemarker.template.Configuration; import freemarker.template.Template; import nz.net.orcon.kanban.controllers.ResourceController; import nz.net.orcon.kanban.model.Action; public class FreemarkerPlugin implements Plugin { @Autowired private ResourceController resourceController; @Override public Map<String,Object> process( Action action, Map<String,Object> context ) throws Exception{ String resource = getResourceController().getResource((String)context.get("boardid"),action.getResource()); Configuration configuration = new Configuration(); configuration.setEncoding(Locale.ENGLISH, "UTF-8"); Template template = new Template(action.getResource(), new StringReader(resource), configuration); Writer output = new StringWriter(); template.process(context, output); String result = output.toString(); context.put(action.getResponse(), result); return context; } public ResourceController getResourceController() { return resourceController; } public void setResourceController(ResourceController resourceController) { this.resourceController = resourceController; } }
gpl-3.0
jdr0887/jgringotts
jgringotts-dao/jgringotts-dao-jpa/src/main/java/com/kiluet/jgringotts/dao/jpa/BaseDAOImpl.java
2776
package com.kiluet.jgringotts.dao.jpa; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceUnit; import javax.persistence.Query; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.kiluet.jgringotts.dao.BaseDAO; import com.kiluet.jgringotts.dao.JGringottsDAOException; import com.kiluet.jgringotts.dao.model.Persistable; public abstract class BaseDAOImpl<T extends Persistable, ID extends Serializable> implements BaseDAO<T, ID> { private static final Logger logger = LoggerFactory.getLogger(BaseDAOImpl.class); @PersistenceUnit(name = "jgringotts", unitName = "jgringotts") private EntityManager entityManager; public BaseDAOImpl() { super(); } public abstract Class<T> getPersistentClass(); @Override public Long save(T entity) throws JGringottsDAOException { logger.debug("ENTERING save(T)"); entityManager.getTransaction().begin(); if (!entityManager.contains(entity) && entity.getId() != null) { entity = entityManager.merge(entity); } else { entityManager.persist(entity); } // logger.info(entity.toString()); entityManager.flush(); entityManager.getTransaction().commit(); return entity.getId(); } @Override public void delete(T entity) throws JGringottsDAOException { logger.debug("ENTERING delete(T)"); entityManager.getTransaction().begin(); // logger.info(entity.toString()); T foundEntity = entityManager.find(getPersistentClass(), entity.getId()); entityManager.remove(foundEntity); entityManager.getTransaction().commit(); } @Override public void delete(List<T> entityList) throws JGringottsDAOException { logger.debug("ENTERING delete(List<T>)"); List<Long> idList = new ArrayList<Long>(); for (T t : entityList) { idList.add(t.getId()); } entityManager.getTransaction().begin(); Query qDelete = entityManager .createQuery("delete from " + getPersistentClass().getSimpleName() + " a where a.id in (?1)"); qDelete.setParameter(1, idList); qDelete.executeUpdate(); entityManager.getTransaction().commit(); } @Override public T findById(ID id) throws JGringottsDAOException { logger.debug("ENTERING findById(T)"); T ret = entityManager.find(getPersistentClass(), id); return ret; } public EntityManager getEntityManager() { return entityManager; } public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } }
gpl-3.0