repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
manav-bhanot/RecursiveImplentations | src/edu/csulb/cecs/codingbat/recursion1/AllStar.java | 916 | /**
*
*/
package edu.csulb.cecs.codingbat.recursion1;
import java.util.Scanner;
/**
* @author Manav
*
* Problem source : http://codingbat.com/prob/p183394
*
* Given a string, compute recursively a new string where all the
* adjacent chars are now separated by a "*".
*
* allStar("hello") → "h*e*l*l*o"
*
* allStar("abc") → "a*b*c"
*
* allStar("ab") → "a*b"
*
*/
public class AllStar {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a string : ");
String str = scan.next();
System.out.println(allStar(str));
}
private static String allStar(String str) {
if (str.isEmpty() || str.length() == 1) {
return str;
}
return str.charAt(0) + "*" + allStar(str.substring(1));
}
}
| gpl-3.0 |
costabatista/JFilterCode | src/io/github/costabatista/jfiltercode/token/TokenComparatorByValueLength.java | 354 | package io.github.costabatista.jfiltercode.token;
import java.util.Comparator;
public class TokenComparatorByValueLength implements Comparator<Token> {
public int compare(Token o1, Token o2) {
// TODO Auto-generated method stub
//o1.compareTo()
return new Integer(o2.getValue().length()).compareTo(new Integer(o1.getValue().length()));
}
}
| gpl-3.0 |
Roundaround/Tiberius | src/roundaround/tiberius/exception/MissingConfigurationAttributeException.java | 412 | package roundaround.tiberius.exception;
public class MissingConfigurationAttributeException extends Exception {
private static final long serialVersionUID = -8206751838064635362L;
public MissingConfigurationAttributeException(String field, String attribute) {
super("The required attribute '" + attribute + "' of field '" + field + "' is missing from this bot's configuration file.");
}
}
| gpl-3.0 |
UM-LPM/EARS | src/org/um/feri/ears/visualization/heatmap/HeatMap.java | 22960 | package org.um.feri.ears.visualization.heatmap;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
/**
*
* <p><strong>Title:</strong> HeatMap</p>
*
* <p>Description: HeatMap is a JPanel that displays a 2-dimensional array of
* data using a selected color gradient scheme.</p>
* <p>For specifying data, the first index into the double[][] array is the x-
* coordinate, and the second index is the y-coordinate. In the constructor and
* updateData method, the 'useGraphicsYAxis' parameter is used to control
* whether the row y=0 is displayed at the top or bottom. Since the usual
* graphics coordinate system has y=0 at the top, setting this parameter to
* true will draw the y=0 row at the top, and setting the parameter to false
* will draw the y=0 row at the bottom, like in a regular, mathematical
* coordinate system. This parameter was added as a solution to the problem of
* "Which coordinate system should we use? Graphics, or mathematical?", and
* allows the user to choose either coordinate system. Because the HeatMap will
* be plotting the data in a graphical manner, using the Java Swing framework
* that uses the standard computer graphics coordinate system, the user's data
* is stored internally with the y=0 row at the top.</p>
* <p>There are a number of defined gradient types (look at the static fields),
* but you can create any gradient you like by using either of the following
* functions in the Gradient class:
* <ul>
* <li>public static Color[] createMultiGradient(Color[] colors, int numSteps)</li>
* <li>public static Color[] createGradient(Color one, Color two, int numSteps)</li>
* </ul>
* You can then assign an arbitrary Color[] object to the HeatMap as follows:
* <pre>myHeatMap.updateGradient(Gradient.createMultiGradient(new Color[] {Color.red, Color.white, Color.blue}, 256));</pre>
* </p>
*
* <p>By default, the graph title, axis titles, and axis tick marks are not
* displayed. Be sure to set the appropriate title before enabling them.</p>
*
* <hr />
* <p><strong>Copyright:</strong> Copyright (c) 2007, 2008</p>
*
* <p>HeatMap is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.</p>
*
* <p>HeatMap 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>
*
* <p>You should have received a copy of the GNU General Public License
* along with HeatMap; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA</p>
*
* @author Matthew Beckler (matthew@mbeckler.org)
* @author Josh Hayes-Sheen (grey@grevian.org), Converted to use BufferedImage.
* @author J. Keller (jpaulkeller@gmail.com), Added transparency (alpha) support, data ordering bug fix.
* @version 1.6
*/
public class HeatMap extends JPanel
{
private double[][] data;
private int[][] dataColorIndices;
// these four variables are used to print the axis labels
private double xMin;
private double xMax;
private double yMin;
private double yMax;
private String title;
private String xAxis;
private String yAxis;
private boolean drawTitle = false;
private boolean drawXTitle = false;
private boolean drawYTitle = false;
private boolean drawLegend = false;
private boolean drawXTicks = false;
private boolean drawYTicks = false;
private Color[] colors;
private Color bg = Color.white;
private Color fg = Color.black;
private BufferedImage bufferedImage;
private Graphics2D bufferedGraphics;
/**
* @param data The data to display, must be a complete array (non-ragged)
* @param useGraphicsYAxis If true, the data will be displayed with the y=0 row at the top of the screen. If false, the data will be displayed with they=0 row at the bottom of the screen.
* @param colors A variable of the type Color[]. See also {@link #createMultiGradient} and {@link #createGradient}.
*/
public HeatMap(double[][] data, boolean useGraphicsYAxis, Color[] colors)
{
super();
updateGradient(colors);
updateData(data, useGraphicsYAxis);
this.setPreferredSize(new Dimension(60+data.length, 60+data[0].length));
this.setDoubleBuffered(true);
this.bg = Color.white;
this.fg = Color.black;
// this is the expensive function that draws the data plot into a
// BufferedImage. The data plot is then cheaply drawn to the screen when
// needed, saving us a lot of time in the end.
drawData();
}
public void saveImage(String name) throws IOException {
ImageIO.write(bufferedImage, "PNG", new File(name+".png"));
}
/**
* Specify the coordinate bounds for the map. Only used for the axis labels, which must be enabled seperately. Calls repaint() when finished.
* @param xMin The lower bound of x-values, used for axis labels
* @param xMax The upper bound of x-values, used for axis labels
*/
public void setCoordinateBounds(double xMin, double xMax, double yMin, double yMax)
{
this.xMin = xMin;
this.xMax = xMax;
this.yMin = yMin;
this.yMax = yMax;
repaint();
}
/**
* Specify the coordinate bounds for the X-range. Only used for the axis labels, which must be enabled seperately. Calls repaint() when finished.
* @param xMin The lower bound of x-values, used for axis labels
* @param xMax The upper bound of x-values, used for axis labels
*/
public void setXCoordinateBounds(double xMin, double xMax)
{
this.xMin = xMin;
this.xMax = xMax;
repaint();
}
/**
* Specify the coordinate bounds for the X Min. Only used for the axis labels, which must be enabled seperately. Calls repaint() when finished.
* @param xMin The lower bound of x-values, used for axis labels
*/
public void setXMinCoordinateBounds(double xMin)
{
this.xMin = xMin;
repaint();
}
/**
* Specify the coordinate bounds for the X Max. Only used for the axis labels, which must be enabled seperately. Calls repaint() when finished.
* @param xMax The upper bound of x-values, used for axis labels
*/
public void setXMaxCoordinateBounds(double xMax)
{
this.xMax = xMax;
repaint();
}
/**
* Specify the coordinate bounds for the Y-range. Only used for the axis labels, which must be enabled seperately. Calls repaint() when finished.
* @param yMin The lower bound of y-values, used for axis labels
* @param yMax The upper bound of y-values, used for axis labels
*/
public void setYCoordinateBounds(double yMin, double yMax)
{
this.yMin = yMin;
this.yMax = yMax;
repaint();
}
/**
* Specify the coordinate bounds for the Y Min. Only used for the axis labels, which must be enabled seperately. Calls repaint() when finished.
* @param yMin The lower bound of Y-values, used for axis labels
*/
public void setYMinCoordinateBounds(double yMin)
{
this.yMin = yMin;
repaint();
}
/**
* Specify the coordinate bounds for the Y Max. Only used for the axis labels, which must be enabled seperately. Calls repaint() when finished.
* @param yMax The upper bound of y-values, used for axis labels
*/
public void setYMaxCoordinateBounds(double yMax)
{
this.yMax = yMax;
repaint();
}
/**
* Updates the title. Calls repaint() when finished.
* @param title The new title
*/
public void setTitle(String title)
{
this.title = title;
repaint();
}
/**
* Updates the state of the title. Calls repaint() when finished.
* @param drawTitle Specifies if the title should be drawn
*/
public void setDrawTitle(boolean drawTitle)
{
this.drawTitle = drawTitle;
repaint();
}
/**
* Updates the X-Axis title. Calls repaint() when finished.
* @param xAxisTitle The new X-Axis title
*/
public void setXAxisTitle(String xAxisTitle)
{
this.xAxis = xAxisTitle;
repaint();
}
/**
* Updates the state of the X-Axis Title. Calls repaint() when finished.
* @param drawXAxisTitle Specifies if the X-Axis title should be drawn
*/
public void setDrawXAxisTitle(boolean drawXAxisTitle)
{
this.drawXTitle = drawXAxisTitle;
repaint();
}
/**
* Updates the Y-Axis title. Calls repaint() when finished.
* @param yAxisTitle The new Y-Axis title
*/
public void setYAxisTitle(String yAxisTitle)
{
this.yAxis = yAxisTitle;
repaint();
}
/**
* Updates the state of the Y-Axis Title. Calls repaint() when finished.
* @param drawYAxisTitle Specifies if the Y-Axis title should be drawn
*/
public void setDrawYAxisTitle(boolean drawYAxisTitle)
{
this.drawYTitle = drawYAxisTitle;
repaint();
}
/**
* Updates the state of the legend. Calls repaint() when finished.
* @param drawLegend Specifies if the legend should be drawn
*/
public void setDrawLegend(boolean drawLegend)
{
this.drawLegend = drawLegend;
repaint();
}
/**
* Updates the state of the X-Axis ticks. Calls repaint() when finished.
* @param drawXTicks Specifies if the X-Axis ticks should be drawn
*/
public void setDrawXTicks(boolean drawXTicks)
{
this.drawXTicks = drawXTicks;
repaint();
}
/**
* Updates the state of the Y-Axis ticks. Calls repaint() when finished.
* @param drawYTicks Specifies if the Y-Axis ticks should be drawn
*/
public void setDrawYTicks(boolean drawYTicks)
{
this.drawYTicks = drawYTicks;
repaint();
}
/**
* Updates the foreground color. Calls repaint() when finished.
* @param fg Specifies the desired foreground color
*/
public void setColorForeground(Color fg)
{
this.fg = fg;
repaint();
}
/**
* Updates the background color. Calls repaint() when finished.
* @param bg Specifies the desired background color
*/
public void setColorBackground(Color bg)
{
this.bg = bg;
repaint();
}
/**
* Updates the gradient used to display the data. Calls drawData() and
* repaint() when finished.
* @param colors A variable of type Color[]
*/
public void updateGradient(Color[] colors)
{
this.colors = (Color[]) colors.clone();
if (data != null)
{
updateDataColors();
drawData();
repaint();
}
}
/**
* This uses the current array of colors that make up the gradient, and
* assigns a color index to each data point, stored in the dataColorIndices
* array, which is used by the drawData() method to plot the points.
*/
private void updateDataColors()
{
//We need to find the range of the data values,
// in order to assign proper colors.
double largest = Double.MIN_VALUE;
double smallest = Double.MAX_VALUE;
for (int x = 0; x < data.length; x++)
{
for (int y = 0; y < data[0].length; y++)
{
largest = Math.max(data[x][y], largest);
smallest = Math.min(data[x][y], smallest);
}
}
double range = largest - smallest;
// dataColorIndices is the same size as the data array
// It stores an int index into the color array
dataColorIndices = new int[data.length][data[0].length];
//assign a Color to each data point
for (int x = 0; x < data.length; x++)
{
for (int y = 0; y < data[0].length; y++)
{
double norm = (data[x][y] - smallest) / range; // 0 < norm < 1
int colorIndex = (int) Math.floor(norm * (colors.length - 1));
dataColorIndices[x][y] = colorIndex;
}
}
}
/**
* This function generates data that is not vertically-symmetric, which
* makes it very useful for testing which type of vertical axis is being
* used to plot the data. If the graphics Y-axis is used, then the lowest
* values should be displayed at the top of the frame. If the non-graphics
* (mathematical coordinate-system) Y-axis is used, then the lowest values
* should be displayed at the bottom of the frame.
* @return double[][] data values of a simple vertical ramp
*/
public static double[][] generateRampTestData()
{
double[][] data = new double[10][10];
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
data[x][y] = y;
}
}
return data;
}
/**
* This function generates an appropriate data array for display. It uses
* the function: z = sin(x)*cos(y). The parameter specifies the number
* of data points in each direction, producing a square matrix.
* @param dimension Size of each side of the returned array
* @return double[][] calculated values of z = sin(x)*cos(y)
*/
public static double[][] generateSinCosData(int dimension)
{
if (dimension % 2 == 0)
{
dimension++; //make it better
}
double[][] data = new double[dimension][dimension];
double sX, sY; //s for 'Scaled'
for (int x = 0; x < dimension; x++)
{
for (int y = 0; y < dimension; y++)
{
sX = 2 * Math.PI * (x / (double) dimension); // 0 < sX < 2 * Pi
sY = 2 * Math.PI * (y / (double) dimension); // 0 < sY < 2 * Pi
data[x][y] = Math.sin(sX) * Math.cos(sY);
}
}
return data;
}
/**
* This function generates an appropriate data array for display. It uses
* the function: z = Math.cos(Math.abs(sX) + Math.abs(sY)). The parameter
* specifies the number of data points in each direction, producing a
* square matrix.
* @param dimension Size of each side of the returned array
* @return double[][] calculated values of z = Math.cos(Math.abs(sX) + Math.abs(sY));
*/
public static double[][] generatePyramidData(int dimension)
{
if (dimension % 2 == 0)
{
dimension++; //make it better
}
double[][] data = new double[dimension][dimension];
double sX, sY; //s for 'Scaled'
for (int x = 0; x < dimension; x++)
{
for (int y = 0; y < dimension; y++)
{
sX = 6 * (x / (double) dimension); // 0 < sX < 6
sY = 6 * (y / (double) dimension); // 0 < sY < 6
sX = sX - 3; // -3 < sX < 3
sY = sY - 3; // -3 < sY < 3
data[x][y] = Math.cos(Math.abs(sX) + Math.abs(sY));
}
}
return data;
}
/**
* Updates the data display, calls drawData() to do the expensive re-drawing
* of the data plot, and then calls repaint().
* @param data The data to display, must be a complete array (non-ragged)
* @param useGraphicsYAxis If true, the data will be displayed with the y=0 row at the top of the screen. If false, the data will be displayed with the y=0 row at the bottom of the screen.
*/
public void updateData(double[][] data, boolean useGraphicsYAxis)
{
this.data = new double[data.length][data[0].length];
for (int ix = 0; ix < data.length; ix++)
{
for (int iy = 0; iy < data[0].length; iy++)
{
// we use the graphics Y-axis internally
if (useGraphicsYAxis)
{
this.data[ix][iy] = data[ix][iy];
}
else
{
this.data[ix][iy] = data[ix][data[0].length - iy - 1];
}
}
}
updateDataColors();
drawData();
repaint();
}
public void drawPoint(int x, int y, int radius, Color color) {
bufferedGraphics.setColor(color);
int diameter = radius * 2;
//shift x and y by the radius of the circle in order to correctly center it
bufferedGraphics.fillOval(x - radius, y - radius, diameter, diameter);
repaint();
}
/**
* Creates a BufferedImage of the actual data plot.
*
* After doing some profiling, it was discovered that 90% of the drawing
* time was spend drawing the actual data (not on the axes or tick marks).
* Since the Graphics2D has a drawImage method that can do scaling, we are
* using that instead of scaling it ourselves. We only need to draw the
* data into the bufferedImage on startup, or if the data or gradient
* changes. This saves us an enormous amount of time. Thanks to
* Josh Hayes-Sheen (grey@grevian.org) for the suggestion and initial code
* to use the BufferedImage technique.
*
* Since the scaling of the data plot will be handled by the drawImage in
* paintComponent, we take the easy way out and draw our bufferedImage with
* 1 pixel per data point. Too bad there isn't a setPixel method in the
* Graphics2D class, it seems a bit silly to fill a rectangle just to set a
* single pixel...
*
* This function should be called whenever the data or the gradient changes.
*/
public void drawData()
{
bufferedImage = new BufferedImage(data.length,data[0].length, BufferedImage.TYPE_INT_ARGB);
bufferedGraphics = bufferedImage.createGraphics();
for (int x = 0; x < data.length; x++)
{
for (int y = 0; y < data[0].length; y++)
{
bufferedGraphics.setColor(colors[dataColorIndices[x][y]]);
bufferedGraphics.fillRect(x, y, 1, 1);
}
}
}
/**
* The overridden painting method, now optimized to simply draw the data
* plot to the screen, letting the drawImage method do the resizing. This
* saves an extreme amount of time.
*/
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int width = this.getWidth();
int height = this.getHeight();
this.setOpaque(true);
// clear the panel
g2d.setColor(bg);
g2d.fillRect(0, 0, width, height);
// draw the heat map
if (bufferedImage == null)
{
// Ideally, we only call drawData in the constructor, or if we
// change the data or gradients. We include this just to be safe.
drawData();
}
// The data plot itself is drawn with 1 pixel per data point, and the
// drawImage method scales that up to fit our current window size. This
// is very fast, and is much faster than the previous version, which
// redrew the data plot each time we had to repaint the screen.
g2d.drawImage(bufferedImage,
31, 31,
width - 30,
height - 30,
0, 0,
bufferedImage.getWidth(), bufferedImage.getHeight(),
null);
// border
g2d.setColor(fg);
g2d.drawRect(30, 30, width - 60, height - 60);
// title
if (drawTitle && title != null)
{
g2d.drawString(title, (width / 2) - 4 * title.length(), 20);
}
// axis ticks - ticks start even with the bottom left coner, end very close to end of line (might not be right on)
int numXTicks = (width - 60) / 50;
int numYTicks = (height - 60) / 50;
String label = "";
DecimalFormat df = new DecimalFormat("##.##");
// Y-Axis ticks
if (drawYTicks)
{
int yDist = (int) ((height - 60) / (double) numYTicks); //distance between ticks
for (int y = 0; y <= numYTicks; y++)
{
g2d.drawLine(26, height - 30 - y * yDist, 30, height - 30 - y * yDist);
label = df.format(((y / (double) numYTicks) * (yMax - yMin)) + yMin);
int labelY = height - 30 - y * yDist - 4 * label.length();
//to get the text to fit nicely, we need to rotate the graphics
g2d.rotate(Math.PI / 2);
g2d.drawString(label, labelY, -14);
g2d.rotate( -Math.PI / 2);
}
}
// Y-Axis title
if (drawYTitle && yAxis != null)
{
//to get the text to fit nicely, we need to rotate the graphics
g2d.rotate(Math.PI / 2);
g2d.drawString(yAxis, (height / 2) - 4 * yAxis.length(), -3);
g2d.rotate( -Math.PI / 2);
}
// X-Axis ticks
if (drawXTicks)
{
int xDist = (int) ((width - 60) / (double) numXTicks); //distance between ticks
for (int x = 0; x <= numXTicks; x++)
{
g2d.drawLine(30 + x * xDist, height - 30, 30 + x * xDist, height - 26);
label = df.format(((x / (double) numXTicks) * (xMax - xMin)) + xMin);
int labelX = (31 + x * xDist) - 4 * label.length();
g2d.drawString(label, labelX, height - 14);
}
}
// X-Axis title
if (drawXTitle && xAxis != null)
{
g2d.drawString(xAxis, (width / 2) - 4 * xAxis.length(), height - 3);
}
// Legend
if (drawLegend)
{
g2d.drawRect(width - 20, 30, 10, height - 60);
for (int y = 0; y < height - 61; y++)
{
int yStart = height - 31 - (int) Math.ceil(y * ((height - 60) / (colors.length * 1.0)));
yStart = height - 31 - y;
g2d.setColor(colors[(int) ((y / (double) (height - 60)) * (colors.length * 1.0))]);
g2d.fillRect(width - 19, yStart, 9, 1);
}
}
}
}
| gpl-3.0 |
idega/is.idega.webservice | src/java/is/idega/webservice/propertyregistryservice/client/ParamInfo.java | 19339 | /**
* ParamInfo.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.3 Oct 05, 2005 (05:23:37 EDT) WSDL2Java emitter.
*/
package is.idega.webservice.propertyregistryservice.client;
public class ParamInfo implements java.io.Serializable {
private java.lang.String fromField;
private java.lang.String toField;
private java.lang.String fromList;
private java.lang.String toList;
private java.lang.String type;
private java.lang.String fromDefValue;
private java.lang.String toDefValue;
private java.lang.String mask;
private java.lang.String length;
private java.lang.String text;
private java.lang.String DBField;
private java.lang.String code;
private int order;
private java.lang.String fromValue;
private java.lang.String toValue;
public ParamInfo() {
}
public ParamInfo(
java.lang.String fromField,
java.lang.String toField,
java.lang.String fromList,
java.lang.String toList,
java.lang.String type,
java.lang.String fromDefValue,
java.lang.String toDefValue,
java.lang.String mask,
java.lang.String length,
java.lang.String text,
java.lang.String DBField,
java.lang.String code,
int order,
java.lang.String fromValue,
java.lang.String toValue) {
this.fromField = fromField;
this.toField = toField;
this.fromList = fromList;
this.toList = toList;
this.type = type;
this.fromDefValue = fromDefValue;
this.toDefValue = toDefValue;
this.mask = mask;
this.length = length;
this.text = text;
this.DBField = DBField;
this.code = code;
this.order = order;
this.fromValue = fromValue;
this.toValue = toValue;
}
/**
* Gets the fromField value for this ParamInfo.
*
* @return fromField
*/
public java.lang.String getFromField() {
return fromField;
}
/**
* Sets the fromField value for this ParamInfo.
*
* @param fromField
*/
public void setFromField(java.lang.String fromField) {
this.fromField = fromField;
}
/**
* Gets the toField value for this ParamInfo.
*
* @return toField
*/
public java.lang.String getToField() {
return toField;
}
/**
* Sets the toField value for this ParamInfo.
*
* @param toField
*/
public void setToField(java.lang.String toField) {
this.toField = toField;
}
/**
* Gets the fromList value for this ParamInfo.
*
* @return fromList
*/
public java.lang.String getFromList() {
return fromList;
}
/**
* Sets the fromList value for this ParamInfo.
*
* @param fromList
*/
public void setFromList(java.lang.String fromList) {
this.fromList = fromList;
}
/**
* Gets the toList value for this ParamInfo.
*
* @return toList
*/
public java.lang.String getToList() {
return toList;
}
/**
* Sets the toList value for this ParamInfo.
*
* @param toList
*/
public void setToList(java.lang.String toList) {
this.toList = toList;
}
/**
* Gets the type value for this ParamInfo.
*
* @return type
*/
public java.lang.String getType() {
return type;
}
/**
* Sets the type value for this ParamInfo.
*
* @param type
*/
public void setType(java.lang.String type) {
this.type = type;
}
/**
* Gets the fromDefValue value for this ParamInfo.
*
* @return fromDefValue
*/
public java.lang.String getFromDefValue() {
return fromDefValue;
}
/**
* Sets the fromDefValue value for this ParamInfo.
*
* @param fromDefValue
*/
public void setFromDefValue(java.lang.String fromDefValue) {
this.fromDefValue = fromDefValue;
}
/**
* Gets the toDefValue value for this ParamInfo.
*
* @return toDefValue
*/
public java.lang.String getToDefValue() {
return toDefValue;
}
/**
* Sets the toDefValue value for this ParamInfo.
*
* @param toDefValue
*/
public void setToDefValue(java.lang.String toDefValue) {
this.toDefValue = toDefValue;
}
/**
* Gets the mask value for this ParamInfo.
*
* @return mask
*/
public java.lang.String getMask() {
return mask;
}
/**
* Sets the mask value for this ParamInfo.
*
* @param mask
*/
public void setMask(java.lang.String mask) {
this.mask = mask;
}
/**
* Gets the length value for this ParamInfo.
*
* @return length
*/
public java.lang.String getLength() {
return length;
}
/**
* Sets the length value for this ParamInfo.
*
* @param length
*/
public void setLength(java.lang.String length) {
this.length = length;
}
/**
* Gets the text value for this ParamInfo.
*
* @return text
*/
public java.lang.String getText() {
return text;
}
/**
* Sets the text value for this ParamInfo.
*
* @param text
*/
public void setText(java.lang.String text) {
this.text = text;
}
/**
* Gets the DBField value for this ParamInfo.
*
* @return DBField
*/
public java.lang.String getDBField() {
return DBField;
}
/**
* Sets the DBField value for this ParamInfo.
*
* @param DBField
*/
public void setDBField(java.lang.String DBField) {
this.DBField = DBField;
}
/**
* Gets the code value for this ParamInfo.
*
* @return code
*/
public java.lang.String getCode() {
return code;
}
/**
* Sets the code value for this ParamInfo.
*
* @param code
*/
public void setCode(java.lang.String code) {
this.code = code;
}
/**
* Gets the order value for this ParamInfo.
*
* @return order
*/
public int getOrder() {
return order;
}
/**
* Sets the order value for this ParamInfo.
*
* @param order
*/
public void setOrder(int order) {
this.order = order;
}
/**
* Gets the fromValue value for this ParamInfo.
*
* @return fromValue
*/
public java.lang.String getFromValue() {
return fromValue;
}
/**
* Sets the fromValue value for this ParamInfo.
*
* @param fromValue
*/
public void setFromValue(java.lang.String fromValue) {
this.fromValue = fromValue;
}
/**
* Gets the toValue value for this ParamInfo.
*
* @return toValue
*/
public java.lang.String getToValue() {
return toValue;
}
/**
* Sets the toValue value for this ParamInfo.
*
* @param toValue
*/
public void setToValue(java.lang.String toValue) {
this.toValue = toValue;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof ParamInfo)) return false;
ParamInfo other = (ParamInfo) obj;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.fromField==null && other.getFromField()==null) ||
(this.fromField!=null &&
this.fromField.equals(other.getFromField()))) &&
((this.toField==null && other.getToField()==null) ||
(this.toField!=null &&
this.toField.equals(other.getToField()))) &&
((this.fromList==null && other.getFromList()==null) ||
(this.fromList!=null &&
this.fromList.equals(other.getFromList()))) &&
((this.toList==null && other.getToList()==null) ||
(this.toList!=null &&
this.toList.equals(other.getToList()))) &&
((this.type==null && other.getType()==null) ||
(this.type!=null &&
this.type.equals(other.getType()))) &&
((this.fromDefValue==null && other.getFromDefValue()==null) ||
(this.fromDefValue!=null &&
this.fromDefValue.equals(other.getFromDefValue()))) &&
((this.toDefValue==null && other.getToDefValue()==null) ||
(this.toDefValue!=null &&
this.toDefValue.equals(other.getToDefValue()))) &&
((this.mask==null && other.getMask()==null) ||
(this.mask!=null &&
this.mask.equals(other.getMask()))) &&
((this.length==null && other.getLength()==null) ||
(this.length!=null &&
this.length.equals(other.getLength()))) &&
((this.text==null && other.getText()==null) ||
(this.text!=null &&
this.text.equals(other.getText()))) &&
((this.DBField==null && other.getDBField()==null) ||
(this.DBField!=null &&
this.DBField.equals(other.getDBField()))) &&
((this.code==null && other.getCode()==null) ||
(this.code!=null &&
this.code.equals(other.getCode()))) &&
this.order == other.getOrder() &&
((this.fromValue==null && other.getFromValue()==null) ||
(this.fromValue!=null &&
this.fromValue.equals(other.getFromValue()))) &&
((this.toValue==null && other.getToValue()==null) ||
(this.toValue!=null &&
this.toValue.equals(other.getToValue())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getFromField() != null) {
_hashCode += getFromField().hashCode();
}
if (getToField() != null) {
_hashCode += getToField().hashCode();
}
if (getFromList() != null) {
_hashCode += getFromList().hashCode();
}
if (getToList() != null) {
_hashCode += getToList().hashCode();
}
if (getType() != null) {
_hashCode += getType().hashCode();
}
if (getFromDefValue() != null) {
_hashCode += getFromDefValue().hashCode();
}
if (getToDefValue() != null) {
_hashCode += getToDefValue().hashCode();
}
if (getMask() != null) {
_hashCode += getMask().hashCode();
}
if (getLength() != null) {
_hashCode += getLength().hashCode();
}
if (getText() != null) {
_hashCode += getText().hashCode();
}
if (getDBField() != null) {
_hashCode += getDBField().hashCode();
}
if (getCode() != null) {
_hashCode += getCode().hashCode();
}
_hashCode += getOrder();
if (getFromValue() != null) {
_hashCode += getFromValue().hashCode();
}
if (getToValue() != null) {
_hashCode += getToValue().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(ParamInfo.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://tempuri.org/", "ParamInfo"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("fromField");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "FromField"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("toField");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "ToField"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("fromList");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "FromList"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("toList");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "ToList"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("type");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "Type"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("fromDefValue");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "FromDefValue"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("toDefValue");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "ToDefValue"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("mask");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "Mask"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("length");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "Length"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("text");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "Text"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("DBField");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "DBField"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("code");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "Code"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("order");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "Order"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("fromValue");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "FromValue"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("toValue");
elemField.setXmlName(new javax.xml.namespace.QName("http://tempuri.org/", "ToValue"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| gpl-3.0 |
willp-bl/tika2fits | src/main/java/edu/harvard/hul/ois/fits/exceptions/FitsException.java | 1617 | /*
* Copyright 2009 Harvard University Library
*
* This file is part of FITS (File Information Tool Set).
*
* FITS 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.
*
* FITS 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 FITS. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.harvard.hul.ois.fits.exceptions;
@SuppressWarnings("javadoc")
public class FitsException extends Exception {
/**
* generated serial id
*/
private static final long serialVersionUID = 1266363844796336485L;
private Exception embeddedException = null;
private String message;
public FitsException() {
super();
}
public FitsException(String message) {
this();
this.message = message;
}
public FitsException(String message, Exception e) {
this();
this.embeddedException = e;
this.message = message;
if (e.getMessage() != null){
this.message = this.message + " (" + e.getMessage() + ")";
}
}
public String getMessage() {
return message;
}
public Exception getEmbeddedException() {
return embeddedException;
}
} | gpl-3.0 |
Humbertda/TP-AG51 | src/main/java/com/humbertdany/tpproject/util/binarystack/v1/BinaryStack.java | 3285 | package com.humbertdany.tpproject.util.binarystack.v1;
import com.humbertdany.tpproject.util.binarystack.ABinaryStack;
import com.humbertdany.tpproject.util.factory.ArrayFactory;
/**
* @deprecated
* @author dhumbert
*/
public class BinaryStack<T extends Node> extends ABinaryStack<T> {
public final static int ORIENTATION_RIGHT = 1;
public final static int ORIENTATION_LEFT = -1;
private T root;
public BinaryStack(final ArrayFactory<T> factory, final T root) {
super(factory);
this.root = root;
}
public void add(final T parent, final T child, final int orientation) {
switch (orientation) {
case BinaryStack.ORIENTATION_LEFT:
parent.setLeft(child);
break;
case BinaryStack.ORIENTATION_RIGHT:
parent.setRight(child);
break;
}
}
/**
* Return true if item is one of the items in the binary sort binarystack to which
* root points. Return false if not.
*/
public boolean contains(final T item) {
return this.treeContains(this.root, item);
}
private boolean treeContains(final Node root, final Node item) {
if (root == null) {
// Tree is empty, so it certainly doesn't contain item.
return false;
} else if (item.equals(root)) {
// Yes, the item has been found in the root node.
return true;
} else if (item.greaterThen(root)) { // TODO make sure this is the right order
// If the item occurs, it must be in the left subtree.
return treeContains(root.getLeft(), item);
} else {
// If the item occurs, it must be in the right subtree.
return treeContains(root.getRight(), item);
}
}
/**
* Print all the items in the binarystack to which root points. The item in the
* left subtree is printed first, followed by the items in the right subtree
* and then the item in the root node.
*/
public void printPostOrder() {
System.out.println("BinaryStack print:");
this.postOrderPrint(root);
System.out.println("--end");
}
private void postOrderPrint(final Node root) {
if (root != null) { // (Otherwise, there's nothing to print.)
postOrderPrint(root.getLeft()); // Print items in left subtree.
postOrderPrint(root.getRight()); // Print items in right subtree.
System.out.print(root.getKey() + " "); // Print the root item.
}
}
/**
* Print all the items in the binarystack to which root points. The item in the
* left subtree is printed first, followed by the item in the root node and
* then the items in the right subtree.
*/
public void printInOrder() {
System.out.println("BinaryStack print:");
this.inOrderPrint(root);
System.out.println("--end");
}
private void inOrderPrint(final Node root) {
if (root != null) { // (Otherwise, there's nothing to print.)
inOrderPrint(root.getLeft()); // Print items in left subtree.
System.out.print(root.getKey() + " "); // Print the root item.
inOrderPrint(root.getRight()); // Print items in right subtree.
}
}
/**
* Return root element
*/
public T getRoot(){
return this.root;
}
@Override
public T deleteMin() {
return null; // TODO
}
@Override
public T getMin() {
return null; // TODO
}
@Override
public void insert(T t) {
// TODO
}
}
| gpl-3.0 |
GerardMundo/jDRQL | src/test/java/name/gerardmundo/jdrql/integration/datastructures/BigDecimalElements.java | 2668 | package name.gerardmundo.jdrql.integration.datastructures;
import java.math.BigDecimal;
public class BigDecimalElements {
private BigDecimal elem1;
private BigDecimal elem2;
private BigDecimal elem3;
private BigDecimal elem4;
private BigDecimal elem5;
private BigDecimal elem6;
private BigDecimal elem7;
private BigDecimal elem8;
private BigDecimal elem9;
private BigDecimal elem10;
private BigDecimal elem11;
private BigDecimal elem12;
private BigDecimal elem13;
private BigDecimal elem14;
public BigDecimal getElem1() {
return elem1;
}
public void setElem1(BigDecimal elem1) {
this.elem1 = elem1;
}
public BigDecimal getElem2() {
return elem2;
}
public void setElem2(BigDecimal elem2) {
this.elem2 = elem2;
}
public BigDecimal getElem3() {
return elem3;
}
public void setElem3(BigDecimal elem3) {
this.elem3 = elem3;
}
public BigDecimal getElem4() {
return elem4;
}
public void setElem4(BigDecimal elem4) {
this.elem4 = elem4;
}
public BigDecimal getElem5() {
return elem5;
}
public void setElem5(BigDecimal elem5) {
this.elem5 = elem5;
}
public BigDecimal getElem6() {
return elem6;
}
public void setElem6(BigDecimal elem6) {
this.elem6 = elem6;
}
public BigDecimal getElem7() {
return elem7;
}
public void setElem7(BigDecimal elem7) {
this.elem7 = elem7;
}
public BigDecimal getElem8() {
return elem8;
}
public void setElem8(BigDecimal elem8) {
this.elem8 = elem8;
}
public BigDecimal getElem9() {
return elem9;
}
public void setElem9(BigDecimal elem9) {
this.elem9 = elem9;
}
public BigDecimal getElem10() {
return elem10;
}
public void setElem10(BigDecimal elem10) {
this.elem10 = elem10;
}
public BigDecimal getElem11() {
return elem11;
}
public void setElem11(BigDecimal elem11) {
this.elem11 = elem11;
}
public BigDecimal getElem12() {
return elem12;
}
public void setElem12(BigDecimal elem12) {
this.elem12 = elem12;
}
public BigDecimal getElem13() {
return elem13;
}
public void setElem13(BigDecimal elem13) {
this.elem13 = elem13;
}
public BigDecimal getElem14() {
return elem14;
}
public void setElem14(BigDecimal elem14) {
this.elem14 = elem14;
}
}
| gpl-3.0 |
Psep/beneficiosweb | src/main/java/cl/jbug/jbpm/beneficiosweb/mbean/BandejaTareasBean.java | 5161 | /*
* Copyright (C) 2015 Pablo Sepúlveda P. (psep_AT_ti-nova_dot_cl)
*
* This file is part of the beneficiosweb.
* beneficiosweb 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.
*
* beneficiosweb 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 beneficiosweb. If not, see <http://www.gnu.org/licenses/>.
*/
package cl.jbug.jbpm.beneficiosweb.mbean;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.inject.Inject;
import org.jboss.logging.Logger;
import org.kie.api.task.model.TaskSummary;
import cl.jbug.jbpm.beneficios.Solicitante;
import cl.jbug.jbpm.beneficiosweb.dao.JbpmDAO;
import cl.jbug.jbpm.beneficiosweb.utils.GenericUtils;
/**
* @author psep
*
*/
@ManagedBean(name = "bandejaTareasBean")
@SessionScoped
public class BandejaTareasBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger
.getLogger(BandejaTareasBean.class);
@Inject
private JbpmDAO jbpmDAO;
private List<TaskSummary> tasks;
private TaskSummary tareaGestionada;
private boolean panelGestion;
private boolean panelObservaciones;
private Solicitante solicitante;
private String observaciones;
@PostConstruct
private void init() {
logger.info("postconstruct");
GenericUtils.removeManagedBean("solicitudBean");
this.panelGestion = false;
this.panelObservaciones = false;
this.observaciones = null;
this.tasks = this.jbpmDAO.listTasksByPotencialOwner();
}
/**
* @param task
*/
public void gestionarAction(TaskSummary task) {
this.tareaGestionada = task;
Solicitante s = this.jbpmDAO.getSolicitante(task.getProcessInstanceId());
if (s == null) {
this.solicitante = new Solicitante();
} else {
this.solicitante = s;
}
this.panelGestion = true;
}
/**
*
*/
public void aceptarAction() {
logger.info("aceptar");
try {
this.completeEvaluacion(true);
this.disabledPaneles();
} catch (Exception e) {
logger.error(e, e);
}
}
/**
*
*/
public void rechazarAction() {
logger.info("rechazar");
try {
this.completeEvaluacion(false);
this.tasks.remove(this.tareaGestionada);
List<TaskSummary> _tasks = this.jbpmDAO.listTasksByPotencialOwner();
logger.info(_tasks.size());
Iterator<TaskSummary> it = _tasks.iterator();
while (it.hasNext()) {
TaskSummary task = it.next();
if (task.getProcessInstanceId().equals(
this.tareaGestionada.getProcessInstanceId())) {
this.tareaGestionada = task;
logger.info("nueva id: " + this.tareaGestionada.getId());
break;
}
}
this.panelGestion = false;
this.panelObservaciones = true;
} catch (Exception e) {
logger.error(e, e);
}
}
/**
*
*/
public void cancelarAction() {
this.tareaGestionada = null;
this.panelGestion = false;
this.solicitante = null;
}
/**
*
*/
public void enviarObservaciones() {
try {
logger.info("obs: " + this.observaciones);
Map<String, Object> params = new HashMap<String, Object>();
params.put("_observaciones", this.observaciones);
this.jbpmDAO.completeTask(this.tareaGestionada.getId(), params);
this.panelObservaciones = false;
} catch (Exception e) {
logger.error(e, e);
}
}
/**
* @param evaluacion
* @throws MalformedURLException
*/
private void completeEvaluacion(boolean evaluacion)
throws MalformedURLException {
Map<String, Object> params = new HashMap<String, Object>();
params.put("_evaluacion", evaluacion);
this.jbpmDAO.completeTask(this.tareaGestionada.getId(), params);
}
/**
*
*/
private void disabledPaneles() {
this.tasks.remove(this.tareaGestionada);
this.cancelarAction();
}
public boolean isPanelGestion() {
return panelGestion;
}
public void setPanelGestion(boolean panelGestion) {
this.panelGestion = panelGestion;
}
public boolean isPanelObservaciones() {
return panelObservaciones;
}
public void setPanelObservaciones(boolean panelObservaciones) {
this.panelObservaciones = panelObservaciones;
}
public String getObservaciones() {
return observaciones;
}
public void setObservaciones(String observaciones) {
this.observaciones = observaciones;
}
public List<TaskSummary> getTasks() {
return tasks;
}
public void setTasks(List<TaskSummary> tasks) {
this.tasks = tasks;
}
public Solicitante getSolicitante() {
return solicitante;
}
public void setSolicitante(Solicitante solicitante) {
this.solicitante = solicitante;
}
}
| gpl-3.0 |
bigbig6/TVHClient | src/org/tvheadend/tvhclient/adapter/GenreColorDialogAdapter.java | 1571 | package org.tvheadend.tvhclient.adapter;
import java.util.List;
import org.tvheadend.tvhclient.model.GenreColorDialogItem;
import org.tvheadend.tvhclient.R;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class GenreColorDialogAdapter extends ArrayAdapter<GenreColorDialogItem> {
private LayoutInflater inflater;
public ViewHolder holder = null;
public GenreColorDialogAdapter(Activity context, final List<GenreColorDialogItem> items) {
super(context, R.layout.genre_color_dialog, items);
this.inflater = context.getLayoutInflater();
}
public class ViewHolder {
public TextView color;
public TextView genre;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.genre_color_dialog, null);
holder = new ViewHolder();
holder.color = (TextView) view.findViewById(R.id.color);
holder.genre = (TextView) view.findViewById(R.id.genre);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
GenreColorDialogItem item = getItem(position);
if (item != null) {
holder.color.setBackgroundColor(item.color);
holder.genre.setText(item.genre);
}
return view;
}
}
| gpl-3.0 |
dominiks/uristmapsj | src/main/java/org/uristmaps/data/StructureGroup.java | 1617 | package org.uristmaps.data;
import java.util.LinkedList;
import java.util.List;
/**
* A group of structures of the same type.
*/
public class StructureGroup {
private int id;
private String type;
private List<Coord2> points = new LinkedList<>();
/**
* Empty constructor for kryo.
*/
public StructureGroup() {}
/**
* Create a new group with the given id and type.
* @param id
* @param type
*/
public StructureGroup(int id, String type) {
this.id = id;
this.type = type;
}
/**
* Get the list of points that belong to this group.
* @return
*/
public List<Coord2> getPoints() {
return points;
}
/**
* Add a point to this group.
* @param p
*/
public void addPoint(Coord2 p) {
points.add(p);
}
/**
* Calculate the center coordinate of this group.
* @return
*/
public Coord2 getCenter() {
int minX = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int minY = Integer.MAX_VALUE;
int maxY = Integer.MIN_VALUE;
for (Coord2 p : points) {
if (p.X() < minX) minX = p.X();
if (p.X() > maxX) maxX = p.X();
if (p.Y() < minY) minY = p.Y();
if (p.Y() > maxY) maxY = p.Y();
}
return new Coord2((minX + maxX) / 2, (minY + maxY) / 2);
}
public String getType() {
return type;
}
public Integer getId() {
return id;
}
@Override
public String toString() {
return getType() + "#" + getId();
}
}
| gpl-3.0 |
marvisan/HadesFIX | Model/src/main/java/net/hades/fix/message/type/AllocType.java | 2303 | /*
* Copyright (c) 2006-2016 Marvisan Pty. Ltd. All rights reserved.
* Use is subject to license terms.
*/
/*
* AllocType.java
*
* $Id: AllocType.java,v 1.4 2011-04-19 12:13:34 vrotaru Exp $
*/
package net.hades.fix.message.type;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* Type or purpose of an Allocation message.
*
* @author <a href="mailto:support@marvisan.com">Support Team</a>
* @version $Revision: 1.4 $
* @created 27/09/2009, 10:37:33 AM
*/
@XmlType
@XmlEnum(Integer.class)
public enum AllocType {
@XmlEnumValue("1") Calculated (1),
@XmlEnumValue("2") Preliminary (2),
@XmlEnumValue("3") SellsideCalcuWithPreliminary (3),
@XmlEnumValue("4") SellsideCalcuwithoutPreliminary (4),
@XmlEnumValue("5") ReadyToBookSingleOrder (5),
@XmlEnumValue("6") ReadyToBookCombinedSet (6),
@XmlEnumValue("7") WarehouseInstruction (7),
@XmlEnumValue("8") RequestToIntermediary (8),
@XmlEnumValue("9") Accept (9),
@XmlEnumValue("10") Reject (10),
@XmlEnumValue("11") AcceptPending (11),
@XmlEnumValue("12") IncompleteGroup (12),
@XmlEnumValue("13") CompleteGroup (13),
@XmlEnumValue("14") ReversalPending (14);
private static final long serialVersionUID = 1L;
private int value;
private static final Map<String, AllocType> stringToEnum = new HashMap<String, AllocType>();
static {
for (AllocType tag : values()) {
stringToEnum.put(String.valueOf(tag.getValue()), tag);
}
}
/** Creates a new instance of AllocType */
AllocType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static AllocType valueFor(int value) {
return stringToEnum.get(String.valueOf(value));
}
}
| gpl-3.0 |
Wehavecookies56/Kingdom-Keys | kk_common/wehavecookies56/kk/item/keychains/ItemRejectionOfFateChain.java | 1505 | package wehavecookies56.kk.item.keychains;
import java.util.List;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import wehavecookies56.kk.item.AddedItems;
import wehavecookies56.kk.item.ItemKingdomKeys;
import wehavecookies56.kk.item.keyblades.ItemRejectionOfFate;
import wehavecookies56.kk.lib.Reference;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemRejectionOfFateChain extends ItemKingdomKeys{
public ItemRejectionOfFateChain(int id) {
super(id);
}
public void registerIcons(IconRegister par1IconRegister) {
itemIcon = par1IconRegister.registerIcon(Reference.MOD_ID + ":" + this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf(".")+1));
}
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack itemStack, EntityPlayer player, List dataList, boolean bool){
dataList.add("Kingdom Hearts 358/2 Days");
}
public void onUpdate(ItemStack par1ItemStack, World par2World, Entity par3Entity, int par4, boolean par5)
{
EntityPlayer player = (EntityPlayer)par3Entity;
if (ItemRejectionOfFate.keyPressed)
{
ItemRejectionOfFate.keyPressed = false;
if (player.getHeldItem() != null && player.getHeldItem().itemID == AddedItems.K55c.itemID)
{
}
}
}
} | gpl-3.0 |
glycoinfo/eurocarbdb | application/ResourcesDB/src/org/eurocarbdb/resourcesdb/monosaccharide/BasetypeConversion.java | 18975 | /*
* EuroCarbDB, a framework for carbohydrate bioinformatics
*
* Copyright (c) 2006-2009, Eurocarb project, or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
* A copy of this license accompanies this distribution in the file LICENSE.txt.
*
* 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.
*
* Last commit: $Rev: 1210 $ by $Author: glycoslave $ on $Date:: 2009-06-12 #$
*/
package org.eurocarbdb.resourcesdb.monosaccharide;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.eurocarbdb.resourcesdb.Config;
import org.eurocarbdb.resourcesdb.ResourcesDbException;
import org.eurocarbdb.resourcesdb.glycoconjugate_derived.*;
import org.eurocarbdb.resourcesdb.template.TemplateContainer;
/**
* Routines to convert monosaccharide basetypes of the EUROCarbDB sugar object model to ones of the MonoSaccharideDB object model and vice versa
* @author Thomas Luetteke
*
*/
public class BasetypeConversion {
public static Monosaccharide eurcarbdbToMsdb(EcdbMonosaccharide eurocarbdbMs, Config conf, TemplateContainer container) throws ResourcesDbException {
Monosaccharide msdbMs = new Monosaccharide(conf, container);
eurocarbdbToMsdb(eurocarbdbMs, msdbMs);
return msdbMs;
}
public static void eurocarbdbToMsdb(EcdbMonosaccharide eurocarbdbMs, Monosaccharide msdbMs) throws ResourcesDbException {
msdbMs.setSize(eurocarbdbMs.getSuperclass().getNumberOfC());
int ringStart = eurocarbdbMs.getRingStart();
if(ringStart == EcdbMonosaccharide.OPEN_CHAIN) {
ringStart = Basetype.OPEN_CHAIN;
} else if(ringStart == EcdbMonosaccharide.UNKNOWN_RING) {
ringStart = Basetype.UNKNOWN_RING;
}
msdbMs.setRingStartNoAdjustment(ringStart);
msdbMs.setDefaultCarbonylPosition(ringStart);
int ringEnd = eurocarbdbMs.getRingEnd();
if(ringEnd == EcdbMonosaccharide.OPEN_CHAIN) {
ringEnd = Basetype.OPEN_CHAIN;
} else if(ringEnd == EcdbMonosaccharide.UNKNOWN_RING) {
ringEnd = Basetype.UNKNOWN_RING;
}
msdbMs.setRingEnd(ringEnd);
msdbMs.setAnomer(anomerEurocarbdbToMsdb(eurocarbdbMs.getAnomer()));
//*** convert modifications: ***
copyCoreModificationsFromEurocarbdbToMsdb(eurocarbdbMs, msdbMs);
//*** get Stereocode from basetypes + modifications: ***
String stereo = BasetypeConversion.getStereocodeFromBasetypeList(eurocarbdbMs.getBaseTypeList());
if(stereo.length() > 0) {
stereo = Stereocode.expandChiralonlyStereoString(stereo, msdbMs);
} else { //*** residue is superclass only ***
stereo = Stereocode.getSuperclassStereostring(msdbMs.getSize());
stereo = Stereocode.markNonchiralPositionsInStereoString(stereo, msdbMs);
}
msdbMs.setStereoStr(stereo);
msdbMs.setAnomerInStereocode();
}
public static org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbMonosaccharide msdbToEurocarbdb(Monosaccharide msdbMs) throws GlycoconjugateException {
//*** create new object and set anomeric and superclass: ***
org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbMonosaccharide eurocarbdbMs = new org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbMonosaccharide(anomerMsdbToEurocarbdb(msdbMs.getAnomer()), org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbSuperclass.forCAtoms(msdbMs.getSize()));
int ringStart = msdbMs.getRingStart();
if(ringStart == Basetype.OPEN_CHAIN) {
ringStart = EcdbMonosaccharide.OPEN_CHAIN;
} else if(ringStart == Basetype.UNKNOWN_RING) {
ringStart = EcdbMonosaccharide.UNKNOWN_RING;
}
int ringEnd = msdbMs.getRingEnd();
if(ringEnd == Basetype.OPEN_CHAIN) {
ringEnd = EcdbMonosaccharide.OPEN_CHAIN;
} else if(ringEnd == Basetype.UNKNOWN_RING) {
ringEnd = EcdbMonosaccharide.UNKNOWN_RING;
}
if(ringEnd == EcdbMonosaccharide.UNKNOWN_RING) {
ringStart = EcdbMonosaccharide.UNKNOWN_RING;
}
if(ringEnd == EcdbMonosaccharide.OPEN_CHAIN) {
ringStart = EcdbMonosaccharide.OPEN_CHAIN;
}
eurocarbdbMs.setRing(ringStart, ringEnd);
//*** set basetypes: ***
ArrayList<EcdbBaseType> basetypeList = BasetypeConversion.getEurocarbdbMsBasetypesFromMsdbMonosaccharide(msdbMs);
for(Iterator<EcdbBaseType> iter = basetypeList.iterator(); iter.hasNext();) {
eurocarbdbMs.addBaseType(iter.next());
}
//*** convert modifications: ***
for(Iterator<CoreModification> iter = msdbMs.getCoreModifications().iterator(); iter.hasNext();) {
CoreModification msdbMod = iter.next();
//*** check for modifications that are substituents in eurocarbdb: ***
//*** (conversion is handled in MonosaccharideConverter.convertMonosaccharide()) ***
if(msdbMod.getTemplate().equals(CoreModificationTemplate.ANHYDRO)) {
continue; //*** anhydro is treated as substituent in eurocarbdb ***
}
if(msdbMod.getTemplate().equals(CoreModificationTemplate.LACTONE)) {
continue; //*** lactone is treated as substituent in eurocarbdb ***
}
if(msdbMod.getTemplate().equals(CoreModificationTemplate.EPOXY)) {
continue; //*** epoxy is treated as substituent in eurocarbdb ***
}
eurocarbdbMs.addModification(BasetypeConversion.ModificationMsdbToEurocarbdb(msdbMod));
}
return(eurocarbdbMs);
}
public static org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbAnomer anomerMsdbToEurocarbdb(Anomer anom) {
if(Anomer.ALPHA.equals(anom)) {
return(org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbAnomer.Alpha);
}
if(Anomer.BETA.equals(anom)) {
return(org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbAnomer.Beta);
}
if(Anomer.OPEN_CHAIN.equals(anom) || Anomer.NONE.equals(anom)) {
return(org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbAnomer.OpenChain);
}
return(org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbAnomer.Unknown);
}
public static Anomer anomerEurocarbdbToMsdb(org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbAnomer anom) {
if(anom.equals(org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbAnomer.Alpha)) {
return(Anomer.ALPHA);
}
if(anom.equals(org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbAnomer.Beta)) {
return(Anomer.BETA);
}
if(anom.equals(org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbAnomer.OpenChain)) {
//TODO: distinguish between openChain and no anomer in ring (would need entire monosaccharide, not just anomer)
return(Anomer.OPEN_CHAIN);
}
return(Anomer.UNKNOWN);
}
private static HashMap<String, EcdbBaseType> eurocarbBasetypesByStereocodeMap = null;
private static void fillEurocarbBasetypeByStereocodeMap() {
BasetypeConversion.eurocarbBasetypesByStereocodeMap = new HashMap<String, EcdbBaseType>();
for(EcdbBaseType bt : EcdbBaseType.values()) {
BasetypeConversion.eurocarbBasetypesByStereocodeMap.put(bt.getStereo(), bt);
}
}
private static EcdbBaseType getEurocarbBasetypeByStereoString(String stereo) throws ResourcesDbException {
EcdbBaseType base = null;
if(Stereocode.stereoStringHasRelativePosition(stereo)) {
if(Stereocode.stereoStringContainsAbsoluteAndRelative(stereo)) {
throw new MonosaccharideException("Cannot get EurocarbDB basetype from a stereocode string that contains both absolute and relative configurations: " + stereo);
}
return(getEuroCarbBasetypeByRelativeStereostring(stereo));
} else {
base = BasetypeConversion.eurocarbBasetypesByStereocodeMap.get(stereo);
}
if(base == null) {
throw new ResourcesDbException("Cannot get EurocarbDB basetype from stereocode string " + stereo);
}
return(base);
}
private static EcdbBaseType getEuroCarbBasetypeByRelativeStereostring(String rStereo) throws ResourcesDbException {
String aStereo = Stereocode.relativeToAbsolute(rStereo);
EcdbBaseType aBase = BasetypeConversion.getEurocarbBasetypeByStereoString(aStereo);
try {
EcdbBaseType rBase = EcdbBaseType.forName("x" + aBase.getName().substring(1));
return(rBase);
} catch(GlycoconjugateException ge) {
ResourcesDbException me = new ResourcesDbException("Cannot get EurocarbDB basetype from stereocode string " + rStereo);
me.initCause(ge);
throw me;
}
}
/**
* @param msdbMs
* @return
* @throws GlycoconjugateException
*/
public static ArrayList<EcdbBaseType> getEurocarbdbMsBasetypesFromMsdbMonosaccharide(Monosaccharide msdbMs) throws GlycoconjugateException {
if(BasetypeConversion.eurocarbBasetypesByStereocodeMap == null) {
BasetypeConversion.fillEurocarbBasetypeByStereocodeMap();
}
ArrayList<EcdbBaseType> basetypeList = new ArrayList<EcdbBaseType>();
try {
String stereo = msdbMs.getStereoStr();
if(msdbMs.getRingStart() > 1) { //*** anomeric center not at position1 => mask potential anomeric stereochemistry ***
stereo = Stereocode.setPositionInStereoString(stereo, StereoConfiguration.Nonchiral.getStereosymbol(), msdbMs.getRingStart());
}
stereo = stereo.substring(1); //*** remove position1 (always nonchiral or anomeric) ***
stereo = stereo.replaceAll("" + StereoConfiguration.Nonchiral.getStereosymbol(), "");
if(!stereo.replaceAll("" + StereoConfiguration.Unknown.getStereosymbol(), "").equals("")) { //*** residue is not just a superclass ***
if(stereo.contains("" + StereoConfiguration.Unknown.getStereosymbol())) {
throw new ResourcesDbException("MonosaccharideDB stereocode contains unknown configurations - cannot generate basetype list for EuroCarbDB monosaccharide from that.");
}
//*** translate stereocenters into basetype(s): ***
while(stereo.length() > 0) {
if(stereo.length() > 4) {
basetypeList.add(0, BasetypeConversion.getEurocarbBasetypeByStereoString(stereo.substring(0, 4)));
stereo = stereo.substring(4);
} else {
basetypeList.add(0, BasetypeConversion.getEurocarbBasetypeByStereoString(stereo));
stereo = "";
}
}
}
} catch(ResourcesDbException me) {
throw new GlycoconjugateException("Error in translating stereocode to basetype list: " + me.getMessage());
}
return(basetypeList);
}
public static String getStereocodeFromBasetypeList(ArrayList<EcdbBaseType> basetypeList) throws ResourcesDbException {
String stereo = "";
for(Iterator<EcdbBaseType> iter = basetypeList.iterator(); iter.hasNext();) {
EcdbBaseType basetype = iter.next();
String tmpStereo = basetype.getStereo();
if(tmpStereo.contains("*")) {
String basename = basetype.getName();
try {
basetype = EcdbBaseType.forName("d" + basename.substring(1));
tmpStereo = Stereocode.absoluteToRelative(basetype.getStereo());
} catch(GlycoconjugateException ge) {
ResourcesDbException me = new ResourcesDbException("GetStereocodeFromBasetypeList: Cannot get absolute equivalent for relative basetype " + basename + " (d" + basename.substring(1) + ")");
me.initCause(ge);
throw me;
}
}
stereo = tmpStereo + stereo;
}
return(stereo);
}
public static void copyCoreModificationsFromEurocarbdbToMsdb(org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbMonosaccharide eurocarbdbMs, Monosaccharide msdbMs) throws ResourcesDbException {
ArrayList<org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbModification> eurocarbdbModificationList;
eurocarbdbModificationList = eurocarbdbMs.getModificationList();
for(Iterator<org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbModification> iter = eurocarbdbModificationList.iterator(); iter.hasNext();) {
org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbModification eurocarbMod = iter.next();
if(eurocarbMod.getName().equals(EcdbModificationType.ALDI.getName())) {
if(eurocarbMod.getPositionOne() != 1) {
throw new ResourcesDbException("Alditol position other than one in EuroCarbDB monosaccharide");
}
msdbMs.setAlditol(true);
continue;
}
CoreModification msdbCoremod = ModificationEurocarbdbToMsdb(eurocarbMod);
//TO DO: take into account, that multiple keto modifications might be given in a residue whithout a defined ring start
if(msdbCoremod.getTemplate().equals(CoreModificationTemplate.KETO) && (msdbMs.getDefaultCarbonylPosition() == Basetype.UNKNOWN_RING)) {
msdbMs.setDefaultCarbonylPosition(msdbCoremod.getPosition1().get(0));
}
msdbMs.addCoreModification(msdbCoremod);
}
}
public static CoreModification ModificationEurocarbdbToMsdb(org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbModification eurocarbdbMod) throws MonosaccharideException {
CoreModification msdbMod = new CoreModification();
if(eurocarbdbMod.getName().equals(EcdbModificationType.DEOXY.getName())) {
msdbMod.setModification(CoreModificationTemplate.DEOXY, eurocarbdbMod.getPositionOne());
} else if(eurocarbdbMod.getName().equals(EcdbModificationType.ACID.getName())) {
msdbMod.setModification(CoreModificationTemplate.ACID, eurocarbdbMod.getPositionOne());
} else if(eurocarbdbMod.getName().equals(EcdbModificationType.KETO.getName())) {
msdbMod.setModification(CoreModificationTemplate.KETO, eurocarbdbMod.getPositionOne());
} else if(eurocarbdbMod.getName().equals(EcdbModificationType.DOUBLEBOND.getName())) {
msdbMod.setDivalentModification(CoreModificationTemplate.EN, eurocarbdbMod.getPositionOne(), eurocarbdbMod.getPositionOne() + 1);
} else if(eurocarbdbMod.getName().equals(EcdbModificationType.UNKNOWN_BOUBLEBOND.getName())) {
msdbMod.setDivalentModification(CoreModificationTemplate.ENX, eurocarbdbMod.getPositionOne(), eurocarbdbMod.getPositionOne() + 1);
} else if(eurocarbdbMod.getName().equals(EcdbModificationType.SP2_HYBRID.getName())) {
msdbMod.setModification(CoreModificationTemplate.SP2, eurocarbdbMod.getPositionOne());
} else if(eurocarbdbMod.getName().equals(EcdbModificationType.GEMINAL.getName())) {
throw new MonosaccharideException("Geminal residues not yet supported.");
//TODO: implement geminal in msdb
} else if(eurocarbdbMod.getName().equals(EcdbModificationType.ANHYDRO.getName())) {
msdbMod.setDivalentModification(CoreModificationTemplate.ANHYDRO, eurocarbdbMod.getPositionOne(), eurocarbdbMod.getPositionTwo());
} else {
throw new MonosaccharideException("cannot convert eurocarbdb core modification " + eurocarbdbMod.getName());
}
return(msdbMod);
}
public static org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbModification ModificationMsdbToEurocarbdb(CoreModification msdbMod) throws GlycoconjugateException {
org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbModification eurocarbdbMod = null;
if(msdbMod.getTemplate().equals(CoreModificationTemplate.DEOXY)) {
eurocarbdbMod = new org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbModification(EcdbModificationType.DEOXY.getName(), msdbMod.getIntValuePosition1());
} else if(msdbMod.getTemplate().equals(CoreModificationTemplate.EN)) {
eurocarbdbMod = new org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbModification(EcdbModificationType.DOUBLEBOND.getName(), msdbMod.getIntValuePosition1(), msdbMod.getIntValuePosition2());
} else if(msdbMod.getTemplate().equals(CoreModificationTemplate.ENX)) {
eurocarbdbMod = new org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbModification(EcdbModificationType.UNKNOWN_BOUBLEBOND.getName(), msdbMod.getIntValuePosition1(), msdbMod.getIntValuePosition2());
} else if(msdbMod.getTemplate().equals(CoreModificationTemplate.ACID)) {
eurocarbdbMod = new org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbModification(EcdbModificationType.ACID.getName(), msdbMod.getIntValuePosition1());
} else if(msdbMod.getTemplate().equals(CoreModificationTemplate.KETO)) {
eurocarbdbMod = new org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbModification(EcdbModificationType.KETO.getName(), msdbMod.getIntValuePosition1());
} else if(msdbMod.getTemplate().equals(CoreModificationTemplate.SP2)) {
eurocarbdbMod = new org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbModification(EcdbModificationType.SP2_HYBRID.getName(), msdbMod.getIntValuePosition1());
} else if(msdbMod.getTemplate().equals(CoreModificationTemplate.ALDITOL)) {
eurocarbdbMod = new org.eurocarbdb.resourcesdb.glycoconjugate_derived.EcdbModification(EcdbModificationType.ALDI.getName(), msdbMod.getIntValuePosition1());
} else if(msdbMod.getTemplate().equals(CoreModificationTemplate.YN)) {
throw new GlycoconjugateException("Core modification 'Yn' not defined for EuroCarbDB monosaccharides.");
} else {
throw new GlycoconjugateException("Unknown msdb core modification: " + msdbMod.getName());
}
return(eurocarbdbMod);
}
}
| gpl-3.0 |
NathanAdhitya/Slimefun4 | src/me/mrCookieSlime/Slimefun/Objects/SlimefunItem/machines/FoodFabricator.java | 1605 | package me.mrCookieSlime.Slimefun.Objects.SlimefunItem.machines;
import me.mrCookieSlime.Slimefun.Lists.RecipeType;
import me.mrCookieSlime.Slimefun.Lists.SlimefunItems;
import me.mrCookieSlime.Slimefun.Objects.Category;
import me.mrCookieSlime.Slimefun.Objects.SlimefunItem.abstractItems.AContainer;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
public abstract class FoodFabricator extends AContainer {
public FoodFabricator(Category category, ItemStack item, String name, RecipeType recipeType, ItemStack[] recipe) {
super(category, item, name, recipeType, recipe);
}
@Override
public void registerDefaultRecipes() {
registerRecipe(12, new ItemStack[] {SlimefunItems.CAN, new ItemStack(Material.WHEAT)}, new ItemStack[] {SlimefunItems.WHEAT_ORGANIC_FOOD});
registerRecipe(12, new ItemStack[] {SlimefunItems.CAN, new ItemStack(Material.CARROT)}, new ItemStack[] {SlimefunItems.CARROT_ORGANIC_FOOD});
registerRecipe(12, new ItemStack[] {SlimefunItems.CAN, new ItemStack(Material.POTATO)}, new ItemStack[] {SlimefunItems.POTATO_ORGANIC_FOOD});
registerRecipe(12, new ItemStack[] {SlimefunItems.CAN, new ItemStack(Material.BEETROOT)}, new ItemStack[] {SlimefunItems.BEETROOT_ORGANIC_FOOD});
registerRecipe(12, new ItemStack[] {SlimefunItems.CAN, new ItemStack(Material.MELON)}, new ItemStack[] {SlimefunItems.MELON_ORGANIC_FOOD});
registerRecipe(12, new ItemStack[] {SlimefunItems.CAN, new ItemStack(Material.APPLE)}, new ItemStack[] {SlimefunItems.APPLE_ORGANIC_FOOD});
}
@Override
public String getMachineIdentifier() {
return "FOOD_FABRICATOR";
}
}
| gpl-3.0 |
ARIG-Robotique/robots | robot-system-lib-parent/robot-system-lib-core/src/main/java/org/arig/robot/communication/socket/ecran/UpdatePhotoQuery.java | 498 | package org.arig.robot.communication.socket.ecran;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.arig.robot.communication.socket.AbstractQueryWithData;
import org.arig.robot.communication.socket.ecran.enums.EcranAction;
import org.arig.robot.model.ecran.EcranPhoto;
@Data
@EqualsAndHashCode(callSuper = true)
public class UpdatePhotoQuery extends AbstractQueryWithData<EcranAction, EcranPhoto> {
public UpdatePhotoQuery() {
super(EcranAction.UPDATE_PHOTO);
}
}
| gpl-3.0 |
Mrkwtkr/shinsei | src/main/java/com/megathirio/shinsei/item/powder/ItemFerrosiliconPowder.java | 333 | package com.megathirio.shinsei.item.powder;
import com.megathirio.shinsei.item.PowderShinsei;
import com.megathirio.shinsei.reference.Names;
public class ItemFerrosiliconPowder extends PowderShinsei {
public ItemFerrosiliconPowder(){
super();
this.setUnlocalizedName(Names.Powders.FERROSILICON_POWDER);
}
}
| gpl-3.0 |
Skylark95/RedditImageDownloader | RedditImageDownloader/src/main/java/com/skylark95/redditdownloader/core/RedditUserExpection.java | 445 | package com.skylark95.redditdownloader.core;
public class RedditUserExpection extends Exception {
private static final long serialVersionUID = 2136184482961103987L;
public RedditUserExpection() {
super();
}
public RedditUserExpection(String message) {
super(message);
}
public RedditUserExpection(Throwable cause) {
super(cause);
}
public RedditUserExpection(String message, Throwable cause) {
super(message, cause);
}
}
| gpl-3.0 |
Mikescher/jClipCorn | src/main/de/jClipCorn/util/parser/StringSpecParser.java | 3120 | package de.jClipCorn.util.parser;
import de.jClipCorn.util.exceptions.CCFormatException;
import de.jClipCorn.util.exceptions.StringSpecFormatException;
import java.util.HashSet;
import java.util.Map;
public class StringSpecParser {
public static String build(String fmt, StringSpecSupplier supplier) {
HashSet<Character> specifier = supplier.getAllStringSpecifier();
StringBuilder repbuilder = new StringBuilder();
char actualCounter = '\0';
int counter = 0;
char c;
for (int p = 0;p<fmt.length();p++) {
c = fmt.charAt(p);
if (specifier.contains(c)) {
if (counter == 0 || actualCounter == c) {
counter++;
actualCounter = c;
} else {
String tmpformat = supplier.resolveStringSpecifier(actualCounter, counter);
if (tmpformat == null) return null;
repbuilder.append(tmpformat);
counter = 1;
actualCounter = c;
}
} else {
if (counter > 0) {
String tmpformat = supplier.resolveStringSpecifier(actualCounter, counter);
if (tmpformat == null) return null;
repbuilder.append(tmpformat);
}
repbuilder.append(c);
counter = 0;
actualCounter = '-';
}
}
if (counter > 0) {
String tmpformat = supplier.resolveStringSpecifier(actualCounter, counter);
if (tmpformat == null) return null;
repbuilder.append(tmpformat);
}
return repbuilder.toString();
}
public static Object parse(String rawData, String fmt, StringSpecSupplier supplier) throws CCFormatException {
Object o = parseInternal(rawData, fmt, supplier);
if (o == null) throw new StringSpecFormatException(rawData, fmt);
return o;
}
public static Object parseOrDefault(String rawData, String fmt, StringSpecSupplier supplier, Object defaultValue) {
Object o = parseInternal(rawData, fmt, supplier);
if (o == null) return defaultValue;
return o;
}
public static boolean testparse(String rawData, String fmt, StringSpecSupplier supplier) {
Object o = parseInternal(rawData, fmt, supplier);
return o != null;
}
public static Object parseInternal(String rawData, String fmt, StringSpecSupplier supplier) {
HashSet<Character> specifier = supplier.getAllStringSpecifier();
Map<Character, Integer> values = supplier.getSpecDefaults();
char c;
int rp = 0;
rawData += '\0';
for (int p = 0;p<fmt.length();p++) {
c = fmt.charAt(p);
while((p+1)<fmt.length() && fmt.charAt(p+1) == fmt.charAt(p) && (specifier.contains(c))) {
p++;
}
if (specifier.contains(c)) {
StringBuilder drep = new StringBuilder(); //$NON-NLS-1$
if (Character.isDigit(rawData.charAt(rp))) {
drep.append(rawData.charAt(rp));
rp++;
} else {
return null;
}
for (; Character.isDigit(rawData.charAt(rp)) ; rp++) {
drep.append(rawData.charAt(rp));
}
values.put(c, Integer.parseInt(drep.toString()));
} else {
if (rawData.charAt(rp) == c) {
rp++;
} else {
return null;
}
}
}
if (rp != rawData.length()-1) return null;
return supplier.createFromParsedData(values);
}
}
| gpl-3.0 |
kabuki5/PopularMovies | app/src/main/java/com/benavides/ramon/popularmovies/adapters/CastCursorAdapter.java | 2058 | package com.benavides.ramon.popularmovies.adapters;
import android.content.Context;
import android.database.Cursor;
import android.speech.tts.TextToSpeech;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.benavides.ramon.popularmovies.R;
import com.benavides.ramon.popularmovies.cviews.RoundedImageView;
import com.benavides.ramon.popularmovies.database.MoviesContract;
import com.squareup.picasso.Picasso;
/**
* Cursor adapter for Reviews Fragment
*/
public class CastCursorAdapter extends CursorAdapter {
private Context mContext;
public CastCursorAdapter(Context context, Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
mContext = context;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_actor, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
view.setTag(viewHolder);
return view;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder vh = ((ViewHolder) view.getTag());
Picasso.with(context).load(cursor.getString(MoviesContract.CastEntry.CAST_COLUMN_PICTURE)).error(R.mipmap.ic_launcher).into(vh.picture);
vh.name.setText(cursor.getString(MoviesContract.ReviewEntry.REVIEWS_COLUMN_AUTHOR));
vh.character.setText(cursor.getString(MoviesContract.ReviewEntry.REVIEWS_COLUMN_CONTENT));
}
static class ViewHolder {
public final RoundedImageView picture;
public final TextView name;
public final TextView character;
public ViewHolder(View view) {
picture = (RoundedImageView) view.findViewById(R.id.item_actor_thumb);
name = (TextView) view.findViewById(R.id.item_actor_name_tev);
character = (TextView)view.findViewById(R.id.item_actor_character_tev);
}
}
}
| gpl-3.0 |
cvtienhoven/graylog-plugin-aggregates | src/main/java/org/graylog/plugins/aggregates/permissions/ReportScheduleRestPermissions.java | 1457 | package org.graylog.plugins.aggregates.permissions;
import com.google.common.collect.ImmutableSet;
import org.graylog2.plugin.security.Permission;
import org.graylog2.plugin.security.PluginPermissions;
import java.util.Collections;
import java.util.Set;
import static org.graylog2.plugin.security.Permission.create;
public class ReportScheduleRestPermissions implements PluginPermissions {
public static final String AGGREGATE_REPORT_SCHEDULES_READ = "aggregate_report_schedules:read";
public static final String AGGREGATE_REPORT_SCHEDULES_CREATE = "aggregate_report_schedules:create";
public static final String AGGREGATE_REPORT_SCHEDULES_UPDATE = "aggregate_report_schedules:update";
public static final String AGGREGATE_REPORT_SCHEDULES_DELETE = "aggregate_report_schedules:delete";
private final ImmutableSet<Permission> permissions = ImmutableSet.of(
create(AGGREGATE_REPORT_SCHEDULES_READ, "Read aggregate report schedules"),
create(AGGREGATE_REPORT_SCHEDULES_CREATE, "Create aggregate report schedules"),
create(AGGREGATE_REPORT_SCHEDULES_UPDATE, "Update aggregate report schedules"),
create(AGGREGATE_REPORT_SCHEDULES_DELETE, "Delete aggregate report schedules")
);
@Override
public Set<Permission> permissions() {
return permissions;
}
@Override
public Set<Permission> readerBasePermissions() {
return Collections.emptySet();
}
} | gpl-3.0 |
AdnanAhmed1/Conversations | src/main/java/eu/siacs/conversations/services/MessageArchiveService.java | 11723 | package eu.siacs.conversations.services;
import android.util.Log;
import android.util.Pair;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.R;
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.generator.AbstractGenerator;
import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded;
import eu.siacs.conversations.xmpp.OnIqPacketReceived;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.stanzas.IqPacket;
public class MessageArchiveService implements OnAdvancedStreamFeaturesLoaded {
private final XmppConnectionService mXmppConnectionService;
private final HashSet<Query> queries = new HashSet<Query>();
private final ArrayList<Query> pendingQueries = new ArrayList<Query>();
public enum PagingOrder {
NORMAL,
REVERSE
};
public MessageArchiveService(final XmppConnectionService service) {
this.mXmppConnectionService = service;
}
private void catchup(final Account account) {
synchronized (this.queries) {
for(Iterator<Query> iterator = this.queries.iterator(); iterator.hasNext();) {
Query query = iterator.next();
if (query.getAccount() == account) {
iterator.remove();
}
}
}
long startCatchup = getLastMessageTransmitted(account);
long endCatchup = account.getXmppConnection().getLastSessionEstablished();
if (startCatchup == 0) {
return;
} else if (endCatchup - startCatchup >= Config.MAM_MAX_CATCHUP) {
startCatchup = endCatchup - Config.MAM_MAX_CATCHUP;
List<Conversation> conversations = mXmppConnectionService.getConversations();
for (Conversation conversation : conversations) {
if (conversation.getMode() == Conversation.MODE_SINGLE && conversation.getAccount() == account && startCatchup > conversation.getLastMessageTransmitted()) {
this.query(conversation,startCatchup);
}
}
}
final Query query = new Query(account, startCatchup, endCatchup);
this.queries.add(query);
this.execute(query);
}
public void catchupMUC(final Conversation conversation) {
if (conversation.getLastMessageTransmitted() < 0 && conversation.countMessages() == 0) {
query(conversation,
0,
System.currentTimeMillis());
} else {
query(conversation,
conversation.getLastMessageTransmitted(),
System.currentTimeMillis());
}
}
private long getLastMessageTransmitted(final Account account) {
Pair<Long,String> pair = mXmppConnectionService.databaseBackend.getLastMessageReceived(account);
return pair == null ? 0 : pair.first;
}
public Query query(final Conversation conversation) {
if (conversation.getLastMessageTransmitted() < 0 && conversation.countMessages() == 0) {
return query(conversation,
0,
System.currentTimeMillis());
} else {
return query(conversation,
conversation.getLastMessageTransmitted(),
conversation.getAccount().getXmppConnection().getLastSessionEstablished());
}
}
public Query query(final Conversation conversation, long end) {
return this.query(conversation,conversation.getLastMessageTransmitted(),end);
}
public Query query(Conversation conversation, long start, long end) {
synchronized (this.queries) {
if (start > end) {
return null;
}
final Query query = new Query(conversation, start, end,PagingOrder.REVERSE);
this.queries.add(query);
this.execute(query);
return query;
}
}
public void executePendingQueries(final Account account) {
List<Query> pending = new ArrayList<>();
synchronized(this.pendingQueries) {
for(Iterator<Query> iterator = this.pendingQueries.iterator(); iterator.hasNext();) {
Query query = iterator.next();
if (query.getAccount() == account) {
pending.add(query);
iterator.remove();
}
}
}
for(Query query : pending) {
this.execute(query);
}
}
private void execute(final Query query) {
final Account account= query.getAccount();
if (account.getStatus() == Account.State.ONLINE) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": running mam query " + query.toString());
IqPacket packet = this.mXmppConnectionService.getIqGenerator().queryMessageArchiveManagement(query);
this.mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
synchronized (MessageArchiveService.this.queries) {
MessageArchiveService.this.queries.remove(query);
if (query.hasCallback()) {
query.callback();
}
}
} else if (packet.getType() != IqPacket.TYPE.RESULT) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": error executing mam: " + packet.toString());
finalizeQuery(query);
}
}
});
} else {
synchronized (this.pendingQueries) {
this.pendingQueries.add(query);
}
}
}
private void finalizeQuery(Query query) {
synchronized (this.queries) {
this.queries.remove(query);
}
final Conversation conversation = query.getConversation();
if (conversation != null) {
conversation.sort();
conversation.setHasMessagesLeftOnServer(query.getMessageCount() > 0);
} else {
for(Conversation tmp : this.mXmppConnectionService.getConversations()) {
if (tmp.getAccount() == query.getAccount()) {
tmp.sort();
}
}
}
if (query.hasCallback()) {
query.callback();
} else {
this.mXmppConnectionService.updateConversationUi();
}
}
public boolean queryInProgress(Conversation conversation, XmppConnectionService.OnMoreMessagesLoaded callback) {
synchronized (this.queries) {
for(Query query : queries) {
if (query.conversation == conversation) {
if (!query.hasCallback() && callback != null) {
query.setCallback(callback);
}
return true;
}
}
return false;
}
}
public void processFin(Element fin, Jid from) {
if (fin == null) {
return;
}
Query query = findQuery(fin.getAttribute("queryid"));
if (query == null || !query.validFrom(from)) {
return;
}
boolean complete = fin.getAttributeAsBoolean("complete");
Element set = fin.findChild("set","http://jabber.org/protocol/rsm");
Element last = set == null ? null : set.findChild("last");
Element first = set == null ? null : set.findChild("first");
Element relevant = query.getPagingOrder() == PagingOrder.NORMAL ? last : first;
boolean abort = (query.getStart() == 0 && query.getTotalCount() >= Config.PAGE_SIZE) || query.getTotalCount() >= Config.MAM_MAX_MESSAGES;
if (complete || relevant == null || abort) {
this.finalizeQuery(query);
Log.d(Config.LOGTAG,query.getAccount().getJid().toBareJid().toString()+": finished mam after "+query.getTotalCount()+" messages");
if (query.getWith() == null && query.getTotalCount() > 0) {
mXmppConnectionService.getNotificationService().finishBacklog(true);
}
} else {
final Query nextQuery;
if (query.getPagingOrder() == PagingOrder.NORMAL) {
nextQuery = query.next(last == null ? null : last.getContent());
} else {
nextQuery = query.prev(first == null ? null : first.getContent());
}
this.execute(nextQuery);
this.finalizeQuery(query);
synchronized (this.queries) {
this.queries.remove(query);
this.queries.add(nextQuery);
}
}
}
public Query findQuery(String id) {
if (id == null) {
return null;
}
synchronized (this.queries) {
for(Query query : this.queries) {
if (query.getQueryId().equals(id)) {
return query;
}
}
return null;
}
}
@Override
public void onAdvancedStreamFeaturesAvailable(Account account) {
if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().mam()) {
this.catchup(account);
}
}
public class Query {
private int totalCount = 0;
private int messageCount = 0;
private long start;
private long end;
private String queryId;
private String reference = null;
private Account account;
private Conversation conversation;
private PagingOrder pagingOrder = PagingOrder.NORMAL;
private XmppConnectionService.OnMoreMessagesLoaded callback = null;
public Query(Conversation conversation, long start, long end) {
this(conversation.getAccount(), start, end);
this.conversation = conversation;
}
public Query(Conversation conversation, long start, long end, PagingOrder order) {
this(conversation,start,end);
this.pagingOrder = order;
}
public Query(Account account, long start, long end) {
this.account = account;
this.start = start;
this.end = end;
this.queryId = new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
}
private Query page(String reference) {
Query query = new Query(this.account,this.start,this.end);
query.reference = reference;
query.conversation = conversation;
query.totalCount = totalCount;
query.callback = callback;
return query;
}
public Query next(String reference) {
Query query = page(reference);
query.pagingOrder = PagingOrder.NORMAL;
return query;
}
public Query prev(String reference) {
Query query = page(reference);
query.pagingOrder = PagingOrder.REVERSE;
return query;
}
public String getReference() {
return reference;
}
public PagingOrder getPagingOrder() {
return this.pagingOrder;
}
public String getQueryId() {
return queryId;
}
public Jid getWith() {
return conversation == null ? null : conversation.getJid().toBareJid();
}
public boolean muc() {
return conversation != null && conversation.getMode() == Conversation.MODE_MULTI;
}
public long getStart() {
return start;
}
public void setCallback(XmppConnectionService.OnMoreMessagesLoaded callback) {
this.callback = callback;
}
public void callback() {
if (this.callback != null) {
this.callback.onMoreMessagesLoaded(messageCount,conversation);
if (messageCount == 0) {
this.callback.informUser(R.string.no_more_history_on_server);
}
}
}
public long getEnd() {
return end;
}
public Conversation getConversation() {
return conversation;
}
public Account getAccount() {
return this.account;
}
public void incrementTotalCount() {
this.totalCount++;
}
public void incrementMessageCount() {
this.messageCount++;
}
public int getTotalCount() {
return this.totalCount;
}
public int getMessageCount() {
return this.messageCount;
}
public boolean validFrom(Jid from) {
if (muc()) {
return getWith().equals(from);
} else {
return (from == null) || account.getJid().toBareJid().equals(from.toBareJid());
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (this.muc()) {
builder.append("to="+this.getWith().toString());
} else {
builder.append("with=");
if (this.getWith() == null) {
builder.append("*");
} else {
builder.append(getWith().toString());
}
}
builder.append(", start=");
builder.append(AbstractGenerator.getTimestamp(this.start));
builder.append(", end=");
builder.append(AbstractGenerator.getTimestamp(this.end));
if (this.reference!=null) {
if (this.pagingOrder == PagingOrder.NORMAL) {
builder.append(", after=");
} else {
builder.append(", before=");
}
builder.append(this.reference);
}
return builder.toString();
}
public boolean hasCallback() {
return this.callback != null;
}
}
}
| gpl-3.0 |
pgilmon/Comanda | comanda-brian/src/net/peterkuterna/android/apps/swipeytabs/SwipeyTabsAdapter.java | 1132 | /*
* Copyright 2011 Peter Kuterna
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.peterkuterna.android.apps.swipeytabs;
import android.support.v4.view.PagerAdapter;
import android.widget.TextView;
public interface SwipeyTabsAdapter {
/**
* Return the number swipey tabs. Needs to be aligned with the number of
* items in your {@link PagerAdapter}.
*
* @return
*/
int getCount();
/**
* Build {@link TextView} to diplay as a swipey tab.
*
* @param position the position of the tab
* @param root the root view
* @return
*/
TextView getTab(int position, SwipeyTabs root);
}
| gpl-3.0 |
maximka1221/GreenCraft | java/cc/cu/maximka/GreenCraft/packet/AbstractPacket.java | 1383 | package cc.cu.maximka.GreenCraft.packet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraft.entity.player.EntityPlayer;
public abstract class AbstractPacket {
/**
* Encode the packet data into the ByteBuf stream. Complex data sets may need specific data handlers (See @link{cpw.mods.fml.common.network.ByteBuffUtils})
*
* @param ctx channel context
* @param buffer the buffer to encode into
*/
public abstract void encodeInto(ChannelHandlerContext ctx, ByteBuf buffer);
/**
* Decode the packet data from the ByteBuf stream. Complex data sets may need specific data handlers (See @link{cpw.mods.fml.common.network.ByteBuffUtils})
*
* @param ctx channel context
* @param buffer the buffer to decode from
*/
public abstract void decodeInto(ChannelHandlerContext ctx, ByteBuf buffer);
/**
* Handle a packet on the client side. Note this occurs after decoding has completed.
*
* @param player the player reference
*/
public abstract void handleClientSide(EntityPlayer player);
/**
* Handle a packet on the server side. Note this occurs after decoding has completed.
*
* @param player the player reference
*/
public abstract void handleServerSide(EntityPlayer player);
}
| gpl-3.0 |
drdrej/android-drafts-behaviours | app/src/main/java/com/touchableheroes/drafts/behaviours/config/IFragmentConfig.java | 197 | package com.touchableheroes.drafts.behaviours.config;
import android.support.v4.app.Fragment;
/**
* Created by asiebert on 03.07.15.
*/
public interface IFragmentConfig extends IUIConfig {
}
| gpl-3.0 |
ratrecommends/dice-heroes | main/src/com/vlaaad/common/util/filters/Filters.java | 1361 | /*
* Dice heroes is a turn based rpg-strategy game where characters are dice.
* Copyright (C) 2016 Vladislav Protsenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vlaaad.common.util.filters;
import com.vlaaad.common.util.filters.imp.EqFilter;
import com.vlaaad.common.util.filters.imp.ExistsFilter;
import com.vlaaad.common.util.filters.imp.ForallFilter;
/**
* Created 18.05.14 by vlaaad
*/
public class Filters {
public static <T> EqFilter<T> eq(T t) {
return new EqFilter<T>(t);
}
public static <T> ExistsFilter<T> exists(Filter<T> filter) {
return new ExistsFilter<T>(filter);
}
public static <T> ForallFilter<T> forall(Filter<T> filter) {
return new ForallFilter<T>(filter);
}
}
| gpl-3.0 |
sherreria/EponSimulator | es/uvigo/det/labredes/epon/ReportArray.java | 2759 | package es.uvigo.det.labredes.epon;
import java.util.Arrays;
import java.util.Collections;
/**
* This class implements an array of traffic reports.
*
* @author Sergio Herreria-Alonso
* @version 1.0
*/
public class ReportArray {
/**
* The array of traffic reports
*/
private Report[] report_array;
/**
* The number of active ONUs.
*/
public int num_active_onus;
/**
* The overall amount of data stored in the upstream queues of all ONUs.
*/
public int overall_qsize;
/**
* The overall amount of data that all ONUs can transmit in the next DBA cycle.
*/
public int overall_tsize;
/**
* Creates a new array of traffic reports.
*/
public ReportArray() {
report_array = new Report[EponSimulator.num_onus];
overall_qsize = overall_tsize = 0;
num_active_onus = 0;
}
/**
* Adds the specified report to this report array at the right position.
*
* @param report the Report to be added
* @return true if the report is correctly added to this report array
*/
public boolean addReport(Report report) {
if (report.onu_id >= 0 && report.onu_id < EponSimulator.num_onus) {
if (report.onu_qsize > 0) {
overall_qsize += report.onu_qsize;
num_active_onus++;
}
if (report.onu_tsize > 0) {
overall_tsize += report.onu_tsize;
}
report_array[report.onu_id] = report;
return true;
}
return false;
}
/**
* Removes all the reports from this report array.
*/
public void clear() {
overall_qsize = overall_tsize = 0;
num_active_onus = 0;
Arrays.fill(report_array, null);
}
/**
* Returns the report at the specified position in this report array.
*
* @param pos the specified position
* @return the report at the specified position in this report array
*/
public Report getReport(int pos) {
return report_array[pos];
}
/**
* Prints on standard output a message for each report contained in this report array.
*/
public void printReports() {
Report report;
for (int i = 0; i < EponSimulator.num_onus; i++) {
report = report_array[i];
if (report != null) {
report.printReport();
}
}
System.out.println("OVERALL ONUs qsize=" + overall_qsize + " tsize=" + overall_tsize + " active=" + num_active_onus);
}
/**
* Sorts this report array by the specified report field.
*
* @param sort_by the report field to sort by
* @param reverse_order if true sorts the array in reverse order
*/
public void sortReports(String sort_by, boolean reverse_order) {
Report.SORT_BY = sort_by;
Arrays.sort(report_array, reverse_order ? Collections.reverseOrder() : null);
}
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/oauth2server/CustomConfigAuthorizationServerIntegrationTest.java | 2394 | package com.baeldung.springbootsecurity.oauth2server;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootAuthorizationServerApplication.class)
@ActiveProfiles("authz")
public class CustomConfigAuthorizationServerIntegrationTest extends OAuth2IntegrationTestSupport {
@Test
public void givenOAuth2Context_whenAccessTokenIsRequested_ThenAccessTokenValueIsNotNull() {
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("read"));
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
OAuth2AccessToken accessToken = restTemplate.getAccessToken();
assertNotNull(accessToken);
}
@Test(expected = OAuth2AccessDeniedException.class)
public void givenOAuth2Context_whenAccessTokenIsRequestedWithInvalidException_ThenExceptionIsThrown() {
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("write"));
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
restTemplate.getAccessToken();
}
@Test
public void givenOAuth2Context_whenAccessTokenIsRequestedByClientWithWriteScope_ThenAccessTokenIsNotNull() {
ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung-admin", singletonList("write"));
OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);
OAuth2AccessToken accessToken = restTemplate.getAccessToken();
assertNotNull(accessToken);
}
}
| gpl-3.0 |
Cr0s/JavaRA | src/soundly/Mix.java | 2674 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package soundly;
/**
* A 'mix' -- e.g. SFXMix, MusicMix, HUDMix, SpeechMix
* or, say, FootstepsMix, if you really want to get specific!
*
* This is useful for situations where you know you want to mix the different
* sound elements in a certain way; e.g. pan all footsteps left, or allow the
* user to adjust the game or HUD sounds differently, etc.
*
* @author Matt
*/
public class Mix {
private float volume = 1f;
private float pitch = 1f;
private float xAdjustment = 0f;
private float yAdjustment = 0f;
private float depthAdjustment = 0f;
private String name = null;
public Mix() {
this(null, 1f, 1f);
}
public Mix(String name, float volume, float pitch) {
this.name = name;
this.volume = volume;
this.pitch = pitch;
}
public Mix(String name) {
this(name, 1f, 1f);
}
public Mix(float volume, float pitch) {
this(null, volume, pitch);
}
public Mix(float volume) {
this(null, volume);
}
public Mix(String name, float volume) {
this(name, volume, 1f);
}
/**
* @return the volume
*/
public float getVolume() {
return volume;
}
/**
* @param volume the volume to set
*/
public void setVolume(float volume) {
this.volume = volume;
}
/**
* @return the pitch
*/
public float getPitch() {
return pitch;
}
/**
* @param pitch the pitch to set
*/
public void setPitch(float pitch) {
this.pitch = pitch;
}
/**
* @return the xAdjustment
*/
public float getXAdjustment() {
return xAdjustment;
}
/**
* @param xAdjustment the xAdjustment to set
*/
public void setXAdjustment(float xAdjustment) {
this.xAdjustment = xAdjustment;
}
/**
* @return the yAdjustment
*/
public float getYAdjustment() {
return yAdjustment;
}
/**
* @param yAdjustment the yAdjustment to set
*/
public void setYAdjustment(float yAdjustment) {
this.yAdjustment = yAdjustment;
}
/**
* @return the depthAdjustment
*/
public float getDepthAdjustment() {
return depthAdjustment;
}
/**
* @param depthAdjustment the depthAdjustment to set
*/
public void setDepthAdjustment(float depthAdjustment) {
this.depthAdjustment = depthAdjustment;
}
public String toString() {
return String.valueOf(name);
}
}
| gpl-3.0 |
PE-INTERNATIONAL/soda4lca | Node/src/main/java/de/iai/ilcd/security/SecurityUtil.java | 15791 | package de.iai.ilcd.security;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import de.iai.ilcd.model.common.DataSet;
import de.iai.ilcd.model.datastock.DataStock;
import de.iai.ilcd.model.datastock.IDataStockMetaData;
import de.iai.ilcd.model.security.Organization;
import de.iai.ilcd.model.security.User;
import de.iai.ilcd.model.security.UserGroup;
/**
* <p>
* Utility class to check for and work with access rights:
* </p>
* <ul>
* <li>All <code>assert***(...)</code>-methods will throw an {@link AuthorizationException} if access shall not be
* granted.</li>
* <li>The <code>isPermitted(...)</code>-methods can be used for direct checking access rights (return boolean value)</li>
* <li>The <code>toWildcardString(...)</code>-methods shall be used for creation of wildcard strings for shiro</li>
* </ul>
*/
public class SecurityUtil {
/**
* Assert that a user is logged in
*/
public static void assertIsLoggedIn() {
Subject currentUser = SecurityUtils.getSubject();
if ( currentUser == null || currentUser.getPrincipal() == null || StringUtils.isBlank( currentUser.getPrincipal().toString() ) ) {
throw new AuthorizationException( "You must be logged in." );
}
}
/**
* Assert that current user has import right on provided data stock
*
* @param dsm
* data stock meta
* @throws IllegalArgumentException
* if invalid stock UUID
* @throws AuthorizationException
* if access is not to be granted
*/
public static void assertCanImport( IDataStockMetaData dsm ) {
if ( dsm == null ) {
throw new IllegalArgumentException( "Invalid stock" );
}
SecurityUtil.assertCan( dsm, "You are not permitted to import data to this data stock.", ProtectionType.IMPORT );
}
/**
* Assert that current user has read right for provided data set,
* exception is being thrown otherwise
*
* @param <T>
* type of data set
* @param dataSet
* data set to check for current user
* @throws AuthorizationException
* if access is not to be granted
*/
public static <T extends DataSet> void assertCanRead( T dataSet ) throws AuthorizationException {
SecurityUtil.assertCan( dataSet, "You are not permitted to read this data set", ProtectionType.READ );
}
/**
* Assert that current user has read right for provided data stock,
* exception is being thrown otherwise
*
* @param dsm
* data stock to check for current user
* @throws AuthorizationException
* if access is not to be granted
*/
public static void assertCanRead( IDataStockMetaData dsm ) throws AuthorizationException {
SecurityUtil.assertCan( dsm, "You are not permitted to read this data stock", ProtectionType.READ );
}
/**
* Assert that current user has write right for provided data set,
* exception is being thrown otherwise. <br />
* <b>Please note:</b> This only checks on permission level, no release management
* is being considered!
*
* @param <T>
* data set type
* @param dataSet
* data set to check for current user
* @throws AuthorizationException
* if access is not to be granted
*/
public static <T extends DataSet> void assertCanWrite( T dataSet ) throws AuthorizationException {
SecurityUtil.assertCan( dataSet, "You are not permitted to write/delete this data set", ProtectionType.WRITE );
}
/**
* Assert that current user has export right for provided data set,
* exception is being thrown otherwise
*
* @param <T>
* data set type
* @param dataSet
* data set to check for current user
* @throws AuthorizationException
* if access is not to be granted
*/
public static <T extends DataSet> void assertCanExport( T dataSet ) throws AuthorizationException {
SecurityUtil.assertCan( dataSet, "You are not permitted to export this data set", ProtectionType.EXPORT );
}
/**
* Assert that current user has provided right for provided data set,
* exception is being thrown otherwise
*
* @param <T>
* data set type
* @param dataSet
* data set to check for current user
* @param canWhat
* type of permissions to check
* @throws AuthorizationException
* if access is not to be granted (generic message)
*/
public static <T extends DataSet> void assertCan( T dataSet, ProtectionType... canWhat ) throws AuthorizationException {
SecurityUtil.assertCan( dataSet, "You are not permitted to perform this operation for this data set", canWhat );
}
/**
* Assert that current user has provided right for provided data set,
* exception is being thrown otherwise
*
* @param <T>
* data set type
* @param dataSet
* data set to check for current user
* @param negativeMessage
* message of exception if permission is not to be granted
* @param canWhat
* type of permissions to check
* @throws AuthorizationException
* if access is not to be granted (provided message)
*/
public static <T extends DataSet> void assertCan( T dataSet, String negativeMessage, ProtectionType... canWhat ) throws AuthorizationException {
if ( !SecurityUtil.isPermitted( dataSet, canWhat ) ) {
throw new AuthorizationException( negativeMessage );
}
}
/**
* Assert that current user has provided right for provided data stock,
* exception is being thrown otherwise
*
* @param <T>
* data set type
* @param dsm
* data stock meta to check for current user
* @param canWhat
* type of permissions to check
* @throws AuthorizationException
* if access is not to be granted (generic message)
*/
public static <T extends DataSet> void assertCan( IDataStockMetaData dsm, ProtectionType... canWhat ) throws AuthorizationException {
SecurityUtil.assertCan( dsm, "You are not permitted to perform this operation for this data stock", canWhat );
}
/**
* Assert that current user has provided right for provided data stock,
* exception is being thrown otherwise
*
* @param <T>
* data set type
* @param dsm
* data stock meta to check for current user
* @param negativeMessage
* message of exception if permission is not to be granted
* @param canWhat
* type of permissions to check
* @throws AuthorizationException
* if access is not to be granted (provided message)
*/
public static <T extends DataSet> void assertCan( IDataStockMetaData dsm, String negativeMessage, ProtectionType... canWhat ) throws AuthorizationException {
if ( dsm == null ) {
throw new AuthorizationException( negativeMessage );
}
SecurityUtil.assertPermission( SecurityUtil.toWildcardString( ProtectableType.STOCK, canWhat, String.valueOf( dsm.getId() ) ), negativeMessage );
}
/**
* Determine if user can edit (has {@link ProtectionType#WRITE write} permission) on the provided user
*
* @param u
* user to check edit rights for
* @param negativeMessage
* message for exception if user lacks edit permission
* @throws AuthorizationException
* if permission is not present
*/
public static void assertCanWrite( User u, String negativeMessage ) throws AuthorizationException {
if ( u != null ) {
SecurityUtil.assertCanWriteUser( u.getId(), negativeMessage );
}
else {
throw new AuthorizationException();
}
}
/**
* Determine if user can edit (has {@link ProtectionType#WRITE write} permission) on the provided user id
*
* @param uid
* user id to check edit rights for
* @param negativeMessage
* message for exception if user lacks edit permission
* @throws AuthorizationException
* if permission is not present
*/
public static void assertCanWriteUser( Long uid, String negativeMessage ) throws AuthorizationException {
SecurityUtil.assertPermission( SecurityUtil.toWildcardString( ProtectableType.USER, ProtectionType.WRITE, String.valueOf( uid ) ), negativeMessage );
}
/**
* Determine if user has super admin permission
*
* @throws AuthorizationException
* if permission is not present
*/
public static void assertSuperAdminPermission() throws AuthorizationException {
if ( !SecurityUtil.hasSuperAdminPermission() ) {
throw new AuthorizationException( "Super Admin Right required" );
}
}
/**
* Assert that the current user has admin rights (is {@link Organization#getAdminUser() admin user} or
* in the {@link Organization#getAdminGroup() admin group}) for the provided organization.
*
* @param o
* organization to check for
*/
public static void assertIsOrganizationAdmin( Organization o ) {
final boolean sadmPermission = SecurityUtil.hasSuperAdminPermission();
if ( sadmPermission ) {
return;
}
if ( o == null ) {
if ( !sadmPermission ) {
throw new AuthorizationException( "Super Admin Right required" );
}
else {
return;
}
}
// no guests!
SecurityUtil.assertIsLoggedIn();
String username = SecurityUtils.getSubject().getPrincipal().toString();
if ( o.getAdminUser() != null && username.equals( o.getAdminUser().getUserName() ) ) {
return;
}
final UserGroup admGroup = o.getAdminGroup();
if ( admGroup != null ) {
final UserAccessBean uab = new UserAccessBean();
final User user = uab.getUserObject();
final List<UserGroup> userGroups = user.getGroups();
if ( CollectionUtils.isNotEmpty( userGroups ) ) {
if ( userGroups.contains( admGroup ) ) {
return;
}
}
}
throw new AuthorizationException( "No admin right for this organization" );
}
/**
* Check a permission
*
* @param permission
* permission to check
* @param negativeMessage
* message for exception if user lacks permission
* @throws AuthorizationException
* if permission is not present
*/
public static void assertPermission( String permission, String negativeMessage ) throws AuthorizationException {
Subject sub = SecurityUtils.getSubject();
if ( sub != null ) {
if ( !sub.isPermitted( permission ) ) {
throw new AuthorizationException( negativeMessage );
}
}
else {
throw new AuthorizationException();
}
}
/**
* Determine if user shall be able to enter admin area
*
* @return <code>true</code> if access shall be granted, <code>false</code> otherwise
*/
public static boolean hasAdminAreaAccessRight() {
return SecurityUtil.isPermitted( ProtectableType.ADMIN_AREA.name() );
}
/**
* Determine if user is super admin
*
* @return <code>true</code> if super admin access shall be granted, <code>false</code> otherwise
*/
public static boolean hasSuperAdminPermission() {
return SecurityUtil.isPermitted( "*:*:*" );
}
/**
* Determine if user has {@link ProtectionType#EXPORT export} permission for provided data set
*
* @param ds
* data set to check for
* @return <code>true</code> if export allowed, <code>false</code> otherwise
*/
public static boolean hasExportPermission( DataSet ds ) {
return SecurityUtil.isPermitted( ds, ProtectionType.EXPORT );
}
/**
* Determine if user has {@link ProtectionType#IMPORT import} permission for provided data stock
*
* @param dsm
* data stock meta
* @return <code>true</code> if import allowed, <code>false</code> otherwise
*/
public static boolean hasImportPermission( IDataStockMetaData dsm ) {
return SecurityUtil.isPermitted( SecurityUtil.toWildcardString( ProtectableType.STOCK, ProtectionType.IMPORT, dsm.getId().toString() ) );
}
/**
* Check if a permission is present to use provided protection types
* (checks all data stocks of provided data set).
*
* @param dataSet
* data set to check for current user
* @param canWhat
* type(s) to check
* @return <code>true</code> if permission shall be granted, <code>false</code> otherwise
*/
private static <T extends DataSet> boolean isPermitted( T dataSet, ProtectionType... canWhat ) {
// 1st: empty canWhan = error (therefore return false)
if ( canWhat == null || canWhat.length == 0 ) {
return false;
}
// 2nd: root data stock
if ( SecurityUtil.isPermitted( SecurityUtil.toWildcardString( ProtectableType.STOCK, canWhat, dataSet.getRootDataStock().getId().toString() ) ) ) {
return true;
}
// 3rd: all normal data stocks
final Set<DataStock> dsList = dataSet.getContainingDataStocks();
if ( dsList != null && !dsList.isEmpty() ) {
for ( DataStock ds : dsList ) {
if ( SecurityUtil.isPermitted( SecurityUtil.toWildcardString( ProtectableType.STOCK, canWhat, ds.getId().toString() ) ) ) {
return true;
}
}
}
return false;
}
/**
* Check a permission
*
* @param permission
* permission to check (wildcard string)
* @return <code>true</code> if permission shall be granted, <code>false</code> otherwise
*/
private static boolean isPermitted( String permission ) {
Subject sub = SecurityUtils.getSubject();
if ( sub != null ) {
if ( !sub.isPermitted( permission ) ) {
return false;
}
}
else {
return false;
}
return true;
}
/**
* Convert to Shiro wildcard string
*
* @param protectableType
* the protectable type to grant access to
* @param protectionType
* the protection type to grant access to as string
* @param vals
* identifier of objects to grant access to
* @return Shiro wildcard string
*/
public static String toWildcardString( String protectableType, String protectionType, String vals ) {
StringBuilder sb = new StringBuilder( protectableType ).append( ":" ).append( protectionType );
if ( vals != null ) {
sb.append( ":" ).append( vals );
}
String res = sb.toString();
return res;
}
/**
* Convert to Shiro wildcard string
*
* @param protectableType
* the protectable type to grant access to
* @param protectionType
* the protection types to grant access to
* @param vals
* identifier of objects to grant access to
* @return Shiro wildcard string
*/
public static String toWildcardString( ProtectableType protectableType, ProtectionType[] protectionType, String vals ) {
return SecurityUtil.toWildcardString( protectableType.name(), StringUtils.join( protectionType, "," ), vals );
}
/**
* Convert to Shiro wildcard string
*
* @param protectableType
* the protectable type to grant access to
* @param protectionType
* the protection type to grant access to
* @param vals
* identifier of objects to grant access to
* @return Shiro wildcard string
*/
public static String toWildcardString( ProtectableType protectableType, ProtectionType protectionType, String vals ) {
return SecurityUtil.toWildcardString( protectableType.name(), protectionType.name(), vals );
}
/**
* Convert to Shiro wildcard string
*
* @param protectableType
* the protectable type to grant access to
* @param protectionType
* the protection type to grant access to
* @param id
* identifier of objects to grant access to
* @return Shiro wildcard string
*/
public static String toWildcardString( String protectableType, String protectionType, long id ) {
return SecurityUtil.toWildcardString( protectableType, protectionType, Long.toString( id ) );
}
}
| gpl-3.0 |
mut0u/thrift-transformer | src/main/java/github/mutou/thrift/transformer/TransformException.java | 199 | package github.mutou.thrift.transformer;
public class TransformException extends Exception {
public TransformException(String message, Throwable cause) {
super(message, cause);
}
}
| gpl-3.0 |
Bernie-2016/bernie-messenger-android | android/app/src/main/java/com/berniesanders/messenger/NativePackages.java | 1253 | package com.berniesanders.messenger;
import android.app.Activity;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
/**
* Created by ajwhite on 5/3/16.
*/
public class NativePackages implements ReactPackage {
private Activity activity;
public NativePackages(Activity activity) {
this.activity = activity;
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactApplicationContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new CommunicationsModule(reactApplicationContext, activity));
modules.add(new AnswersModule(reactApplicationContext));
return modules;
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactApplicationContext) {
return Collections.emptyList();
}
}
| gpl-3.0 |
marvisan/HadesFIX | Model/src/test/java/net/hades/fix/message/impl/v50sp2/fixml/OrderCancelRejectMsgFIXML50SP2Test.java | 4978 | /*
* Copyright (c) 2006-2016 Marvisan Pty. Ltd. All rights reserved.
* Use is subject to license terms.
*/
/*
* OrderCancelRejectMsgFIXML50SP2Test.java
*
* $Id: OrderCancelRejectMsgFIXML50SP2Test.java,v 1.1 2011-01-23 10:02:05 vrotaru Exp $
*/
package net.hades.fix.message.impl.v50sp2.fixml;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import net.hades.fix.TestUtils;
import net.hades.fix.message.MsgTest;
import net.hades.fix.message.OrderCancelRejectMsg;
import net.hades.fix.message.XMLValidationResult;
import net.hades.fix.message.builder.FIXMsgBuilder;
import net.hades.fix.message.impl.v50sp2.data.OrderCancelRejectMsg50SP2TestData;
import net.hades.fix.message.type.BeginString;
import net.hades.fix.message.type.CxlRejResponseTo;
import net.hades.fix.message.type.MsgType;
import net.hades.fix.message.type.OrdStatus;
/**
* Test suite for OrderCancelRejectMsg50SP2 class FIXML implementation.
*
* @author <a href="mailto:support@marvisan.com">Support Team</a>
* @version $Revision: 1.1 $
* @created 20/10/2008, 20:57:03
*/
public class OrderCancelRejectMsgFIXML50SP2Test extends MsgTest {
public OrderCancelRejectMsgFIXML50SP2Test() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of encode method, of class OrderCancelRejectMsg for FIXML 4.4.
* @throws Exception
*/
@Test
public void testMarshallUnmarshallFixmlReq() throws Exception {
System.out.println("-->testMarshallUnmarshallFixmlReq");
setPrintableValidatingFixml();
try {
OrderCancelRejectMsg msg = (OrderCancelRejectMsg) FIXMsgBuilder.build(MsgType.OrderCancelReject.getValue(), BeginString.FIX_5_0SP2);
TestUtils.populate50HeaderAll(msg);
msg.setOrderID("ORDD7264363");
msg.setClOrdID("X162773883");
msg.setOrigClOrdID("DD7264363");
msg.setOrdStatus(OrdStatus.Canceled);
msg.setCxlRejResponseTo(CxlRejResponseTo.OrderCancelRequest);
String fixml = msg.toFixml();
System.out.println("fixml-->" + fixml);
XMLValidationResult result = validateXMLAgainstXSD(fixml, FIXML_SCHEMA_V50SP2);
if (result.hasErrors()) {
System.out.println("\nERRORS:\n");
System.out.println(result.getFatals());
System.out.println(result.getErrors());
}
System.out.println(result.getWarnings());
assertFalse(result.hasErrors());
OrderCancelRejectMsg dmsg = (OrderCancelRejectMsg) FIXMsgBuilder.build(MsgType.OrderCancelReject.getValue(), BeginString.FIX_5_0SP2);
dmsg.fromFixml(fixml);
assertEquals(msg.getOrderID(), dmsg.getOrderID());
assertEquals(msg.getClOrdID(), dmsg.getClOrdID());
assertEquals(msg.getOrigClOrdID(), dmsg.getOrigClOrdID());
assertEquals(msg.getOrdStatus(), dmsg.getOrdStatus());
assertEquals(msg.getCxlRejResponseTo(), dmsg.getCxlRejResponseTo());
} finally {
unsetPrintableFixml();
}
}
/**
* Test of encode method, of class OrderCancelRejectMsg for FIXML 4.4.
* @throws Exception
*/
@Test
public void testMarshallUnmarshallFixml() throws Exception {
System.out.println("-->testMarshallUnmarshallFixml");
setPrintableValidatingFixml();
try {
OrderCancelRejectMsg msg = (OrderCancelRejectMsg) FIXMsgBuilder.build(MsgType.OrderCancelReject.getValue(), BeginString.FIX_5_0SP2);
TestUtils.populate50HeaderAll(msg);
OrderCancelRejectMsg50SP2TestData.getInstance().populate(msg);
String fixml = msg.toFixml();
System.out.println("fixml-->" + fixml);
XMLValidationResult result = validateXMLAgainstXSD(fixml, FIXML_SCHEMA_V50SP2);
if (result.hasErrors()) {
System.out.println("\nERRORS:\n");
System.out.println(result.getFatals());
System.out.println(result.getErrors());
}
System.out.println(result.getWarnings());
assertFalse(result.hasErrors());
OrderCancelRejectMsg dmsg = (OrderCancelRejectMsg) FIXMsgBuilder.build(MsgType.OrderCancelReject.getValue(), BeginString.FIX_5_0SP2);
dmsg.fromFixml(fixml);
OrderCancelRejectMsg50SP2TestData.getInstance().check(msg, dmsg);
} finally {
unsetPrintableFixml();
}
}
// NEGATIVE TEST CASES
/////////////////////////////////////////
// UTILITY MESSAGES
/////////////////////////////////////////
} | gpl-3.0 |
nextgis/ngm_clink_monitoring | app/src/main/java/com/nextgis/ngm_clink_monitoring/map/FoclProject.java | 17776 | /*
* Project: NextGIS mobile apps for Compulink
* Purpose: Mobile GIS for Android
* Authors: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru
* NikitaFeodonit, nfeodonit@yandex.com
* *****************************************************************************
* Copyright (C) 2014-2015 NextGIS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextgis.ngm_clink_monitoring.map;
import android.accounts.Account;
import android.content.Context;
import android.content.Intent;
import android.content.SyncResult;
import android.database.sqlite.SQLiteException;
import android.text.TextUtils;
import android.util.Log;
import com.nextgis.maplib.api.IGISApplication;
import com.nextgis.maplib.api.ILayer;
import com.nextgis.maplib.api.INGWLayer;
import com.nextgis.maplib.map.LayerFactory;
import com.nextgis.maplib.map.LayerGroup;
import com.nextgis.maplib.util.Constants;
import com.nextgis.maplib.util.NGException;
import com.nextgis.maplib.util.NetworkUtil;
import com.nextgis.ngm_clink_monitoring.GISApplication;
import com.nextgis.ngm_clink_monitoring.util.FoclConstants;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FoclProject
extends LayerGroup
implements INGWLayer
{
public static final String SYNC_LAYER_COUNT =
"com.nextgis.ngm_clink_monitoring.sync_layer_count";
public static final String SYNC_CURRENT_LAYER =
"com.nextgis.ngm_clink_monitoring.sync_current_layer";
protected static final String JSON_ACCOUNT_KEY = "account";
protected static final String JSON_FOCL_DICTS_KEY = "focl_dicts";
protected NetworkUtil mNet;
protected String mAccountName = "";
protected String mCacheUrl;
protected String mCacheLogin;
protected String mCachePassword;
protected FoclDitcs mFoclDitcs;
public FoclProject(
Context context,
File path,
LayerFactory layerFactory)
{
super(context, path, layerFactory);
mNet = new NetworkUtil(context);
mLayerType = FoclConstants.LAYERTYPE_FOCL_PROJECT;
}
public static String getUserFoclListUrl(String server)
{
if (!server.startsWith("http")) {
server = "http://" + server;
}
return server + FoclConstants.FOCL_USER_FOCL_LIST_URL;
}
public static String getAllDictsUrl(String server)
{
if (!server.startsWith("http")) {
server = "http://" + server;
}
return server + FoclConstants.FOCL_ALL_DICTS_URL;
}
public static String getSetFoclStatusUrl(String server)
{
if (!server.startsWith("http")) {
server = "http://" + server;
}
return server + FoclConstants.FOCL_SET_FOCL_STATUS_URL;
}
@Override
public String getAccountName()
{
return mAccountName;
}
@Override
public void setAccountName(String accountName)
{
mAccountName = accountName;
setAccountCacheData();
}
@Override
public void setAccountCacheData()
{
IGISApplication app = (IGISApplication) mContext.getApplicationContext();
Account account = app.getAccount(mAccountName);
if (null != account) {
mCacheUrl = app.getAccountUrl(account);
mCacheLogin = app.getAccountLogin(account);
mCachePassword = app.getAccountPassword(account);
}
}
@Override
public void sync(
String authority,
SyncResult syncResult)
{
}
@Override
public int getSyncType()
{
return 0;
}
@Override
public void setSyncType(int syncType)
{
}
@Override
public long getRemoteId()
{
return 0;
}
@Override
public void setRemoteId(long remoteId)
{
}
public FoclStruct getFoclStructByRemoteId(long remoteId)
{
for (ILayer layer : mLayers) {
FoclStruct foclStruct = (FoclStruct) layer;
if (foclStruct.getRemoteId() == remoteId) {
return foclStruct;
}
}
return null;
}
@Override
public JSONObject toJSON()
throws JSONException
{
JSONObject rootConfig = super.toJSON();
rootConfig.put(JSON_ACCOUNT_KEY, mAccountName);
if (null != mFoclDitcs) {
rootConfig.put(JSON_FOCL_DICTS_KEY, mFoclDitcs.toJSON());
}
return rootConfig;
}
public FoclDitcs getFoclDitcs()
{
return mFoclDitcs;
}
@Override
public void fromJSON(JSONObject jsonObject)
throws JSONException
{
super.fromJSON(jsonObject);
setAccountName(jsonObject.getString(JSON_ACCOUNT_KEY));
if (jsonObject.has(JSON_FOCL_DICTS_KEY)) {
mFoclDitcs = new FoclDitcs(jsonObject.getJSONObject(JSON_FOCL_DICTS_KEY));
}
}
public String sync()
{
for (ILayer layer : mLayers) {
if (Thread.currentThread().isInterrupted()) {
break;
}
FoclStruct foclStruct = (FoclStruct) layer;
if (foclStruct.isStatusChanged()) {
long id = foclStruct.getRemoteId();
String status = foclStruct.getStatus();
if (null == foclStruct.getStatusUpdateTime()) {
continue;
}
long updateDate = foclStruct.getStatusUpdateTime() / 1000; // must not be null!
if (sendLineStatusOnServer(id, status, updateDate)) {
foclStruct.setIsStatusChanged(false);
foclStruct.save();
Log.d(
Constants.TAG,
"status SENT, path name: " + getPath().getName() + " - line name: " +
getName());
} else {
String error = "Set status line failed";
Log.d(Constants.TAG, error);
return error;
}
}
}
return download();
}
protected boolean sendLineStatusOnServer(
long foclStructId,
String lineStatus,
long updateDate)
{
if (!mNet.isNetworkAvailable()) {
return false;
}
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put(Constants.JSON_ID_KEY, foclStructId);
jsonObject.put(FoclConstants.JSON_STATUS_KEY, lineStatus);
jsonObject.put(FoclConstants.JSON_UPDATE_DT_KEY, updateDate);
String payload = jsonObject.toString();
Log.d(Constants.TAG, "send status, payload: " + payload);
String data = mNet.put(
getSetFoclStatusUrl(mCacheUrl), payload, mCacheLogin, mCachePassword);
return null != data;
} catch (JSONException | IOException e) {
e.printStackTrace();
return false;
}
}
public FoclStruct addOrUpdateFoclStruct(
JSONObject jsonStruct,
JSONArray jsonLayers)
throws JSONException, SQLiteException
{
long structId = jsonStruct.getLong(Constants.JSON_ID_KEY);
String structStatus = jsonStruct.isNull(FoclConstants.JSON_STATUS_KEY)
? FoclConstants.FIELD_VALUE_STATUS_PROJECT
: jsonStruct.getString(FoclConstants.JSON_STATUS_KEY);
String structName = jsonStruct.isNull(Constants.JSON_NAME_KEY)
? ""
: jsonStruct.getString(Constants.JSON_NAME_KEY);
String structRegion = jsonStruct.isNull(FoclConstants.JSON_REGION_KEY)
? ""
: jsonStruct.getString(FoclConstants.JSON_REGION_KEY);
String structDistrict = jsonStruct.isNull(FoclConstants.JSON_DISTRICT_KEY)
? ""
: jsonStruct.getString(FoclConstants.JSON_DISTRICT_KEY);
FoclStruct foclStruct = getFoclStructByRemoteId(structId);
if (null != foclStruct) {
if (!foclStruct.getStatus().equals(structStatus)) {
foclStruct.setStatus(structStatus);
}
if (!foclStruct.getName().equals(structName)) {
foclStruct.setName(structName);
}
if (!foclStruct.getRegion().equals(structRegion)) {
foclStruct.setRegion(structRegion);
}
if (!foclStruct.getDistrict().equals(structDistrict)) {
foclStruct.setDistrict(structDistrict);
}
List<Long> layerIdList = new ArrayList<>(jsonLayers.length());
for (int jj = 0; jj < jsonLayers.length(); jj++) {
JSONObject jsonLayer = jsonLayers.getJSONObject(jj);
long layerId = jsonLayer.getInt(Constants.JSON_ID_KEY);
layerIdList.add(layerId);
}
List<ILayer> layers = foclStruct.getLayers();
for (int i = 0; i < layers.size(); ++i) {
if (Thread.currentThread().isInterrupted()) {
break;
}
ILayer layer = layers.get(i);
FoclVectorLayer foclVectorLayer = (FoclVectorLayer) layer;
if (!layerIdList.contains(foclVectorLayer.getRemoteId())) {
foclVectorLayer.delete();
--i;
}
}
} else {
foclStruct = new FoclStruct(getContext(), createLayerStorage(), mLayerFactory);
foclStruct.setRemoteId(structId);
foclStruct.setStatus(structStatus);
foclStruct.setName(structName);
foclStruct.setRegion(structRegion);
foclStruct.setDistrict(structDistrict);
addLayer(foclStruct);
}
return foclStruct;
}
public void addOrUpdateFoclVectorLayer(
JSONObject jsonLayer,
FoclStruct foclStruct)
throws JSONException, SQLiteException
{
int layerId = jsonLayer.getInt(Constants.JSON_ID_KEY);
String layerName = jsonLayer.isNull(Constants.JSON_NAME_KEY)
? ""
: jsonLayer.getString(Constants.JSON_NAME_KEY);
String layerType = jsonLayer.getString(Constants.JSON_TYPE_KEY);
FoclVectorLayer foclVectorLayer = foclStruct.getLayerByRemoteId(layerId);
boolean createNewVectorLayer = false;
if (foclVectorLayer != null) {
if (foclVectorLayer.getFoclLayerType() !=
FoclVectorLayer.getFoclLayerTypeFromString(layerType)) {
foclVectorLayer.delete();
createNewVectorLayer = true;
}
if (!createNewVectorLayer) {
if (!foclVectorLayer.getName().equals(layerName)) {
foclVectorLayer.setName(layerName);
}
}
}
if (createNewVectorLayer || foclVectorLayer == null) {
foclVectorLayer = new FoclVectorLayer(
foclStruct.getContext(), foclStruct.createLayerStorage());
int foclLayerType = FoclVectorLayer.getFoclLayerTypeFromString(layerType);
foclVectorLayer.setRemoteId(layerId);
foclVectorLayer.setName(layerName);
foclVectorLayer.setFoclLayerType(foclLayerType);
foclVectorLayer.setAccountName(mAccountName);
foclVectorLayer.setSyncType(Constants.SYNC_ALL);
foclStruct.addLayer(foclVectorLayer);
if (FoclConstants.LAYERTYPE_FOCL_OPTICAL_CABLE == foclLayerType) {
foclStruct.moveLayer(0, foclVectorLayer);
}
if (FoclConstants.LAYERTYPE_FOCL_REAL_OPTICAL_CABLE_POINT == foclLayerType) {
foclStruct.moveLayer(1, foclVectorLayer);
}
try {
foclVectorLayer.createFromNGW(null);
} catch (NGException | IOException e) {
Log.d(Constants.TAG, e.getLocalizedMessage());
}
}
}
public String createOrUpdateFromJson(JSONArray jsonArray)
{
if (Thread.currentThread().isInterrupted()) {
return "";
}
try {
List<Long> structIdList = new ArrayList<>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); ++i) {
JSONObject jsonStruct = jsonArray.getJSONObject(i);
long structId = jsonStruct.getLong(Constants.JSON_ID_KEY);
structIdList.add(structId);
}
for (int i = 0; i < mLayers.size(); ++i) {
ILayer layer = mLayers.get(i);
if (Thread.currentThread().isInterrupted()) {
break;
}
FoclStruct foclStruct = (FoclStruct) layer;
if (!structIdList.contains(foclStruct.getRemoteId())) {
foclStruct.delete();
--i;
}
}
int structCount = jsonArray.length();
int layerCount = 0;
for (int i = 0; i < structCount; ++i) {
if (Thread.currentThread().isInterrupted()) {
break;
}
JSONObject jsonStruct = jsonArray.getJSONObject(i);
JSONArray jsonLayers = jsonStruct.getJSONArray(Constants.JSON_LAYERS_KEY);
layerCount += jsonLayers.length();
}
Intent layerCountIntent = new Intent(SYNC_LAYER_COUNT);
layerCountIntent.putExtra(SYNC_LAYER_COUNT, layerCount);
getContext().sendBroadcast(layerCountIntent);
int currentLayer = 0;
for (int i = 0; i < structCount; ++i) {
if (Thread.currentThread().isInterrupted()) {
break;
}
JSONObject jsonStruct = jsonArray.getJSONObject(i);
JSONArray jsonLayers = jsonStruct.getJSONArray(Constants.JSON_LAYERS_KEY);
FoclStruct foclStruct = addOrUpdateFoclStruct(jsonStruct, jsonLayers);
for (int jj = 0; jj < jsonLayers.length(); ++jj) {
if (Thread.currentThread().isInterrupted()) {
break;
}
JSONObject jsonLayer = jsonLayers.getJSONObject(jj);
addOrUpdateFoclVectorLayer(jsonLayer, foclStruct);
Intent currentLayerIntent = new Intent(SYNC_CURRENT_LAYER);
currentLayerIntent.putExtra(SYNC_CURRENT_LAYER, currentLayer++);
getContext().sendBroadcast(currentLayerIntent);
}
}
return "";
} catch (JSONException | SQLiteException e) {
e.printStackTrace();
return e.getLocalizedMessage();
}
}
protected String downloadData(String url)
throws IOException
{
String data = NetworkUtil.get(url, mCacheLogin, mCachePassword);
if (null == data) {
Log.d(Constants.TAG, "No content downloading FOCL: " + url);
return getContext().getString(com.nextgis.maplib.R.string.error_download_data);
}
return data;
}
public String download()
{
if (!mNet.isNetworkAvailable()) {
return getContext().getString(com.nextgis.maplib.R.string.error_network_unavailable);
}
try {
JSONArray jsonArrayProject = new JSONArray(downloadData(getUserFoclListUrl(mCacheUrl)));
JSONObject jsonObjectDicts = new JSONObject(downloadData(getAllDictsUrl(mCacheUrl)));
String error = createOrUpdateFromJson(jsonArrayProject);
if (TextUtils.isEmpty(error)) {
save();
} else {
return error;
}
mFoclDitcs = new FoclDitcs();
error = mFoclDitcs.createOrUpdateFromJson(jsonObjectDicts);
if (TextUtils.isEmpty(error)) {
save();
}
return error;
} catch (IOException e) {
Log.d(
Constants.TAG, "Problem downloading FOCL: " + mCacheUrl + " Error: " +
e.getLocalizedMessage());
return getContext().getString(com.nextgis.maplib.R.string.error_download_data);
} catch (JSONException e) {
e.printStackTrace();
return getContext().getString(com.nextgis.maplib.R.string.error_download_data);
}
}
@Override
protected void onLayerAdded(ILayer layer)
{
GISApplication app = (GISApplication) mContext.getApplicationContext();
layer.setId(app.getMap().getNewId());
super.onLayerAdded(layer);
}
}
| gpl-3.0 |
hardwork2014/familyGang | src/main/java/com/jzb/family/web/controller/LoginController.java | 2480 | package com.jzb.family.web.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.jzb.family.common.enums.StatusEnum;
import com.jzb.family.domain.AppUser;
@Controller
public class LoginController extends BaseController {
private static final Logger logger = (Logger) LoggerFactory.getLogger(LoginController.class);
/**
* 根据用户角色来决定默认的展现页面.
* @return String
*/
@RequestMapping(value = "login", method = RequestMethod.GET)
public String loginPage(HttpServletRequest request,Model model) {
try {
AppUser user = getAppUser();
if(user != null) {
return "redirect:/common/main";
}
}catch (Exception e) {
logger.error("loginPage exception : {}",e);
}
return "login";
}
@RequestMapping(value = "main", method = RequestMethod.GET)
public String forwardToDefaultPage(Model model) {
model.addAttribute("appUser", getAppUser());
return "main";
}
/**
* 验证输入码的正确性
* author zhouhuiqun470
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
@RequestMapping(value="resultServlet/validateCode",method=RequestMethod.POST)
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String validateC = (String) request.getSession().getAttribute("validateCode");
String veryCode = request.getParameter("c");
PrintWriter out = response.getWriter();
if(validateC.equalsIgnoreCase(veryCode)){
out.println(StatusEnum.success.getCode());
}else{
out.println(StatusEnum.fail.getCode());
}
out.flush();
out.close();
}
}
| gpl-3.0 |
kuiwang/my-dev | src/main/java/com/aliyun/api/ecs/ecs20140526/request/ReleaseEipAddressRequest.java | 3427 | package com.aliyun.api.ecs.ecs20140526.request;
import java.util.Map;
import com.aliyun.api.AliyunRequest;
import com.aliyun.api.ecs.ecs20140526.response.ReleaseEipAddressResponse;
import com.taobao.api.ApiRuleException;
import com.taobao.api.internal.util.RequestCheckUtils;
import com.taobao.api.internal.util.TaobaoHashMap;
/**
* TOP API: ecs.aliyuncs.com.ReleaseEipAddress.2014-05-26 request
*
* @author auto create
* @since 1.0, 2014-11-02 16:51:39
*/
public class ReleaseEipAddressRequest implements AliyunRequest<ReleaseEipAddressResponse> {
/**
* 申请Id
*/
private String allocationId;
private Map<String, String> headerMap = new TaobaoHashMap();
/** 仅用于渠道商发起API调用时,指定访问的资源拥有者的账号 */
private String ownerAccount;
/** 仅用于渠道商发起API调用时,指定访问的资源拥有者的ID */
private String ownerId;
/**
* API调用者试图通过API调用来访问别人拥有但已经授权给他的资源时,通过使用该参数来声明此次操作涉及到的资源是谁名下的,
* 该参数仅官网用户可用
*/
private String resourceOwnerAccount;
private Long timestamp;
private TaobaoHashMap udfParams; // add user-defined text parameters
@Override
public void check() throws ApiRuleException {
RequestCheckUtils.checkNotEmpty(allocationId, "allocationId");
}
public String getAllocationId() {
return this.allocationId;
}
@Override
public String getApiMethodName() {
return "ecs.aliyuncs.com.ReleaseEipAddress.2014-05-26";
}
@Override
public Map<String, String> getHeaderMap() {
return headerMap;
}
public String getOwnerAccount() {
return ownerAccount;
}
public String getOwnerId() {
return ownerId;
}
public String getResourceOwnerAccount() {
return resourceOwnerAccount;
}
@Override
public Class<ReleaseEipAddressResponse> getResponseClass() {
return ReleaseEipAddressResponse.class;
}
@Override
public Map<String, String> getTextParams() {
TaobaoHashMap txtParams = new TaobaoHashMap();
txtParams.put("OwnerId", this.ownerId);
txtParams.put("OwnerAccount", this.ownerAccount);
txtParams.put("ResourceOwnerAccount", this.resourceOwnerAccount);
txtParams.put("AllocationId", this.allocationId);
if (this.udfParams != null) {
txtParams.putAll(this.udfParams);
}
return txtParams;
}
@Override
public Long getTimestamp() {
return this.timestamp;
}
@Override
public void putOtherTextParam(String key, String value) {
if (this.udfParams == null) {
this.udfParams = new TaobaoHashMap();
}
this.udfParams.put(key, value);
}
public void setAllocationId(String allocationId) {
this.allocationId = allocationId;
}
public void setOwnerAccount(String ownerAccount) {
this.ownerAccount = ownerAccount;
}
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
public void setResourceOwnerAccount(String resourceOwnerAccount) {
this.resourceOwnerAccount = resourceOwnerAccount;
}
@Override
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
}
| gpl-3.0 |
bbrooker/minespacemod | net/bbrooker/minespace/Items/License/RoboticLicense.java | 873 | package net.bbrooker.minespace.Items
import java.util.Random;
import java.util.List;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.bbrooker.minespace.MCSpaceInfo;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class RoboticLicense extends Item {
public RoboticLicense(int id) {
super(id);
setMaxStackSize(1);
setCreativeTab(CreativeTabs.tabMaterials);
setUnlocalizedName("RoboticLicense");
setTextureName("minespace:RoboticLicense");
}
@SideOnly(Side.CLIENT) //add item lore
public void addInformation(ItemStack itemStack, EntityPlayer entityPlayer, List list, boolean is)
{
list.add("[License] Can craft or build Droid");
}
}
| gpl-3.0 |
rbieb/ClientServer | src/Client.java | 2590 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
// Create scanner to read from system in
Scanner input = new Scanner(System.in);
try {
while (true) {
// Start the socket
Socket client = new Socket("localhost", 4444); //ec2-54-229-5-118.eu-west-1.compute.amazonaws.com
System.out.println("Client started!");
System.out.print("Please enter the full path to the file you'd like to see: ");
String preliminaryMessage = input.nextLine();
// Exit closes the connection
if ("exit".equals(preliminaryMessage)) {
System.out.println("Connection terminated");
break;
// More than 20 chars is too long
} else if (preliminaryMessage.length() > 20) {
System.out.println("Message is too long");
// Spaces are forbidden
} else if (preliminaryMessage.contains(" ")) {
System.out.println("Message must not contain spaces");
} else {
// Put the message and the protocol info together
String finalMessageToServer = ("GET /" + preliminaryMessage + " " + "HTTP/1.0");
// These are needed for the messages being sent to the server
OutputStream out = client.getOutputStream();
PrintWriter writer = new PrintWriter(out);
// This is where we receive the messages from the server
InputStream in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// Actually send the message
writer.write(finalMessageToServer + "\n");
writer.flush();
// Print whatever the server sent until null is received
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
System.out.print(line + "\n");
}
}
}
} catch (IOException ex) {
ex.printStackTrace(System.out);
} finally {
}
}
}
| gpl-3.0 |
vpillac/vroom | Technicians/src/vroom/trsp/io/DynamicTRSPPersistenceHelper.java | 2893 | /**
*
*/
package vroom.trsp.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import vroom.common.modeling.dataModel.attributes.ReleaseDate;
import vroom.common.modeling.dataModel.attributes.RequestAttributeKey;
import vroom.trsp.datamodel.TRSPInstance;
/**
* <code>DynamicTRSPPersistenceHelper</code>
* <p>
* Creation date: Nov 8, 2011 - 3:07:06 PM
*
* @author Victor Pillac, <a href="http://uniandes.edu.co">Universidad de Los Andes</a>-<a
* href="http://copa.uniandes.edu.co">Copa</a> <a href="http://www.emn.fr">Ecole des Mines de Nantes</a>-<a
* href="http://www.irccyn.ec-nantes.fr/irccyn/d/en/equipes/Slp">SLP</a>
* @version 1.0
*/
public class DynamicTRSPPersistenceHelper implements ITRSPPersistenceHelper {
private final ITRSPPersistenceHelper mInstanceReader;
/**
* Creates a new <code>DynamicTRSPPersistenceHelper</code>
*
* @param instanceReader
* the persistence helper used to read the base instance
*/
public DynamicTRSPPersistenceHelper(ITRSPPersistenceHelper instanceReader) {
super();
mInstanceReader = instanceReader;
}
@Override
public TRSPInstance readInstance(File input, Object... params) throws Exception {
File dynFile = (File) params[0];
boolean cvrptw = (boolean) params[1];
TRSPInstance instance = mInstanceReader.readInstance(input, cvrptw);
readRelDates(instance, dynFile, false);
return instance;
}
/**
* Read the release dates from a file
*
* @param instance
* @param rdFile
* @param cvrpInstance
* @throws IOException
*/
public static void readRelDates(TRSPInstance instance, File rdFile, boolean cvrpInstance)
throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(rdFile));
// Skip the comment line and other info
reader.readLine();
reader.readLine();
reader.readLine();
reader.readLine();
String line = reader.readLine();
double dynReq = 0;
while (line != null) {
String[] info = line.split("\\s+");
int id = Integer.valueOf(info[0]);
int rd = Integer.valueOf(info[1]);
instance.getRequest(cvrpInstance ? instance.getDepotCount() + id - 1 : id)
.setAttribute(RequestAttributeKey.RELEASE_DATE, new ReleaseDate(rd));
if (rd >= 0)
dynReq++;
line = reader.readLine();
}
double dod = dynReq / instance.getRequestCount();
instance.setDod(dod);
reader.close();
}
@Override
public boolean writeInstance(TRSPInstance instance, File output) throws IOException {
throw new UnsupportedOperationException("Not implemented");
}
}
| gpl-3.0 |
F1rst-Unicorn/stocks | android-client/app/src/main/java/de/njsm/stocks/android/db/dbview/RecipeIngredientAmountAndStock.java | 4564 | /*
* stocks is client-server program to manage a household's food stock
* Copyright (C) 2021 The stocks developers
*
* This file is part of the stocks program suite.
*
* stocks 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.
*
* stocks 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 <https://www.gnu.org/licenses/>.
*/
package de.njsm.stocks.android.db.dbview;
import androidx.room.ColumnInfo;
import androidx.room.DatabaseView;
import static de.njsm.stocks.android.db.dbview.RecipeIngredientAmountAndStock.QUERY;
@DatabaseView(viewName = RecipeIngredientAmountAndStock.RECIPE_INGREDIENT_AMOUNT_AND_STOCK_TABLE, value = QUERY)
public class RecipeIngredientAmountAndStock {
public static final String RECIPE_INGREDIENT_AMOUNT_AND_STOCK_TABLE = "current_scaled_ingredient_amount_and_stock";
public static final String RECIPE_INGREDIENT_AMOUNT_AND_STOCK_PREFIX = RECIPE_INGREDIENT_AMOUNT_AND_STOCK_TABLE + "_";
public static final String QUERY ="select " +
"recipe._id as recipe_id, " +
"recipe_ingredient.ingredient as ingredient, " +
"recipe_ingredient.amount as required_amount, " +
"recipe_ingredient.unit as required_unit, " +
"current_scaled_amount.amount as present_amount, " +
"current_scaled_amount.scaled_unit__id as present_unit, " +
"cast(current_scaled_amount.amount as numeric) * coalesce((" +
"select factor " +
"from current_scaled_unit_conversion " +
"where source_id = current_scaled_amount.scaled_unit__id " +
"and target_id = recipe_ingredient.unit)," +
" 0) as present_amount_scaled " +
"from current_recipe recipe " +
"join current_recipe_ingredient recipe_ingredient on recipe_ingredient.recipe = recipe._id " +
"join current_scaled_amount current_scaled_amount on current_scaled_amount.of_type = recipe_ingredient.ingredient";
public static final String SCALED_AMOUNT_FIELDS_QUALIFIED =
RECIPE_INGREDIENT_AMOUNT_AND_STOCK_TABLE + ".recipe_id as " + RECIPE_INGREDIENT_AMOUNT_AND_STOCK_PREFIX + "recipe_id, " +
RECIPE_INGREDIENT_AMOUNT_AND_STOCK_TABLE + ".ingredient as " + RECIPE_INGREDIENT_AMOUNT_AND_STOCK_PREFIX + "ingredient, " +
RECIPE_INGREDIENT_AMOUNT_AND_STOCK_TABLE + ".required_amount as " + RECIPE_INGREDIENT_AMOUNT_AND_STOCK_PREFIX + "required_amount, " +
RECIPE_INGREDIENT_AMOUNT_AND_STOCK_TABLE + ".required_unit as " + RECIPE_INGREDIENT_AMOUNT_AND_STOCK_PREFIX + "required_unit, " +
RECIPE_INGREDIENT_AMOUNT_AND_STOCK_TABLE + ".present_amount as " + RECIPE_INGREDIENT_AMOUNT_AND_STOCK_PREFIX + "present_amount, " +
RECIPE_INGREDIENT_AMOUNT_AND_STOCK_TABLE + ".present_unit as " + RECIPE_INGREDIENT_AMOUNT_AND_STOCK_PREFIX + "present_unit, " +
RECIPE_INGREDIENT_AMOUNT_AND_STOCK_TABLE + ".present_amount_scaled as " + RECIPE_INGREDIENT_AMOUNT_AND_STOCK_PREFIX + "present_amount_scaled, ";
@ColumnInfo(name = "recipe_id")
private final int recipeId;
@ColumnInfo(name = "ingredient")
private final int ingredient;
@ColumnInfo(name = "required_amount")
private final int requiredAmount;
@ColumnInfo(name = "required_unit")
private final int requiredUnit;
@ColumnInfo(name = "present_amount")
private final int presentAmount;
@ColumnInfo(name = "present_unit")
private final int presentUnit;
@ColumnInfo(name = "present_amount_scaled")
private final int presentAmountScaled;
public RecipeIngredientAmountAndStock(int recipeId, int ingredient, int requiredAmount, int requiredUnit, int presentAmount, int presentUnit, int presentAmountScaled) {
this.recipeId = recipeId;
this.ingredient = ingredient;
this.requiredAmount = requiredAmount;
this.requiredUnit = requiredUnit;
this.presentAmount = presentAmount;
this.presentUnit = presentUnit;
this.presentAmountScaled = presentAmountScaled;
}
}
| gpl-3.0 |
boecker-lab/sirius_frontend | sirius_gui/src/main/java/de/unijena/bioinf/sirius/gui/io/DataFormatIdentifier.java | 1123 | package de.unijena.bioinf.sirius.gui.io;
import de.unijena.bioinf.myxo.io.spectrum.CSVFormatReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class DataFormatIdentifier {
private CSVFormatReader csv;
public DataFormatIdentifier() {
csv = new CSVFormatReader();
}
public DataFormat identifyFormat(File f){
if(f.getName().toLowerCase().endsWith(".ms")) return DataFormat.JenaMS;
else if(csv.isCompatible(f)) return DataFormat.CSV;
else if(f.getName().toLowerCase().endsWith(".mgf")) return DataFormat.MGF;
else if (f.getName().toLowerCase().endsWith(".txt")) return DataFormat.CSV;
else return DataFormat.NotSupported;
}
}
class MGFCompatibilityValidator{
public boolean isCompatible(File f){
try(BufferedReader reader = new BufferedReader(new FileReader(f))){
String temp = null;
while((temp = reader.readLine()) != null){
temp = temp.trim();
if(temp.isEmpty()) continue;
return temp.toUpperCase().equals("BEGIN IONS");
}
}catch(IOException e){
return false;
}
return false;
}
}
| gpl-3.0 |
ulises-jeremias/ayed | src/tests/ArbolGeneralTest.java | 1890 | package tests;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import arbolGeneral.ArbolGeneral;
public class ArbolGeneralTest {
ArbolGeneral<Integer> ag;
ArbolGeneral<Integer> a2;
ArbolGeneral<Integer> a3;
ArbolGeneral<Integer> a4;
ArbolGeneral<Integer> a5;
ArbolGeneral<Integer> a6;
ArbolGeneral<Integer> a7;
ArbolGeneral<Integer> a8;
ArbolGeneral<Integer> a9;
ArbolGeneral<Integer> a10;
@Before
public void setUp() throws Exception {
ag = new ArbolGeneral<Integer>(1);
a2 = new ArbolGeneral<Integer>(2);
a3 = new ArbolGeneral<Integer>(3);
a4 = new ArbolGeneral<Integer>(4);
a5 = new ArbolGeneral<Integer>(5);
a6 = new ArbolGeneral<Integer>(6);
a7 = new ArbolGeneral<Integer>(7);
a8 = new ArbolGeneral<Integer>(8);
a9 = new ArbolGeneral<Integer>(9);
a10= new ArbolGeneral<Integer>(10);
ag.agregarHijo(a2);
ag.agregarHijo(a3);
ag.agregarHijo(a4);
a2.agregarHijo(a5);
a3.agregarHijo(a6);
a3.agregarHijo(a7);
a3.agregarHijo(a8);
a4.agregarHijo(a9);
/* Arbol usado en las pruebas
1
2 3 4
5 6 7 8 9
*/
}
@Test
public void testAltura() {
assertEquals(new Integer(2), ag.altura());
assertEquals(new Integer(1), a2.altura());
assertEquals(new Integer(0), a5.altura());
}
@Test
public void testNivel() {
//Prueba para un arbol que es solo una hoja
assertEquals(new Integer(0), a5.nivel(5));
//Prueba para distintos elementos del arbol ag
assertEquals(new Integer(0), ag.nivel(1));
assertEquals(new Integer(1), ag.nivel(2));
assertEquals(new Integer(2), ag.nivel(7));
assertEquals(new Integer(2), ag.nivel(9));
assertEquals(new Integer(-1), ag.nivel(10));
}
@Test
public void testAncho() {
assertEquals(new Integer(5), ag.ancho());
assertEquals(new Integer(3), a3.ancho());
assertEquals(new Integer(1), a4.ancho());
}
}
| gpl-3.0 |
gama-platform/gama | msi.gama.core/src/msi/gama/util/file/GamaShapeFile.java | 15330 | /*******************************************************************************************************
*
* msi.gama.util.file.GamaShapeFile.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and
* simulation platform (v. 1.8.1)
*
* (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners
*
* Visit https://github.com/gama-platform/gama for license information and contacts.
*
********************************************************************************************************/
package msi.gama.util.file;
import static org.apache.commons.lang.StringUtils.join;
import static org.apache.commons.lang.StringUtils.splitByWholeSeparatorPreserveAllTokens;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;
import org.geotools.data.FeatureReader;
import org.geotools.data.Query;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.store.ContentFeatureSource;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.opengis.feature.Feature;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.feature.type.GeometryType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Polygon;
import msi.gama.common.geometry.Envelope3D;
import msi.gama.common.geometry.GeometryUtils;
import msi.gama.common.util.GISUtils;
import msi.gama.metamodel.shape.GamaGisGeometry;
import msi.gama.metamodel.shape.IShape;
import msi.gama.metamodel.topology.projection.ProjectionFactory;
import msi.gama.precompiler.GamlAnnotations.doc;
import msi.gama.precompiler.GamlAnnotations.example;
import msi.gama.precompiler.GamlAnnotations.file;
import msi.gama.precompiler.IConcept;
import msi.gama.runtime.GAMA;
import msi.gama.runtime.IScope;
import msi.gama.runtime.exceptions.GamaRuntimeException;
import msi.gama.util.GamaListFactory;
import msi.gama.util.IList;
import msi.gaml.operators.Strings;
import msi.gaml.types.IType;
import msi.gaml.types.Types;
import ummisco.gama.dev.utils.DEBUG;
/**
* Written by drogoul Modified on 13 nov. 2011
*
* @todo Description
*
*/
@file (
name = "shape",
extensions = { "shp" },
buffer_type = IType.LIST,
buffer_content = IType.GEOMETRY,
buffer_index = IType.INT,
concept = { IConcept.SHAPEFILE, IConcept.FILE },
doc = @doc ("Represents a shape file as defined by the ESRI standard. See https://en.wikipedia.org/wiki/Shapefile for more information."))
@SuppressWarnings ({ "unchecked", "rawtypes" })
public class GamaShapeFile extends GamaGisFile {
public static class ShapeInfo extends GamaFileMetaData {
final int itemNumber;
final CoordinateReferenceSystem crs;
final double width;
final double height;
final Map<String, String> attributes = new LinkedHashMap();
public ShapeInfo(final IScope scope, final URL url, final long modificationStamp) {
super(modificationStamp);
ShapefileDataStore store = null;
ReferencedEnvelope env = new ReferencedEnvelope();
CoordinateReferenceSystem crs1 = null;
int number = 0;
try {
store = getDataStore(url);
final SimpleFeatureSource source = store.getFeatureSource();
final SimpleFeatureCollection features = source.getFeatures();
try {
crs1 = source.getInfo().getCRS();
} catch (final Exception e) {
DEBUG.ERR("Ignored exception in ShapeInfo getCRS:" + e.getMessage());
}
env = source.getBounds();
if (crs1 == null) {
crs1 = GISUtils.manageGoogleCRS(url);
if (crs1 != null) {
env = new ReferencedEnvelope(env, crs1);
}
}
if (crs1 != null) {
try {
env = env.transform(new ProjectionFactory().getTargetCRS(scope), true);
} catch (final Exception e) {
throw e;
}
}
try {
number = features.size();
} catch (final Exception e) {
DEBUG.ERR("Error in loading shapefile: " + e.getMessage());
}
final java.util.List<AttributeDescriptor> att_list = store.getSchema().getAttributeDescriptors();
for (final AttributeDescriptor desc : att_list) {
String type;
if (desc.getType() instanceof GeometryType) {
type = "geometry";
} else {
type = Types.get(desc.getType().getBinding()).toString();
}
attributes.put(desc.getName().getLocalPart(), type);
}
} catch (final Exception e) {
DEBUG.ERR("Error in reading metadata of " + url);
e.printStackTrace();
} finally {
width = env.getWidth();
height = env.getHeight();
itemNumber = number;
this.crs = crs1;
if (store != null) {
store.dispose();
}
}
}
public CoordinateReferenceSystem getCRS() {
return crs;
}
public ShapeInfo(final String propertiesString) {
super(propertiesString);
final String[] segments = split(propertiesString);
itemNumber = Integer.parseInt(segments[1]);
final String crsString = segments[2];
CoordinateReferenceSystem theCRS;
if ("null".equals(crsString) || crsString.startsWith("Unknown")) {
theCRS = null;
} else {
try {
theCRS = CRS.parseWKT(crsString);
} catch (final Exception e) {
theCRS = null;
}
}
crs = theCRS;
width = Double.parseDouble(segments[3]);
height = Double.parseDouble(segments[4]);
if (segments.length > 5) {
final String[] names = splitByWholeSeparatorPreserveAllTokens(segments[5], SUB_DELIMITER);
final String[] types = splitByWholeSeparatorPreserveAllTokens(segments[6], SUB_DELIMITER);
for (int i = 0; i < names.length; i++) {
attributes.put(names[i], types[i]);
}
}
}
/**
* Method getSuffix()
*
* @see msi.gama.util.file.GamaFileMetaInformation#getSuffix()
*/
@Override
public String getSuffix() {
final StringBuilder sb = new StringBuilder();
appendSuffix(sb);
return sb.toString();
}
@Override
public void appendSuffix(final StringBuilder sb) {
sb.append(itemNumber).append(" object");
if (itemNumber > 1) {
sb.append("s");
}
sb.append(SUFFIX_DEL);
sb.append(crs == null ? "Unknown CRS" : crs.getName().getCode());
sb.append(SUFFIX_DEL);
sb.append(Math.round(width)).append("m x ");
sb.append(Math.round(height)).append("m");
}
@Override
public String getDocumentation() {
final StringBuilder sb = new StringBuilder();
sb.append("Shapefile").append(Strings.LN);
sb.append(itemNumber).append(" objects").append(Strings.LN);
sb.append("Dimensions: ").append(Math.round(width) + "m x " + Math.round(height) + "m").append(Strings.LN);
sb.append("Coordinate Reference System: ").append(crs == null ? "Unknown CRS" : crs.getName().getCode())
.append(Strings.LN);
if (!attributes.isEmpty()) {
sb.append("Attributes: ").append(Strings.LN);
attributes.forEach((k, v) -> sb.append("<li>").append(k).append(" (" + v + ")").append("</li>"));
}
return sb.toString();
}
public Map<String, String> getAttributes() {
return attributes;
}
@Override
public String toPropertyString() {
// See Issue #1603: .toWKT() && pa can sometimes cause problem with
// certain projections.
String system = crs == null ? "Unknown projection" : crs.toWKT();
try {
CRS.parseWKT(system);
} catch (final Exception e) {
// The toWKT()/parseWKT() pair has a problem
String srs = CRS.toSRS(crs);
if (srs == null && crs != null) {
srs = crs.getName().getCode();
}
system = "Unknown projection " + srs;
}
final String attributeNames = join(attributes.keySet(), SUB_DELIMITER);
final String types = join(attributes.values(), SUB_DELIMITER);
final Object[] toSave =
new Object[] { super.toPropertyString(), itemNumber, system, width, height, attributeNames, types };
return join(toSave, DELIMITER);
}
}
/**
* @throws GamaRuntimeException
* @param scope
* @param pathName
*/
@doc (
value = "This file constructor allows to read a shapefile (.shp) file",
examples = { @example (
value = "file f <- shape_file(\"file.shp\");",
isExecutable = false) })
public GamaShapeFile(final IScope scope, final String pathName) throws GamaRuntimeException {
super(scope, pathName, (Integer) null);
}
@doc (
value = "This file constructor allows to read a shapefile (.shp) file and specifying the coordinates system code, as an int (epsg code)",
examples = { @example (
value = "file f <- shape_file(\"file.shp\", \"32648\");",
isExecutable = false) })
public GamaShapeFile(final IScope scope, final String pathName, final Integer code) throws GamaRuntimeException {
super(scope, pathName, code);
}
@doc (
value = "This file constructor allows to read a shapefile (.shp) file and specifying the coordinates system code (epg,...,), as a string",
examples = { @example (
value = "file f <- shape_file(\"file.shp\", \"EPSG:32648\");",
isExecutable = false) })
public GamaShapeFile(final IScope scope, final String pathName, final String code) throws GamaRuntimeException {
super(scope, pathName, code);
}
@doc (
value = "This file constructor allows to read a shapefile (.shp) file and take a potential z value (not taken in account by default)",
examples = { @example (
value = "file f <- shape_file(\"file.shp\", true);",
isExecutable = false) })
public GamaShapeFile(final IScope scope, final String pathName, final boolean with3D) throws GamaRuntimeException {
super(scope, pathName, (Integer) null, with3D);
}
@doc (
value = "This file constructor allows to read a shapefile (.shp) file and specifying the coordinates system code, as an int (epsg code) and take a potential z value (not taken in account by default)",
examples = { @example (
value = "file f <- shape_file(\"file.shp\", \"32648\", true);",
isExecutable = false) })
public GamaShapeFile(final IScope scope, final String pathName, final Integer code, final boolean with3D)
throws GamaRuntimeException {
super(scope, pathName, code, with3D);
}
@doc (
value = "This file constructor allows to read a shapefile (.shp) file and specifying the coordinates system code (epg,...,), as a string and take a potential z value (not taken in account by default)",
examples = { @example (
value = "file f <- shape_file(\"file.shp\", \"EPSG:32648\",true);",
isExecutable = false) })
public GamaShapeFile(final IScope scope, final String pathName, final String code, final boolean with3D)
throws GamaRuntimeException {
super(scope, pathName, code, with3D);
}
/**
* @see msi.gama.util.GamaFile#fillBuffer()
*/
@Override
protected void fillBuffer(final IScope scope) throws GamaRuntimeException {
if (getBuffer() != null) { return; }
setBuffer(GamaListFactory.<IShape> create(Types.GEOMETRY));
readShapes(scope);
}
@Override
public IList<String> getAttributes(final IScope scope) {
ShapeInfo s;
final IFileMetaDataProvider p = scope.getGui().getMetaDataProvider();
if (p != null) {
s = (ShapeInfo) p.getMetaData(getFile(scope), false, true);
} else {
try {
s = new ShapeInfo(scope, getFile(scope).toURI().toURL(), 0);
} catch (final MalformedURLException e) {
return GamaListFactory.EMPTY_LIST;
}
}
return GamaListFactory.wrap(Types.STRING, s.attributes.keySet());
}
@Override
protected CoordinateReferenceSystem getOwnCRS(final IScope scope) {
ShapefileDataStore store = null;
try {
final URL url = getFile(scope).toURI().toURL();
store = getDataStore(url);
CoordinateReferenceSystem crs = store.getFeatureSource().getInfo().getCRS();
if (crs == null) {
crs = GISUtils.manageGoogleCRS(url);
}
return crs;
} catch (final IOException e) {
return null;
} finally {
if (store != null) {
store.dispose();
}
}
}
static ShapefileDataStore getDataStore(final URL url) {
final ShapefileDataStore store = new ShapefileDataStore(url);
store.setGeometryFactory(GeometryUtils.GEOMETRY_FACTORY);
store.setBufferCachingEnabled(true);
store.setMemoryMapped(true);
store.setCharset(Charset.forName("UTF8"));
return store;
}
protected void readShapes(final IScope scope) {
scope.getGui().getStatus(scope).beginSubStatus("Reading file " + getName(scope));
ShapefileDataStore store = null;
final File file = getFile(scope);
final IList list = getBuffer();
int size = 0;
try {
store = getDataStore(file.toURI().toURL());
final ContentFeatureSource source = store.getFeatureSource();
final Envelope3D env = Envelope3D.of(source.getBounds());
size = source.getCount(Query.ALL);
int index = 0;
computeProjection(scope, env);
try (FeatureReader reader = store.getFeatureReader()) {
while (reader.hasNext()) {
index++;
if (index % 20 == 0) {
scope.getGui().getStatus(scope).setSubStatusCompletion(index / (double) size);
}
final Feature feature = reader.next();
Geometry g = (Geometry) feature.getDefaultGeometryProperty().getValue();
if (g != null && !g.isEmpty() /* Fix for Issue 725 && 677 */ ) {
if (!with3D && !g.isValid()) {
g = GeometryUtils.cleanGeometry(g);
}
g = gis.transform(g);
if (!with3D) {
g.apply(ZERO_Z);
g.geometryChanged();
}
g = multiPolygonManagement(g);
GamaGisGeometry gt = new GamaGisGeometry(g, feature);
if (gt.getInnerGeometry() != null)
list.add(gt);
} else if (g == null) {
// See Issue 725
GAMA.reportError(scope,
GamaRuntimeException
.warning("GamaShapeFile.fillBuffer; geometry could not be added as it is "
+ "nil: " + feature.getIdentifier(), scope),
false);
}
}
}
} catch (final IOException e) {
throw GamaRuntimeException.create(e, scope);
} finally {
if (store != null) {
store.dispose();
}
scope.getGui().getStatus(scope).endSubStatus("Reading file " + getName(scope));
}
if (size > list.size()) {
GAMA.reportError(scope, GamaRuntimeException.warning("Problem with file " + getFile(scope) + ": only "
+ list.size() + " of the " + size + " geometries could be added", scope), false);
}
}
@Override
public Envelope3D computeEnvelope(final IScope scope) {
if (gis == null) {
ShapefileDataStore store = null;
try {
store = getDataStore(getFile(scope).toURI().toURL());
final Envelope3D env = Envelope3D.of(store.getFeatureSource().getBounds());
computeProjection(scope, env);
} catch (final IOException e) {
return Envelope3D.EMPTY;
} finally {
if (store != null) {
store.dispose();
}
}
}
return gis.getProjectedEnvelope();
}
}
| gpl-3.0 |
terrencewei/note | src/main/java/com/terrencewei/markdown/bean/OSSOutput.java | 1040 | package com.terrencewei.markdown.bean;
import java.util.Arrays;
/**
* Created by terrencewei on 2017/04/21.
*/
public class OSSOutput {
private boolean success;
private String code;
private String msg;
private OSSObject[] objects;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean pSuccess) {
success = pSuccess;
}
public String getCode() {
return code;
}
public void setCode(String pCode) {
code = pCode;
}
public String getMsg() {
return msg;
}
public void setMsg(String pMsg) {
msg = pMsg;
}
public OSSObject[] getObjects() {
return objects;
}
public void setObjects(OSSObject[] pObjects) {
objects = pObjects;
}
@Override
public String toString() {
return "OSSOutput [" + "success=" + success + ", code=" + code + ", msg=" + msg + ", objects="
+ Arrays.toString(objects) + ']';
}
}
| gpl-3.0 |
PeratX/Nukkit | src/main/java/cn/nukkit/entity/Entity.java | 50994 | package cn.nukkit.entity;
import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockDirt;
import cn.nukkit.block.BlockFire;
import cn.nukkit.block.BlockWater;
import cn.nukkit.entity.data.*;
import cn.nukkit.event.entity.*;
import cn.nukkit.event.player.PlayerTeleportEvent;
import cn.nukkit.item.Item;
import cn.nukkit.level.Level;
import cn.nukkit.level.Location;
import cn.nukkit.level.Position;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.math.AxisAlignedBB;
import cn.nukkit.math.NukkitMath;
import cn.nukkit.math.Vector2;
import cn.nukkit.math.Vector3;
import cn.nukkit.metadata.MetadataValue;
import cn.nukkit.metadata.Metadatable;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.nbt.tag.DoubleTag;
import cn.nukkit.nbt.tag.FloatTag;
import cn.nukkit.nbt.tag.ListTag;
import cn.nukkit.network.protocol.MobEffectPacket;
import cn.nukkit.network.protocol.RemoveEntityPacket;
import cn.nukkit.network.protocol.SetEntityDataPacket;
import cn.nukkit.plugin.Plugin;
import cn.nukkit.potion.Effect;
import cn.nukkit.timings.Timing;
import cn.nukkit.timings.Timings;
import cn.nukkit.timings.TimingsHistory;
import cn.nukkit.utils.ChunkException;
import java.lang.reflect.Constructor;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author MagicDroidX
*/
public abstract class Entity extends Location implements Metadatable {
public static final int NETWORK_ID = -1;
public abstract int getNetworkId();
public static final int DATA_TYPE_BYTE = 0;
public static final int DATA_TYPE_SHORT = 1;
public static final int DATA_TYPE_INT = 2;
public static final int DATA_TYPE_FLOAT = 3;
public static final int DATA_TYPE_STRING = 4;
public static final int DATA_TYPE_SLOT = 5;
public static final int DATA_TYPE_POS = 6;
public static final int DATA_TYPE_LONG = 7;
//public static final int DATA_TYPE_ROTATION = 7;
//public static final int DATA_TYPE_LONG = 8;
public static final int DATA_FLAGS = 0;
public static final int DATA_AIR = 1;
public static final int DATA_NAMETAG = 2;
public static final int DATA_SHOW_NAMETAG = 3;
public static final int DATA_SILENT = 4;
public static final int DATA_POTION_COLOR = 7;
public static final int DATA_POTION_AMBIENT = 8;
public static final int DATA_NO_AI = 15;
public static final int DATA_FLAG_ONFIRE = 0;
public static final int DATA_FLAG_SNEAKING = 1;
public static final int DATA_FLAG_RIDING = 2;
public static final int DATA_FLAG_SPRINTING = 3;
public static final int DATA_FLAG_ACTION = 4;
public static final int DATA_FLAG_INVISIBLE = 5;
public static final int DATA_LEAD_HOLDER = 23;
public static final int DATA_LEAD = 24;
public static long entityCount = 1;
private static final Map<String, Class<? extends Entity>> knownEntities = new HashMap<>();
private static final Map<String, String> shortNames = new HashMap<>();
protected Map<Integer, Player> hasSpawned = new HashMap<>();
protected final Map<Integer, Effect> effects = new ConcurrentHashMap<>();
protected long id;
protected int dataFlags = 0;
protected final EntityMetadata dataProperties = new EntityMetadata()
.putByte(DATA_FLAGS, 0)
.putShort(DATA_AIR, 300)
.putString(DATA_NAMETAG, "")
.putBoolean(DATA_SHOW_NAMETAG, true)
.putBoolean(DATA_SILENT, false)
.putBoolean(DATA_NO_AI, false)
.putLong(DATA_LEAD_HOLDER, -1)
.putByte(DATA_LEAD, 0);
public Entity rider = null;
public Entity riding = null;
public FullChunk chunk;
protected EntityDamageEvent lastDamageCause = null;
private List<Block> blocksAround = new ArrayList<>();
public double lastX;
public double lastY;
public double lastZ;
public boolean firstMove = true;
public double motionX;
public double motionY;
public double motionZ;
public Vector3 temporalVector;
public double lastMotionX;
public double lastMotionY;
public double lastMotionZ;
public double lastYaw;
public double lastPitch;
public AxisAlignedBB boundingBox;
public boolean onGround;
public boolean inBlock = false;
public boolean positionChanged;
public boolean motionChanged;
public int deadTicks = 0;
protected int age = 0;
protected int health = 20;
private int maxHealth = 20;
protected float ySize = 0;
public boolean keepMovement = false;
public float fallDistance = 0;
public int ticksLived = 0;
public int lastUpdate;
public int maxFireTicks;
public int fireTicks = 0;
public int inPortalTicks = 0;
public CompoundTag namedTag;
protected boolean isStatic = false;
public boolean isCollided = false;
public boolean isCollidedHorizontally = false;
public boolean isCollidedVertically = false;
public int noDamageTicks;
public boolean justCreated;
public boolean fireProof;
public boolean invulnerable;
protected Server server;
public double highestPosition;
public boolean closed = false;
protected Timing timing;
protected boolean isPlayer = false;
public float getHeight() {
return 0;
}
public float getEyeHeight() {
return this.getHeight() / 2 + 0.1f;
}
public float getWidth() {
return 0;
}
public float getLength() {
return 0;
}
protected double getStepHeight() {
return 0;
}
public boolean canCollide() {
return true;
}
protected float getGravity() {
return 0;
}
protected float getDrag() {
return 0;
}
public Entity(FullChunk chunk, CompoundTag nbt) {
if (this instanceof Player) {
return;
}
this.init(chunk, nbt);
}
protected void initEntity() {
if (this.namedTag.contains("ActiveEffects")) {
ListTag<CompoundTag> effects = this.namedTag.getList("ActiveEffects", CompoundTag.class);
for (CompoundTag e : effects.getAll()) {
Effect effect = Effect.getEffect(e.getByte("Id"));
if (effect == null) {
continue;
}
effect.setAmplifier(e.getByte("Amplifier")).setDuration(e.getInt("Duration")).setVisible(e.getBoolean("showParticles"));
this.addEffect(effect);
}
}
if (this.namedTag.contains("CustomName")) {
this.setNameTag(this.namedTag.getString("CustomName"));
if (this.namedTag.contains("CustomNameVisible")) {
this.setNameTagVisible(this.namedTag.getBoolean("CustomNameVisible"));
}
}
this.scheduleUpdate();
}
protected final void init(FullChunk chunk, CompoundTag nbt) {
if ((chunk == null || chunk.getProvider() == null)) {
throw new ChunkException("Invalid garbage Chunk given to Entity");
}
this.timing = Timings.getEntityTiming(this);
this.isPlayer = this instanceof Player;
this.temporalVector = new Vector3();
this.id = Entity.entityCount++;
this.justCreated = true;
this.namedTag = nbt;
this.chunk = chunk;
this.setLevel(chunk.getProvider().getLevel());
this.server = chunk.getProvider().getLevel().getServer();
this.boundingBox = new AxisAlignedBB(0, 0, 0, 0, 0, 0);
ListTag<DoubleTag> posList = this.namedTag.getList("Pos", DoubleTag.class);
ListTag<FloatTag> rotationList = this.namedTag.getList("Rotation", FloatTag.class);
ListTag<DoubleTag> motionList = this.namedTag.getList("Motion", DoubleTag.class);
this.setPositionAndRotation(
this.temporalVector.setComponents(
posList.get(0).data,
posList.get(1).data,
posList.get(2).data
),
rotationList.get(0).data,
rotationList.get(1).data
);
this.setMotion(this.temporalVector.setComponents(
motionList.get(0).data,
motionList.get(1).data,
motionList.get(2).data
));
if (!this.namedTag.contains("FallDistance")) {
this.namedTag.putFloat("FallDistance", 0);
}
this.fallDistance = this.namedTag.getFloat("FallDistance");
this.highestPosition = this.y + this.namedTag.getFloat("FallDistance");
if (!this.namedTag.contains("Fire") || this.namedTag.getShort("Fire") > 32767) {
this.namedTag.putShort("Fire", 0);
}
this.fireTicks = this.namedTag.getShort("Fire");
if (!this.namedTag.contains("Air")) {
this.namedTag.putShort("Air", 300);
}
this.setDataProperty(new ShortEntityData(DATA_AIR, this.namedTag.getShort("Air")), false);
if (!this.namedTag.contains("OnGround")) {
this.namedTag.putBoolean("OnGround", false);
}
this.onGround = this.namedTag.getBoolean("OnGround");
if (!this.namedTag.contains("Invulnerable")) {
this.namedTag.putBoolean("Invulnerable", false);
}
this.invulnerable = this.namedTag.getBoolean("Invulnerable");
this.chunk.addEntity(this);
this.level.addEntity(this);
this.initEntity();
this.lastUpdate = this.server.getTick();
this.server.getPluginManager().callEvent(new EntitySpawnEvent(this));
this.scheduleUpdate();
}
public boolean hasCustomName() {
return !this.getNameTag().isEmpty();
}
public String getNameTag() {
return this.getDataPropertyString(DATA_NAMETAG);
}
public boolean isNameTagVisible() {
return this.getDataPropertyBoolean(DATA_SHOW_NAMETAG);
}
public void setNameTag(String name) {
this.setDataProperty(new StringEntityData(DATA_NAMETAG, name));
}
public void setNameTagVisible() {
this.setNameTagVisible(true);
}
public void setNameTagVisible(boolean visible) {
this.setDataProperty(new ByteEntityData(DATA_SHOW_NAMETAG, visible ? 1 : 0));
}
public boolean isSneaking() {
return this.getDataFlag(DATA_FLAGS, DATA_FLAG_SNEAKING);
}
public void setSneaking() {
this.setSneaking(true);
}
public void setSneaking(boolean value) {
this.setDataFlag(DATA_FLAGS, DATA_FLAG_SNEAKING, value);
}
public boolean isSprinting() {
return this.getDataFlag(DATA_FLAGS, DATA_FLAG_SPRINTING);
}
public void setSprinting() {
this.setSprinting(true);
}
public void setSprinting(boolean value) {
this.setDataFlag(DATA_FLAGS, DATA_FLAG_SPRINTING, value);
}
public Map<Integer, Effect> getEffects() {
return effects;
}
public void removeAllEffects() {
for (Effect effect : this.effects.values()) {
this.removeEffect(effect.getId());
}
}
public void removeEffect(int effectId) {
if (this.effects.containsKey(effectId)) {
Effect effect = this.effects.get(effectId);
this.effects.remove(effectId);
effect.remove(this);
this.recalculateEffectColor();
}
}
public Effect getEffect(int effectId) {
return this.effects.containsKey(effectId) ? this.effects.get(effectId) : null;
}
public boolean hasEffect(int effectId) {
return this.effects.containsKey(effectId);
}
public void addEffect(Effect effect) {
if (effect == null) {
return; //here add null means add nothing
}
Effect oldEffect = this.effects.getOrDefault(effect.getId(), null);
if (oldEffect != null) {
if (Math.abs(effect.getAmplifier()) < Math.abs(oldEffect.getAmplifier())) return;
if (Math.abs(effect.getAmplifier()) == Math.abs(oldEffect.getAmplifier())
&& effect.getDuration() < oldEffect.getDuration()) return;
effect.add(this, true);
} else {
effect.add(this, false);
}
this.effects.put(effect.getId(), effect);
this.recalculateEffectColor();
if (effect.getId() == Effect.HEALTH_BOOST) {
this.setHealth(this.getHealth() + 4 * (effect.getAmplifier() + 1));
}
}
protected void recalculateEffectColor() {
int[] color = new int[3];
int count = 0;
boolean ambient = true;
for (Effect effect : this.effects.values()) {
if (effect.isVisible()) {
int[] c = effect.getColor();
color[0] += c[0] * (effect.getAmplifier() + 1);
color[1] += c[1] * (effect.getAmplifier() + 1);
color[2] += c[2] * (effect.getAmplifier() + 1);
count += effect.getAmplifier() + 1;
if (!effect.isAmbient()) {
ambient = false;
}
}
}
if (count > 0) {
int r = (color[0] / count) & 0xff;
int g = (color[1] / count) & 0xff;
int b = (color[2] / count) & 0xff;
this.setDataProperty(new IntEntityData(Entity.DATA_POTION_COLOR, (r << 16) + (g << 8) + b));
this.setDataProperty(new ByteEntityData(Entity.DATA_POTION_AMBIENT, ambient ? 1 : 0));
} else {
this.setDataProperty(new IntEntityData(Entity.DATA_POTION_COLOR, 0));
this.setDataProperty(new ByteEntityData(Entity.DATA_POTION_AMBIENT, 0));
}
}
public static Entity createEntity(String name, FullChunk chunk, CompoundTag nbt, Object... args) {
Entity entity = null;
if (knownEntities.containsKey(name)) {
Class<? extends Entity> clazz = knownEntities.get(name);
if (clazz == null) {
return null;
}
for (Constructor constructor : clazz.getConstructors()) {
if (entity != null) {
break;
}
if (constructor.getParameterCount() != (args == null ? 2 : args.length + 2)) {
continue;
}
try {
if (args == null || args.length == 0) {
entity = (Entity) constructor.newInstance(chunk, nbt);
} else {
Object[] objects = new Object[args.length + 2];
objects[0] = chunk;
objects[1] = nbt;
System.arraycopy(args, 0, objects, 2, args.length);
entity = (Entity) constructor.newInstance(objects);
}
} catch (Exception e) {
//ignore
}
}
}
return entity;
}
public static Entity createEntity(int type, FullChunk chunk, CompoundTag nbt, Object... args) {
return createEntity(String.valueOf(type), chunk, nbt, args);
}
public static boolean registerEntity(String name, Class<? extends Entity> clazz) {
return registerEntity(name, clazz, false);
}
public static boolean registerEntity(String name, Class<? extends Entity> clazz, boolean force) {
if (clazz == null) {
return false;
}
try {
int networkId = clazz.getField("NETWORK_ID").getInt(null);
knownEntities.put(String.valueOf(networkId), clazz);
} catch (Exception e) {
if (!force) {
return false;
}
}
knownEntities.put(name, clazz);
shortNames.put(clazz.getSimpleName(), name);
return true;
}
public void saveNBT() {
if (!(this instanceof Player)) {
this.namedTag.putString("id", this.getSaveId());
if (!this.getNameTag().equals("")) {
this.namedTag.putString("CustomName", this.getNameTag());
this.namedTag.putString("CustomNameVisible", String.valueOf(this.isNameTagVisible()));
} else {
this.namedTag.remove("CustomName");
this.namedTag.remove("CustomNameVisible");
}
}
this.namedTag.putList(new ListTag<DoubleTag>("Pos")
.add(new DoubleTag("0", this.x))
.add(new DoubleTag("1", this.y))
.add(new DoubleTag("2", this.z))
);
this.namedTag.putList(new ListTag<DoubleTag>("Motion")
.add(new DoubleTag("0", this.motionX))
.add(new DoubleTag("1", this.motionY))
.add(new DoubleTag("2", this.motionZ))
);
this.namedTag.putList(new ListTag<FloatTag>("Rotation")
.add(new FloatTag("0", (float) this.yaw))
.add(new FloatTag("1", (float) this.pitch))
);
this.namedTag.putFloat("FallDistance", this.fallDistance);
this.namedTag.putShort("Fire", this.fireTicks);
this.namedTag.putShort("Air", this.getDataPropertyShort(DATA_AIR));
this.namedTag.putBoolean("OnGround", this.onGround);
this.namedTag.putBoolean("Invulnerable", this.invulnerable);
if (!this.effects.isEmpty()) {
ListTag<CompoundTag> list = new ListTag<>("ActiveEffects");
for (Effect effect : this.effects.values()) {
list.add(new CompoundTag(String.valueOf(effect.getId()))
.putByte("Id", effect.getId())
.putByte("Amplifier", effect.getAmplifier())
.putInt("Duration", effect.getDuration())
.putBoolean("Ambient", false)
.putBoolean("ShowParticles", effect.isVisible())
);
}
this.namedTag.putList(list);
} else {
this.namedTag.remove("ActiveEffects");
}
}
public String getName() {
if (this.hasCustomName()) {
return this.getNameTag();
} else {
return this.getSaveId();
}
}
public final String getSaveId() {
return shortNames.getOrDefault(this.getClass().getSimpleName(), "");
}
public void spawnTo(Player player) {
if (!this.hasSpawned.containsKey(player.getLoaderId()) && player.usedChunks.containsKey(Level.chunkHash(this.chunk.getX(), this.chunk.getZ()))) {
this.hasSpawned.put(player.getLoaderId(), player);
}
}
public Map<Integer, Player> getViewers() {
return hasSpawned;
}
public void sendPotionEffects(Player player) {
for (Effect effect : this.effects.values()) {
MobEffectPacket pk = new MobEffectPacket();
pk.eid = 0;
pk.effectId = effect.getId();
pk.amplifier = effect.getAmplifier();
pk.particles = effect.isVisible();
pk.duration = effect.getDuration();
pk.eventId = MobEffectPacket.EVENT_ADD;
player.dataPacket(pk);
}
}
public void sendData(Player player) {
this.sendData(player, null);
}
public void sendData(Player player, EntityMetadata data) {
SetEntityDataPacket pk = new SetEntityDataPacket();
pk.eid = player == this ? 0 : this.getId();
pk.metadata = data == null ? this.dataProperties : data;
player.dataPacket(pk);
}
public void sendData(Player[] players) {
this.sendData(players, null);
}
public void sendData(Player[] players, EntityMetadata data) {
SetEntityDataPacket pk = new SetEntityDataPacket();
pk.eid = this.getId();
pk.metadata = data == null ? this.dataProperties : data;
Server.broadcastPacket(players, pk);
}
public void despawnFrom(Player player) {
if (this.hasSpawned.containsKey(player.getLoaderId())) {
RemoveEntityPacket pk = new RemoveEntityPacket();
pk.eid = this.getId();
player.dataPacket(pk);
this.hasSpawned.remove(player.getLoaderId());
}
}
public void attack(EntityDamageEvent source) {
if (hasEffect(Effect.FIRE_RESISTANCE)
&& (source.getCause() == EntityDamageEvent.CAUSE_FIRE
|| source.getCause() == EntityDamageEvent.CAUSE_FIRE_TICK
|| source.getCause() == EntityDamageEvent.CAUSE_LAVA)) {
source.setCancelled();
}
getServer().getPluginManager().callEvent(source);
if (source.isCancelled()) {
return;
}
setLastDamageCause(source);
setHealth(getHealth() - source.getFinalDamage());
}
public void attack(float damage) {
this.attack(new EntityDamageEvent(this, EntityDamageEvent.CAUSE_VOID, damage));
}
public void heal(EntityRegainHealthEvent source) {
this.server.getPluginManager().callEvent(source);
if (source.isCancelled()) {
return;
}
this.setHealth(this.getHealth() + source.getAmount());
}
public void heal(float amount) {
this.heal(new EntityRegainHealthEvent(this, amount, EntityRegainHealthEvent.CAUSE_REGEN));
}
public int getHealth() {
return health;
}
public boolean isAlive() {
return this.health > 0;
}
public void setHealth(float health) {
int h = (int) health;
if (this.health == h) {
return;
}
if (h <= 0) {
if (this.isAlive()) {
this.kill();
}
} else if (h <= this.getMaxHealth() || h < this.health) {
this.health = h;
} else {
this.health = this.getMaxHealth();
}
}
public void setLastDamageCause(EntityDamageEvent type) {
this.lastDamageCause = type;
}
public EntityDamageEvent getLastDamageCause() {
return lastDamageCause;
}
public int getMaxHealth() {
return maxHealth + (this.hasEffect(Effect.HEALTH_BOOST) ? 4 * (this.getEffect(Effect.HEALTH_BOOST).getAmplifier() + 1) : 0);
}
public void setMaxHealth(int maxHealth) {
this.maxHealth = maxHealth;
}
public boolean canCollideWith(Entity entity) {
return !this.justCreated && this != entity;
}
protected boolean checkObstruction(double x, double y, double z) {
int i = NukkitMath.floorDouble(x);
int j = NukkitMath.floorDouble(y);
int k = NukkitMath.floorDouble(z);
double diffX = x - i;
double diffY = y - j;
double diffZ = z - k;
if (!Block.transparent[this.level.getBlockIdAt(i, j, k)]) {
boolean flag = Block.transparent[this.level.getBlockIdAt(i - 1, j, k)];
boolean flag1 = Block.transparent[this.level.getBlockIdAt(i + 1, j, k)];
boolean flag2 = Block.transparent[this.level.getBlockIdAt(i, j - 1, k)];
boolean flag3 = Block.transparent[this.level.getBlockIdAt(i, j + 1, k)];
boolean flag4 = Block.transparent[this.level.getBlockIdAt(i, j, k - 1)];
boolean flag5 = Block.transparent[this.level.getBlockIdAt(i, j, k + 1)];
int direction = -1;
double limit = 9999;
if (flag) {
limit = diffX;
direction = 0;
}
if (flag1 && 1 - diffX < limit) {
limit = 1 - diffX;
direction = 1;
}
if (flag2 && diffY < limit) {
limit = diffY;
direction = 2;
}
if (flag3 && 1 - diffY < limit) {
limit = 1 - diffY;
direction = 3;
}
if (flag4 && diffZ < limit) {
limit = diffZ;
direction = 4;
}
if (flag5 && 1 - diffZ < limit) {
direction = 5;
}
double force = new Random().nextDouble() * 0.2 + 0.1;
if (direction == 0) {
this.motionX = -force;
return true;
}
if (direction == 1) {
this.motionX = force;
return true;
}
if (direction == 2) {
this.motionY = -force;
return true;
}
if (direction == 3) {
this.motionY = force;
return true;
}
if (direction == 4) {
this.motionZ = -force;
return true;
}
if (direction == 5) {
this.motionZ = force;
return true;
}
}
return false;
}
public boolean entityBaseTick() {
return this.entityBaseTick(1);
}
public boolean entityBaseTick(int tickDiff) {
Timings.entityBaseTickTimer.startTiming();
this.blocksAround = null;
this.justCreated = false;
if (!this.isAlive()) {
this.removeAllEffects();
this.despawnFromAll();
if (!this.isPlayer) {
this.close();
}
Timings.entityBaseTickTimer.stopTiming();
return false;
}
if (!this.effects.isEmpty()) {
for (Effect effect : this.effects.values()) {
if (effect.canTick()) {
effect.applyEffect(this);
}
effect.setDuration(effect.getDuration() - tickDiff);
if (effect.getDuration() <= 0) {
this.removeEffect(effect.getId());
}
}
}
boolean hasUpdate = false;
this.checkBlockCollision();
if (this.y <= -16 && this.isAlive()) {
EntityDamageEvent ev = new EntityDamageEvent(this, EntityDamageEvent.CAUSE_VOID, 10);
this.attack(ev);
hasUpdate = true;
}
if (this.fireTicks > 0) {
if (this.fireProof) {
this.fireTicks -= 4 * tickDiff;
if (this.fireTicks < 0) {
this.fireTicks = 0;
}
} else {
if (!this.hasEffect(Effect.FIRE_RESISTANCE) && ((this.fireTicks % 20) == 0 || tickDiff > 20)) {
EntityDamageEvent ev = new EntityDamageEvent(this, EntityDamageEvent.CAUSE_FIRE_TICK, 1);
this.attack(ev);
}
this.fireTicks -= tickDiff;
}
if (this.fireTicks <= 0) {
this.extinguish();
} else {
this.setDataFlag(DATA_FLAGS, DATA_FLAG_ONFIRE, true);
hasUpdate = true;
}
}
if (this.noDamageTicks > 0) {
this.noDamageTicks -= tickDiff;
if (this.noDamageTicks < 0) {
this.noDamageTicks = 0;
}
}
this.age += tickDiff;
this.ticksLived += tickDiff;
TimingsHistory.activatedEntityTicks++;
Timings.entityBaseTickTimer.stopTiming();
return hasUpdate;
}
protected void updateMovement() {
double diffPosition = (this.x - this.lastX) * (this.x - this.lastX) + (this.y - this.lastY) * (this.y - this.lastY) + (this.z - this.lastZ) * (this.z - this.lastZ);
double diffRotation = (this.yaw - this.lastYaw) * (this.yaw - this.lastYaw) + (this.pitch - this.lastPitch) * (this.pitch - this.lastPitch);
double diffMotion = (this.motionX - this.lastMotionX) * (this.motionX - this.lastMotionX) + (this.motionY - this.lastMotionY) * (this.motionY - this.lastMotionY) + (this.motionZ - this.lastMotionZ) * (this.motionZ - this.lastMotionZ);
if (diffPosition > 0.04 || diffRotation > 2.25 && (diffMotion > 0.0001 && this.getMotion().lengthSquared() <= 0.00001)) { //0.2 ** 2, 1.5 ** 2
this.lastX = this.x;
this.lastY = this.y;
this.lastZ = this.z;
this.lastYaw = this.yaw;
this.lastPitch = this.pitch;
this.addMovement(this.x, this.y + this.getEyeHeight(), this.z, this.yaw, this.pitch, this.yaw);
}
if (diffMotion > 0.0025 || (diffMotion > 0.0001 && this.getMotion().lengthSquared() <= 0.0001)) { //0.05 ** 2
this.lastMotionX = this.motionX;
this.lastMotionY = this.motionY;
this.lastMotionZ = this.motionZ;
this.addMotion(this.motionX, this.motionY, this.motionZ);
}
}
public void addMovement(double x, double y, double z, double yaw, double pitch, double headYaw) {
this.level.addEntityMovement(this.chunk.getX(), this.chunk.getZ(), this.id, x, y, z, yaw, pitch, headYaw);
}
public void addMotion(double motionX, double motionY, double motionZ) {
this.level.addEntityMotion(this.chunk.getX(), this.chunk.getZ(), this.id, motionX, motionY, motionZ);
}
public Vector3 getDirectionVector() {
Vector3 vector = super.getDirectionVector();
return this.temporalVector.setComponents(vector.x, vector.y, vector.z);
}
public Vector2 getDirectionPlane() {
return (new Vector2((float) (-Math.cos(Math.toRadians(this.yaw) - Math.PI / 2)), (float) (-Math.sin(Math.toRadians(this.yaw) - Math.PI / 2)))).normalize();
}
public boolean onUpdate(int currentTick) {
if (this.closed) {
return false;
}
if (!this.isAlive()) {
++this.deadTicks;
if (this.deadTicks >= 10) {
this.despawnFromAll();
if (!this.isPlayer) {
this.close();
}
}
return this.deadTicks < 10;
}
int tickDiff = currentTick - this.lastUpdate;
if (tickDiff <= 0) {
return false;
}
this.lastUpdate = currentTick;
boolean hasUpdate = this.entityBaseTick(tickDiff);
this.updateMovement();
return hasUpdate;
}
public final void scheduleUpdate() {
this.level.updateEntities.put(this.id, this);
}
public boolean isOnFire() {
return this.fireTicks > 0;
}
public void setOnFire(int seconds) {
int ticks = seconds * 20;
if (ticks > this.fireTicks) {
this.fireTicks = ticks;
}
}
public Integer getDirection() {
double rotation = (this.yaw - 90) % 360;
if (rotation < 0) {
rotation += 360.0;
}
if ((0 <= rotation && rotation < 45) || (315 <= rotation && rotation < 360)) {
return 2; //North
} else if (45 <= rotation && rotation < 135) {
return 3; //East
} else if (135 <= rotation && rotation < 225) {
return 0; //South
} else if (225 <= rotation && rotation < 315) {
return 1; //West
} else {
return null;
}
}
public void extinguish() {
this.fireTicks = 0;
this.setDataFlag(DATA_FLAGS, DATA_FLAG_ONFIRE, false);
}
public boolean canTriggerWalking() {
return true;
}
public void resetFallDistance() {
this.highestPosition = 0;
}
protected void updateFallState(boolean onGround) {
if (onGround) {
fallDistance = (float) (this.highestPosition - this.y);
if (fallDistance > 0) {
if (this instanceof EntityLiving && !this.isInsideOfWater()) {
this.fall(fallDistance);
}
this.resetFallDistance();
}
}
}
public AxisAlignedBB getBoundingBox() {
return this.boundingBox;
}
public void fall(float fallDistance) {
float damage = (float) Math.floor(fallDistance - 3 - (this.hasEffect(Effect.JUMP) ? this.getEffect(Effect.JUMP).getAmplifier() + 1 : 0));
if (damage > 0) {
EntityDamageEvent ev = new EntityDamageEvent(this, EntityDamageEvent.CAUSE_FALL, damage);
this.attack(ev);
}
if (fallDistance > 1) {
Block down = this.level.getBlock(this.temporalVector.setComponents(getFloorX(), getFloorY() - 1, getFloorZ()));
if (down.getId() == Item.FARMLAND) {
this.level.setBlock(this.temporalVector.setComponents(down.x, down.y, down.z), new BlockDirt(), true, true);
}
}
}
public void handleLavaMovement() {
//todo
}
public void moveFlying() {
//todo
}
public void onCollideWithPlayer(EntityHuman entityPlayer) {
}
protected boolean switchLevel(Level targetLevel) {
if (this.closed) {
return false;
}
if (this.isValid()) {
EntityLevelChangeEvent ev = new EntityLevelChangeEvent(this, this.level, targetLevel);
this.server.getPluginManager().callEvent(ev);
if (ev.isCancelled()) {
return false;
}
this.level.removeEntity(this);
if (this.chunk != null) {
this.chunk.removeEntity(this);
}
this.despawnFromAll();
}
this.setLevel(targetLevel);
this.level.addEntity(this);
this.chunk = null;
return true;
}
public Position getPosition() {
return new Position(this.x, this.y, this.z, this.level);
}
public Location getLocation() {
return new Location(this.x, this.y, this.z, this.yaw, this.pitch, this.level);
}
public boolean isInsideOfWater() {
double y = this.y + this.getEyeHeight();
Block block = this.level.getBlock(this.temporalVector.setComponents(NukkitMath.floorDouble(this.x), NukkitMath.floorDouble(y), NukkitMath.floorDouble(this.z)));
if (block instanceof BlockWater) {
double f = (block.y + 1) - (((BlockWater) block).getFluidHeightPercent() - 0.1111111);
return y < f;
}
return false;
}
public boolean isInsideOfSolid() {
double y = this.y + this.getEyeHeight();
Block block = this.level.getBlock(
this.temporalVector.setComponents(
NukkitMath.floorDouble(this.x),
NukkitMath.floorDouble(y),
NukkitMath.floorDouble(this.z))
);
AxisAlignedBB bb = block.getBoundingBox();
return bb != null && block.isSolid() && !block.isTransparent() && bb.intersectsWith(this.getBoundingBox());
}
public boolean isInsideOfFire() {
for (Block block : this.getBlocksAround()) {
if (block instanceof BlockFire) {
return true;
}
}
return false;
}
public boolean fastMove(double dx, double dy, double dz) {
if (dx == 0 && dy == 0 && dz == 0) {
return true;
}
Timings.entityMoveTimer.startTiming();
AxisAlignedBB newBB = this.boundingBox.getOffsetBoundingBox(dx, dy, dz);
if (server.getAllowFlight() || !this.level.hasCollision(this, newBB, false)) {
this.boundingBox = newBB;
}
this.x = (this.boundingBox.minX + this.boundingBox.maxX) / 2;
this.y = this.boundingBox.minY - this.ySize;
this.z = (this.boundingBox.minZ + this.boundingBox.maxZ) / 2;
this.checkChunks();
if (!this.onGround || dy != 0) {
AxisAlignedBB bb = this.boundingBox.clone();
bb.minY -= 0.75;
this.onGround = this.level.getCollisionBlocks(bb).length > 0;
}
this.isCollided = this.onGround;
this.updateFallState(this.onGround);
Timings.entityMoveTimer.stopTiming();
return true;
}
public boolean move(double dx, double dy, double dz) {
if (dx == 0 && dz == 0 && dy == 0) {
return true;
}
if (this.keepMovement) {
this.boundingBox.offset(dx, dy, dz);
this.setPosition(this.temporalVector.setComponents((this.boundingBox.minX + this.boundingBox.maxX) / 2, this.boundingBox.minY, (this.boundingBox.minZ + this.boundingBox.maxZ) / 2));
this.onGround = this.isPlayer;
return true;
} else {
Timings.entityMoveTimer.startTiming();
this.ySize *= 0.4;
double movX = dx;
double movY = dy;
double movZ = dz;
AxisAlignedBB axisalignedbb = this.boundingBox.clone();
AxisAlignedBB[] list = this.level.getCollisionCubes(this, this.level.getTickRate() > 1 ? this.boundingBox.getOffsetBoundingBox(dx, dy, dz) : this.boundingBox.addCoord(dx, dy, dz), false);
for (AxisAlignedBB bb : list) {
dy = bb.calculateYOffset(this.boundingBox, dy);
}
this.boundingBox.offset(0, dy, 0);
boolean fallingFlag = (this.onGround || (dy != movY && movY < 0));
for (AxisAlignedBB bb : list) {
dx = bb.calculateXOffset(this.boundingBox, dx);
}
this.boundingBox.offset(dx, 0, 0);
for (AxisAlignedBB bb : list) {
dz = bb.calculateZOffset(this.boundingBox, dz);
}
this.boundingBox.offset(0, 0, dz);
if (this.getStepHeight() > 0 && fallingFlag && this.ySize < 0.05 && (movX != dx || movZ != dz)) {
double cx = dx;
double cy = dy;
double cz = dz;
dx = movX;
dy = this.getStepHeight();
dz = movZ;
AxisAlignedBB axisalignedbb1 = this.boundingBox.clone();
this.boundingBox.setBB(axisalignedbb);
list = this.level.getCollisionCubes(this, this.boundingBox.addCoord(dx, dy, dz), false);
for (AxisAlignedBB bb : list) {
dy = bb.calculateYOffset(this.boundingBox, dy);
}
this.boundingBox.offset(0, dy, 0);
for (AxisAlignedBB bb : list) {
dx = bb.calculateXOffset(this.boundingBox, dx);
}
this.boundingBox.offset(dx, 0, 0);
for (AxisAlignedBB bb : list) {
dz = bb.calculateZOffset(this.boundingBox, dz);
}
this.boundingBox.offset(0, 0, dz);
this.boundingBox.offset(0, 0, dz);
if ((cx * cx + cz * cz) >= (dx * dx + dz * dz)) {
dx = cx;
dy = cy;
dz = cz;
this.boundingBox.setBB(axisalignedbb1);
} else {
this.ySize += 0.5;
}
}
this.x = (this.boundingBox.minX + this.boundingBox.maxX) / 2;
this.y = this.boundingBox.minY - this.ySize;
this.z = (this.boundingBox.minZ + this.boundingBox.maxZ) / 2;
this.checkChunks();
this.checkGroundState(movX, movY, movZ, dx, dy, dz);
this.updateFallState(this.onGround);
if (movX != dx) {
this.motionX = 0;
}
if (movY != dy) {
this.motionY = 0;
}
if (movZ != dz) {
this.motionZ = 0;
}
//TODO: vehicle collision events (first we need to spawn them!)
Timings.entityMoveTimer.stopTiming();
return true;
}
}
protected void checkGroundState(double movX, double movY, double movZ, double dx, double dy, double dz) {
this.isCollidedVertically = movY != dy;
this.isCollidedHorizontally = (movX != dx || movZ != dz);
this.isCollided = (this.isCollidedHorizontally || this.isCollidedVertically);
this.onGround = (movY != dy && movY < 0);
}
public List<Block> getBlocksAround() {
if (this.blocksAround == null) {
int minX = NukkitMath.floorDouble(this.boundingBox.minX);
int minY = NukkitMath.floorDouble(this.boundingBox.minY);
int minZ = NukkitMath.floorDouble(this.boundingBox.minZ);
int maxX = NukkitMath.ceilDouble(this.boundingBox.maxX);
int maxY = NukkitMath.ceilDouble(this.boundingBox.maxY);
int maxZ = NukkitMath.ceilDouble(this.boundingBox.maxZ);
this.blocksAround = new ArrayList<>();
for (int z = minZ; z <= maxZ; ++z) {
for (int x = minX; x <= maxX; ++x) {
for (int y = minY; y <= maxY; ++y) {
Block block = this.level.getBlock(this.temporalVector.setComponents(x, y, z));
if (block.hasEntityCollision()) {
this.blocksAround.add(block);
}
}
}
}
}
return this.blocksAround;
}
protected void checkBlockCollision() {
Vector3 vector = new Vector3(0, 0, 0);
for (Block block : this.getBlocksAround()) {
block.onEntityCollide(this);
block.addVelocityToEntity(this, vector);
}
if (vector.lengthSquared() > 0) {
vector = vector.normalize();
double d = 0.014d;
this.motionX += vector.x * d;
this.motionY += vector.y * d;
this.motionZ += vector.z * d;
}
}
public boolean setPositionAndRotation(Vector3 pos, double yaw, double pitch) {
if (this.setPosition(pos)) {
this.setRotation(yaw, pitch);
return true;
}
return false;
}
public void setRotation(double yaw, double pitch) {
this.yaw = yaw;
this.pitch = pitch;
this.scheduleUpdate();
}
protected void checkChunks() {
if (this.chunk == null || (this.chunk.getX() != ((int) this.x >> 4)) || this.chunk.getZ() != ((int) this.z >> 4)) {
if (this.chunk != null) {
this.chunk.removeEntity(this);
}
this.chunk = this.level.getChunk((int) this.x >> 4, (int) this.z >> 4, true);
if (!this.justCreated) {
Map<Integer, Player> newChunk = this.level.getChunkPlayers((int) this.x >> 4, (int) this.z >> 4);
for (Player player : new ArrayList<>(this.hasSpawned.values())) {
if (!newChunk.containsKey(player.getLoaderId())) {
this.despawnFrom(player);
} else {
newChunk.remove(player.getLoaderId());
}
}
for (Player player : newChunk.values()) {
this.spawnTo(player);
}
}
if (this.chunk == null) {
return;
}
this.chunk.addEntity(this);
}
}
public boolean setPosition(Vector3 pos) {
if (this.closed) {
return false;
}
if (pos instanceof Position && ((Position) pos).level != null && ((Position) pos).level != this.level) {
if (!this.switchLevel(((Position) pos).getLevel())) {
return false;
}
}
this.x = pos.x;
this.y = pos.y;
this.z = pos.z;
double radius = this.getWidth() / 2d;
this.boundingBox.setBounds(pos.x - radius, pos.y, pos.z - radius, pos.x + radius, pos.y + this.getHeight(), pos.z +
radius);
this.checkChunks();
return true;
}
public Vector3 getMotion() {
return new Vector3(this.motionX, this.motionY, this.motionZ);
}
public boolean setMotion(Vector3 motion) {
if (!this.justCreated) {
EntityMotionEvent ev = new EntityMotionEvent(this, motion);
this.server.getPluginManager().callEvent(ev);
if (ev.isCancelled()) {
return false;
}
}
this.motionX = motion.x;
this.motionY = motion.y;
this.motionZ = motion.z;
if (!this.justCreated) {
this.updateMovement();
}
return true;
}
public boolean isOnGround() {
return onGround;
}
public void kill() {
this.health = 0;
this.scheduleUpdate();
}
public boolean teleport(Vector3 pos) {
return this.teleport(pos, PlayerTeleportEvent.TeleportCause.PLUGIN);
}
public boolean teleport(Vector3 pos, PlayerTeleportEvent.TeleportCause cause) {
return this.teleport(Location.fromObject(pos, this.level, this.yaw, this.pitch), cause);
}
public boolean teleport(Position pos) {
return this.teleport(pos, PlayerTeleportEvent.TeleportCause.PLUGIN);
}
public boolean teleport(Position pos, PlayerTeleportEvent.TeleportCause cause) {
return this.teleport(Location.fromObject(pos, pos.level, this.yaw, this.pitch), cause);
}
public boolean teleport(Location location) {
return this.teleport(location, PlayerTeleportEvent.TeleportCause.PLUGIN);
}
public boolean teleport(Location location, PlayerTeleportEvent.TeleportCause cause) {
double yaw = location.yaw;
double pitch = location.pitch;
Location from = this.getLocation();
Location to = location;
if (cause != null) {
EntityTeleportEvent ev = new EntityTeleportEvent(this, from, to);
this.server.getPluginManager().callEvent(ev);
if (ev.isCancelled()) {
return false;
}
to = ev.getTo();
}
this.ySize = 0;
this.setMotion(this.temporalVector.setComponents(0, 0, 0));
if (this.setPositionAndRotation(to, yaw, pitch)) {
this.resetFallDistance();
this.onGround = true;
this.updateMovement();
return true;
}
return false;
}
public long getId() {
return this.id;
}
public void respawnToAll() {
for (Player player : this.hasSpawned.values()) {
this.spawnTo(player);
}
this.hasSpawned = new HashMap<>();
}
public void spawnToAll() {
if (this.chunk == null || this.closed) {
return;
}
for (Player player : this.level.getChunkPlayers(this.chunk.getX(), this.chunk.getZ()).values()) {
if (player.isOnline()) {
this.spawnTo(player);
}
}
}
public void despawnFromAll() {
for (Player player : new ArrayList<>(this.hasSpawned.values())) {
this.despawnFrom(player);
}
}
public void close() {
if (!this.closed) {
this.server.getPluginManager().callEvent(new EntityDespawnEvent(this));
this.closed = true;
this.despawnFromAll();
if (this.chunk != null) {
this.chunk.removeEntity(this);
}
if (this.level != null) {
this.level.removeEntity(this);
}
}
}
public boolean setDataProperty(EntityData data) {
return setDataProperty(data, true);
}
public boolean setDataProperty(EntityData data, boolean send) {
if (!Objects.equals(data, this.getDataProperties().get(data.getId()))) {
this.getDataProperties().put(data);
if (send)
this.sendData(this.hasSpawned.values().stream().toArray(Player[]::new), new EntityMetadata().put(this.dataProperties.get(data.getId())));
return true;
}
return false;
}
public EntityMetadata getDataProperties() {
return this.dataProperties;
}
public EntityData getDataProperty(int id) {
return this.getDataProperties().get(id);
}
public int getDataPropertyInt(int id) {
return this.getDataProperties().getInt(id);
}
public int getDataPropertyShort(int id) {
return this.getDataProperties().getShort(id);
}
public int getDataPropertyByte(int id) {
return this.getDataProperties().getByte(id);
}
public boolean getDataPropertyBoolean(int id) {
return this.getDataProperties().getBoolean(id);
}
public long getDataPropertyLong(int id) {
return this.getDataProperties().getLong(id);
}
public String getDataPropertyString(int id) {
return this.getDataProperties().getString(id);
}
public float getDataPropertyFloat(int id) {
return this.getDataProperties().getFloat(id);
}
public Item getDataPropertySlot(int id) {
return this.getDataProperties().getSlot(id);
}
public Vector3 getDataPropertyPos(int id) {
return this.getDataProperties().getPosition(id);
}
public int getDataPropertyType(int id) {
return this.getDataProperties().exists(id) ? this.getDataProperty(id).getType() : -1;
}
public void setDataFlag(int propertyId, int id) {
this.setDataFlag(propertyId, id, true);
}
public void setDataFlag(int propertyId, int id, boolean value) {
if (this.getDataFlag(propertyId, id) != value) {
int flags = this.getDataPropertyByte(propertyId);
flags ^= 1 << id;
this.setDataProperty(new ByteEntityData(propertyId, flags));
}
}
public boolean getDataFlag(int propertyId, int id) {
return ((this.getDataPropertyByte(propertyId) & 0xff) & (1 << id)) > 0;
}
@Override
public void setMetadata(String metadataKey, MetadataValue newMetadataValue) {
this.server.getEntityMetadata().setMetadata(this, metadataKey, newMetadataValue);
}
@Override
public List<MetadataValue> getMetadata(String metadataKey) {
return this.server.getEntityMetadata().getMetadata(this, metadataKey);
}
@Override
public boolean hasMetadata(String metadataKey) {
return this.server.getEntityMetadata().hasMetadata(this, metadataKey);
}
@Override
public void removeMetadata(String metadataKey, Plugin owningPlugin) {
this.server.getEntityMetadata().removeMetadata(this, metadataKey, owningPlugin);
}
public Server getServer() {
return server;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Entity other = (Entity) obj;
return this.getId() == other.getId();
}
@Override
public int hashCode() {
int hash = 7;
hash = (int) (29 * hash + this.getId());
return hash;
}
}
| gpl-3.0 |
addo37/AbilityBots | src/main/java/org/telegram/abilitybots/api/objects/Ability.java | 6118 | package org.telegram.abilitybots.api.objects;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.logging.BotLogger;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Lists.newArrayList;
import static java.lang.String.format;
import static java.util.Objects.hash;
import static java.util.Optional.ofNullable;
import static org.apache.commons.lang3.StringUtils.*;
/**
* An ability is a fully-fledged bot action that contains all the necessary information to process:
* <ol>
* <li>A response to a command</li>
* <li>A post-response to a command</li>
* <li>A reply to a sequence of actions</li>
* </ol>
* <p>
* In-order to instantiate an ability, you can call {@link Ability#builder()} to get the {@link AbilityBuilder}.
* Once you're done setting your ability, you'll call {@link AbilityBuilder#build()} to get your constructed ability.
* <p>
* The only optional fields in an ability are {@link Ability#info}, {@link Ability#postAction}, {@link Ability#flags} and {@link Ability#replies}.
*
* @author Abbas Abou Daya
*/
public final class Ability {
private static final String TAG = Ability.class.getSimpleName();
private final String name;
private final String info;
private final Locality locality;
private final Privacy privacy;
private final int argNum;
private final Consumer<MessageContext> action;
private final Consumer<MessageContext> postAction;
private final List<Reply> replies;
private final List<Predicate<Update>> flags;
private Ability(String name, String info, Locality locality, Privacy privacy, int argNum, Consumer<MessageContext> action, Consumer<MessageContext> postAction, List<Reply> replies, Predicate<Update>... flags) {
checkArgument(!isEmpty(name), "Method name cannot be empty");
checkArgument(!containsWhitespace(name), "Method name cannot contain spaces");
checkArgument(isAlphanumeric(name), "Method name can only be alpha-numeric", name);
this.name = name;
this.info = info;
this.locality = checkNotNull(locality, "Please specify a valid locality setting. Use the Locality enum class");
this.privacy = checkNotNull(privacy, "Please specify a valid privacy setting. Use the Privacy enum class");
checkArgument(argNum >= 0, "The number of arguments the method can handle CANNOT be negative. " +
"Use the number 0 if the method ignores the arguments OR uses as many as appended");
this.argNum = argNum;
this.action = checkNotNull(action, "Method action can't be empty. Please assign a function by using .action() method");
if (postAction == null)
BotLogger.info(TAG, format("No post action was detected for method with name [%s]", name));
this.flags = ofNullable(flags).map(Arrays::asList).orElse(newArrayList());
this.postAction = postAction;
this.replies = replies;
}
public static AbilityBuilder builder() {
return new AbilityBuilder();
}
public String name() {
return name;
}
public String info() {
return info;
}
public Locality locality() {
return locality;
}
public Privacy privacy() {
return privacy;
}
public int tokens() {
return argNum;
}
public Consumer<MessageContext> action() {
return action;
}
public Consumer<MessageContext> postAction() {
return postAction;
}
public List<Reply> replies() {
return replies;
}
public List<Predicate<Update>> flags() {
return flags;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("name", name)
.add("locality", locality)
.add("privacy", privacy)
.add("argNum", argNum)
.toString();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Ability ability = (Ability) o;
return argNum == ability.argNum &&
Objects.equal(name, ability.name) &&
locality == ability.locality &&
privacy == ability.privacy;
}
@Override
public int hashCode() {
return hash(name, info, locality, privacy, argNum, action, postAction, replies, flags);
}
public static class AbilityBuilder {
private String name;
private String info;
private Privacy privacy;
private Locality locality;
private int argNum;
private Consumer<MessageContext> consumer;
private Consumer<MessageContext> postConsumer;
private List<Reply> replies;
private Flag[] flags;
private AbilityBuilder() {
replies = newArrayList();
}
public AbilityBuilder action(Consumer<MessageContext> consumer) {
this.consumer = consumer;
return this;
}
public AbilityBuilder name(String name) {
this.name = name;
return this;
}
public AbilityBuilder info(String info) {
this.info = info;
return this;
}
public AbilityBuilder flag(Flag... flags) {
this.flags = flags;
return this;
}
public AbilityBuilder locality(Locality type) {
this.locality = type;
return this;
}
public AbilityBuilder input(int argNum) {
this.argNum = argNum;
return this;
}
public AbilityBuilder privacy(Privacy privacy) {
this.privacy = privacy;
return this;
}
public AbilityBuilder post(Consumer<MessageContext> postConsumer) {
this.postConsumer = postConsumer;
return this;
}
@SafeVarargs
public final AbilityBuilder reply(Consumer<Update> action, Predicate<Update>... conditions) {
replies.add(Reply.of(action, conditions));
return this;
}
public Ability build() {
return new Ability(name, info, locality, privacy, argNum, consumer, postConsumer, replies, flags);
}
}
}
| gpl-3.0 |
Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/spring-all/src/main/java/org/baeldung/shell/simple/SimpleURLConverter.java | 1009 | package org.baeldung.shell.simple;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.springframework.shell.core.Completion;
import org.springframework.shell.core.Converter;
import org.springframework.shell.core.MethodTarget;
import org.springframework.stereotype.Component;
@Component
public class SimpleURLConverter implements Converter<URL> {
@Override
public URL convertFromText(String value, Class<?> requiredType, String optionContext) {
try {
return new URL(value);
} catch (MalformedURLException ex) {
// Ignore
}
return null;
}
@Override
public boolean getAllPossibleValues(List<Completion> completions, Class<?> requiredType, String existingData, String optionContext, MethodTarget target) {
return false;
}
@Override
public boolean supports(Class<?> requiredType, String optionContext) {
return URL.class.isAssignableFrom(requiredType);
}
}
| gpl-3.0 |
Karlosjp/Clase-DAM | Luis Braille/1 DAM/Programacion - Entornos/Vacaciones navidad/src/ejercicio03/Main.java | 3785 | package ejercicio03;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String titulo, autor;
int ejemplares;
//se crea el objeto libro1 utilizando el constructor con parámetros
Libro libro1 = new Libro("El quijote", "Cervantes", 1, 0);
//se crea el objeto libro2 utilizando el constructor por defecto
Libro libro2 = new Libro();
System.out.print("Introduce titulo: ");
titulo = sc.nextLine();
System.out.print("Introduce autor: ");
autor = sc.nextLine();
System.out.print("Numero de ejemplares: ");
ejemplares = sc.nextInt();
//se asigna a libro2 los datos pedidos por teclado.
//para ello se utilizan los métodos setters
libro2.setStrTitulo(titulo);
libro2.setStrAutor(autor);
libro2.setIntEjemplares(ejemplares);
//se muestran por pantalla los datos del objeto libro1
//se utilizan los métodos getters para acceder al valor de los atributos
System.out.println("Libro 1:");
System.out.println("Titulo: " + libro1.getStrTitulo());
System.out.println("Autor: " + libro1.getStrAutor());
System.out.println("Ejemplares: " + libro1.getIntEjemplares());
System.out.println("Prestados: " + libro1.getIntPrestados());
System.out.println();
//se realiza un préstamo de libro1. El método devuelve true si se ha podido
//realizar el préstamo y false en caso contrario
if (libro1.prestamo()) {
System.out.println("Se ha prestado el libro " + libro1.getStrTitulo());
} else {
System.out.println("No quedan ejemplares del libro " + libro1.getStrTitulo() + " para prestar");
}
//se realiza una devolución de libro1. El método devuelve true si se ha podido
//realizar la devolución y false en caso contrario
if (libro1.devolucion()) {
System.out.println("Se ha devuelto el libro " + libro1.getStrTitulo());
} else {
System.out.println("No hay ejemplares del libro " + libro1.getStrTitulo() + " prestados");
}
//se realiza otro préstamo de libro1
if (libro1.prestamo()) {
System.out.println("Se ha prestado el libro " + libro1.getStrTitulo());
} else {
System.out.println("No quedan ejemplares del libro " + libro1.getStrTitulo() + " para prestar");
}
//se realiza otro préstamo de libro1. En este caso no se podrá realizar ya que
//solo hay un ejemplar de este libro y ya está prestado. Se mostrará por
//pantalla el mensaje No quedan ejemplares del libro
if (libro1.prestamo()) {
System.out.println("Se ha prestado el libro " + libro1.getStrTitulo());
} else {
System.out.println("No quedan ejemplares del libro " + libro1.getStrTitulo() + " para prestar");
}
//mostrar los datos del objeto libro1
System.out.println("Libro 1:");
System.out.println("Titulo: " + libro1.getStrTitulo());
System.out.println("Autor: " + libro1.getStrAutor());
System.out.println("Ejemplares: " + libro1.getIntEjemplares());
System.out.println("Prestados: " + libro1.getIntPrestados());
System.out.println();
//mostrar los datos del objeto libro2
System.out.println("Libro 2:");
System.out.println("Titulo: " + libro2.getStrTitulo());
System.out.println("Autor: " + libro2.getStrAutor());
System.out.println("Ejemplares: " + libro2.getIntEjemplares());
System.out.println("Prestados: " + libro2.getIntPrestados());
System.out.println();
}
}
| gpl-3.0 |
chvink/kilomek | megamek/src/megamek/common/weapons/ISMediumPulseLaserPrototype.java | 2437 | /**
* MegaMek - Copyright (C) 2005 Ben Mazur (bmazur@sev.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 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.
*/
/*
* Created on Sep 8, 2005
*
*/
package megamek.common.weapons;
import megamek.common.IGame;
import megamek.common.TechConstants;
import megamek.common.ToHitData;
import megamek.common.actions.WeaponAttackAction;
import megamek.server.Server;
/**
* @author Sebastian Brocks
*/
public class ISMediumPulseLaserPrototype extends PulseLaserWeapon {
/**
*
*/
private static final long serialVersionUID = -8402915088560062495L;
/**
*
*/
public ISMediumPulseLaserPrototype() {
super();
techLevel.put(2595, TechConstants.T_IS_EXPERIMENTAL);
name = "Medium Pulse Laser Prototype";
setInternalName("ISMediumPulseLaserPrototype");
addLookupName("IS Pulse Med Laser Prototype");
addLookupName("IS Medium Pulse Laser Prototype");
flags = flags.or(F_PROTOTYPE);
heat = 4;
damage = 6;
toHitModifier = -2;
shortRange = 2;
mediumRange = 4;
longRange = 6;
extremeRange = 8;
waterShortRange = 2;
waterMediumRange = 3;
waterLongRange = 4;
waterExtremeRange = 6;
tonnage = 2.0f;
criticals = 1;
bv = 48;
cost = 60000;
introDate = 2595;
extinctDate = 2609;
reintroDate = 3037;
availRating = new int[] { RATING_E, RATING_F, RATING_D };
techRating = RATING_E;
}
/*
* (non-Javadoc)
*
* @see
* megamek.common.weapons.Weapon#getCorrectHandler(megamek.common.ToHitData,
* megamek.common.actions.WeaponAttackAction, megamek.common.Game,
* megamek.server.Server)
*/
@Override
protected AttackHandler getCorrectHandler(ToHitData toHit,
WeaponAttackAction waa, IGame game, Server server) {
return new PrototypeLaserHandler(toHit, waa, game, server);
}
}
| gpl-3.0 |
ciasaboark/Nodyn | app/src/main/java/io/phobotic/nodyn_app/view/VerifyCheckOutView.java | 6695 | /*
* Copyright (c) 2019 Jonathan Nelson <ciasaboark@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.phobotic.nodyn_app.view;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Handler;
import android.text.Html;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
import java.util.Timer;
import java.util.TimerTask;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.preference.PreferenceManager;
import io.phobotic.nodyn_app.R;
import io.phobotic.nodyn_app.avatar.AvatarHelper;
import io.phobotic.nodyn_app.database.model.User;
import io.phobotic.nodyn_app.helper.AnimationHelper;
/**
* Created by Jonathan Nelson on 9/6/17.
*/
public class VerifyCheckOutView extends LinearLayout {
private static final String TAG = VerifyCheckinView.class.getSimpleName();
private final Context context;
private String headerText;
private String eulaText;
private ObservableMarkdownView markdownView;
private View rootView;
private User user;
private Timer timer;
private int scrollY = -1;
public VerifyCheckOutView(@NotNull User user, @NotNull Context context,
@Nullable AttributeSet attrs, String eulaText, String headerText) {
super(context, attrs);
this.context = context;
this.user = user;
this.eulaText = eulaText;
this.headerText = headerText;
init();
}
public void setHeaderText(String headerText) {
this.headerText = headerText;
initHeader();
}
public void setEulaText(String eulaText) {
this.eulaText = eulaText;
initMarkdown();
}
private void init() {
rootView = inflate(context, R.layout.view_verify_checkout, this);
markdownView = rootView.findViewById(R.id.markdown);
if (!isInEditMode()) {
initUserDetails();
initHeader();
initMarkdown();
}
}
private void initUserDetails() {
ImageView image = rootView.findViewById(R.id.image);
TextView textView = rootView.findViewById(R.id.username);
textView.setText(user.getName());
AvatarHelper helper = new AvatarHelper();
helper.loadAvater(context, user, image, 90);
}
private void showOrHideIndicator() {
if (!isInEditMode()) {
ImageView indicator = rootView.findViewById(R.id.fade_indicator);
boolean canScroll = canViewScroll();
boolean isAtBottom = isScrollAtBottom(scrollY);
if (!canScroll || isAtBottom) {
AnimationHelper.fadeOut(getContext(), indicator);
} else {
AnimationHelper.fadeIn(getContext(), indicator);
}
}
}
private boolean isScrollAtBottom(int scrollY) {
boolean isScrollAtBottom = false;
int height = (int) Math.floor(markdownView.getContentHeight() * markdownView.getScale());
int webViewHeight = markdownView.getHeight();
int cutoff = height - webViewHeight - 10;
if (scrollY >= cutoff) {
isScrollAtBottom = true;
}
return isScrollAtBottom;
}
private boolean canViewScroll() {
boolean canViewScroll = true;
int contentHeight = markdownView.getContentHeight();
int visibleHeight = markdownView.getHeight() - markdownView.getPaddingTop() - markdownView.getPaddingBottom();
canViewScroll = visibleHeight < contentHeight;
return canViewScroll;
}
private void initHeader() {
TextView headerTV = rootView.findViewById(R.id.header);
if (headerText == null || headerText.length() == 0) {
headerTV.setVisibility(View.GONE);
} else {
headerTV.setVisibility(View.VISIBLE);
//allow the text to be passed in as HTML formatted text and convert to a spannable
headerTV.setText(Html.fromHtml(headerText));
}
}
private void initMarkdown() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (eulaText.length() == 0) {
//if the EULA has been set to an empty string then don't use the default, just indicate that no
//+ EULA has been set
eulaText = getResources().getString(R.string.check_out_no_eula_set);
}
markdownView.loadMarkdown(eulaText, "file:///android_asset/markdown.css");
markdownView.setOnScrollChangeListener(new ObservableMarkdownView.OnScrollChangeListener() {
@Override
public void onScrollChange(WebView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
VerifyCheckOutView.this.scrollY = scrollY;
showOrHideIndicator();
}
@Override
public void onPageFinished() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
showOrHideIndicator();
}
}, 300);
}
});
markdownView.setBackgroundColor(getContext().getResources().getColor(R.color.dialog_window_background));
if (this.timer != null) {
timer.cancel();
}
this.timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//must run on the UI thread
post(new Runnable() {
@Override
public void run() {
showOrHideIndicator();
}
});
}
}, 0, 500);
}
public ObservableMarkdownView getMarkdownView() {
return markdownView;
}
}
| gpl-3.0 |
ckaestne/CIDE | CIDE_Language_ECMAScript/src/tmp/generated_ecmascript/AssignmentExpression1.java | 1481 | package tmp.generated_ecmascript;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public class AssignmentExpression1 extends AssignmentExpression {
public AssignmentExpression1(LeftHandSideExpression leftHandSideExpression, AssignmentOperator assignmentOperator, AssignmentExpression assignmentExpression, Token firstToken, Token lastToken) {
super(new Property[] {
new PropertyOne<LeftHandSideExpression>("leftHandSideExpression", leftHandSideExpression),
new PropertyOne<AssignmentOperator>("assignmentOperator", assignmentOperator),
new PropertyOne<AssignmentExpression>("assignmentExpression", assignmentExpression)
}, firstToken, lastToken);
}
public AssignmentExpression1(Property[] properties, IToken firstToken, IToken lastToken) {
super(properties,firstToken,lastToken);
}
public IASTNode deepCopy() {
return new AssignmentExpression1(cloneProperties(),firstToken,lastToken);
}
public LeftHandSideExpression getLeftHandSideExpression() {
return ((PropertyOne<LeftHandSideExpression>)getProperty("leftHandSideExpression")).getValue();
}
public AssignmentOperator getAssignmentOperator() {
return ((PropertyOne<AssignmentOperator>)getProperty("assignmentOperator")).getValue();
}
public AssignmentExpression getAssignmentExpression() {
return ((PropertyOne<AssignmentExpression>)getProperty("assignmentExpression")).getValue();
}
}
| gpl-3.0 |
adyavanapalli/princeton-algorithms | code/kdtree/KdTree.java | 1644 | import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.RectHV;
/**
*
*/
public class KdTree {
/**
*
*/
private class Point implements Comparable<Point> {
private Point2D point;
private String color;
private Point right;
private Point left;
public Point(Point2D point) {
this.point = point;
}
public int compareTo(Point that) {
if (that.color.equals("RED"))
return Double.compare(this.point.x(), that.point.x());
else // that.color == "BLUE"
return Double.compare(this.point.y(), that.point.y());
}
}
private Point root;
private int size;
/**
*
*/
public KdTree() {
root = null;
size = 0;
}
/**
*
*/
public boolean isEmpty() {
return size == 0;
}
/**
*
*/
public int size() {
return size;
}
/**
*
*/
public void insert(Point2D p) {
}
/**
*
*/
public boolean contains(Point2D p) {
return false;
}
/**
*
*/
public void draw() {
}
/**
*
*/
public Iterable<Point2D> range(RectHV rect) {
return null;
}
/**
*
*/
public Point2D nearest(Point2D p) {
return null;
}
/**
* Unit tests KdTree data type.
*/
public static void main(String[] args) {
KdTree tree = new KdTree();
tree.insert(new Point2D(1, 1));
tree.insert(new Point2D(2, 2));
System.out.println(tree.size());
}
}
| gpl-3.0 |
juangranadilla/TaskBan-Android | app/src/main/java/com/juangm/taskban_android/adapters/CardsAdapter.java | 4832 | package com.juangm.taskban_android.adapters;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.juangm.taskban_android.KanbanActivity;
import com.juangm.taskban_android.KanbanApplication;
import com.juangm.taskban_android.R;
import com.juangm.taskban_android.models.Card;
import java.util.List;
//Cards adapter to show every card in the corresponding list
public class CardsAdapter extends RecyclerView.Adapter<CardsAdapter.ViewHolder>{
private List<Card> mCards;
public CardsAdapter(List<Card> cards) {
mCards = cards;
}
//Define the fields of every card item in the list
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView description;
public LinearLayout leftColor;
public ViewHolder(View itemView) {
super(itemView);
description = (TextView) itemView.findViewById(R.id.card_description);
leftColor = (LinearLayout) itemView.findViewById(R.id.card_left_color);
}
}
@Override
public CardsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.item_card, parent, false);
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
@Override
public void onBindViewHolder(CardsAdapter.ViewHolder viewHolder, int position) {
// Get the data model based on position
final Card card = mCards.get(position);
TextView description = viewHolder.description;
description.setText(card.getContent());
LinearLayout leftColor = viewHolder.leftColor;
if(card.getCategory().equals("ready")) {
leftColor.setBackgroundColor(ContextCompat.getColor(
viewHolder.itemView.getContext(),
R.color.readyColor));
} else if(card.getCategory().equals("inprogress")) {
leftColor.setBackgroundColor(ContextCompat.getColor(
viewHolder.itemView.getContext(),
R.color.inprogressColor));
} else if(card.getCategory().equals("paused")) {
leftColor.setBackgroundColor(ContextCompat.getColor(
viewHolder.itemView.getContext(),
R.color.pausedColor));
} else if(card.getCategory().equals("testing")) {
leftColor.setBackgroundColor(ContextCompat.getColor(
viewHolder.itemView.getContext(),
R.color.testingColor));
} else if(card.getCategory().equals("done")) {
leftColor.setBackgroundColor(ContextCompat.getColor(
viewHolder.itemView.getContext(),
R.color.doneColor));
}
KanbanApplication application =
(KanbanApplication) viewHolder.itemView.getContext().getApplicationContext();
viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
final View view = v;
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext(), R.style.AlertDialogLightTheme);
builder.setTitle(v.getResources().getString(R.string.choose_action))
.setItems(R.array.actions_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(which == 0) {
//Move card to another category (column)
((KanbanActivity) view.getContext()).moveCardDialog(card);
} else if(which == 1) {
//Edit card
((KanbanActivity) view.getContext()).editCardDialog(card);
} else if(which == 2) {
//Delete card
((KanbanActivity) view.getContext()).deleteCardDialog(card);
}
}
})
.show();
return true;
}
});
}
// Return the total count of items
@Override
public int getItemCount() {
return mCards.size();
}
}
| gpl-3.0 |
corjohnson/IT405 | in_class/10_05/ActivityLifecycle/app/src/main/java/co/miniforge/corey/activitylifecycle/MainActivity.java | 2704 | package co.miniforge.corey.activitylifecycle;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
String logTag = "ActivityLifecycle";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(logTag, "onCreate Called");
/*
In onCreate, you would want to set up any parts of your
activity that you'd want ready before the user sees the
page. So you could call findViewById for the different
elements so that you have references to them already
*/
}
@Override
protected void onStart() {
super.onStart();
Log.i(logTag, "onStart Called");
/*
onStart is a good place to write code that should run just as the
Activity becomes visible. As an example, if you're making an app
that has an embedded camera, you'd initialize it here
*/
}
@Override
protected void onResume() {
super.onResume();
Log.i(logTag, "onResume Called");
/*
onResume is called when an activity is considered "in the foreground".
What this means is that if you have a little share button that brings up
a drawer from the bottom, or a modal that appears over the top of your
activity, when those are dismissed, onResume is called again
*/
}
@Override
protected void onPause() {
super.onPause();
Log.i(logTag, "onPause Called");
/*
onPause is called whenever your activity loses it's foreground state
So if you have a nav drawer from the bottom appear when you press a button,
then it will get the foreground state, and your activity's onPause will be called
*/
}
@Override
protected void onStop() {
super.onStop();
Log.i(logTag, "onStop Called");
/*
onStop is called when the activity is dismissed. So when you hit the home button, onStop
is called because your activity is no longer visible
*/
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(logTag, "onDestroy Called");
/*
onDestroy is called when your activity is garbage collected. Do any last minute clean up
here, but if you have caching or anything that needs to happen, it should probably be
done in onStop
*/
}
}
| gpl-3.0 |
axkr/symja_android_library | symja_android_library/matheclipse-external/src/main/java/uk/ac/ed/ph/snuggletex/semantics/TextInterpretation.java | 411 | /* $Id:TextInterpretation.java 179 2008-08-01 13:41:24Z davemckain $
*
* Copyright (c) 2010, The University of Edinburgh.
* All Rights Reserved
*/
package uk.ac.ed.ph.snuggletex.semantics;
/**
* Base for text- (i.e. not maths-) based interpretations.
*
* @author David McKain
* @version $Revision:179 $
*/
public interface TextInterpretation extends Interpretation {
/* Marker interface only */
}
| gpl-3.0 |
JohnyPeng/Note | android/NDKDemo/app/src/main/java/com/example/ndkdemo/CallMethodFromJni.java | 778 | package com.example.ndkdemo;
import android.content.Context;
import android.util.Log;
public class CallMethodFromJni {
private static final String TAG = "CallMethodFromJni";
private Context mContext;
public static void staticMethod(String fromJni) {
Log.d(TAG, "CallMethodFromJni.callStaticMethodFromJni: " + fromJni);
}
public CallMethodFromJni() {
Log.d(TAG, "CallMethodFromJni.CallMethodFromJni: CallMethodFromJni() initial");
}
public CallMethodFromJni(String fromJni) {
Log.d(TAG, "CallMethodFromJni.CallMethodFromJni: " + fromJni);
}
public void instanceMethod(String fromJni) {
Log.d(TAG, "CallMethodFromJni.callInstanceMethodFromJni: " + fromJni);
}
public void showJniToast() {
}
}
| gpl-3.0 |
alexeq/datacrown | datacrow-core/_source/net/datacrow/core/objects/helpers/Software.java | 3143 | /******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* Data / \ Crow *
* ^ ^ *
* info@datacrow.net *
* *
* This file is part of Data Crow. *
* Data Crow 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. *
* *
* Data Crow 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 net.datacrow.core.objects.helpers;
import net.datacrow.core.modules.DcModules;
import net.datacrow.core.objects.DcMediaObject;
public class Software extends DcMediaObject {
private static final long serialVersionUID = -7444435615496014105L;
public static final int _F_DEVELOPER = 1;
public static final int _G_PUBLISHER = 2;
public static final int _H_PLATFORM = 3;
public static final int _I_WEBPAGE = 4;
public static final int _K_CATEGORIES = 6;
public static final int _M_PICTUREFRONT = 8;
public static final int _N_PICTUREBACK = 9;
public static final int _O_PICTURECD = 10;
public static final int _P_SCREENSHOTONE = 11;
public static final int _Q_SCREENSHOTTWO = 12;
public static final int _R_SCREENSHOTTHREE = 13;
public static final int _S_SERIALKEY = 14;
public static final int _V_STATE = 17;
public static final int _W_STORAGEMEDIUM = 18;
public static final int _X_EAN = 19;
public static final int _Y_VERSION = 20;
public static final int _Z_LICENSE = 21;
public static final int _AA_COOP = 22;
public static final int _AB_MULTI = 23;
public Software() {
super(DcModules._SOFTWARE);
}
}
| gpl-3.0 |
ricecakesoftware/CommunityMedicalLink | ricecakesoftware.communitymedicallink.hl7/src/org/hl7/v3/PRPAMT201302UV02MemberIdUpdateMode.java | 936 |
package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>PRPA_MT201302UV02.Member.id.updateModeのJavaクラス。
*
* <p>次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。
* <p>
* <pre>
* <simpleType name="PRPA_MT201302UV02.Member.id.updateMode">
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="A"/>
* <enumeration value="N"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "PRPA_MT201302UV02.Member.id.updateMode")
@XmlEnum
public enum PRPAMT201302UV02MemberIdUpdateMode {
A,
N;
public String value() {
return name();
}
public static PRPAMT201302UV02MemberIdUpdateMode fromValue(String v) {
return valueOf(v);
}
}
| gpl-3.0 |
Allexit/GladiatorBrawler | core/src/com/saltosion/gladiator/state/WinState.java | 1394 | /**
* GladiatorBrawler is a 2D swordfighting game.
* Copyright (C) 2015 Jeasonfire/Allexit
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.saltosion.gladiator.state;
import com.saltosion.gladiator.gui.creators.WinGUICreator;
import com.saltosion.gladiator.util.AppUtil;
public class WinState extends BaseState {
private WinGUICreator guiCreator;
@Override
public void create() {
// Start from a clean slate
AppUtil.guiManager.clearGUI();
guiCreator = new WinGUICreator();
guiCreator.create();
}
@Override
public void update(float deltaTime) {
if (guiCreator.shouldReturn()) {
setState(new MainMenuState());
}
}
@Override
public void destroy() {
// Clear GUI so there's nothing leftover for the next state
AppUtil.guiManager.clearGUI();
}
}
| gpl-3.0 |
Vult-R/Astraeus-Java-Framework | src/main/java/com/astraeus/net/packet/in/EnterRegionPacket.java | 415 | package com.astraeus.net.packet.in;
import com.astraeus.game.world.entity.mob.player.Player;
import com.astraeus.net.packet.IncomingPacket;
import com.astraeus.net.packet.Receivable;
@IncomingPacket.IncomingPacketOpcode(IncomingPacket.ENTER_REGION)
public final class EnterRegionPacket implements Receivable {
@Override
public void handlePacket(Player player, IncomingPacket packet) {
}
}
| gpl-3.0 |
integram/cleverbus | core/src/test/java/org/cleverbus/core/camel/CamelBeanMethodOgnlFieldTest.java | 2801 | /*
* Copyright (C) 2015
* 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.cleverbus.core.camel;
import static org.hamcrest.CoreMatchers.is;
import org.apache.camel.Handler;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
/**
* Test suite for checking correct bean binding,
* see <a href="https://issues.apache.org/jira/browse/CAMEL-6687">CAMEL-6687</a>.
*/
public class CamelBeanMethodOgnlFieldTest extends CamelTestSupport {
@Produce
ProducerTemplate producer;
@Test
public void testBothValues() {
ExamplePojo fooBar = new ExamplePojo();
fooBar.setFoo("foo1");
fooBar.setBar("bar2");
String result = producer.requestBody("direct:routeONE", fooBar, String.class);
assertThat(result, is("foo: foo1; bar: bar2"));
}
@Test
public void testNullValue() {
ExamplePojo fooBar = new ExamplePojo();
fooBar.setFoo(null);
fooBar.setBar("test");
String result = producer.requestBody("direct:routeONE", fooBar, String.class);
assertThat(result, is("foo: null; bar: test"));
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:routeONE")
.bean(new ExampleBean(), "doWithFooBar(${body.foo}, ${body.bar})");
}
};
}
public static class ExampleBean {
@Handler
public String doWithFooBar(String foo, String bar) {
return String.format("foo: %s; bar: %s", foo, bar);
}
}
public static class ExamplePojo {
private String foo;
private String bar;
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
}
| gpl-3.0 |
fastlockel/BetonQuest | src/main/java/pl/betoncraft/betonquest/config/ConfigHandler.java | 15148 | /**
* BetonQuest - advanced quests for Bukkit
* Copyright (C) 2015 Jakub "Co0sh" Sapalski
*
* 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 pl.betoncraft.betonquest.config;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import pl.betoncraft.betonquest.BetonQuest;
import pl.betoncraft.betonquest.utils.Debug;
/**
*
* @author Co0sh
*/
public class ConfigHandler {
/**
* Active instance of the ConfigHandler.
*/
private static ConfigHandler instance;
/**
* Represents plugins root folder.
*/
private File folder;
/**
* Map containing accessors for every conversation.
*/
private HashMap<String, ConfigAccessor> conversationsMap = new HashMap<>();
/**
* Deprecated accessor for single conversations file, used only for updating
* configuration.
*/
private ConfigAccessor conversations;
/**
* Deprecated accessor for objectives file, used only for updating
* configuration.
*/
private ConfigAccessor objectives;
/**
* Accessor for conditions file.
*/
private ConfigAccessor conditions;
/**
* Accessor for events file.
*/
private ConfigAccessor events;
/**
* Accessor for messages file.
*/
private ConfigAccessor messages;
/**
* Accessor for npcs file.
*/
private ConfigAccessor npcs;
/**
* Accessor for journal file.
*/
private ConfigAccessor journal;
/**
* Accessor for items file.
*/
private ConfigAccessor items;
/**
* Creates new configuration handler, which makes it easier to access all
* those files.
*/
public ConfigHandler() {
instance = this;
// save default config if there isn't one
BetonQuest.getInstance().saveDefaultConfig();
BetonQuest.getInstance().reloadConfig();
BetonQuest.getInstance().saveConfig();
// create conversations folder if there isn't one
folder = new File(BetonQuest.getInstance().getDataFolder(), "conversations");
if (!folder.isDirectory()) {
folder.mkdirs();
}
// if it's empty copy default conversation
if (folder.listFiles().length == 0) {
File defaultConversation = new File(folder, "innkeeper.yml");
try {
Files.copy(BetonQuest.getInstance().getResource("defaultConversation.yml"),
defaultConversation.toPath());
} catch (IOException e) {
e.printStackTrace();
}
}
// put conversations accessors in the hashmap
for (File file : folder.listFiles()) {
conversationsMap.put(file.getName().substring(0, file.getName().indexOf(".")),
new ConfigAccessor(BetonQuest.getInstance(), file, file.getName()));
}
// load messages safely
try {
messages = new ConfigAccessor(BetonQuest.getInstance(), new File(BetonQuest.getInstance()
.getDataFolder(), "messages.yml"), "messages.yml");
messages.getConfig().getString("global.plugin_prefix");
} catch (Exception e) {
messages = new ConfigAccessor(BetonQuest.getInstance(), new File(BetonQuest.getInstance()
.getDataFolder(), "messages.yml"), "simple-messages.yml");
}
String simple = BetonQuest.getInstance().getConfig().getString("simple");
if (simple != null && simple.equals("true")) {
new File(BetonQuest.getInstance().getDataFolder(), "messages.yml").delete();
messages = new ConfigAccessor(BetonQuest.getInstance(), new File(BetonQuest.getInstance()
.getDataFolder(), "messages.yml"), "simple-messages.yml");
BetonQuest.getInstance().getConfig().set("simple", null);
BetonQuest.getInstance().saveConfig();
Debug.broadcast("Using simple language files!");
}
// put config accesors in fields
conversations = new ConfigAccessor(BetonQuest.getInstance(), new File(BetonQuest
.getInstance().getDataFolder(), "conversations.yml"), "conversations.yml");
objectives = new ConfigAccessor(BetonQuest.getInstance(), new File(BetonQuest.getInstance()
.getDataFolder(), "objectives.yml"), "objectives.yml");
conditions = new ConfigAccessor(BetonQuest.getInstance(), new File(BetonQuest.getInstance()
.getDataFolder(), "conditions.yml"), "conditions.yml");
events = new ConfigAccessor(BetonQuest.getInstance(), new File(BetonQuest.getInstance()
.getDataFolder(), "events.yml"), "events.yml");
npcs = new ConfigAccessor(BetonQuest.getInstance(), new File(BetonQuest.getInstance()
.getDataFolder(), "npcs.yml"), "npcs.yml");
journal = new ConfigAccessor(BetonQuest.getInstance(), new File(BetonQuest.getInstance()
.getDataFolder(), "journal.yml"), "journal.yml");
items = new ConfigAccessor(BetonQuest.getInstance(), new File(BetonQuest.getInstance()
.getDataFolder(), "items.yml"), "items.yml");
// save config if there isn't one
conditions.saveDefaultConfig();
events.saveDefaultConfig();
messages.saveDefaultConfig();
npcs.saveDefaultConfig();
journal.saveDefaultConfig();
items.saveDefaultConfig();
}
/**
* Retireves from configuration the string at supplied path. The path should
* follow this syntax: "filename.branch.(moreBranches).branch.variable". For
* example getting color for day in journal date would be
* "config.journal_colors.date.day". Everything should be handled as a
* string for simplicity's sake.
*
* @param rawPath
* path for the variable
* @return the String object representing requested variable
*/
public static String getString(String rawPath) {
// get parts of path
String[] parts = rawPath.split("\\.");
String first = parts[0];
String path = rawPath.substring(first.length() + 1);
String object;
// for every possible file try to access the path and return String
// object
switch (first) {
case "config":
object = BetonQuest.getInstance().getConfig().getString(path);
if (object == null) {
// if object is null then there is no such variable at
// specified path
Debug.info("Error while accessing path: " + rawPath);
}
return object;
case "conversations":
object = null;
// conversations should be handled with one more level, as they
// are in
// multiple files
String conversationID = path.split("\\.")[0];
String rest = path.substring(path.indexOf(".") + 1);
if (instance.conversationsMap.get(conversationID) != null) {
object = instance.conversationsMap.get(conversationID).getConfig()
.getString(rest);
}
if (object == null) {
Debug.info("Error while accessing path: " + rawPath);
}
return object;
case "objectives":
object = instance.objectives.getConfig().getString(path);
if (object == null) {
Debug.info("Error while accessing path: " + rawPath);
}
return object;
case "conditions":
object = instance.conditions.getConfig().getString(path);
if (object == null) {
Debug.info("Error while accessing path: " + rawPath);
}
return object;
case "events":
object = instance.events.getConfig().getString(path);
if (object == null) {
Debug.info("Error while accessing path: " + rawPath);
}
return object;
case "messages":
object = instance.messages.getConfig().getString(path);
if (object == null) {
Debug.info("Error while accessing path: " + rawPath);
}
return object;
case "npcs":
object = instance.npcs.getConfig().getString(path);
return object;
case "journal":
object = instance.journal.getConfig().getString(path);
if (object == null) {
Debug.info("Error while accessing path: " + rawPath);
}
return object;
case "items":
object = instance.items.getConfig().getString(path);
if (object == null) {
Debug.info("Error while accessing path: " + rawPath);
}
return object;
default:
Debug.info("Fatal error while accessing path: " + rawPath
+ " (there is no such file)");
return null;
}
}
public static boolean setString(String path, String value) {
if (path == null) return false;
String[] parts = path.split("\\.");
if (parts.length < 2) {
Debug.info("Not enough arguments in path");
return false;
}
String ID = parts[0];
ConfigAccessor convFile = null;
int i = 1;
if (ID.equals("conversations")) {
if (parts.length < 3) {
Debug.info("Not enough arguments in path");
return false;
}
Debug.info("Getting conversation accessor");
convFile = instance.conversationsMap.get(parts[1]);
i = 2;
} else if (ID.equals("config")) {
StringBuilder convPath = new StringBuilder();
while (i < parts.length) {
convPath.append(parts[i] + ".");
i++;
}
if (convPath.length() < 2) {
Debug.info("Path was too short");
return false;
}
BetonQuest.getInstance().reloadConfig();
BetonQuest.getInstance().getConfig().set(convPath.substring(0, convPath.length() - 1), value);
BetonQuest.getInstance().saveConfig();
Debug.info("Saved value to config");
return true;
} else {
Debug.info("Getting standard accessor");
try {
convFile = (ConfigAccessor) instance.getClass().getDeclaredField(ID).get(instance);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException
| IllegalAccessException e) {
Debug.info("Could not get the accessor: " + e.getMessage());
e.printStackTrace();
}
}
if (convFile == null) {
Debug.info("Accessor was null");
return false;
}
StringBuilder convPath = new StringBuilder();
while (i < parts.length) {
convPath.append(parts[i] + ".");
i++;
}
if (convPath.length() < 2) {
Debug.info("Path was too short");
return false;
}
convFile.reloadConfig();
convFile.getConfig().set(convPath.substring(0, convPath.length() - 1), value);
convFile.saveConfig();
Debug.info("Saved value to config");
return true;
}
/**
* Reloads all config files
*/
public static void reload() {
BetonQuest.getInstance().reloadConfig();
// put conversations accessors in the hashmap again, so it works just
// like
// reloading
instance.conversationsMap.clear();
for (File file : instance.folder.listFiles()) {
instance.conversationsMap.put(file.getName().substring(0, file.getName().indexOf(".")),
new ConfigAccessor(BetonQuest.getInstance(), file, file.getName()));
}
String simple = BetonQuest.getInstance().getConfig().getString("simple");
if (simple != null && simple.equals("true")) {
new File(BetonQuest.getInstance().getDataFolder(), "messages.yml").delete();
instance.messages = new ConfigAccessor(BetonQuest.getInstance(), new File(BetonQuest
.getInstance().getDataFolder(), "messages.yml"), "simple-messages.yml");
BetonQuest.getInstance().getConfig().set("simple", null);
BetonQuest.getInstance().saveConfig();
instance.messages.saveDefaultConfig();
Debug.broadcast("Using simple language files!");
}
instance.conditions.reloadConfig();
instance.events.reloadConfig();
instance.journal.reloadConfig();
instance.messages.reloadConfig();
instance.npcs.reloadConfig();
instance.objectives.reloadConfig();
instance.items.reloadConfig();
}
/**
* Retrieves a map containing all config accessors. Should be used for more
* advanced tasks than simply getting a String. Note that conversations are
* not included in this map. See {@link #getConversations()
* getConversations} method for that. Conversations accessor included in
* this map is just a deprecated old conversations file. The same situation
* is with unused objectives accessor.
*
* @return HashMap containing all config accessors
*/
public static HashMap<String, ConfigAccessor> getConfigs() {
HashMap<String, ConfigAccessor> map = new HashMap<>();
map.put("conversations", instance.conversations);
map.put("conditions", instance.conditions);
map.put("events", instance.events);
map.put("objectives", instance.objectives);
map.put("journal", instance.journal);
map.put("messages", instance.messages);
map.put("npcs", instance.npcs);
map.put("items", instance.items);
return map;
}
/**
* Retrieves map containing all conversation accessors.
*
* @return HashMap containing conversation accessors
*/
public static HashMap<String, ConfigAccessor> getConversations() {
return instance.conversationsMap;
}
} | gpl-3.0 |
BrainStone/SpacePackExtended | src/main/java/com/space/extended/model/ModelBeetle.java | 8048 | package com.space.extended.model;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.MathHelper;
public class ModelBeetle extends ModelBase {
// fields
ModelRenderer Head;
ModelRenderer Legleft1;
ModelRenderer Legleft2;
ModelRenderer Legleft3;
ModelRenderer Legright1;
ModelRenderer Legright2;
ModelRenderer Legright3;
ModelRenderer Neck1;
ModelRenderer Body1Top;
ModelRenderer Body2;
ModelRenderer Tail1;
ModelRenderer RearEnd2;
ModelRenderer Tail2;
ModelRenderer Tail3;
ModelRenderer Tail4;
ModelRenderer RearEnd1;
ModelRenderer Neck2;
ModelRenderer Body1;
public ModelBeetle() {
textureWidth = 128;
textureHeight = 64;
Head = new ModelRenderer(this, 32, 20);
Head.addBox(-2F, -2F, -4F, 4, 3, 5);
Head.setRotationPoint(0F, 16F, -6F);
Head.setTextureSize(128, 64);
Head.mirror = true;
setRotation(Head, 0F, 0F, 0F);
Legleft1 = new ModelRenderer(this, 18, 0);
Legleft1.addBox(-1F, -1F, -1F, 16, 2, 2);
Legleft1.setRotationPoint(4F, 16F, -1F);
Legleft1.setTextureSize(128, 64);
Legleft1.mirror = true;
setRotation(Legleft1, 0F, 0.5759587F, 0.1919862F);
Legleft2 = new ModelRenderer(this, 18, 0);
Legleft2.addBox(-1F, -1F, -1F, 16, 2, 2);
Legleft2.setRotationPoint(4F, 16F, 3F);
Legleft2.setTextureSize(128, 64);
Legleft2.mirror = true;
setRotation(Legleft2, 0F, -0.2792527F, 0.1919862F);
Legleft3 = new ModelRenderer(this, 18, 0);
Legleft3.addBox(-1F, -1F, -1F, 16, 2, 2);
Legleft3.setRotationPoint(4F, 16F, 7F);
Legleft3.setTextureSize(128, 64);
Legleft3.mirror = true;
setRotation(Legleft3, 0F, -0.5759587F, 0.1919862F);
Legright1 = new ModelRenderer(this, 18, 0);
Legright1.addBox(-15F, -1F, -1F, 16, 2, 2);
Legright1.setRotationPoint(-4F, 16F, -1F);
Legright1.setTextureSize(128, 64);
Legright1.mirror = true;
setRotation(Legright1, 0F, -0.5759587F, -0.1919862F);
Legright2 = new ModelRenderer(this, 18, 0);
Legright2.addBox(-15F, -1F, -1F, 16, 2, 2);
Legright2.setRotationPoint(-4F, 16F, 3F);
Legright2.setTextureSize(128, 64);
Legright2.mirror = true;
setRotation(Legright2, 0F, 0.2792527F, -0.1919862F);
Legright3 = new ModelRenderer(this, 18, 0);
Legright3.addBox(-15F, -1F, -1F, 16, 2, 2);
Legright3.setRotationPoint(-4F, 16F, 7F);
Legright3.setTextureSize(128, 64);
Legright3.mirror = true;
setRotation(Legright3, 0F, 0.5759587F, -0.1919862F);
Neck1 = new ModelRenderer(this, 32, 4);
Neck1.addBox(-4F, -4F, -8F, 8, 7, 1);
Neck1.setRotationPoint(0F, 15F, 4F);
Neck1.setTextureSize(128, 64);
Neck1.mirror = true;
setRotation(Neck1, 0F, 0F, 0F);
Body1Top = new ModelRenderer(this, 0, 34);
Body1Top.addBox(-5F, -4F, -6F, 6, 1, 10);
Body1Top.setRotationPoint(2F, 15F, 3F);
Body1Top.setTextureSize(128, 64);
Body1Top.mirror = true;
setRotation(Body1Top, 0F, 0F, 0F);
Body2 = new ModelRenderer(this, 0, 25);
Body2.addBox(-5F, -4F, -6F, 8, 5, 3);
Body2.setRotationPoint(1F, 17F, 15F);
Body2.setTextureSize(128, 64);
Body2.mirror = true;
setRotation(Body2, 0F, 0F, 0F);
Tail1 = new ModelRenderer(this, 0, 18);
Tail1.addBox(-5F, -4F, -6F, 6, 4, 2);
Tail1.setRotationPoint(2F, 17F, 18F);
Tail1.setTextureSize(128, 64);
Tail1.mirror = true;
setRotation(Tail1, 0F, 0F, 0F);
RearEnd2 = new ModelRenderer(this, 1, 0);
RearEnd2.addBox(-0.5F, -1F, -1F, 1, 1, 4);
RearEnd2.setRotationPoint(-1F, 10.5F, 22.10667F);
RearEnd2.setTextureSize(128, 64);
RearEnd2.mirror = true;
setRotation(RearEnd2, 0.7733151F, -0.6543436F, 0F);
Tail2 = new ModelRenderer(this, 0, 6);
Tail2.addBox(-5F, -4F, -6F, 4, 3, 2);
Tail2.setRotationPoint(3F, 17F, 20F);
Tail2.setTextureSize(128, 64);
Tail2.mirror = true;
setRotation(Tail2, 0F, 0F, 0F);
Tail3 = new ModelRenderer(this, 15, 12);
Tail3.addBox(-1F, -1F, -1F, 2, 2, 4);
Tail3.setRotationPoint(0F, 14F, 16F);
Tail3.setTextureSize(128, 64);
Tail3.mirror = true;
setRotation(Tail3, 0.2974289F, 0F, 0F);
Tail4 = new ModelRenderer(this, 1, 12);
Tail4.addBox(-1F, -1F, -1F, 1, 2, 4);
Tail4.setRotationPoint(0.5F, 12.69333F, 19.10667F);
Tail4.setTextureSize(128, 64);
Tail4.mirror = true;
setRotation(Tail4, 0.7733151F, 0F, 0F);
RearEnd1 = new ModelRenderer(this, 1, 0);
RearEnd1.addBox(-0.5F, -1F, -1F, 1, 1, 4);
RearEnd1.setRotationPoint(1F, 10.5F, 22.10667F);
RearEnd1.setTextureSize(128, 64);
RearEnd1.mirror = true;
setRotation(RearEnd1, 0.7681514F, 0.6520605F, 0.0194155F);
Neck2 = new ModelRenderer(this, 32, 13);
Neck2.addBox(-4F, -4F, -8F, 6, 5, 1);
Neck2.setRotationPoint(1F, 17F, 3F);
Neck2.setTextureSize(128, 64);
Neck2.mirror = true;
setRotation(Neck2, 0F, 0F, 0F);
Body1 = new ModelRenderer(this, 0, 46);
Body1.addBox(-5F, -4F, -6F, 10, 6, 12);
Body1.setRotationPoint(0F, 16F, 3F);
Body1.setTextureSize(128, 64);
Body1.mirror = true;
setRotation(Body1, 0F, 0F, 0F);
}
@Override
public void render(Entity entityIn, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw,
float headPitch, float scale) {
setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale, entityIn);
Head.render(scale);
Legleft1.render(scale);
Legleft2.render(scale);
Legleft3.render(scale);
Legright1.render(scale);
Legright2.render(scale);
Legright3.render(scale);
Neck1.render(scale);
Body1Top.render(scale);
Body2.render(scale);
Tail1.render(scale);
RearEnd2.render(scale);
Tail2.render(scale);
Tail3.render(scale);
Tail4.render(scale);
RearEnd1.render(scale);
Neck2.render(scale);
Body1.render(scale);
}
private void setRotation(ModelRenderer model, float x, float y, float z) {
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
@SuppressWarnings("unused")
@Override
public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw,
float headPitch, float scaleFactor, Entity entityIn) {
Head.rotateAngleY = netHeadYaw * 0.017453292F;
Head.rotateAngleX = headPitch * 0.017453292F;
float f = ((float) Math.PI / 4F);
Legleft1.rotateAngleZ = ((float) Math.PI / 4F);
Legleft2.rotateAngleZ = 0.58119464F;
Legleft3.rotateAngleZ = ((float) Math.PI / 4F);
Legright1.rotateAngleZ = -((float) Math.PI / 4F);
Legright2.rotateAngleZ = -0.58119464F;
Legright3.rotateAngleZ = -((float) Math.PI / 4F);
float f1 = -0.0F;
float f2 = 0.3926991F;
Legleft1.rotateAngleY = ((float) Math.PI / 4F);
Legleft2.rotateAngleY = -0.3926991F;
Legleft3.rotateAngleY = -((float) Math.PI / 4F);
Legright1.rotateAngleY = -((float) Math.PI / 4F);
Legright2.rotateAngleY = 0.3926991F;
Legright3.rotateAngleY = ((float) Math.PI / 4F);
float f3 = -(MathHelper.cos((limbSwing * 0.6662F * 2.0F) + 0.0F) * 0.4F) * limbSwingAmount;
float f4 = -(MathHelper.cos((limbSwing * 0.6662F * 2.0F) + (float) Math.PI) * 0.4F) * limbSwingAmount;
float f5 = -(MathHelper.cos((limbSwing * 0.6662F * 2.0F) + ((float) Math.PI / 2F)) * 0.4F) * limbSwingAmount;
float f6 = -(MathHelper.cos((limbSwing * 0.6662F * 2.0F) + (((float) Math.PI * 3F) / 2F)) * 0.4F)
* limbSwingAmount;
float f7 = Math.abs(MathHelper.sin((limbSwing * 0.6662F) + 0.0F) * 0.4F) * limbSwingAmount;
float f8 = Math.abs(MathHelper.sin((limbSwing * 0.6662F) + (float) Math.PI) * 0.4F) * limbSwingAmount;
float f9 = Math.abs(MathHelper.sin((limbSwing * 0.6662F) + ((float) Math.PI / 2F)) * 0.4F) * limbSwingAmount;
float f10 = Math.abs(MathHelper.sin((limbSwing * 0.6662F) + (((float) Math.PI * 3F) / 2F)) * 0.4F)
* limbSwingAmount;
Legleft1.rotateAngleY += -f6;
Legleft2.rotateAngleY += -f4;
Legleft3.rotateAngleY += -f3;
Legright1.rotateAngleY += f6;
Legright2.rotateAngleY += f4;
Legright3.rotateAngleY += f3;
Legleft1.rotateAngleZ += -f10;
Legleft2.rotateAngleZ += -f8;
Legleft3.rotateAngleZ += -f7;
Legright1.rotateAngleZ += f10;
Legright2.rotateAngleZ += f8;
Legright3.rotateAngleZ += f7;
}
}
| gpl-3.0 |
don4of4/AssetPortal | src/asset/portal/command/impl/DeleteCommand.java | 1333 | package asset.portal.command.impl;
import org.bukkit.entity.Player;
import asset.portal.command.Command;
import asset.portal.command.CommandPermissionException;
import asset.portal.command.CommandSyntaxException;
import asset.portal.gate.Gate;
import asset.portal.gate.GateRegistry;
import asset.portal.util.MessageConstants;
import asset.portal.util.PermissionConstants;
public class DeleteCommand implements Command {
private GateRegistry gateRegistry;
public DeleteCommand(GateRegistry gateRegistry) {
this.gateRegistry = gateRegistry;
}
public void execute(Player player, String[] args) throws CommandPermissionException, CommandSyntaxException {
if(!player.hasPermission(PermissionConstants.PORTAL_DELETE)) {
throw new CommandPermissionException(PermissionConstants.PORTAL_DELETE);
}
if(args.length < 1) {
throw new CommandSyntaxException("destinationServer");
}
String detinationServer = args[0];
Gate gate = this.gateRegistry.getByDestinationServer(detinationServer);
if(gate == null) {
player.sendMessage(MessageConstants.format(MessageConstants.DELETE_NO_EXIST, detinationServer));
return;
}
this.gateRegistry.unregister(gate);
player.sendMessage(MessageConstants.format(MessageConstants.DELETE_SUCCESS, detinationServer));
}
public String getId() {
return "delete";
}
}
| gpl-3.0 |
polyvi/openxface-android | framework/android/src/com/polyvi/xface/extension/XCallbackContext.java | 4721 |
/*
This file was modified from or inspired by Apache Cordova.
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package com.polyvi.xface.extension;
import org.json.JSONArray;
import org.json.JSONObject;
import com.polyvi.xface.plugin.api.XIWebContext;
import com.polyvi.xface.util.XLog;
public class XCallbackContext {
private static final String CLASS_NAME = XCallbackContext.class.getName();
private boolean mFinished;
private String mCallbackId;
private XIWebContext mWebContext;
public XCallbackContext(XIWebContext webContext, String callbackId) {
mWebContext = webContext;
mCallbackId = callbackId;
}
public boolean isFinished() {
return mFinished;
}
public String getCallbackId() {
return mCallbackId;
}
/**
* 发送执行扩展的结果
* @param extResult
*/
public void sendExtensionResult(XExtensionResult extResult) {
synchronized (this) {
if (mFinished) {
XLog.w(CLASS_NAME, "Send a callbackID: " + mCallbackId
+ "\nResult was: " + extResult.getMessage());
return;
} else {
mFinished = !extResult.getKeepCallback();
}
mWebContext.sendExtensionResult(extResult, mCallbackId);
}
}
/**
* 发送执行扩展的结果
* @param message
*/
public void sendExtensionResult(String message) {
mWebContext.sendJavascript(message);
}
/**
* 发送没有附加内容的成功回调结果
*/
public void success() {
sendExtensionResult(new XExtensionResult(XExtensionResult.Status.OK));
}
/**
* 发送JSON数据对象信息的成功回调结果
* @param message
*/
public void success(JSONObject message) {
sendExtensionResult(new XExtensionResult(XExtensionResult.Status.OK, message));
}
/**
* 发送String数据对象信息的成功回调结果
* @param message
*/
public void success(String message) {
sendExtensionResult(new XExtensionResult(XExtensionResult.Status.OK, message));
}
/**
* 发送JSONArray数据对象信息的成功回调结果
* @param message
*/
public void success(JSONArray message) {
sendExtensionResult(new XExtensionResult(XExtensionResult.Status.OK, message));
}
/**
* 发送long类型数据信息的成功回调结果
* @param message
*/
public void success(long value) {
sendExtensionResult(new XExtensionResult(XExtensionResult.Status.OK, value));
}
/**
* 发送boolean类型数据信息的成功回调结果
* @param message
*/
public void success(boolean value) {
sendExtensionResult(new XExtensionResult(XExtensionResult.Status.OK, value));
}
/**
* 发送没有附加内容的失败回调结果
*/
public void error() {
sendExtensionResult(new XExtensionResult(XExtensionResult.Status.ERROR));
}
/**
* 发送String数据对象信息的失败回调结果
* @param message
*/
public void error(String message) {
sendExtensionResult(new XExtensionResult(XExtensionResult.Status.ERROR, message));
}
/**
* 发送int数据对象信息的失败回调结果
* @param message
*/
public void error(int message) {
sendExtensionResult(new XExtensionResult(XExtensionResult.Status.ERROR, message));
}
/**
* 发送JSONObject数据对象信息的失败回调结果
* @param message
*/
public void error(JSONObject message) {
sendExtensionResult(new XExtensionResult(XExtensionResult.Status.ERROR, message));
}
/**
* 发送JSONArray数据对象信息的失败回调结果
* @param message
*/
public void error(JSONArray message) {
sendExtensionResult(new XExtensionResult(XExtensionResult.Status.ERROR, message));
}
}
| gpl-3.0 |
Deletescape-Media/Lawnchair | quickstep/recents_ui_overrides/src/com/android/quickstep/fallback/RecentsTaskController.java | 1167 | /*
* Copyright (C) 2018 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.android.quickstep.fallback;
import com.android.launcher3.uioverrides.touchcontrollers.TaskViewTouchController;
import com.android.quickstep.RecentsActivity;
public class RecentsTaskController extends TaskViewTouchController<RecentsActivity> {
public RecentsTaskController(RecentsActivity activity) {
super(activity);
}
@Override
protected boolean isRecentsInteractive() {
return mActivity.hasWindowFocus();
}
@Override
protected boolean isRecentsModal() {
return false;
}
}
| gpl-3.0 |
onycom-ankus/ankus_analyzer_G | trunk_web/ankus-web-services/src/main/java/org/ankus/web/engine/Update_Engineinfo.java | 4127 | /**
* Copyright (C) 2011 ankus Framework (http://www.openankus.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.ankus.web.engine;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
public class Update_Engineinfo extends HttpServlet {
/*
* db config 정보
* 2016.01.06
*
* by shm7255@onycom.com
*/
@Value("${jdbc.driver}")
public String jdbc_driver;
@Value("${jdbc.url}")
public String jdbc_url;
@Value("${jdbc.username}")
public String jdbc_username;
@Value("${jdbc.password}")
public String jdbc_password;
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// key와 value로 구성되어있는 HashMap 생성.
PrintWriter out = resp.getWriter();
Connection conn = null; // null로 초기화 한다.
String engineid = "", enginename="", engineip="",
engineport ="", cluster_id = "";
try{
String url = jdbc_url; //"jdbc:mysql://localhost:3306/"; // 사용하려는 데이터베이스명을 포함한 URL 기술
String id = jdbc_username; //"root"; // 사용자 계정
String pw = jdbc_password; //""; // 사용자 계정의 패스워드
// 사용자 계정의 패스워드
engineid = req.getParameter("id");
enginename = req.getParameter("name");
engineip = req.getParameter("engineIP");
engineport = req.getParameter("enginePort");
cluster_id = req.getParameter("hadoopClusterId");
Class.forName(jdbc_driver/*"com.mysql.jdbc.Driver"*/); // 데이터베이스와 연동하기 위해 DriverManager에 등록한다.
conn=DriverManager.getConnection(url,id,pw); // DriverManager 객체로부터 Connection 객체를 얻어온다.
System.out.println("제대로 연결되었습니다."); // 커넥션이 제대로 연결되면 수행된다.
java.sql.Statement st = null;
st = conn.createStatement();
String update_query="";
update_query = "UPDATE ENGINE SET name='" + enginename + "',";
update_query += "IP='" + engineip + "',";
update_query += "PORT='" + engineport + "',";
update_query += "CLUSTER_ID=" + cluster_id + "";
update_query += " WHERE ID = " + engineid;
System.out.println(update_query);
int rtn = st.executeUpdate(update_query);
JSONObject data = new JSONObject();
if(rtn >= 0)
{
data.put("success", "true");
//req.setAttribute("jsonStr", data);
System.out.println(data);
out.print(data);
}
else
{
data.put("success", "failed");
req.setAttribute("jsonStr", data);
System.out.println(data);
out.print(data);
}
st.close();
conn.close();
}
catch(Exception e)
{ // 예외가 발생하면 예외 상황을 처리한다.
System.out.println(e.toString());
}
}
}
| gpl-3.0 |
zluuluyenz/mtech | js/lab4/Notes.java | 6284 | package lab4;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Event;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.TextArea;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
// Notes Text editor
// Contains
// 1. TextArea
// 2. Open/Save Dialogs
// 3. Menus and MenuBar
// All of which are private to this class
public class Notes extends Frame
{
private TextArea t;
private FileDialog openDialog;
private FileDialog saveDialog;
private MenuBar mbar;
// The constructor where we initialize data
public Notes()
{
super("Notes Editor");
// For non-Win95 systems, try "Helvetica" or "TimesRoman"
// for the font name
Font f = new Font("TimesRoman", Font.PLAIN, 12);
setFont(f);
setBackground(Color.gray);
// Move the code out of the contructor into other methods
InitializeMenus();
InitializeTextArea();
InitializeToolBars();
openDialog = new FileDialog(this, "Open File...", FileDialog.LOAD);
saveDialog = new FileDialog(this, "Save File...", FileDialog.SAVE);
setMenuBar(mbar);
resize(300,200);
pack();
show();
}
// Reads from a file, throws an IOException if an error occured
public void read(String s) throws IOException
{
String line;
int i =0;
FileInputStream in = null;
BufferedInputStream bis = null;
DataInputStream dataIn = null;
try
{
in = new FileInputStream(s);
bis = new BufferedInputStream(in);
dataIn = new DataInputStream(bis);
}
catch(Throwable e)
{
System.out.println("Error in opening file");
return;
}
try
{
while ((line = dataIn.readLine()) != null)
{
t.insertText(line, i);
i++;
}
in.close();
}
catch(IOException e)
{
System.out.println("Error in reading file");
throw e;
}
}
// Writes to a file
public void write(String s) throws IOException
{
FileOutputStream out = null;
BufferedOutputStream bos = null;
DataOutputStream dataOut = null;
try
{
out = new FileOutputStream(s);
bos = new BufferedOutputStream(out);
dataOut = new DataOutputStream(bos);
}
catch (Throwable e)
{
System.out.println("Error in opening file");
return;
}
try
{
dataOut.writeChars(t.getText());
out.close();
}
catch(IOException e)
{
System.out.println("Error in writing to file");
throw e;
}
}
// Creates the menus and attaches it to the MenuBar
private void InitializeMenus()
{
mbar = new MenuBar();
Menu m = new Menu("File");
m.add(new MenuItem("New"));
m.add(new MenuItem("Open"));
m.add(new MenuItem("Save"));
m.add(new MenuItem("Save As"));
m.addSeparator();
m.add(new MenuItem("Quit"));
mbar.add(m);
m = new Menu("Help");
m.add(new MenuItem("Help!!!!"));
m.addSeparator();
m.add(new MenuItem("About..."));
mbar.add(m);
}
// Creates the TextArea
private void InitializeTextArea()
{
t = new TextArea("This is a TextArea", 24, 80);
t.setEditable(true);
add("Center", t);
}
// Creates the Toolbars
private void InitializeToolBars()
{
}
// Handle events that have occurred
public boolean handleEvent(Event evt)
{
switch(evt.id) {
case Event.WINDOW_DESTROY:
{
System.out.println("Exiting...");
System.exit(0);
return true;
}
// This can be handled
case Event.ACTION_EVENT:
{
String label = evt.arg.toString();
if(evt.target instanceof MenuItem)
{
// or "Open".equals(label)
// or evt.arg.equals("Open")
if (label.equals("Open"))
{
String filename;
openDialog.show();
// getFile() throws an exception
// So wee need to catch it if there is an error
try
{
filename = openDialog.getFile();
read(filename);
}
catch(IOException e)
{
System.out.println("File not found");
return true;
}
return true;
}
else if (label.equals("Save As"))
{
String filename;
try
{
filename = saveDialog.getFile();
write(filename);
}
catch(IOException e)
{
System.out.println("File not found");
return true;
}
saveDialog.show();
return true;
}
else if(label.equals("Quit"))
{
System.exit(0);
}
else if(label.equals("About..."))
{
AboutDialog ab = new AboutDialog(this);
ab.show();
return true;
}
}
}
default:
return false;
}
}
// Where execution begins in a stand-alone executable
public static void main(String args[])
{
new Notes();
}
}
// Sub-class(i.e child/descendant) of Dialog, put is NOT public
// because only one public class can reside in a file and that
// class is the name of the file
class AboutDialog extends Dialog
{
// Class is specific to "Notes", because it takes a parameter to
// to it. Can be made generic, by asking for a Frame instead
public AboutDialog(Notes parent)
{
super(parent, "About Dialog", true);
Panel p = new Panel();
p.add(new Button("OK"));
add("South", p);
resize(300,200);
}
// Same as the above. Except lets try something different
/*
public boolean handleEvent(Event evt)
{
switch(evt.id)
{
case Event.ACTION_EVENT:
{
if("OK".equals(evt.arg))
{
dispose();
return true;
}
}
default:
return false;
}
}
*/
// No different from the above handler
public boolean action(Event evt, Object arg)
{
if("Ok".equals(arg))
{
dispose();
return true;
}
return false;
}
}
| gpl-3.0 |
Harmades/PamelaGUI | src/test/java/basictest/PropertyTest.java | 2834 | package basictest;
import model.PamelaEntity;
import model.PamelaProperty;
import org.jboss.forge.roaster.Roaster;
import org.jboss.forge.roaster.model.source.JavaInterfaceSource;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openflexo.model.annotations.Getter;
import project.PamelaProject;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* Created by adria on 14/12/2016.
*/
public class PropertyTest {
private static final String BasicPamelaEntity1Path = "src/test/java/basictest/BasicPamelaEntity1.java";
private JavaInterfaceSource pamelaClazz;
@Before
public void initialize() throws IOException {
pamelaClazz = Roaster.parse(JavaInterfaceSource.class, new File(BasicPamelaEntity1Path));
}
@Test
public void getPropertiesTest() {
PamelaEntity entity = new PamelaEntity(pamelaClazz);
List<PamelaProperty> properties = entity.getProperties();
Assert.assertNotNull(properties);
Assert.assertFalse(properties.isEmpty());
Assert.assertNotNull(properties.get(0).getGetter());
Assert.assertNotNull(properties.get(0).getSetter());
}
@Test
public void addPropertiesTest() {
PamelaEntity entity = new PamelaEntity(pamelaClazz);
entity.addProperty("test", int.class.getCanonicalName());
Assert.assertTrue(entity.getProperties().size() == 2);
System.out.println(PamelaProject.serialize(entity));
}
@Test
public void removePropertiesTest() {
PamelaEntity entity = new PamelaEntity(pamelaClazz);
PamelaProperty propertyToRemove = entity.getProperty("MYATTRIBUTE");
Assert.assertNotNull(propertyToRemove);
entity.removeProperty(propertyToRemove.getIdentifier());
Assert.assertTrue(entity.getProperties().isEmpty());
}
@Test
public void modifyPropertyTest() {
PamelaEntity entity = new PamelaEntity(pamelaClazz);
PamelaProperty property = entity.getProperty("MYATTRIBUTE");
property.getGetter().setCardinality(Getter.Cardinality.MAP);
Assert.assertTrue(property.getGetter().getCardinality().equals(Getter.Cardinality.MAP));
}
@Test
public void addSetterToPropertyTest() {
PamelaEntity entity = new PamelaEntity(pamelaClazz);
PamelaProperty property = entity.addProperty("testAdd", int.class.getCanonicalName());
property.addSetter();
Assert.assertNotNull(property.getSetter());
Assert.assertTrue(entity.getProperties().size() == 2);
}
@Test
public void addEmbeddedTest() {
PamelaEntity entity = new PamelaEntity(pamelaClazz);
entity.getProperty("MYATTRIBUTE").addEmbedded();
Assert.assertTrue(entity.getProperty("MYATTRIBUTE").isEmbedded());
}
}
| gpl-3.0 |
huanghongxun/HMCL | HMCL/src/main/java/org/jackhuang/hmcl/ui/WebStage.java | 2808 | /*
* Hello Minecraft! Launcher
* Copyright (C) 2020 huangyuhui <huanghongxun2008@126.com> and contributors
*
* 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 <https://www.gnu.org/licenses/>.
*/
package org.jackhuang.hmcl.ui;
import com.jfoenix.controls.JFXProgressBar;
import javafx.beans.binding.Bindings;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import org.jackhuang.hmcl.Metadata;
import static org.jackhuang.hmcl.setting.ConfigHolder.config;
import static org.jackhuang.hmcl.ui.FXUtils.newImage;
public class WebStage extends Stage {
protected final StackPane pane = new StackPane();
protected final JFXProgressBar progressBar = new JFXProgressBar();
protected final WebView webView = new WebView();
protected final WebEngine webEngine = webView.getEngine();
public WebStage() {
this(800, 480);
}
public WebStage(int width, int height) {
setScene(new Scene(pane, width, height));
getScene().getStylesheets().addAll(config().getTheme().getStylesheets(config().getLauncherFontFamily()));
getIcons().add(newImage("/assets/img/icon.png"));
webView.getEngine().setUserDataDirectory(Metadata.HMCL_DIRECTORY.toFile());
webView.setContextMenuEnabled(false);
progressBar.progressProperty().bind(webView.getEngine().getLoadWorker().progressProperty());
progressBar.visibleProperty().bind(Bindings.createBooleanBinding(() -> {
switch (webView.getEngine().getLoadWorker().getState()) {
case SUCCEEDED:
case FAILED:
case CANCELLED:
return false;
default:
return true;
}
}, webEngine.getLoadWorker().stateProperty()));
BorderPane borderPane = new BorderPane();
borderPane.setPickOnBounds(false);
borderPane.setTop(progressBar);
progressBar.prefWidthProperty().bind(borderPane.widthProperty());
pane.getChildren().setAll(webView, borderPane);
}
public WebView getWebView() {
return webView;
}
}
| gpl-3.0 |
netgroup/hts-cycle | WiFiOnOff/src/it/uniroma2/wifionoff/ShutDownReceiver.java | 637 | package it.uniroma2.wifionoff;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ShutDownReceiver extends BroadcastReceiver {
private static final String Log_tag = "ShutDownReceiver";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
OnOffService.isOff();
ServiceCall ser=ServiceCall.getInstance(context);
ser.getCTX().unregisterReceiver(ser.netReceiver);
context.sendBroadcast(new Intent(Setting.TIMEOUT_OCCURRED));
Log.w(Log_tag,"B Received");
}
}
| gpl-3.0 |
SiLeBAT/FSK-Lab | de.bund.bfr.knime.pmm.nodes/src/de/bund/bfr/knime/pmm/dataviewandselect/SettingsHelper.java | 12121 | /*******************************************************************************
* Copyright (c) 2015 Federal Institute for Risk Assessment (BfR), Germany
*
* 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/>.
*
* Contributors:
* Department Biological Safety - BfR
*******************************************************************************/
package de.bund.bfr.knime.pmm.dataviewandselect;
import java.awt.Color;
import java.awt.Shape;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.NodeSettingsRO;
import org.knime.core.node.NodeSettingsWO;
import de.bund.bfr.knime.pmm.common.XmlConverter;
import de.bund.bfr.knime.pmm.common.chart.ChartConstants;
public class SettingsHelper {
protected static final String CFG_SELECTEDIDS = "SelectedIDs";
protected static final String CFG_COLORS = "Colors";
protected static final String CFG_SHAPES = "Shapes";
protected static final String CFG_SELECTALLIDS = "SelectAllIDs";
protected static final String CFG_MANUALRANGE = "ManualRange";
protected static final String CFG_MINX = "MinX";
protected static final String CFG_MAXX = "MaxX";
protected static final String CFG_MINY = "MinY";
protected static final String CFG_MAXY = "MaxY";
protected static final String CFG_DRAWLINES = "DrawLines";
protected static final String CFG_SHOWLEGEND = "ShowLegend";
protected static final String CFG_ADDLEGENDINFO = "AddLegendInfo";
protected static final String CFG_DISPLAYHIGHLIGHTED = "DisplayHighlighted";
protected static final String CFG_EXPORTASSVG = "ExportAsSvg";
protected static final String CFG_UNITX = "UnitX";
protected static final String CFG_UNITY = "UnitY";
protected static final String CFG_TRANSFORMX = "TransformX";
protected static final String CFG_TRANSFORMY = "TransformY";
protected static final String CFG_STANDARDVISIBLECOLUMNS = "StandardVisibleColumns";
protected static final String CFG_VISIBLECOLUMNS = "VisibleColumns";
protected static final String CFG_COLUMNWIDTHS = "ColumnWidths";
protected static final boolean DEFAULT_SELECTALLIDS = true;
protected static final boolean DEFAULT_MANUALRANGE = false;
protected static final double DEFAULT_MINX = 0.0;
protected static final double DEFAULT_MAXX = 100.0;
protected static final double DEFAULT_MINY = 0.0;
protected static final double DEFAULT_MAXY = 10.0;
protected static final boolean DEFAULT_DRAWLINES = false;
protected static final boolean DEFAULT_SHOWLEGEND = true;
protected static final boolean DEFAULT_ADDLEGENDINFO = false;
protected static final boolean DEFAULT_DISPLAYHIGHLIGHTED = true;
protected static final boolean DEFAULT_EXPORTASSVG = false;
protected static final String DEFAULT_TRANSFORM = ChartConstants.NO_TRANSFORM;
protected static final boolean DEFAULT_STANDARDVISIBLECOLUMNS = true;
private List<String> selectedIDs;
private Map<String, Color> colors;
private Map<String, Shape> shapes;
private boolean selectAllIDs;
private boolean manualRange;
private double minX;
private double maxX;
private double minY;
private double maxY;
private boolean drawLines;
private boolean showLegend;
private boolean addLegendInfo;
private boolean displayHighlighted;
private boolean exportAsSvg;
private String unitX;
private String unitY;
private String transformX;
private String transformY;
private boolean standardVisibleColumns;
private List<String> visibleColumns;
private Map<String, Integer> columnWidths;
public SettingsHelper() {
selectedIDs = new ArrayList<>();
colors = new LinkedHashMap<>();
shapes = new LinkedHashMap<>();
selectAllIDs = DEFAULT_SELECTALLIDS;
manualRange = DEFAULT_MANUALRANGE;
minX = DEFAULT_MINX;
maxX = DEFAULT_MAXX;
minY = DEFAULT_MINY;
maxY = DEFAULT_MAXY;
drawLines = DEFAULT_DRAWLINES;
showLegend = DEFAULT_SHOWLEGEND;
addLegendInfo = DEFAULT_ADDLEGENDINFO;
displayHighlighted = DEFAULT_DISPLAYHIGHLIGHTED;
exportAsSvg = DEFAULT_EXPORTASSVG;
unitX = null;
unitY = null;
transformX = DEFAULT_TRANSFORM;
transformY = DEFAULT_TRANSFORM;
standardVisibleColumns = DEFAULT_STANDARDVISIBLECOLUMNS;
visibleColumns = new ArrayList<>();
columnWidths = new LinkedHashMap<>();
}
public void loadSettings(NodeSettingsRO settings) {
try {
selectedIDs = XmlConverter.xmlToObject(
settings.getString(CFG_SELECTEDIDS),
new ArrayList<String>());
} catch (InvalidSettingsException e) {
}
try {
colors = XmlConverter.xmlToColorMap(settings.getString(CFG_COLORS));
} catch (InvalidSettingsException e) {
}
try {
shapes = XmlConverter.xmlToShapeMap(settings.getString(CFG_SHAPES));
} catch (InvalidSettingsException e) {
}
try {
selectAllIDs = settings.getBoolean(CFG_SELECTALLIDS);
} catch (InvalidSettingsException e) {
}
try {
manualRange = settings.getBoolean(CFG_MANUALRANGE);
} catch (InvalidSettingsException e) {
}
try {
minX = settings.getDouble(CFG_MINX);
} catch (InvalidSettingsException e) {
}
try {
maxX = settings.getDouble(CFG_MAXX);
} catch (InvalidSettingsException e) {
}
try {
minY = settings.getDouble(CFG_MINY);
} catch (InvalidSettingsException e) {
}
try {
maxY = settings.getDouble(CFG_MAXY);
} catch (InvalidSettingsException e) {
}
try {
drawLines = settings.getBoolean(CFG_DRAWLINES);
} catch (InvalidSettingsException e) {
}
try {
showLegend = settings.getBoolean(CFG_SHOWLEGEND);
} catch (InvalidSettingsException e) {
}
try {
addLegendInfo = settings.getBoolean(CFG_ADDLEGENDINFO);
} catch (InvalidSettingsException e) {
}
try {
displayHighlighted = settings.getBoolean(CFG_DISPLAYHIGHLIGHTED);
} catch (InvalidSettingsException e) {
}
try {
exportAsSvg = settings.getBoolean(CFG_EXPORTASSVG);
} catch (InvalidSettingsException e) {
}
try {
unitX = settings.getString(CFG_UNITX);
} catch (InvalidSettingsException e) {
}
try {
unitY = settings.getString(CFG_UNITY);
} catch (InvalidSettingsException e) {
}
try {
transformX = settings.getString(CFG_TRANSFORMX);
} catch (InvalidSettingsException e) {
}
try {
transformY = settings.getString(CFG_TRANSFORMY);
} catch (InvalidSettingsException e) {
}
try {
standardVisibleColumns = settings
.getBoolean(CFG_STANDARDVISIBLECOLUMNS);
} catch (InvalidSettingsException e) {
}
try {
visibleColumns = XmlConverter.xmlToObject(
settings.getString(CFG_VISIBLECOLUMNS),
new ArrayList<String>());
} catch (InvalidSettingsException e) {
}
try {
columnWidths = XmlConverter.xmlToObject(
settings.getString(CFG_COLUMNWIDTHS),
new LinkedHashMap<String, Integer>());
} catch (InvalidSettingsException e) {
}
}
public void saveSettings(NodeSettingsWO settings) {
settings.addString(CFG_SELECTEDIDS,
XmlConverter.objectToXml(selectedIDs));
settings.addString(CFG_COLORS, XmlConverter.colorMapToXml(colors));
settings.addString(CFG_SHAPES, XmlConverter.shapeMapToXml(shapes));
settings.addBoolean(CFG_SELECTALLIDS, selectAllIDs);
settings.addBoolean(CFG_MANUALRANGE, manualRange);
settings.addDouble(CFG_MINX, minX);
settings.addDouble(CFG_MAXX, maxX);
settings.addDouble(CFG_MINY, minY);
settings.addDouble(CFG_MAXY, maxY);
settings.addBoolean(CFG_DRAWLINES, drawLines);
settings.addBoolean(CFG_SHOWLEGEND, showLegend);
settings.addBoolean(CFG_ADDLEGENDINFO, addLegendInfo);
settings.addBoolean(CFG_DISPLAYHIGHLIGHTED, displayHighlighted);
settings.addBoolean(CFG_EXPORTASSVG, exportAsSvg);
settings.addString(CFG_UNITX, unitX);
settings.addString(CFG_UNITY, unitY);
settings.addString(CFG_TRANSFORMX, transformX);
settings.addString(CFG_TRANSFORMY, transformY);
settings.addBoolean(CFG_STANDARDVISIBLECOLUMNS, standardVisibleColumns);
settings.addString(CFG_VISIBLECOLUMNS,
XmlConverter.objectToXml(visibleColumns));
settings.addString(CFG_COLUMNWIDTHS,
XmlConverter.objectToXml(columnWidths));
}
public List<String> getSelectedIDs() {
return selectedIDs;
}
public void setSelectedIDs(List<String> selectedIDs) {
this.selectedIDs = selectedIDs;
}
public Map<String, Color> getColors() {
return colors;
}
public void setColors(Map<String, Color> colors) {
this.colors = colors;
}
public Map<String, Shape> getShapes() {
return shapes;
}
public void setShapes(Map<String, Shape> shapes) {
this.shapes = shapes;
}
public boolean isSelectAllIDs() {
return selectAllIDs;
}
public void setSelectAllIDs(boolean selectAllIDs) {
this.selectAllIDs = selectAllIDs;
}
public boolean isManualRange() {
return manualRange;
}
public void setManualRange(boolean manualRange) {
this.manualRange = manualRange;
}
public double getMinX() {
return minX;
}
public void setMinX(double minX) {
this.minX = minX;
}
public double getMaxX() {
return maxX;
}
public void setMaxX(double maxX) {
this.maxX = maxX;
}
public double getMinY() {
return minY;
}
public void setMinY(double minY) {
this.minY = minY;
}
public double getMaxY() {
return maxY;
}
public void setMaxY(double maxY) {
this.maxY = maxY;
}
public boolean isDrawLines() {
return drawLines;
}
public void setDrawLines(boolean drawLines) {
this.drawLines = drawLines;
}
public boolean isShowLegend() {
return showLegend;
}
public void setShowLegend(boolean showLegend) {
this.showLegend = showLegend;
}
public boolean isAddLegendInfo() {
return addLegendInfo;
}
public void setAddLegendInfo(boolean addLegendInfo) {
this.addLegendInfo = addLegendInfo;
}
public boolean isDisplayHighlighted() {
return displayHighlighted;
}
public void setDisplayHighlighted(boolean displayHighlighted) {
this.displayHighlighted = displayHighlighted;
}
public boolean isExportAsSvg() {
return exportAsSvg;
}
public void setExportAsSvg(boolean exportAsSvg) {
this.exportAsSvg = exportAsSvg;
}
public String getUnitX() {
return unitX;
}
public void setUnitX(String unitX) {
this.unitX = unitX;
}
public String getUnitY() {
return unitY;
}
public String getTransformX() {
return transformX;
}
public void setTransformX(String transformX) {
this.transformX = transformX;
}
public void setUnitY(String unitY) {
this.unitY = unitY;
}
public String getTransformY() {
return transformY;
}
public void setTransformY(String transformY) {
this.transformY = transformY;
}
public boolean isStandardVisibleColumns() {
return standardVisibleColumns;
}
public void setStandardVisibleColumns(boolean standardVisibleColumns) {
this.standardVisibleColumns = standardVisibleColumns;
}
public List<String> getVisibleColumns() {
return visibleColumns;
}
public void setVisibleColumns(List<String> visibleColumns) {
this.visibleColumns = visibleColumns;
}
public Map<String, Integer> getColumnWidths() {
return columnWidths;
}
public void setColumnWidths(Map<String, Integer> columnWidths) {
this.columnWidths = columnWidths;
}
}
| gpl-3.0 |
tompecina/retro | src/cz/pecina/retro/pmi80/SettingsFrame.java | 2668 | /* SettingsFrame.java
*
* Copyright (C) 2015, Tomáš Pecina <tomas@pecina.cz>
*
* This file is part of cz.pecina.retro, retro 8-bit computer emulators.
*
* This application 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 application 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 cz.pecina.retro.pmi80;
import java.util.logging.Logger;
import cz.pecina.retro.common.Application;
import cz.pecina.retro.peripherals.Peripheral;
/**
* The Settings frame.
*
* @author @AUTHOR@
* @version @VERSION@
*/
public class SettingsFrame extends HidingFrame {
// static logger
private static final Logger log =
Logger.getLogger(SettingsFrame.class.getName());
// the commputer control object
private Computer computer;
// settings panel
private SettingsPanel settingsPanel;
// array of available peripherals
private Peripheral[] peripherals;
/**
* Creates the Settings frame.
*
* @param computer the computer control object
* @param peripherals array of available peripherals
*/
public SettingsFrame(final Computer computer,
final Peripheral[] peripherals) {
super(Application.getString(SettingsFrame.class, "settings.frameTitle"),
computer.getIconLayout().getIcon(IconLayout.ICON_POSITION_WHEEL));
assert computer != null;
log.fine("New SettingsFrame creation started");
this.computer = computer;
this.peripherals = peripherals;
settingsPanel = new SettingsPanel(this, computer, peripherals);
add(settingsPanel);
pack();
log.fine("SettingsFrame set up");
}
// for description see HidingFrame
@Override
public void setUp() {
settingsPanel.setUp();
}
// redraw frame
private void redraw() {
log.fine("SettingsFrame redraw started");
super.setTitle(Application.getString(this, "settings.frameTitle"));
remove(settingsPanel);
settingsPanel = new SettingsPanel(this, computer, peripherals);
add(settingsPanel);
pack();
log.fine("SettingsFrame redraw completed");
}
// for description see Localized
@Override
public void redrawOnLocaleChange() {
redraw();
}
}
| gpl-3.0 |
takisd123/executequery | src/org/executequery/base/DockedTabToolTip.java | 1679 | /*
* DockedTabToolTip.java
*
* Copyright (C) 2002-2017 Takis Diakoumis
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.executequery.base;
import javax.swing.JToolTip;
/* ----------------------------------------------------------
* CVS NOTE: Changes to the CVS repository prior to the
* release of version 3.0.0beta1 has meant a
* resetting of CVS revision numbers.
* ----------------------------------------------------------
*/
/**
*
* @author Takis Diakoumis
*/
public class DockedTabToolTip extends JToolTip {
/** the current tab index of this tip */
private int tabIndex;
/** Creates a new instance of DockedTabToolTip */
public DockedTabToolTip() {}
public void setVisible(boolean visible) {
super.setVisible(visible);
if (!visible) {
tabIndex = -1;
setToolTipText(null);
}
}
public int getTabIndex() {
return tabIndex;
}
public void setTabIndex(int tabIndex) {
this.tabIndex = tabIndex;
}
}
| gpl-3.0 |
FSFTN/andriod-discuss-fsftn-org | app/src/main/java/org/fsftn/discuss/ActivityCheckerService.java | 2811 | package org.fsftn.discuss;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.Calendar;
public class ActivityCheckerService extends Service {
Calendar LastNotified;
Integer NotificationID;
public ActivityCheckerService() {
NotificationID=123456;
LastNotified=Calendar.getInstance();
}
public class MyBinder extends Binder
{
public ActivityCheckerService getService()
{
return ActivityCheckerService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
IBinder mb=new MyBinder();
return (mb);
}
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent,flags,startId);
try {
JSONObject reader = (JSONObject) new JSONObjectRetriever().execute("http://discuss.fsftn.org/latest.json").get();
JSONArray j = reader.getJSONObject("topic_list").getJSONArray("topics");
for (int i = j.length() - 1; i > 0; i--) {
String lpdate = j.getJSONObject(i).getString("last_posted_at");
Calendar date = ParseDate.parse(lpdate);
if (date.after(LastNotified)) {
notifyNewPost(j.getJSONObject(i));
LastNotified = date;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return START_STICKY;
}
public void notifyNewPost(JSONObject j)
{
try {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(j.getString("title"))
.setContentText("Click to check");
String slug = j.getString("slug");
Integer id = j.getInt("id");
String url="http://discuss.fsftn.org/t/"+slug+"/"+id.toString();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(NotificationID, mBuilder.build());
NotificationID++;
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
| gpl-3.0 |
teamblueridge/TBRStatus | app/src/main/java/org/teamblueridge/status/DrawerAdapter.java | 1666 | package org.teamblueridge.status;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class DrawerAdapter extends RecyclerView.Adapter<DrawerAdapter.CustomHolder> {
List<DrawerItem> mItems = Collections.emptyList();
private LayoutInflater mInflater;
private Context mContext;
public DrawerAdapter(Context context, List<DrawerItem> items) {
mItems = items;
mContext = context;
mInflater = LayoutInflater.from(mContext);
}
@Override
public DrawerAdapter.CustomHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = mInflater.inflate(R.layout.drawer_row, viewGroup, false);
CustomHolder holder = new CustomHolder(view);
return holder;
}
@Override
public void onBindViewHolder(DrawerAdapter.CustomHolder customHolder, int i) {
DrawerItem currentItem = mItems.get(i);
customHolder.mTitle.setText(currentItem.getTitle());
customHolder.mIcon.setImageDrawable(currentItem.getIcon());
}
@Override
public int getItemCount() {
return mItems.size();
}
class CustomHolder extends RecyclerView.ViewHolder {
ImageView mIcon;
TextView mTitle;
public CustomHolder(View view) {
super(view);
mIcon = (ImageView) view.findViewById(R.id.nav_icon);
mTitle = (TextView) view.findViewById(R.id.title);
}
}
}
| gpl-3.0 |
SoapboxRaceWorld/soapbox-race-core | src/main/java/com/soapboxrace/core/engine/EngineExceptionTrans.java | 4412 | /*
* This file is part of the Soapbox Race World core source code.
* If you use any of this code for third-party purposes, please provide attribution.
* Copyright (c) 2020.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911
// .1802
// 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: 2019.07.21 at 05:18:54 PM EDT
//
package com.soapboxrace.core.engine;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for EngineExceptionTrans complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="EngineExceptionTrans">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="ErrorCode" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="InnerException" type="{}EngineInnerExceptionTrans" minOccurs="0"/>
* <element name="Message" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="StackTrace" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "EngineExceptionTrans", propOrder = {
"description",
"errorCode",
"innerException",
"message",
"stackTrace"
})
public class EngineExceptionTrans {
@XmlElement(name = "Description")
protected String description;
@XmlElement(name = "ErrorCode")
protected int errorCode;
@XmlElement(name = "InnerException")
protected EngineInnerExceptionTrans innerException;
@XmlElement(name = "Message")
protected String message;
@XmlElement(name = "StackTrace")
protected String stackTrace;
/**
* Gets the value of the description property.
*
* @return possible object is
* {@link String }
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value allowed object is
* {@link String }
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the errorCode property.
*/
public int getErrorCode() {
return errorCode;
}
/**
* Sets the value of the errorCode property.
*/
public void setErrorCode(int value) {
this.errorCode = value;
}
/**
* Gets the value of the innerException property.
*
* @return possible object is
* {@link EngineInnerExceptionTrans }
*/
public EngineInnerExceptionTrans getInnerException() {
return innerException;
}
/**
* Sets the value of the innerException property.
*
* @param value allowed object is
* {@link EngineInnerExceptionTrans }
*/
public void setInnerException(EngineInnerExceptionTrans value) {
this.innerException = value;
}
/**
* Gets the value of the message property.
*
* @return possible object is
* {@link String }
*/
public String getMessage() {
return message;
}
/**
* Sets the value of the message property.
*
* @param value allowed object is
* {@link String }
*/
public void setMessage(String value) {
this.message = value;
}
/**
* Gets the value of the stackTrace property.
*
* @return possible object is
* {@link String }
*/
public String getStackTrace() {
return stackTrace;
}
/**
* Sets the value of the stackTrace property.
*
* @param value allowed object is
* {@link String }
*/
public void setStackTrace(String value) {
this.stackTrace = value;
}
}
| gpl-3.0 |
shiver-me-timbers/smt-servlet-junit-runner-parent | smt-servlet-junit-runner/src/main/java/shiver/me/timbers/junit/runner/servlet/configuration/ResourceClassPathsFactory.java | 5354 | /*
* Copyright (C) 2015 Karl Bennett
*
* 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 shiver.me.timbers.junit.runner.servlet.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import shiver.me.timbers.junit.runner.servlet.Packages;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import static java.lang.String.format;
/**
* This factory takes package names an returns a list of the class paths to all the files within those packages.
*
* @author Karl Bennett
*/
public class ResourceClassPathsFactory implements ClassPathsFactory {
private final Logger log = LoggerFactory.getLogger(ResourceClassPathsFactory.class);
private static final ClassLoader CLASS_LOADER = Thread.currentThread().getContextClassLoader();
@Override
public List<String> create(Packages packages) {
final ArrayList<String> fileNames = new ArrayList<>();
log.debug("Finding files in {}", packages);
for (String pkg : packages) {
final String packagePath = toPath(pkg);
final URL resource = toResource(packagePath);
checkPackageExists(resource);
final String resourcePath = resource.getPath();
if (isInJar(resourcePath)) {
log.debug("Finding files in JAR path {}", resourcePath);
fileNames.addAll(filesInJarPath(resourcePath));
} else {
log.debug("Finding files in filesystem path {}", resourcePath);
fileNames.addAll(filesInPath(resourcePath, packagePath));
}
}
log.debug("All files in {} are {}", packages, fileNames);
return fileNames;
}
private static String toPath(String pkg) {
return pkg.replaceAll("\\.", "/");
}
private static URL toResource(String path) {
return CLASS_LOADER.getResource(path);
}
private static void checkPackageExists(URL resource) {
if (null == resource) {
throw new IllegalArgumentException(format("Package (%s) does not exist.", resource));
}
}
private static boolean isInJar(String path) {
return path.contains(".jar!");
}
static List<String> filesInJarPath(String resourcePath) {
try {
final String jarFilePrefix = resourcePath.replaceAll("!.*$", "!/");
final JarFile jarFile = new JarFile(jarFilePrefix.replace("file:", "").replace("!/", ""));
final String packagePath = resourcePath.replaceAll(jarFilePrefix, "");
final Enumeration<JarEntry> entries = jarFile.entries();
final List<String> fileNames = new ArrayList<>();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
final String entryName = entry.getName();
if (entryName.equals(packagePath) || entryName.equals(packagePath + "/")) {
packageIsDirectory(jarFile.getJarEntry(entryName));
}
if (!entry.isDirectory() && entryName.startsWith(packagePath)) {
fileNames.add(entryName);
}
}
return fileNames;
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private static void packageIsDirectory(JarEntry pkg) {
if (!pkg.isDirectory()) {
throw new IllegalArgumentException(format("Package (%s) is not a directory.", pkg));
}
}
private static List<String> filesInPath(String resourcePath, String packagePath) {
return filesInPath(resourcePath.replace(packagePath, ""), resourcePath, packagePath);
}
private static List<String> filesInPath(String basePath, String resourcePath, String packagePath) {
final File pkg = new File(resourcePath);
packageIsDirectory(pkg);
final List<String> fileNames = new ArrayList<>();
final File[] files = pkg.listFiles();
for (File file : files) {
final String absolutePath = file.getAbsolutePath();
if (file.isDirectory()) {
fileNames.addAll(filesInPath(absolutePath, absolutePath.replace(basePath, "")));
} else {
fileNames.add(packagePath + "/" + file.getName());
}
}
return fileNames;
}
private static void packageIsDirectory(File pkg) {
if (!pkg.isDirectory()) {
throw new IllegalArgumentException(format("Package (%s) is not a directory.", pkg));
}
}
}
| gpl-3.0 |
abmindiarepomanager/ABMOpenMainet | Mainet1.1/MainetServiceParent/MainetServiceCommon/src/main/java/com/abm/mainet/common/workflow/domain/IAction.java | 150 | package com.abm.mainet.common.workflow.domain;
public interface IAction {
public String getDecision();
public String getComments();
}
| gpl-3.0 |
Tarik02/cr-private-server | src/main/java/royaleserver/utils/DataStream.java | 10970 | package royaleserver.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class DataStream {
public static final int RRSINT_NULL = -64;
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
private static final int DEFAULT_BUFFER_LENGTH = 128;
protected final ByteBuffer byteBuffer;
protected byte[] buffer;
protected int offset, count;
public DataStream() {
byteBuffer = ByteBuffer.allocate(8);
buffer = new byte[DEFAULT_BUFFER_LENGTH];
offset = 0;
count = 0;
}
public DataStream(byte[] buffer) {
this(buffer, 0);
}
public DataStream(byte[] buffer, int offset) {
byteBuffer = ByteBuffer.allocate(8);
setBuffer(buffer);
setOffset(offset);
}
protected static int calculateVarInt32(long value) {
if (value < 1 << 7) {
return 1;
}
if (value < 1 << 14) {
return 2;
}
if (value < 1 << 21) {
return 3;
}
if (value < 1 << 28) {
return 4;
}
return 5;
}
public DataStream reset() {
return reset(false);
}
public DataStream reset(boolean saveBufferCapacity) {
if (saveBufferCapacity) {
//Arrays.fill(buffer, (byte)0);
} else {
buffer = new byte[32];
}
offset = 0;
count = 0;
return this;
}
public byte[] getBuffer() {
return Arrays.copyOf(buffer, count);
}
public DataStream setBuffer(byte[] buffer) {
if (buffer == null) {
this.buffer = new byte[DEFAULT_BUFFER_LENGTH];
count = 0;
} else {
this.buffer = buffer;
count = buffer.length;
}
return this;
}
public int getOffset() {
return offset;
}
public DataStream setOffset(int offset) {
ensureCapacity(offset);
this.offset = offset;
return this;
}
public int getCount() {
return count;
}
public int remaining() {
return buffer.length - offset;
}
public boolean eof() {
return remaining() <= 0;
}
protected void ensureCapacity(int capacity) {
while (buffer.length < capacity) {
buffer = Arrays.copyOf(buffer, buffer.length << 1);
}
}
public DataStream skip(int count) {
offset += count;
return this;
}
public byte[] get() {
byte[] result = Arrays.copyOfRange(buffer, offset, count);
offset = count;
return result;
}
public byte[] get(int len) {
if (offset + len > buffer.length) {
len = buffer.length - offset;
}
byte[] result = Arrays.copyOfRange(buffer, offset, offset + len);
offset += len;
return result;
}
public DataStream zlibCompress() {
Deflater compressor = new Deflater();
compressor.setInput(this.get());
this.reset();
this.put(Hex.toByteArray("0178040000")); // size?!
byte[] buf = new byte[1024];
int length = 0;
compressor.finish();
while (!compressor.finished()) {
int count = compressor.deflate(buf);
this.put(buf, 0, count);
length += count;
}
compressor.end();
return this;
}
public DataStream put(byte[] bytes) {
return put(bytes, 0, bytes.length);
}
public DataStream put(byte[] bytes, int start, int length) {
length = Math.min(length, bytes.length);
ensureCapacity(count + length);
System.arraycopy(bytes, start, buffer, count, length);
count += length;
return this;
}
public boolean getBoolean() {
return getByte() == 0x01;
}
public DataStream putBoolean(boolean value) {
return putByte(value ? (byte)0x01 : (byte)0x00);
}
public byte getByte() {
if (offset < buffer.length) {
return buffer[offset++];
}
return 0;
}
public DataStream putByte(byte value) {
ensureCapacity(count + 1);
buffer[count] = value;
++count;
return this;
}
public short getBShort() {
byteBuffer.position(0);
return byteBuffer.order(ByteOrder.BIG_ENDIAN).put(get(2)).getShort(0);
}
public DataStream putBShort(short value) {
return put(byteBuffer.order(ByteOrder.BIG_ENDIAN).putShort(0, value).array(), 0, 2);
}
public short getLShort() {
byteBuffer.position(0);
return byteBuffer.order(ByteOrder.LITTLE_ENDIAN).put(get(2)).getShort(0);
}
public DataStream putLShort(short value) {
return put(byteBuffer.order(ByteOrder.LITTLE_ENDIAN).putShort(0, value).array(), 0, 2);
}
public int getBTriad() {
byteBuffer.position(0);
return byteBuffer.order(ByteOrder.BIG_ENDIAN).put(0, (byte)0x00).put(get(3)).getInt(0);
}
public DataStream putBTriad(int value) {
return put(byteBuffer.order(ByteOrder.BIG_ENDIAN).putInt(0, value).array(), 1, 3);
}
public int getLTriad() {
byteBuffer.position(0);
return byteBuffer.order(ByteOrder.LITTLE_ENDIAN).put(get(3)).put((byte)0x00).getInt(0);
}
public DataStream putLTriad(int value) {
return put(byteBuffer.order(ByteOrder.LITTLE_ENDIAN).putInt(0, value).array(), 0, 3);
}
public int getBInt() {
byteBuffer.position(0);
return byteBuffer.order(ByteOrder.BIG_ENDIAN).put(get(4)).getInt(0);
}
public DataStream putBInt(int value) {
return put(byteBuffer.order(ByteOrder.BIG_ENDIAN).putInt(0, value).array(), 0, 4);
}
public int getLInt() {
byteBuffer.position(0);
return byteBuffer.order(ByteOrder.LITTLE_ENDIAN).put(get(4)).getInt(0);
}
public DataStream putLInt(int value) {
return put(byteBuffer.order(ByteOrder.LITTLE_ENDIAN).putInt(0, value).array(), 0, 4);
}
public long getBLong() {
byteBuffer.position(0);
return byteBuffer.order(ByteOrder.BIG_ENDIAN).put(get(8)).getLong(0);
}
public DataStream putBLong(long value) {
return put(byteBuffer.order(ByteOrder.BIG_ENDIAN).putLong(0, value).array(), 0, 8);
}
public long getLLong() {
byteBuffer.position(0);
return byteBuffer.order(ByteOrder.LITTLE_ENDIAN).put(get(8)).getLong(0);
}
public DataStream putLLong(long value) {
return put(byteBuffer.order(ByteOrder.LITTLE_ENDIAN).putLong(0, value).array(), 0, 8);
}
public float getBFloat() {
byteBuffer.position(0);
return byteBuffer.order(ByteOrder.BIG_ENDIAN).put(get(4)).getFloat(0);
}
public DataStream putBFloat(float value) {
return put(byteBuffer.order(ByteOrder.BIG_ENDIAN).putFloat(0, value).array(), 0, 4);
}
public float getLFloat() {
byteBuffer.position(0);
return byteBuffer.order(ByteOrder.LITTLE_ENDIAN).put(get(4)).getFloat(0);
}
public DataStream putLFloat(float value) {
return put(byteBuffer.order(ByteOrder.LITTLE_ENDIAN).putFloat(0, value).array(), 0, 4);
}
public int getRrsInt32() {
short c = 0;
long value = 0;
long b;
long seventh;
long msb;
do {
b = getByte();
if (c == 0) {
seventh = (b & 0x40) >> 6; // save 7th bit
msb = (b & 0x80) >> 7; // save msb
b = b << 1; // rotate to the left
b = b & ~(0x181); // clear 8th and 1st bit and 9th if any
b = b | (msb << 7) | (seventh); // insert msb and 6th back in
}
value |= (b & 0x7f) << (7 * c);
++c;
} while ((b & 0x80) != 0);
value = (value >>> 1) ^ -(value & 1);
return (int)value;
}
public DataStream putRrsInt32(int value) {
long lvalue = value;
int size = calculateVarInt32(lvalue);
boolean rotate = true;
long b;
if (value == 0) {
putByte((byte)0);
} else {
lvalue = (lvalue << 1) ^ (lvalue >> 31);
while (lvalue != 0) {
b = (lvalue & 0x7f);
if (lvalue >= 0x80) {
b |= 0x80;
}
if (rotate) {
rotate = false;
long lsb = b & 0x1;
long msb = (b & 0x80) >> 7;
b = b >> 1; // rotate to the right
b = b & ~(0xC0); // clear 7th and 6th bit
b = b | (msb << 7) | (lsb << 6); // insert msb and lsb back in
}
putByte((byte)b);
lvalue >>>= 7;
}
}
return this;
}
public long getRrsLong() {
return (((long)getRrsInt32()) << 32) | ((long)getRrsInt32());
}
public DataStream putRrsLong(long value) {
return putRrsInt32((int)(value >> 32)).putRrsInt32((int)value);
}
public String getString() {
int count = getBInt();
if (count == 0xFFFFFFFF) {
return "";
}
return new String(get(count), UTF8_CHARSET);
}
public DataStream writeStructureRRS(int[] rrs) {
putRrsInt32(rrs.length);
for (int i = 0; i < rrs.length; i++) {
putRrsInt32(rrs[i]);
}
return this;
}
public DataStream putString(String value) {
if (value.length() == 0) {
putBInt(0xFFFFFFFF);
} else {
byte[] bytes = value.getBytes(UTF8_CHARSET);
putBInt(bytes.length);
put(bytes);
}
return this;
}
public String getZipString() {
int length = getBInt() - 4;
int zlength = getLInt();
if (remaining() > length) {
Inflater decompressor = new Inflater();
decompressor.setInput(buffer, offset, length);
offset += length;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream(zlength);
byte[] buf = new byte[1024];
int count;
while ((!decompressor.finished()) && ((count = decompressor.inflate(buf)) > 0)) {
bos.write(buf, 0, count);
}
decompressor.end();
bos.close();
return new String(bos.toByteArray(), UTF8_CHARSET);
} catch (DataFormatException | IOException ignored) {
}
}
return null;
}
public DataStream putZipString(String value) {
Deflater compressor = new Deflater();
byte[] buffer = value.getBytes(UTF8_CHARSET);
compressor.setInput(buffer);
int sizeOffset = count;
putBInt(0).putLInt(buffer.length);
byte[] buf = new byte[1024];
int length = 0;
compressor.finish();
while (!compressor.finished()) {
int count = compressor.deflate(buf);
put(buf, 0, count);
length += count;
}
compressor.end();
int endOffset = count;
count = sizeOffset;
putBInt(length);
count = endOffset;
return this;
}
public Bitset getBitset() {
return new Bitset(getByte());
}
public DataStream putBitset(Bitset value) {
return putByte(value.getValue());
}
public byte[] getByteSet() {
int len = getBInt();
if (len == 0xFFFFFFFF) {
return new byte[0];
}
return get(len);
}
public DataStream putByteSet(byte[] value) {
if (value.length == 0) {
return putBInt(0xFFFFFFFF);
}
return putBInt(value.length).put(value);
}
public SCID getSCID() {
int high = getRrsInt32();
if (high > 0) {
int low = getRrsInt32();
return new SCID(high, low);
}
return new SCID();
}
public DataStream putSCID(SCID value) {
if (value.getHigh() > 0) {
return putRrsInt32(value.getHigh()).putRrsInt32(value.getLow());
}
return putRrsInt32(0);
}
public int getVarInt32() {
int result = 0;
int shift = 0;
int b;
do {
if (shift >= 32) {
return 0;
}
b = getByte();
result |= (b & 0x7F) << shift;
shift += 7;
} while ((b & 0x80) != 0);
return result;
}
public DataStream putVarInt32(int value) {
do {
int bits = value & 0x7F;
value >>>= 7;
byte b = (byte)(bits + ((value != 0) ? 0x80 : 0));
putByte(b);
} while (value != 0);
return this;
}
public String dump() {
return Hex.dump(buffer, 0, count);
}
public DataStream printDump() {
System.out.println(dump());
return this;
}
}
| gpl-3.0 |
Presage/Presage2 | core/src/main/java/uk/ac/imperial/presage2/core/cli/run/SubProcessExecutor.java | 8186 | /**
* Copyright (C) 2011 Sam Macbeth <sm1106 [at] imperial [dot] ac [dot] uk>
*
* This file is part of Presage2.
*
* Presage2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Presage2 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with Presage2. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.ac.imperial.presage2.core.cli.run;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.log4j.Logger;
/**
* <p>
* A {@link SimulationExecutor} which has a set of sub processes which each runs
* a simulation. This abstract class automates the management of these
* processes. It calls the {@link #createProcess(long)} function to get a
* {@link ProcessBuilder} with which to spawn the process to manage. This class
* can also log output from these processes to files.
* </p>
*
* @author Sam Macbeth
*
*/
public abstract class SubProcessExecutor implements SimulationExecutor {
protected Logger logger = Logger.getLogger(this.toString());;
protected int MAX_PROCESSES;
protected List<Process> running;
protected Timer processMonitor;
boolean saveLogs = false;
String logsDir = System.getProperty("user.dir", "") + "/logs/";
protected final String xms;
protected final String xmx;
protected final int gcThreads;
protected final String[] customArgs;
/**
* Create SubProcessExecutor which can execute at most
* <code>max_processes</code> processes in parallel. The processes will use
* default vm arguments.
*
* @param max_processes
* max concurrent processes
*/
protected SubProcessExecutor(int max_processes) {
this(max_processes, "", "", 4, new String[] {});
}
/**
* Create SubProcessExecutor with the given properties:
*
* @param max_processes
* max concurrent processes
* @param xms
* -Xms value for JVM
* @param xmx
* -Xmx value for JVM
* @param gcThreads
* Number of threads to use for parallel GC.
*/
protected SubProcessExecutor(int max_processes, String xms, String xmx,
int gcThreads) {
this(max_processes, xms, xmx, gcThreads, new String[] {});
}
/**
* Create SubProcessExecutor with a custom array of properties passed to
* java.
*
* @param max_processes
* max concurrent processes
* @param customArgs
* array of args to pass to java executable on the command line.
*/
protected SubProcessExecutor(int max_processes, String... customArgs) {
this(max_processes, "", "", 4, customArgs);
}
private SubProcessExecutor(int max_processes, String xms, String xmx,
int gcThreads, String[] customArgs) {
super();
MAX_PROCESSES = max_processes;
this.xms = xms;
this.xmx = xmx;
this.gcThreads = gcThreads;
this.customArgs = customArgs;
this.running = Collections.synchronizedList(new ArrayList<Process>(
MAX_PROCESSES));
this.processMonitor = new Timer(this.getClass().getSimpleName()
+ "-monitor", true);
this.processMonitor.schedule(new TimerTask() {
@Override
public void run() {
List<Process> completed = new LinkedList<Process>();
for (Process p : running) {
try {
// check exit value to see if process has exited.
int val = p.exitValue();
logger.info("Simulation completed, returned " + val);
completed.add(p);
// if we got a non 0 exit code stop accepting
// simulations
// This is a fast fail solution to prevent large numbers
// of simulations failing due to one faulty executor or
// config.
if (val != 0) {
logger.warn("Receive non-zero exit code, shutting down executor as a precaution.");
MAX_PROCESSES = 0;
}
} catch (IllegalThreadStateException e) {
// process is still running.
}
}
running.removeAll(completed);
}
}, 1000, 1000);
}
@Override
public boolean enableLogs() {
return saveLogs;
}
@Override
public void enableLogs(boolean saveLogs) {
this.saveLogs = saveLogs;
}
@Override
public String getLogsDirectory() {
return logsDir;
}
@Override
public void setLogsDirectory(String logsDir) {
this.logsDir = logsDir;
}
@Override
public synchronized void run(long simId)
throws InsufficientResourcesException {
// don't launch more than maxConcurrent processes.
if (this.running() >= maxConcurrent())
throw new InsufficientResourcesException(
"Max number of concurrent processes, " + maxConcurrent()
+ " has been reached");
ProcessBuilder builder = createProcess(simId);
builder.redirectErrorStream(true);
// start process and gobble streams
try {
logger.info("Starting simulation ID: " + simId + "");
logger.debug("Process args: "+ builder.command());
Process process = builder.start();
InputStream is = process.getInputStream();
OutputStream os = null;
// optionally pipe process output to a log.
if (saveLogs) {
String logPath = logsDir + simId + ".log";
logger.debug("Logging to: " + logPath);
try {
// ensure log dir exists
File logDir = new File(logsDir);
if (!logDir.exists()) {
logDir.mkdirs();
}
File logFile = new File(logPath);
if (!logFile.exists())
logFile.createNewFile();
os = new FileOutputStream(logFile, true);
} catch (IOException e) {
logger.warn("Unable to create log file: " + logPath, e);
os = null;
}
}
StreamGobbler gobbler = os == null ? new StreamGobbler(is)
: new StreamGobbler(is, os);
gobbler.start();
running.add(process);
} catch (IOException e) {
logger.warn("Error launching process", e);
}
}
/**
* Create a {@link ProcessBuilder} which will spawn a {@link Process} to run
* the given simulation.
*
* @param simId
* @return
* @throws InsufficientResourcesException
*/
protected abstract ProcessBuilder createProcess(long simId)
throws InsufficientResourcesException;
@Override
public int running() {
return this.running.size();
}
@Override
public int maxConcurrent() {
return MAX_PROCESSES;
}
protected String getClasspath() {
String classpath = System.getProperty("java.class.path");
// if the system classpath only contains classworlds.jar we must rebuild
// classpath from this class's classloader.
if (classpath.split(":").length == 1
&& classpath.matches(".*classworlds.*")) {
ClassLoader sysClassLoader = this.getClass().getClassLoader();
URL[] urls = ((URLClassLoader) sysClassLoader).getURLs();
String separator = System.getProperty("path.separator", ":");
classpath = "";
for (int i = 0; i < urls.length; i++) {
classpath += urls[i].getFile();
if (i >= urls.length - 1)
break;
classpath += separator;
}
}
return classpath;
}
/**
* Get the list of arguments which should be passed to the java executable
* for the vm. These arguments come before the program args.
*
* @return
*/
protected List<String> getJvmArgs() {
List<String> args = new LinkedList<String>();
if (customArgs.length > 0) {
// if custom args have been specified use them instead of defaults
Collections.addAll(args, customArgs);
} else {
// defaults: use parallel gc & specify xms/xmx
if (!xms.isEmpty())
args.add("-Xms" + xms);
if (!xmx.isEmpty())
args.add("-Xmx" + xmx);
args.add("-XX:+UseParallelGC");
args.add("-XX:ParallelGCThreads=" + gcThreads);
}
return args;
}
}
| gpl-3.0 |
maoruibin/GankDaily | app/src/main/java/com/gudong/gankio/ui/adapter/MainListAdapter.java | 8983 | /*
*
* Copyright (C) 2015 Drakeet <drakeet.me@gmail.com>
* Copyright (C) 2015 GuDong <maoruibin9035@gmail.com>
*
* Meizhi 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.
*
* Meizhi 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 Meizhi. If not, see <http://www.gnu.org/licenses/>.
*/
package com.gudong.gankio.ui.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.gudong.gankio.R;
import com.gudong.gankio.core.GankCategory;
import com.gudong.gankio.data.entity.Gank;
import com.gudong.gankio.ui.activity.BaseActivity;
import com.gudong.gankio.ui.widget.RatioImageView;
import com.gudong.gankio.util.DateUtil;
import com.gudong.gankio.util.StringStyleUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by GuDong on 10/9/15 22:53.
* Contact with gudong.name@gmail.com.
*/
public class MainListAdapter extends RecyclerView.Adapter<MainListAdapter.ViewHolderItem> {
private List<Gank> mGankList;
private BaseActivity mContext;
private static IClickMainItem mIClickItem;
//blur meizi
private static ColorFilter mColorFilter;
public MainListAdapter(BaseActivity context) {
mContext = context;
mGankList = new ArrayList<>();
mGankList.add(getDefGankGirl());
float[]array = new float[]{
1,0,0,0,-70,
0,1,0,0,-70,
0,0,1,0,-70,
0,0,0,1,0,
};
mColorFilter = new ColorMatrixColorFilter(new ColorMatrix(array));
}
/**
* before add data , it will remove history data
* @param data
*/
public void updateWithClear(List<Gank> data) {
mGankList.clear();
update(data);
}
/**
* add data append to history data*
* @param data new data
*/
public void update(List<Gank> data) {
formatGankData(data);
notifyDataSetChanged();
}
/**
* the type of RecycleView item
*/
private enum EItemType{
ITEM_TYPE_GIRL,
ITEM_TYPE_NORMAL,
ITEM_TYPE_CATEGOTY;
}
@Override
public int getItemViewType(int position) {
Gank gank = mGankList.get(position);
if(gank.is妹子()){
return EItemType.ITEM_TYPE_GIRL.ordinal();
}else if(gank.isHeader){
return EItemType.ITEM_TYPE_CATEGOTY.ordinal();
}else{
return EItemType.ITEM_TYPE_NORMAL.ordinal();
}
}
@Override
public MainListAdapter.ViewHolderItem onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if (viewType == EItemType.ITEM_TYPE_GIRL.ordinal()) {
view = LayoutInflater.from(mContext).inflate(R.layout.gank_item_girl, null);
return new ViewHolderItemGirl(view);
}else if(viewType == EItemType.ITEM_TYPE_CATEGOTY.ordinal()){
view = LayoutInflater.from(mContext).inflate(R.layout.gank_item_category, null);
return new ViewHolderItemCategory(view);
} else {
view = LayoutInflater.from(mContext).inflate(R.layout.gank_item_normal, null);
return new ViewHolderItemNormal(view);
}
}
@Override
public void onBindViewHolder(final MainListAdapter.ViewHolderItem holder, int position) {
holder.bindItem(mContext, mGankList.get(position),position);
}
@Override
public int getItemCount() {
return mGankList.size();
}
/**
* ViewHolderItem is a parent class for different item
*/
abstract static class ViewHolderItem extends RecyclerView.ViewHolder {
public ViewHolderItem(View itemView) {
super(itemView);
}
abstract void bindItem(Context context, Gank gank, int position);
}
static class ViewHolderItemNormal extends ViewHolderItem {
@Bind(R.id.tv_gank_title)
TextView mTvTitle;
@Bind(R.id.ll_gank_parent)
RelativeLayout mRlGankParent;
ViewHolderItemNormal(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bindItem(final Context context, final Gank gank, int position){
mTvTitle.setText(StringStyleUtils.getGankInfoSequence(context, gank));
mRlGankParent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mIClickItem.onClickGankItemNormal(gank, view);
}
});
}
}
static class ViewHolderItemCategory extends ViewHolderItem {
@Bind(R.id.tv_category)
TextView mTvCategory;
ViewHolderItemCategory(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
@Override
void bindItem(Context context, Gank gank, int position) {
mTvCategory.setText(gank.type);
}
}
static class ViewHolderItemGirl extends ViewHolderItem {
@Bind(R.id.tv_video_name)
TextView mTvTime;
@Bind(R.id.ll_bk_time)
View mBkTime;
@Bind(R.id.iv_index_photo)
RatioImageView mImageView;
ViewHolderItemGirl(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
mImageView.setOriginalSize(200, 100);
}
@Override
void bindItem(Context context, final Gank gank, final int position) {
mTvTime.setText(DateUtil.toDate(gank.publishedAt));
Glide.with(context)
.load(gank.url)
.asBitmap()
.into(new BitmapImageViewTarget(mImageView){
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
super.onResourceReady(resource, glideAnimation);
mBkTime.setVisibility(View.VISIBLE);
}
});
mTvTime.setText(DateUtil.toDate(gank.publishedAt));
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mIClickItem.onClickGankItemGirl(gank, mImageView, mTvTime);
}
});
}
}
public void setIClickItem(IClickMainItem IClickItem) {
mIClickItem = IClickItem;
}
public interface IClickMainItem{
/**
* click gank girl info item
* @param gank
* @param viewImage
* @param viewText
*/
void onClickGankItemGirl(Gank gank,View viewImage,View viewText);
/**
* click gank normal info item
* @param gank
* @param view
*/
void onClickGankItemNormal(Gank gank,View view);
}
/**
* filter list and add category entity into list
* @param data source data
*/
private void formatGankData(List<Gank> data) {
//Insert headers into list of items.
String lastHeader = "";
for (int i = 0; i < data.size(); i++) {
Gank gank = data.get(i);
String header = gank.type;
if (!gank.is妹子() && !TextUtils.equals(lastHeader, header)) {
// Insert new header view.
Gank gankHeader = gank.clone();
lastHeader = header;
gankHeader.isHeader = true;
mGankList.add(gankHeader);
}
gank.isHeader = false;
mGankList.add(gank);
}
}
/**
* get a init Gank entity
* @return gank entity
*/
private Gank getDefGankGirl(){
Gank gank = new Gank();
gank.publishedAt = new Date(System.currentTimeMillis());
gank.url = "empty";
gank.type = GankCategory.福利.name();
return gank;
}
}
| gpl-3.0 |
Ingwersaft/ValueClassGenerator | testData/person_after.java | 5298 | import java.awt.*;
import java.util.Objects;
public class Person {
private final Name name;
private final Surname surname;
private final Age age;
private final Alive alive;
private final SystemColor nonPrimitiveOrPrimitiveWrapper;
public Person(Name name, Surname surname, Age age, Alive alive, SystemColor nonPrimitiveOrPrimitiveWrapper) {
this.name = name;
this.surname = surname;
this.age = age;
this.alive = alive;
this.nonPrimitiveOrPrimitiveWrapper = nonPrimitiveOrPrimitiveWrapper;
}
public Name getName() {
return name;
}
public Surname getSurname() {
return surname;
}
public Age getAge() {
return age;
}
public Alive getAlive() {
return alive;
}
public SystemColor getNonPrimitiveOrPrimitiveWrapper() {
return nonPrimitiveOrPrimitiveWrapper;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return java.util.Objects.equals(name, person.name) &&
java.util.Objects.equals(surname, person.surname) &&
java.util.Objects.equals(age, person.age) &&
java.util.Objects.equals(alive, person.alive) &&
java.util.Objects.equals(nonPrimitiveOrPrimitiveWrapper, person.nonPrimitiveOrPrimitiveWrapper);
}
@Override
public int hashCode() {
return java.util.Objects.hash(name, surname, age, alive, nonPrimitiveOrPrimitiveWrapper);
}
@Override
public String toString() {
return "Person{" +
"name:" + name.get() + "," +
"surname:" + surname.get() + "," +
"age:" + age.get() + "," +
"alive:" + alive.get() + "," +
"nonPrimitiveOrPrimitiveWrapper:" + nonPrimitiveOrPrimitiveWrapper + "," +
"}";
}
public static final class Name {
private final String name;
public String get() {
return name;
}
public Name(String name) {
this.name = name;
}
@Override
public String toString() {
return "Name:" + name;
}
public static Name of(final String name) {
return new Name(name);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Name name1 = (Name) o;
return java.util.Objects.equals(name, name1.name);
}
@Override
public int hashCode() {
return java.util.Objects.hash(name);
}
}
public static final class Surname {
private final String surname;
public String get() {
return surname;
}
public Surname(String surname) {
this.surname = surname;
}
@Override
public String toString() {
return "Surname:" + surname;
}
public static Surname of(final String surname) {
return new Surname(surname);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Surname surname1 = (Surname) o;
return java.util.Objects.equals(surname, surname1.surname);
}
@Override
public int hashCode() {
return java.util.Objects.hash(surname);
}
}
public static final class Age {
private final Integer age;
public Integer get() {
return age;
}
public Age(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Age:" + age;
}
public static Age of(final Integer age) {
return new Age(age);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Age age1 = (Age) o;
return java.util.Objects.equals(age, age1.age);
}
@Override
public int hashCode() {
return java.util.Objects.hash(age);
}
}
public static final class Alive {
private final Boolean alive;
public Boolean get() {
return alive;
}
public Alive(Boolean alive) {
this.alive = alive;
}
@Override
public String toString() {
return "Alive:" + alive;
}
public static Alive of(final Boolean alive) {
return new Alive(alive);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Alive alive1 = (Alive) o;
return java.util.Objects.equals(alive, alive1.alive);
}
@Override
public int hashCode() {
return java.util.Objects.hash(alive);
}
}
} | gpl-3.0 |
craftercms/deployer | src/main/java/org/craftercms/deployer/impl/rest/ExceptionHandlers.java | 4379 | /*
* 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.deployer.impl.rest;
import org.craftercms.commons.exceptions.InvalidManagementTokenException;
import org.craftercms.commons.rest.BaseRestExceptionHandlers;
import org.craftercms.commons.rest.RestServiceUtils;
import org.craftercms.commons.validation.rest.ValidationAwareRestExceptionHandlers;
import org.craftercms.deployer.api.exceptions.TargetAlreadyExistsException;
import org.craftercms.deployer.api.exceptions.TargetNotFoundException;
import org.craftercms.deployer.api.exceptions.UnsupportedSearchEngineException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
/**
* Extension of {@link BaseRestExceptionHandlers} that provides exception handlers for specific Crafter Deployer exceptions.
*
* @author avasquez
*/
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class ExceptionHandlers extends ValidationAwareRestExceptionHandlers {
/**
* Handles a {@link TargetNotFoundException} by returning a 404 NOT FOUND.
*
* @param ex the exception
* @param request the current request
*
* @return the response entity, with the body and status
*/
@ExceptionHandler(TargetNotFoundException.class)
public ResponseEntity<Object> handleTargetNotFoundException(TargetNotFoundException ex, WebRequest request) {
return handleExceptionInternal(ex, "Target not found", new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
/**
* Handles a {@link TargetAlreadyExistsException} by returning a 409 CONFLICT.
*
* @param ex the exception
* @param request the current request
*
* @return the response entity, with the body and status
*/
@ExceptionHandler(TargetAlreadyExistsException.class)
public ResponseEntity<Object> handleTargetAlreadyExistsException(TargetAlreadyExistsException ex, WebRequest request) {
HttpHeaders headers = RestServiceUtils.setLocationHeader(new HttpHeaders(),
TargetController.BASE_URL + TargetController.GET_TARGET_URL,
ex.getEnv(), ex.getSiteName());
return handleExceptionInternal(ex, "Target already exists", headers, HttpStatus.CONFLICT, request);
}
/**
* Handles a {@link UnsupportedSearchEngineException} by returning a 400 BAD REQUEST.
*
* @param ex the exception
* @param request the current request
*
* @return the response entity, with the body and status
*/
@ExceptionHandler(UnsupportedSearchEngineException.class)
public ResponseEntity<Object> handleUnsupportedSearchEngineException(UnsupportedSearchEngineException ex,
WebRequest request) {
return handleExceptionInternal(ex, ex.getMessage(), new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
@ExceptionHandler(InvalidManagementTokenException.class)
public ResponseEntity<Object> handleInvalidManagementTokenException(InvalidManagementTokenException ex,
WebRequest request) {
return handleExceptionInternal(ex, "Invalid management token", new HttpHeaders(), HttpStatus.UNAUTHORIZED,
request);
}
}
| gpl-3.0 |
lecousin/net.lecousin.framework-0.1 | net.lecousin.framework/library/src/net/lecousin/framework/io/IOUtil.java | 3819 | package net.lecousin.framework.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;
import net.lecousin.framework.collections.ArrayUtil;
import net.lecousin.framework.random.Random;
public class IOUtil {
public static String generateUniqueFileName(File dir) {
long l = Random.randLong(Long.MAX_VALUE);
String[] files = dir.list();
do {
String s = Long.toHexString(l).toUpperCase();
while (s.length() < 8)
s = "0" + s;
if (!ArrayUtil.contains(files, s))
return s;
if (l < Long.MAX_VALUE) ++l; else l = 0;
} while (true);
}
public static byte[] readAll(InputStream in) throws IOException {
byte[] result = new byte[in.available()];
in.read(result);
return result;
}
public static String readAllInString(InputStream in) throws IOException {
return new String(readAll(in));
}
public static String readPart(InputStream in, String endDelimiter) throws IOException {
StringBuilder str = new StringBuilder();
do {
int c = in.read();
if (c == -1) return str.toString();
str.append((char)c);
} while (str.length() < endDelimiter.length() || !str.substring(str.length()-endDelimiter.length()).equals(endDelimiter));
str.delete(str.length()-endDelimiter.length(), str.length());
return str.toString();
}
public static String[] readAllLines(File file, boolean includeEmptyLines) throws FileNotFoundException, IOException {
return readAllLines(new LCBufferedInputStream(new FileInputStream(file)), includeEmptyLines);
}
public static String[] readAllLines(InputStream stream, boolean includeEmptyLines) throws IOException {
TextLineInputStream in = new TextLineInputStream(stream);
List<String> lines = new LinkedList<String>();
String line;
while ((line = in.readLine()) != null) {
if (!includeEmptyLines && line.length() == 0)
continue;
lines.add(line);
}
return lines.toArray(new String[lines.size()]);
}
public static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[65536];
do {
int nb = in.read(buffer);
if (nb == -1) break;
out.write(buffer, 0, nb);
} while (true);
}
/** big-endian or motorola format */
public static long readLongMotorola(byte[] buffer, int offset) {
long value = 0;
value += (buffer[offset] & 0xFF) << 24;
value += (buffer[offset+1] & 0xFF) << 16;
value += (buffer[offset+2] & 0xFF) << 8;
value += (buffer[offset+3] & 0xFF);
return value;
}
/** little-endian or intel format */
public static long readLongIntel(byte[] buffer, int offset) {
long value = 0;
value += (buffer[offset] & 0xFF);
value += (buffer[offset+1] & 0xFF) << 8;
value += (buffer[offset+2] & 0xFF) << 16;
value += (buffer[offset+3] & 0xFF) << 24;
return value;
}
/** little-endian or intel format */
public static short readShortIntel(byte[] buffer, int offset) {
short value = 0;
value += (buffer[offset] & 0xFF);
value += (buffer[offset+1] & 0xFF) << 8;
return value;
}
/** big-endian or motorola format */
public static short readShortMotorola(byte[] buffer, int offset) {
short value = 0;
value += (buffer[offset] & 0xFF) << 8;
value += (buffer[offset+1] & 0xFF);
return value;
}
public static int readAllBuffer(InputStream stream, byte[] buffer) throws IOException {
return readAllBuffer(stream, buffer, 0, buffer.length);
}
public static int readAllBuffer(InputStream stream, byte[] buffer, int off, int len) throws IOException {
int total = 0;
do {
int l = len-total;
int nb = stream.read(buffer, off, l);
if (nb <= 0)
return total;
off += nb;
total += nb;
} while (total < len);
return total;
}
}
| gpl-3.0 |
pantelis60/L2Scripts_Underground | gameserver/src/main/java/l2s/gameserver/model/entity/olympiad/CompEndTask.java | 1221 | package l2s.gameserver.model.entity.olympiad;
import l2s.commons.threading.RunnableImpl;
import l2s.gameserver.Announcements;
import l2s.gameserver.ThreadPoolManager;
import l2s.gameserver.network.l2.components.SystemMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class CompEndTask extends RunnableImpl
{
private static final Logger _log = LoggerFactory.getLogger(CompEndTask.class);
@Override
public void runImpl() throws Exception
{
if(Olympiad.isOlympiadEnd())
return;
Olympiad._inCompPeriod = false;
try
{
OlympiadManager manager = Olympiad._manager;
// Если остались игры, ждем их завершения еще одну минуту
if(manager != null && !manager.getOlympiadGames().isEmpty())
{
ThreadPoolManager.getInstance().schedule(new CompEndTask(), 60000);
return;
}
Announcements.getInstance().announceToAll(SystemMsg.MUCH_CARNAGE_HAS_BEEN_LEFT_FOR_THE_CLEANUP_CREW_OF_THE_OLYMPIAD_STADIUM);
_log.info("Olympiad System: Olympiad Game Ended");
OlympiadDatabase.save();
}
catch(Exception e)
{
_log.warn("Olympiad System: Failed to save Olympiad configuration:");
_log.error("", e);
}
Olympiad.init();
}
} | gpl-3.0 |
tvesalainen/util | util/src/main/java/org/vesalainen/math/sliding/LongTimeoutSlidingMin.java | 1849 | /*
* Copyright (C) 2016 Timo Vesalainen <timo.vesalainen@iki.fi>
*
* 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.vesalainen.math.sliding;
import java.time.Clock;
import java.util.function.LongSupplier;
/**
* A class for counting min value for given time.
* @author Timo Vesalainen <timo.vesalainen@iki.fi>
*/
public class LongTimeoutSlidingMin extends LongAbstractTimeoutSlidingBound
{
/**
*
* @param size Initial size of buffers
* @param timeout Sample timeout in millis
*/
public LongTimeoutSlidingMin(int size, long timeout)
{
this(System::currentTimeMillis, size, timeout);
}
public LongTimeoutSlidingMin(Clock clock, int size, long timeout)
{
this(clock::millis, size, timeout);
}
public LongTimeoutSlidingMin(LongSupplier clock, int size, long timeout)
{
super(clock, size, timeout);
}
public LongTimeoutSlidingMin(Timeouting parent)
{
super(parent);
}
@Override
protected boolean exceedsBounds(int index, long value)
{
return ring[index] >value;
}
public long getMin()
{
return getBound();
}
}
| gpl-3.0 |
NRJD/BVApp1 | src/org/nrjd/bv/app/util/ArrayUtils.java | 924 | /*
* Copyright (C) 2015 ISKCON New Rajapur Jagannatha Dham.
*
* This file is part of Bhakti Vriksha application.
*/
package org.nrjd.bv.app.util;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ArrayUtils {
private ArrayUtils() {
}
public static Set<String> convertToSet(String... values) {
Set<String> set = null;
if (values != null) {
for (String value : values) {
if (set == null) {
set = new HashSet<String>();
}
set.add(value);
}
}
return set;
}
public static Set<String> convertToSet(List<String> values) {
Set<String> set = null;
if (values != null) {
if (set == null) {
set = new HashSet<String>();
}
set.addAll(values);
}
return set;
}
}
| gpl-3.0 |
Joshua-Barclay/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/AudioResource.java | 1334 | package com.github.bordertech.wcomponents;
/**
* Provides a bridge to static audio resources which are present in the class path, but not in the web application
* itself.
*
* @author Yiannis Paschalidis
* @since 1.0.0
*/
public class AudioResource extends InternalResource implements Audio {
/**
* The audio length, if known.
*/
private int duration;
/**
* Creates an AudioResource.
*
* @param audioResource the resource name.
*/
public AudioResource(final String audioResource) {
this(audioResource, "unknown audio clip");
}
/**
* Creates an AudioResource.
*
* @param audioResource the resource name.
* @param description the description of the audio clip.
*/
public AudioResource(final String audioResource, final String description) {
super(audioResource, description);
}
/**
* Retrieves the duration of the audio clip. A value of <= 0 indicates that the duration is unknown.
*
* @return the duration of the audio clip.
*/
@Override
public int getDuration() {
return duration;
}
/**
* Sets the duration of the audio clip, A value of <= 0 indicates that the duration is unknown.
*
* @param duration The duration to set.
*/
public void setDuration(final int duration) {
this.duration = duration;
}
}
| gpl-3.0 |
evrignaud/fim | src/main/java/org/fim/model/output/DuplicatedFile.java | 1417 | /*
* This file is part of Fim - File Integrity Manager
*
* Copyright (C) 2017 Etienne Vrignaud
*
* Fim 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.
*
* Fim 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 Fim. If not, see <https://www.gnu.org/licenses/>.
*/
package org.fim.model.output;
public class DuplicatedFile {
private String path;
private String name;
private long length;
private String type;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| gpl-3.0 |
eternnoir/ToS_Prophet | src/com/tos_prophet/XmlParser.java | 1346 | package com.tos_prophet;
import java.io.FileReader;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.util.Log;
public class XmlParser {
public XmlParser() {
}
public String parserXmlByID(String _path, String ID) {
String ret = "";
XmlPullParserFactory parserFactory;
XmlPullParser pullParser;
try {
parserFactory = XmlPullParserFactory.newInstance();
parserFactory.setNamespaceAware(true);
pullParser = parserFactory.newPullParser();
FileReader fileReader = new FileReader(_path);
pullParser.setInput(fileReader);
int eventType = pullParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
Log.d("Test", "the tag name is :" + pullParser.getName());
if (pullParser.getName().equals("string")) {
if (pullParser.getAttributeValue(0).equals(ID)) {
eventType = pullParser.next();
if (eventType == XmlPullParser.TEXT) {
ret = pullParser.getText();
}
}
}
}
eventType = pullParser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
return "Can't Find File";
}
return ret;
}
}
| gpl-3.0 |
h-j-13/MyNote | Programming language/Java/Java program experiment/Demo4/src/Demo4/Demo_4_3.java | 1696 | package Demo4;
/**
* Created by z.g.13@163.com on 2016/7/22.
创建一个名为Telephone的类,
Telephone类中包含有 电话品牌(brand)、
电话号码(number)、
通话时间(dialedTime)、
费率(rate)等属性,
以及计算话费(callCost) 和
显示话费信息(display)方法。
再创建一个名为Mobilephone的类,它是Telephone的子类,
除了具有Telephone类的属性外,
它还有自己的属性如网络类型(network)、
被叫时间(receivedTime),
同时它有自己的计算话费和显示信息的方法。
另外,程序中还有一个
主类PhoneCost来使用上述两个类并显示它们的信息。
电话话费= dialedTime*rate;
电话费率rate=0.2元/分钟;
移动电话话费=(dialedTime+0.5*receivedTime)*rate;
移动电话费率rate=0.4元/分钟
---DEMO----
程序运行的效果如下:
电话品牌:TCL
电话号码:5687506
通话时间:130.0分钟
费率: 0.2元/分钟
花费总计:26.0元
电话品牌:SAMSUNG
电话号码:15163155787
网络: 3G
主叫时间:80.0 分钟
被叫时间:120.0分钟
费率: 0.4元/分钟
花费总计:56.0元
*/
public class Demo_4_3 {
Demo_4_3()
{
Telephone t = new Telephone("TLC","5687506",130.0,0.2);
t.display();
System.out.println();
Mobilephone mt = new Mobilephone("SAMSUNG","15163155787",200,0.4,"3G",120);
mt.display();
}
}
| gpl-3.0 |
tompecina/retro | src/cz/pecina/retro/ondra/KeyChooserPanel.java | 3937 | /* KeyChooserPanel.java
*
* Copyright (C) 2015, Tomáš Pecina <tomas@pecina.cz>
*
* This file is part of cz.pecina.retro, retro 8-bit computer emulators.
*
* This application 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 application 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 cz.pecina.retro.ondra;
import java.util.logging.Logger;
import java.util.Set;
import java.util.NavigableSet;
import java.util.TreeSet;
import java.awt.Frame;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import cz.pecina.retro.gui.BackgroundFixedPane;
import cz.pecina.retro.gui.ToggleButton;
import cz.pecina.retro.gui.GUI;
import cz.pecina.retro.gui.IconCache;
/**
* The key chooser panel.
*
* @author @AUTHOR@
* @version @VERSION@
*/
public class KeyChooserPanel extends BackgroundFixedPane {
// static logger
private static final Logger log =
Logger.getLogger(KeyChooserPanel.class.getName());
// key geometry
private static final int KEY_OFFSET_X = 40;
private static final int KEY_OFFSET_Y = 12;
private static final int KEY_GRID_X = 2;
private static final int KEY_GRID_Y = 28;
// NMI button position
private static final int NMI_OFFSET_X = 14;
private static final int NMI_OFFSET_Y = 16;
// enclosing frame
private Frame frame;
// keys on the emulated keyboard
private ToggleButton buttons[] = new ToggleButton[KeyboardLayout.NUMBER_KEYS + 1];
/**
* Creates a panel containing the mock-up keyboard.
*
* @param frame enclosing frame
* @param keyboardLayout the keyboard layout
* @param keys set of key numbers curently assigned to this shortcut
*/
public KeyChooserPanel(final Frame frame,
final KeyboardLayout keyboardLayout,
final Set<Integer> keys) {
super("ondra/KeyboardPanel/kbdmask",
"metal",
"black");
log.fine("New KeyChooserPanel creation started");
this.frame = frame;
// set up keys
final int pixelSize = GUI.getPixelSize();
for (int n = 0; n < KeyboardLayout.NUMBER_KEYS; n++) {
final KeyboardKey key = keyboardLayout.getKeys()[n];
final ToggleButton button =
new ToggleButton("ondra/KeyboardKey/" + key.getCap() + "-%d-%s.png",
null,
null);
button.setOnIcon(IconCache.get(String.format(button.getTemplate(),
pixelSize,
"l")));
button.setPressed(keys.contains(n));
button.place(this,
KEY_OFFSET_X + (key.getOffsetX() * KEY_GRID_X),
KEY_OFFSET_Y + (key.getOffsetY() * KEY_GRID_Y));
buttons[n] = button;
log.finest("Button for key '" + key + "' placed");
}
final ToggleButton button =
new ToggleButton("ondra/NmiButton/nmi-%d-%s.png",
null,
null);
button.setOnIcon(IconCache.get(String.format(button.getTemplate(),
pixelSize,
"l")));
button.setPressed(keys.contains(KeyboardLayout.NUMBER_KEYS));
button.place(this, NMI_OFFSET_X, NMI_OFFSET_Y);
buttons[KeyboardLayout.NUMBER_KEYS] = button;
log.fine("KeyChooserPanel set up");
}
/**
* Returns a set of all selected keys.
*
* @return a set of all selected keys
*/
public NavigableSet<Integer> getKeys() {
final NavigableSet<Integer> set = new TreeSet<>();
for (int n = 0; n < (KeyboardLayout.NUMBER_KEYS + 1); n++) {
if (buttons[n].isPressed()) {
set.add(n);
}
}
return set;
}
}
| gpl-3.0 |
mwilbers/mw-repo | modules/ofdb-impl/src/main/java/de/mw/mwdata/ofdb/exception/OfdbFormatException.java | 340 | /**
*
*/
package de.mw.mwdata.ofdb.exception;
/**
* @author mwilbers
*
*/
public class OfdbFormatException extends OfdbRuntimeException {
/**
*
*/
private static final long serialVersionUID = -612564368932150245L;
public OfdbFormatException(final String message, final Throwable cause) {
super( message, cause );
}
}
| gpl-3.0 |
jmacauley/OpenDRAC | Clients/AdminConsole/src/main/java/com/nortel/appcore/app/drac/client/lpcpadminconsole/tabs/NeListPanel.java | 17008 | /**
* <pre>
* The owner of the original code is Ciena Corporation.
*
* Portions created by the original owner are Copyright (C) 2004-2010
* the original owner. All Rights Reserved.
*
* Portions created by other contributors are Copyright (C) the contributor.
* All Rights Reserved.
*
* Contributor(s):
* (Contributors insert name & email here)
*
* This file is part of DRAC (Dynamic Resource Allocation Controller).
*
* DRAC 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.
*
* DRAC 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/>.
* </pre>
*/
package com.nortel.appcore.app.drac.client.lpcpadminconsole.tabs;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nortel.appcore.app.drac.client.lpcpadminconsole.NeCache;
import com.nortel.appcore.app.drac.client.lpcpadminconsole.OpenDracDesktop;
import com.nortel.appcore.app.drac.client.lpcpadminconsole.common.DracTableModel;
import com.nortel.appcore.app.drac.client.lpcpadminconsole.topology.JungTopologyPanel;
import com.nortel.appcore.app.drac.client.lpcpadminconsole.topology.NetworkGraph;
import com.nortel.appcore.app.drac.client.lpcpadminconsole.topology.TopologyPopupMenu;
import com.nortel.appcore.app.drac.client.lpcpadminconsole.topology.TopologyViewEventHandler;
import com.nortel.appcore.app.drac.client.lpcpadminconsole.util.ServerOperation;
import com.nortel.appcore.app.drac.client.lpcpadminconsole.util.ServerOperationCallback;
import com.nortel.appcore.app.drac.client.lpcpadminconsole.widgets.TablePanel;
import com.nortel.appcore.app.drac.common.graph.DracVertex;
import com.nortel.appcore.app.drac.common.graph.NeStatus;
import com.nortel.appcore.app.drac.common.types.NetworkElementHolder;
/**
* @author pitman
*/
public final class NeListPanel implements ServerOperationCallback, ActionListener {
private final Logger log = LoggerFactory.getLogger(getClass());
private final JLabel nesManagedLabel = new JLabel("Total NEs managed: 0");
private final JButton addNetworkElementButton = new JButton("Add NE");
private final List<String> neColumns = Arrays.asList(new String[] { "IP",
"Port", "TID", "NEID", "Type", "Status", "Mode", "NeRelease", "Protocol",
"AutoRediscover", "NeIndex", "UserId" });
private final OpenDracDesktop desktop;
private final TablePanel tablePanel = new TablePanel(
new DracTableModel<String>(null, neColumns), null, null);
public NeListPanel(OpenDracDesktop dracDesktop) {
desktop = dracDesktop;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addNetworkElementButton) {
TopologyPopupMenu.addNEDialog(desktop);
}
}
public void enableAddNetworkElementButton(boolean enabled) {
addNetworkElementButton.setEnabled(enabled);
}
public JPanel buildNePanel(){
JPanel nePanel = new JPanel(new BorderLayout(1, 1));
JPanel neListPanel = buildNeListPanel();
JPanel manageNEPanel = buildManageNEPanel();
nePanel.add(neListPanel, BorderLayout.NORTH);
nePanel.add(manageNEPanel, BorderLayout.SOUTH);
return nePanel;
}
public JPanel buildManageNEPanel() {
JPanel manageNEPanel = new JPanel(new BorderLayout(5, 5));
JPanel addNEPanel = new JPanel(new BorderLayout(1, 1));
JLabel addNELabel = new JLabel("Manage NE in OpenDRAC");
JPanel findNEPanel = new JPanel(new BorderLayout(5, 5));
JPanel findNEWestPanel = new JPanel(new BorderLayout(1, 1));
JLabel findNELabel = new JLabel("Find NE");
final JComboBox findNEBox = buildNEBox();
JButton findNEButton = new JButton("Find");
findNEBox.setPreferredSize(new Dimension(365, 21));
findNEBox.setEditable(true);
findNEBox.addPopupMenuListener(new PopupMenuListener() {
boolean willBecomeVisible = false;
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
//
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
//
}
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// Workaround for bug:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4743225
if (!willBecomeVisible) {
JComboBox list = (JComboBox) e.getSource();
findNEBox.removeAllItems();
populateNEBox(findNEBox);
willBecomeVisible = true; // prevent a loop
try {
list.getUI().setPopupVisible(list, true);
}
finally {
willBecomeVisible = false;
}
}
}
});
findNEBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent ie) {
try {
String neSearchString = (String) findNEBox.getSelectedItem();
NetworkGraph.INSTANCE.highlightNELike(neSearchString);
}
catch (Exception e) {
log.error("Error: ", e);
}
}
});
addNetworkElementButton.addActionListener(this);
addNetworkElementButton.setFont(OpenDracDesktop.BASE_FONT);
addNEPanel.add(addNELabel, BorderLayout.CENTER);
addNEPanel.add(addNetworkElementButton, BorderLayout.EAST);
findNEWestPanel.add(findNELabel, BorderLayout.WEST);
findNEWestPanel.add(findNEBox, BorderLayout.CENTER);
findNEWestPanel.add(findNEButton, BorderLayout.EAST);
findNEButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
String neSearchString = (String) findNEBox.getSelectedItem();
NetworkGraph.INSTANCE.highlightNELike(neSearchString);
}
catch (Exception e) {
log.error("Error: ", e);
}
}
});
findNEPanel.add(findNEWestPanel, BorderLayout.CENTER);
manageNEPanel.setBorder(BorderFactory.createTitledBorder("Network Element Management"));
manageNEPanel.add(nesManagedLabel, BorderLayout.NORTH);
manageNEPanel.add(addNEPanel, BorderLayout.CENTER);
manageNEPanel.add(findNEPanel, BorderLayout.SOUTH);
return manageNEPanel;
}
public JPanel buildNeListPanel() {
JButton retrieveButton = new JButton("Retrieve");
retrieveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
((DracTableModel<String>) tablePanel.getTable().getModel())
.clearTable();
getAllNes();
}
});
tablePanel.addButton(tablePanel.getExportButton(desktop, null));
tablePanel.addButton(retrieveButton);
tablePanel.getTable().addMouseListener(new MouseAdapter() {
// Some platforms (like LINUX only detect the mouse pressed)
@Override
public void mousePressed(MouseEvent me) {
if (me.isPopupTrigger()) {
showPopup((Component) me.getSource(), me.getX(), me.getY());
}
}
@Override
public void mouseReleased(MouseEvent me) {
if (me.isPopupTrigger()) {
showPopup((Component) me.getSource(), me.getX(), me.getY());
}
}
});
return tablePanel.getWrappedPanel("Network Element List");
}
@Override
public void handleServerOperationResult(ServerOperation op) {
List<NetworkElementHolder> nes = (List<NetworkElementHolder>) op
.getResult().get(ServerOperation.MAP_RESULT_KEY);
if (nes == null) {
JOptionPane.showMessageDialog(desktop,
"Error occurred retrieving Network elements.", "Error",
JOptionPane.ERROR_MESSAGE);
}
else {
displayNetworkElements(nes);
}
desktop.hideProgressDialog();
}
private void displayNetworkElements(List<NetworkElementHolder> nes) {
List<List<String>> rows = new ArrayList<List<String>>();
List<String> row = null;
try {
desktop.setCursor(OpenDracDesktop.WAIT_CURSOR);
Map<NeStatus, Integer> status = new TreeMap<NeStatus, Integer>();
for (NetworkElementHolder ne : nes) {
row = new ArrayList<String>();
row.add(ne.getIp());
row.add(ne.getPort());
row.add(ne.getTid());
row.add(ne.getId());
row.add(ne.getType().toString());
row.add(ne.getNeStatusWithDate());
row.add(ne.getMode().toString());
row.add(ne.getSubType());
row.add(ne.getNeRelease());
row.add(ne.getCommProtocol().toString());
row.add(Boolean.toString(ne.isAutoReDiscover()));
row.add(Integer.toString(ne.getNeIndex()));
row.add(ne.getUserId());
rows.add(row);
Integer count = status.get(ne.getNeStatus());
if (count == null) {
count = Integer.valueOf(0);
}
count = Integer.valueOf(count.intValue() + 1);
status.put(ne.getNeStatus(), count);
}
StringBuilder sb = new StringBuilder();
sb.append(" (");
for (Map.Entry<NeStatus, Integer> e : status.entrySet()) {
sb.append(e.getValue());
sb.append(" ");
sb.append(e.getKey());
sb.append(" ");
}
sb.append(") ");
((DracTableModel<String>) tablePanel.getTable().getModel()).setData(rows);
tablePanel.setResultsLabel(sb.toString());
tablePanel.updateTable();
desktop.hideProgressDialog();
}
finally {
desktop.setCursor(OpenDracDesktop.DEFAULT_CURSOR);
}
}
private void getAllNes() {
Map<String, String> parametersMap = new HashMap<String, String>();
Thread t = new Thread(new ServerOperation(
ServerOperation.Operation.OP_GET_ALL_NES, this, parametersMap),
OpenDracDesktop.SVR_OP_THREAD_NAME + ": getAllNes()");
desktop.showProgressDialog("Retrieving...");
t.setDaemon(true);
t.start();
}
private JComboBox buildNEBox() {
return new JComboBox(NeCache.INSTANCE.getNEList());
}
private void populateNEBox(JComboBox box) {
String[] nelist = NeCache.INSTANCE.getNEList();
Arrays.sort(nelist);
for (String s : nelist) {
box.addItem(s);
}
}
private void showPopup(Component source, int x, int y) {
JPopupMenu popup = new JPopupMenu();
JMenuItem findNe = new JMenuItem("Find Ne");
JMenuItem neDelete = new JMenuItem("Remove NE");
JMenuItem neToggle = new JMenuItem("Toggle NE Communications Link");
JMenuItem props = new JMenuItem("Properties");
popup.add(neDelete);
popup.add(neToggle);
if (tablePanel.getTable().getSelectedRowCount() > 1) {
log.debug("Multi-Selected " + tablePanel.getTable().getSelectedRowCount()
+ " NEs");
neDelete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
int result = JOptionPane
.showConfirmDialog(
null,
"<HTML>Are you sure you want to remove "
+ tablePanel.getTable().getSelectedRowCount()
+ " Network Elements?<BR><B>All manually provisioned data will be lost</B></HTML>",
"Remove Network Element", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
for (int row : tablePanel.getTable().getSelectedRows()) {
String ip = tablePanel.getTable().getValueAt(row, 0).toString();
String port = tablePanel.getTable().getValueAt(row, 1).toString();
String ieee = tablePanel.getTable().getValueAt(row, 3).toString();
log.debug("Sending delete for " + ip + ":" + port + " " + ieee);
NetworkElementHolder ne = new NetworkElementHolder(ip, port,
null, null, null, NeStatus.NE_UNKNOWN, null, null, 0, null,
null, ieee, null, false, "Unknown", null, null, null);
desktop.handleTopologyViewEvents(
TopologyViewEventHandler.EVENT_TYPE.UNMANAGE_EVENT, ne);
}
getAllNes();
JungTopologyPanel.resetTopology();
}
}
});
neToggle.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
int result = JOptionPane
.showConfirmDialog(
null,
"<HTML>Are you sure you want to toggle the communication link to "
+ tablePanel.getTable().getSelectedRowCount()
+ " Network Elements ?<BR><B>Communications will temporarily be lost</B></HTML>",
"Toggle Network Element Communications",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
for (int row : tablePanel.getTable().getSelectedRows()) {
String ip = tablePanel.getTable().getValueAt(row, 0).toString();
String port = tablePanel.getTable().getValueAt(row, 1).toString();
log.debug("Sending toggle for " + ip + ":" + port);
NetworkElementHolder ne = new NetworkElementHolder(ip, port,
null, null, null, NeStatus.NE_UNKNOWN, null, null, 0, null,
null, null, null, false, "Unknown", null, null, null);
desktop.handleTopologyViewEvents(
TopologyViewEventHandler.EVENT_TYPE.TOGGLE_NE_EVENT, ne);
}
getAllNes();
}
}
});
}
else {
if (tablePanel.getTable().getSelectedRowCount() < 1) {
// Didn't really select a row!
return;
}
popup.add(findNe);
popup.add(props);
final String ip = tablePanel.getTable()
.getValueAt(tablePanel.getTable().getSelectedRow(), 0).toString();
final String port = tablePanel.getTable()
.getValueAt(tablePanel.getTable().getSelectedRow(), 1).toString();
final String tid = tablePanel.getTable()
.getValueAt(tablePanel.getTable().getSelectedRow(), 2).toString();
final String ieee = tablePanel.getTable()
.getValueAt(tablePanel.getTable().getSelectedRow(), 3).toString();
log.debug("Selected single NE " + ip + " " + port + " " + ieee);
props.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DracVertex vertex = NeCache.INSTANCE.getVertex(ip, port);
if (vertex != null) {
TopologyPopupMenu.showNEProperties(desktop.getJungTopologyPanel(),
desktop, vertex);
}
}
});
findNe.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
// desktop.getCurrentView().highlightNELike(tid);
NetworkGraph.INSTANCE.highlightNELike(tid);
}
catch (Exception e1) {
log.error("Error: ", e1);
}
}
});
neDelete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
int result = JOptionPane
.showConfirmDialog(
null,
"<HTML>Are you sure you want to remove "
+ ip
+ " ("
+ tid
+ ") ?<BR><B>All manually provisioned data will be lost</B></HTML>",
"Remove Network Element", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
NetworkElementHolder ne = new NetworkElementHolder(ip, port, null,
null, null, NeStatus.NE_UNKNOWN, null, null, 0, null, null,
ieee, null, false, "Unknown", null, null, null);
desktop.handleTopologyViewEvents(
TopologyViewEventHandler.EVENT_TYPE.UNMANAGE_EVENT, ne);
getAllNes();
}
}
});
neToggle.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
int result = JOptionPane
.showConfirmDialog(
null,
"<HTML>Are you sure you want to toggle the communication link to "
+ ip
+ " ("
+ tid
+ ") ?<BR><B>Communications will temporarily be lost</B></HTML>",
"Toggle Network Element Communications",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
NetworkElementHolder ne = new NetworkElementHolder(ip, port, null,
null, null, NeStatus.NE_UNKNOWN, null, null, 0, null, null,
null, null, false, "Unknown", null, null, null);
desktop.handleTopologyViewEvents(
TopologyViewEventHandler.EVENT_TYPE.TOGGLE_NE_EVENT, ne);
getAllNes();
}
}
});
}
popup.show(source, x, y);
}
}
| gpl-3.0 |
ShahMalavS/MedicinesOnWay | app/src/main/java/com/malav/medicinesontheway/activity/PaymentActivity.java | 1099 | package com.malav.medicinesontheway.activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.WindowManager;
import com.malav.medicinesontheway.R;
import com.malav.medicinesontheway.utils.Constants;
/**
* Created by shahmalav on 20/06/17.
*/
public class PaymentActivity extends AppCompatActivity{
private SharedPreferences someData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
someData = getSharedPreferences(Constants.filename, 0);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Payment Page");
}
}
| gpl-3.0 |
sloanr333/opd-legacy | src/com/watabou/legacy/GamesInProgress.java | 1746 | /*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.watabou.legacy;
import java.util.HashMap;
import com.watabou.legacy.actors.hero.HeroClass;
import com.watabou.utils.Bundle;
public class GamesInProgress {
private static HashMap<HeroClass, Info> state = new HashMap<HeroClass, Info>();
public static Info check( HeroClass cl ) {
if (state.containsKey( cl )) {
return state.get( cl );
} else {
Info info;
try {
Bundle bundle = Dungeon.gameBundle( Dungeon.gameFile( cl ) );
info = new Info();
Dungeon.preview( info, bundle );
} catch (Exception e) {
info = null;
}
state.put( cl, info );
return info;
}
}
public static void set( HeroClass cl, int depth, int level ) {
Info info = new Info();
info.depth = depth;
info.level = level;
state.put( cl, info );
}
public static void setUnknown( HeroClass cl ) {
state.remove( cl );
}
public static void delete( HeroClass cl ) {
state.put( cl, null );
}
public static class Info {
public int depth;
public int level;
}
}
| gpl-3.0 |
PuzzlesLab/UVA | King/13095 Tobby and Query.java | 1238 | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
class Main {
public static void main (String [] args) throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s=br.readLine()).length()>0) {
// End of input is a new line, what a shame that this is not stated in the question!
// Using scanner will lead to TLE.
int N=Integer.parseInt(s);
StringTokenizer st=new StringTokenizer(br.readLine());
int [] nums=new int [N];
for (int n=0;n<N;n++) nums[n]=Integer.parseInt(st.nextToken());
int [][] appears=new int [11][N+1];
for (int n=1;n<=N;n++) {
int num=nums[n-1];
for (int i=0;i<appears.length;i++) appears[i][n]=appears[i][n-1];
appears[num][n]++;
}
StringBuilder sb=new StringBuilder();
int Q=Integer.parseInt(br.readLine());
for (int q=0;q<Q;q++) {
st=new StringTokenizer(br.readLine());
int L=Integer.parseInt(st.nextToken());
int R=Integer.parseInt(st.nextToken());
int ans=0;
for (int i=0;i<appears.length;i++) if(appears[i][R]-appears[i][L-1]>0) ans++;
sb.append(ans);
sb.append('\n');
}
System.out.print(sb.toString());
}
}
}
| gpl-3.0 |
TheJulianJES/UtilsPlus | src/main/java/de/TheJulianJES/UtilsPlus/lib/Quat.java | 2526 | package de.TheJulianJES.UtilsPlus.lib;
import java.util.Formatter;
import java.util.Locale;
public class Quat {
public double x;
public double y;
public double z;
public double s;
public Quat() {
s = 1.0D;
x = 0.0D;
y = 0.0D;
z = 0.0D;
}
public Quat(Quat quat) {
x = quat.x;
y = quat.y;
z = quat.z;
s = quat.s;
}
public Quat(double d, double d1, double d2, double d3) {
x = d1;
y = d2;
z = d3;
s = d;
}
public void set(Quat quat) {
x = quat.x;
y = quat.y;
z = quat.z;
s = quat.s;
}
public static Quat aroundAxis(double ax, double ay, double az, double angle) {
angle *= 0.5D;
double d4 = Math.sin(angle);
return new Quat(Math.cos(angle), ax * d4, ay * d4, az * d4);
}
public void multiply(Quat quat) {
double d = s * quat.s - x * quat.x - y * quat.y - z * quat.z;
double d1 = s * quat.x + x * quat.s - y * quat.z + z * quat.y;
double d2 = s * quat.y + x * quat.z + y * quat.s - z * quat.x;
double d3 = s * quat.z - x * quat.y + y * quat.x + z * quat.s;
s = d;
x = d1;
y = d2;
z = d3;
}
public void rightMultiply(Quat quat) {
double d = s * quat.s - x * quat.x - y * quat.y - z * quat.z;
double d1 = s * quat.x + x * quat.s + y * quat.z - z * quat.y;
double d2 = s * quat.y - x * quat.z + y * quat.s + z * quat.x;
double d3 = s * quat.z + x * quat.y - y * quat.x + z * quat.s;
s = d;
x = d1;
y = d2;
z = d3;
}
public double mag() {
return Math.sqrt(x * x + y * y + z * z + s * s);
}
public void normalize() {
double d = mag();
if (d == 0.0D) {
return;
} else {
d = 1.0D / d;
x *= d;
y *= d;
z *= d;
s *= d;
return;
}
}
public void rotate(Vector3 vec) {
double d = -x * vec.x - y * vec.y - z * vec.z;
double d1 = s * vec.x + y * vec.z - z * vec.y;
double d2 = s * vec.y - x * vec.z + z * vec.x;
double d3 = s * vec.z + x * vec.y - y * vec.x;
vec.x = d1 * s - d * x - d2 * z + d3 * y;
vec.y = d2 * s - d * y + d1 * z - d3 * x;
vec.z = d3 * s - d * z - d1 * y + d2 * x;
}
@Override
public String toString() {
StringBuilder stringbuilder = new StringBuilder();
Formatter formatter = new Formatter(stringbuilder, Locale.US);
formatter.format("Quaternion:\n", new Object[0]);
formatter.format(" < %f %f %f %f >\n", Double.valueOf(s), Double.valueOf(x), Double.valueOf(y), Double.valueOf(z));
formatter.close();
return stringbuilder.toString();
}
public static Quat aroundAxis(Vector3 axis, double angle) {
return aroundAxis(axis.x, axis.y, axis.z, angle);
}
} | gpl-3.0 |
wwgong/CVoltDB | src/frontend/org/voltdb/compiler/deploymentfile/DeploymentType.java | 7973 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10
// 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: 2011.10.17 at 06:12:41 PM EDT
//
package org.voltdb.compiler.deploymentfile;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for deploymentType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="deploymentType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <all>
* <element name="cluster" type="{}clusterType"/>
* <element name="paths" type="{}pathsType" minOccurs="0"/>
* <element name="partition-detection" type="{}partitionDetectionType" minOccurs="0"/>
* <element name="admin-mode" type="{}adminModeType" minOccurs="0"/>
* <element name="heartbeat" type="{}heartbeatType" minOccurs="0"/>
* <element name="httpd" type="{}httpdType" minOccurs="0"/>
* <element name="snapshot" type="{}snapshotType" minOccurs="0"/>
* <element name="export" type="{}exportType" minOccurs="0"/>
* <element name="users" type="{}usersType" minOccurs="0"/>
* <element name="commandlog" type="{}commandLogType" minOccurs="0"/>
* <element name="systemsettings" type="{}systemSettingsType" minOccurs="0"/>
* </all>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "deploymentType", propOrder = {
})
public class DeploymentType {
@XmlElement(required = true)
protected ClusterType cluster;
protected PathsType paths;
@XmlElement(name = "partition-detection")
protected PartitionDetectionType partitionDetection;
@XmlElement(name = "admin-mode")
protected AdminModeType adminMode;
protected HeartbeatType heartbeat;
protected HttpdType httpd;
protected SnapshotType snapshot;
protected ExportType export;
protected UsersType users;
protected CommandLogType commandlog;
protected SystemSettingsType systemsettings;
/**
* Gets the value of the cluster property.
*
* @return
* possible object is
* {@link ClusterType }
*
*/
public ClusterType getCluster() {
return cluster;
}
/**
* Sets the value of the cluster property.
*
* @param value
* allowed object is
* {@link ClusterType }
*
*/
public void setCluster(ClusterType value) {
this.cluster = value;
}
/**
* Gets the value of the paths property.
*
* @return
* possible object is
* {@link PathsType }
*
*/
public PathsType getPaths() {
return paths;
}
/**
* Sets the value of the paths property.
*
* @param value
* allowed object is
* {@link PathsType }
*
*/
public void setPaths(PathsType value) {
this.paths = value;
}
/**
* Gets the value of the partitionDetection property.
*
* @return
* possible object is
* {@link PartitionDetectionType }
*
*/
public PartitionDetectionType getPartitionDetection() {
return partitionDetection;
}
/**
* Sets the value of the partitionDetection property.
*
* @param value
* allowed object is
* {@link PartitionDetectionType }
*
*/
public void setPartitionDetection(PartitionDetectionType value) {
this.partitionDetection = value;
}
/**
* Gets the value of the adminMode property.
*
* @return
* possible object is
* {@link AdminModeType }
*
*/
public AdminModeType getAdminMode() {
return adminMode;
}
/**
* Sets the value of the adminMode property.
*
* @param value
* allowed object is
* {@link AdminModeType }
*
*/
public void setAdminMode(AdminModeType value) {
this.adminMode = value;
}
/**
* Gets the value of the heartbeat property.
*
* @return
* possible object is
* {@link HeartbeatType }
*
*/
public HeartbeatType getHeartbeat() {
return heartbeat;
}
/**
* Sets the value of the heartbeat property.
*
* @param value
* allowed object is
* {@link HeartbeatType }
*
*/
public void setHeartbeat(HeartbeatType value) {
this.heartbeat = value;
}
/**
* Gets the value of the httpd property.
*
* @return
* possible object is
* {@link HttpdType }
*
*/
public HttpdType getHttpd() {
return httpd;
}
/**
* Sets the value of the httpd property.
*
* @param value
* allowed object is
* {@link HttpdType }
*
*/
public void setHttpd(HttpdType value) {
this.httpd = value;
}
/**
* Gets the value of the snapshot property.
*
* @return
* possible object is
* {@link SnapshotType }
*
*/
public SnapshotType getSnapshot() {
return snapshot;
}
/**
* Sets the value of the snapshot property.
*
* @param value
* allowed object is
* {@link SnapshotType }
*
*/
public void setSnapshot(SnapshotType value) {
this.snapshot = value;
}
/**
* Gets the value of the export property.
*
* @return
* possible object is
* {@link ExportType }
*
*/
public ExportType getExport() {
return export;
}
/**
* Sets the value of the export property.
*
* @param value
* allowed object is
* {@link ExportType }
*
*/
public void setExport(ExportType value) {
this.export = value;
}
/**
* Gets the value of the users property.
*
* @return
* possible object is
* {@link UsersType }
*
*/
public UsersType getUsers() {
return users;
}
/**
* Sets the value of the users property.
*
* @param value
* allowed object is
* {@link UsersType }
*
*/
public void setUsers(UsersType value) {
this.users = value;
}
/**
* Gets the value of the commandlog property.
*
* @return
* possible object is
* {@link CommandLogType }
*
*/
public CommandLogType getCommandlog() {
return commandlog;
}
/**
* Sets the value of the commandlog property.
*
* @param value
* allowed object is
* {@link CommandLogType }
*
*/
public void setCommandlog(CommandLogType value) {
this.commandlog = value;
}
/**
* Gets the value of the systemsettings property.
*
* @return
* possible object is
* {@link SystemSettingsType }
*
*/
public SystemSettingsType getSystemsettings() {
return systemsettings;
}
/**
* Sets the value of the systemsettings property.
*
* @param value
* allowed object is
* {@link SystemSettingsType }
*
*/
public void setSystemsettings(SystemSettingsType value) {
this.systemsettings = value;
}
}
| gpl-3.0 |