file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
OnlyPerceptronsAllowed.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/generator/exception/OnlyPerceptronsAllowed.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.generator.exception;
/**
* This exception will be thrown when the perceptron-constraint is not
* fulfilled during the generation of MLPs.
* <br></br>
* @author Sebastian Otte
*/
public class OnlyPerceptronsAllowed extends NetGeneratorException {
private static final long serialVersionUID = -678831812096197825L;
public OnlyPerceptronsAllowed() { super("only perceptrons allowed."); }
}
| 1,320 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
NoInputLayerDefined.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/generator/exception/NoInputLayerDefined.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.generator.exception;
/**
* This exception will be thrown if now input layer is defined during
* generation.
* <br></br>
* @author Sebastian Otte
*/
public class NoInputLayerDefined extends NetGeneratorException {
private static final long serialVersionUID = -678831812096197825L;
public NoInputLayerDefined() { super("no input layer defined."); }
}
| 1,283 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
GeneratingFailed.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/generator/exception/GeneratingFailed.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.generator.exception;
/**
* This exception will be thrown when the generation process could not
* be completed successfully.
* <br></br>
* @author Sebastian Otte
*/
public class GeneratingFailed extends NetGeneratorException {
private static final long serialVersionUID = -678831812096197825L;
public GeneratingFailed() { super("generating failed."); }
}
| 1,288 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
BinaryFunctionDouble.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/misc/BinaryFunctionDouble.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.misc;
/**
* This interface defines a binary function over double.
* <br></br>
* @author Sebastian Otte
*/
public interface BinaryFunctionDouble {
/**
* Computes the operation (first o second), where o is
* a implementation specific operation.
* <br></br>
* @param first Left operand.
* @param second Right operand.
* @return The result of the operation.
*/
public double perform(double first, double second);
}
| 1,378 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
ObjectCopy.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/misc/ObjectCopy.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.misc;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* This class contains a static method for deep copy
* object instances. Note that the objects must implement
* the Serializable interface.
* <br></br>
* @author Sebastian Otte
*/
public class ObjectCopy {
/**
* Returns a copy of the object, or null if the object cannot
* be serialized.
*/
public static <T extends Serializable> T copy(final T obj) {
try {
//
// serialize object.
//
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(buffer);
out.writeObject(obj);
out.flush();
out.close();
//
// de-serialize object.
//
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray())
);
//
@SuppressWarnings("unchecked")
final T result = (T)in.readObject();
in.close();
return result;
} catch (Exception e) {
return null;
}
}
}
| 2,230 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
UnaryFunctionDouble.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/misc/UnaryFunctionDouble.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.misc;
/**
* This interface defines a unary function over double.
* <br></br>
* @author Sebastian Otte
*/
public interface UnaryFunctionDouble {
/**
* Computes the operation (o value) where o is
* a implementation specific unary operation.
* <br></br>
* @param value The operation operand.
* @return The result of the operation.
*/
public double perform(double value);
}
| 1,332 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
DoubleTools.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/misc/DoubleTools.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.misc;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Random;
/**
* This class provides some methods for handling arrays
* of doubles.
* <br></br>
* @author Sebastian Otte
*/
public final class DoubleTools {
public static void copy(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o2++] = data[o1++];
}
}
public static void copy(
final double[] data,
final int dataoffset,
final int[] dataselection,
final double[] result,
final int resultoffset
) {
int o2 = resultoffset;
//
for (int i = 0; i < dataselection.length; i++) {
result[o2++] = data[dataoffset + dataselection[i]];
}
}
public static void copy(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int[] resultselection
) {
int o1 = dataoffset;
//
for (int i = 0; i < resultselection.length; i++) {
result[resultoffset + resultselection[i]] = data[o1++];
}
}
public static void copy(
final double[] data,
final int dataoffset,
final int datastep,
final double[] result,
final int resultoffset,
final int resultstep,
final int size
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o2] = data[o1];
o1 += datastep;
o2 += resultstep;
}
}
public static void fill(
final double[] result,
final int resultoffset,
final int resultstep,
final int size,
final Random rnd,
double lbd,
double ubd
) {
if (lbd > ubd) {
final double temp = lbd;
lbd = ubd;
ubd = temp;
}
final double width = ubd - lbd;
//
int o = resultoffset;
//
for (int i = 0; i < size; i++) {
final double value = (rnd.nextDouble() * width) + lbd;
result[o] = value;
o += resultstep;
}
}
public static void fill(
final double[] result,
final int resultoffset,
final int size,
final Random rnd,
double lbd,
double ubd
) {
if (lbd > ubd) {
final double temp = lbd;
lbd = ubd;
ubd = temp;
}
final double width = ubd - lbd;
//
int o = resultoffset;
//
for (int i = 0; i < size; i++) {
final double value = (rnd.nextDouble() * width) + lbd;
result[o++] = value;
}
}
public static void fill(
final double[] result,
final int resultoffset,
final int size,
final double value
) {
int o = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o++] = value;
}
}
public static void fill(
final double[] result,
final int resultoffset,
final int resultstep,
final int size,
final double value
) {
int o = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o] = value;
o += resultstep;
}
}
public static void threshold(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size,
final double threshold
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o2++] = (data[o1++] > threshold)?(1.0):(0.0);
}
}
public static void threshold(
final double[] data,
final int dataoffset,
final int datastep,
final double[] result,
final int resultoffset,
final int resultstep,
final int size,
final double threshold
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o2] = (data[o1] > threshold)?(1.0):(0.0);
o1 += datastep;
o2 += resultstep;
}
}
public static void map(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size,
final UnaryFunctionDouble f
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o2++] = f.perform(data[o1++]);
}
}
public static void map(
final double[] data,
final int dataoffset,
final int datastep,
final double[] result,
final int resultoffset,
final int resultstep,
final int size,
final UnaryFunctionDouble f
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o2] = f.perform(data[o1]);
o1 += datastep;
o2 += resultstep;
}
}
public static void map(
final double[] first,
final int firstoffset,
final double[] second,
final int secondoffset,
final double[] result,
final int resultoffset,
final int size,
final BinaryFunctionDouble f
) {
int o1 = firstoffset;
int o2 = secondoffset;
int o3 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o3++] = f.perform(first[o1++], second[o2++]);
}
}
public static void map(
final double[] first,
final int firstoffset,
final int firststep,
final double[] second,
final int secondoffset,
final int secondstep,
final double[] result,
final int resultoffset,
final int resultstep,
final int size,
final BinaryFunctionDouble f
) {
int o1 = firstoffset;
int o2 = secondoffset;
int o3 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o3] = f.perform(first[o1], second[o2]);
o1 += firststep;
o2 += secondstep;
o3 += resultstep;
}
}
public static double absSum(
final double[] data,
final int offset,
final int size
) {
int o = offset;
//
double value = 0.0;
//
for (int i = 0; i < size; i++) {
final double x = data[o++];
value += Math.abs(x);
}
//
return value;
}
public static double absSum(
final double[] data,
final int offset,
final int size,
final int step
) {
int o = offset;
//
double value = 0.0;
//
for (int i = 0; i < size; i++) {
final double x = data[o];
value += Math.abs(x);
o += step;
}
//
return value;
}
public static double meanSquareSum(
final double[] data,
final int offset,
final int size
) {
int o = offset;
//
double value = 0.0;
//
for (int i = 0; i < size; i++) {
final double x = data[o++];
value += (x * x);
}
//
return value / ((double)size);
}
public static double squareSum(
final double[] data,
final int offset,
final int size
) {
int o = offset;
//
double value = 0.0;
//
for (int i = 0; i < size; i++) {
final double x = data[o++];
value += (x * x);
}
//
return value;
}
public static double squareSum(
final double[] data,
final int offset,
final int size,
final int step
) {
int o = offset;
//
double value = 0.0;
//
for (int i = 0; i < size; i++) {
final double x = data[o];
value += (x * x);
o += step;
}
//
return value;
}
public static double sum(
final double[] data,
final int offset,
final int size
) {
int o = offset;
//
double value = 0.0;
//
for (int i = 0; i < size; i++) {
value += data[o++];
}
//
return value;
}
public static double sum(
final double[] data,
final int offset,
final int size,
final int step
) {
int o = offset;
//
double value = 0.0;
//
for (int i = 0; i < size; i++) {
value += data[o];
o += step;
}
//
return value;
}
public static double mul(
final double[] data,
final int offset,
final int size
) {
int o = offset;
//
double value = 1.0;
//
for (int i = 0; i < size; i++) {
value *= data[o++];
}
//
return value;
}
public static double mul(
final double[] data,
final int offset,
final int size,
final int step
) {
int o = offset;
//
double value = 1.0;
//
for (int i = 0; i < size; i++) {
value *= data[o];
o += step;
}
//
return value;
}
public static void dot(
final double[] first,
final int firstoffset,
final double[] second,
final int secondoffset,
final int size,
final double[] result,
final int resultoffset
) {
int o1 = firstoffset;
int o2 = secondoffset;
int o3 = resultoffset;
//
double sum = 0;
//
for (int i = 0; i < size; i++) {
sum += (first[o1++] * second[o2++]);
}
//
result[o3] = sum;
}
public static void dot(
final double[] first,
final int firstoffset,
final int firststep,
final double[] second,
final int secondoffset,
final int secondstep,
final int size,
final double[] result,
final int resultoffset
) {
int o1 = firstoffset;
int o2 = secondoffset;
int o3 = resultoffset;
//
double sum = 0;
//
for (int i = 0; i < size; i++) {
sum += (first[o1] * second[o2]);
o1 += firststep;
o2 += secondstep;
}
//
result[o3] = sum;
}
public static void add(
final double[] first,
final int firstoffset,
final double[] second,
final int secondoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = firstoffset;
int o2 = secondoffset;
int o3 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o3++] = first[o1++] + second[o2++];
}
}
public static void add(
final double[] first,
final int firstoffset,
final int firststep,
final double[] second,
final int secondoffset,
final int secondstep,
final double[] result,
final int resultoffset,
final int resultstep,
final int size
) {
int o1 = firstoffset;
int o2 = secondoffset;
int o3 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o3] = first[o1] + second[o2];
o1 += firststep;
o2 += secondstep;
o3 += resultstep;
}
}
public static void sub(
final double[] first,
final int firstoffset,
final double[] second,
final int secondoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = firstoffset;
int o2 = secondoffset;
int o3 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o3++] = first[o1++] - second[o2++];
}
}
public static void sub(
final double[] first,
final int firstoffset,
final int firststep,
final double[] second,
final int secondoffset,
final int secondstep,
final double[] result,
final int resultoffset,
final int resultstep,
final int size
) {
int o1 = firstoffset;
int o2 = secondoffset;
int o3 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o3] = first[o1] - second[o2];
o1 += firststep;
o2 += secondstep;
o3 += resultstep;
}
}
public static void mul(
final double[] first,
final int firstoffset,
final double[] second,
final int secondoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = firstoffset;
int o2 = secondoffset;
int o3 = resultoffset;
//
for (int i = 0; i < size; i++) {
final double v1 = first[o1++];
final double v2 = second[o2++];
//
final double value = v1 * v2;
result[o3++] = value;
}
}
public static void mul(
final double[] first,
final int firstoffset,
final int firststep,
final double[] second,
final int secondoffset,
final int secondstep,
final double[] result,
final int resultoffset,
final int resultstep,
final int size
) {
int o1 = firstoffset;
int o2 = secondoffset;
int o3 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o3] = first[o1] * second[o2];
o1 += firststep;
o2 += secondstep;
o3 += resultstep;
}
}
public static void div(
final double[] first,
final int firstoffset,
final double[] second,
final int secondoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = firstoffset;
int o2 = secondoffset;
int o3 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o3++] = first[o1++] / second[o2++];
}
}
public static void div(
final double[] first,
final int firstoffset,
final int firststep,
final double[] second,
final int secondoffset,
final int secondstep,
final double[] result,
final int resultoffset,
final int resultstep,
final int size
) {
int o1 = firstoffset;
int o2 = secondoffset;
int o3 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o3] = first[o1] / second[o2];
o1 += firststep;
o2 += secondstep;
o3 += resultstep;
}
}
public static void divSafe(
final double[] first,
final int firstoffset,
final double[] second,
final int secondoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = firstoffset;
int o2 = secondoffset;
int o3 = resultoffset;
//
for (int i = 0; i < size; i++) {
final double value = first[o1++];
final double quo = second[o2++];
result[o3++] = (quo == 0)?(value):(value / quo);
}
}
public static void divSafe(
final double[] first,
final int firstoffset,
final int firststep,
final double[] second,
final int secondoffset,
final int secondstep,
final double[] result,
final int resultoffset,
final int resultstep,
final int size
) {
int o1 = firstoffset;
int o2 = secondoffset;
int o3 = resultoffset;
//
for (int i = 0; i < size; i++) {
final double value = first[o1];
final double quo = second[o2];
result[o3] = (quo == 0)?(value):(value / quo);
o1 += firststep;
o2 += secondstep;
o3 += resultstep;
}
}
public static String asString(final double[] data, final int decimals) {
return asString(data, 0, 1, data.length, decimals);
}
public static String asString(final double value, final int decimals) {
//
DecimalFormat f = new DecimalFormat();
f.setDecimalSeparatorAlwaysShown(true);
f.setMaximumFractionDigits(decimals);
f.setMinimumFractionDigits(decimals);
f.setGroupingUsed(false);
//
f.setDecimalFormatSymbols(new DecimalFormatSymbols() {
private static final long serialVersionUID = -2464236658633690492L;
public char getGroupingSeparator() { return ' '; }
public char getDecimalSeparator() { return '.'; }
});
return f.format(value);
}
public static String asString(
final double[] data,
final String delimiter,
final int decimals
) {
return asString(data, delimiter, 0, 1, data.length, decimals);
}
public static String asString(
final double[] data, final int offset, final int size, final int decimals
) {
return asString(data, offset, 1, size, decimals);
}
public static String asString(
final double[] data,
final String delimiter,
final int offset, final int size, final int decimals
) {
return asString(data, delimiter, offset, 1, size, decimals);
}
public static String asString(
final double[] data, final int offset,
final int step, final int size,
final int decimals
) {
return asString(data, ", ", offset, step, size, decimals);
}
public static String asString(
final double[] data,
final String delimiter,
final int offset,
final int step, final int size,
final int decimals
) {
StringWriter out = new StringWriter();
DecimalFormat f = new DecimalFormat();
f.setDecimalSeparatorAlwaysShown(true);
f.setMaximumFractionDigits(decimals);
f.setMinimumFractionDigits(decimals);
f.setGroupingUsed(false);
f.setDecimalFormatSymbols(new DecimalFormatSymbols() {
private static final long serialVersionUID = -2464236658633690492L;
public char getGroupingSeparator() { return ' '; }
public char getDecimalSeparator() { return '.'; }
});
int o = offset;
for (int i = 0; i < size; i++) {
if (i > 0) out.append(delimiter);
out.append(f.format(data[o]));
o += step;
}
return out.toString();
}
public static double[] tail(
final double[] data,
final int size
) {
double[] result = new double[size];
int offset = data.length - 1;
for (int i = size - 1; i >= 0; i--) {
if (offset < 0) break;
result[i] = data[offset--];
}
return result;
}
public static double[] merge(final double[] ...arrays) {
int length = 0;
for(int i = 0; i < arrays.length; i++) {
length += arrays[i].length;
}
double[] result = new double[length];
int offset = 0;
for(int i = 0; i < arrays.length; i++) {
final int l = arrays[i].length;
copy(arrays[i], 0, result, offset, l);
offset += l;
}
return result;
}
}
| 22,457 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
TimeCounter.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/misc/TimeCounter.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.misc;
/**
* This class is for measurement of performance an timings.
* <br></br>
* @author Sebastian Otte
*/
public class TimeCounter {
//
private final static long SCALE_MICRO = 1000L;
private final static long SCALE_MILLI = 1000000L;
//
private final static double FACTOR_MICRO = 1.0 / 1000.0;
private final static double FACTOR_MILLI = 1.0 / 1000000.0;
protected long value = 0L;
/**
* Resets the saved start time with the actual time.
*/
public void reset() {
this.value = System.nanoTime();
}
/**
* Creates an instance of PerformanceCounter.
*/
public TimeCounter() {
this.reset();
}
/**
* Returns the passed nanoseconds since the last counter reset.
*/
public long valueNano() {
final long now = System.nanoTime();
final long ns = now - this.value;
return ns;
}
/**
* Return the passed milliseconds since the last counter reset.
*/
public long value() {
final long now = System.nanoTime();
final long ns = now - this.value;
return ns / SCALE_MILLI;
}
/**
* Return the passed microseconds since the last counter reset.
*/
public long valueMicro() {
final long now = System.nanoTime();
final long ns = now - this.value;
return ns / SCALE_MICRO;
}
/**
* Return the passed microseconds since the last counter reset.
*/
public long valueMilli() {
final long now = System.nanoTime();
final long ns = now - this.value;
return ns / SCALE_MILLI;
}
/**
* Return the passed nanoseconds since the last counter reset.
*/
public double valueNanoDouble() {
final long now = System.nanoTime();
final double ns = now - this.value;
return ns;
}
/**
* Return the passed milliseconds since the last counter reset.
*/
public double valueDouble() {
final long now = System.nanoTime();
final double ns = now - this.value;
return ns * FACTOR_MILLI;
}
/**
* Return the passed microseconds since the last counter reset.
*/
public double valueMicroDouble() {
final long now = System.nanoTime();
final double ns = now - this.value;
return ns * FACTOR_MICRO;
}
/**
* Return the passed milliseconds since the last counter reset.
*/
public double valueMilliDouble() {
final long now = System.nanoTime();
final double ns = now - this.value;
return ns * FACTOR_MILLI;
}
/**
* Returns the current passed millisecond and calls reset().
*/
public long reval() {
final long now = System.nanoTime();
final long ns = now - this.value;
//
this.value = now;
//
return ns / SCALE_MILLI;
}
/**
* Returns the current passed milliseconds and calls reset().
*/
public double revalDouble() {
final long now = System.nanoTime();
final double ns = now - this.value;
//
this.value = now;
//
return ns * FACTOR_MILLI;
}
}
| 3,775 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
IntTools.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/misc/IntTools.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.misc;
import java.io.StringWriter;
import java.util.Random;
/**
* This class provides some methods for handling
* arrays of ints.
* <br></br>
* @author Sebastian Otte
*/
public final class IntTools {
public static void shuffle(
final int[] data,
final Random rnd
) {
//
final int size = data.length;
//
for (int i = size; i > 1; i--) {
final int ii = i - 1;
final int r = rnd.nextInt(i);
//
final int temp = data[ii];
data[ii] = data[r];
data[r] = temp;
}
}
public static String asString(final int[] data) {
return asString(data, 0, data.length);
}
public static String asString(final int[] data, final int offset, final int size) {
StringWriter out = new StringWriter();
int o = offset;
for (int i = 0; i < size; i++) {
if (i > 0) out.append(", ");
out.append(Integer.toString(data[o]));
o++;
}
return out.toString();
}
}
| 2,016 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
MatrixTools.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/math/MatrixTools.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.math;
import de.jannlab.misc.DoubleTools;
public class MatrixTools {
public static final int VALUE_PADDING = 2;
public static double[] allocate(final int m, final int n) {
return new double[m * n];
}
public static double[] allocate(final int m) {
return new double[m];
}
public static void setRow(
final double[] matrix, final int n, final int m,
final int i, final double ...values
) {
//
setRow(matrix, n, m, i, values, 0);
}
public static void setRow(
final double[] matrix, final int n, final int m,
final int i, final double[] values, final int offset
) {
//
DoubleTools.copy(
matrix, i * n, values, offset,
Math.min(n, values.length - offset)
);
}
public static int idx(final int i, final int j, final int n) {
return (i * n) + j;
}
public static void transpose(
final double[] A,
final int m,
final int n,
final double[] At
) {
//
final double[] copy = A.clone();
final int size = m * n;
//
int offset = 0;
//
for (int i = 0; i < size; i++) {
//
At[offset] = copy[i];
//
offset += m;
if (offset >= size) {
offset = (offset - size) + 1;
}
}
}
public static String asString(
final double[] A,
int m,
int n,
int decimals
) {
final StringBuilder out = new StringBuilder();
final int size = m * n;
final String[] elements = new String[size];
//
int max = 0;
//
for (int i = 0; i < size; i++) {
elements[i] = DoubleTools.asString(A, i, 1, decimals);
if (elements[i].length() > max) {
max = elements[i].length();
}
}
//
final int celllength = max + VALUE_PADDING;
//
for (int i = 0; i < size; i++) {
if ((i > 0) && ((i % n) == 0)) out.append("\n");
//
final String value = elements[i];
final int diff = celllength - value.length();
for (int j = 0; j < diff; j++) {
out.append(" ");
}
out.append(value);
}
//
return out.toString();
}
}
| 3,413 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
MathTools.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/math/MathTools.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.math;
/**
* This class provides some frequently used mathematical
* helper methods.
* <br></br>
* @author Sebastian Otte
*/
public class MathTools {
public static final double NULL_THRESHOLD_DOUBLE = 1.0e-9;
public static final float NULL_THRESHOLD_FLOAT = 1.0e-9f;
/**
* Checks, if the given value is approximately 0.0 based on the
* threshold NULL_THRESHOLD_DOUBLE.
* <br></br>
* @param value The value which is to check.
* @return True if absolute of the given value is smaller than the threshold.
*/
public static boolean approxNull(final double value) {
return Math.abs(value) < NULL_THRESHOLD_DOUBLE;
}
/**
* Checks, if the given value is approximately 0.0 based on the
* threshold NULL_THRESHOLD_FLOAT.
* <br></br>
* @param value The value which is to check.
* @return True if absolute of the given value is smaller than the threshold.
*/
public static boolean approxNull(final float value) {
return Math.abs(value) < NULL_THRESHOLD_FLOAT;
}
/**
* Checks, if the given value is approximately 0.0 based on the
* threshold given by errorbound.
* <br></br>
* @param value The value which is to check.
* @param errorbound The explicitly given threshold.
* @return True if absolute of the given value is smaller than the threshold.
*/
public static boolean approxNull(final double value, final double errorbound) {
return Math.abs(value) < Math.abs(errorbound);
}
/**
* Checks, if the given value is approximately 0.0 based on the
* threshold given by errorbound.
* <br></br>
* @param value The value which is to check.
* @param errorbound The explicitly given threshold.
* @return True if absolute of the given value is smaller than the threshold.
*/
public static boolean approxNull(final float value, final float errorbound) {
return Math.abs(value) < Math.abs(errorbound);
}
/**
* Computes the apprixmation of the exponential function e^{x} using
* the interpretation of IEEE-754 numbers.
* <br></br>
* References:
* <br></br>
* Schraudolph, Nicol N.: A Fast, Compact Approximation of the
* Exponential Function. In:Neural Computation11 (1998), S. 11???4
* <br></br>
* Optimized Exponential Functions for Java.
* http://martin.ankerl.com/2007/02/11/optimized-exponential-
* functions-for-java/, 2007. ??? Visited on Januar, 12st 2012
* <br></br>
* @param value The argument of the exp function.
* @return Approximation of e^{x}.
*/
public static double fastExp(final double value) {
final long tmp = (long)(1512775 * value) + 1072632447;
return Double.longBitsToDouble(tmp << 32);
}
/**
* Computes a fast tanh function based on the approximation
* of the expontial function.
* <br></br>
* @param value The argument of the tanh function.
* @return Approximation of tanh(x).
*/
public static double fastTanh(final double value) {
final double pos = fastExp(value);
final double neg = fastExp(-value);
return (pos - neg) / (pos + neg);
}
/**
* Return the index of the biggest values in an array of doubles.
* Returns -1 if an empty array is given.
* <br></br>
* @param args Double array.
* @return The index of the biggest value.
*/
public static int argmax(final double ...args) {
if (args.length == 0) return -1;
//
int maxidx = 0;
double max = args[0];
for (int i = 1; i < args.length; i++) {
if (args[i] > max) {
max = args[i];
maxidx = i;
}
}
return maxidx;
}
/**
* Return the index of the smallest values in an array of doubles.
* Returns -1 if an empty array is given.
* <br></br>
* @param args Double array.
* @return The index of the smallest value.
*/
public static int argmin(final double ...args) {
if (args.length == 0) return -1;
//
int minidx = 0;
double min = args[0];
for (int i = 1; i < args.length; i++) {
if (args[i] < min) {
min = args[i];
minidx = i;
}
}
return minidx;
}
/**
* Clamps a given value x returned as x' within the interval [lbd, ubd]
* such that x' = lbd if x < lbd, x' = ubd if x > ubd or x' = x otherwise.
* @param value The given value.
* @param lbd Lower bound of the clamp interval.
* @param ubd Upper bound of the clamp interval.
* @return A values within the interval [lbd, ubd]
*/
public static double clamp(
final double value, final double lbd, final double ubd
) {
return (
(value < lbd) ? (lbd) : (
(value > ubd) ? (ubd) : (value)
)
);
}
}
| 5,978 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
Histogram.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/math/Histogram.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.math;
import de.jannlab.misc.DoubleTools;
/**
* This class provides the construction of ordinary histograms based on the
* type double. For setting up a histogram a number of quanta (bins) as well
* as a lower and an upper bound of the value interval must be given. With
* the note method a value can be "counted". After all, the histogram can
* be normalized.
* <br></br>
* @author Sebastian Otte
*/
public class Histogram {
/**
* The lower bound of the value interval.
*/
private double lbd;
/**
* The upper bound of the value interval.
*/
private double ubd;
/**
* The width of the value interval.
*/
private double irange;
/**
* The inverted range of the value interval
* (for runtime improvements).
*/
private double range;
/**
* The number of quanta (bins).
*/
private int quanta;
/**
* The number of quanta as double (slightly lower value).
*/
private double dquanta;
/**
* The inner accumulator containing the histogram values.
*/
private double[] accu;
/**
* Returns the lower bound of the value interval.
* <br></br>
* @return Lower bound as double.
*/
public final double getLbd() {
return this.lbd;
}
/**
* Return the upper bound of the value value interval.
* <br></br>
* @return Upper bound as double.
*/
public final double getUbd() {
return this.ubd;
}
/**
* Returns the number of quanta (bins).
* <br></br>
* @return The number of quanta.
*/
public final int getQuanta() {
return this.quanta;
}
/**
* Accumulates the given value in the current histogram with
* weight of 1.0.
* <br></br>
* @param value Value within the given interval.
*/
public void note(final double value) {
this.note(value, 1.0);
}
/**
* Normalized the histogram such that the range form the biggest value
* to biggest negative value is about 1.0.
*/
public void normalize() {
this.normalize(1.0);
}
/**
* Makes all values of the histogram positive.
*/
public void abs() {
for (int i = 0; i < this.quanta; i++) {
this.accu[i] = Math.abs(this.accu[i]);
}
}
/**
* Normalized the histogram such that the sum of all values
* (absolute values are taken) is about 1.0.
*/
public void normalizeSum() {
this.normalizeSum(1.0);
}
/**
* Normalized the histogram such that the sum of all values
* (absolute values are taken) is about a value given by height.
*/
public void normalizeSum(final double height) {
double sum = 0.0;
//
// collecting sum.
//
for (int i = 0; i < this.quanta; i++) {
sum += Math.abs(this.accu[i]);
}
final double isum = ((sum > 0.0)?(1.0 / sum):(0.0)) * height;
//
// normalizing values.
//
for (int i = 0; i < this.quanta; i++) {
this.accu[i] *= isum;
}
}
/**
* Normalized the histogram such that the range form the biggest value
* to biggest negative value is about a value given by height.
*/
public void normalize(final double height) {
//
double min = 0.0;
double max = 0.0;
//
// determine max postive and negative amplitude.
//
for (int i = 0; i < this.quanta; i++) {
final double amp = this.accu[i];
if (amp < min) min = amp;
if (amp > max) max = amp;
//
}
//
// compute range.
//
final double width = max - min;
final double iwidth = (width > 0)?(1.0 / width):(0.0);
//
// normalize values with range.
//
for (int i = 0; i < this.quanta; i++) {
this.accu[i] *= iwidth;
}
}
/**
* Quantizes a given value, which means that the
* quantum (bin) index is calculated based on the
* the histogram interval.
* <br></br>
* @param value
* @return The quantum index.
*/
private int quantize(final double value) {
//
// normalize value to [0, 1].
//
final double norm = (value - this.lbd) * this.irange;
//
// then scale to number of quanta and compute floor value.
//
final int idx = (int)(norm * this.dquanta);
return idx;
}
/**
* Accumulates the given value in the current histogram with
* an additionally given weight.
* <br></br>
* @param value Value within the given interval.
* @param weight The weight of the value.
*/
public void note(final double value, final double weight) {
final int idx = quantize(value);
if ((idx < 0) || (idx >= this.quanta)) return;
this.accu[idx] += weight;
}
/**
* Resets the current histogram. All accumulated values
* are set to 0.0.
*/
public void clear() {
DoubleTools.fill(this.accu, 0, this.quanta, 0.0);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return "[" + DoubleTools.asString(this.accu, 2) + "]";
}
/**
* Instantiates a Histogram object for given values value range determined
* by a lower and an upper bound, with a given number a quanta (bins).
* <br></br>
* @param lbd Lower bound of the accumulation interval.
* @param ubd Upper bound of the accumulation interval.
* @param quanta Number of quanta (bins).
*/
public Histogram(final double lbd, final double ubd, final int quanta) {
//
this.lbd = Math.min(lbd, ubd);
this.ubd = Math.max(lbd, ubd);
this.range = this.ubd - this.lbd;
this.irange = (this.range > 0.0)?(1.0 / this.range):(0.0);
//
this.quanta = Math.max(1, quanta);
this.dquanta = ((double)this.quanta) - Double.MIN_VALUE;
this.accu = new double[this.quanta];
}
/**
* Check, if at least one of the histogram values is positive (> 0.0).
* <br></br>
* @return True if one value is positive, false otherwise.
*/
public boolean hasPositiveValues() {
for (int i = 0; i < this.quanta; i++) {
if (this.accu[i] > 0.0) return true;
}
return false;
}
/**
* Check, if at least one of the histogram values is negative (< 0.0).
* <br></br>
* @return True if one value is negative, false otherwise.
*/
public boolean hasNegativeValues() {
for (int i = 0; i < this.quanta; i++) {
if (this.accu[i] < 0.0) return true;
}
return false;
}
/**
* This method produces a simple bar-chart representation of the
* inner accumulator as a white-space aligned String. The given
* height defines the number of text lines of which the highest bar
* in the histogram may consists of. Note, that the resulting
* string is just for ascii-style printouts, it should not be
* used for extracting histogram data.
* <br></br>
* @param height The number of lines of the highest bar.
* @return A string containing the bar-char representation of the histogram.
*/
public String printBars(final int height) {
//
StringBuilder out = new StringBuilder();
final boolean neg = this.hasNegativeValues();
final boolean pos = this.hasPositiveValues();
//
if (pos) {
String[][] matrix = new String[height][this.quanta];
//
double max = 0.0;
for (int i = 0; i < this.quanta; i++) {
if (accu[i] > max) {
max = accu[i];
}
}
//
final double step = (max / ((double)height));
//
for (int i = 0; i < this.quanta; i++) {
double thres = 0;
double value = this.accu[i];
for (int j = 0; j < height; j++) {
if (value > thres) {
matrix[j][i] = " || ";
} else {
matrix[j][i] = " ";
}
thres += step;
}
}
for (int j = height - 1; j >= 0; j--) {
for (int i = 0; i < this.quanta; i++) {
out.append(matrix[j][i]);
}
out.append("\n");
}
}
//
for (int i = 0; i < this.quanta; i++) {
out.append("----");
}
out.append("\n");
//
if (neg) {
String[][] matrix = new String[height][this.quanta];
//
double min = 0.0;
for (int i = 0; i < this.quanta; i++) {
if (this.accu[i] < min) {
min = this.accu[i];
}
}
//
final double step = (min / ((double)height));
//
for (int i = 0; i < this.quanta; i++) {
double thres = 0;
double value = this.accu[i];
for (int j = 0; j < height; j++) {
if (value < thres) {
matrix[j][i] = " || ";
} else {
matrix[j][i] = " ";
}
thres += step;
}
}
for (int j = 0; j < height; j++) {
for (int i = 0; i < this.quanta; i++) {
out.append(matrix[j][i]);
}
out.append("\n");
}
}
return out.toString();
}
/**
* Returns the inner accumulator, which contains all
* histogram values.
* <br></br>
* @return Histogram values as double[].
*/
public double[] getAccu() {
return this.accu;
}
}
| 11,234 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
NetStructure.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/NetStructure.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
import java.io.Serializable;
import java.io.StringWriter;
import static de.jannlab.tools.Debug.*;
/**
* An instance of the class NetStructure contains the while structural specification
* of a network. This includes the cells and their partition into layers and cellarrays.
* Note that a cells is still determined by a single index.
* Also additional informations of the network are given, e.g. whether the network
* if recurrent or not. The structure of the network mainly defines its computation
* process. From this point of view, the structure instance can be seen as an "algorithm"
* performed by the ANN framework.
* <br></br>
* Note that some data values in the structure are redundant with values over layers
* and arrays. That is to minimize frequently performed hierarchical data acquisitions,
* which affect the runtime performance.
* <br></br>
* @author Sebastian Otte
*/
public final class NetStructure implements Serializable {
private static final long serialVersionUID = -4202226869611119404L;
//
/**
* Gives the complete number of cells.
*/
public int cellsnum;
/**
* Gives only the number of values cells.
*/
public int valcellsnum;
/**
* Gives the number computing cells (non-value).
*/
public int comcellsnum;
/**
* Gives the lower bound of the range of input cells.
*/
public int incellslbd;
/**
* Gives the upper bound of the range of input cells.
*/
public int incellsubd;
/**
* Gives the number of input cells.
*/
public int incellsnum;
/**
* Gives the number of output cells.
*/
public int outcellsnum;
/**
* Gives lower bound of the range of output cells.
*/
public int outcellslbd;
/**
* Gives the upper bound of the range of output cells.
*/
public int outcellsubd;
/**
* provides the array of layers.
*/
public Layer[] layers;
/**
* gives the number of layers.
*/
public int layersnum;
/**
* determines whether the network has recurrent connections or not.
*/
public boolean recurrent;
/**
* determines whether the network computes "offline" or "online".
*/
public boolean offline;
/**
* determines whether the network is bidirectional, which a special form
* of offline computing networks.
*/
public boolean bidirectional;
/**
* gives the index of the input layer.
*/
public int inputlayer;
/**
* gives the index of the output layer.
*/
public int outputlayer;
/**
* provides all CellArray instances of the networks.
*/
public CellArray[] arrays;
/**
* gives the number of cellarrays.
*/
public int arraysnum;
/**
* provides all links of the network in dst major order. this
* links are used in forward computation.
*/
public int[] links;
/**
* provides all links of the network in src major order, where
* this src and dst values are additionally swapped. so we can say
* that linksrev contains the inverted links.
*/
public int[] linksrev;
/**
* gives the number of links in this network.
*/
public int linksnum;
/**
* Gives the number of weights exclusive the constant 1.0 weight.
* (redundant to NetData.weightsnum). The number of weights can be
* less than the number of links.
*/
public int weightsnum;
//
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringWriter w = new StringWriter();
//
w.append("cellsnum : " + this.cellsnum + "\n");
w.append("valcellsnum : " + this.valcellsnum + "\n");
w.append("comcellsnum : " + this.comcellsnum + "\n");
w.append("incellslbd : " + this.incellslbd + "\n");
w.append("incellsubd : " + this.incellsubd + "\n");
w.append("incellsnum : " + this.incellsnum + "\n");
w.append("outcellsnum : " + this.outcellsnum + "\n");
w.append("outcellslbd : " + this.outcellslbd + "\n");
w.append("outcellsubd : " + this.outcellsubd + "\n");
w.append("recurrent : " + this.recurrent + "\n");
w.append("offline : " + this.offline + "\n");
w.append("bidirectional : " + this.bidirectional + "\n");
w.append("layersnum : " + this.layersnum + "\n");
w.append("inputlayer : " + this.inputlayer + "\n");
w.append("outputlayer : " + this.outputlayer + "\n");
w.append("\n");
//
for (int i = 0; i < this.layersnum; i++) {
w.append("layers["+ i +"] : {\n");
w.append(indent(this.layers[i].toString()) + "\n");
w.append("}\n");
}
//
w.append("\n");
w.append("arraysnum : " + this.arraysnum + "\n");
w.append("\n");
//
for (int i = 0; i < this.arraysnum; i++) {
w.append("arrays["+ i +"] : {\n");
w.append(indent(this.arrays[i].toString()) + "\n");
w.append("}\n");
}
//
w.append("\n");
w.append("linksnum : " + this.linksnum + "\n");
w.append("weightsnum : " + this.weightsnum + "\n");
w.append("\n");
//
// print connections.
//
w.append("links : {\n");
w.append(indent(Link.asString(this.links, 0, this.linksnum, 10)));
w.append("\n");
w.append("}\n");
w.append("\n");
//
w.append("linksrev : {\n");
w.append(indent(Link.asString(this.linksrev, 0, this.linksnum, 10)));
w.append("\n");
w.append("}\n");
w.append("\n");
//
return w.toString();
}
}
| 6,747 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
CellFunction.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/CellFunction.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
/**
* This class contains static methods for computing the activations and
* derivations for serveral types of activation functions. These are unary functions
* for computing just single values and more complex functions for computing the
* activation for a range cells. For such a function an argument array and a result array
* with offsets are given.
* <br></br>
* @author Sebastian Otte
*/
public final class CellFunction {
//
/** No computation. */
public static final int NONE = 0;
/** Const value of one. */
public static final int CONST_ONE = 1;
/** ID function (just copy). */
public static final int ID = 2;
/** Standard sigmoid function. */
public static final int SIGMOID = 3;
/** Derivation of the sigmoid function. */
public static final int SIGMOIDDX = 4;
/** Sigmoid function with range of [-1,1]. */
public static final int SIGMOID1 = 5;
/** Derivation of the sigmoid11 function. */
public static final int SIGMOID1DX = 6;
/** Sigmoid function with range of [-2,2]. */
public static final int SIGMOID2 = 7;
/** Derivation of the sigmoid22 function. */
public static final int SIGMOID2DX = 8;
/** Tangens hyperbolicus */
public static final int TANH = 9;
/** Derivation of the tanges hyperbolicus */
public static final int TANHDX = 10;
/** Multiplicative invert function (1/x). */
public static final int INVERT = 11;
// ------------------------------------------------------------------------
// Unary functions.
// ------------------------------------------------------------------------
/**
* This is just a exp-wrapper method. In this method
* the exp-function can be replaced by a fast approx. version of exp.
* <br></br>
* @param value The exponent.
* @return The exponentiation of e^{value}.
*/
public static double exp(final double value) {
//
// replacing the exp with fastExp improves dramatically the runtime
// performance of computing activation but with less accuracy.
// Experiments could show, that for some training problems, the
// fast exp works great but on most problems the convergence is
// lower and for example LSTMs may produce NaN values.
//
//return de.sotte.math.MathTools.fastExp(value);
//
return Math.exp(value);
}
/**
* Computes the standard sigmoid function.
* <br></br>
* @param value Argument of the function.
* @return The function result.
*/
public static double sigmoid(final double value) {
return 1.0 / (1.0 + exp(-value));
}
/**
* Computes the derivation of the standard sigmoid function.
* <br></br>
* @param value Argument of the function.
* @return The function result.
*/
public static double sigmoidDx(final double value) {
final double sig = sigmoid(value);
return sig * (1.0 - sig);
}
/**
* Computes the sigmoid function with range [-2, 2].
* <br></br>
* @param value Argument of the function.
* @return The function result.
*/
public static double sigmoid2(final double value) {
return (4.0 / (1.0 + exp(-value))) - 2.0;
}
/**
* Computes the derivation of the sigmoid22 function.
* <br></br>
* @param value Argument of the function.
* @return The function result.
*/
public static double sigmoid2Dx(final double value) {
final double ex = exp(value);
return (4.0 * ex) / ((1 + ex) * (1 + ex));
//final double sig = sigmoid(value);
//return 4.0 * (sig * (1.0 - sig));
}
/**
* Computes the sigmoid function with range [-1, 1].
* <br></br>
* @param value Argument of the function.
* @return The function result.
*/
public static double sigmoid1(final double value) {
return (2.0 / (1.0 + exp(-value))) - 1.0;
}
/**
* Computes the derivation of the sigmoid11 function.
* <br></br>
* @param value Argument of the function.
* @return The function result.
*/
public static double sigmoid1Dx(final double value) {
final double ex = exp(value);
return (2.0 * ex) / ((1 + ex) * (1 + ex));
}
/**
* Computes the tangens hyperbolicus.
* <br></br>
* @param value Argument of the function.
* @return The function result.
*/
public static double tanh(final double value) {
//
//final double exp = exp(2.0 * value);
//return 1.0 - (2.0 / (exp + 1.0));
/*
return -1.0 + (2.0 / (
1 + exp(-2.0 * value)
));
*/
//
return Math.tanh(value);
}
/**
* Computes the derivation of the tangens hyperbolicus.
* <br></br>
* @param value Argument of the function.
* @return The function result.
*/
public static double tanhDx(final double value) {
final double tanh = tanh(value);
return 1.0 - (tanh * tanh);
}
// ------------------------------------------------------------------------
// Functions for cell ranges.
// ------------------------------------------------------------------------
/**
* Applies the identification function (copy) on a given memory block.
* <br></br>
* @param data Refers the source array containing the function arguments.
* @param dataoffset Gives the lower bound for the argument values.
* @param result Refers the destination array where the function results will be stored in.
* @param resultoffset Give the lower bound for the result values.
* @param size Gives the number of arguments.
*/
public static void id(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
final double value = data[o1++];
result[o2++] = value;
}
}
/**
* Applies the inversion function (1/x) on a given memory block.
* <br></br>
* @param data Refers the source array containing the function arguments.
* @param dataoffset Gives the lower bound for the argument values.
* @param result Refers the destination array where the function results will be stored in.
* @param resultoffset Give the lower bound for the result values.
* @param size Gives the number of arguments.
*/
public static void invert(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
final double value = data[o1++];
result[o2++] = (value == 0.0)?(0.0):(1.0 / value);
}
}
/**
* Assigns constant 1.0 to a given memory block.
* <br></br>
* @param data Is not relevant here.
* @param dataoffset Is not relevant here.
* @param result Refers the destination array where the function results will be stored in.
* @param resultoffset Give the lower bound for the result values.
* @param size Gives the number of arguments.
*/
public static void constOne(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o2++] = 1.0;
}
}
/**
* Applies the standard sigmoid function on a given memory block.
* <br></br>
* @param data Refers the source array containing the function arguments.
* @param dataoffset Gives the lower bound for the argument values.
* @param result Refers the destination array where the function results will be stored in.
* @param resultoffset Give the lower bound for the result values.
* @param size Gives the number of arguments.
*/
public static void sigmoid(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
final double sig = sigmoid(data[o1++]);
result[o2++] = sig;
}
}
/**
* Applies the derivation of the standard sigmoid function on a given memory block.
* <br></br>
* @param data Refers the source array containing the function arguments.
* @param dataoffset Gives the lower bound for the argument values.
* @param result Refers the destination array where the function results will be stored in.
* @param resultoffset Give the lower bound for the result values.
* @param size Gives the number of arguments.
*/
public static void sigmoidDx(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o2++] = sigmoidDx(data[o1++]);
}
}
/**
* Applies the sigmoid function with result range of [-2,2] on a given memory block.
* <br></br>
* @param data Refers the source array containing the function arguments.
* @param dataoffset Gives the lower bound for the argument values.
* @param result Refers the destination array where the function results will be stored in.
* @param resultoffset Give the lower bound for the result values.
* @param size Gives the number of arguments.
*/
public static void sigmoid2(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
final double sig = sigmoid2(data[o1++]);
result[o2++] = sig;
}
}
/**
* Applies the derivation of the standard sigmoid function of range [-2, 2] on a
* given memory block.
* <br></br>
* @param data Refers the source array containing the function arguments.
* @param dataoffset Gives the lower bound for the argument values.
* @param result Refers the destination array where the function results will be stored in.
* @param resultoffset Give the lower bound for the result values.
* @param size Gives the number of arguments.
*/
public static void sigmoid2Dx(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o2++] = sigmoid2Dx(data[o1++]);
}
}
/**
* Applies the sigmoid function with result range of [-1, 1] on a given memory block.
* <br></br>
* @param data Refers the source array containing the function arguments.
* @param dataoffset Gives the lower bound for the argument values.
* @param result Refers the destination array where the function results will be stored in.
* @param resultoffset Give the lower bound for the result values.
* @param size Gives the number of arguments.
*/
public static void sigmoid1(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
final double sig = sigmoid1(data[o1++]);
result[o2++] = sig;
}
}
/**
* Applies the derivation of the standard sigmoid function of range [-1, 1] on a
* given memory block.
* <br></br>
* @param data Refers the source array containing the function arguments.
* @param dataoffset Gives the lower bound for the argument values.
* @param result Refers the destination array where the function results will be stored in.
* @param resultoffset Give the lower bound for the result values.
* @param size Gives the number of arguments.
*/
public static void sigmoid1Dx(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o2++] = sigmoid1Dx(data[o1++]);
}
}
/**
* Applies the tanh function on a given memory block.
* <br></br>
* @param data Refers the source array containing the function arguments.
* @param dataoffset Gives the lower bound for the argument values.
* @param result Refers the destination array where the function results will be stored in.
* @param resultoffset Give the lower bound for the result values.
* @param size Gives the number of arguments.
*/
public static void tanh(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o2++] = tanh(data[o1++]);
}
}
/**
* Applies the derivation of tanh function on a given memory block.
* <br></br>
* @param data Refers the source array containing the function arguments.
* @param dataoffset Gives the lower bound for the argument values.
* @param result Refers the destination array where the function results will be stored in.
* @param resultoffset Give the lower bound for the result values.
* @param size Gives the number of arguments.
*/
public static void tanhDx(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size
) {
int o1 = dataoffset;
int o2 = resultoffset;
//
for (int i = 0; i < size; i++) {
result[o2++] = tanhDx(data[o1++]);
}
}
// ------------------------------------------------------------------------
/**
* Applies the function given by an index on a given memory block. The methods uses
* a switch block to map to the specific activation function.
* <br></br>
* @param data Refers the source array containing the function arguments.
* @param dataoffset Gives the lower bound for the argument values.
* @param result Refers the destination array where the function results will be stored in.
* @param resultoffset Give the lower bound for the result values.
* @param size Gives the number of arguments.
* @param function Determines the specific activation function.
*/
public static void perform(
final double[] data,
final int dataoffset,
final double[] result,
final int resultoffset,
final int size,
final int function
) {
//
// Note: Is has been tested, that in Java a "short" switch block is MUCH!
// faster than any other decision mechanism such as polymorphic
// approaches like the strategy pattern.
//
switch (function) {
case CellFunction.ID:
id(
data, dataoffset, result, resultoffset, size
);
break;
case CellFunction.CONST_ONE:
constOne(
data, dataoffset, result, resultoffset, size
);
break;
case CellFunction.SIGMOID:
sigmoid(
data, dataoffset, result, resultoffset, size
);
break;
case CellFunction.SIGMOIDDX:
sigmoidDx(
data, dataoffset, result, resultoffset, size
);
break;
case CellFunction.SIGMOID1:
sigmoid1(
data, dataoffset, result, resultoffset, size
);
break;
case CellFunction.SIGMOID1DX:
sigmoid1Dx(
data, dataoffset, result, resultoffset, size
);
break;
case CellFunction.SIGMOID2:
sigmoid2(
data, dataoffset, result, resultoffset, size
);
break;
case CellFunction.SIGMOID2DX:
sigmoid2Dx(
data, dataoffset, result, resultoffset, size
);
break;
case CellFunction.TANH:
tanh(
data, dataoffset, result, resultoffset, size
);
break;
case CellFunction.TANHDX:
tanhDx(
data, dataoffset, result, resultoffset, size
);
break;
case CellFunction.INVERT:
invert(
data, dataoffset, result, resultoffset, size
);
break;
default:
//
// none.
//
break;
}
}
}
| 19,101 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
OfflineRecurrentNetBase.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/OfflineRecurrentNetBase.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
/**
* This is a implementation for offline computing RNNs. Here the computing
* It computes all times steps per layer.
* <br></br>
* @author Sebastian Otte
*/
public final class OfflineRecurrentNetBase extends RecurrentNetBase {
private static final long serialVersionUID = 3076455342302573784L;
/**
* Creates an instance of this class by a given NetStructure and
* NetData instance. The given NetStructure should fulfill the
* requirements of an offline computing RNN, otherwise the correct
* behavior of the network could not be assured and is assumed as
* undefined.
* <br></br>
* @param structure The given net structure containing the topology
* and functional specification.
* @param data Instance of NetData containing data buffer and weights
* and must fit the NetStructure.
*/
public OfflineRecurrentNetBase(NetStructure structure, NetData data) {
super(structure, data);
}
/**
* {@inheritDoc}
*/
@Override
final public void compute() {
//
// reset time.
//
final int last = this.frameidx;
this.setFrameIdx(0);
//
for (int t = 0; t <= last; t++) {
//
if (t > 0) {
this.copyOutput(this.frameidx - 1, this.frameidx);
}
//
// from first to last layer.
//
for (int l = 0; l < this.structure.layers.length; l++) {
this.computeLayerActivations(l);
}
//
if (t < last) this.incrFrameIdx();
}
}
/**
* {@inheritDoc}
*/
@Override
final public void computeGradient() {
//
final int last = this.frameidx;
//
for (int t = last; t >= 0; t--) {
//
if (t < last) {
this.copyGradOutput(this.frameidx + 1, this.frameidx);
}
//
// from last to first layer.
//
for (int l = this.structure.layers.length - 1; l >= 0; l--) {
this.computeLayerGradients(l);
}
//
if (t > 0) this.decrFrameIdx();
}
//
this.setFrameIdx(last);
}
}
| 3,213 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
LayerTag.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/LayerTag.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
/**
* This small class just contains some constants
* defining the computational behavior of layer.
* Whether it is regular (computing input sequences
* in forward direction) or (reverted computing
* input sequences in backward direction). Constants
* are chosen to allow adding other computational
* behaviors later (e.g for multidimensional ANNs).
* <br></br>
* @author Sebastian Otte
*/
public final class LayerTag {
/**
* A layer defined as regular computes input sequences in
* forward direction.
*/
public static final int REGULAR = 0x1;
/**
* A layer defined as reverted computes input sequences in
* backward direction.
*/
public static final int REVERSED = 0x2;
/**
* Makes a string representation of a given id.
* This method is mainly for debugging.
* <br></br>
* @param tag A layer tag id.
* @return String representation.
*/
public final static String asString(final int tag) {
if (tag == REGULAR) return "REGULAR";
if (tag == REVERSED) return "REVERTED";
//
return "UNKNOWN";
}
}
| 2,051 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
NetData.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/NetData.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
import java.io.Serializable;
import de.jannlab.misc.ObjectCopy;
/**
* An instance of this class contains the entire data of an ANN. This are on one hand
* the data buffers for forward and backward computation (input, ouput, gradinput,
* gradoutput) for each time step (the timesteps are defined by the frame width).
* @author Sebastian Otte
*/
public final class NetData implements Serializable {
private static final long serialVersionUID = 9138637243730569419L;
/**
* provides the input buffer. the results of the forward
* integrations are stored here.
*/
public double[][] input;
/**
* provides the output buffer. the results of the forward
* activations and also the network input are stored here.
*/
public double[][] output;
/**
* provides the grad. input buffer. the results of the backward
* integrations and also the network error are stored here.
*/
public double[][] gradinput;
/**
* provides the grad. output buffer. the results of the activation
* deviations and also the "back-flowing" error are stored here.
*/
public double[][] gradoutput;
/**
* determines the frame width, which is the first dimension of the
* data buffers. MLPs or trained RNNs only need a frame width of 1.
* Online offline computing RNNs or online computing RNNs during
* training need a frame width > 1.
*/
public int framewidth;
/**
* provides the vector of weigts. note that the first value of the vector
* is generally 1.0. this is founded in some runtime peformance improvements
* concerning non weighted links.
*/
public double[] weights;
/**
* Gives the number of weights exclusive the constant 1.0 weight.
*/
public int weightsnum;
/**
* Stores the indices to the cells used for constant value assignments.
*/
public int[] asgns;
/**
* Stores the constant values assignments corresponding to the indices
* given in asgns.
*/
public double[] asgnsv;
/**
* This method returns a shared copy of the current data record. This means
* that the entire data buffer is "really" duplicated while the weights and
* the assignments are shared. A shared copy can be used for independent
* computations on the same weights vector, which is an important requirement
* for computing/training the same problem in parallel with multiple Net instances.
* <br></br>
* @return Copy of this data record with shared weights and assigments.
*/
public NetData sharedCopy() {
NetData copy = new NetData();
//
// copy.
//
copy.input = ObjectCopy.copy(this.input);
copy.output = ObjectCopy.copy(this.output);
copy.gradinput = ObjectCopy.copy(this.gradinput);
copy.gradoutput = ObjectCopy.copy(this.gradoutput);
copy.framewidth = this.framewidth;
//
// share.
//
copy.weights = this.weights;
copy.weightsnum = this.weightsnum;
copy.asgns = this.asgns;
copy.asgnsv = this.asgnsv;
//
return copy;
}
/**
* Makes a complete "real" copy of the current data record including the weight vectors.
* No data is shared between the copy and original instance.
* @return A copy of this data record.
*/
public NetData copy() {
return ObjectCopy.copy(this);
}
}
| 4,447 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
CellType.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/CellType.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
import java.io.Serializable;
/**
* This class lists all standard cell types. Also individual cell types
* can be instantiated using the constructor.For each cell type
* several informations are given. On one hand these are functional
* specifications of the cell such as activation or integration function
* for both forward and backward pass. On the other hand these are
* some more meta informations, which are mainly used for debugging.
* <br></br>
* @author Sebastian Otte
*/
public final class CellType implements Serializable {
private static final long serialVersionUID = -807350423371938387L;
//
/**
* A simple value cell with no functional specification.
*/
public static final CellType VALUE = new CellType(
CellIntegration.NONE,
CellFunction.NONE,
CellIntegration.NONE,
CellFunction.NONE,
"value",
true,
true
);
/**
* A standard sigmoid with sum for integration. The enumeration instance
* represents on of the standard non-linear perceptrons.
*/
public static final CellType SIGMOID = new CellType(
CellIntegration.SUM,
CellFunction.SIGMOID,
CellIntegration.SUM,
CellFunction.SIGMOIDDX,
"sigmoid",
true,
false
);
/**
* A cell with sigmoid activation of range [-2, 2] and sum integration.
*/
public static final CellType SIGMOID2 = new CellType(
CellIntegration.SUM,
CellFunction.SIGMOID2,
CellIntegration.SUM,
CellFunction.SIGMOID2DX,
"sigmoid[-2,2]",
true,
false
);
/**
* A cell with sigmoid activation of range [-1, 1] and sum integration.
*/
public static final CellType SIGMOID1 = new CellType(
CellIntegration.SUM,
CellFunction.SIGMOID1,
CellIntegration.SUM,
CellFunction.SIGMOID1DX,
"sigmoid[-1,1]",
true,
false
);
/**
* A tanh cell with sum for integration. The enumeration instance
* represents on of the standard non-linear perceptrons.
*/
public static final CellType TANH = new CellType(
CellIntegration.SUM,
CellFunction.TANH,
CellIntegration.SUM,
CellFunction.TANHDX,
"tanh",
true,
false
);
/**
* A linear cell with id for activation and sum for integration.
* In this cell the error will just been passed though.
*/
public static final CellType LINEAR = new CellType(
CellIntegration.SUM,
CellFunction.ID,
CellIntegration.SUM,
CellFunction.CONST_ONE,
"linear",
true,
true
);
/**
* The multiplicative cell has an id activation and a product integration.
* The error in this cell will be just multiplied with the previous input.
* This is why this cell type regularly needs to be combined with DMULTIPLICATIVE
* cell to gain a correct gradient based error flow.
*/
public static final CellType MULTIPLICATIVE = new CellType(
CellIntegration.MULT,
CellFunction.ID,
CellIntegration.SUM,
CellFunction.ID,
"multiplicative",
false,
false
);
/**
* The dmultiplicative cells (delta correction) just pass the input of their the last
* incoming connection. In backward pass the divide the error by previous input (NaN are
* avoided). Regularly this cells is placed before each incoming connection to a
* multiplicative cell to gain a correct gradient based error flow.
*/
public static final CellType DMULTIPLICATIVE = new CellType(
CellIntegration.LASTID,
CellFunction.ID,
CellIntegration.LASTID,
CellFunction.INVERT,
"multiplicative delta correction",
false,
false
);
//
//-------------------------------------------------------------------------
/**
* Gives the id of the used integration function in the forward pass.
* @see CellIntegration
*/
public final int integration;
/**
* Gives the id of the used activation function in the forward pass.
*/
public final int activation;
/**
* Gives the id of the used integration function in the backward pass.
*/
public final int revintegration;
/**
* Gives the id of the used "activation" correctly the devidation of the activation
* function in the backward pass.
*/
public final int revactivation;
/**
* Is the cell a perceptron?
*/
public final boolean perceptron;
/**
* Is the cell linear?
*/
public final boolean linear;
/**
* Gives the name of the cell.
*/
public final String name;
//-------------------------------------------------------------------------
/**
* Creates an individual instance of CellType.
*/
public CellType(
final int integration,
final int activation,
final int revintegration,
final int revactivation,
final String name,
final boolean perceptron,
final boolean linear
) {
this.integration = integration;
this.activation = activation;
this.revintegration = revintegration;
this.revactivation = revactivation;
this.name = name;
this.perceptron = perceptron;
this.linear = linear;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return this.name;
}
}
| 6,606 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
CellIntegration.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/CellIntegration.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
/**
* This class contains static methods for computing serveral
* integrations function. An integration function "integrates"
* data from a source array into a destination array in a
* specific way. Which value are integrated and where the results
* are stored is determined by a sequence of links. Thereby, each
* source value is multiplied with the weight of the link (an
* non-weighted link has weight 1.0). The overhead of multiplying
* 1.0 on non-weighted links is much faster than an "if"-check for
* each weight.
* <br></br>
* @see Link
* @author Sebastian Otte
*
*/
public final class CellIntegration {
//
/** None integration function. */
public static final int NONE = 0;
/** Ordinary sum over all values. */
public static final int SUM = 1;
/** Product over all values. */
public static final int MULT = 2;
/** Copy last source value for dest. */
public static final int LASTID = 3;
//
/**
* This method computes the weighted sum for the given arguments.
* <br></br>
* @param src Refers the source data array.
* @param dst Refers the destination data array.
* @param cellsoff Refers the lower bound of the destination range.
* @param cellsnum Refers the size of the destination range.
* @param weights Refers the weights vector.
* @param links Refers the links vector.
* @param linksoff Gives the offset of the first link according
* the this current context.
* @param linksnum Gives the number of links according to the current context.
*/
public static void sum(
final double[] src,
final double[] dst,
final int cellsoff,
final int cellsnum,
final double[] weights,
final int[] links,
final int linksoff,
final int linksnum
) {
if (linksnum == 0) return;
//
int link = linksoff;
//
// clean cell inputs.
//
int end = (cellsoff + cellsnum);
for (int i = cellsoff; i < end; i++) {
dst[i] = 0.0;
}
//
// compute weighted sum over all links.
//
for (int i = 0; i < linksnum; i++) {
//
final int ci = links[link + Link.IDX_SRC];
final int cj = links[link + Link.IDX_DST];
final int ij = links[link + Link.IDX_WEIGHT];
///
final double xi = src[ci];
final double wij = weights[ij];
//
dst[cj] += (xi * wij);
//
// next link.
//
link += Link.LINK_SIZE;
}
}
/**
* This method copies the value of the last source cell of all predecessor cells for
* each destination cell. This method does not respect weights.
* <br></br>
* @param src Refers the source data array.
* @param dst Refers the destination data array.
* @param cellsoff Refers the lower bound of the destination range.
* @param cellsnum Refers the size of the destination range.
* @param weights Refers the weights vector.
* @param links Refers the links vector.
* @param linksoff Gives the offset of the first link according
* the this current context.
* @param linksnum Gives the number of links according to the current context.
*/
public static void lastID(
final double[] src,
final double[] dst,
final int cellsoff,
final int cellsnum,
final double[] weights,
final int[] links,
final int linksoff,
final int linksnum
) {
if (linksnum == 0) return;
//
int link = linksoff;
//
// compute weighted sum over all links.
//
for (int i = 0; i < linksnum; i++) {
//
final int ci = links[link + Link.IDX_SRC];
final int cj = links[link + Link.IDX_DST];
///
final double xi = src[ci];
//
dst[cj] = xi;
//
// next link.
//
link += Link.LINK_SIZE;
}
}
/**
* This method computes product for the given arguments.
* <br></br>
* @param src Refers the source data array.
* @param dst Refers the destination data array.
* @param cellsoff Refers the lower bound of the destination range.
* @param cellsnum Refers the size of the destination range.
* @param weights Refers the weights vector.
* @param links Refers the links vector.
* @param linksoff Gives the offset of the first link according
* the this current context.
* @param linksnum Gives the number of links according to the current context.
*/
public static void mult(
final double[] src,
final double[] dst,
final int cellsoff,
final int cellsnum,
final double[] weights,
final int[] links,
final int linksoff,
final int linksnum
) {
if (linksnum == 0) return;
//
int link = linksoff;
//
// clean cell inputs.
//
int end = (cellsoff + cellsnum);
for (int i = cellsoff; i < end; i++) {
dst[i] = 1.0;
}
//
// compute weighted sum over all links.
//
for (int i = 0; i < linksnum; i++) {
//
final int ci = links[link + Link.IDX_SRC];
final int cj = links[link + Link.IDX_DST];
final int ij = links[link + Link.IDX_WEIGHT];
//
final double xi = src[ci];
final double wij = weights[ij];
//
/*
// # DEBUG #
if (wij != 1.0) {
System.out.println("ARG!");
System.exit(1);
}
// #
*/
dst[cj] *= (xi * wij);
//
// next link.
//
link += Link.LINK_SIZE;
}
}
/**
* This methods applies the a integration given by an index for the given arguments.
* The methods uses a switch block to map to the specific integration function.
* <br></br>
* @param src Refers the source data array.
* @param dst Refers the destination data array.
* @param cellsoff Refers the lower bound of the destination range.
* @param cellsnum Refers the size of the destination range.
* @param weights Refers the weights vector.
* @param links Refers the links vector.
* @param linksoff Gives the offset of the first link according
* the this current context.
* @param linksnum Gives the number of links according to the current context.
* @param integration Determines the specific integration function.
*/
public static void perform(
final double[] src,
final double[] dst,
final int cellsoff,
final int cellsnum,
final double[] weights,
final int[] links,
final int linksoff,
final int linksnum,
final int integration
) {
//
// Note: Is has been tested, that in Java a "short" switch block is much
// faster than any other decision mechanism such as polymorphic
// approaches like the strategy pattern.
//
switch (integration) {
case CellIntegration.SUM:
sum(
src, dst, cellsoff, cellsnum,
weights, links, linksoff, linksnum
);
break;
//
case CellIntegration.MULT:
mult(
src, dst, cellsoff, cellsnum,
weights, links, linksoff, linksnum
);
break;
//
case CellIntegration.LASTID:
lastID(
src, dst, cellsoff, cellsnum,
weights, links, linksoff, linksnum
);
break;
//
default:
//
// none.
//
break;
}
}
}
| 9,277 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
FeedForwardNetBase.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/FeedForwardNetBase.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
/**
* This class is to implement feed-forwards networks. It simplifies the
* activation/derivation computation compared to recurrent networks. If
* all cells (exclusive the input layer) are non linear perceptrons and there
* is an hidden layer an instance of this class is a multilayer perceptron.
* <br></br>
* @author Sebastian Otte
*/
public final class FeedForwardNetBase extends NetBase {
private static final long serialVersionUID = 3076455342302573784L;
/**
* Creates an instance of this class by a given NetStructure and
* NetData instance. The given NetStructure should fulfill the
* requirements of an feed forward network, otherwise the correct
* behavior of the network could not be assured and is assumed as
* undefined.
* <br></br>
* @param structure The given net structure containing the topology
* and functional specification.
* @param data Instance of NetData containing data buffer and weights
* and must fit the NetStructure.
*/
public FeedForwardNetBase(final NetStructure structure, final NetData data) {
super(structure, data);
}
/**
* {@inheritDoc}
*/
@Override
final public void compute() {
//
// from first to last layer.
//
for (int l = 0; l < this.structure.layers.length; l++) {
this.computeLayerActivations(l);
}
//
}
/**
* {@inheritDoc}
*/
@Override
final public void computeGradient() {
//
// from last to first layer.
//
for (int l = this.structure.layers.length - 1; l >= 0; l--) {
this.computeLayerGradients(l);
}
}
}
| 2,638 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
Layer.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/Layer.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
import java.io.Serializable;
import de.jannlab.misc.IntTools;
/**
* An instance of this class defines a Layer in ANN. It contains some information
* on the CellArray corresponding to this layer and some other computational
* specification (e.g. the computational dependencies of the containing CellArrays).
* <br></br>
* @author Sebastian Otte
*/
public final class Layer implements Serializable{
private static final long serialVersionUID = 52359162370719687L;
public static final int NO_LAYER = -1;
//-------------------------------------------------------------------------
/**
* Gives the lower bound of the cells contained by this layer.
*/
public int cellslbd = 0;
/**
* Gives the upper bound of the cells contained by this layer.
*/
public int cellsubd = -1;
/**
* Gives the number of the cells contained by this layer.
*/
public int cellsnum = 0;
/**
* Gives the lower bound of the arrays contained by this layer.
*/
public int arrayslbd = 0;
/**
* Gives the upper bound of the arrays contained by this layer.
*/
public int arraysubd = -1;
/**
* Gives the number of the arrays contained by this layer.
*/
public int arraysnum = 0;
/**
* Gives the lower bounds of the packages of computational independent
* arrays. Arrays with the same computation index are computed at the same
* time.
*/
public int[] complbds = null;
/**
* Gives the uppder bounds of the packages of computational independent
* arrays. Arrays with the same computation index are computed at the same
* time.
*/
public int[] compubds = null;
/**
* Gives the number of the packages of computational independent
* arrays.
*/
public int compwidth = 0;
/**
* Gives the degree of incoming connections to all cells contained by all
* array in this layer.
*/
public int indeg = 0;
/**
* Gives the degree of outgoing connections of all cells contained by all
* array in this layer.
*/
public int outdeg = 0;
/**
* Gives the tag of the layer, which contains information of its
* computational behavior.
*/
public int tag = LayerTag.REGULAR;
//-------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder w = new StringBuilder();
//
w.append("cellslbd : " + this.cellslbd + "\n");
w.append("cellsubd : " + this.cellsubd + "\n");
w.append("cellsnum : " + this.cellsnum + "\n");
w.append("arrayslbd : " + this.arrayslbd + "\n");
w.append("arraysubd : " + this.arraysubd + "\n");
w.append("arraysnum : " + this.arraysnum + "\n");
w.append("compwidth : " + this.compwidth + "\n");
w.append("complbds : " + "(" + IntTools.asString(this.complbds) + ")\n");
w.append("compubds : " + "(" + IntTools.asString(this.compubds) + ")\n");
w.append("indeg : " + this.indeg + "\n");
w.append("outdeg : " + this.outdeg + "\n");
w.append("tag : " + LayerTag.asString(this.tag) + "\n");
//
return w.toString();
}
}
| 4,253 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
BidirectionalNetBase.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/BidirectionalNetBase.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
/**
* This class is a specific implementation for bidirectional networks.
* It computes all times steps per layer and inverts the computing direction
* for REVERSED layer.
* <br></br>
* @author Sebastian Otte
*/
public final class BidirectionalNetBase extends RecurrentNetBase {
private static final long serialVersionUID = 3076455342302573784L;
/**
* Creates an instance of this class by a given NetStructure and
* NetData instance. The given NetStructure should fulfill the
* requirements of an bidirectional (offline) RNN, otherwise the correct
* behavior of the network could not be assured and is assumed as
* undefined.
* <br></br>
* @param structure The given net structure containing the topology
* and functional specification.
* @param data Instance of NetData containing data buffer and weights
* and must fit the NetStructure.
*/
public BidirectionalNetBase(NetStructure structure, NetData data) {
super(structure, data);
}
/**
* {@inheritDoc}
*/
@Override
final public void compute() {
//
// reset time.
//
final int last = this.frameidx;
//
// from first to last layer.
//
for (int l = 0; l < this.structure.layers.length; l++) {
//
if (l == this.structure.inputlayer) continue;
final Layer layer = this.structure.layers[l];
//
// regular or reversed layer?
//
if (layer.tag == LayerTag.REGULAR) {
this.setFrameIdx(0);
for (int t = 0; t <= last; t++) {
//
if (t > 0) {
this.copyOutput(this.frameidx - 1, this.frameidx, l);
}
this.computeLayerActivations(l);
//
this.incrFrameIdx();
}
} else {
this.setFrameIdx(last);
for (int t = last; t >= 0; t--) {
//
if (t < last) {
this.copyOutput(this.frameidx + 1, this.frameidx, l);
}
this.computeLayerActivations(l);
//
this.decrFrameIdx();
}
}
}//
this.setFrameIdx(last);
}
/**
* {@inheritDoc}
*/
@Override
final public void computeGradient() {
//
final int last = this.frameidx;
//
// from last to first layer.
//
for (int l = this.structure.layers.length - 1; l >= 0; l--) {
//
if (l == this.structure.inputlayer) continue;
final Layer layer = this.structure.layers[l];
//
// regular or reversed layer?
//
if (layer.tag == LayerTag.REGULAR) {
this.setFrameIdx(last);
for (int t = last; t >= 0; t--) {
//
if (t < last) {
this.copyGradOutput(
this.frameidx + 1, this.frameidx, l
);
}
this.computeLayerGradients(l);
//
this.decrFrameIdx();
}
} else {
this.setFrameIdx(0);
for (int t = 0; t <= last; t++) {
//
if (t > 0) {
this.copyGradOutput(
this.frameidx - 1, this.frameidx, l
);
}
this.computeLayerGradients(l);
//
this.incrFrameIdx();
}
}
}
//
this.setFrameIdx(last);
}
} | 4,893 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
Link.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/Link.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
/**
* This class provides constants and static methods for handling links and arrays
* of links. A link consists of a 3-tuple (i,j,k) where i gives a source index,
* j gives a destination index and k gives a weight index.
* <br></br>
* All links of a ANN are contained by a large 1-dimensional int-array. This is to
* improve the runtime performance by supporting the system's caching mechanisms:
* A multidimensional array could be theoretically distributed over the whole memory.
* Having all links in one int-array aligned corresponding to the computation order
* of the network highly allows the benefit from caching (memory burst). For this
* it is recommend to enable JIT of the JVM.
* <br></br>
* The code of the two merge sort implementations is largely redundant.
* But a particular implementation for links with a static compare function improves
* the runtime performance in comparison with
* the native sorting methods which needs a comparator object.
* <br></br>
* @author Sebastian Otte
*/
public final class Link {
/**
* Gives the index of the soruce part in a link triple.
*/
public static final int IDX_SRC = 0; // index of source index.
/**
* Gives the index of the destination part in a link triple.
*/
public static final int IDX_DST = 1; // index of destination index.
/**
* Gives the index of the weight part in a link triple.
*/
public static final int IDX_WEIGHT = 2; // index of weight index.
/**
* Just gives the number of part of a link triple (which is 3).
*/
public static final int LINK_SIZE = 3; // size of a link tuple.
/**
* This constant means (a < b) in a comparison of a and b.
*/
private static final int SMALLER = -1; // comparison constant: a < b
/**
* This constant means (a == b) in a comparison of a and b.
*/
private static final int EQUAL = 0; // comparison constant: a == b
/**
* This constant means (a > b) in a comparison of a and b.
*/
private static final int BIGGER = 1; // comparison constant: a > b
/**
* The constant defines to sort in ascending order.
*/
public static final int ORDER_ASC = BIGGER; // sort in ascending order.
/**
* The constant defines to sort in descending order.
*/
public static final int ORDER_DESC = SMALLER; // sort in descending order.
/**
* The constant it used, when a links a no weight. In generated network this
* will be replaced by an index to a constant-one-weight.
*/
public static final int NOWEIGHT = -1; // tag for non weighted link.
//
//-------------------------------------------------------------------------
/**
* Creates a non weighted link from src to dst as int[3].
* In a non weighted link the weight index is set to NOWEIGHT.
* @param src Source index.
* @param dst Destination index.
* @return Non weighted link.
*/
public static int[] link(final int src, final int dst) {
return link(src, dst, NOWEIGHT);
}
/**
* Creates a weighted link from src to dst with weight widx as int[3].
* @param src Source index.
* @param dst Destination index.
* @param widx Weight index.
* @return Weighted link.
*/
public static int[] link(final int src, final int dst, final int widx) {
return new int[]{ src, dst, widx };
}
/**
* Allocates a memory block for n links.
* @param links Number of links.
* @return Allocated memory block.
*/
public static int[] alloc(final int links) {
return new int[links * LINK_SIZE];
}
/**
* Returns the source index of a link.
* @param buffer Array of links.
* @param offset Link offset.
* @return Source index.
*/
public static int src(final int[] buffer, final int offset) {
return buffer[offset + IDX_SRC];
}
/**
* Returns the destination index of a link.
* @param buffer Array of links.
* @param offset Link offset.
* @return Destination index.
*/
public static int dst(final int[] buffer, final int offset) {
return buffer[offset + IDX_DST];
}
/**
* Returns the weight index of a link.
* @param buffer Array of links.
* @param offset Link offset.
* @return Weight index.
*/
public static int weight(final int[] buffer, final int offset) {
return buffer[offset + IDX_WEIGHT];
}
//-------------------------------------------------------------------------
/**
* Swaps two given links.
* @param buffer Array of links.
* @param first The first link.
* @param second The second link.
*/
public static void swap(final int[] buffer, final int first, final int second) {
//
final int tmp1 = buffer[first];
buffer[first] = buffer[second];
buffer[second] = tmp1;
//
final int tmp2 = buffer[first + 1];
buffer[first + 1] = buffer[second + 1];
buffer[second + 1] = tmp2;
//
final int tmp3 = buffer[first + 2];
buffer[first + 2] = buffer[second + 2];
buffer[second + 2] = tmp3;
}
/**
* Compares two links in dst-major order.
* @param buffer Array of links.
* @param first The first link.
* @param second The second link.
* @return SMALLER, BIGGER or EQUAL.
*/
public static int cmpDstMaj(final int[] buffer, final int first, final int second) {
//
if (buffer[first + IDX_DST] < buffer[second + IDX_DST]) return SMALLER;
if (buffer[first + IDX_DST] > buffer[second + IDX_DST]) return BIGGER;
if (buffer[first + IDX_SRC] < buffer[second + IDX_SRC]) return SMALLER;
if (buffer[first + IDX_SRC] > buffer[second + IDX_SRC]) return BIGGER;
//
return EQUAL;
}
/**
* Compares two links in src-major order.
* @param buffer Array of links.
* @param first The first link.
* @param second The second link.
* @return SMALLER, BIGGER or EQUAL.
*/
public static int cmpSrcMaj(final int[] buffer, final int first, final int second) {
//
if (buffer[first + IDX_SRC] < buffer[second + IDX_SRC]) return SMALLER;
if (buffer[first + IDX_SRC] > buffer[second + IDX_SRC]) return BIGGER;
if (buffer[first + IDX_DST] < buffer[second + IDX_DST]) return SMALLER;
if (buffer[first + IDX_DST] > buffer[second + IDX_DST]) return BIGGER;
//
return EQUAL;
}
/**
* Compares two links to equality.
* @param buffer Array of links.
* @param first The first link.
* @param second The second link.
* @return true or false.
*/
public static boolean equal(final int[] buffer, final int first, final int second) {
return (
(buffer[first + IDX_SRC] == buffer[second + IDX_SRC]) &&
(buffer[first + IDX_DST] == buffer[second + IDX_DST])
);
}
/**
* Adaption of fast merge sort algorithm from
* http://www.java2s.com/Code/Java/Collections-Data-Structure/FastMergeSort.htm
* which uses insertion sort for smaller arrays. Sorting in dst-major order.
* <br></br>
* @param src Unsorted data as int[].
* @param dst Result data as int[].
* @param low Lower bound of data frame.
* @param high Exclusive upper bound of data frame.
* @param order ORDER_ASC or ORDER_DESC for ascending respectively descending order.
*/
public static void sortDstMaj(
final int[] src, final int[] dst, final int low, final int high, final int order
) {
final int threshold = LINK_SIZE * 20;
final int length = high - low;
//
// use insertion sort on smallest arrays < 7 elements (LINK_SIZE * 7).
//
if (length < threshold) {
for (int i = low; i < high; i += LINK_SIZE) {
//
// cmp > 0 ~ cmp > EQUAL ~ cmp == order.
//
for (
int j = i;
(j > low) && (cmpDstMaj(dst, j - LINK_SIZE, j) == order);
j -= LINK_SIZE
) {
swap(dst, j - LINK_SIZE, j);
}
}
return;
}
//
// calculate mid idx.
// OPZIMIZED: final int mid = (((low + high) / LINK_SIZE) >> 1) * LINK_SIZE;
//
final int rng = (low + high) >> 1;
final int mid = rng - (rng % LINK_SIZE);
//
// recursively sort halves of dest into src.
//
sortDstMaj(dst, src, low, mid, order);
sortDstMaj(dst, src, mid, high, order);
//
// is list already sorted? cmp <= 0 ~ cmp <= EQUAL ~ cmp != order.
//
if (cmpDstMaj(src, mid - LINK_SIZE, mid) != order) {
System.arraycopy(src, low, dst, low, length);
return;
}
//
// merge sorted halves from src into dest.
// OPZIMIZED: for (int i = low, p = low, q = mid; i < high; i += LINK_SIZE) {
//
for (int i = low, p = low, q = mid; i < high;) {
//
// cmp <= 0 ~ cmp <= EQUAL ~ cmp != order.
//
if ((q >= high) || ((p < mid) && (cmpDstMaj(src, p, q) != order))) {
//
// OPZIMIZED:
// copy(src, p, dst, i);
// p += LINK_SIZE;
//
dst[i] = src[p]; p++; i++;
dst[i] = src[p]; p++; i++;
dst[i] = src[p]; p++; i++;
} else {
//
// OPZIMIZED:
// copy(src, q, dst, i);
// q += LINK_SIZE;
//
dst[i] = src[q]; q++; i++;
dst[i] = src[q]; q++; i++;
dst[i] = src[q]; q++; i++;
}
}
}
/**
* Adaption of fast merge sort algorithm from
* http://www.java2s.com/Code/Java/Collections-Data-Structure/FastMergeSort.htm
* which uses insertion sort for smaller arrays. Sorting in src-major order.
* <br></br>
* @param src Unsorted data as int[].
* @param dst Result data as int[].
* @param low Lower bound of data frame.
* @param high Exclusive upper bound of data frame.
* @param order ORDER_ASC or ORDER_DESC for ascending respectively descending order.
*/
public static void sortSrcMaj(
final int[] src, final int[] dst, final int low, final int high, final int order
) {
final int threshold = LINK_SIZE * 20;
final int length = high - low;
//
// use insertion sort on smallest arrays < 7 elements (LINK_SIZE * 7).
//
if (length < threshold) {
for (int i = low; i < high; i += LINK_SIZE) {
//
// cmp > 0 ~ cmp > EQUAL ~ cmp == order.
//
for (
int j = i;
(j > low) && (cmpSrcMaj(dst, j - LINK_SIZE, j) == order);
j -= LINK_SIZE
) {
swap(dst, j - LINK_SIZE, j);
}
}
return;
}
//
// calculate mid idx.
// OPZIMIZED: final int mid = (((low + high) / LINK_SIZE) >> 1) * LINK_SIZE;
//
final int rng = (low + high) >> 1;
final int mid = rng - (rng % LINK_SIZE);
//
// recursively sort halves of dest into src.
//
sortSrcMaj(dst, src, low, mid, order);
sortSrcMaj(dst, src, mid, high, order);
//
// is list already sorted? cmp <= 0 ~ cmp <= EQUAL ~ cmp != order.
//
if (cmpSrcMaj(src, mid - LINK_SIZE, mid) != order) {
System.arraycopy(src, low, dst, low, length);
return;
}
//
// merge sorted halves from src into dest.
// OPZIMIZED: for (int i = low, p = low, q = mid; i < high; i += LINK_SIZE) {
//
for (int i = low, p = low, q = mid; i < high;) {
//
// cmp <= 0 ~ cmp <= EQUAL ~ cmp != order.
//
if ((q >= high) || ((p < mid) && (cmpSrcMaj(src, p, q) != order))) {
//
// OPZIMIZED:
// copy(src, p, dst, i);
// p += LINK_SIZE;
//
dst[i] = src[p]; p++; i++;
dst[i] = src[p]; p++; i++;
dst[i] = src[p]; p++; i++;
} else {
//
// OPZIMIZED:
// copy(src, q, dst, i);
// q += LINK_SIZE;
//
dst[i] = src[q]; q++; i++;
dst[i] = src[q]; q++; i++;
dst[i] = src[q]; q++; i++;
}
}
}
/**
* Copy link from source array to destination array.
* @param src Source array of links.
* @param srcoff Source link offset.
* @param dst Destination array of links.
* @param dstoff Destination link offset.
*/
public static void copy(
final int[] src,
final int srcoff,
final int[] dst,
final int dstoff
) {
dst[dstoff + IDX_SRC] = src[srcoff + IDX_SRC];
dst[dstoff + IDX_DST] = src[srcoff + IDX_DST];
dst[dstoff + IDX_WEIGHT] = src[srcoff + IDX_WEIGHT];
}
/**
* Sorts a given array of links in src-major order.
* @param data Array of links.
* @param order ORDER_ASC or ORDER_DESC for ascending respectively descending order.
*/
public static void sortSrcMaj(
final int[] data, final int order
) {
int[] buffer = data.clone();
sortSrcMaj(buffer, data, 0, data.length, order);
}
/**
* Sorts a given array of links in dst-major order.
* @param data Array of links.
* @param order ORDER_ASC or ORDER_DESC for ascending respectively descending order.
*/
public static void sortDstMaj(
final int[] data, final int order
) {
int[] buffer = data.clone();
sortDstMaj(buffer, data, 0, data.length, order);
}
/**
* Eliminates redundant links in a sorted array of links.
* @param links Array of links.
* @return A "clean" array of links.
*/
public static int[] eliminateRedundantLinks(int[] links) {
//
final int tag = Integer.MIN_VALUE;
//
int last = 0;
int ctr = 0;
//
if (links.length > 0) {
ctr += LINK_SIZE;
}
//
// first make redundant links invalid.
//
for (int i = LINK_SIZE; i < links.length; i += LINK_SIZE) {
if (equal(links, i, last)) {
//
// links equal, eliminate link.
//
links[i] = tag;
} else {
last = i;
ctr += LINK_SIZE;
}
}
//
// collect non-null links
//
int[] result = new int[ctr];
int idx = 0;
for (int i = 0; i < links.length; i += LINK_SIZE) {
if (links[i] != tag) {
copy(links, i, result, idx);
idx += LINK_SIZE;
}
}
return result;
}
/**
* Builds a string for a given range of links. The resulting string is just one
* single text line.
* <br></br>
* @param links The links.
* @param off The offset of the links range.
* @param num The number of links.
* @return String representation of the link range.
*/
public static String asString(final int[] links, final int off, final int num) {
StringBuilder out = new StringBuilder();
int idx = off;
for (int i = 0; i < num; i++) {
if (i > 0) {
out.append(" ");
}
final int src = links[idx + Link.IDX_SRC];
final int dst = links[idx + Link.IDX_DST];
final int widx = links[idx + Link.IDX_WEIGHT];
out.append("(" + src + "," + dst + "," + widx + ")");
idx += LINK_SIZE;
}
return out.toString();
}
/**
* Builds a string for a given range of links. The resulting string contains of
* multiple lines. A line break is set after every numbreak links.
* <br></br>
* @param links The links.
* @param off The offset of the links range.
* @param num The number of links.
* @param numbreak Number of links per text line.
* @return String representation of the link range.
*/
public static String asString(
final int[] links, final int off, final int num, final int numbreak
) {
StringBuilder out = new StringBuilder();
int idx = off;
for (int i = 0; i < num; i++) {
if (i > 0) {
if (i % numbreak == 0) {
out.append("\n");
} else {
out.append(" ");
}
}
final int src = links[idx + Link.IDX_SRC];
final int dst = links[idx + Link.IDX_DST];
final int widx = links[idx + Link.IDX_WEIGHT];
out.append("(" + src + "," + dst + "," + widx + ")");
idx += LINK_SIZE;
}
return out.toString();
}
}
| 18,537 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
OnlineRecurrentNetBase.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/OnlineRecurrentNetBase.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
/**
* This is a implementation for online computing RNNs. Here the computing
* is only for one time step, which is determined from outside.
* <br></br>
* @author Sebastian Otte
*/
public final class OnlineRecurrentNetBase extends RecurrentNetBase {
private static final long serialVersionUID = 3076455342302573784L;
/**
* Creates an instance of this class by a given NetStructure and
* NetData instance. The given NetStructure should fulfill the
* requirements of an online computing RNN, otherwise the correct
* behavior of the network could not be assured and is assumed as
* undefined.
* <br></br>
* @param structure The given net structure containing the topology
* and functional specification.
* @param data Instance of NetData containing data buffer and weights
* and must fit the NetStructure.
*/
public OnlineRecurrentNetBase(NetStructure structure, NetData data) {
super(structure, data);
}
/**
* {@inheritDoc}
*/
@Override
final public void compute() {
//
if (this.frameidx > 0) {
this.copyOutput(this.frameidx - 1, this.frameidx);
}
//
// from first to last layer.
//
for (int l = 0; l < this.structure.layers.length; l++) {
this.computeLayerActivations(l);
}
}
/**
* {@inheritDoc}
*/
@Override
final public void computeGradient() {
//
if (this.frameidx < (this.data.framewidth - 1)) {
this.copyGradOutput(this.frameidx + 1, this.frameidx);
}
//
// from last to first layer.
//
for (int l = this.structure.layers.length - 1; l >= 0; l--) {
this.computeLayerGradients(l);
}
}
}
| 2,746 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
RecurrentNetBase.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/RecurrentNetBase.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
import de.jannlab.misc.DoubleTools;
/**
* This is an abstract inter class for other recurrent network types.
* It contains copy methods to tranfer data between different timesteps.
* <br></br>
* @author Sebastian Otte
*
*/
public abstract class RecurrentNetBase extends NetBase {
private static final long serialVersionUID = 3076455342302573784L;
RecurrentNetBase(NetStructure structure, NetData data) {
super(structure, data);
}
/**
* Copies output values from source time to destination time.
* <br></br>
* @param source Source time index.
* @param dest Destination time index.
*/
protected void copyOutput(final int source, final int dest) {
//
// copy output from previous context buffer.
//
for (CellArray a : this.structure.arrays) {
if (a.celltype != CellType.VALUE) {
DoubleTools.copy(
this.data.output[source], a.cellslbd,
this.data.output[dest], a.cellslbd, a.cellsnum
);
/** /
DoubleTools.copy(
this.data.input[source], a.cellslbd,
this.data.input[dest], a.cellslbd, a.cellsnum
);
/**/
}
}
}
/**
* Copies output values from source time to destination time
* just for one single layer.
* <br></br>
* @param source Source time index.
* @param dest Destination time index.
* @param layer Layer index.
*/
protected void copyOutput(final int source, final int dest, final int layer) {
//
// copy output from previous context buffer.
//
final int albd = this.structure.layers[layer].arrayslbd;
final int aubd = this.structure.layers[layer].arraysubd;
//
for (int i = albd; i <= aubd; i++) {
final CellArray a = this.structure.arrays[i];
//
if (a.celltype != CellType.VALUE) {
DoubleTools.copy(
this.data.output[source], a.cellslbd,
this.data.output[dest], a.cellslbd, a.cellsnum
);
/** /
DoubleTools.copy(
this.data.input[source], a.cellslbd,
this.data.input[dest], a.cellslbd, a.cellsnum
);
/**/
}
}
}
/**
* Copies gradient output values from source time to destination time.
* <br></br>
* @param source Source time index.
* @param dest Destination time index.
*/
protected void copyGradOutput(final int source, final int dest) {
//
// copy grad output from previous context buffer.
//
for (CellArray a : this.structure.arrays) {
if (
(a.celltype != CellType.VALUE) &&
(a.layer != this.structure.outputlayer)
) {
DoubleTools.copy(
this.data.gradoutput[source], a.cellslbd,
this.data.gradoutput[dest], a.cellslbd, a.cellsnum
);
/*
DoubleTools.copy(
this.data.gradinput[source], a.cellslbd,
this.data.gradinput[dest], a.cellslbd, a.cellsnum
);
*/
}
}
}
/**
* Copies gradient output values from source time to destination time
* just for one single layer.
* <br></br>
* @param source Source time index.
* @param dest Destination time index.
* @param layer Layer index.
*/
protected void copyGradOutput(final int source, final int dest, final int layer) {
//
// copy grad output from previous context buffer.
//
final int albd = this.structure.layers[layer].arrayslbd;
final int aubd = this.structure.layers[layer].arraysubd;
//
for (int i = albd; i <= aubd; i++) {
final CellArray a = this.structure.arrays[i];
if (
(a.celltype != CellType.VALUE) &&
(a.layer != this.structure.outputlayer)
) {
DoubleTools.copy(
this.data.gradoutput[source], a.cellslbd,
this.data.gradoutput[dest], a.cellslbd, a.cellsnum
);
/*
DoubleTools.copy(
this.data.gradinput[source], a.cellslbd,
this.data.gradinput[dest], a.cellslbd, a.cellsnum
);
*/
}
}
}
}
| 5,669 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
NetBase.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/NetBase.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
import java.io.Serializable;
import java.util.Random;
import de.jannlab.Net;
import de.jannlab.data.ReadPort;
import de.jannlab.data.WritePort;
import de.jannlab.misc.DoubleTools;
import de.jannlab.misc.ObjectCopy;
import de.jannlab.tools.Debug;
/**
* This class is an abstract base-class for all different implementations
* in this framework. It contains general methods, which are equal for different
* network types. The aim is to reduce the amount of code each special network
* implementation needs. Such general methods are input, output and buffering
* mechanisms, computing a layer integration or activation (or the gradient) for
* one time step, computing the error and some other data- and meta-methods.
* <br></br>
* @see Net
* @author Sebastian Otte
*/
public abstract class NetBase implements Net, Serializable, Cloneable {
private static final long serialVersionUID = 4485482287977886674L;
/**
* Gives the standard lower bound for random weight initialization.
*/
public static final double RANDOM_WEIGHT_LBD = -0.1;
/**
* Gives the standard upper bound for random weight initialization.
*/
public static final double RANDOM_WEIGHT_UBD = 0.1;
/**
* Provides the network structure of this network instance.
* @see NetStructure
*/
protected NetStructure structure = null;
/**
* Provides the network data of this network instance.
*/
protected NetData data = null;
/**
* Gives the current frameidx of the network. This can be
* considered as an inner state during the computation process.
*/
protected int frameidx = 0;
/**
* Provides a read port to the output data of this network. This port
* targets to the range of output cells in the output buffer
* using the current frameidx.
*/
private ReadPort outputport = null;
/**
* Provides a write port to the input data of this network. This port
* targets to the range of input cells in the output buffer
* using the current frameidx.
*/
private WritePort inputport = null;
/**
* Provides a write port to the target data of this network (necessary
* to compute the error). This port targets to the range of output cells
* the gradinput buffer.
*/
private WritePort targetport = null;
/**
* This methods computes the activation (also integration) of a single
* layer given by idx, based on the current frameidx. The method
* ensures that the activations of all arrays of the layer are computed
* in correct time order, which has been defined during generating the network.
* <br></br>
* @param idx Gives a layer index.
*/
protected void computeLayerActivations(final int idx) {
final Layer layer = this.structure.layers[idx];
//
// respect shifted computation indices.
//
for (int c = 0; c < layer.compwidth; c++) {
//
final int lbd = layer.complbds[c];
final int ubd = layer.compubds[c];
//
// integration.
//
for (int a = lbd; a <= ubd; a++) {
final CellArray array = this.structure.arrays[a];
//
CellIntegration.perform(
this.data.output[this.frameidx], this.data.input[this.frameidx],
array.cellslbd, array.cellsnum,
this.data.weights, this.structure.links,
array.predslbd, array.predsnum,
array.celltype.integration
);
}
//
// activation.
//
for (int a = lbd; a <= ubd; a++) {
final CellArray array = this.structure.arrays[a];
//
CellFunction.perform(
this.data.input[this.frameidx], array.cellslbd,
this.data.output[this.frameidx], array.cellslbd,
array.cellsnum, array.celltype.activation
);
}
}
}
/**
* This methods computes the gradient (reverse integration and derivative
* activation)for a single layer given by idx, based on the current frameidx.
* The method ensures that gradient of the arrays of the layer are computed
* in correct (reverse) time order, which has been defined during generating
* the network.
* <br></br>
* @param idx Gives a layer index.
*/
protected void computeLayerGradients(final int idx) {
final Layer layer = this.structure.layers[idx];
//
// respect shifted computation indices.
//
for (int c = layer.compwidth - 1; c >= 0; c--) {
//
final int lbd = layer.complbds[c];
final int ubd = layer.compubds[c];
//
// reverse integration, which is always SUM.
//
for (int a = ubd; a >= lbd; a--) {
/*
// # DEBUG #
if (a == 6) {
System.out.println("STOP");
}
// #
*/
final CellArray array = this.structure.arrays[a];
//
CellIntegration.perform(
this.data.gradoutput[this.frameidx],
this.data.gradinput[this.frameidx],
array.cellslbd, array.cellsnum,
this.data.weights, this.structure.linksrev,
array.succslbd, array.succsnum,
array.celltype.revintegration
);
}
//
// activation derivation.
//
for (int a = lbd; a <= ubd; a++) {
/*
// # DEBUG #
if (a == 6) {
System.out.println("STOP");
}
// #
*/
final CellArray array = this.structure.arrays[a];
//
// compute f'(input) first and then store
// multiplication with reverse integration.
//
CellFunction.perform(
this.data.input[this.frameidx], array.cellslbd,
this.data.gradoutput[this.frameidx], array.cellslbd,
array.cellsnum, array.celltype.revactivation
);
//
DoubleTools.mul(
this.data.gradinput[this.frameidx], array.cellslbd,
this.data.gradoutput[this.frameidx], array.cellslbd,
this.data.gradoutput[this.frameidx], array.cellslbd,
array.cellsnum
);
}
}
}
/**
* Clears the entire data buffer by setting all cell values to zero.
* After that the constant assignments to data cells are restored.
* This method effects all particular buffers over all time steps.
*/
private void clearData() {
final int size = this.structure.cellsnum;
//
// setting all values to zero. Maybe it would be faster
// just to reallocate the data and drop the previous.
//
for (int f = 0; f < this.data.framewidth; f++) {
DoubleTools.fill(this.data.input[f], 0, size, 0.0);
DoubleTools.fill(this.data.output[f], 0, size, 0.0);
DoubleTools.fill(this.data.gradinput[f], 0, size, 0.0);
DoubleTools.fill(this.data.gradoutput[f], 0, size, 0.0);
}
//
// perform assignments.
//
for (int t = 0; t < this.data.framewidth; t++) {
for (int i = 0; i < this.data.asgns.length; i++) {
final int idx = this.data.asgns[i];
this.data.output[t][idx] = this.data.asgnsv[i];
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void rebuffer(final int frames) {
final int size = this.structure.cellsnum;
//
this.data.input = new double[frames][size];
this.data.output = new double[frames][size];
this.data.gradinput = new double[frames][size];
this.data.gradoutput = new double[frames][size];
this.data.framewidth = frames;
//
// this will restore assigments.
//
this.reset();
}
/**
* This methods sets up all data ports provides by the network. The ports by them self use
* the input, output and target methods of this network.
*/
private void setupPorts() {
//
// setup input port.
//
this.inputport = new WritePort() {
private static final long serialVersionUID = 5944146445529987404L;
@Override
public void write(final double[] buffer, final int offset) {
NetBase.this.input(buffer, offset);
}
@Override
public void write(final double[] buffer, final int offset, final int[] selection) {
NetBase.this.input(buffer, offset, selection);
}
};
//
// setup output port.
//
this.outputport = new ReadPort() {
private static final long serialVersionUID = -7424453538318475273L;
@Override
public void read(final double[] buffer, final int offset) {
NetBase.this.output(buffer, offset);
}
@Override
public void read(final double[] buffer, final int offset, final int[] selection) {
NetBase.this.output(buffer, offset, selection);
}
};
//
// setup target port.
//
this.targetport = new WritePort() {
private static final long serialVersionUID = 3258515325902331582L;
@Override
public void write(final double[] buffer, final int offset) {
NetBase.this.target(buffer, offset);
}
@Override
public void write(final double[] buffer, final int offset, final int[] selection) {
NetBase.this.target(buffer, offset, selection);
}
};
}
/**
* {@inheritDoc}
*/
@Override
public void incrFrameIdx() {
this.frameidx++;
if (this.frameidx >= this.data.framewidth) {
this.frameidx--;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setFrameIdx(final int idx) {
if (idx < 0) {
this.frameidx = 0;
} else if (idx >= this.data.framewidth) {
this.frameidx = this.data.framewidth - 1;
} else {
this.frameidx = idx;
}
}
/**
* {@inheritDoc}
*/
@Override
public void decrFrameIdx() {
if (this.frameidx <= 0) return;
this.frameidx--;
}
/**
* {@inheritDoc}
*/
public Net sharedCopy() {
try {
//
// no deep copy -> instance copy. all sub-objects are shared.
//
NetBase copy = (NetBase)this.clone();
//
// deep copy only data and re-setup ports.
//
copy.data = this.data.sharedCopy();
copy.setupPorts();
//
return copy;
} catch (CloneNotSupportedException e) {
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
public Net copy() {
return ObjectCopy.copy(this);
}
/**
* Creates a NetBase instance. The constructor is only visible in the core package.
* This method assigns given NetStructure and NetData instance and sets up fundamental
* things such as data ports or buffer initialization.
* <br></br>
* @param structure
* @param data
*/
NetBase(
final NetStructure structure,
final NetData data
) {
//
this.structure = structure;
this.data = data;
//
this.setupPorts();
this.reset();
}
/**
* {@inheritDoc}
*/
@Override
public int getFrameIdx() {
return this.frameidx;
}
/**
* {@inheritDoc}
*/
@Override
public int getFrameWidth() {
return this.data.framewidth;
}
/**
* {@inheritDoc}
*/
@Override
public WritePort inputPort() {
return this.inputport;
}
/**
* {@inheritDoc}
*/
@Override
public WritePort targetPort() {
return this.targetport;
}
/**
* {@inheritDoc}
*/
@Override
public ReadPort outputPort() {
return this.outputport;
}
/**
* {@inheritDoc}
*/
@Override
public void reset() {
this.frameidx = 0;
this.clearData();
}
/**
* {@inheritDoc}
*/
public double[] getOutputBuffer(final int frameidx) {
return this.data.output[frameidx];
}
/**
* {@inheritDoc}
*/
public double[] getGradOutputBuffer(final int frameidx) {
return this.data.gradoutput[frameidx];
}
/**
* {@inheritDoc}
*/
public double[] getGradInputBuffer(final int frameidx) {
return this.data.gradinput[frameidx];
}
/**
* {@inheritDoc}
*/
@Override
final public NetStructure getStructure() {
return this.structure;
}
/**
* {@inheritDoc}
*/
@Override
final public boolean isBidirectional() {
return this.structure.bidirectional;
}
/**
* {@inheritDoc}
*/
@Override
final public boolean isRecurrent() {
return this.structure.recurrent;
}
/**
* {@inheritDoc}
*/
@Override
final public boolean isOnline() {
return !this.isOffline();
}
/**
* {@inheritDoc}
*/
@Override
final public boolean isOffline() {
return this.structure.offline;
}
/**
* {@inheritDoc}
*/
@Override
final public int getInputCells() {
return this.structure.incellsnum;
}
/**
* {@inheritDoc}
*/
@Override
final public int getOutputCells() {
return this.structure.outcellsnum;
}
/**
* {@inheritDoc}
*/
@Override
final public int getValueCells() {
return this.structure.valcellsnum;
}
/**
* {@inheritDoc}
*/
@Override
final public int getComputingCells() {
return this.structure.comcellsnum;
}
/**
* {@inheritDoc}
*/
@Override
public double error() {
//
// compute difference of the expected data
// and output of the output layer. store result
// in output layer (gradinput again).
//
DoubleTools.sub(
this.data.gradinput[this.frameidx], this.structure.outcellslbd,
this.data.output[this.frameidx], this.structure.outcellslbd,
this.data.gradinput[this.frameidx], this.structure.outcellslbd,
this.structure.outcellsnum
);
/*
//
// build sum of absolute error.
//
final double err = DoubleTools.absSum(
this.data.gradinput[this.frameidx], this.structure.outcellslbd,
this.structure.outcellsnum
);
*/
//
// build sum of square error.
//
final double err = DoubleTools.meanSquareSum(
this.data.gradinput[this.frameidx], this.structure.outcellslbd,
this.structure.outcellsnum
);
return err;
}
/**
* {@inheritDoc}
*/
@Override
public void initializeWeights() {
this.initializeWeights(new Random(System.currentTimeMillis()));
}
/**
* {@inheritDoc}
*/
@Override
public void initializeWeights(final Random rnd) {
//
int size = this.data.weightsnum;
int offset = 1;
//
DoubleTools.fill(
this.data.weights, offset, size, rnd,
RANDOM_WEIGHT_LBD, RANDOM_WEIGHT_UBD
);
}
/**
* {@inheritDoc}
*/
@Override
public double[] getWeights() {
return this.data.weights;
}
/**
* {@inheritDoc}
*/
@Override
public void writeWeights(final double[] data, final int offset) {
DoubleTools.copy(
data, offset, this.data.weights, 1, this.data.weightsnum
);
}
/**
* {@inheritDoc}
*/
@Override
public void readWeights(final double[] data, final int offset) {
DoubleTools.copy(
this.data.weights, 1, data, offset, this.data.weightsnum
);
}
/**
* {@inheritDoc}
*/
@Override
public int[] getLinks() {
return this.structure.links;
}
/**
* {@inheritDoc}
*/
@Override
public int[] getLinksRev() {
return this.structure.linksrev;
}
/**
* {@inheritDoc}
*/
@Override
public int getWeightsNum() {
return this.data.weightsnum;
}
/**
* {@inheritDoc}
*/
@Override
public int getLinksNum() {
return this.structure.linksnum;
}
/**
* {@inheritDoc}
*/
@Override
public void input(final double[] data, final int offset) {
//
// copy given data into current output buffer.
//
DoubleTools.copy(
data, offset, this.data.output[this.frameidx],
this.structure.incellslbd,
this.structure.incellsnum
);
}
/**
* {@inheritDoc}
*/
@Override
public void input(final double[] data, final int offset, final int[] selection) {
//
// copy given data into current output buffer, respecting only
// the indices determined in selection.
//
DoubleTools.copy(
data, offset, selection, this.data.output[this.frameidx],
this.structure.incellslbd
);
}
/**
* {@inheritDoc}
*/
@Override
public void output(final double[] data, final int offset) {
//
// copy values from the current output buffer in the given data array.
//
DoubleTools.copy(
this.data.output[this.frameidx], this.structure.outcellslbd,
data, offset, this.structure.outcellsnum
);
}
/**
* {@inheritDoc}
*/
@Override
public void output(final double[] data, final int offset, final int[] selection) {
//
// copy values from the current output buffer in the given data array,
// respecting only the indices determined in selection.
//
DoubleTools.copy(
data, this.structure.outcellslbd, this.data.output[this.frameidx],
offset, selection
);
}
/**
* {@inheritDoc}
*/
@Override
public void target(final double[] data, final int offset) {
//
// write expected data in output layer (gradinput).
//
DoubleTools.copy(
data, offset, this.data.gradinput[this.frameidx],
this.structure.outcellslbd,
this.structure.outcellsnum
);
}
/**
* {@inheritDoc}
*/
@Override
public void target(final double[] data, final int offset, final int[] selection) {
//
// write expected data in output layer (gradinput), respecting only
// the indices determined in selection.
//
DoubleTools.copy(
data, offset, selection, this.data.gradinput[this.frameidx],
this.structure.outcellslbd
);
}
/**
* Performs a numerical check for a given value.
* <br></br>
* @param value The value that is to check.
* @return True if the given value is not NaN or infinite.
*/
private static boolean check(final double value) {
if (Double.isNaN(value)) {
if (Debug.DEBUG) {
System.out.println("NaN occurs.");
}
return false;
}
if (Double.isInfinite(value)) {
if (Debug.DEBUG) {
System.out.println("Infinite occurs.");
}
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean numericalCheck() {
//
// over all time steps.
//
for (int f = 0; f < this.data.framewidth; f++) {
//
// for all cells.
//
for (int j = 0; j < this.structure.cellsnum; j++) {
if (!check(this.data.input[f][j])) return false;
if (!check(this.data.output[f][j])) return false;
if (!check(this.data.gradinput[f][j])) return false;
if (!check(this.data.gradoutput[f][j])) return false;
}
}
//
// for all weights.
//
for (int i = 0; i < this.data.weightsnum; i++) {
if (!check(this.data.weights[i])) return false;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder out = new StringBuilder();
out.append("NetStructure : {\n");
out.append("" + Debug.indent(this.structure.toString()) + "\n");
out.append("}\n\n");
//
out.append("Assignments : {\n");
for (int i = 0; i < this.data.asgns.length; i++) {
out.append("\t" + this.data.asgns[i] + " : " + this.data.asgnsv[i] + "\n");
}
out.append("}\n\n");
return out.toString();
}
}
| 22,885 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
CellArray.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/core/CellArray.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.core;
import java.io.Serializable;
/**
* A CellArray defines a range of cells with the same functional specification
* and same computation-point-of-time. Semantically the
* computation-point-of-time can be considered as parallel for cells in the
* array.<br></br>
* @author Sebastian Otte
*/
public final class CellArray implements Serializable {
private static final long serialVersionUID = -322002318603819740L;
// ------------------------------------------------------------------------
/** Cells are not automatically connected. */
public static final int ILC_NONE = 0x0;
/** Cells are only connected through incoming connections. */
public static final int ILC_IN = 0x1;
/** Cells are only connected through outgoing connections. */
public static final int ILC_OUT = 0x2;
/** Cells are connected through both incoming and outgoing connections. */
public static final int ILC_BOTH = ILC_IN | ILC_OUT;
// ------------------------------------------------------------------------
/**
* The lower bound of the cell range specified by the CellArray.
*/
public int cellslbd;
/**
* The upper bound of the cell range specified by the CellArray.
*/
public int cellsubd;
/**
* The number of cells in the range specified by the CellArray.
*/
public int cellsnum;
/**
* The input degree of all cells contained by the layer. This field is redundant
* to predsnum but is used while the generation process to verify result.
*/
public int indeg;
/**
* The output degree of all cells contained by the layer. This field is redundant
* to succsnum but is used while the generation process to verify result.
*/
public int outdeg;
/**
* The lower bound of the links from all predecessors of the cells in the CellArray.
*/
public int predslbd;
/**
* The upper bound of the links from all predecessors of the cells in the CellArray.
*/
public int predsubd;
/**
* The number of links from all predecessors of the cells in the CellArray.
*/
public int predsnum;
/**
* The number of weights of all predecessor links.
*/
public int predswnum;
/**
* The lower bound of the links to all successors of the cells in the CellArray.
*/
public int succslbd;
/**
* The upper bound of the links to all successors of the cells in the CellArray.
*/
public int succsubd;
/**
* The number of links to all successors of the cells in the CellArray.
*/
public int succsnum;
/**
* The number of weights of all successor links.
*/
public int succswnum;
/**
* Refers the parent layer.
*/
public int layer;
/**
* Defines the computation-point-of-time in the corresponding layer. If the value is -1
* this indicates that the CellArray contains non-computing cells.
*/
public int compidx;
/**
* This tag can be one of ILC_IN, ILC_OUT or ILC_BOTH. It indicates the "connective-type"
* of the cells. This allows to define input, output and "hidden" cells per layer.
*/
public int ilctag;
/**
* The CellType gives the functional specification (i.e. the integration and activation
* function) of the cells in this CellArray.
* @see CellType
*/
public CellType celltype;
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder w = new StringBuilder();
//
w.append("cellslbd : " + this.cellslbd + "\n");
w.append("cellsubd : " + this.cellsubd + "\n");
w.append("cellsnum : " + this.cellsnum + "\n");
w.append("indeg : " + this.indeg + "\n");
w.append("outdeg : " + this.outdeg + "\n");
w.append("predslbd : " + this.predslbd + "\n");
w.append("predsubd : " + this.predsubd + "\n");
w.append("predsnum : " + this.predsnum + "\n");
w.append("predswnum : " + this.predswnum + "\n");
w.append("succslbd : " + this.succslbd + "\n");
w.append("succsubd : " + this.succsubd + "\n");
w.append("succsnum : " + this.succsnum + "\n");
w.append("succswnum : " + this.succswnum + "\n");
w.append("layer : " + this.layer + "\n");
w.append("compidx : " + this.compidx + "\n");
w.append("ilctag : " + this.ilctag + "\n");
w.append("celltype : " + this.celltype.toString() + "\n");
//w.append("tag : " + this.tag + "\n");
//
return w.toString();
}
}
| 5,623 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
Objective.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/Objective.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization;
public interface Objective {
public int arity();
public double compute(final double[] args, final int offset);
} | 1,054 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
OptimizerBase.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/OptimizerBase.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization;
import de.jannlab.optimization.exception.IterativeMethodException;
import de.jannlab.optimization.exception.NoObjective;
import de.jannlab.optimization.exception.RequiresDifferentiableObjective;
public abstract class OptimizerBase<I extends Optimizer<I>>
extends IterativeMethodBase<I> implements Optimizer<I> {
//
public static final String KEY_PARAMS = "parameters";
//
private Objective objective;
private int parameters;
public void setParameters(final int parameters) {
this.parameters = parameters;
}
public int getParameters() {
return this.parameters;
}
@Override
public String toString() {
StringBuilder out = new StringBuilder();
//
out.append(super.toString());
//
out.append(
KEY_PARAMS + ": " + this.getParameters() + "\n"
);
//
return out.toString();
}
public OptimizerBase() {
this.parameters = 0;
}
@Override
public void reset() {
super.reset();
}
@Override
public Objective getObjective() {
return this.objective;
}
@Override
public void updateObjective(final Objective objective) {
if (this.requiresGradient()) {
if (!(objective instanceof DifferentiableObjective)) {
throw new RequiresDifferentiableObjective();
}
}
this.objective = objective;
}
@Override
protected void preIterationCheck() throws IterativeMethodException {
super.preIterationCheck();
if (this.objective == null) throw new NoObjective();
}
@Override
protected void preIterationsCheck() throws IterativeMethodException {
super.preIterationCheck();
if (this.objective == null) throw new NoObjective();
}
} | 2,810 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
IterationListener.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/IterationListener.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization;
public interface IterationListener<I extends IterativeMethod<I>> {
public void started(final I reference);
public void beforeIteration(final int iteration, final I reference);
public void afterIteration(final int iteration, final I reference);
public void finished(
final int iterations, final double error, final I reference
);
} | 1,312 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
BasicIterationListener.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/BasicIterationListener.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization;
import de.jannlab.misc.DoubleTools;
public class BasicIterationListener<I extends IterativeMethod<I>>
implements IterationListener<I> {
private double best;
@Override
public void started(I reference) {
//
this.best = reference.getError();
}
@Override
public void beforeIteration(int iteration, I reference) {
//
}
private static String paddingBack(String data, int length) {
StringBuilder s = new StringBuilder();
s.append(data);
int rest = length - s.length();
for (int i = 0; i < rest; i++) {
s.append(" ");
}
return s.toString();
}
@Override
public void afterIteration(int iteration, I reference) {
//
final int width1 = 20;
final int width2 = 8;
final int width3 = 30;
//
final double error = reference.getError();
String imprec = "(-)";
if (error < this.best) {
this.best = error;
imprec = "(+)";
}
//
System.out.print(paddingBack("iteration: " + iteration, width1));
System.out.print(paddingBack(imprec, width2));
System.out.print(
paddingBack("error: " + DoubleTools.asString(error, 10), width3)
);
System.out.print(
"best error: " + DoubleTools.asString(this.best, 10)
);
System.out.println();
}
@Override
public void finished(int iterations, double error, I reference) {
//
}
} | 2,502 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
IterativeMethod.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/IterativeMethod.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization;
public interface IterativeMethod<I extends IterativeMethod<I>> {
public void addListener(final IterationListener<I> listener);
public void removeListener(final IterationListener<I> listener);
public void clearListener(final IterationListener<I> listener);
public int getIteration();
public void initialize();
public void reset();
public double getError();
public double performIteration();
public double iterate(
final int iterations, final double targeterror
);
public void requestAbort();
} | 1,526 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
Optimizer.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/Optimizer.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization;
public interface Optimizer<T extends Optimizer<T>> extends IterativeMethod<T> {
public Objective getObjective();
public void updateObjective(final Objective objective);
public boolean requiresGradient();
public double getBestError();
public void copyBestSolution(final double[] target, final int offset);
} | 1,271 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
DifferentiableObjective.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/DifferentiableObjective.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization;
public interface DifferentiableObjective extends Objective {
public double computeGradient(
final double[] args, final int argsoffset,
final double[] target, final int targetoffset
);
} | 1,144 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
IterativeMethodBase.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/IterativeMethodBase.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization;
import java.util.LinkedList;
import java.util.List;
import de.jannlab.optimization.exception.IterativeMethodException;
import de.jannlab.optimization.exception.NotAllowedWhileRunning;
import de.jannlab.optimization.exception.NotInitialized;
public abstract class IterativeMethodBase<I extends IterativeMethod<I>>
implements IterativeMethod<I> {
private int iteration;
private double error;
private boolean initialized;
private boolean abort;
private boolean running;
private List<IterationListener<I>> listener;
protected IterativeMethodBase() {
this.listener = new LinkedList<IterationListener<I>>();
this.initialized = false;
this.abort = false;
this.running = false;
}
@Override
public void addListener(IterationListener<I> listener) {
this.listener.add(listener);
}
@Override
public void removeListener(IterationListener<I> listener) {
this.listener.remove(listener);
}
@Override
public void clearListener(IterationListener<I> listener) {
this.listener.clear();
}
@Override
synchronized
public void requestAbort() {
if (this.running) {
this.abort = true;
}
}
protected void abort() {
this.abort = true;
}
protected boolean getAbort() {
return this.abort;
}
protected abstract I iterativeMethodMe();
private void beforeIteration() {
//
final I me = this.iterativeMethodMe();
//
for (IterationListener<I> l : this.listener) {
l.beforeIteration(this.iteration, me);
}
}
private void afterIteration() {
//
final I me = this.iterativeMethodMe();
//
for (IterationListener<I> l : this.listener) {
l.afterIteration(this.iteration, me);
}
}
private void started() {
//
final I me = this.iterativeMethodMe();
//
for (IterationListener<I> l : this.listener) {
l.started(me);
}
}
protected abstract void iterativeMethodInitialize();
@Override
public void initialize() {
this.iterativeMethodInitialize();
this.initialized = true;
this.reset();
}
private void finished() {
//
final I me = this.iterativeMethodMe();
//
for (IterationListener<I> l : this.listener) {
l.finished(this.iteration, this.error, me);
}
}
@Override
public int getIteration() {
return this.iteration;
}
protected abstract void iterativeMethodReset();
protected abstract double iterativeMethodPerformIteration();
protected void updateError(final double error) {
this.error = error;
}
@Override
public void reset() {
if (this.running) throw new NotAllowedWhileRunning();
this.iteration = 0;
this.abort = false;
this.updateError(Double.POSITIVE_INFINITY);
this.iterativeMethodReset();
}
protected void preIterationCheck() throws IterativeMethodException {
if (!this.initialized) throw new NotInitialized();
}
protected void preIterationsCheck() throws IterativeMethodException {
if (!this.initialized) throw new NotInitialized();
}
@Override
public double performIteration() {
//
this.preIterationCheck();
this.beforeIteration();
final double result = this.iterativeMethodPerformIteration();
this.updateError(result);
this.afterIteration();
this.iteration++;
return result;
}
@Override
public double getError() {
return this.error;
}
@Override
synchronized
public double iterate(final int iterations, final double targeterror) {
if (this.running) throw new NotAllowedWhileRunning();
this.abort = false;
this.running = true;
//
this.preIterationsCheck();
//
this.started();
//
for (int i = 0; i < iterations; i++) {
final double result = this.performIteration();
if ((result < targeterror) || this.abort) {
break;
}
}
//
this.finished();
//
this.running = false;
return this.error;
}
} | 5,401 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
Mutation.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/diffevo/Mutation.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization.diffevo;
/**
*
* @author Sebastian Otte
*/
public enum Mutation {
//
RAND_ONE,
BEST_ONE,
RAND_TWO,
BEST_TWO,
//
RAND2BEST_ONE
} | 1,091 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
DifferentialEvolution.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/diffevo/DifferentialEvolution.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization.diffevo;
import java.util.Random;
import de.jannlab.math.MatrixTools;
import de.jannlab.misc.DoubleTools;
import de.jannlab.optimization.Objective;
import de.jannlab.optimization.OptimizerBase;
import de.jannlab.optimization.exception.NoObjective;
/**
*
* @author Sebastian Otte
*/
public class DifferentialEvolution extends OptimizerBase<DifferentialEvolution>{
public static final String KEY_POPSIZE = "popsize";
public static final String KEY_CR = "CR";
public static final String KEY_F = "F";
public static final String KEY_F2 = "F2";
public static final String KEY_MUTATION = "mutation";
public static final String KEY_INITLBD = "initlbd";
public static final String KEY_INITUBD = "initubd";
public static final int DEFAULT_POPSIZE = 100;
public static final double DEFAULT_CR = 0.7;
public static final double DEFAULT_F = 0.4;
public static final double DEFAULT_F2 = 0.4;
public static final Mutation DEFAULT_MUTATION = Mutation.RAND_ONE;
public static final double DEFAULT_INITLBD = -1.0;
public static final double DEFAULT_INITUBD = 1.0;
private double[] population;
private double[] buffer;
private double[] accu;
private double[] fitness;
private double best_f;
private int best;
private int popsize;
private double CR;
private double F;
private double F2;
private Mutation mutation;
private double initlbd;
private double initubd;
private Random rnd;
@Override
public String toString() {
StringBuilder out = new StringBuilder();
//
out.append(super.toString());
//
out.append(KEY_POPSIZE + ": " + this.popsize + "\n");
out.append(KEY_CR + ": " + this.CR + "\n");
out.append(KEY_F + ": " + this.F + "\n");
out.append(KEY_F2 + ": " + this.F2 + "\n");
out.append(
KEY_MUTATION + ": " + this.mutation.name() + "\n"
);
out.append(KEY_INITLBD + ": " + this.initlbd + "\n");
out.append(KEY_INITUBD + ": " + this.initubd + "\n");
//
return out.toString();
}
public DifferentialEvolution() {
//
this.popsize = DEFAULT_POPSIZE;
this.CR = DEFAULT_CR;
this.F = DEFAULT_F;
this.F2 = DEFAULT_F2;
//
this.mutation = DEFAULT_MUTATION;
//
this.initlbd = DEFAULT_INITLBD;
this.initubd = DEFAULT_INITUBD;
//
this.rnd = new Random(System.currentTimeMillis());
//
this.best = -1;
this.best_f = Double.POSITIVE_INFINITY;
}
public double getInitUbd() {
return this.initubd;
}
@Override
public boolean requiresGradient() {
return false;
}
@Override
public double getBestError() {
return this.best_f;
}
public void setInitUbd(final double initubd) {
this.initubd = initubd;
}
public double getInitLbd() {
return this.initlbd;
}
public void setInitLbd(final double initlbd) {
this.initlbd = initlbd;
}
public Mutation getMutation() {
return this.mutation;
}
public void setMutation(final Mutation mutation) {
this.mutation = mutation;
}
public int getPopSize() {
return this.popsize;
}
public void setPopSize(final int popsize) {
this.popsize = popsize;
}
public double getCR() {
return this.CR;
}
public void setCR(final double CR) {
this.CR = CR;
}
public double getF() {
return this.F;
}
public void setF(final double F) {
this.F = F;
}
public double getF2() {
return this.F2;
}
public void setF2(final double F2) {
this.F2 = F2;
}
public void setRnd(final Random rnd) {
this.rnd = rnd;
}
public int getPopulationSize() {
return this.popsize;
}
public Random getRnd() {
return this.rnd;
}
@Override
protected DifferentialEvolution iterativeMethodMe() {
return this;
}
final private int offset(final int idx) {
return this.getParameters() * idx;
}
@Override
protected void iterativeMethodInitialize() {
//
// initialize population buffer and
// generation working buffer.
//
this.population = MatrixTools.allocate(
this.popsize, this.getParameters()
);
this.buffer = MatrixTools.allocate(
this.popsize, this.getParameters()
);
//
// initialize computation accu for
// storing intermediate results.
//
this.accu = MatrixTools.allocate(
this.getParameters()
);
//
// initialize the fitness array with
// +\inf for each individual.
//
this.fitness = MatrixTools.allocate(
this.popsize
);
for (int i = 0; i < this.fitness.length; i++) {
this.fitness[i] = Double.POSITIVE_INFINITY;
}
}
private void initializePopulation() {
//
Objective obj = this.getObjective();
if (obj == null) throw new NoObjective();
//
// value initialization.
//
DoubleTools.fill(
this.population, 0, this.population.length,
this.rnd, this.initlbd, this.initubd
);
//
// evaluate fitness values for each individual.
//
int offset = 0;
//
int lbest = -1;
double lbest_f = Double.POSITIVE_INFINITY;
//
for (int i = 0; i < this.popsize; i++) {
//
final double f = obj.compute(this.population, offset);
this.fitness[i] = f;
//
if (f < lbest_f) {
lbest = i;
lbest_f = f;
}
//
offset += this.getParameters();
}
//
this.best = lbest;
this.best_f = lbest_f;
//
this.updateError(lbest_f);
}
@Override
protected void iterativeMethodReset() {
this.initializePopulation();
}
private void preventRandomIndex(final int i) {
//
// TODO: Implement.
//
}
private int nextRandomIndex() {
return this.rnd.nextInt(this.popsize);
}
private void mutateRandOne(final int i) {
this.preventRandomIndex(i);
//
// pick three indices randomly.
//
final int a = this.nextRandomIndex();
final int b = this.nextRandomIndex();
final int c = this.nextRandomIndex();
//
int offset_a = this.offset(a);
int offset_b = this.offset(b);
int offset_c = this.offset(c);
//
final int n = this.getParameters();
//
for (int j = 0; j < n; j++) {
//
this.accu[j] = (
this.population[offset_a] +
(
this.F * (
this.population[offset_b] -
this.population[offset_c]
)
)
);
//
offset_a++;
offset_b++;
offset_c++;
}
}
private void mutateBestOne(final int i) {
this.preventRandomIndex(i);
//
// pick three indices randomly.
//
final int best = this.best;
this.preventRandomIndex(best);
final int a = this.nextRandomIndex();
final int b = this.nextRandomIndex();
//
int offset_best = this.offset(best);
int offset_a = this.offset(a);
int offset_b = this.offset(b);
//
final int n = this.getParameters();
//
for (int j = 0; j < n; j++) {
//
this.accu[j] = (
this.population[offset_best] +
(
this.F * (
this.population[offset_a] -
this.population[offset_b]
)
)
);
//
offset_best++;
offset_a++;
offset_b++;
}
}
private void mutateRand2BestOne(final int i) {
this.preventRandomIndex(i);
//
// pick three indices randomly.
//
final int best = this.best;
this.preventRandomIndex(best);
final int a = this.nextRandomIndex();
final int b = this.nextRandomIndex();
final int c = this.nextRandomIndex();
//
int offset_i = this.offset(i);
int offset_best = this.offset(best);
int offset_a = this.offset(a);
int offset_b = this.offset(b);
int offset_c = this.offset(c);
//
final int n = this.getParameters();
//
for (int j = 0; j < n; j++) {
//
this.accu[j] = (
this.population[offset_i] + (
this.F * (
this.population[offset_best] -
this.population[offset_a]
)
) + (
this.F2 * (
this.population[offset_b] -
this.population[offset_c]
)
)
);
//
offset_i++;
offset_best++;
offset_a++;
offset_b++;
offset_c++;
}
}
private void mutateRandTwo(final int i) {
this.preventRandomIndex(i);
//
// pick three indices randomly.
//
final int a = this.nextRandomIndex();
final int b = this.nextRandomIndex();
final int c = this.nextRandomIndex();
final int d = this.nextRandomIndex();
final int e = this.nextRandomIndex();
//
int offset_a = this.offset(a);
int offset_b = this.offset(b);
int offset_c = this.offset(c);
int offset_d = this.offset(d);
int offset_e = this.offset(e);
//
final int n = this.getParameters();
//
for (int j = 0; j < n; j++) {
//
this.accu[j] = (
this.population[offset_a] + (
this.F * (
this.population[offset_b] -
this.population[offset_c]
)
) + (
this.F2 * (
this.population[offset_d] -
this.population[offset_e]
)
)
);
//
offset_a++;
offset_b++;
offset_c++;
offset_d++;
offset_e++;
}
}
private void mutateBestTwo(final int i) {
this.preventRandomIndex(i);
//
// pick three indices randomly.
//
final int best = this.best;
this.preventRandomIndex(best);
final int a = this.nextRandomIndex();
final int b = this.nextRandomIndex();
final int c = this.nextRandomIndex();
final int d = this.nextRandomIndex();
//
int offset_best = this.offset(best);
int offset_a = this.offset(a);
int offset_b = this.offset(b);
int offset_c = this.offset(c);
int offset_d = this.offset(d);
//
final int n = this.getParameters();
//
for (int j = 0; j < n; j++) {
//
this.accu[j] = (
this.population[offset_best] +
(
this.F * (
this.population[offset_a] +
this.population[offset_b] -
this.population[offset_c] -
this.population[offset_d]
)
)
);
//
offset_best++;
offset_a++;
offset_b++;
offset_c++;
offset_d++;
}
}
private void mutate(final int i) {
switch (this.mutation) {
case RAND_ONE:
this.mutateRandOne(i);
break;
case BEST_ONE:
this.mutateBestOne(i);
break;
case RAND_TWO:
this.mutateRandTwo(i);
break;
case BEST_TWO:
this.mutateBestTwo(i);
break;
case RAND2BEST_ONE:
this.mutateRand2BestOne(i);
break;
}
}
private void crossover(final int i) {
//
// building the crossover vector: the origin vector is given
// through the population-buffer at offset(i). the mutation
// vector comes from the accu at offset 0.
//
int orig_offset = this.offset(i);
int accu_offset = 0;
//
final int n = this.getParameters();
//
for (int j = 0; j < n; j++) {
final double r = this.rnd.nextDouble();
//
this.accu[accu_offset] = (
(r < this.CR)?
(this.accu[accu_offset]):
(this.population[orig_offset])
);
//
orig_offset++;
accu_offset++;
}
//
}
@Override
protected double iterativeMethodPerformIteration() {
final Objective obj = this.getObjective();
//
int lbest = this.best;
double lbest_f = this.best_f;
int offset = 0;
//
final int n = this.getParameters();
//
// for all individuals in population...
//
for (int i = 0; i < this.popsize; i++) {
//
// first, create mutation vector based on the
// selected mutation strategy. the resulting
// vector is stored in this.accu at offset 0.
//
this.mutate(i);
//
// crossover operation of the current individual
// and the mutation vector. the result is stored
// this.accu at offset 0.
//
this.crossover(i);
//
// selection the new vector from this.accu is used
// in the next generation, if its fitness is better
// than the origin vector.
//
final double f_y = obj.compute(this.accu, 0);
if (f_y < this.fitness[i]) {
//
// copy new vector and update fitness.
//
this.fitness[i] = f_y;
DoubleTools.copy(
this.accu, 0, this.buffer, offset, n
);
//
// check for new best.
//
if (f_y < lbest_f) {
lbest_f = f_y;
lbest = i;
}
} else {
//
// copy origin vector.
//
DoubleTools.copy(
this.population, offset, this.buffer, offset, n
);
}
//
offset += n;
}
//
// copy new generation.
//
DoubleTools.copy(
this.buffer, 0, this.population, 0, this.buffer.length
);
//
// update best.
//
this.best = lbest;
this.best_f = lbest_f;
//
return this.best_f;
}
@Override
public void copyBestSolution(
final double[] target,
final int offset) {
//
DoubleTools.copy(
this.population, this.offset(this.best),
target, offset, this.getParameters()
);
}
} | 17,169 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
IterativeMethodException.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/exception/IterativeMethodException.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization.exception;
import de.jannlab.exception.JANNLabException;
public class IterativeMethodException extends JANNLabException {
private static final long serialVersionUID = -4578796617966258713L;
public IterativeMethodException(
final String msg
) {
super(msg);
}
public IterativeMethodException(
final String msg,
final Throwable cause
) {
super(msg, cause);
}
public IterativeMethodException() {};
} | 1,416 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
OptimizerException.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/exception/OptimizerException.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization.exception;
public class OptimizerException extends IterativeMethodException {
private static final long serialVersionUID = -4578796617966258713L;
public OptimizerException(
final String msg
) {
super(msg);
}
public OptimizerException(
final String msg,
final Throwable cause
) {
super(msg, cause);
}
public OptimizerException() {};
} | 1,348 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
RequiresDifferentiableObjective.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/exception/RequiresDifferentiableObjective.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization.exception;
public class RequiresDifferentiableObjective extends IterativeMethodException {
private static final long serialVersionUID = -4578796617966258713L;
public RequiresDifferentiableObjective() {
super("differentiable objective required.");
}
} | 1,206 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
NotInitialized.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/exception/NotInitialized.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization.exception;
public class NotInitialized extends IterativeMethodException {
private static final long serialVersionUID = 1194916015131585272L;
public NotInitialized() {
super("optimizer not initialized.");
}
} | 1,166 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
NotAllowedWhileRunning.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/exception/NotAllowedWhileRunning.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization.exception;
public class NotAllowedWhileRunning extends IterativeMethodException {
private static final long serialVersionUID = 1194916015131585272L;
public NotAllowedWhileRunning() {
super("Action not allowed while running process.");
}
} | 1,197 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
NoObjective.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/optimization/exception/NoObjective.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.optimization.exception;
public class NoObjective extends OptimizerException {
private static final long serialVersionUID = -3687981706725406116L;
public NoObjective() {
super("no objective given.");
}
} | 1,148 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
JANNLabException.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/exception/JANNLabException.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.exception;
/**
* The main Exception. In this version it is a subclass of RuntimeException.
* <br></br>
* @author Sebastian Otte
*/
public class JANNLabException extends RuntimeException {
private static final long serialVersionUID = -7235877054218115313L;
//
public JANNLabException(
final String msg
) {
super(msg);
}
public JANNLabException(
final String msg,
final Throwable cause
) {
super(msg, cause);
}
public JANNLabException() {};
}
| 1,453 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
GradientDescent.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/training/GradientDescent.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.training;
import de.jannlab.core.Link;
import de.jannlab.data.Sample;
import de.jannlab.data.SampleSet;
import de.jannlab.misc.DoubleTools;
import de.jannlab.misc.IntTools;
import de.jannlab.tools.NetTools;
/**
* This class implements the common gradient descent learning algorithm.
* <br></br>
* @author Sebastian Otte
*/
public final class GradientDescent extends NetTrainer {
//
public static final double DEFAULT_ALPHA = 0.9;
public static final double DEFAULT_MU = 0.0001; // 10^{-5}
public static final int DEFAULT_VLDINTERVAL = 5;
public static final boolean DEFAULT_EARLYSTOP = false;
public static final int DEFAULT_EARLYSTOPCOUNT = 10;
public static final int DEFAULT_EPOCHS = 100;
public static final double DEFAULT_TARGETERROR = 0.0;
public static final boolean DEFAULT_ONLINE = true;
public static final boolean DEFAULT_PERMUTE = true;
/**
* Containing the permutation of the trainset.
*/
private int[] permutation = null;
/**
* Do online or offline sampling?
*/
private boolean online = DEFAULT_ONLINE;
/**
* Learning rate.
*/
private double mu = DEFAULT_MU;
/**
* Mommentum factor.
*/
private double alpha = DEFAULT_ALPHA;
/**
* Validation interval.
*/
private int validint = 1;
/**
* Use early stopping?
*/
private boolean earlystop = DEFAULT_EARLYSTOP;
/**
* Early stopping count.
*/
private int earlystopcount = DEFAULT_EARLYSTOPCOUNT;
/**
* Permute training set?
*/
private boolean permute = DEFAULT_PERMUTE;
/**
* Weights vector of the reference network.
*/
private double[] weights = null;
/**
* Number of weights of the reference network.
*/
private int weightsnum = 0;
/**
* The last weight differences.
*/
private double[] dweightslast = null;
/**
* The current weight differences.
*/
private double[] dweights = null;
/**
* The links of the reference network.
*/
private int[] links = null;
/**
* The number of links.
*/
private int linksnum = 0;
/*
// # DEBUG #
private double[] deltasdbg;
private double[] deltasindbg;
private double[] weightsdbg;
// #
*/
/**
* Creates an instance of GradientDescent.
*/
public GradientDescent() {
//
this.validint = DEFAULT_VLDINTERVAL;
this.targeterror = DEFAULT_TARGETERROR;
}
/**
* {@inheritDoc}
*/
@Override
public void reset() {
//
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder out = new StringBuilder();
//
out.append("permute : " + this.permute + "\n");
out.append("online: : " + this.online + "\n");
out.append("targeterror : " + this.targeterror + "\n");
out.append("epochs : " + this.epochs + "\n");
out.append("learningrate : " + this.mu + "\n");
out.append("momentum : " + this.alpha + "\n");
out.append("validationinterval : " + this.validint + "\n");
out.append("earlystopping : " + this.earlystop + "\n");
out.append("earlystoppingcount : " + this.earlystopcount + "\n");
//
return super.toString() + out.toString();
}
/**
* Returns of the weights are updated online or offline.
*/
public boolean getOnline() {
return this.online;
}
/**
* Sets if to update weights online or offline.
*/
public void setOnline(final boolean value) {
this.online = value;
}
/**
* Returns if to permute the training set.
*/
public boolean getPermute() {
return this.permute;
}
/**
* Sets if to permute the trianing set.
* @param value Value as boolean.
*/
public void setPermute(final boolean value) {
this.permute = value;
}
/**
* Returns validation interval.
*/
public int getValidationInterval() {
return this.validint;
}
/**
* Sets validation interval.
* @param value Valuie as int.
*/
public void setValidationInterval(final int value) {
this.validint = Math.max(1, value);
}
/**
* Return if to use early stopping.
*/
public boolean getEarlyStopping() {
return this.earlystop;
}
/**
* Sets if to use early stopping.
* @param value Value as boolean.
*/
public void setEarlyStopping(final boolean value) {
this.earlystop = value;
}
/**
* Sets the number of misses before early stopping.
* @param value Value as int.
*/
public void setEarlyStoppingCount(final int value) {
this.earlystopcount = value;
}
/**
* Returns the learning rate.
*/
public final double getLearningRate() {
return this.mu;
}
/**
* Sets the learning rate.
* @param mu Value as double.
*/
public final void setLearningRate(final double mu) {
this.mu = mu;
}
/**
* Return the momentum factor.
* @return Value as double.
*/
public final double getMomentum() {
return this.alpha;
}
/**
* Sets the mumentum factor.
* @param alpha Value as double.
*/
public final void setMomentum(final double alpha) {
this.alpha = alpha;
}
/**
* {@inheritDoc}
*/
@Override
protected void init() {
super.init();
//
this.permutation = new int[this.trainset.size()];
for (int i = 0; i < this.permutation.length; i++) {
this.permutation[i] = i;
}
this.weights = this.net.getWeights();
this.dweights = new double[this.weights.length];
this.dweightslast = new double[this.weights.length];
//
this.weightsnum = net.getWeightsNum();
this.links = net.getLinks();
this.linksnum = net.getLinksNum();
//
this.epoch = 0;
this.validationerror = 0.0;
this.trainerror = 0.0;
//
}
/**
* Resets and current weight differences and stores them
* in history memory.
*/
private void resetWeightDiffs() {
//
// initialize weight diffs.
//
for (int i = 1; i <= this.weightsnum; i++) {
this.dweightslast[i] = this.dweights[i];
this.dweights[i] = 0.0;
}
}
/**
* Accumulates the weight differences for the given frame index (time index)
* and the current gradient results.
* @param frameidx Frame index (time index).
*/
private void accumulateWeightsDiffs(final int frameidx) {
//
// collect deltas * activations .
//
for (int t = 0; t <= frameidx; t++) {
//
final double[] outputs = this.net.getOutputBuffer(t);
final double[] deltas = this.net.getGradOutputBuffer(t);
//
/*
// # DEBUG #
final double[] deltasin = net.getGradInputBuffer(t);
for (int i = 0; i < deltas.length; i++) {
this.deltasdbg[i] += Math.abs(deltas[i]);
this.deltasindbg[i] += Math.abs(deltasin[i]);
}
// #
*/
int off = 0;
//
for (int i = 0; i < this.linksnum; i++) {
//
final int src = this.links[off + Link.IDX_SRC];
final int dst = this.links[off + Link.IDX_DST];
final int widx = this.links[off + Link.IDX_WEIGHT];
//
if (widx > 0) {
final double dk = deltas[dst];
final double xj = outputs[src];
//
final double dw = (dk * xj);
this.dweights[widx] += (dw);
}
//
off += Link.LINK_SIZE;
}
}
}
/**
* Finally computes the weight differences based on the accumulated
* values.
*/
private void computeWeightDiffs() {
//
// add momentum and multiply learning rate mu.
//
for (int i = 1; i <= this.weightsnum; i++) {
//
// calculate momentum.
//
final double mw = this.dweightslast[i] * this.alpha;
this.dweights[i] = (this.mu * this.dweights[i]) + mw;
}
}
/**
* Adjusts the weights.
*/
private void adjustWeights() {
//
for (int i = 1; i <= this.weightsnum; i++) {
//
this.weights[i] += this.dweights[i];
/*
// # DEBUG #
this.weightsdbg[i] += Math.abs(this.dweights[i]);
// #
*/
}
}
/**
* {@inheritDoc}
*/
@Override
synchronized
public void train() {
//
this.init();
//
this.notifyStarted();
//
// iterate epochs.
//
final SampleSet tset = this.trainset;
final int tsetsize = this.permutation.length;
//
int count = 0;
int nbetterctr = 0;
double[] minweights = this.net.getWeights().clone();
double minerror = Double.MAX_VALUE;
//
for (int i = 0; i < this.epochs; i++) {
this.epoch = i;
//
double epocherror = 0.0;
if (this.permute) {
IntTools.shuffle(this.permutation, this.rnd);
}
//
// do online or offline gradient descent?
//
if (this.online) {
//
// for all patterns in trainset.
//
for (int j = 0; j < tsetsize; j++) {
//
// determine permuted index and sample.
//
final int idx = this.permutation[j];
final Sample sample = tset.get(idx);
//
// compute forward pass.
//
this.net.reset();
final double err = NetTools.performForward(
this.net, sample, this.features
);
final int frameidx = this.net.getFrameIdx();
//
// compute backward pass.
//
NetTools.performBackward(this.net);
//
// compute weight differences and adjust weights.
//
this.resetWeightDiffs();
this.accumulateWeightsDiffs(frameidx);
this.computeWeightDiffs();
this.adjustWeights();
//
epocherror += err;
}
} else {
//
// for all patterns in trainset.
//
this.resetWeightDiffs();
for (int j = 0; j < tsetsize; j++) {
//
// determine permuted index and sample.
//
final int idx = this.permutation[j];
final Sample sample = tset.get(idx);
//
// compute forward pass.
//
this.net.reset();
final double err = NetTools.performForward(
this.net, sample, this.features
);
final int frameidx = this.net.getFrameIdx();
//
// compute backward pass.
//
NetTools.performBackward(this.net);
//
// compute weight differences and adjust weights.
//
this.accumulateWeightsDiffs(frameidx);
//
epocherror += err;
}
this.computeWeightDiffs();
this.adjustWeights();
}
//
epocherror = (epocherror / (double)tsetsize);
this.trainerror = epocherror;
//
if ((this.trainset == this.validationset) || (this.validationset == null)) {
this.validationerror = this.trainerror;
} else {
if ((i % this.validint) == 0) {
this.validationerror = NetTools.computeError(net, this.validationset);
}
}
//
if ((i % this.validint) == 0) {
if (this.validationerror < minerror) {
minerror = this.validationerror;
minweights = this.weights.clone();
nbetterctr = 0;
} else {
nbetterctr++;
}
}
//
this.notifyEpoch();
//
// early stopping.
//
if (nbetterctr > this.earlystopcount) {
if (this.earlystop) break;
}
if (this.validationerror < this.targeterror) {
break;
}
count++;
}
//
// take best weights.
//
if (count > 0) {
this.validationerror = minerror;
DoubleTools.copy(minweights, 1, this.weights, 1, this.weightsnum);
}
//
this.notifyFinished();
}
}
| 14,877 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
RandomSearch.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/training/RandomSearch.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.training;
import de.jannlab.data.SampleSet;
import de.jannlab.misc.DoubleTools;
import de.jannlab.tools.NetTools;
/**
* This class implements a simple RandomSearch learning algorithm.
* Per epoch a new random weight vector is generated and at the end
* of the training the best found vector will be kept.
* <br></br>
* @author Sebastian Otte
*
*/
public final class RandomSearch extends NetTrainer {
//
public static final double DEFAULT_LBD = -100.0;
public static final double DEFAULT_UBD = 100.0;
//
/**
* Lower bound of the random choice.
*/
private double lbd = DEFAULT_LBD;
/**
* Upper bound of the random choice.
*/
private double ubd = DEFAULT_UBD;
//
/**
* Weight vector of the reference network.
*/
private double[] weights = null;
/**
* Number of weights.
*/
private int weightsnum = 0;
/**
* Creates an instance of RandomSearch.
*/
public RandomSearch() {
//
}
/**
* {@inheritDoc}
*/
@Override
public void reset() {
//
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder out = new StringBuilder();
//
out.append("targeterror : " + this.targeterror + "\n");
out.append("epochs : " + this.epochs + "\n");
out.append("searchlbd : " + this.lbd + "\n");
out.append("searchubd : " + this.ubd + "\n");
//
return super.toString() + out.toString();
}
/**
* Returns the lower bound of the search space.
* @return Lower bound as double.
*/
public final double getSearchLbd() {
return this.lbd;
}
/**
* Sets the lower bound of the search space.
* @param value Lower bound as double.
*/
public final void setSearchLbd(final double value) {
this.lbd = value;
}
/**
* Sets the upper bound of the search space.
* @param value Upper bound as double.
*/
public final void setSearchUbd(final double value) {
this.ubd = value;
}
/**
* Returns the upper bound of the search space.
* @return Upper bound as double.
*/
public final double getSearchUbd() {
return this.ubd;
}
/**
* {@inheritDoc}
*/
@Override
protected void init() {
super.init();
//
this.weights = this.net.getWeights();
this.weightsnum = net.getWeightsNum();
//
this.epoch = 0;
this.validationerror = 0.0;
this.trainerror = 0.0;
//
}
/**
* {@inheritDoc}
*/
@Override
synchronized
public void train() {
//
this.init();
//
this.notifyStarted();
//
// iterate epochs.
//
final SampleSet tset = this.trainset;
//
double[] minweights = this.net.getWeights().clone();
double minerror = Double.MAX_VALUE;
int count = 0;
//
for (int i = 0; i < this.epochs; i++) {
this.epoch = i;
//
DoubleTools.fill(this.weights, 1, this.weightsnum, this.rnd, this.lbd, this.ubd);
double error = NetTools.computeError(this.net, tset);
//
this.trainerror = error;
this.validationerror = error;
//
if (error < minerror) {
minerror = error;
minweights = this.net.getWeights().clone();
}
//
this.notifyEpoch();
//
if (this.validationerror < this.targeterror) {
break;
}
count++;
}
//
// take best weights.
//
if (count > 0) {
this.trainerror = minerror;
this.validationerror = minerror;
DoubleTools.copy(minweights, 1, this.weights, 1, this.weightsnum);
}
//
this.notifyFinished();
}
}
| 4,993 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
NetTrainerListener.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/training/NetTrainerListener.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.training;
/**
* Instances of this interface can be used to access the training
* process of all NetTrainer implementations, e.g. for build
* lerning curves.
* <br></br>
* @author Sebastian Otte
*/
public interface NetTrainerListener {
/**
* Will be called when the training has just been started.
* <br></br>
* @param trainer The NetTrainer instance which has fired the event.
*/
public void started(final NetTrainer trainer);
/**
* Will be called after each epoch of training.
* <br></br>
* @param trainer The NetTrainer instance which has fired the event.
*/
public void epoch(final NetTrainer trainer);
/**
* Will be called after the training has been finished.
* <br></br>
* @param trainer The NetTrainer instance which has fired the event.
*/
public void finished(final NetTrainer trainer);
//
}
| 1,817 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
NetTrainer.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/training/NetTrainer.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.training;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import de.jannlab.Net;
import de.jannlab.data.SampleSet;
import de.jannlab.tools.Debug;
import de.jannlab.tools.DefaultNetTrainerListener;
import de.jannlab.training.NetTrainerListener;
import de.jannlab.training.exception.NetTrainerException;
/**
* This class is the base class for all Traininer classes,
* and contains general variables and methods which they are all sharing.
* <br></br>
* @author Sebastian Otte
*/
public abstract class NetTrainer {
/**
* A set of training samples.
*/
protected SampleSet trainset = null;
/**
* A set of validation samples.
*/
protected SampleSet validationset = null;
/**
* The reference network.
*/
protected Net net = null;
/**
* The intern random number generator.
*/
protected Random rnd = new Random(0L);
/**
* The target error.
*/
protected double targeterror = 0.0;
/**
* The number of epochs.
*/
protected int epochs = 100;
/**
* The current epoch.
*/
protected int epoch = 0;
/**
* The current training error.
*/
protected double trainerror = 0.0;
/**
* Gives a feature selection (null => select all)
*/
protected int[] features = null;
/**
* The current validation error.
*/
protected double validationerror = 0.0;
/**
* Returns the current training error.
* <br></br>
* @return Training error as double.
*/
public final double getTrainingError() {
return this.trainerror;
}
/**
* Returns the current validation error.
* @return Validation error as double.
*/
public final double getValidationError() {
return this.validationerror;
}
/**
* Returns the current training epoch.
* @return Epoch as int.
*/
public int getEpoch() {
return this.epoch;
}
/**
* A list of listeners.
*/
private List<NetTrainerListener> listener =
new LinkedList<NetTrainerListener>();
/**
* Add a NetTraininerListener to the list of listeners.
* <br></br>
* @param listener Instance of NetTrainerListener.
*/
public final void addListener(final NetTrainerListener listener) {
this.listener.add(listener);
}
/**
* Removes a given NetTrainerListener from the list of listeners.
* @param listener Instance of NetTrainerListener.
*/
public final void removeListener(final NetTrainerListener listener) {
this.listener.remove(listener);
}
/**
* Notifies all listeners that the current epoch has been finished.
*/
protected void notifyEpoch() {
for (NetTrainerListener listener : this.listener) {
listener.epoch(this);
}
}
/**
* Notifies all listeners that the training has been finished.
*/
protected void notifyFinished() {
for (NetTrainerListener listener : this.listener) {
listener.finished(this);
}
}
/**
* Notifies all listeners that the training has been started.
*/
protected void notifyStarted() {
for (NetTrainerListener listener : this.listener) {
listener.started(this);
}
}
/**
* Clears the list of listeners.
*/
public final void clearListener() {
this.listener.clear();
}
/**
* Resets the trainer (errors, states).
*/
public abstract void reset();
/**
* Initialization after before training.
*/
protected void init() {
//
this.check();
}
/**
* Check training configuration.
*/
protected void check() {
if (this.net == null) {
throw new NetTrainerException("No network given.");
}
if (this.trainset == null) {
throw new NetTrainerException("No trainset given.");
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder out = new StringBuilder();
//
out.append(this.getClass().getSimpleName() + "\n");
//
return out.toString();
}
/**
* Create an instance of NetTrainer.
*/
public NetTrainer() {
//
if (Debug.DEBUG) {
this.addListener(new DefaultNetTrainerListener());
}
}
/**
* Return the number of training epochs.
* @return Epochs as int.
*/
public final int getEpochs() {
return this.epochs;
}
/**
* Returns the current feature selection (null == select all features).
* @return Feature selection as int[].
*/
public final int[] getFeatures() {
return this.features;
}
/**
* Sets the current features selection (null == select all features).
* @param features Feature selection as int[].
*/
public final void setFeatures(final int[] features) {
this.features = features;
}
/**
* This the number of training epochs.
* @param epochs Training epochs as int.
*/
public final void setEpochs(final int epochs) {
this.epochs = epochs;
}
/**
* Returns the target error.
* @return Target error as double.
*/
public final double getTargetError() {
return this.targeterror;
}
/**
* Sets the target error.
* @param targeterror Target error as double.
*/
public final void setTargetError(final double targeterror) {
this.targeterror = targeterror;
}
/**
* Set the validation set.
* @param validationset Istance of SampleSet.
*/
public final void setValidationSet(final SampleSet validationset) {
this.validationset = validationset;
}
/**
* Returns the training set.
* @return Instance of SampleSet.
*/
public SampleSet getTrainingSet() {
return this.trainset;
}
/**
* Returns the validation set.
* @return Instance of SampleSet.
*/
public SampleSet getValidationSet() {
return this.validationset;
}
/**
* Sets the reference networks.
* @param net Instance of Net.
*/
public final void setNet(final Net net) {
this.net = net;
}
/**
* Returns the reference network.
* @return Instance of Net.
*/
public Net getNet() {
return this.net;
}
/**
* Returns the random number generator.
* @return Instance of Random.
*/
public Random getRnd() {
return this.rnd;
}
/**
* Sets the random number generator.
* @param rnd Instance of Random.
*/
public void setRnd(final Random rnd) {
this.rnd = rnd;
}
/**
* Sets the training set.
* @param trainset Instance of SampleSet.
*/
public final void setTrainingSet(final SampleSet trainset) {
this.trainset = trainset;
}
/**
* Forces the trainer to start the training process.
*/
public abstract void train();
}
| 8,068 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
NetTrainerException.java | /FileExtraction/Java_unseen/JANNLab_JANNLab/src/main/java/de/jannlab/training/exception/NetTrainerException.java | /*******************************************************************************
* JANNLab Neural Network Framework for Java
* Copyright (C) 2012-2013 Sebastian Otte
*
* 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 de.jannlab.training.exception;
import de.jannlab.exception.JANNLabException;
/**
* A special exception, which is thrown by NetTrainer instances.
* <br></br>
* @author Sebastian Otte
*/
public class NetTrainerException extends JANNLabException {
private static final long serialVersionUID = 2633408152951314316L;
public NetTrainerException(
final String msg
) {
super(msg);
}
public NetTrainerException(
final String msg,
final Throwable cause
) {
super(msg, cause);
}
public NetTrainerException() {};
}
| 1,492 | Java | .java | JANNLab/JANNLab | 31 | 14 | 3 | 2013-06-26T21:04:08Z | 2015-08-01T21:01:44Z |
Test.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/test/java/gyurix/test/Test.java | package gyurix.test;
import com.google.common.collect.Lists;
import gyurix.configfile.ConfigData;
import gyurix.configfile.ConfigFile;
import gyurix.configfile.DefaultSerializers;
import gyurix.nbt.NBTCompound;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import java.util.*;
import static gyurix.nbt.NBTTagType.tag;
/**
* Created by GyuriX on 2016. 07. 31..
*/
public class Test {
static Map.Entry<String, Double> entry;
static {
DefaultSerializers.init();
}
public static void main(String[] args) {
testMapEntry();
}
public static void testMapEntry() {
entry = new AbstractMap.SimpleEntry<>("Test / | / it", 1.5);
String kf = new ConfigData(new Test()).toString();
System.out.println(kf);
entry = null;
Test t = new ConfigFile(kf).data.deserialize(Test.class);
System.out.println(entry.getKey() + ": " + entry.getValue());
}
public static void testNBT() {
ConfigData cd = new ConfigData("String data");
cd.listData = new ArrayList<>();
cd.listData.add(new ConfigData("le1"));
cd.listData.add(new ConfigData("le2"));
ConfigData cd2 = new ConfigData();
cd2.mapData = new LinkedHashMap<>();
cd2.mapData.put(new ConfigData("key"), cd);
System.out.println(cd2);
ItemStack is = new ItemStack(Material.STONE);
NBTCompound compound = (NBTCompound) tag(new HashMap<>());
compound.put("byte", tag((byte) 1));
compound.put("short", tag((short) 1));
compound.put("int", tag(1));
compound.put("long", tag(1L));
compound.put("float", tag(1.0f));
compound.put("double", tag(1.0));
compound.put("string", tag("Some text"));
compound.put("byte[]", tag(new byte[]{1, 2, 3}));
compound.put("int[]", tag(new int[]{1, 2, 3}));
compound.put("List", tag(Lists.newArrayList(tag("First"), tag("Second"), tag("Third"))));
String s1 = new ConfigData(compound).toString();
NBTCompound compound2 = new ConfigFile(s1).data.deserialize(NBTCompound.class);
String s2 = new ConfigData(compound2).toString();
System.out.println("S1:\n" + s1 + "\n\n\nS2:\n" + s2 + "\n\n\nEquals: " + s1.equals(s2) + "\nCompounds equals: " + compound.equals(compound2));
//System.out.println(ChatTag.fromColoredText("null"));
}
}
| 2,263 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
NBTTag.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/nbt/NBTTag.java | package gyurix.nbt;
import gyurix.configfile.ConfigData;
import gyurix.configfile.ConfigSerialization;
import gyurix.protocol.utils.WrappedData;
import gyurix.spigotutils.NullUtils;
import io.netty.buffer.ByteBuf;
import java.lang.reflect.Type;
public interface NBTTag extends WrappedData {
void write(ByteBuf buf);
class NBTSerializer implements ConfigSerialization.Serializer {
@Override
public Object fromData(ConfigData data, Class paramClass, Type... paramVarArgs) {
String d[] = data.stringData.split(" ", 2);
data.stringData = d.length == 1 ? null : d[1];
NBTTagType type = NBTTagType.values()[Integer.valueOf(d[0])];
Class wrapperCl = type.getWrapperClass();
return type.makeTag(data.deserialize(wrapperCl == NBTPrimitive.class ? type.getDataClass() : wrapperCl));
}
@Override
public ConfigData postSerialize(Object o, ConfigData data) {
data.stringData = NBTTagType.of(o).ordinal() + " " + NullUtils.to0(data.stringData);
return data;
}
@Override
public ConfigData toData(Object obj, Type... paramVarArgs) {
Object o = obj instanceof NBTPrimitive ? ((NBTPrimitive) obj).getData() : obj;
ConfigData cd = ConfigData.serializeObject(o);
cd.stringData = NBTTagType.of(o).ordinal() + " " + NullUtils.to0(cd.stringData);
return cd;
}
}
}
| 1,356 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
NBTPrimitive.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/nbt/NBTPrimitive.java | package gyurix.nbt;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import gyurix.spigotlib.SU;
import io.netty.buffer.ByteBuf;
import lombok.Data;
import static gyurix.spigotlib.SU.utf8;
@Data
public class NBTPrimitive implements NBTTag, StringSerializable {
private Object data;
public NBTPrimitive() {
}
public NBTPrimitive setData(Object data) {
this.data = data;
return this;
}
@Override
public Object toNMS() {
try {
return NBTTagType.of(data).getNmsConstructor().newInstance(data);
} catch (Throwable e) {
SU.cs.sendMessage("§eError on converting " + data + " " + data.getClass() + " to NMS.");
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
}
public String toString() {
return data.toString();
}
public void write(ByteBuf buf) {
if (data instanceof byte[]) {
byte[] d = (byte[]) data;
buf.writeInt(d.length);
buf.writeBytes(d);
} else if (data instanceof int[]) {
int[] d = (int[]) data;
buf.writeInt(d.length);
for (int i : d)
buf.writeInt(i);
} else if (data instanceof String) {
String d = (String) data;
byte[] bytes = d.getBytes(utf8);
buf.writeShort(bytes.length);
buf.writeBytes(bytes);
} else if (data instanceof Byte)
buf.writeByte((byte) data);
else if (data instanceof Short)
buf.writeShort((short) data);
else if (data instanceof Integer)
buf.writeInt((int) data);
else if (data instanceof Long)
buf.writeLong((long) data);
else if (data instanceof Float)
buf.writeFloat((float) data);
else if (data instanceof Double)
buf.writeDouble((double) data);
}
}
| 1,726 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
NBTApi.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/nbt/NBTApi.java | package gyurix.nbt;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.SU;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import org.bukkit.entity.Entity;
import java.io.DataInputStream;
import java.lang.reflect.Method;
import static gyurix.nbt.NBTTagType.Compound;
import static gyurix.nbt.NBTTagType.tag;
import static gyurix.protocol.Reflection.getNMSClass;
import static gyurix.spigotlib.SU.utf8;
public final class NBTApi {
static Method entityFillNBTTag;
static Method getEntityHandle;
static Class nmsEntityClass;
static Method setEntityNBTData;
static {
getEntityHandle = Reflection.getMethod(Reflection.getOBCClass("entity.CraftEntity"), "getHandle");
nmsEntityClass = getNMSClass("Entity");
entityFillNBTTag = Reflection.getMethod(nmsEntityClass, "c", Compound.getNmsClass());
setEntityNBTData = Reflection.getMethod(nmsEntityClass, "f", Compound.getNmsClass());
}
public static NBTCompound getNbtData(Entity ent) {
try {
Object nmsEntity = getEntityHandle.invoke(ent);
Object tag = Compound.getNmsConstructor().newInstance();
entityFillNBTTag.invoke(nmsEntity, tag);
return (NBTCompound) Compound.makeTag(tag);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
}
public static String readString(DataInputStream bis) throws Throwable {
short s = bis.readShort();
byte[] d = new byte[s];
bis.read(d);
return new String(d, utf8);
}
public static NBTTag readTag(DataInputStream bis, byte type) throws Throwable {
switch (type) {
case 0:
return tag(null);
case 1:
return tag(bis.readByte());
case 2:
return tag(bis.readShort());
case 3:
return tag(bis.readInt());
case 4:
return tag(bis.readLong());
case 5:
return tag(bis.readFloat());
case 6:
return tag(bis.readDouble());
case 7: {
int len = bis.readInt();
byte[] ar = new byte[len];
bis.read(ar);
return tag(ar);
}
case 8:
return tag(readString(bis));
case 9: {
byte listType = bis.readByte();
int len = bis.readInt();
NBTList out = new NBTList();
if (listType == 0 || len == 0)
return out;
for (int i = 0; i < len; ++i)
out.add(readTag(bis, listType));
return out;
}
case 10: {
NBTCompound out = new NBTCompound();
while (true) {
byte compType = bis.readByte();
if (compType == 0)
return out;
out.put(readString(bis), readTag(bis, compType));
}
}
case 11: {
int len = bis.readInt();
int[] ar = new int[len];
for (int i = 0; i < len; ++i)
ar[i] = bis.readInt();
return tag(ar);
}
}
throw new RuntimeException("§cUnknown NBT tag type - " + type);
}
public static ByteBuf save(String title, NBTCompound comp) {
ByteBuf buf = ByteBufAllocator.DEFAULT.heapBuffer();
buf.writeByte(10);
buf.writeShort(title.length());
buf.writeBytes(title.getBytes());
comp.write(buf);
return buf;
}
public static void setNbtData(Entity ent, NBTCompound data) {
try {
Object nmsEntity = getEntityHandle.invoke(ent);
setEntityNBTData.invoke(nmsEntity, data.toNMS());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 3,479 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
NBTTagType.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/nbt/NBTTagType.java | package gyurix.nbt;
import gyurix.protocol.Primitives;
import gyurix.protocol.Reflection;
import lombok.Getter;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static gyurix.protocol.Reflection.getNMSClass;
@Getter
public enum NBTTagType {
End(void.class),
Byte(byte.class),
Short(short.class),
Int(int.class),
Long(long.class),
Float(float.class),
Double(double.class),
ByteArray(byte[].class),
String(String.class),
List(List.class, NBTList.class, NBTTag.class),
Compound(Map.class, NBTCompound.class, String.class, NBTTag.class),
IntArray(int[].class),
LongArray(long[].class);
private static final HashMap<Class, NBTTagType> classes = new HashMap<>();
@Getter
private static final Field nmsListTypeField;
static {
for (NBTTagType t : values()) {
classes.put(t.dataClass, t);
classes.put(t.nmsClass, t);
classes.put(t.wrapperClass, t);
}
nmsListTypeField = Reflection.getField(List.nmsClass, "type");
}
private final Type[] dataTypes;
private final Class nmsClass, dataClass, wrapperClass;
private final Constructor nmsConstructor;
private final Field nmsDataField;
NBTTagType(Class dataCl) {
this(dataCl, NBTPrimitive.class);
}
NBTTagType(Class dataCl, Class wrapperCl, Type... types) {
dataClass = dataCl;
nmsClass = getNMSClass("NBTTag" + name());
wrapperClass = wrapperCl;
dataTypes = types;
Constructor nmsConst = Reflection.getConstructor(nmsClass, dataClass);
if (nmsConst == null)
nmsConst = Reflection.getConstructor(nmsClass);
nmsConstructor = nmsConst;
nmsDataField = Reflection.getFirstFieldOfType(nmsClass, dataClass);
}
public static NBTTagType of(Object o) {
if (o == null)
return null;
if (o instanceof NBTPrimitive)
o = ((NBTPrimitive) o).getData();
if (o instanceof Map)
return Compound;
if (o instanceof Iterable || o.getClass().isArray())
return List;
return classes.get(Primitives.unwrap(o.getClass()));
}
public static NBTTag tag(Object o) {
NBTTagType type = of(o);
return type.makeTag(o);
}
public NBTTag makeTag(Object o) {
try {
if (o == null)
return null;
if (o instanceof NBTTag)
return (NBTTag) o;
if (o.getClass().getName().startsWith("net.minecraft"))
o = nmsDataField.get(o);
NBTTag tag = (NBTTag) wrapperClass.newInstance();
if (tag instanceof NBTPrimitive)
((NBTPrimitive) tag).setData(o);
else if (tag instanceof NBTList) {
NBTList list = (NBTList) tag;
if (o.getClass().isArray()) {
int len = Array.getLength(o);
for (int i = 0; i < len; ++i) {
Object o2 = Array.get(o, i);
list.add(of(o2).makeTag(o2));
}
} else
for (Object o2 : (Iterable) o)
list.add(of(o2).makeTag(o2));
} else {
NBTCompound cmp = (NBTCompound) tag;
for (Map.Entry<String, Object> e : ((Map<String, Object>) o).entrySet())
cmp.put(e.getKey(), of(e.getValue()).makeTag(e.getValue()));
}
return tag;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
}
| 3,370 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
NBTCompound.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/nbt/NBTCompound.java | package gyurix.nbt;
import gyurix.spigotlib.SU;
import io.netty.buffer.ByteBuf;
import java.lang.String;
import java.util.HashMap;
import java.util.Map;
import static gyurix.nbt.NBTTagType.*;
import static gyurix.spigotlib.SU.utf8;
public class NBTCompound extends HashMap<String, NBTTag> implements NBTTag {
public NBTCompound() {
super();
}
public boolean getBoolean(String key) {
NBTTag tag = get(key);
return tag instanceof NBTPrimitive && ((NBTPrimitive) tag).getData().toString().equals("1");
}
public NBTCompound getCompound(String key) {
NBTTag tag = get(key);
if (!(tag instanceof NBTCompound)) {
tag = new NBTCompound();
put(key, tag);
}
return (NBTCompound) tag;
}
public NBTList getList(String key) {
NBTTag tag = get(key);
if (!(tag instanceof NBTList)) {
tag = new NBTList();
put(key, tag);
}
return (NBTList) tag;
}
public NBTCompound set(String key, Object value) {
if (value == null) {
remove(key);
} else {
put(key, tag(value));
}
return this;
}
@Override
public Object toNMS() {
try {
Object tag = Compound.getNmsConstructor().newInstance();
Map m = (Map) Compound.getNmsDataField().get(tag);
for (Entry<String, NBTTag> e : entrySet())
m.put(e.getKey(), e.getValue().toNMS());
return tag;
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Entry<String, NBTTag> e : entrySet()) {
sb.append("\n\u00a7e").append(e.getKey()).append(":\u00a7b ").append(e.getValue());
}
return sb.length() == 0 ? "{}" : "{" + sb.substring(1) + "}";
}
public void write(ByteBuf buf) {
for (Map.Entry<String, NBTTag> e : entrySet()) {
buf.writeByte(of(e.getValue()).ordinal());
byte[] a = e.getKey().getBytes(utf8);
buf.writeShort(a.length);
buf.writeBytes(a);
e.getValue().write(buf);
}
buf.writeByte(0);
}
}
| 2,073 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
NBTList.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/nbt/NBTList.java | package gyurix.nbt;
import io.netty.buffer.ByteBuf;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import static gyurix.nbt.NBTTagType.List;
public class NBTList extends ArrayList<NBTTag> implements NBTTag {
public NBTList() {
}
@Override
public Object toNMS() {
try {
Object o = List.getNmsClass().newInstance();
ArrayList<Object> l = new ArrayList<>();
for (NBTTag t : this)
l.add(t.toNMS());
List.getNmsDataField().set(o, l);
if (!l.isEmpty())
NBTTagType.getNmsListTypeField().set(o, (byte) NBTTagType.of(l.get(0)).ordinal());
return o;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
public String toString() {
return "[§b" + StringUtils.join(this, ", §b") + "§b]";
}
@Override
public void write(ByteBuf buf) {
if (isEmpty()) {
buf.writeByte(0);
buf.writeInt(0);
return;
}
buf.writeByte(NBTTagType.of(get(0)).ordinal());
buf.writeInt(size());
for (NBTTag nbtTag : this)
nbtTag.write(buf);
}
}
| 1,092 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
PagedConfig.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/inventory/PagedConfig.java | package gyurix.inventory;
import org.bukkit.inventory.ItemStack;
/**
* Created by GyuriX on 2016. 09. 17..
*/
public class PagedConfig extends GUIConfig {
public StaticItem back, previous, next;
public ItemStack element;
}
| 231 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
BooleanItem.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/inventory/BooleanItem.java | package gyurix.inventory;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import static gyurix.spigotutils.ItemUtils.fillVariables;
/**
* Created by GyuriX on 2016. 09. 17..
*/
public class BooleanItem {
public int slot;
public ItemStack yes, no;
public void set(Inventory inv, boolean value) {
inv.setItem(slot, value ? yes : no);
}
public void set(Inventory inv, boolean value, Object... vars) {
inv.setItem(slot, fillVariables(value ? yes : no, vars));
}
}
| 517 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
CustomGUI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/inventory/CustomGUI.java | package gyurix.inventory;
import org.bukkit.entity.Player;
public abstract class CustomGUI extends CloseableGUI {
public CustomGUI(Player plr) {
super(plr);
}
public abstract void onClick(int slot, boolean right, boolean shift);
}
| 244 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
GUIConfig.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/inventory/GUIConfig.java | package gyurix.inventory;
import gyurix.spigotlib.SU;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import static gyurix.spigotutils.ItemUtils.fillVariables;
public class GUIConfig {
public HashMap<Integer, ItemStack> items = new HashMap<>();
public ItemStack separator;
public int size;
public String title;
public Inventory getInventory(int size, CustomGUI gui, Object... vars) {
return getInventory(size, (InventoryHolder) gui, vars);
}
public Inventory getInventory(int size, InventoryHolder holder, Object... vars) {
size = (size + 8) / 9 * 9;
Inventory inv = Bukkit.createInventory(holder, size, SU.fillVariables(title, vars));
ItemStack sep = fillVariables(separator, vars);
for (int i = 0; i < size; i++) {
ItemStack is = items.get(i);
inv.setItem(i, is == null ? sep : fillVariables(is, vars));
}
return inv;
}
public Inventory getInventory(InventoryHolder holder, Object... vars) {
return getInventory(size, holder, vars);
}
public Inventory getInventory(CustomGUI gui, Object... vars) {
return getInventory((InventoryHolder) gui, vars);
}
}
| 1,261 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
StaticItem.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/inventory/StaticItem.java | package gyurix.inventory;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import gyurix.spigotutils.ItemUtils;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import static gyurix.spigotutils.ItemUtils.fillVariables;
/**
* Created by GyuriX on 2016. 09. 17..
*/
public class StaticItem implements StringSerializable {
public ItemStack item;
public int slot;
public StaticItem(String in) {
String[] s = in.split(" ", 2);
slot = Integer.valueOf(s[0]);
item = ItemUtils.stringToItemStack(s[1]);
}
public void set(Inventory inv) {
inv.setItem(slot, item == null ? null : item.clone());
}
public void set(Inventory inv, Object... vars) {
inv.setItem(slot, fillVariables(item, vars));
}
@Override
public String toString() {
return slot + " " + ItemUtils.itemToString(item);
}
}
| 874 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
CloseableGUI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/inventory/CloseableGUI.java | package gyurix.inventory;
import gyurix.spigotlib.SU;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.plugin.Plugin;
public class CloseableGUI implements InventoryHolder {
protected Inventory inv;
protected Player plr;
protected RuntimeException firstClose;
@Getter
@Setter
private boolean forceClose;
public CloseableGUI(Player plr) {
this.plr = plr;
}
public static void cancel(Plugin pl) {
for (Player p : Bukkit.getOnlinePlayers()) {
Inventory inv = p.getOpenInventory().getTopInventory();
if (inv != null && inv.getHolder() instanceof CloseableGUI) {
CloseableGUI gui = (CloseableGUI) inv.getHolder();
if (pl == gui.getPlugin()) {
gui.setForceClose(true);
p.closeInventory();
}
}
}
}
public final void close() {
if (firstClose != null) {
SU.cs.sendMessage("§cDetected double closed GUI:");
String pln = getPlugin().getName();
SU.error(SU.cs, firstClose, pln, "gyurix");
SU.error(SU.cs, new RuntimeException("Second close"), pln, "gyurix");
return;
}
firstClose = new RuntimeException("First close");
if (forceClose)
onForceClose();
else
onClose();
}
@Override
public Inventory getInventory() {
return inv;
}
public Player getPlayer() {
return plr;
}
public Plugin getPlugin() {
return SU.getPlugin(getClass());
}
protected void onClose() {
}
protected void onForceClose() {
}
}
| 1,645 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
TradeAPI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/inventory/trade/TradeAPI.java | package gyurix.inventory.trade;
import com.google.common.collect.Lists;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.Main;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.EntityUtils;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.MerchantInventory;
import org.bukkit.inventory.MerchantRecipe;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
/**
* An API for managing NPC trade menus
*/
public class TradeAPI implements Listener {
/**
* An instance of the AIR material, feel free to use it anywhere, just do NOT modify it
*/
public static final ItemStack air = new ItemStack(Material.AIR);
private static Class cmrCl = Reflection.getOBCClass("inventory.CraftMerchantRecipe");
private static Constructor cmrC = Reflection.getConstructor(cmrCl, ItemStack.class, int.class, int.class, boolean.class);
private static Class humanCl = Reflection.getNMSClass("EntityHuman");
private static Class imc = Reflection.getNMSClass("IMerchant");
private static Field ingredientsF = Reflection.getField(MerchantRecipe.class, "ingredients");
private static Method openTradeM = Reflection.getMethod(humanCl, "openTrade", imc);
private static Method toMinecraftM = Reflection.getMethod(cmrCl, "toMinecraft");
/**
* Initializes the TradeAPI, do NOT use this method
*/
public TradeAPI() {
SU.pm.registerEvents(this, Main.pl);
}
/**
* Creates a not acceptable (crossed arrow) MerchantRecipe from the given items
*
* @param items - no items = empty recipe, 1. item = output slot, 2. item = first slot, 3. item = second slot, there
* are no required amount of given items, this method works with 0,1,2 and 3 arguments too.
* @return The generated recipe
*/
public static MerchantRecipe makeDeniedRecipe(ItemStack... items) {
MerchantRecipe mr = new MerchantRecipe((items.length == 0 || items[0] == null) ? air : items[0], 1, 0, false);
if (items.length > 1)
mr.addIngredient(items[1] == null ? air : items[1]);
else
mr.addIngredient(air);
if (items.length > 2)
mr.addIngredient(items[2] == null ? air : items[2]);
return mr;
}
/**
* Creates an acceptable MerchantRecipe from the given items
*
* @param items - no items = empty recipe, 1. item = output slot, 2. item = first slot, 3. item = second slot, there
* are no required amount of given items, this method works with 0,1,2 and 3 arguments too.
* @return The generated recipe
*/
public static MerchantRecipe makeRecipe(ItemStack... items) {
MerchantRecipe mr = new MerchantRecipe((items.length == 0 || items[0] == null) ? air : items[0], 0, 10000, false);
if (items.length > 1)
mr.addIngredient(items[1] == null ? air : items[1]);
else
mr.addIngredient(air);
if (items.length > 2)
mr.addIngredient(items[2] == null ? air : items[2]);
return mr;
}
/**
* Opens a TradeGUI for the given player
*
* @param plr - The TradeGUI receiver player
* @param title - The title of the TradeGUI
* @param recipes - The recipes shown in the GUI
* @return The opened TradeGUI
*/
public static MerchantInventory openGUI(final Player plr, String title, MerchantRecipe... recipes) {
return openGUI(plr, title, Lists.newArrayList(recipes));
}
/**
* Opens a TradeGUI for the given player
*
* @param plr - The TradeGUI receiver player
* @param title - The title of the TradeGUI
* @param recipes - The recipes shown in the GUI
* @return The opened TradeGUI
*/
public static MerchantInventory openGUI(final Player plr, String title, Iterable<MerchantRecipe> recipes) {
try {
Object nmsPlr = EntityUtils.getNMSEntity(plr);
IMerchantHook imh = new IMerchantHook(nmsPlr, title);
Object im = Proxy.newProxyInstance(nmsPlr.getClass().getClassLoader(), new Class[]{imc}, imh);
ArrayList<Object> mrl = imh.offers;
for (MerchantRecipe r : recipes)
mrl.add(toNMSMerchantRecipe(r));
openTradeM.invoke(nmsPlr, im);
return (MerchantInventory) plr.getOpenInventory().getTopInventory();
} catch (Throwable e) {
SU.error(SU.cs, e, "MythaliumCore", "mythalium");
}
return null;
}
public static Object toNMSMerchantRecipe(MerchantRecipe r) {
try {
Object cmr = cmrC.newInstance(r.getResult(), r.getUses(), r.getMaxUses(), false);
ingredientsF.set(cmr, ingredientsF.get(r));
return toMinecraftM.invoke(cmr);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
}
| 4,819 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
IMerchantHook.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/inventory/trade/IMerchantHook.java | package gyurix.inventory.trade;
import gyurix.chat.ChatTag;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.SU;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
/**
* Hook, which implements IMerchant interface
*/
class IMerchantHook implements InvocationHandler {
private static final Class mrlC = Reflection.getNMSClass("MerchantRecipeList");
private final String displayName;
public ArrayList<Object> offers;
public Object player;
IMerchantHook(Object player, String title) {
this.player = player;
displayName = title;
try {
offers = (ArrayList<Object>) mrlC.newInstance();
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
switch (method.getName()) {
case "t_":
return player;
case "setTradingPlayer":
player = args[0];
return null;
case "getScoreboardDisplayName":
return new ChatTag(displayName).toICBC();
case "getOffers":
return offers;
}
return null;
}
}
| 1,178 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
CommandBlockGUI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/datareader/CommandBlockGUI.java | package gyurix.datareader;
import gyurix.json.JsonAPI;
import gyurix.nbt.NBTCompound;
import gyurix.protocol.Protocol;
import gyurix.protocol.event.PacketInEvent;
import gyurix.protocol.event.PacketInType;
import gyurix.protocol.utils.BlockLocation;
import gyurix.protocol.wrappers.inpackets.PacketPlayInCustomPayload;
import gyurix.protocol.wrappers.outpackets.PacketPlayOutBlockChange;
import gyurix.protocol.wrappers.outpackets.PacketPlayOutTileEntityData;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.BlockData;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import java.util.function.Consumer;
import static gyurix.spigotlib.Main.pl;
import static gyurix.spigotlib.SU.tp;
/**
* SignGUI, which can be used
*/
public class CommandBlockGUI extends DataReader<String> {
private final BlockLocation bl;
private final String[] initialLines;
private final Location loc;
private final Protocol.PacketInListener dig = this::onDig;
private int rid = -1;
private final Protocol.PacketInListener click = this::onClick;
public CommandBlockGUI(Player player, Consumer<String> onResult) {
this(player, onResult, new String[]{"", ""});
}
public CommandBlockGUI(Player plr, Consumer<String> onResult, String[] initialLines) {
super(plr, onResult);
this.initialLines = initialLines;
loc = plr.getLocation();
loc.setX(loc.getBlockX() + 0.5);
loc.setY(loc.getBlockY());
loc.setZ(loc.getBlockZ() + 0.5);
bl = new BlockLocation(loc);
showCmdBlock();
tp.registerIncomingListener(pl, this, PacketInType.CustomPayload);
tp.registerIncomingListener(pl, dig, PacketInType.BlockDig);
tp.registerIncomingListener(pl, click, PacketInType.BlockPlace);
}
@Override
public boolean cancel() {
if (super.cancel()) {
System.out.println("Cancelled.");
SU.sch.cancelTask(rid);
SU.tp.unregisterIncomingListener(click);
SU.tp.unregisterIncomingListener(dig);
return true;
}
return false;
}
@Override
protected boolean onPacket(Object packet) {
PacketPlayInCustomPayload p = new PacketPlayInCustomPayload();
p.loadVanillaPacket(packet);
if (!p.channel.equals("MC|AdvCdm"))
return false;
String msg = new String(p.data, 14, p.data.length - 15);
onResult(msg);
return true;
}
public void hideCmdBlock() {
Player plr = getPlayer();
plr.teleport(loc);
for (int x = -1; x <= 1; ++x) {
for (int y = -1; y <= 2; ++y) {
for (int z = -1; z <= 1; ++z) {
Block b = getPlayer().getWorld().getBlockAt(bl.x + x, bl.y + y, bl.z + z);
tp.sendPacket(plr, new PacketPlayOutBlockChange(new BlockLocation(bl.x + x, bl.y + y, bl.z + z), new BlockData(b)));
}
}
}
rid = SU.sch.scheduleSyncRepeatingTask(pl, () -> {
double dist = plr.getLocation().distance(loc);
if (dist > 0)
cancel();
}, 5, 5);
}
private void onClick(PacketInEvent e) {
if (e.getPlayer() != getPlayer())
return;
e.setCancelled(true);
SU.sch.scheduleSyncDelayedTask(pl, this::hideCmdBlock);
}
private void onDig(PacketInEvent e) {
if (e.getPlayer() != getPlayer())
return;
e.setCancelled(true);
SU.sch.scheduleSyncDelayedTask(pl, this::showCmdBlock);
}
public void showCmdBlock() {
Player plr = getPlayer();
plr.teleport(loc);
NBTCompound nbt = new NBTCompound();
nbt.set("Command", initialLines[0]);
nbt.set("LastOutput", "\"" + JsonAPI.escape(initialLines[1]) + "\"");
for (int x = -1; x <= 1; ++x) {
for (int y = -1; y <= 2; ++y) {
for (int z = -1; z <= 1; ++z) {
if (x == 0 && y == 0 && z == 0 || x == 0 && y == 1 && z == 0) {
tp.sendPacket(plr, new PacketPlayOutBlockChange(new BlockLocation(bl.x + x, bl.y + y, bl.z + z), new BlockData(Material.AIR)));
} else {
tp.sendPacket(plr, new PacketPlayOutBlockChange(new BlockLocation(bl.x + x, bl.y + y, bl.z + z), new BlockData(Material.COMMAND_BLOCK)));
tp.sendPacket(plr, new PacketPlayOutTileEntityData(new BlockLocation(bl.x + x, bl.y + y, bl.z + z), 2, nbt));
}
}
}
}
}
}
| 4,251 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
SignGUI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/datareader/SignGUI.java | package gyurix.datareader;
import gyurix.chat.ChatTag;
import gyurix.protocol.Reflection;
import gyurix.protocol.event.PacketInType;
import gyurix.protocol.utils.BlockLocation;
import gyurix.protocol.wrappers.inpackets.PacketPlayInUpdateSign;
import gyurix.protocol.wrappers.outpackets.PacketPlayOutBlockChange;
import gyurix.protocol.wrappers.outpackets.PacketPlayOutOpenSignEditor;
import gyurix.protocol.wrappers.outpackets.PacketPlayOutUpdateSign;
import gyurix.spigotutils.BlockData;
import gyurix.spigotutils.ServerVersion;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import java.util.function.Consumer;
import static gyurix.chat.ChatTag.fromColoredText;
import static gyurix.spigotlib.Main.pl;
import static gyurix.spigotlib.SU.tp;
/**
* SignGUI, which can be used
*/
public class SignGUI extends DataReader<String[]> {
private final Block b;
private final BlockLocation bl;
/**
* Opens a new SignGUI to the given player with empty lines
*
* @param plr - Player to which the SignGUI should be opened
* @param resultConsumer - The consumer of the result
*/
public SignGUI(Player plr, Consumer<String[]> resultConsumer) {
this(plr, resultConsumer, new String[]{"", "", "", ""});
}
/**
* Opens a new SignGUI to the given player with the given default lines
*
* @param plr - Player to which the SignGUI should be opened
* @param resultConsumer - The consumer of the result
* @param initialLines - Default lines of the sign
*/
public SignGUI(Player plr, Consumer<String[]> resultConsumer, String[] initialLines) {
super(plr, resultConsumer);
bl = new BlockLocation(plr.getLocation().getBlockX(), 255, plr.getLocation().getBlockZ());
b = bl.getBlock(plr.getWorld());
tp.sendPacket(plr, new PacketPlayOutBlockChange(bl, new BlockData(Material.valueOf(Reflection.ver.isAbove(ServerVersion.v1_13) ? "OAK_SIGN" : "SIGN_POST"))));
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
tp.sendPacket(plr, new PacketPlayOutUpdateSign(bl, new ChatTag[]{
fromColoredText(initialLines[0]), fromColoredText(initialLines[1]),
fromColoredText(initialLines[2]), fromColoredText(initialLines[3])}));
tp.registerIncomingListener(pl, this, PacketInType.UpdateSign);
tp.sendPacket(plr, new PacketPlayOutOpenSignEditor(bl));
}
@Override
protected boolean onPacket(Object packet) {
PacketPlayInUpdateSign p = new PacketPlayInUpdateSign();
p.loadVanillaPacket(packet);
String[] res = new String[4];
for (int i = 0; i < 4; ++i)
res[i] = p.lines[i].toColoredString();
tp.sendPacket(getPlayer(), new PacketPlayOutBlockChange(bl, new BlockData(b)).getVanillaPacket());
onResult(res);
return true;
}
}
| 2,856 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
DataReader.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/datareader/DataReader.java | package gyurix.datareader;
import gyurix.protocol.Protocol;
import gyurix.protocol.event.PacketInEvent;
import gyurix.spigotlib.SU;
import lombok.Getter;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.util.HashMap;
import java.util.function.Consumer;
public abstract class DataReader<T> implements Protocol.PacketInListener {
private static final HashMap<String, DataReader> open = new HashMap<>();
private final Consumer<T> onResult;
@Getter
private final Player player;
protected DataReader(Player player, Consumer<T> onResult) {
cancel(player);
this.player = player;
this.onResult = onResult;
open.put(player.getName(), this);
}
public static boolean cancel(Plugin plugin) {
open.values().removeIf((dr) -> {
if (SU.getPlugin(dr.onResult.getClass()) == plugin) {
SU.tp.unregisterIncomingListener(dr);
return true;
}
return false;
});
return false;
}
public static boolean cancel(Player plr) {
DataReader dr = open.get(plr.getName());
if (dr != null) {
dr.cancel();
return true;
}
return false;
}
public boolean cancel() {
DataReader dr = open.remove(getPlayer().getName());
if (dr == null)
return false;
SU.tp.unregisterIncomingListener(this);
return true;
}
protected abstract boolean onPacket(Object packet);
@Override
public void onPacketIN(PacketInEvent e) {
if (e.getPlayer() != player)
return;
if (onPacket(e.getPacket()))
e.setCancelled(true);
}
public void onResult(T result) {
SU.sch.scheduleSyncDelayedTask(SU.getPlugin(onResult.getClass()), () -> {
try {
cancel();
onResult.accept(result);
} catch (Throwable e) {
SU.error(SU.cs, e, SU.getPlugin(onResult.getClass()).getName(), "gyurix");
}
});
}
}
| 1,871 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ChatGUI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/datareader/ChatGUI.java | package gyurix.datareader;
import gyurix.protocol.event.PacketInType;
import gyurix.protocol.wrappers.inpackets.PacketPlayInChat;
import gyurix.spigotlib.ChatAPI;
import org.bukkit.entity.Player;
import java.util.function.Consumer;
import static gyurix.spigotlib.Main.pl;
import static gyurix.spigotlib.SU.tp;
public class ChatGUI extends DataReader<String> {
public ChatGUI(Player player, String msg, Consumer<String> onResult) {
super(player, onResult);
if (msg != null)
ChatAPI.sendJsonMsg(ChatAPI.ChatMessageType.SYSTEM, msg, player);
tp.registerIncomingListener(pl, this, PacketInType.Chat);
}
@Override
protected boolean onPacket(Object packet) {
PacketPlayInChat p = new PacketPlayInChat();
p.loadVanillaPacket(packet);
onResult(p.message);
return true;
}
}
| 814 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
StringReader.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/json/StringReader.java | package gyurix.json;
public class StringReader {
public int id;
public char[] str;
public StringReader(String in) {
str = in.toCharArray();
}
public boolean hasNext() {
return id < str.length;
}
public char last() {
return str[id - 1];
}
public char next() {
return str[id++];
}
}
| 323 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
JsonAPI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/json/JsonAPI.java | package gyurix.json;
import com.google.common.primitives.Primitives;
import gyurix.configfile.ConfigSerialization;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import gyurix.configfile.DefaultSerializers;
import gyurix.protocol.Reflection;
import gyurix.spigotlib.SU;
import java.lang.reflect.*;
import java.util.*;
import java.util.Map.Entry;
import static gyurix.protocol.Reflection.newInstance;
import static gyurix.spigotlib.Config.debug;
public class JsonAPI {
public static final Type[] emptyTypeArray = new Type[0];
public static int HextoDec(char c) {
return c >= '0' && c <= '9' ? c - 48 : c >= 'A' && c <= 'F' ? c - 55 : c - 87;
}
private static Object deserialize(Object parent, StringReader in, Class cl, Type... params) throws Throwable {
cl = Primitives.wrap(cl);
char c = '-';
if (in.hasNext())
c = in.next();
else in.id++;
if (Map.class.isAssignableFrom(cl)) {
if (cl.isInterface())
cl = ConfigSerialization.getInterfaceBasedClasses().get(cl);
if (c != '{') {
throw new Throwable("JSONAPI: Error on deserializing Json " + new String(in.str) + ", expected {, found " + c + " (character id: " + in.id + ")");
}
Class keyClass = (Class) (params[0] instanceof ParameterizedType ? ((ParameterizedType) params[0]).getRawType() : params[0]);
Type[] keyType = params[0] instanceof ParameterizedType ? ((ParameterizedType) params[0]).getActualTypeArguments() : emptyTypeArray;
Class valueClass = (Class) (params[1] instanceof ParameterizedType ? ((ParameterizedType) params[1]).getRawType() : params[1]);
Type[] valueType = params[1] instanceof ParameterizedType ? ((ParameterizedType) params[1]).getActualTypeArguments() : emptyTypeArray;
Map map = cl == EnumMap.class ? new EnumMap<>(keyClass) : (Map) cl.newInstance();
if (in.next() == '}')
return map;
else
in.id -= 2;
while (in.next() != '}') {
Object key = deserialize(map, in, keyClass, keyType);
if (in.next() != ':')
throw new Throwable("JSONAPI: Error on deserializing Json " + new String(in.str) + ", expected :, found " + in.last() + " (character id: " + (in.id - 1) + ")");
map.put(key, deserialize(map, in, valueClass, valueType));
}
return map;
} else if (Collection.class.isAssignableFrom(cl)) {
if (cl.isInterface())
cl = ConfigSerialization.getInterfaceBasedClasses().get(cl);
if (c != '[') {
throw new Throwable("JSONAPI: Error on deserializing Json " + new String(in.str) + ", expected {, found " + c + " (character id: " + in.id + ")");
}
Class dataClass = (Class) (params[0] instanceof ParameterizedType ? ((ParameterizedType) params[0]).getRawType() : params[0]);
Type[] dataType = params[0] instanceof ParameterizedType ? ((ParameterizedType) params[0]).getActualTypeArguments() : emptyTypeArray;
Collection col = (Collection) cl.newInstance();
if (in.next() == ']')
return col;
else
in.id -= 2;
while (in.next() != ']') {
col.add(deserialize(col, in, dataClass, dataType));
}
return col;
} else if (cl.isArray()) {
if (c != '[') {
throw new Throwable("JSONAPI: Error on deserializing Json " + new String(in.str) + ", expected {, found " + c + " (character id: " + in.id + ")");
}
Class dataClass = cl.getComponentType();
ArrayList col = new ArrayList();
if (in.next() == ']') {
return Array.newInstance(dataClass, 0);
} else
in.id -= 2;
while (in.next() != ']') {
col.add(deserialize(null, in, dataClass));
}
Object[] out = (Object[]) Array.newInstance(dataClass, col.size());
return col.toArray(out);
} else if (c == '{') {
Object obj = newInstance(cl);
if (in.next() == '}')
return obj;
else
in.id -= 2;
while (in.next() != '}') {
String fn = readString(in);
if (in.next() != ':')
throw new Throwable("JSONAPI: Error on deserializing Json " + new String(in.str) + ", expected :, found " + in.last() + " (character id: " + (in.id - 1) + ")");
try {
Field f = Reflection.getField(cl, fn);
Type gt = f.getGenericType();
f.set(obj, deserialize(obj, in, f.getType(), gt instanceof ParameterizedType ? ((ParameterizedType) gt).getActualTypeArguments() : emptyTypeArray));
} catch (Throwable e) {
SU.cs.sendMessage("§6[§eJSONAPI§6] §cField §f" + fn + "§e is declared in json, but it is missing from class §e" + cl.getName() + "§c.");
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
try {
Field f = Reflection.getField(cl, "parent");
f.set(obj, parent);
} catch (Throwable ignored) {
}
try {
Field f = Reflection.getField(cl, "self");
f.set(obj, obj);
} catch (Throwable ignored) {
}
try {
Field f = Reflection.getField(cl, "instance");
f.set(obj, obj);
} catch (Throwable ignored) {
}
return obj;
} else {
in.id--;
String str = readString(in);
try {
return Reflection.getConstructor(cl, String.class).newInstance(str);
} catch (Throwable ignored) {
}
try {
return Reflection.getMethod(cl, "valueOf", String.class).invoke(null, str);
} catch (Throwable ignored) {
}
try {
Method m = Reflection.getMethod(cl, "fromString", String.class);
if (cl == UUID.class && !str.contains("-"))
str = str.replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5");
return m.invoke(null, str);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
throw new Throwable("JSONAPI: Error on deserializing Json " + new String(in.str) + ", expected " + cl.getName() + ", found String.");
}
}
public static <T> T deserialize(String json, Class<T> cl, Type... params) {
if (json == null)
return null;
StringReader sr = new StringReader(json);
try {
return (T) deserialize(null, sr, cl, params);
} catch (Throwable e) {
debug.msg("Json", "§cFailed to deserialize JSON §e" + json + "§c to class §e" + cl.getName());
debug.msg("Json", e);
return null;
}
}
public static String escape(String s) {
return s.replace("\\", "\\\\").replace("\"", "\\\"");
}
public static String readString(StringReader in) {
int start = in.id;
int end = -1;
boolean esc = false;
boolean stresc = false;
while (in.hasNext()) {
char c = in.next();
if (esc)
esc = false;
else if (c == '\\')
esc = true;
else if (c == '\"') {
if (stresc) {
end = in.id - 1;
break;
} else {
stresc = true;
start = in.id;
}
} else if (!stresc && (c == ']' || c == '}' || c == ',' || c == ':')) {
in.id--;
break;
}
}
if (end == -1)
end = in.id;
return unescape(new String(in.str, start, end - start));
}
private static void serialize(StringBuilder sb, Object o) {
if (o == null) {
sb.append("null");
return;
}
Class cl = o.getClass();
if (o instanceof String || o instanceof UUID || o.getClass().isEnum() || o instanceof StringSerializable) {
sb.append('\"').append(escape(o.toString())).append("\"");
} else if (o instanceof Boolean || o instanceof Byte || o instanceof Short || o instanceof Integer || o instanceof Long || o instanceof Float || o instanceof Double) {
sb.append(o);
} else if (o instanceof Iterable || cl.isArray()) {
sb.append('[');
if (cl.isArray()) {
int max = Array.getLength(o);
for (int i = 0; i < max; i++) {
serialize(sb, Array.get(o, i));
sb.append(',');
}
} else {
for (Object obj : (Iterable) o) {
serialize(sb, obj);
sb.append(',');
}
}
if (sb.charAt(sb.length() - 1) == ',') {
sb.setCharAt(sb.length() - 1, ']');
} else {
sb.append(']');
}
} else if (o instanceof Map) {
sb.append('{');
for (Entry<?, ?> e : ((Map<?, ?>) o).entrySet()) {
String key = String.valueOf(e.getKey());
sb.append('\"').append(escape(key)).append("\":");
serialize(sb, e.getValue());
sb.append(',');
}
if (sb.charAt(sb.length() - 1) == ',') {
sb.setCharAt(sb.length() - 1, '}');
} else {
sb.append('}');
}
} else {
if (DefaultSerializers.shouldSkip(cl)) {
sb.append('\"').append(escape(o.toString())).append('\"');
return;
}
sb.append('{');
for (Field f : cl.getDeclaredFields()) {
try {
f.setAccessible(true);
JsonSettings settings = f.getAnnotation(JsonSettings.class);
String fn = f.getName();
String fnLower = fn.toLowerCase();
boolean serialize = !(fnLower.equals("self") || fnLower.equals("parent") || fnLower.equals("instance") || fnLower.equals("empty"));
String defaultValue = null;
if (settings != null) {
serialize = settings.serialize();
defaultValue = settings.defaultValue();
}
Object fo = f.get(o);
if (!serialize || fo == null || defaultValue != null && fo.toString().equals(defaultValue) || fo.getClass().getName().startsWith("java.lang.reflect.") || fo.getClass() == Class.class)
continue;
sb.append('\"').append(escape(fn)).append("\":");
serialize(sb, fo);
sb.append(',');
} catch (Throwable e) {
debug.msg("Json", e);
}
}
if (sb.charAt(sb.length() - 1) == ',') {
sb.setCharAt(sb.length() - 1, '}');
} else {
sb.append('}');
}
}
}
public static String serialize(Object o) {
StringBuilder sb = new StringBuilder();
try {
serialize(sb, o);
return sb.toString();
} catch (Throwable e) {
debug.msg("Json", "Error on serializing " + o.getClass().getName() + " object.");
debug.msg("Json", e);
return "{}";
}
}
public static String unescape(String s) {
boolean esc = false;
int utf = -1;
int utfc = -1;
StringBuilder out = new StringBuilder();
for (char c : s.toCharArray()) {
if (esc) {
switch (c) {
case 'b':
out.append('\b');
break;
case 'f':
out.append('\f');
break;
case 'n':
out.append('\n');
break;
case 'r':
out.append('\r');
break;
case 't':
out.append('\t');
break;
case 'u':
utf = 0;
utfc = 0;
break;
default:
out.append(c);
}
esc = false;
continue;
}
if (utf >= 0) {
utf = utf * 16 + HextoDec(c);
if (++utfc != 4) continue;
out.append((char) utf);
utf = -1;
utfc = -1;
continue;
}
if (c == '\\') {
esc = true;
continue;
}
out.append(c);
}
return out.toString();
}
} | 11,421 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
JsonSettings.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/json/JsonSettings.java | package gyurix.json;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = {ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface JsonSettings {
String defaultValue() default "null";
boolean serialize() default true;
}
| 378 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
PluginSignChangeEvent.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/sign/PluginSignChangeEvent.java | //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package gyurix.sign;
import org.bukkit.block.Block;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.block.BlockEvent;
public class PluginSignChangeEvent extends BlockEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final String[] lines;
private boolean cancel;
public PluginSignChangeEvent(Block block, String[] lines) {
super(block);
this.lines = lines;
}
public static HandlerList getHandlerList() {
return handlers;
}
public HandlerList getHandlers() {
return handlers;
}
public String getLine(int index) throws IndexOutOfBoundsException {
return lines[index];
}
public String[] getLines() {
return lines;
}
public boolean isCancelled() {
return cancel;
}
public void setCancelled(boolean cancel) {
this.cancel = cancel;
}
public void setLine(int index, String line) throws IndexOutOfBoundsException {
lines[index] = line;
}
}
| 1,123 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
SignConfig.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/sign/SignConfig.java | package gyurix.sign;
import gyurix.spigotlib.SU;
import lombok.Data;
import org.bukkit.block.Sign;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
@Data
public class SignConfig {
public ArrayList<String> lines = new ArrayList<>();
public String[] getLinesArray(Object... vars) {
String[] out = new String[4];
for (int i = 0; i < 4; i++)
out[i] = SU.fillVariables(lines.get(i), vars);
return out;
}
public String[] getLinesArray(Map<String, String> vars) {
String[] out = new String[4];
for (int i = 0; i < 4; i++)
out[i] = SU.fillVariables(lines.get(i), vars);
return out;
}
public TreeMap<String, String> getPlaceholders(String[] sign) {
TreeMap<String, String> out = new TreeMap<>();
for (int i = 0; i < 4; ++i) {
TreeMap<String, String> map = SU.getPlaceholders(lines.get(i), sign[i]);
if (map == null)
return null;
out.putAll(map);
}
return out;
}
public boolean matches(String[] sign) {
return getPlaceholders(sign) != null;
}
public boolean set(Sign s, Object... vars) {
try {
String[] newLines = new String[4];
for (int i = 0; i < 4; i++)
newLines[i] = SU.fillVariables(lines.get(i), vars);
PluginSignChangeEvent e = new PluginSignChangeEvent(s.getBlock(), newLines);
SU.pm.callEvent(e);
if (e.isCancelled())
return false;
for (int i = 0; i < 4; i++)
s.setLine(i, newLines[i]);
s.update(true, false);
return true;
} catch (Throwable e) {
return false;
}
}
public boolean setNoEvent(Sign s, Object... vars) {
try {
for (int i = 0; i < 4; i++)
s.setLine(i, SU.fillVariables(lines.get(i), vars));
s.update(true, false);
return true;
} catch (Throwable e) {
return false;
}
}
@Override
public String toString() {
return "- " + lines.get(0) + "\n- " + lines.get(1) + "\n- " + lines.get(2) + "\n- " + lines.get(3);
}
}
| 2,010 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Hologram.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/hologram/Hologram.java | package gyurix.hologram;
import gyurix.configfile.ConfigSerialization.ConfigOptions;
import gyurix.configfile.PostLoadable;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.LocationData;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.function.Function;
import static gyurix.spigotlib.Main.pl;
public class Hologram implements PostLoadable {
@Getter
@Setter
private Function<Player, Boolean> canSee = (plr) -> true;
private String id;
@ConfigOptions(serialize = false)
@Getter
private ArrayList<HologramLine> lineEntities = new ArrayList<>();
@Getter
private ArrayList<String> lines = new ArrayList<>();
private LocationData loc;
private HologramSettings settings;
@ConfigOptions(serialize = false)
private int taskId = -1;
private HashSet<String> viewers = new HashSet<>();
Hologram() {
}
Hologram(Location loc, String id, String... lines) {
this.loc = new LocationData(loc);
this.id = id;
this.lines.addAll(Arrays.asList(lines));
this.settings = new HologramSettings();
postLoad();
}
public void checkVisibility() {
Iterator<String> it = viewers.iterator();
Location l = loc.getLocation();
while (it.hasNext()) {
String s = it.next();
Player p = Bukkit.getPlayerExact(s);
if (p == null || !p.getWorld().getName().equals(loc.world)) {
for (HologramLine hl : lineEntities)
hl.viewers.remove(s);
it.remove();
continue;
}
if (p.getLocation().distance(l) > settings.dist || !canSee.apply(p)) {
for (HologramLine hl : lineEntities)
hl.hide(p);
it.remove();
}
}
World w = l.getWorld();
for (Player p : w.getPlayers()) {
if (viewers.contains(p.getName()))
continue;
if (p.isOnline() && p.getLocation().distance(l) <= settings.dist && canSee.apply(p)) {
for (HologramLine hl : lineEntities)
hl.show(p);
viewers.add(p.getName());
}
}
}
public void destroy() {
SU.sch.cancelTask(taskId);
for (HologramLine hl : lineEntities)
hl.destroy();
HologramAPI.holograms.remove(id);
}
@Override
public void postLoad() {
LocationData ld = loc.clone();
ld.y += settings.lineDist;
if (settings.align == LineAlign.CENTER)
ld.y += settings.lineDist * (lines.size() - 1) / 2;
else if (settings.align == LineAlign.UP)
ld.y += settings.lineDist * (lines.size() - 1);
for (String line : lines) {
ld = ld.clone();
ld.y -= settings.lineDist;
lineEntities.add(new HologramLine(line, ld));
}
}
public void reload() {
viewers.clear();
for (HologramLine hl : lineEntities)
hl.destroy();
lineEntities.clear();
postLoad();
checkVisibility();
}
public void setLines(String... lines) {
int len = lines.length;
this.lines = new ArrayList<>(Arrays.asList(lines));
if (len != lineEntities.size()) {
reload();
return;
}
for (int i = 0; i < lines.length; ++i) {
HologramLine line = lineEntities.get(i);
line.text = lines[i];
line.update();
}
}
public void setUpdateTicks(int update) {
settings.update = update;
SU.sch.cancelTask(taskId);
taskId = SU.sch.scheduleSyncRepeatingTask(pl, this::update, settings.update, settings.update);
}
public void teleport(LocationData loc, boolean skipPackets) {
loc = loc.clone();
loc.world = this.loc.world;
if (this.loc.equals(loc))
return;
this.loc = loc.clone();
LocationData ld = loc.clone();
ld.y += settings.lineDist;
if (settings.align == LineAlign.CENTER)
ld.y += settings.lineDist * (lines.size() - 1) / 2;
else if (settings.align == LineAlign.UP)
ld.y += settings.lineDist * (lines.size() - 1);
for (int i = 0; i < lines.size(); i++) {
ld = ld.clone();
ld.y -= settings.lineDist;
lineEntities.get(i).teleport(ld, skipPackets);
}
}
public void update() {
for (HologramLine hl : lineEntities)
hl.update();
}
}
| 4,279 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
HologramSettings.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/hologram/HologramSettings.java | package gyurix.hologram;
import lombok.Getter;
@Getter
public class HologramSettings {
LineAlign align = LineAlign.DOWN;
double dist = 50;
double lineDist = 0.225;
int update = 100;
public HologramSettings clone() {
HologramSettings settings = new HologramSettings();
settings.dist = dist;
settings.lineDist = lineDist;
settings.align = align;
return settings;
}
}
| 400 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
LineAlign.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/hologram/LineAlign.java | package gyurix.hologram;
public enum LineAlign {
UP, DOWN, CENTER;
}
| 72 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
HologramLine.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/hologram/HologramLine.java | package gyurix.hologram;
import gyurix.chat.ChatTag;
import gyurix.protocol.Reflection;
import gyurix.protocol.utils.DataWatcher;
import gyurix.protocol.utils.DataWatcher.WrappedItem;
import gyurix.protocol.utils.Vector;
import gyurix.protocol.wrappers.outpackets.*;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.LocationData;
import gyurix.spigotutils.ServerVersion;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.UUID;
import static gyurix.api.VariableAPI.fillVariables;
public class HologramLine {
public Object destroyP;
public Object spawnP;
public int id = HologramAPI.nextHologramId++;
public LocationData loc;
public ArrayList<WrappedItem> metaData = new ArrayList<>();
public String text;
public UUID uid = UUID.randomUUID();
public HashMap<String, String> viewers = new HashMap<>();
public HologramLine(String text, LocationData loc) {
this.text = text;
this.loc = loc;
if (Reflection.ver.isAbove(ServerVersion.v1_14))
makeMeta1_14();
else if (Reflection.ver.isAbove(ServerVersion.v1_9))
makeMeta1_9();
else
makeMeta1_8();
destroyP = new PacketPlayOutEntityDestroy(id).getVanillaPacket();
if (Reflection.ver.isBellow(ServerVersion.v1_8))
spawnP = new PacketPlayOutSpawnEntity(id, 78, uid, loc, new Vector()).getVanillaPacket();
}
private void applyText(String plText) {
metaData.set(2, new WrappedItem(2, Reflection.ver.isAbove(ServerVersion.v1_14) ? Optional.of(ChatTag.fromColoredText(plText).toICBC()) : plText));
}
public void destroy() {
for (String s : viewers.keySet()) {
Player p = Bukkit.getPlayerExact(s);
if (p != null)
SU.tp.sendPacket(p, destroyP);
}
}
public String fixEmpty(String in) {
return in.isEmpty() ? " " : in;
}
private Object getSpawnPacket() {
return new PacketPlayOutSpawnEntityLiving(id, uid, 1, loc, 0, new Vector(), new DataWatcher(metaData)).getVanillaPacket();
}
public void hide(Player plr) {
SU.tp.sendPacket(plr, destroyP);
viewers.remove(plr.getName());
}
public void makeMeta1_14() {
/*
0x01 On Fire
0x02 Crouched
0x08 Sprinting
0x10 Eating/drinking/blocking
0x20 Invisible
0x40 Glowing effect
0x80 Flying with elytra
*/
metaData.add(new WrappedItem(0, (byte) 0x20)); // 0 Byte - flags
metaData.add(new WrappedItem(1, 300)); // 1 VarInt - Air
metaData.add(new WrappedItem(2, Optional.of(ChatTag.fromColoredText(text).toICBC()))); // 2 String - Custom name
metaData.add(new WrappedItem(3, true)); // 3 Boolean - Custom name visible
metaData.add(new WrappedItem(4, true)); // 4 Boolean - Silent
metaData.add(new WrappedItem(5, true)); // 5 Boolean - No gravity
/*
0x01 Is hand active
0x02 Active hand (0 = main hand, 1 = offhand)
*/
/*metaData.add(new WrappedItem(7, (byte) 0)); // 7 Byte - hand flags
metaData.add(new WrappedItem(8, 20f)); // 8 Float - Health
metaData.add(new WrappedItem(9, 0)); // 9 VarInt - Potion effect color
metaData.add(new WrappedItem(10, false)); // 10 Boolean - Is potion effect ambient
metaData.add(new WrappedItem(11, 0)); // 11 VarInt - Number of arrows in entity*/
/*
0x01 is Small
0x04 has Arms
0x08 no BasePlate
0x10 set Marker
*/
/*metaData.add(new WrappedItem(13, (byte) (0x01 + 0x08 + 0x10))); // 13 Byte- flags*/
}
public void makeMeta1_8() {
/*
0x01 On Fire
0x02 Crouched
0x08 Sprinting
0x10 Eating/drinking/blocking
0x20 Invisible
*/
metaData.add(new WrappedItem(0, (byte) 0x20)); // 0 Byte - flags
metaData.add(new WrappedItem(1, (short) 300)); // 1 VarInt - Air
metaData.add(new WrappedItem(2, text)); // 2 String - Custom name
metaData.add(new WrappedItem(3, (byte) 1)); // 3 Byte - Custom name visible
metaData.add(new WrappedItem(6, 20f)); // 6 Float - Health
metaData.add(new WrappedItem(8, (byte) 0)); // 8 Byte - Is potion effect ambient
metaData.add(new WrappedItem(9, (byte) 0)); // 9 Byte - Number of arrows in entity
/*
0x01 is Small
0x02 has Gravity
0x04 has Arms
0x08 no BasePlate
0x16 zero bounding box
*/
metaData.add(new WrappedItem(10, (byte) (0x08 + 0x16))); // 10 Byte- flags
}
public void makeMeta1_9() {
/*
0x01 On Fire
0x02 Crouched
0x08 Sprinting
0x10 Eating/drinking/blocking
0x20 Invisible
0x40 Glowing effect
0x80 Flying with elytra
*/
metaData.add(new WrappedItem(0, (byte) 0x20)); // 0 Byte - flags
metaData.add(new WrappedItem(1, 300)); // 1 VarInt - Air
metaData.add(new WrappedItem(2, text)); // 2 String - Custom name
metaData.add(new WrappedItem(3, true)); // 3 Boolean - Custom name visible
metaData.add(new WrappedItem(4, true)); // 4 Boolean - Silent
metaData.add(new WrappedItem(5, true)); // 5 Boolean - No gravity
/*
0x01 Is hand active
0x02 Active hand (0 = main hand, 1 = offhand)
*/
metaData.add(new WrappedItem(6, (byte) 0)); // 6 Byte - hand flags
metaData.add(new WrappedItem(7, 20f)); // 7 Float - Health
metaData.add(new WrappedItem(8, 0)); // 8 VarInt - Potion effect color
metaData.add(new WrappedItem(9, false)); // 9 Boolean - Is potion effect ambient
metaData.add(new WrappedItem(10, 0)); // 10 VarInt - Number of arrows in entity
/*
0x01 is Small
0x04 has Arms
0x08 no BasePlate
0x10 set Marker
*/
metaData.add(new WrappedItem(11, (byte) (0x01 + 0x08 + 0x10))); // 11 Byte- flags
}
public void show(final Player plr) {
String plText = fixEmpty(fillVariables(text, plr));
applyText(plText);
if (Reflection.ver.isAbove(ServerVersion.v1_9))
SU.tp.sendPacket(plr, getSpawnPacket());
else {
SU.tp.sendPacket(plr, spawnP);
SU.tp.sendPacket(plr, new PacketPlayOutEntityMetadata(id, metaData));
}
viewers.put(plr.getName(), plText);
}
public void teleport(LocationData ld, boolean skipPackets) {
this.loc = ld;
if (!skipPackets) {
Object teleport = new PacketPlayOutEntityTeleport(id, this.loc).getVanillaPacket();
for (String s : viewers.keySet()) {
Player p = Bukkit.getPlayerExact(s);
if (p != null)
SU.tp.sendPacket(p, teleport);
}
}
}
public void update() {
for (Entry<String, String> e : viewers.entrySet()) {
Player p = Bukkit.getPlayerExact(e.getKey());
if (p != null) {
String oldText = e.getValue();
String newText = fixEmpty(fillVariables(text, p));
if (oldText.equals(newText))
continue;
e.setValue(newText);
applyText(newText);
SU.tp.sendPacket(p, new PacketPlayOutEntityMetadata(id, metaData));
}
}
}
}
| 7,215 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
HologramAPI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/hologram/HologramAPI.java | package gyurix.hologram;
import gyurix.spigotlib.Main;
import gyurix.spigotlib.SU;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Location;
import java.util.HashMap;
public class HologramAPI {
@Getter
static HashMap<String, Hologram> holograms = new HashMap<>();
static int nextHologramId = 459786;
@Getter
@Setter
static int visibilityCheckRate = 10;
static int visibilityCheckTaskId = -1;
private static void enable() {
if (visibilityCheckTaskId == -1)
visibilityCheckTaskId = SU.sch.scheduleSyncRepeatingTask(Main.pl, () -> holograms.values().forEach(Hologram::checkVisibility), visibilityCheckRate, visibilityCheckRate);
}
public static boolean destroyHologram(String id) {
Hologram h = holograms.get(id);
if (h == null)
return false;
h.destroy();
return true;
}
public static Hologram getHologram(String id) {
return holograms.get(id);
}
public static Hologram createHologram(Location loc, String id, String... lines) {
enable();
Hologram h = new Hologram(loc, id, lines);
holograms.put(id, h);
return h;
}
}
| 1,118 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
AnimationRunnable.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/animation/AnimationRunnable.java | package gyurix.animation;
import gyurix.animation.effects.FramesEffect;
import gyurix.spigotlib.SU;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import static gyurix.api.VariableAPI.fillVariables;
public class AnimationRunnable implements Runnable {
public final Animation a;
public final String name;
public final Plugin pl;
public final Player plr;
protected final HashMap<String, HashMap<String, CustomEffect>> effects = new HashMap();
private final FramesEffect f;
private final AnimationUpdateListener listener;
public String text = "§cERROR";
protected ScheduledFuture future;
protected AnimationRunnable(Plugin pl, Animation a, String name, Player plr, AnimationUpdateListener listener) {
this.pl = pl;
this.a = a;
this.name = name;
this.plr = plr;
this.listener = listener;
for (Entry<String, HashMap<String, CustomEffect>> e : a.effects.entrySet()) {
HashMap<String, CustomEffect> map = new HashMap<>();
effects.put(e.getKey(), map);
for (Entry<String, CustomEffect> e2 : e.getValue().entrySet())
map.put(e2.getKey(), e2.getValue().clone());
}
f = (FramesEffect) effects.get("frame").get("main").clone();
run();
}
public boolean isRunning() {
return future != null;
}
@Override
public void run() {
future = null;
try {
text = fillVariables(SU.optimizeColorCodes(f.next("")), plr, this);
if (!listener.onUpdate(this, text) || f.delay >= Integer.MAX_VALUE)
return;
} catch (Throwable e) {
String main = pl.getDescription().getMain();
SU.error(SU.cs, e, pl.getName(), main.substring(0, main.lastIndexOf(".")));
}
if (f.delay < 1)
f.delay = 1;
future = AnimationAPI.pool.schedule(this, f.delay, TimeUnit.MILLISECONDS);
}
public boolean stop() {
if (future == null)
return false;
future.cancel(true);
future = null;
return true;
}
}
| 2,091 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Animation.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/animation/Animation.java | package gyurix.animation;
import gyurix.animation.effects.FramesEffect;
import gyurix.configfile.ConfigData;
import gyurix.configfile.ConfigSerialization.Serializer;
import gyurix.spigotlib.SU;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
public class Animation {
public HashMap<String, HashMap<String, CustomEffect>> effects = new HashMap();
public HashMap<String, String> init = new HashMap<>();
public static class AnimationSerializer
implements Serializer {
@Override
public Object fromData(ConfigData data, Class cl, Type... args) {
Animation anim = new Animation();
long ft = 0;
if (data.mapData != null) {
for (Entry<ConfigData, ConfigData> e : data.mapData.entrySet()) {
String key = e.getKey().stringData;
ConfigData value = e.getValue();
if (key.endsWith("s")) {
if (AnimationAPI.effects.containsKey(key = key.substring(0, key.length() - 1))) {
anim.effects.put(key, e.getValue().deserialize(HashMap.class, String.class, AnimationAPI.effects.get(key)));
continue;
}
SU.cs.sendMessage("§e[AnimationAPI] §cUnregistered effect type §e" + key + "§c can't be active.");
continue;
}
if (key.equals("frameTime"))
ft = Long.valueOf(value.stringData);
}
}
if (data.listData != null) {
FramesEffect fe = new FramesEffect();
for (ConfigData cd : data.listData) {
fe.frames.add(new Frame(cd.stringData));
}
HashMap<String, CustomEffect> map = anim.effects.get("frame");
if (map == null)
map = new HashMap<>();
map.put("main", fe);
anim.effects.put("frame", map);
}
if (data.stringData != null && !data.stringData.isEmpty()) {
if (data.stringData.startsWith("{")) {
int id = data.stringData.indexOf("}");
for (String d : data.stringData.substring(1, id).split(" ")) {
String[] d2 = d.split(":", 2);
if (d2[0].equals("FT"))
ft = Integer.valueOf(d2[1]);
else
anim.init.put(d2[0], d2.length == 1 ? null : d2[1]);
}
data.stringData = data.stringData.substring(id + 1);
}
HashMap map = anim.effects.get("frame");
if (map == null)
anim.effects.put("frame", map = new HashMap());
if (!map.containsKey("main")) {
FramesEffect fe = new FramesEffect();
if (data.stringData.contains(";")) {
for (String s : data.stringData.split(";"))
fe.frames.add(new Frame(s));
} else
fe.frames.add(new Frame(data.stringData));
map.put("main", fe);
}
}
if (!anim.effects.containsKey("frame")) {
SU.cs.sendMessage("§e[AnimationAPI] §cError, the animation doesn't contain ANY frames parts.");
return fromData(new ConfigData("ERROR-NO-FRAMES"), cl, args);
}
if (!anim.effects.get("frame").containsKey("main")) {
SU.cs.sendMessage("§e[AnimationAPI] §cError, the animation doesn't contain the main frames part.");
return fromData(new ConfigData("ERROR-NO-MAINFRAMEPART"), cl, args);
}
if (((FramesEffect) anim.effects.get("frame").get("main")).frames.isEmpty()) {
SU.cs.sendMessage("§e[AnimationAPI] §cError, the animation doesn't contain any frames.");
return fromData(new ConfigData("ERROR-NO-MAINFRAMES"), cl, args);
}
if (ft > 0) {
((FramesEffect) anim.effects.get("frame").get("main")).frameTime = ft;
}
for (CustomEffect fe : anim.effects.get("frame").values()) {
for (Frame f : ((FramesEffect) fe).frames) {
for (Entry<String, Class> ef : AnimationAPI.effects.entrySet()) {
int id;
String text = f.text;
String efn = ef.getKey();
while ((id = text.indexOf("<" + efn + ":")) != -1) {
int bracket;
int colon = (text = text.substring(id += efn.length() + 2)).indexOf(":");
if (colon == -1) {
colon = text.length();
}
if ((bracket = text.indexOf(">")) == -1) {
bracket = text.length();
}
int id2 = Math.min(bracket, colon);
String name = text.substring(0, id2);
HashMap map = anim.effects.get(efn);
if (map == null) {
map = new HashMap();
}
try {
if (map.containsKey(name)) continue;
map.put(name, ef.getValue().newInstance());
anim.effects.put(efn, map);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
}
}
return anim;
}
@Override
public ConfigData toData(Object obj, Type... types) {
Animation anim = (Animation) obj;
ConfigData out = new ConfigData();
out.mapData = new LinkedHashMap();
for (Entry<String, HashMap<String, CustomEffect>> e : anim.effects.entrySet()) {
Class cl = AnimationAPI.effects.get(e.getKey());
if (cl == null) {
System.err.println("Unregistered effect type " + e.getKey() + " can't be saved.");
continue;
}
out.mapData.put(new ConfigData(e.getKey() + "s"), ConfigData.serializeObject(e.getValue(), String.class, cl));
}
return out;
}
}
}
| 5,601 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
AnimationAPI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/animation/AnimationAPI.java | package gyurix.animation;
import gyurix.animation.Animation.AnimationSerializer;
import gyurix.animation.effects.*;
import gyurix.api.VariableAPI;
import gyurix.api.VariableAPI.VariableHandler;
import gyurix.configfile.ConfigSerialization;
import gyurix.spigotlib.Config;
import gyurix.spigotlib.Main;
import gyurix.spigotlib.SU;
import org.apache.commons.lang.StringUtils;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
/**
* An API used for running Animations
*/
public final class AnimationAPI {
protected static final ScheduledExecutorService pool = Executors.newScheduledThreadPool(Config.animationApiThreads);
/**
* Custom effect name - Custom effect class mapping
*/
public static HashMap<String, Class> effects = new HashMap();
private static HashMap<Plugin, HashMap<String, HashSet<AnimationRunnable>>> runningAnimations = new HashMap();
/**
* Initializes the AnimationAPI:
* - registers built in custom effects
* - registers a CustomEffectHandler for every custom effect
* - registers the AnimationSerializer
*/
public static void init() {
effects.put("scroller", ScrollerEffect.class);
effects.put("blink", BlinkEffect.class);
effects.put("frame", FramesEffect.class);
effects.put("flame", FlameEffect.class);
effects.put("rainbow", RainbowEffect.class);
for (String key : effects.keySet())
VariableAPI.handlers.put(key, new CustomEffectHandler(key));
ConfigSerialization.getSerializers().put(Animation.class, new AnimationSerializer());
}
/**
* Starts the execution of an Animation
*
* @param pl - Plugin which wants to start the Animation, used for auto stopping it, when the plugin is unloaded
* @param a - The runnable Animation
* @param name - The name under which the Animation should be executed, this name can help for the plugin
* to determine what kind of animation is actually running
* @param plr - The player to who this Animation should be linked. Every placeholder in the Animation will
* be filled with his data
* @param listener - The AnimationUpdateListener, which should handle every state change in the animation
* @return The AnimationRunnable, usable for cancelling the execution of the Animation at any time
*/
public static AnimationRunnable runAnimation(Plugin pl, Animation a, String name, Player plr, AnimationUpdateListener listener) {
if (pl == null || a == null || plr == null || listener == null)
return null;
HashMap<String, HashSet<AnimationRunnable>> map = runningAnimations.computeIfAbsent(pl, k -> new HashMap<>());
HashSet<AnimationRunnable> ars = map.computeIfAbsent(plr.getName(), k -> new HashSet<>());
AnimationRunnable ar = new AnimationRunnable(pl, a, name, plr, listener);
ars.add(ar);
return ar;
}
/**
* Force stops the given AnimationRunnable
*
* @param ar - The stoppable AnimationRunnable
*/
public static void stopRunningAnimation(AnimationRunnable ar) {
if (ar == null)
return;
HashMap<String, HashSet<AnimationRunnable>> map = runningAnimations.get(ar.pl);
if (map == null || map.isEmpty())
return;
HashSet<AnimationRunnable> ars = map.get(ar.plr.getName());
ars.remove(ar);
ar.stop();
}
/**
* Force stops every AnimationRunnable linked to the given player.
* This method is automatically executed by SpigotLib, when player logs out.
*
* @param plr - Target player
*/
public static void stopRunningAnimations(Player plr) {
if (plr == null)
return;
for (HashMap<String, HashSet<AnimationRunnable>> map : runningAnimations.values()) {
HashSet<AnimationRunnable> ars = map.remove(plr.getName());
if (ars != null)
for (AnimationRunnable ar : ars)
if (ar.future != null)
ar.future.cancel(true);
}
}
/**
* Force stops every AnimationRunnable linked to the given plugin.
* This method is automatically executed by SpigotLib, when a plugin is unloaded.
*
* @param pl - Target plugin
*/
public static void stopRunningAnimations(Plugin pl) {
if (pl == null)
return;
HashMap<String, HashSet<AnimationRunnable>> map = runningAnimations.remove(pl);
if (map == null || map.isEmpty())
return;
for (HashSet<AnimationRunnable> ars : map.values()) {
for (AnimationRunnable ar : ars)
ar.stop();
}
}
/**
* Force stops every AnimationRunnable linked to the given plugin and to the given player.
* This method helps plugins to stop their AnimationRunnables without keeping their instances.
*
* @param pl - Target plugin
* @param plr - Target Player
*/
public static void stopRunningAnimations(Plugin pl, Player plr) {
if (pl == null || plr == null)
return;
HashMap<String, HashSet<AnimationRunnable>> map = runningAnimations.get(pl);
if (map == null || map.isEmpty())
return;
HashSet<AnimationRunnable> ars = map.remove(plr.getName());
if (ars != null)
for (AnimationRunnable ar : ars)
ar.stop();
}
/**
* The CustomEffectHandler class is used for making custom effects in Animations work as VariableAPI variables
* for easier usage
*/
public static class CustomEffectHandler implements VariableHandler {
public final String name;
public CustomEffectHandler(String name) {
this.name = name;
}
@Override
public Object getValue(Player plr, ArrayList<Object> inside, Object[] oArgs) {
AnimationRunnable ar = (AnimationRunnable) oArgs[0];
String[] d = StringUtils.join(inside, "").split(":", 2);
CustomEffect effect = ar.effects.get(name).get(d[0]);
if (effect != null) {
String text = d.length <= 1 ? effect.getText() : d[1];
return effect.next(VariableAPI.fillVariables(text, plr, oArgs));
}
SU.log(Main.pl, "The given " + name + " name (" + d[0] + ") is invalid " + name + " name in animation ");
return "?";
}
}
}
| 6,229 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
AnimationUpdateListener.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/animation/AnimationUpdateListener.java | package gyurix.animation;
/**
* Interface represanting the listener for the frames of a running animation
*/
public interface AnimationUpdateListener {
/**
* @param ar - The running AnimationRunnable
* @param text - The next of the current frame of the animation
* @return true if the animation can continue running, false otherwise
*/
boolean onUpdate(AnimationRunnable ar, String text);
}
| 412 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
CustomEffect.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/animation/CustomEffect.java | package gyurix.animation;
public interface CustomEffect {
CustomEffect clone();
String getText();
void setText(String var1);
String next(String var1);
}
| 166 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Frame.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/animation/Frame.java | package gyurix.animation;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import java.util.ArrayList;
public class Frame implements StringSerializable {
public ArrayList<Long> delays;
public ArrayList<Long> repeats;
public String text;
public Frame(String in) {
if (in.startsWith("{")) {
delays = new ArrayList<>();
repeats = new ArrayList<>();
int id = in.indexOf("}");
for (String s : in.substring(1, id).split("(,+| +) *")) {
String[] d2 = s.split(":", 2);
if (d2.length == 2) {
delays.add(Long.valueOf(d2[1]));
repeats.add(Long.valueOf(d2[0]));
continue;
}
delays.add(Long.valueOf(d2[0]));
repeats.add(1L);
}
text = in.substring(id + 1);
} else {
text = in;
}
}
@Override
public String toString() {
if (delays == null || delays.isEmpty()) {
return text;
}
StringBuilder out = new StringBuilder();
out.append('{');
for (int i = 0; i < delays.size(); ++i) {
long repeat = repeats.get(i);
long delay = delays.get(i);
if (repeat == 1) {
out.append(delay);
} else {
out.append(repeat).append(':').append(delay);
}
out.append(",");
}
out.setCharAt(out.length() - 1, '}');
out.append(text);
return out.toString();
}
}
| 1,372 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
BlinkEffect.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/animation/effects/BlinkEffect.java | package gyurix.animation.effects;
import gyurix.animation.CustomEffect;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import java.util.ArrayList;
import java.util.Iterator;
public class BlinkEffect implements StringSerializable, CustomEffect {
private boolean active = true;
private Iterator<Long> data;
private long remaining;
private ArrayList<Long> repeat = new ArrayList();
private String text;
public BlinkEffect(String in) {
if (in.startsWith("{")) {
for (String s : in.substring(1, in.indexOf("}")).split(" ")) {
if (s.equals("A")) {
active = false;
continue;
}
repeat.add(Long.valueOf(s));
}
} else {
repeat.add(1L);
text = in;
}
data = repeat.iterator();
remaining = data.next();
}
public BlinkEffect() {
}
@Override
public CustomEffect clone() {
BlinkEffect be = new BlinkEffect();
be.active = active;
be.data = data;
be.remaining = remaining;
be.repeat = repeat;
be.text = text;
return be;
}
@Override
public String toString() {
StringBuilder out = new StringBuilder();
out.append("{");
if (!active) {
out.append("A ");
}
for (Long r : repeat) {
out.append(r).append(' ');
}
out.setCharAt(out.length() - 1, '}');
return out.append(text).toString();
}
@Override
public String getText() {
return text;
}
@Override
public void setText(String newText) {
text = newText;
}
@Override
public String next(String in) {
--remaining;
if (remaining == 0) {
if (!data.hasNext()) {
data = repeat.iterator();
}
remaining = data.next();
active = !active;
}
return active ? in : in.replaceAll(".", " ");
}
}
| 1,796 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
FramesEffect.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/animation/effects/FramesEffect.java | package gyurix.animation.effects;
import gyurix.animation.CustomEffect;
import gyurix.animation.Frame;
import gyurix.configfile.ConfigSerialization.ConfigOptions;
import gyurix.spigotlib.SU;
import java.util.ArrayList;
import java.util.Iterator;
public class FramesEffect implements CustomEffect {
@ConfigOptions(serialize = false)
public long delay;
@ConfigOptions(serialize = false)
public Iterator<Long> delays;
@ConfigOptions(serialize = false)
public Frame f;
@ConfigOptions(defaultValue = "9223372036854775807")
public long frameTime = Long.MAX_VALUE;
public ArrayList<Frame> frames = new ArrayList();
public boolean random;
@ConfigOptions(serialize = false)
public long repeat;
@ConfigOptions(serialize = false)
public Iterator<Long> repeats;
@ConfigOptions(serialize = false)
public int state = -1;
@Override
public CustomEffect clone() {
FramesEffect fe = new FramesEffect();
fe.frameTime = frameTime;
fe.state = state;
fe.frames = frames;
fe.random = random;
fe.f = f;
fe.delay = delay;
fe.delays = delays;
fe.repeats = repeats;
fe.repeat = repeat;
return fe;
}
@Override
public String getText() {
return f != null ? f.text : "";
}
@Override
public void setText(String newText) {
}
@Override
public String next(String in) {
if (repeat == 0) {
if (delays == null || !delays.hasNext()) {
state = random ? SU.rand.nextInt(frames.size()) : (state + 1) % frames.size();
f = frames.get(state);
if (f.delays == null) {
delay = frameTime;
repeat = 1;
delays = null;
} else {
delays = f.delays.iterator();
repeats = f.repeats.iterator();
delay = delays.next();
repeat = repeats.next();
}
} else {
delay = delays.next();
repeat = repeats.next();
}
}
--repeat;
return f.text;
}
}
| 1,951 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
FlameEffect.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/animation/effects/FlameEffect.java | package gyurix.animation.effects;
import gyurix.animation.CustomEffect;
import gyurix.configfile.ConfigSerialization.StringSerializable;
import gyurix.spigotlib.SU;
public class FlameEffect implements CustomEffect {
public FlameInfo info;
public boolean rotate;
public int speed = 1;
public int start;
@Override
public CustomEffect clone() {
FlameEffect fe = new FlameEffect();
fe.info = info;
fe.speed = speed;
fe.start = start;
fe.rotate = rotate;
return fe;
}
@Override
public String getText() {
return "";
}
@Override
public void setText(String newText) {
}
@Override
public String next(String in) {
StringBuilder out = new StringBuilder();
int strstate = start;
int state = 0;
if (strstate >= in.length()) {
step(in);
return in;
}
if (strstate > 0) {
out.append(in.substring(0, strstate));
}
for (int i = 0; i < info.counts.length; i++) {
out.append(info.pref[i]);
if (strstate + info.counts[i] > 0) {
int maxid = strstate + info.counts[i];
if (maxid > in.length())
break;
else {
out.append(in.substring(Math.max(strstate, 0), maxid));
}
}
strstate += info.counts[i];
}
if (strstate < in.length()) {
out.append(in.substring(Math.max(strstate, 0)));
}
step(in);
return SU.optimizeColorCodes(out.toString());
}
private void step(String in) {
int count = 0;
for (int c : info.counts) {
count += c;
}
count -= info.counts[info.counts.length - 1];
if (start >= in.length()) {
if (rotate) {
speed = -speed;
} else {
start = -count;
return;
}
} else if (rotate && speed < 0 && start <= -count) {
speed = -speed;
}
start += speed;
}
public static class FlameInfo
implements StringSerializable {
public int[] counts;
public String[] pref;
public FlameInfo() {
}
public FlameInfo(String in) {
String[] d = in.split(" ");
counts = new int[d.length];
pref = new String[d.length];
for (int i = 0; i < d.length; ++i) {
String[] d2 = d[i].split(":", 2);
counts[i] = 1;
try {
pref[i] = d2[0];
counts[i] = Integer.valueOf(d2[1]);
} catch (Throwable t) {
}
}
}
@Override
public String toString() {
StringBuilder out = new StringBuilder();
for (int i = 0; i < counts.length; ++i) {
out.append(' ').append(pref[i]).append(':').append(counts[i]);
}
return out.substring(1);
}
}
}
| 2,651 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ScrollerEffect.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/animation/effects/ScrollerEffect.java | package gyurix.animation.effects;
import gyurix.animation.CustomEffect;
import java.util.HashSet;
import java.util.Iterator;
public class ScrollerEffect implements CustomEffect {
public char fill = 32;
public int max = 80;
public boolean reversed;
public int size = 16;
public boolean skipColors = true;
public int speed = 1;
public int start;
public String text;
public ScrollerEffect() {
}
public ScrollerEffect(int max, int size, String text) {
this(max, size, 1, 0, false, true, ' ', text);
}
public ScrollerEffect(int max, int size, int speed, int start, boolean reversed, boolean skipColors, char fill, String text) {
this.max = max;
this.size = size;
this.speed = speed;
this.start = start;
this.reversed = reversed;
this.skipColors = skipColors;
this.fill = fill;
this.text = text;
}
@Override
public CustomEffect clone() {
return new ScrollerEffect(max, size, speed, start, reversed, skipColors, fill, text);
}
@Override
public String getText() {
return text;
}
@Override
public void setText(String text) {
this.text = text;
}
@Override
public String next(String text) {
char c;
int i;
int i2;
int id;
StringBuilder sb = new StringBuilder(size);
HashSet<Character> formats = new HashSet<Character>();
int inc = speed;
char colorPrefix = ' ';
char[] chars = text.toCharArray();
for (int i3 = 1; i3 < max; ++i3) {
int id2 = (start + max - i3) % max;
if (chars.length <= id2 || chars[id2] != '\u00a7' || chars.length <= (id2 = (id2 + 1) % max)) continue;
c = chars[id2];
if (c < 'k' || c > 'o') {
colorPrefix = c;
break;
}
formats.add(Character.valueOf(c));
}
int n = i2 = chars.length > (id = (start + max - 1) % max) && chars[id] == '\u00a7' ? 1 : 0;
while (i2 < size && chars.length > (id = (start + i2) % max) && chars[id] == '\u00a7') {
id = (start + i2 + 1) % max;
if (chars.length > id) {
c = chars[id];
if (skipColors) {
inc += 2;
}
if (c < 'k' || c > 'o') {
formats.clear();
colorPrefix = c;
} else {
formats.add(Character.valueOf(c));
}
}
i2 += 2;
}
if (colorPrefix != ' ') {
sb.append('\u00a7').append(colorPrefix);
}
Iterator i$ = formats.iterator();
while (i$.hasNext()) {
c = ((Character) i$.next()).charValue();
sb.append('\u00a7').append(c);
}
id = (start + max - 1) % max;
int n2 = i = chars.length > id && chars[id] == '\u00a7' ? 1 : 0;
while (sb.length() < size) {
id = (start + i) % max;
sb.append(chars.length > id ? chars[id] : fill);
++i;
}
if (sb.charAt(size - 1) == '\u00a7') {
sb.setCharAt(size - 1, fill);
}
if (reversed) {
start -= inc;
if (start < 0) {
start = max - inc;
}
} else {
start += inc;
if (start >= max) {
start = inc - 1;
}
}
return sb.toString();
}
}
| 3,084 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
RainbowEffect.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/animation/effects/RainbowEffect.java | package gyurix.animation.effects;
import gyurix.animation.CustomEffect;
import gyurix.spigotlib.SU;
public class RainbowEffect implements CustomEffect {
public boolean random;
public int state = -1;
public RainbowEffect() {
}
public RainbowEffect(int state, boolean random) {
this.state = state;
this.random = random;
}
@Override
public CustomEffect clone() {
return new RainbowEffect(state, random);
}
@Override
public String getText() {
return "";
}
@Override
public void setText(String newText) {
}
@Override
public String next(String in) {
state = random ? SU.rand.nextInt(in.length()) : (state + 1) % in.length();
return "\u00a7" + in.charAt(state % in.length());
}
}
| 742 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Config.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotlib/Config.java | package gyurix.spigotlib;
import gyurix.debug.Debugger;
import gyurix.economy.EconomyAPI;
import gyurix.mysql.MySQLDatabase;
import gyurix.spigotutils.BackendType;
import gyurix.spigotutils.TPSMeter;
/**
* Memory represantation of the SpigotLib's configuration (config.yml)
*/
public class Config {
/**
* Allow access to every SpigotLib command for the plugins author,
* so he could debug other plugins quickly without needing to ask you
* for changing his perms all the time
*/
public static boolean allowAllPermsForAuthor;
/**
* Amount of async threads used in AnimationAPI for running animations smoothly
*/
public static int animationApiThreads;
/**
* BungeeAPI related configurations
*/
public static BungeeAPI bungee;
/**
* Toggle debug messages in the plugin
*/
public static Debugger debug = new Debugger();
/**
* Default server language used in language files
*/
public static String defaultLang = "en";
/**
* Disable plugins on crash
*/
public static boolean disablePluginsOnCrash;
/**
* Disable weather changes on the entire server, useful for testing
*/
public static boolean disableWeatherChange;
/**
* Log player data management system player loading and unloading events
*/
public static boolean logPlayerConfigLoadUnload;
/**
* EconomyAPI related configurations
*/
public static EconomyAPI economy;
/**
* Disable version sensitive features of SpigotLib, like PacketAPI, ScoreboardAPI for
* fixing compatibility issues with older server versions
*/
public static boolean forceReducedMode;
/**
* Require SSL for MySQL connections
*/
public static boolean mysqlSSL;
/**
* Automatically hook to PlaceholderAPI if it's added to the server
*/
public static boolean phaHook;
/**
* Allow using Javascript engine for players using /sl commands.
* This feature might be abused by players, and give them unpredictable amount of power,
* so it's default by default for security
*/
public static boolean playerEval;
/**
* Player data storage related settings
*/
public static PlayerFile playerFile;
/**
* Purge player data storage in the next server restart
*/
public static boolean purgePF;
/**
* Hide every error handled through the SpigotLib error handler
*/
public static boolean silentErrors;
/**
* TPS meter related settings
*/
public static TPSMeter tpsMeter;
/**
* BungeeAPI related settings.
*/
public static class BungeeAPI {
/**
* Amount of ticks how often the current server name should be querried from Bungee automatically.
* 0 = disable feature
*/
public static int currentServerName;
/**
* Force enable BungeeAPI, without checking if the Spigot is connected to BungeeCord or not.
* Use this option only if the automatic BungeeCord detection does not detect the BungeeCord.
*/
public static boolean forceEnable;
/**
* Querry players real IP address from the Bungee, when he joins
*/
public static boolean ipOnJoin;
/**
* Amount of ticks how often the player counts should be querried from Bungee automatically.
* 0 = disable feature
*/
public static int playerCount;
/**
* Amount of ticks how often the player counts should be querried from Bungee automatically.
* 0 = disable feature
*/
public static int playerList;
/**
* Amount of ticks how often the IPs of every server should be querried from Bungee automatically.
* 0 = disable feature
*/
public static int serverIP;
/**
* Amount of ticks how often the server list should be querried from Bungee automatically.
* 0 = disable feature
*/
public static int servers;
/**
* Amount of ticks how often the uuid of every player should be querried from Bungee automatically.
* 0 = disable feature
*/
public static int uuidAll;
}
public static class PlayerFile {
public static BackendType backend;
public static boolean keepOfflineDataLoaded;
public static String file = "players.yml";
public static MySQLDatabase mysql;
}
}
| 4,192 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Main.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotlib/Main.java | package gyurix.spigotlib;
import gyurix.animation.AnimationAPI;
import gyurix.api.BungeeAPI;
import gyurix.api.VariableAPI;
import gyurix.commands.CustomCommandMap;
import gyurix.commands.SpigotLibCommands;
import gyurix.commands.plugin.CommandMatcher;
import gyurix.configfile.ConfigFile;
import gyurix.configfile.ConfigSerialization;
import gyurix.datareader.DataReader;
import gyurix.economy.EconomyAPI;
import gyurix.economy.custom.ExpBalanceType;
import gyurix.economy.custom.VaultBalanceType;
import gyurix.hologram.HologramAPI;
import gyurix.inventory.CloseableGUI;
import gyurix.inventory.CustomGUI;
import gyurix.mysql.MySQLDatabase;
import gyurix.protocol.Reflection;
import gyurix.protocol.event.PacketInType;
import gyurix.protocol.event.PacketOutType;
import gyurix.protocol.manager.ProtocolImpl;
import gyurix.protocol.manager.ProtocolLegacyImpl;
import gyurix.protocol.utils.WrapperFactory;
import gyurix.scoreboard.PlayerBars;
import gyurix.scoreboard.ScoreboardAPI;
import gyurix.scoreboard.ScoreboardBar;
import gyurix.spigotlib.Config.PlayerFile;
import gyurix.spigotlib.GlobalLangFile.PluginLang;
import gyurix.spigotutils.BackendType;
import gyurix.spigotutils.TPSMeter;
import net.milkbowl.vault.chat.Chat;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.ServiceRegisterEvent;
import org.bukkit.event.server.ServiceUnregisterEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import javax.script.ScriptEngineManager;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.UUID;
import static gyurix.economy.EconomyAPI.VaultHookType.*;
import static gyurix.protocol.Reflection.ver;
import static gyurix.spigotlib.Config.PlayerFile.backend;
import static gyurix.spigotlib.Config.PlayerFile.mysql;
import static gyurix.spigotlib.Config.forceReducedMode;
import static gyurix.spigotlib.SU.*;
import static gyurix.spigotutils.ServerVersion.*;
/**
* Main SpigotLib plugin class containing all the command handlers, loaders and delegators needed for starting up the API
*/
public class Main extends JavaPlugin implements Listener {
/**
* The UUID of the plugins author for being able to grant him full plugin, if allowed in the config
*/
public static final UUID author = UUID.fromString("877c9660-b0da-4dcb-8f68-9146340f2f68");
/**
* The list of SpigotLib subcommands used for tab completion.
*/
public static final String[] commands = {"chm", "abm", "sym", "title", "vars", "perm", "lang", "save", "reload", "velocity", "world", "setamount", "item"};
/**
* Current version of the plugin, stored here to not be able to be abused so easily by server owners, by changing the plugin.yml file
*/
public static final String version = "10.2.6";
/**
* Data directory of the plugin (plugins/SpigotLib folder)
*/
public static File dir;
/**
* Tells if the server was fully enabled, or not yet. If not yet, then the players are automatically kicked to prevent any damage caused by too early joins.
*/
public static ConfigFile kf, itemf;
public static PluginLang lang;
public static Main pl;
private static boolean schedulePacketAPI;
public void load() {
cs.sendMessage("§2[§aSpigotLib§2]§e Loading §aconfiguration§e and §alanguage file§e...");
saveResources(this, "lang.yml", "config.yml", "items.yml");
kf = new ConfigFile(getResource("config.yml"));
kf.load(new File(dir + File.separator + "config.yml"));
kf.data.deserialize(Config.class);
Config.debug.setPlugin(this);
kf.save();
lang = GlobalLangFile.loadLF("spigotlib", getResource("lang.yml"), dir + File.separator + "lang.yml");
cs.sendMessage("§2[§aSpigotLib§2]§e Loading §aenchants file§e...");
itemf = new ConfigFile(new File(dir + File.separator + "items.yml"));
itemf.data.deserialize(Items.class);
if (backend == BackendType.FILE) {
cs.sendMessage("§2[§aSpigotLib§2]§e Loading §aFILE§e backend for §aplayer data storage§e...");
if (Config.purgePF) {
Config.purgePF = false;
kf.save();
if (new File(dir + File.separator + PlayerFile.file).delete())
cs.sendMessage("§2[§aSpigotLib§2]§b Purged player file.");
else
cs.sendMessage("§2[§aSpigotLib§2]§c Failed to purge player file.");
}
pf = new ConfigFile(new File(dir + File.separator + PlayerFile.file));
} else if (backend == BackendType.MYSQL) {
cs.sendMessage("§2[§aSpigotLib§2]§e Loading §aMySQL§e backend for §aplayer data storage§e...");
if (Config.purgePF) {
Config.purgePF = false;
kf.save();
if (mysql.command("DROP TABLE " + mysql.table))
cs.sendMessage("§2[§aSpigotLib§2]§b Dropped " + mysql.table + " table.");
else
cs.sendMessage("§2[§aSpigotLib§2]§c Failed to drop " + mysql.table + " table.");
}
mysql.command("CREATE TABLE IF NOT EXISTS " + mysql.table + " (`uuid` VARCHAR(40) NOT NULL PRIMARY KEY, `data` MEDIUMTEXT)");
pf = new ConfigFile(mysql, mysql.table, "key", "value");
loadPlayerConfig(null);
Bukkit.getOnlinePlayers().forEach((p) -> loadPlayerConfig(p.getUniqueId()));
}
if (ver.isAbove(v1_8))
tp = new ProtocolImpl();
else if (ver != UNKNOWN)
tp = new ProtocolLegacyImpl();
else
forceReducedMode = true;
if (!forceReducedMode)
startPacketAPI();
cs.sendMessage("§2[§aSpigotLib§2]§e Loading §aAnimationAPI§e...");
AnimationAPI.init();
ConfigSerialization.getInterfaceBasedClasses().put(ItemStack.class, Reflection.getOBCClass("inventory.CraftItemStack"));
if (!forceReducedMode) {
cs.sendMessage("§2[§aSpigotLib§2]§e Starting SpigotLib in §afully compatible§e mode, starting " +
"Offline player management, ChatAPI, TitleAPI, NBTApi, ScoreboardAPI...");
WrapperFactory.init();
PacketInType.init();
PacketOutType.init();
ChatAPI.init();
for (Player p : Bukkit.getOnlinePlayers())
ScoreboardAPI.playerJoin(p);
} else {
cs.sendMessage("§2[§aSpigotLib§2]§e Starting SpigotLib in §csemi compatible mode§e, skipping the load of " +
"PacketAPI, Offline player management, ChatAPI, TitleAPI, NBTApi, ScoreboardAPI.");
}
cs.sendMessage("§2[§aSpigotLib§2]§e Preparing §aPlaceholderAPI§e and §aVault§e hooks...");
VariableAPI.phaHook = pm.getPlugin("PlaceholderAPI") != null && Config.phaHook;
}
@EventHandler
public void onClick(InventoryClickEvent e) {
Inventory top = e.getView().getTopInventory();
if (top == null || top.getHolder() == null || !(top.getHolder() instanceof CustomGUI))
return;
e.setCancelled(true);
if (e.getClickedInventory() == top)
try {
((CustomGUI) top.getHolder()).onClick(e.getSlot(), e.isRightClick(), e.isShiftClick());
sch.scheduleSyncDelayedTask(pl, () -> ((Player) e.getView().getPlayer()).updateInventory());
} catch (Throwable err) {
Player plr = (Player) e.getWhoClicked();
error(plr.hasPermission("spigotlib.debug") ? plr : cs, err, SU.getPlugin(top.getHolder().getClass()).getName(), "gyurix");
}
}
@EventHandler
public void onClose(InventoryCloseEvent e) {
Inventory top = e.getView().getTopInventory();
if (top == null || top.getHolder() == null || !(top.getHolder() instanceof CloseableGUI))
return;
try {
((CloseableGUI) top.getHolder()).close();
} catch (Throwable err) {
Player plr = (Player) e.getPlayer();
error(plr.hasPermission("spigotlib.debug") ? plr : cs, err, SU.getPlugin(top.getHolder().getClass()).getName(), "gyurix");
}
}
@EventHandler
public void onDeath(PlayerRespawnEvent e) {
HologramAPI.getHolograms().values().forEach(h -> {
h.getLineEntities().forEach(hl -> hl.viewers.remove(e.getPlayer().getName()));
h.checkVisibility();
});
}
public void onDisable() {
log(this, "§4[§cShutdown§4]§e Collecting plugins depending on SpigotLib...");
ArrayList<Plugin> depend = new ArrayList<>();
for (Plugin p : pm.getPlugins()) {
PluginDescriptionFile pdf = p.getDescription();
if (pdf.getDepend() != null && pdf.getDepend().contains("SpigotLib") || pdf.getSoftDepend() != null && pdf.getSoftDepend().contains("SpigotLib"))
depend.add(p);
}
log(this, "§4[§cShutdown§4]§e Saving players...");
if (backend == BackendType.FILE)
pf.saveNoAsync();
else if (backend == BackendType.MYSQL) {
for (Player p : Bukkit.getOnlinePlayers())
savePlayerConfigNoAsync(p.getUniqueId());
mysql.close();
}
log(this, "§4[§cShutdown§4]§e Unloading plugins depending on SpigotLib...");
HashSet<Plugin> unloaded = new HashSet<>();
for (Plugin p : depend) {
log(this, "§4[§cShutdown§4]§e Unloading plugin §f" + p.getName() + "§e...");
unloadPlugin(unloaded, p);
}
pf = null;
if (TPSMeter.meter != null) {
log(this, "§4[§cShutdown§4]§e Stopping TPSMeter...");
TPSMeter.meter.cancel(true);
}
if (!forceReducedMode) {
log(this, "§4[§cShutdown§4]§e Stopping PacketAPI...");
try {
tp.close();
} catch (Throwable e) {
error(cs, e, "SpigotLib", "gyurix");
}
}
log(this, "§4[§cShutdown§4]§e Stopping AnimationAPI...");
AnimationAPI.stopRunningAnimations(this);
if (!forceReducedMode && ver.isAbove(v1_8)) {
log(this, "§4[§cShutdown§4]§e Stopping ScoreboardAPI...");
for (Player p : Bukkit.getOnlinePlayers()) {
PlayerBars pbs = ScoreboardAPI.sidebars.remove(p.getName());
for (ScoreboardBar sb : pbs.loaded)
sb.unload(p);
pbs = ScoreboardAPI.nametags.remove(p.getName());
for (ScoreboardBar sb : pbs.loaded)
sb.unload(p);
pbs = ScoreboardAPI.tabbars.remove(p.getName());
for (ScoreboardBar sb : pbs.loaded)
sb.unload(p);
}
}
if (ver.isBellow(v1_12)) {
log(this, "§4[§cShutdown§4]§e Stopping CommandAPI...");
CustomCommandMap.unhook();
}
log(this, "§4[§cShutdown§4]§a The SpigotLib has shutted down properly.");
}
public void onEnable() {
PluginCommand cmd = getCommand("sl");
SpigotLibCommands exec = new SpigotLibCommands();
cmd.setExecutor(exec);
cmd.setTabCompleter(exec);
if (cs == null)
onLoad();
else if (ver.isBellow(v1_12))
cm = new CustomCommandMap();
if (!forceReducedMode) {
cs.sendMessage("§2[§aSpigotLib§2]§e Initializing §aoffline player manager§e...");
pm.registerEvents(tp, this);
initOfflinePlayerManager();
}
pm.registerEvents(this, this);
BungeeAPI.enabled = Config.BungeeAPI.forceEnable || srv.spigot().getConfig().getConfigurationSection("settings").getBoolean("bungeecord");
if (BungeeAPI.enabled) {
cs.sendMessage("§2[§aSpigotLib§2]§e Starting §aBungeeAPI§e...");
msg.registerOutgoingPluginChannel(this, "BungeeCord");
msg.registerIncomingPluginChannel(this, "BungeeCord", new BungeeAPI());
} else {
cs.sendMessage("§2[§aSpigotLib§2]§e Your server is §cnot connected§e to a BungeeCord server, §cskipping BungeeAPI§e load...");
}
vault = pm.getPlugin("Vault") != null;
EconomyAPI.registerBalanceType("exp", new ExpBalanceType(EconomyAPI.getBalanceType("exp")));
EconomyAPI.VaultHookType vaultHookType = EconomyAPI.getVaultHookType();
if (!vault)
cs.sendMessage("§2[§aSpigotLib§2]§e The plugin §aVault§e is not present, skipping hook...");
else {
if (vaultHookType == NONE) {
cs.sendMessage("§2[§aSpigotLib§2]§e The plugin §aVault§e is present, but the hook is disabled in config, so skipping hook...");
}
if (vaultHookType == USER) {
cs.sendMessage("§2[§aSpigotLib§2]§e The plugin §aVault§e is present, hooking to it as §aEconomy USER§e...");
RegisteredServiceProvider<Economy> econService = srv.getServicesManager().getRegistration(Economy.class);
if (econService != null) {
econ = econService.getProvider();
EconomyAPI.registerBalanceType("default", new VaultBalanceType(EconomyAPI.getBalanceType("default")));
}
if (EconomyAPI.isMigrate()) {
cs.sendMessage("§2[§aSpigotLib§2]§e Migrating economy data from old Economy " + econ.getName() + "... ");
EconomyAPI.setVaultHookType(NONE);
for (OfflinePlayer op : Bukkit.getOfflinePlayers()) {
EconomyAPI.setBalance(op.getUniqueId(), BigDecimal.valueOf(econ.getBalance(op)));
log(this, "Done player " + op.getName());
}
EconomyAPI.setVaultHookType(PROVIDER);
EconomyAPI.setMigrate(false);
log(this, "Finished data migration, please restart the server!");
setEnabled(false);
return;
}
}
}
sch.scheduleSyncDelayedTask(this, () -> {
if (!forceReducedMode && schedulePacketAPI)
startPacketAPI();
if (vault) {
if (EconomyAPI.getVaultHookType() == USER) {
RegisteredServiceProvider<Economy> rspEcon = srv.getServicesManager().getRegistration(Economy.class);
if (rspEcon != null)
econ = rspEcon.getProvider();
}
RegisteredServiceProvider<Permission> rspPerm = srv.getServicesManager().getRegistration(Permission.class);
if (rspPerm != null)
perm = (Permission) rspPerm.getProvider();
RegisteredServiceProvider<Chat> rspChat = srv.getServicesManager().getRegistration(Chat.class);
if (rspChat != null)
chat = (Chat) rspChat.getProvider();
}
if (TPSMeter.enabled) {
cs.sendMessage("§2[§aSpigotLib§2]§e Starting TPSMeter...");
Config.tpsMeter.start();
}
cs.sendMessage("§2[§aSpigotLib§2]§e Starting PlaceholderAPI hook...");
VariableAPI.init();
cs.sendMessage("§2[§aSpigotLib§2]§a Started SpigotLib §e" + version + "§a properly.");
}, 1);
}
public void onLoad() {
pl = this;
try {
srv = getServer();
cs = srv.getConsoleSender();
if (cs == null)
return;
pm = srv.getPluginManager();
msg = srv.getMessenger();
sm = srv.getServicesManager();
sch = srv.getScheduler();
js = new ScriptEngineManager().getEngineByName("JavaScript");
dir = getDataFolder();
cs.sendMessage("§2[§aSpigotLib§2]§e Loading §aReflectionAPI§e...");
Reflection.init();
pluginsF = Reflection.getField(pm.getClass(), "plugins");
lookupNamesF = Reflection.getField(pm.getClass(), "lookupNames");
} catch (Throwable e) {
log(this, "§cFailed to get default Bukkit managers :-( The plugin is shutting down...");
error(cs, e, "SpigotLib", "gyurix");
pm.disablePlugin(this);
return;
}
try {
ConfigHook.registerSerializers();
ConfigHook.registerVariables();
CommandMatcher.registerCustomMatchers();
} catch (Throwable e) {
log(this, "§cFailed to load config hook :-( The plugin is shutting down...");
error(cs, e, "SpigotLib", "gyurix");
pm.disablePlugin(this);
return;
}
try {
load();
} catch (Throwable e) {
log(this, "Failed to load plugin, trying to reset the config...");
error(cs, e, "SpigotLib", "gyurix");
resetConfig();
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerLeave(PlayerQuitEvent e) {
Player plr = e.getPlayer();
UUID uid = plr.getUniqueId();
if (backend == BackendType.MYSQL) {
savePlayerConfig(uid);
unloadPlayerConfig(uid);
}
AnimationAPI.stopRunningAnimations(plr);
if (!forceReducedMode && ver.isAbove(v1_8))
ScoreboardAPI.playerLeave(plr);
DataReader.cancel(plr);
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerLogin(PlayerLoginEvent e) {
Player plr = e.getPlayer();
if (backend == BackendType.MYSQL && !loadedPlayers.contains(plr.getUniqueId())) {
MySQLDatabase.batchThread.submit(() -> {
cs.sendMessage("Player " + e.getPlayer().getUniqueId() + " was not loaded yet, loading it now...");
loadPlayerConfig(plr.getUniqueId());
});
}
if (!forceReducedMode)
ScoreboardAPI.playerJoin(plr);
}
@EventHandler
public void onPluginUnload(PluginDisableEvent e) {
Plugin pl = e.getPlugin();
AnimationAPI.stopRunningAnimations(pl);
DataReader.cancel(pl);
CloseableGUI.cancel(pl);
if (tp != null) {
tp.unregisterIncomingListener(pl);
tp.unregisterOutgoingListener(pl);
}
//pf.data.unWrapAll();
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPreLogin(AsyncPlayerPreLoginEvent e) {
if (ver != UNKNOWN) {
UUID id = e.getUniqueId();
if (Config.logPlayerConfigLoadUnload)
cs.sendMessage("§ePreLogin - §b" + e.getUniqueId());
if (backend == BackendType.MYSQL) {
loadPlayerConfig(id);
}
}
}
@EventHandler
public void onWeatherChange(WeatherChangeEvent e) {
if (Config.disableWeatherChange)
e.setCancelled(true);
}
@EventHandler
public void registerServiceEvent(ServiceRegisterEvent e) {
RegisteredServiceProvider p = e.getProvider();
String sn = p.getService().getName();
switch (sn) {
case "net.milkbowl.vault.chat.Chat":
chat = (Chat) p.getProvider();
break;
case "net.milkbowl.vault.economy.Economy":
econ = (Economy) p.getProvider();
break;
case "net.milkbowl.vault.permission.Permission":
perm = (Permission) p.getProvider();
break;
}
}
public void resetConfig() {
try {
File oldConf = new File(dir + File.separator + "config.yml");
File backupConf = new File(dir + File.separator + "config.yml.bak");
if (backupConf.exists())
backupConf.delete();
oldConf.renameTo(backupConf);
File oldLang = new File(dir + File.separator + "lang.yml");
File backupLang = new File(dir + File.separator + "lang.yml.bak");
if (backupLang.exists()) {
backupLang.delete();
}
oldLang.renameTo(backupLang);
} catch (Throwable e) {
log(this, "§cFailed to reset the config :-( The plugin is shutting down...");
error(cs, e, "SpigotLib", "gyurix");
pm.disablePlugin(this);
return;
}
try {
load();
} catch (Throwable e) {
log(this, "§cFailed to load plugin after config reset :-( The plugin is shutting down...");
error(cs, e, "SpigotLib", "gyurix");
pm.disablePlugin(this);
}
}
public void startPacketAPI() {
cs.sendMessage("§2[§aSpigotLib§2]§e Starting PacketAPI...");
try {
tp.init();
} catch (Throwable e) {
if (schedulePacketAPI) {
error(cs, e, "SpigotLib", "gyurix");
cs.sendMessage("§2[§aSpigotLib§2]§c Failed to start PacketAPI.");
}
schedulePacketAPI = true;
cs.sendMessage("§2[§aSpigotLib§2]§e Scheduled PacketAPI SpigotLib.");
}
}
@EventHandler
public void unregisterServiceEvent(ServiceUnregisterEvent e) {
RegisteredServiceProvider p = e.getProvider();
String sn = p.getService().getName();
switch (sn) {
case "net.milkbowl.vault.chat.Chat":
chat = null;
break;
case "net.milkbowl.vault.economy.Economy":
econ = null;
break;
case "net.milkbowl.vault.permission.Permission":
perm = null;
break;
}
}
}
| 20,627 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
GlobalLangFile.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotlib/GlobalLangFile.java | package gyurix.spigotlib;
import gyurix.chat.ChatTag;
import gyurix.configfile.ConfigData;
import gyurix.spigotlib.ChatAPI.ChatMessageType;
import lombok.Getter;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import static gyurix.spigotlib.Config.debug;
public class GlobalLangFile {
public static final HashMap<String, HashMap<String, String>> map = new HashMap<>();
/**
* @param lang - The language
* @param adr - The key to the message
* @return The message from the language file. If not found then an error message is returned.
*/
public static String get(String lang, String adr) {
HashMap<String, String> m;
String msg;
if (lang != null && !lang.isEmpty()) {
m = map.get(lang);
if (m != null) {
msg = m.get(adr);
if (msg != null) {
return msg;
}
debug.msg("Lang", "§cThe requested key (" + adr + ") is missing from language " + lang + ". Using servers default language...");
}
SU.log(Main.pl, "§cThe requested language (" + lang + ") is not available.");
}
if ((m = map.get(Config.defaultLang)) != null) {
msg = m.get(adr);
if (msg != null) {
return msg;
}
debug.msg("Lang", "§cThe requested key (" + adr + ") is missing from servers default language (" + Config.defaultLang + "). Trying to find it in any other language...");
}
for (HashMap<String, String> l : map.values()) {
String msg2 = l.get(adr);
if (msg2 == null) continue;
return msg2;
}
debug.msg("Lang", "§cThe requested key (" + adr + ") wasn't found in any language.");
return "§cNot found (§f" + lang + "." + adr + "§c)\\-T§ePlease try to remove the plugins lang.yml file. If the problem still appears, please contact the plugins dev.\\-S" + lang + "." + adr + " ";
}
private static void load(String[] data) {
StringBuilder adr = new StringBuilder(".en");
StringBuilder cs = new StringBuilder();
int lvl = 0;
int line = 0;
for (String s : data) {
int blockLvl = 0;
++line;
while (s.charAt(blockLvl) == ' ') {
++blockLvl;
}
String[] d = ((s = s.substring(blockLvl)) + " ").split(" *: +", 2);
if (d.length == 1) {
s = ConfigData.unescape(s);
if (cs.length() != 0) {
cs.append('\n');
}
cs.append(s);
continue;
}
put(adr.substring(1), cs.toString());
cs.setLength(0);
if (blockLvl == lvl + 2) {
adr.append(".").append(d[0]);
lvl += 2;
} else if (blockLvl == lvl) {
adr = new StringBuilder(adr.substring(0, adr.toString().lastIndexOf('.') + 1) + d[0]);
} else if (blockLvl < lvl && blockLvl % 2 == 0) {
while (blockLvl != lvl) {
lvl -= 2;
adr = new StringBuilder(adr.substring(0, adr.toString().lastIndexOf('.')));
}
adr = new StringBuilder(adr.substring(0, adr.toString().lastIndexOf('.') + 1) + d[0]);
} else {
throw new RuntimeException("Block leveling error in line " + line + " (block level = " + blockLvl + ", previous = " + lvl + ")!");
}
if (d[1].isEmpty()) continue;
cs.append(d[1], 0, d[1].length() - 1);
}
put(adr.substring(1), cs.toString());
}
/**
* @param pn - The name of the plugin
* @param stream - InputStream of the language file
* @param fn - The name of the language file
* @return The PluginLang or null
*/
public static PluginLang loadLF(String pn, InputStream stream, String fn) {
try {
byte[] bytes = new byte[stream.available()];
stream.read(bytes);
load(new String(bytes, "UTF-8").replaceAll("&([0-9a-fk-or])", "§$1").split("\r?\n"));
load(new String(Files.readAllBytes(new File(fn).toPath()), "UTF-8").replaceAll("&([0-9a-fk-or])", "§$1").split("\r?\n"));
return new PluginLang(pn);
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
/**
* @param pn - The name of the plugin
* @param fn - The name of the language file
* @return The PluginLang or null
*/
public static PluginLang loadLF(String pn, String fn) {
try {
load(new String(Files.readAllBytes(new File(fn).toPath()), "UTF-8").replaceAll("&([0-9a-fk-or])", "§$1").split("\r?\n"));
return new PluginLang(pn);
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
/**
* @param adr - The address to be changed
* @param value - The new value
*/
private static void put(String adr, String value) {
if (!adr.contains(".")) {
if (!map.containsKey(adr)) {
map.put(adr, new HashMap<>());
}
} else {
HashMap<String, String> m = map.get(adr.substring(0, adr.indexOf('.')));
m.put(adr.substring(adr.indexOf('.') + 1), value);
}
}
/**
* @param lng - The language file
*/
public static void unloadLF(PluginLang lng) {
for (HashMap<String, String> m : map.values()) {
Iterator<Entry<String, String>> i = m.entrySet().iterator();
while (i.hasNext()) {
Entry<String, String> e = i.next();
if (!e.getKey().matches(".*\\." + lng.pluginName + ".*")) continue;
i.remove();
}
}
}
public static class PluginLang {
@Getter
private final String pluginName;
private PluginLang(String plugin) {
pluginName = plugin;
}
public String get(Player plr, String adr, String... repl) {
return get(plr, adr, (Object[]) repl);
}
public String get(Player plr, String adr, Object... repl) {
String msg = GlobalLangFile.get(SU.getPlayerConfig(plr).getString("lang"), pluginName + '.' + adr);
Object key = null;
for (Object o : repl) {
if (key == null) {
key = o;
continue;
}
msg = msg.replace("<" + key + '>', String.valueOf(o));
key = null;
}
return msg;
}
/**
* @param prefix - Custom prefix of the message
* @param sender - The receiver of the message
* @param msg - The key of the message in the language file
* @param repl - The variables in the message
*/
public void msg(String prefix, CommandSender sender, String msg, Object... repl) {
Player plr = sender instanceof Player ? (Player) sender : null;
msg = prefix + get(plr, msg, repl);
if (plr == null) {
sender.sendMessage(ChatTag.stripExtras(msg));
} else {
ChatAPI.sendJsonMsg(ChatMessageType.CHAT, msg, plr);
}
}
/**
* @param sender - The receiver of the message
* @param msg - The key of the message in the language file
* @param repl - The variables in the message
*/
public void msg(CommandSender sender, String msg, String... repl) {
msg(sender, msg, (Object[]) repl);
}
/**
* @param sender - The receiver of the message
* @param msg - The key of the message in the language file
* @param repl - The variables in the message
*/
public void msg(CommandSender sender, String msg, Object... repl) {
Player plr = sender instanceof Player ? (Player) sender : null;
msg(get(plr, "prefix"), sender, msg, repl);
}
/**
* @param prefix - Custom prefix of the message
* @param sender - The receiver of the message
* @param msg - The key of the message in the language file
* @param repl - The variables in the message
*/
public void msg(String prefix, CommandSender sender, String msg, String... repl) {
msg(prefix, sender, msg, (Object[]) repl);
}
}
}
| 7,814 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ConfigHook.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotlib/ConfigHook.java | package gyurix.spigotlib;
import gyurix.configfile.ConfigData;
import gyurix.configfile.ConfigSerialization.Serializer;
import gyurix.economy.EconomyAPI;
import gyurix.protocol.Reflection;
import gyurix.sign.SignConfig;
import gyurix.spigotutils.ItemUtils;
import gyurix.spigotutils.TPSMeter;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.Vector;
import javax.script.ScriptException;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import static gyurix.api.VariableAPI.handlers;
import static gyurix.configfile.ConfigSerialization.getSerializers;
/**
* Collection of custom config serializers and custom variable handlers used only on Spigot
*/
public class ConfigHook {
/**
* Data storage for dget and dstore placeholders
*/
public static HashMap<String, Object> data = new HashMap<>();
/**
* Registers the custom serializers used only on Spigot
*/
public static void registerSerializers() {
HashMap<Class, Serializer> serializers = getSerializers();
serializers.put(SignConfig.class, new Serializer() {
@Override
public Object fromData(ConfigData cd, Class cl, Type... paramVarArgs) {
SignConfig sc = new SignConfig();
for (int i = 0; i < 4; i++) {
String s = cd.listData.get(i).stringData;
sc.lines.add(s.equals(" ") ? "" : s);
}
return sc;
}
@Override
public ConfigData toData(Object sco, Type... paramVarArgs) {
SignConfig sc = (SignConfig) sco;
ConfigData cd = new ConfigData();
cd.listData = new ArrayList<>();
for (int i = 0; i < 4; i++)
cd.listData.add(new ConfigData(sc.lines.get(i)));
return cd;
}
});
serializers.put(Vector.class, new Serializer() {
@Override
public Object fromData(ConfigData data, Class paramClass, Type... paramVarArgs) {
String[] s = data.stringData.split(" ", 3);
return new Vector(Double.parseDouble(s[0]), Double.parseDouble(s[1]), Double.parseDouble(s[2]));
}
@Override
public ConfigData toData(Object obj, Type... paramVarArgs) {
Vector v = (Vector) obj;
return new ConfigData(String.valueOf(v.getX()) + ' ' + v.getY() + ' ' + v.getZ());
}
});
serializers.put(Location.class, new Serializer() {
@Override
public Object fromData(ConfigData data, Class paramClass, Type... paramVarArgs) {
String[] s = data.stringData.split(" ", 6);
if (s.length == 4) {
return new Location(Bukkit.getWorld(s[0]), Double.parseDouble(s[1]), Double.parseDouble(s[2]), Double.parseDouble(s[3]));
}
return new Location(Bukkit.getWorld(s[0]), Double.parseDouble(s[1]), Double.parseDouble(s[2]), Double.parseDouble(s[3]), Float.parseFloat(s[4]), Float.parseFloat(s[5]));
}
@Override
public ConfigData toData(Object obj, Type... paramVarArgs) {
Location loc = (Location) obj;
if (loc.getPitch() == 0.0f && loc.getYaw() == 0.0f) {
return new ConfigData(loc.getWorld().getName() + ' ' + loc.getX() + ' ' + loc.getY() + ' ' + loc.getZ());
}
return new ConfigData(loc.getWorld().getName() + ' ' + loc.getX() + ' ' + loc.getY() + ' ' + loc.getZ() + ' ' + loc.getYaw() + ' ' + loc.getPitch());
}
});
serializers.put(ItemStack.class, new ItemSerializer());
serializers.put(PotionEffect.class, new PotionSerializer());
}
/**
* Registers the built in custom variable handlers
*/
public static void registerVariables() {
handlers.put("eval", (plr, inside, oArgs) -> {
String s = StringUtils.join(inside, "");
try {
return SU.js.eval(s);
} catch (ScriptException e) {
return "<eval:" + s + '>';
}
});
handlers.put("tobool", (plr, inside, oArgs) -> Boolean.valueOf(StringUtils.join(inside, "")));
handlers.put("tobyte", (plr, inside, oArgs) -> (byte) Double.valueOf(StringUtils.join(inside, "")).doubleValue());
handlers.put("toshort", (plr, inside, oArgs) -> (short) Double.valueOf(StringUtils.join(inside, "")).doubleValue());
handlers.put("toint", (plr, inside, oArgs) -> (int) Double.valueOf(StringUtils.join(inside, "")).doubleValue());
handlers.put("tolong", (plr, inside, oArgs) -> (long) Double.valueOf(StringUtils.join(inside, "")).doubleValue());
handlers.put("tofloat", (plr, inside, oArgs) -> Float.valueOf(StringUtils.join(inside, "")));
handlers.put("todouble", (plr, inside, oArgs) -> Double.valueOf(StringUtils.join(inside, "")));
handlers.put("tostr", (plr, inside, oArgs) -> StringUtils.join(inside, ""));
handlers.put("toarray", (plr, inside, oArgs) -> inside.toArray());
handlers.put("substr", (plr, inside, oArgs) -> {
String[] s = StringUtils.join(inside, "").split(" ", 3);
int from = Integer.parseInt(s[0]);
int to = Integer.parseInt(s[1]);
return s[2].substring(from < 0 ? s[2].length() + from : from, to < 0 ? s[2].length() + to : to);
});
handlers.put("splits", (plr, inside, oArgs) -> StringUtils.join(inside, "").split(" "));
handlers.put("splitlen", (plr, inside, oArgs) -> {
String[] s = StringUtils.join(inside, "").split(" ", 3);
int max = Integer.parseInt(s[0]);
String pref = SU.unescapeText(s[1]);
String text = s[2];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < text.length(); i += max) {
sb.append('\n').append(pref).append(text, i, Math.min(text.length(), i + max));
}
return sb.length() == 0 ? "" : sb.substring(1);
});
handlers.put("noout", (plr, inside, oArgs) -> "");
handlers.put("lang", (plr, inside, oArgs) -> {
String s = StringUtils.join(inside, "");
String lang = SU.getPlayerConfig(plr).getString("lang");
return s.isEmpty() ? lang : GlobalLangFile.get(lang, s);
});
handlers.put("booltest", (plr, inside, oArgs) -> {
String[] s = StringUtils.join(inside, "").split(";");
return Boolean.parseBoolean(s[0]) ? s[1] : s[2];
});
handlers.put("args", (plr, inside, oArgs) -> {
int id = Integer.parseInt(StringUtils.join(inside, ""));
return oArgs[id];
});
handlers.put("len", (plr, inside, oArgs) -> {
Object o = inside.get(0);
return o.getClass().isArray() ? Array.getLength(o) : ((Collection<?>) o).size();
});
handlers.put("iarg", (plr, inside, oArgs) -> {
int id = Integer.parseInt(inside.get(0).toString());
return inside.get(id);
});
handlers.put("plr", (plr, inside, oArgs) -> Reflection.getData(plr, inside));
handlers.put("obj", (plr, inside, oArgs) -> Reflection.getData(oArgs[0], inside));
handlers.put("iobj", (plr, inside, oArgs) -> {
Object obj = inside.remove(0);
return Reflection.getData(obj, inside);
});
handlers.put("dstore", (plr, inside, oArgs) -> {
if (inside.size() == 1) {
String[] s = StringUtils.join(inside, "").split(" ", 2);
return data.put(s[0], s[1]);
}
return data.put(inside.get(0).toString(), inside.get(1));
});
handlers.put("dget", (plr, inside, oArgs) -> data.get(StringUtils.join(inside, "")));
handlers.put("tps", (plr, inside, oArgs) -> TPSMeter.tps);
handlers.put("real", (plr, inside, oArgs) -> System.currentTimeMillis());
handlers.put("formattime", (plr, inside, oArgs) -> {
String str = StringUtils.join(inside, "");
int id = str.indexOf(' ');
long time = Long.parseLong(str.substring(0, id));
String format = str.substring(id + 1);
return new SimpleDateFormat(format).format(time);
});
handlers.put("balf", (plr, inside, oArgs) -> {
if (inside == null || inside.isEmpty()) {
return EconomyAPI.getBalanceType("default").format(EconomyAPI.getBalance(plr.getUniqueId()));
}
String balanceType = StringUtils.join(inside, "");
return EconomyAPI.getBalanceType(balanceType).format(
EconomyAPI.getBalance(plr.getUniqueId(), balanceType).setScale(2, BigDecimal.ROUND_HALF_UP));
});
}
/**
* Custom config Serializer used for saving and loading ItemStacks
*/
public static class ItemSerializer implements Serializer {
@Override
public Object fromData(ConfigData data, Class cl, Type... paramVarArgs) {
return ItemUtils.stringToItemStack(data.stringData);
}
@Override
public ConfigData toData(Object is, Type... paramVarArgs) {
return new ConfigData(ItemUtils.itemToString((ItemStack) is));
}
}
/**
* Custom config Serializer used for saving and loading ItemStacks
*/
public static class PotionSerializer implements Serializer {
@Override
public Object fromData(ConfigData data, Class cl, Type... paramVarArgs) {
String[] d = data.stringData.split(" ");
switch (d.length) {
case 2:
return new PotionEffect(PotionEffectType.getByName(d[0]), Integer.parseInt(d[1]), 0);
case 3:
return new PotionEffect(PotionEffectType.getByName(d[0]), Integer.parseInt(d[1]), Integer.parseInt(d[2]));
}
return null;
}
@Override
public ConfigData toData(Object obj, Type... paramVarArgs) {
PotionEffect potion = (PotionEffect) obj;
return new ConfigData(potion.getType().getName() + " " + potion.getDuration() + " " + potion.getAmplifier());
}
}
}
| 9,720 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
PHAHook.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotlib/PHAHook.java | package gyurix.spigotlib;
import gyurix.api.VariableAPI;
import me.clip.placeholderapi.PlaceholderAPI;
import me.clip.placeholderapi.PlaceholderHook;
import org.bukkit.entity.Player;
/**
* PlaceholderAPI %sl_% placeholder hook, used for making plugins using PlaceholderAPI instead of SpigotLib's
* PlaceholderAPI compatible with SpigotLib PlaceholderAPI placeholders.
*/
public class PHAHook extends PlaceholderHook {
public PHAHook() {
PlaceholderAPI.registerPlaceholderHook("sl", this);
}
@Override
public String onPlaceholderRequest(Player plr, String msg) {
return VariableAPI.fillVariables(msg, plr);
}
}
| 634 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
ChatAPI.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotlib/ChatAPI.java | package gyurix.spigotlib;
import gyurix.chat.ChatTag;
import gyurix.json.JsonAPI;
import gyurix.protocol.Reflection;
import gyurix.protocol.wrappers.outpackets.PacketPlayOutChat;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.lang.reflect.Method;
import java.util.Collection;
import static gyurix.spigotlib.Config.debug;
import static gyurix.spigotutils.ServerVersion.v1_8;
public class ChatAPI {
/**
* Method for converting IChatBaseComponent to raw JSON.
*/
public static Method fromICBC;
/**
* The IChatBaseComponent class
*/
public static Class icbcClass;
/**
* Method for converting raw json to IChatBaseComponent.
*/
public static Method toICBC;
/**
* Converts the given message to raw JSON format
*
* @param msg - The message
* @return The conversion result raw json
*/
public static String TextToJson(String msg) {
return ChatTag.fromExtraText(msg).toString();
}
/**
* Initializes the ChatAPI. Do not use this method.
*/
public static void init() {
try {
icbcClass = Reflection.getNMSClass("IChatBaseComponent");
Class serializerClass = Reflection.getNMSClass("ChatSerializer");
if (serializerClass == null)
for (Class c : icbcClass.getClasses())
if (c.getName().endsWith("ChatSerializer")) {
serializerClass = c;
break;
}
toICBC = serializerClass.getMethod("a", String.class);
fromICBC = serializerClass.getMethod("a", icbcClass);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
/**
* Converts a string to it's json format
*
* @param value - The convertable String
* @return The conversion result
*/
public static String quoteJson(String value) {
return "{\"text\":\"" + JsonAPI.escape(value) + "\"}";
}
/**
* Sends the given type json message to the given players or to every online player
*
* @param type - The type of the sendable JSON message
* @param msg - The json message
* @param pls - The receiver list, if it is empty then all the online players will get the message
*/
public static void sendJsonMsg(ChatMessageType type, String msg, Player... pls) {
if (pls.length == 0) {
sendJsonMsg(type, msg, Bukkit.getOnlinePlayers());
return;
}
String json = type == ChatMessageType.ACTION_BAR ? quoteJson(msg) : TextToJson(msg);
sendRawJson(type, json, pls);
}
/**
* Sends the given type json message to the given players or to every online player
*
* @param type - The type of the sendable JSON message
* @param msg - The json message
* @param pls - The receiver list, if it is empty then all the online players will get the message
*/
public static void sendJsonMsg(ChatMessageType type, String msg, Collection<? extends Player> pls) {
if (!Config.forceReducedMode && Reflection.ver.isAbove(v1_8)) {
String json = type == ChatMessageType.ACTION_BAR ? quoteJson(msg) : TextToJson(msg);
sendRawJson(type, json, pls);
} else {
msg = ChatTag.stripExtras(msg);
for (Player p : pls)
p.sendMessage(msg);
}
}
/**
* Sends a raw Json message to the given players
*
* @param type - The type of the sendable JSON message
* @param json - The raw json
* @param pls - The receiver list
*/
public static void sendRawJson(ChatMessageType type, String json, Player... pls) {
debug.msg("Chat", "§bSendRawJson - §f" + json);
if (!Config.forceReducedMode) {
Object packet = new PacketPlayOutChat((byte) type.ordinal(), JsonAPI.deserialize(json, ChatTag.class)).getVanillaPacket();
for (Player p : pls)
SU.tp.sendPacket(p, packet);
return;
}
json = JsonAPI.deserialize(json, ChatTag.class).toColoredString();
for (Player p : pls)
p.sendMessage(json);
}
/**
* Sends a raw Json message to the given players
*
* @param type - The type of the sendable JSON message
* @param json - The raw json
* @param pls - The receiver list
*/
public static void sendRawJson(ChatMessageType type, String json, Collection<? extends Player> pls) {
debug.msg("Chat", "§bSendRawJson - §f" + json);
if (!Config.forceReducedMode) {
Object packet = new PacketPlayOutChat((byte) type.ordinal(), JsonAPI.deserialize(json, ChatTag.class)).getVanillaPacket();
for (Player p : pls)
SU.tp.sendPacket(p, packet);
return;
}
String[] j = JsonAPI.deserialize(json, ChatTag.class).toColoredString().split("\n");
for (Player p : pls)
p.sendMessage(j);
}
/**
* Converts a raw json message to vanilla IChatBaseComponent
*
* @param json - The raw json
* @return The vanilla IChatBaseComponent
*/
public static Object toICBC(String json) {
try {
return json == null ? null : toICBC.invoke(null, json);
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
/**
* Converts a vanilla IChatBaseComponent to a raw Json message
*
* @param icbc - The vanilla IChatBaseComponent
* @return The raw json message
*/
public static String toJson(Object icbc) {
try {
if (icbc == null) {
return null;
}
return (String) fromICBC.invoke(null, icbc);
} catch (Throwable e) {
debug.msg("Chat", e);
return null;
}
}
/**
* Escapes an unicode character
*
* @param ch - The escapeable character
* @return The unicode escaped character in String
*/
public static String unicodeEscape(char ch) {
StringBuilder sb = new StringBuilder();
sb.append("\\u");
String hex = Integer.toHexString(ch);
for (int i = hex.length(); i < 4; ++i) {
sb.append('0');
}
sb.append(hex);
return sb.toString();
}
/**
* Enum of the available ChatMessageTypes
*/
public enum ChatMessageType {
CHAT,
SYSTEM,
ACTION_BAR;
ChatMessageType() {
}
}
} | 6,002 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Items.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotlib/Items.java | package gyurix.spigotlib;
import gyurix.configfile.ConfigSerialization.ConfigOptions;
import gyurix.configfile.PostLoadable;
import gyurix.spigotutils.BlockData;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import static com.google.common.collect.Lists.newArrayList;
/**
* Class representing the custom item names stored in the config, used in the ItemAPI
*/
public class Items implements PostLoadable {
/**
* The map containing all the enchant alias (in keys) and their corresponding enchants (in values)
*/
@ConfigOptions(serialize = false)
private static HashMap<String, Enchantment> enchantAliases = new HashMap<>();
/**
* The in config editable enchant name (key), enchant aliases (value) map.
*/
private static HashMap<String, ArrayList<String>> enchants = new HashMap<>();
/**
* The map containing all the material ids and their corresponding materials (values)
*/
private static HashMap<Integer, Material> materialIds = new HashMap<>();
/**
* The map containing all the item names (in keys) and their corresponding item types (values)
*/
@ConfigOptions(serialize = false)
private static HashMap<String, ItemStack> nameAliases = new HashMap<>();
/**
* The in config editable item type (key), item name aliases (value) map.
*/
private static HashMap<BlockData, ArrayList<String>> names = new HashMap<>();
/**
* Add an item name alias to item to string and item from string converters
*
* @param name - The items name
* @param item - The item
*/
public static void addItemNameAlias(String name, ItemStack item) {
nameAliases.put(name, item);
}
public static Enchantment getEnchant(String name) {
name = name.toLowerCase();
Enchantment enchantment = enchantAliases.get(name);
if (enchantment == null) {
name = name.toUpperCase();
return Enchantment.getByName(name);
}
return enchantment;
}
public static String getEnchantName(Enchantment ench) {
String out = ench.getName();
List<String> encs = enchants.get(out);
if (encs == null)
return out;
return encs.get(0);
}
public static ItemStack getItem(String name) {
name = name.toLowerCase();
ItemStack is = nameAliases.get(name);
if (is != null)
return is.clone();
try {
return new ItemStack(Material.valueOf(name.toUpperCase()));
} catch (Throwable ignored) {
try {
return new ItemStack(getMaterial(Integer.parseInt(name)));
} catch (Throwable ig) {
try {
return new ItemStack(Material.valueOf("LEGACY_"+name.toUpperCase()));
} catch(Throwable i) {
try {
return new ItemStack(Material.valueOf(name.toUpperCase().replace("LEGACY_", "")));
} catch(Throwable t) {
SU.cs.sendMessage("§cInvalid item name or id: §e" + name);
}
}
}
System.out.println("Name = \"" + name + "\"");
}
return null;
}
public static Material getMaterial(int id) {
Material mat = materialIds.get(id);
if (mat == null)
throw new RuntimeException("Item for id " + id + " was not found.");
return mat;
}
public static String getName(BlockData block) {
ArrayList<String> list = names.get(block);
if (list == null)
return block.getType().name();
return list.get(0);
}
public static List<String> getNames(BlockData block) {
return names.get(block);
}
/**
* Remove an item name alias from the item to string and item from string converters
*
* @param name - The items name
* @return True if the item name alias was removed successfully, false otherwise
*/
public static boolean removeItemNameAlias(String name) {
return nameAliases.remove(name) != null;
}
/**
* Makes the enchantAliases and nameAliases caches.
*/
@Override
public void postLoad() {
for (Material m : Material.values()) {
try {
materialIds.put(m.getId(), m);
} catch (Throwable ignored) {
}
}
for (Enchantment e : Enchantment.values()) {
if (!enchants.containsKey(e.getName()))
enchants.put(e.getName(), newArrayList(e.getName().toLowerCase().replace("_", "")));
}
enchantAliases.clear();
for (Entry<String, ArrayList<String>> e : enchants.entrySet()) {
Enchantment ec = Enchantment.getByName(e.getKey());
for (String s : e.getValue()) {
enchantAliases.put(s, ec);
}
}
nameAliases.clear();
for (Entry<BlockData, ArrayList<String>> e : names.entrySet()) {
BlockData bd = e.getKey();
for (String s : e.getValue()) {
try {
nameAliases.put(s, bd.toItem());
} catch (Throwable err) {
SU.error(SU.cs, err, "SpigotLib", "gyurix");
}
}
}
}
}
| 4,969 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
SU.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotlib/SU.java | package gyurix.spigotlib;
import gyurix.commands.CustomCommandMap;
import gyurix.configfile.ConfigFile;
import gyurix.mojang.MojangAPI;
import gyurix.mysql.MySQLDatabase;
import gyurix.protocol.Protocol;
import gyurix.protocol.Reflection;
import gyurix.protocol.utils.GameProfile;
import gyurix.spigotlib.Config.PlayerFile;
import gyurix.spigotutils.BackendType;
import gyurix.spigotutils.DualMap;
import gyurix.spigotutils.ServerVersion;
import net.milkbowl.vault.chat.Chat;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import org.apache.commons.lang.StringUtils;
import org.bukkit.*;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.ServicesManager;
import org.bukkit.plugin.messaging.Messenger;
import org.bukkit.scheduler.BukkitScheduler;
import javax.script.ScriptEngine;
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.Map.Entry;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static gyurix.commands.CustomCommandMap.knownCommands;
/**
* SpigotLib utilities class
*/
public final class SU {
public static final Charset utf8 = StandardCharsets.UTF_8;
private static final Field NAMED_GROUPS_FIELD = Reflection.getField(Pattern.class, "namedGroups");
/**
* The instance of current Chat provider in Vault
*/
public static Chat chat;
/**
* Instance of the CustomCommandMap used by SpigotLibs CommandAPI
*/
public static CustomCommandMap cm;
/**
* The main instance of the ConsoleCommandSender object.
*/
public static ConsoleCommandSender cs;
private static final Pattern REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");
/**
* The instance of current Economy provider in Vault
*/
public static Economy econ;
/**
* An instance of the Javascript script engine, used for the eval variable
*/
public static ScriptEngine js;
public static Set<UUID> loadedPlayers = Collections.synchronizedSet(new HashSet<>());
/**
* The main instance of the Messenger object.
*/
public static Messenger msg;
/**
* The instance of current Permission provider in Vault
*/
public static Permission perm;
/**
* Player configuration file instance (players.yml file in the SpigotLib)
*/
public static ConfigFile pf;
/**
* The main instance of the PluginManager object.
*/
public static PluginManager pm;
/**
* An instance of the Random number generator
*/
public static Random rand = new Random();
/**
* The main instance of the BukkitScheduler object.
*/
public static BukkitScheduler sch;
/**
* The main instance of the ServicesManager object
*/
public static ServicesManager sm;
/**
* The main instance of the CraftServer object.
*/
public static Server srv;
/**
* PacketAPI instance
*/
public static Protocol tp;
/**
* Name - UUID cache
*/
public static DualMap<String, UUID> uuidCache = new DualMap<>();
/**
* True if Vault is found on the server
*/
public static boolean vault;
static Field pluginsF, lookupNamesF;
private static Field entityF;
private static Constructor entityPlayerC, playerInterractManagerC;
private static Method getBukkitEntityM, loadDataM, saveDataM;
private static Field pingF;
private static Object worldServer, mcServer;
/**
* Sends an error report to the given sender and to console. The report only includes the stack trace parts, which
* contains the authors name
*
* @param sender - The CommandSender who should receive the error report
* @param err - The error
* @param plugin - The plugin where the error appeared
* @param author - The author name, which will be searched in the error report
*/
public static void error(CommandSender sender, Throwable err, String plugin, String author) {
if (Config.silentErrors)
return;
StringBuilder report = new StringBuilder();
report.append("§4§l").append(plugin).append(" - ERROR REPORT - §e§l")
.append(err.getClass().getSimpleName());
do {
if (err.getMessage() != null)
report.append('\n').append(err.getMessage());
int i = 0;
boolean startrep = true;
for (StackTraceElement el : err.getStackTrace()) {
boolean force = el.getClassName() != null && el.getClassName().contains(author);
if (force)
startrep = false;
if (startrep || force)
report.append("\n§c #").append(++i)
.append(": §eLINE §a").append(el.getLineNumber())
.append("§e in FILE §6").append(el.getFileName())
.append("§e (§7").append(el.getClassName())
.append("§e.§b").append(el.getMethodName())
.append("§e)");
}
err = err.getCause();
if (err != null) {
report.append("\n§4§lCaused by - §e§l").append(err.getClass().getSimpleName());
}
} while (err != null);
String rep = report.toString();
if (cs == null) {
System.err.println(ChatColor.stripColor(rep));
return;
}
cs.sendMessage(rep);
if (sender != null && sender != cs)
sender.sendMessage(rep);
}
/**
* Escapes the given regex, without quoting it, like Pattern.quote does
*
* @param regex - The escapable regex
* @return The escaped regex
*/
public static String escapeRegex(String regex) {
return REGEX_CHARS.matcher(regex).replaceAll("\\\\$0");
}
/**
* Escape multi line text to a single line one
*
* @param text multi line escapeable text input
* @return The escaped text
*/
public static String escapeText(String text) {
return text.replace("\\", "\\\\")
.replace("_", "\\_")
.replace("|", "\\|")
.replace(" ", "_")
.replace("\n", "|");
}
/**
* Fills variables in a String
*
* @param s - The String
* @param vars - The variables and their values, which should be filled
* @return The variable filled String
*/
public static String fillVariables(String s, HashMap<String, Object> vars) {
for (Entry<String, Object> v : vars.entrySet())
s = s.replace('<' + v.getKey() + '>', String.valueOf(v.getValue()));
return s;
}
/**
* Fills variables in a String
*
* @param s - The String
* @param vars - The variables and their values, which should be filled
* @return The variable filled String
*/
public static String fillVariables(String s, Object... vars) {
String last = null;
for (Object v : vars) {
if (last == null)
last = (String) v;
else {
s = s.replace('<' + last + '>', String.valueOf(v));
last = null;
}
}
return s;
}
/**
* Fills variables in an iterable
*
* @param iterable - The iterable
* @param vars - The variables and their values, which should be filled
* @return The variable filled iterable converted to an ArrayList
*/
public static ArrayList<String> fillVariables(Iterable<String> iterable, Object... vars) {
ArrayList<String> out = new ArrayList<>();
iterable.forEach((s) -> {
String last = null;
for (Object v : vars) {
if (last == null)
last = (String) v;
else {
s = s.replace('<' + last + '>', String.valueOf(v));
last = null;
}
}
out.add(s);
});
return out;
}
/**
* Fills variables in a String and highlight them by using the given prefix and suffix
*
* @param s - The String
* @param prefix - The prefix used for highlighting
* @param suffix - The suffix used for highlighting
* @param vars - The variables and their values, which should be filled
* @return The variable filled String
*/
public static String fillVariablesHighlighted(String prefix, String suffix, String s, Object... vars) {
String last = null;
for (Object v : vars) {
if (last == null)
last = (String) v;
else {
s = s.replace('<' + last + '>', prefix + v + suffix);
last = null;
}
}
return s;
}
/**
* Filters the startings of the given data
*
* @param data - The data to be filtered
* @param start - Filter every string which starts with this one
* @return The filtered Strings
*/
public static ArrayList<String> filterStart(String[] data, String start) {
start = start.toLowerCase();
ArrayList<String> ld = new ArrayList<>();
for (String s : data) {
if (s.toLowerCase().startsWith(start))
ld.add(s);
}
Collections.sort(ld);
return ld;
}
/**
* Filters the startings of the given data
*
* @param data - The data to be filtered
* @param start - Filter every string which starts with this one
* @return The filtered Strings
*/
public static ArrayList<String> filterStart(Iterable<String> data, String start) {
start = start.toLowerCase();
ArrayList<String> ld = new ArrayList<>();
for (String s : data) {
if (s.toLowerCase().startsWith(start))
ld.add(s);
}
Collections.sort(ld);
return ld;
}
public static ArrayList<Class<?>> getClasses(String packageName) {
ArrayList<Class<?>> classes = new ArrayList<>();
try {
String packagePrefix = packageName.replace(".", "/");
File f = new File(Material.class.getProtectionDomain().getCodeSource().getLocation().toString().substring(6));
ZipInputStream zis = new ZipInputStream(new FileInputStream(f));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String name = ze.getName();
if (name.startsWith(packagePrefix) && name.endsWith(".class") && !name.contains("$"))
classes.add(Class.forName(name.substring(0, name.length() - 6).replace("/", ".")));
ze = zis.getNextEntry();
}
} catch (Throwable e) {
e.printStackTrace();
}
return classes;
}
/**
* Get the name of an offline player based on it's UUID.
*
* @param id UUID of the target player
* @return The name of the requested player or null if the name was not found.
*/
public static String getName(UUID id) {
Player plr = Bukkit.getPlayer(id);
if (plr != null)
return plr.getName();
OfflinePlayer op = Bukkit.getOfflinePlayer(id);
if (op == null)
return MojangAPI.getProfile(id.toString()).name;
return op.getName();
}
public static UUID getOfflineUUID(String name) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(utf8));
}
public static UUID getOnlineUUID(String name) {
name = name.toLowerCase();
UUID uid = uuidCache.get(name);
if (uid == null) {
GameProfile prof = MojangAPI.getProfile(name);
if (prof == null) {
cs.sendMessage("§cInvalid online player name: §e" + name + "§c. Using offline UUID.");
return getOfflineUUID(name);
}
uid = prof.id;
uuidCache.put(name, uid);
}
return uid;
}
/**
* Get the ping of a player in milliseconds
*
* @param plr target player
* @return The ping of the given player in milliseconds.
*/
public static int getPing(Player plr) {
try {
return pingF.getInt(entityF.get(plr));
} catch (Throwable e) {
e.printStackTrace();
}
return -1;
}
/**
* Gets the placeholders with their values from the given text
*
* @param format - The texts placeholder arrangement format
* @param text - The text
* @return TreeMap with the placeholders as keys and placeholder values as values, or null
* if the text can not be matched with the format
*/
public static TreeMap<String, String> getPlaceholders(String format, String text) {
try {
Pattern pattern = Pattern.compile(escapeRegex(format).replaceAll("<([^>]+)>", "(?<$1>.*)"));
Map<String, Integer> namedGroups = (Map<String, Integer>) NAMED_GROUPS_FIELD.get(pattern);
Matcher matcher = pattern.matcher(text);
if (!matcher.matches())
return null;
if (namedGroups == null)
return new TreeMap<>();
TreeMap<String, String> out = new TreeMap<>();
namedGroups.forEach((g, id) -> out.put(g, matcher.group(id)));
return out;
} catch (Throwable err) {
SU.error(SU.cs, err, "SpigotLib", "gyurix");
}
return null;
}
/**
* Get an online player or optionally load an offline player based on its name
*
* @param name name of the player, which should be got / active.
* @return The online player / active offline player who has the given name, or null if no such player have found.
*/
public static Player getPlayer(String name) {
try {
if (name.length() == 40) {
UUID uuid = UUID.fromString(name);
Player p = Bukkit.getPlayer(uuid);
if (p == null)
p = loadPlayer(uuid);
return p;
}
Player p = Bukkit.getPlayerExact(name);
if (p == null)
p = loadPlayer(getUUID(name));
return p;
} catch (IllegalArgumentException e) {
return null;
}
}
public static Player getPlayer(UUID uid) {
Player plr = Bukkit.getPlayer(uid);
if (plr != null)
return plr;
OfflinePlayer op = Bukkit.getOfflinePlayer(uid);
if (op != null)
return loadPlayer(uid);
return null;
}
/**
* Get the configuration part of a player or the CONSOLE
*
* @param plr the player, whos configuration part will be returned
* @return the configuration part of the given player, or the configuration part of the CONSOLE, if the given player
* is null.
*/
public static ConfigFile getPlayerConfig(Player plr) {
return getPlayerConfig(plr == null ? null : plr.getUniqueId());
}
/**
* Get the configuration part of an online/offline player using based on his UUID, or the
* configuration part of the CONSOLE, if the given UUID is null.
*
* @param plr the UUID of the online/offline player
* @return the configuration part of the given player, or the configuration part of the CONSOLE, if the given player
* UUID is null.
*/
public static ConfigFile getPlayerConfig(final UUID plr) {
String pln = plr == null ? "CONSOLE" : plr.toString();
if (pf.data.mapData == null)
pf.data.mapData = new LinkedHashMap<>();
if (PlayerFile.backend == BackendType.MYSQL && !loadedPlayers.contains(plr)) {
SU.error(SU.cs, new Throwable("Trying to get the config of player " + plr + ", who is not loaded"), "SpigotLib", "gyurix");
return null;
}
return pf.subConfig(pln);
}
/**
* Get the plugin containing the given class
*
* @param cl - The checkable class
* @return The plugin
*/
public static Plugin getPlugin(Class<?> cl) {
ClassLoader loader = cl.getClassLoader();
if (loader.getClass().getName().equals("org.bukkit.plugin.java.PluginClassLoader"))
return (Plugin) Reflection.getFieldData(loader.getClass(), "plugin", loader);
return null;
}
/**
* Get GameProfile of the given player. The GameProfile contains the players name, UUID and skin.
*
* @param plr target player
* @return the GameProfile of the target player
*/
public static GameProfile getProfile(Player plr) {
try {
return new GameProfile(plr.getClass().getMethod("getProfile").invoke(plr));
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
/**
* Get the UUID of an offline player based on his name.
*
* @param name name of the target player
* @return The UUID of the requested player, or null if it was not found.
*/
public static UUID getUUID(String name) {
Player plr = Bukkit.getPlayer(name);
if (plr != null)
return plr.getUniqueId();
OfflinePlayer[] offlinePls = Bukkit.getOfflinePlayers();
for (OfflinePlayer p : offlinePls) {
if (p.getName() != null && p.getName().equals(name))
return p.getUniqueId();
}
name = name.toLowerCase();
for (OfflinePlayer p : offlinePls) {
if (p.getName() != null && p.getName().toLowerCase().equals(name))
return p.getUniqueId();
}
for (OfflinePlayer p : offlinePls) {
if (p.getName() != null && p.getName().toLowerCase().contains(name))
return p.getUniqueId();
}
return getOnlineUUID(name);
}
/**
* Get the UUID of an offline player based on his name.
*
* @param name name of the target player
* @return The UUID of the requested player, or null if it was not found.
*/
public static UUID getUUIDExact(String name) {
Player plr = Bukkit.getPlayer(name);
if (plr != null)
return plr.getUniqueId();
OfflinePlayer[] offlinePls = Bukkit.getOfflinePlayers();
for (OfflinePlayer p : offlinePls) {
if (p.getName() != null && p.getName().equals(name))
return p.getUniqueId();
}
return MojangAPI.getProfile(name).id;
}
static void initOfflinePlayerManager() {
try {
if (PlayerFile.keepOfflineDataLoaded) {
for (OfflinePlayer p : Bukkit.getOfflinePlayers()) {
loadPlayerConfig(p.getUniqueId());
}
}
Class<?> mcServerClass = Reflection.getNMSClass("MinecraftServer");
Class<?> entityPlayerClass = Reflection.getNMSClass("EntityPlayer");
Class<?> craftPlayerClass = Reflection.getOBCClass("entity.CraftPlayer");
Class<?> pIMClass = Reflection.getNMSClass("PlayerInteractManager");
Class<?> worldServerClass = Reflection.getNMSClass("WorldServer");
entityF = Reflection.getField(Reflection.getOBCClass("entity.CraftEntity"), "entity");
pingF = Reflection.getNMSClass("EntityPlayer").getField("ping");
mcServer = mcServerClass.getMethod("getServer").invoke(null);
playerInterractManagerC = pIMClass.getConstructor(Reflection.getNMSClass(Reflection.ver.isAbove(ServerVersion.v1_14) ? "WorldServer" : "World"));
worldServer = Reflection.getFieldData(Reflection.getOBCClass("CraftWorld"), "world", Bukkit.getWorlds().iterator().next());
entityPlayerC = entityPlayerClass.getConstructor(mcServerClass, worldServerClass, Reflection.getUtilClass("com.mojang.authlib.GameProfile"), pIMClass);
getBukkitEntityM = entityPlayerClass.getMethod("getBukkitEntity");
loadDataM = craftPlayerClass.getMethod("loadData");
saveDataM = craftPlayerClass.getMethod("saveData");
} catch (Throwable e) {
log(Main.pl, "§cError in initializing offline player manager.");
error(cs, e, "SpigotLib", "gyurix");
}
}
/**
* Load an offline player to be handleable like an online one.
*
* @param uuid uuid of the loadable offline player
* @return the active Player object, or null if the player was not found.
*/
public static Player loadPlayer(UUID uuid) {
try {
if (uuid == null) {
return null;
}
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
if (player == null || !player.hasPlayedBefore()) {
return null;
}
Player plr = (Player) getBukkitEntityM.invoke(entityPlayerC.newInstance(mcServer, worldServer, new GameProfile(player.getName(), uuid).toNMS(), playerInterractManagerC.newInstance(worldServer)));
if (plr != null) {
loadDataM.invoke(plr);
return plr;
}
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
return null;
}
public static void loadPlayerConfig(UUID uid) {
if (PlayerFile.backend == BackendType.MYSQL) {
if (!PlayerFile.keepOfflineDataLoaded && loadedPlayers.contains(uid))
return;
String key = uid == null ? "CONSOLE" : uid.toString();
try (ResultSet rs = PlayerFile.mysql.query("SELECT `data` FROM `" + PlayerFile.mysql.table + "` WHERE `uuid` = ? LIMIT 1", key)) {
if (rs.next())
pf.setData(key, new ConfigFile(rs.getString("data")).data);
} catch (SQLException e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
loadedPlayers.add(uid);
if (Config.logPlayerConfigLoadUnload)
SU.cs.sendMessage("§eLoaded player §b" + uid);
}
}
/**
* Logs messages from the given plugin. You can use color codes in the msg.
*
* @param pl - The plugin who wants to log the message
* @param msg - The message which should be logged
*/
public static void log(Plugin pl, Object... msg) {
String s = pl == null ? "" : ('[' + pl.getName() + "] ") + StringUtils.join(msg, ", ");
if (cs != null)
cs.sendMessage(s);
else
System.out.println(ChatColor.stripColor(s));
}
/**
* Logs messages from the given plugin. You can use color codes in the msg.
*
* @param pl - The plugin who wants to log the message
* @param msg - The message which should be logged
*/
public static void log(Plugin pl, Iterable<Object>... msg) {
cs.sendMessage('[' + pl.getName() + "] " + StringUtils.join(msg, ", "));
}
/**
* Convertion of a collection of player UUIDs to the Arraylist containing the player names matching with the UUIDs.
*
* @param uuids collection of player uuids which will be converted to names
* @return the convertion result, which is an ArrayList of player names
*/
public static ArrayList<String> namesFromUUIDs(Collection<UUID> uuids) {
ArrayList<String> out = new ArrayList<>();
for (UUID id : uuids) {
out.add(getName(id));
}
return out;
}
/**
* Convertion of a collection of player names to the Arraylist containing the player UUIDs matching with the names.
*
* @param names collection of player names which will be converted to UUIDs
* @return the convertion result, which is an ArrayList of player UUIDs
*/
public static ArrayList<UUID> namesToUUIDs(Collection<String> names) {
ArrayList<UUID> out = new ArrayList<>();
for (String s : names) {
out.add(getUUID(s));
}
return out;
}
/**
* Optimizes color and formatting code usage in a string by removing redundant color/formatting codes
*
* @param in input message containing color and formatting codes
* @return The color and formatting code optimized string
*/
public static String optimizeColorCodes(String in) {
StringBuilder out = new StringBuilder();
StringBuilder oldFormat = new StringBuilder();
StringBuilder newFormat = new StringBuilder();
StringBuilder formatChange = new StringBuilder();
String formatArchive = "";
boolean color = false;
for (char c : in.toCharArray()) {
if (color) {
color = false;
if (c >= 'k' && c <= 'o') {
int max = newFormat.length();
boolean add = true;
for (int i = 1; i < max; i += 2) {
if (newFormat.charAt(i) == c) {
add = false;
break;
}
}
if (add) {
newFormat.append('§').append(c);
formatChange.append('§').append(c);
}
continue;
}
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')))
c = 'f';
newFormat.setLength(0);
newFormat.append('§').append(c);
formatChange.setLength(0);
formatChange.append('§').append(c);
} else if (c == '§')
color = true;
else if (c == '\u7777') {
formatArchive = newFormat.toString();
} else if (c == '\u7778') {
oldFormat.setLength(0);
newFormat.setLength(0);
newFormat.append(formatArchive);
formatChange.setLength(0);
formatChange.append(formatArchive);
} else {
if (!newFormat.toString().equals(oldFormat.toString())) {
out.append(formatChange);
formatChange.setLength(0);
oldFormat.setLength(0);
oldFormat.append(newFormat);
}
out.append(c);
}
}
return out.toString();
}
/**
* Generates a random number between min (inclusive) and max (exclusive)
*
* @param min - Minimal value of the random number
* @param max - Maximal value of the random number
* @return A random double between min and max
*/
public static double rand(double min, double max) {
return rand.nextDouble() * Math.abs(max - min) + min;
}
/**
* Generate a configurable random color
*
* @param minSaturation - Minimal saturation (0-1)
* @param maxSaturation - Maximal saturation (0-1)
* @param minLuminance - Minimal luminance (0-1)
* @param maxLuminance - Maximal luminance (0-1)
* @return The generated random color
*/
public static Color randColor(double minSaturation, double maxSaturation, double minLuminance, double maxLuminance) {
float hue = rand.nextFloat();
float saturation = (float) rand(minSaturation, maxSaturation);
float luminance = (float) rand(minLuminance, maxLuminance);
java.awt.Color color = java.awt.Color.getHSBColor(hue, saturation, luminance);
return Color.fromRGB(color.getRed(), color.getGreen(), color.getBlue());
}
/**
* Save a active offline player. You should use this method when you have active an offline player
* and you have changed some of it's data
*
* @param plr Loaded offline players Player object
*/
public static void savePlayer(Player plr) {
try {
saveDataM.invoke(plr);
} catch (Throwable e) {
e.printStackTrace();
}
}
public static void savePlayerConfig(UUID uid) {
String key = uid == null ? "CONSOLE" : uid.toString();
switch (PlayerFile.backend) {
case FILE:
pf.data.unWrapAll();
pf.save();
return;
case MYSQL:
if (!loadedPlayers.contains(uid)) {
SU.error(SU.cs, new Throwable("Trying to save the config of player " + uid + ", who is not loaded"), "SpigotLib", "gyurix");
return;
}
String data = getPlayerConfig(uid).toString();
MySQLDatabase.batchThread.submit(() -> {
if (PlayerFile.mysql.update("UPDATE `" + PlayerFile.mysql.table + "` SET `data` = ? WHERE `uuid` = ? LIMIT 1", data, key) == 0)
PlayerFile.mysql.command("INSERT INTO `" + PlayerFile.mysql.table + "` (`uuid`,`data`) VALUES ( ? , ? )", key, data);
});
SU.cs.sendMessage("§eSaved player §b" + uid);
}
}
public static void savePlayerConfigNoAsync(UUID uid) {
String key = uid == null ? "CONSOLE" : uid.toString();
switch (PlayerFile.backend) {
case FILE:
pf.data.unWrapAll();
pf.save();
return;
case MYSQL:
String data = getPlayerConfig(uid).toString();
if (PlayerFile.mysql.update("UPDATE `" + PlayerFile.mysql.table + "` SET `data` = ? WHERE `uuid` = ? LIMIT 1", data, key) == 0)
PlayerFile.mysql.command("INSERT INTO `" + PlayerFile.mysql.table + "` (`uuid`,`data`) VALUES ( ? , ? )", key, data);
SU.cs.sendMessage("§eSaved player NO ASYNC §b" + uid);
}
}
/**
* Save files from the given plugins jar file to its subfolder in the plugins folder. The files will only be saved
* if they doesn't exists in the plugins subfolder.
*
* @param pl instane of the plugin
* @param fileNames names of the saveable files
*/
public static void saveResources(Plugin pl, String... fileNames) {
Logger log = pl.getLogger();
File df = pl.getDataFolder();
ClassLoader cl = pl.getClass().getClassLoader();
df.mkdir();
for (String fn : fileNames) {
try {
File f = new File(df + File.separator + fn);
if (!f.exists()) {
if (fn.contains(File.separator)) {
new File(df + File.separator + fn.substring(0, fn.lastIndexOf(File.separatorChar))).mkdirs();
}
InputStream is = cl.getResourceAsStream(fn);
if (is == null) {
log.severe("Error, the requested file (" + fn + ") is missing from the plugins jar file.");
} else
Files.copy(is, f.toPath());
}
} catch (Throwable e) {
log.severe("Error, on copying file (" + fn + "): ");
e.printStackTrace();
}
}
}
/**
* Set maximum length of a String by cutting the redundant characters off from it
*
* @param in input String
* @param len maximum length
* @return The cutted String, which will maximally len characters.
*/
public static String setLength(String in, int len) {
return in.length() > len ? in.substring(0, len) : in;
}
public static String[] splitPage(String text, int lines) {
String[] d = text.split("\n");
String[] out = new String[(d.length + (lines - 1)) / lines];
for (int i = 0; i < d.length; i++) {
if (i % lines == 0)
out[i / lines] = d[i];
else
out[i / lines] += "\n" + d[i];
}
return out;
}
public static String toCamelCase(String name) {
StringBuilder sb = new StringBuilder();
for (String s : name.split("[ _]")) {
if (s.isEmpty())
continue;
sb.append(' ').append(Character.toUpperCase(s.charAt(0))).append(s.substring(1).toLowerCase());
}
return sb.length() == 0 ? sb.toString() : sb.substring(1);
}
/**
* Transloads an InputStream to an OutputStream, closes the InputStream, when it's done
*
* @param is - The InputStream
* @param os - The OutputStream
*/
public static void transloadStream(InputStream is, OutputStream os) throws IOException {
byte[] buf = new byte[4096];
for (int done = is.read(buf); done > 0; done = is.read(buf))
os.write(buf, 0, done);
is.close();
}
/**
* Unescape multi line to single line escaped text
*
* @param text multi line escaped text input
* @return The unescaped text
*/
public static String unescapeText(String text) {
return (' ' + text).replaceAll("([^\\\\])_", "$1 ")
.replaceAll("([^\\\\])\\|", "$1\n")
.replaceAll("([^\\\\])\\\\([_\\|])", "$1$2")
.replace("\\\\", "\\").substring(1);
}
/**
* Unloads the configuration of the given player or of the console if
* uid = null
*
* @param uid - The UUID of the player, or null for console
* @return True if the unload was successful, false otherwise
*/
public static boolean unloadPlayerConfig(UUID uid) {
if (PlayerFile.keepOfflineDataLoaded)
return false;
if (PlayerFile.backend == BackendType.MYSQL) {
String key = uid == null ? "CONSOLE" : uid.toString();
loadedPlayers.remove(uid);
if (Config.logPlayerConfigLoadUnload)
SU.cs.sendMessage("§eUnloaded player §b" + uid);
return pf.removeData(key);
}
return false;
}
public static void unloadPlugin(Plugin p) {
unloadPlugin(new HashSet<>(), p);
}
/**
* Unloads a plugin
*
* @param p - The unloadable plugin
*/
public static void unloadPlugin(HashSet<Plugin> unloaded, Plugin p) {
try {
if (unloaded.contains(p))
return;
unloaded.add(p);
if (!p.isEnabled())
return;
String pn = p.getName();
for (Plugin p2 : pm.getPlugins()) {
PluginDescriptionFile pdf = p2.getDescription();
if (pdf.getDepend() != null && pdf.getDepend().contains(pn) || pdf.getSoftDepend() != null && pdf.getSoftDepend().contains(pn))
unloadPlugin(unloaded, p2);
}
pm.disablePlugin(p);
((List) pluginsF.get(pm)).remove(p);
((Map) lookupNamesF.get(pm)).remove(pn);
for (Iterator it = knownCommands.entrySet().iterator(); it.hasNext(); ) {
Entry entry = (Entry) it.next();
if ((entry.getValue() instanceof PluginCommand)) {
PluginCommand c = (PluginCommand) entry.getValue();
if (c.getPlugin() == p)
it.remove();
}
}
((URLClassLoader) p.getClass().getClassLoader()).close();
System.gc();
} catch (Throwable e) {
error(cs, e, "SpigotLib", "gyurix");
}
}
} | 32,500 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
MapIcon.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/map/MapIcon.java | package gyurix.map;
import gyurix.json.JsonAPI;
import gyurix.json.JsonSettings;
import gyurix.protocol.Reflection;
import gyurix.protocol.utils.WrappedData;
import gyurix.spigotlib.SU;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
/**
* Created by GyuriX on 2016. 07. 06..
*/
public class MapIcon implements WrappedData {
@JsonSettings(serialize = false)
private static final Constructor con;
@JsonSettings(serialize = false)
private static final Field fType, fX, fY, fRotation;
static {
Class cl = Reflection.getNMSClass("MapIcon");
con = Reflection.getConstructor(cl, byte.class, byte.class, byte.class, byte.class);
fType = Reflection.getField(cl, "type");
fX = Reflection.getField(cl, "x");
fY = Reflection.getField(cl, "y");
fRotation = Reflection.getField(cl, "rotation");
}
public byte rotation;
public byte type;
public byte x;
public byte y;
public MapIcon(Object nmsMapIcon) {
try {
type = (byte) fType.get(nmsMapIcon);
x = (byte) fX.get(nmsMapIcon);
y = (byte) fY.get(nmsMapIcon);
rotation = (byte) fRotation.get(nmsMapIcon);
} catch (Throwable e) {
}
}
public MapIcon(int type, int x, int y, int rotation) {
this.type = (byte) type;
this.x = (byte) x;
this.y = (byte) y;
this.rotation = (byte) rotation;
}
@Override
public Object toNMS() {
try {
return con.newInstance(type, x, y, rotation);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
return null;
}
}
@Override
public String toString() {
return JsonAPI.serialize(this);
}
}
| 1,648 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
MapData.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/map/MapData.java | package gyurix.map;
import gyurix.protocol.wrappers.outpackets.PacketPlayOutMap;
import gyurix.spigotlib.SU;
import gyurix.spigotutils.EntityUtils;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.map.MapView;
import org.bukkit.map.MapView.Scale;
import java.lang.reflect.Method;
import java.util.ArrayList;
import static gyurix.protocol.Reflection.*;
/**
* Created by GyuriX on 2016. 07. 06..
*/
@Builder
@Getter
@Setter
public class MapData {
private static final Object itemWorldMap, worldMap;
private static final Method mapGenMethod;
private static final MapView view;
private static final byte[] viewColors;
static {
Class cl = getNMSClass("ItemWorldMap");
Class cl2 = getNMSClass("WorldMap");
itemWorldMap = newInstance(cl);
worldMap = newInstance(cl2, new Class[]{String.class}, "map_0");
view = (MapView) getFieldData(cl2, "mapView", worldMap);
view.getRenderers().clear();
viewColors = (byte[]) getFieldData(cl2, "colors", worldMap);
mapGenMethod = getMethod(cl, "a", getNMSClass("World"), getNMSClass("Entity"), cl2);
}
private final byte[] colors = new byte[16384];
private final ArrayList<MapIcon> icons = new ArrayList<>();
private int centerX, centerZ;
@Builder.Default
private int mapId = 1;
@Builder.Default
private Scale scale = Scale.CLOSEST;
@Builder.Default
private boolean showIcons = true;
private World world;
public void clear(byte color) {
if (color < 0 && color > -113)
color = 0;
for (int i = 0; i < 16384; i++)
colors[i] = color;
}
public byte[] cloneColors() {
return colors.clone();
}
public void setColor(int x, int y, byte color) {
if (x > -1 && x < 128 && y > -1 && y < 128)
colors[x + y * 128] = color;
}
public void setColor(int x, int y, int xLen, int yLen, byte color) {
for (int cx = 0; cx < xLen; cx++) {
for (int cy = 0; cy < yLen; cy++) {
if (x + cx > -1 && x + cx < 128 && y + cy > -1 && y + cy < 128)
colors[x + cx + (y + cy) * 128] = color;
}
}
}
public void setVanillaMapGenData(Player plr) {
view.setWorld(world);
view.setCenterX(centerX);
view.setCenterZ(centerZ);
view.setScale(scale);
try {
mapGenMethod.invoke(itemWorldMap, EntityUtils.getNMSWorld(world), EntityUtils.getNMSEntity(plr), worldMap);
System.arraycopy(viewColors, 0, colors, 0, 16384);
} catch (Throwable e) {
SU.error(SU.cs, e, "SpigotLib", "gyurix");
}
}
public void update(Player plr) {
SU.tp.sendPacket(plr, new PacketPlayOutMap(this));
}
}
| 2,677 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
NullUtils.java | /FileExtraction/Java_unseen/gyurix_SpigotLib/src/main/java/gyurix/spigotutils/NullUtils.java | package gyurix.spigotutils;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Class for converting null objects to 0 values and vice versa
*/
public class NullUtils {
public static Boolean from0(boolean data) {
return !data ? null : data;
}
public static Float from0(float data) {
return data == 0 ? null : data;
}
public static Double from0(double data) {
return data == 0 ? null : data;
}
public static Byte from0(byte data) {
return data == 0 ? null : data;
}
public static Short from0(short data) {
return data == 0 ? null : data;
}
public static Integer from0(int data) {
return data == 0 ? null : data;
}
public static Long from0(long data) {
return data == 0 ? null : data;
}
public static String from0(String in) {
return in == null || in.isEmpty() ? null : in;
}
public static boolean to0(Boolean data) {
return data == null ? false : data;
}
public static float to0(Float data) {
return data == null ? 0 : data;
}
public static double to0(Double data) {
return data == null ? 0 : data;
}
public static byte to0(Byte data) {
return data == null ? 0 : data;
}
public static short to0(Short data) {
return data == null ? 0 : data;
}
public static int to0(Integer data) {
return data == null ? 0 : data;
}
public static long to0(Long data) {
return data == null ? 0L : data;
}
public static String to0(String data) {
return data == null ? "" : data;
}
public static <T> ArrayList<T> to0(ArrayList<T> list) {
return list == null ? new ArrayList<T>() : list;
}
public static <K, V> HashMap<K, V> to0(HashMap<K, V> map) {
return map == null ? new HashMap<K, V>() : map;
}
}
| 1,752 | Java | .java | gyurix/SpigotLib | 53 | 6 | 3 | 2018-03-14T22:12:00Z | 2020-10-05T05:01:38Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.