id
int64 | file_name
string | file_path
string | content
string | size
int64 | language
string | extension
string | total_lines
int64 | avg_line_length
float64 | max_line_length
int64 | alphanum_fraction
float64 | repo_name
string | repo_stars
int64 | repo_forks
int64 | repo_open_issues
int64 | repo_license
string | repo_extraction_date
string | exact_duplicates_redpajama
bool | near_duplicates_redpajama
bool | exact_duplicates_githubcode
bool | exact_duplicates_stackv2
bool | exact_duplicates_stackv1
bool | near_duplicates_githubcode
bool | near_duplicates_stackv1
bool | near_duplicates_stackv2
bool | length
int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,861,372
|
ClassRef.java
|
hydraxman_ApkEditor/src/main/java/com/bryansharp/tools/parseapk/entity/refs/ClassRef.java
|
package com.bryansharp.tools.parseapk.entity.refs;
/**
* Created by bsp on 17/3/18.
*/
public class ClassRef {
public static final int SIZE = 32;
public int classIdx;
public int accessFlags;
public int superclassIdx;
public int interfacesOff;
public int sourceFileIdx;
public int annotationsOff;
public int classDataOff;
public int staticValuesOff;
@Override
public String toString() {
return "\nClassRef{" +
"classIdx=" + classIdx +
", accessFlags=" + accessFlags +
", superclassIdx=" + superclassIdx +
", interfacesOff=" + interfacesOff +
", sourceFileIdx=" + sourceFileIdx +
", annotationsOff=" + annotationsOff +
", classDataOff=" + classDataOff +
", staticValuesOff=" + staticValuesOff +
'}';
}
}
| 906
|
Java
|
.java
| 28
| 24.071429
| 56
| 0.592466
|
hydraxman/ApkEditor
| 16
| 3
| 0
|
GPL-3.0
|
9/4/2024, 8:21:15 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| true
| false
| 906
|
3,466,429
|
OptionElementCollection.java
|
mehah_jRender/src/com/jrender/jscript/dom/elements/OptionElementCollection.java
|
package com.jrender.jscript.dom.elements;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.jrender.jscript.DOM;
import com.jrender.jscript.DOMHandle;
import com.jrender.jscript.dom.Node;
import com.jrender.jscript.dom.Window;
public final class OptionElementCollection<T> extends DOM implements Iterable<OptionElement<T>>{
private final Class<T> typeValue;
OptionElementCollection(Window window, Class<T> typeValue) {
super(window);
this.typeValue = typeValue;
}
List<OptionElement<T>> list;
private OptionIterator iterator;
public Iterator<OptionElement<T>> iterator() {
if(iterator == null)
iterator = new OptionIterator();
else
iterator.reset();
return iterator;
}
public OptionElement<T> namedItem(String nameOrId) {
String res;
for (OptionElement<T> o : list) {
if((res = o.getAttribute("name")) != null && res.equals(nameOrId) || (res = o.getAttribute("id")) != null && res.equals(nameOrId))
return o;
}
return null;
}
public OptionElement<T> item(int index) {
OptionElement<T> e = list.get(index);
if(e == null)
DOMHandle.registerReturnByCommand((Node)(e = new OptionElement<T>(this.window, typeValue)), this, "item", index);
return e;
}
public Integer length() {
if(list == null) {
list = new ArrayList<OptionElement<T>>();
final Integer size = DOMHandle.getVariableValueByProperty(this, "length", Integer.class, "length");
for (int i = -1; ++i < size;)
list.add(null);
}
return list.size();
}
public void add(OptionElement<T> option) {
add(option, null);
}
public void add(OptionElement<T> option, Integer index) {
if(index == null)
{
list.add(option);
DOMHandle.execCommand(this, "add", option);
}else {
list.add(index, option);
DOMHandle.execCommand(this, "add", option, index);
}
}
public OptionElement<T> remove(int index) {
OptionElement<T> e = list.remove(index);
DOMHandle.execCommand(this, "remove", index);
return e;
}
private class OptionIterator implements Iterator<OptionElement<T>> {
private int currentIndex = 0;
public void reset() { currentIndex = 0; };
public boolean hasNext() { return currentIndex < list.size(); }
public OptionElement<T> next() { return item(currentIndex++); }
public void remove() {}
}
}
| 2,334
|
Java
|
.java
| 72
| 29.208333
| 133
| 0.722122
|
mehah/jRender
| 3
| 0
| 0
|
GPL-3.0
|
9/4/2024, 11:29:27 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
| 2,334
|
2,087,442
|
ClipPlaneUboDataProvider.java
|
KilnGraphics_Rosella/src/test/java/graphics/kiln/rosella/example/fboWater/ubo/ClipPlaneUboDataProvider.java
|
package graphics.kiln.rosella.example.fboWater.ubo;
import graphics.kiln.rosella.scene.object.RenderObject;
import graphics.kiln.rosella.ubo.UboDataProvider;
import org.joml.Vector4f;
import java.nio.ByteBuffer;
public class ClipPlaneUboDataProvider extends UboDataProvider<RenderObject> {
public final Vector4f clippingPlane;
public ClipPlaneUboDataProvider(Vector4f clippingPlane) {
this.clippingPlane = clippingPlane;
}
@Override
public void update(ByteBuffer data, RenderObject renderObject) {
reset();
super.writeMatrix4f(renderObject.modelMatrix, data);
super.writeMatrix4f(renderObject.viewMatrix, data);
super.writeMatrix4f(renderObject.projectionMatrix, data);
super.writeVector4f(clippingPlane, data);
}
@Override
public int getSize() {
return (16 * Float.BYTES) + // Model Matrix
(16 * Float.BYTES) + // View Matrix
(16 * Float.BYTES) + // Projection Matrix
(4 * Float.BYTES); // Clipping Plane
}
}
| 1,057
|
Java
|
.java
| 26
| 34
| 77
| 0.711914
|
KilnGraphics/Rosella
| 10
| 3
| 2
|
LGPL-3.0
|
9/4/2024, 8:28:58 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 1,057
|
4,609,415
|
ClusterOperator.java
|
pbousquets_beast-mcmc-flipflop/src/dr/evomodel/antigenic/phyloClustering/misc/obsolete/ClusterOperator.java
|
package dr.evomodel.antigenic.phyloClustering.misc.obsolete;
import dr.evomodel.antigenic.NPAntigenicLikelihood;
import dr.inference.model.Bounds;
import dr.inference.model.CompoundParameter;
import dr.inference.model.Likelihood;
import dr.inference.model.MatrixParameter;
import dr.inference.model.Parameter;
import dr.inference.operators.GibbsOperator;
import dr.inference.operators.MCMCOperator;
import dr.inference.operators.OperatorFailedException;
import dr.inference.operators.SimpleMCMCOperator;
import dr.inference.operators.RandomWalkOperator.BoundaryCondition;
import dr.math.MathUtils;
import dr.xml.*;
public class ClusterOperator extends SimpleMCMCOperator {
public final static String CLUSTER_OPERATOR = "clusterOperator";
public static final String WINDOW_SIZE = "windowSize";
public NPAntigenicLikelihood modelLikelihood;
private Parameter assignments = null;
private Parameter links = null;
private MatrixParameter virusLocations = null;
private double windowSize = 1;
public ClusterOperator(Parameter assignments, MatrixParameter virusLocations, double weight, double windowSize, NPAntigenicLikelihood Likelihood, Parameter links) {
//System.out.println("Constructor");
this.links = links;
this.assignments = assignments;
this.virusLocations = virusLocations;
this.windowSize = windowSize;
this.modelLikelihood = Likelihood;
setWeight(weight);
//load in the virusLocations
System.out.println((int)assignments.getParameterValue(0));
Parameter vLoc = virusLocations.getParameter(0);
//double d0= vLoc.getParameterValue(0);
//double d1= vLoc.getParameterValue(1);
//System.out.println( d0 + "," + d1);
//System.exit(0);
}
//assume no boundary
/**
* change the parameter and return the hastings ratio.
*/
public final double doOperation() {
double moveWholeClusterOrChangeOnePoint = MathUtils.nextDouble();
//double moveWholeClusterProb = 0.2;
double moveWholeClusterProb = 0.5;
int numSamples = assignments.getDimension();
// if(moveWholeClusterOrChangeOnePoint <moveWholeClusterProb){
// System.out.print("Group changes: ");
//System.out.println("Move a group of points in a cluster together");
int target = MathUtils.nextInt(numSamples);
int targetCluster = (int) assignments.getParameterValue(target);
//for(int i=0; i < numSamples; i++){
//Parameter vLoc = virusLocations.getParameter(i);
//double d0= vLoc.getParameterValue(0);
//double d1= vLoc.getParameterValue(1);
//System.out.println( d0 + "," + d1);
//}
// a random dimension to perturb
int ranDim= MathUtils.nextInt(virusLocations.getParameter(0).getDimension());
// a random point around old value within windowSize * 2
double draw = (2.0 * MathUtils.nextDouble() - 1.0) * windowSize;
for(int i=0; i < numSamples; i++){
if((int) assignments.getParameterValue(i)== targetCluster ){
//System.out.print("update "+ i +" from ");
Parameter vLoc = virusLocations.getParameter(i);
//System.out.print(vLoc.getParameterValue(index));
double newValue = vLoc.getParameterValue(ranDim) + draw;
vLoc.setParameterValue(ranDim, newValue);
//System.out.println(" to " + vLoc.getParameterValue(index));
}
}
// }
/*
//change cluster assignment!
else{
System.out.print("Cluster assignment & Group move:");
//System.out.println("Change a single point to another cluster");
//moving the point without coupling the point is useless!
//randomly pick a point to change cluster assignment
//move the point and couple it with change in cluster:
int index = MathUtils.nextInt(numSamples);
int oldGroup = (int)assignments.getParameterValue(index);
// Set index customer link to index and all connected to it to a new assignment (min value empty)
int minEmp = minEmpty(modelLikelihood.getLogLikelihoodsVector());
links.setParameterValue(index, index);
int[] visited = connected(index, links);
int ii = 0;
while (visited[ii]!=0){
assignments.setParameterValue(visited[ii]-1, minEmp);
ii++;
}
//Adjust likvector for group separated
modelLikelihood.setLogLikelihoodsVector(oldGroup,modelLikelihood.getLogLikGroup(oldGroup) );
modelLikelihood.setLogLikelihoodsVector(minEmp,modelLikelihood.getLogLikGroup(minEmp) );
int maxFull = maxFull( modelLikelihood.getLogLikelihoodsVector());
//pick new link
int k = MathUtils.nextInt(numSamples); //wonder if there is a way to make this more efficient at choosing good moves
links.setParameterValue(index, k);
int newGroup = (int)assignments.getParameterValue(k);
int countNumChanged = 0;
ii = 0;
while (visited[ii]!=0){
assignments.setParameterValue(visited[ii]-1, newGroup);
ii++;
countNumChanged++;
}
System.out.print("changed="+countNumChanged+ " ");
int targetCluster = (int) assignments.getParameterValue(k);
// updating conditional likelihood vector
modelLikelihood.setLogLikelihoodsVector(newGroup, modelLikelihood.getLogLikGroup(newGroup));
if (newGroup!=minEmp){
modelLikelihood.setLogLikelihoodsVector(minEmp, 0);
}
//change the location
// a random dimension to perturb
int ranDim= MathUtils.nextInt(virusLocations.getParameter(0).getDimension());
// a random point around old value within windowSize * 2
double draw = (2.0 * MathUtils.nextDouble() - 1.0) * windowSize;
int countNumLocChanged = 0;
for(int i=0; i < numSamples; i++){
if((int) assignments.getParameterValue(i)== targetCluster ){
//System.out.print("update "+ i +" from ");
Parameter vLoc = virusLocations.getParameter(i);
//System.out.print(vLoc.getParameterValue(index));
double newValue = vLoc.getParameterValue(ranDim) + draw;
vLoc.setParameterValue(ranDim, newValue);
//System.out.println(" to " + vLoc.getParameterValue(index));
countNumLocChanged++;
}
}
System.out.print("loc changed="+countNumLocChanged+ " ");
// sampleMeans(maxFull); // I decide not to resample the means here.
}
//Want to check that virusLocations WON't get updated if rejected
// System.out.println(target);
// System.out.println(targetCluster);
//for(int i=0; i < assignments.getDimension();)
*/
return 0.0;
}
/*
* find min Empty
*/
public int minEmpty(double[] logLikVector){
int isEmpty=0;
int i =0;
while (isEmpty==0){
if(logLikVector[i]==0){
isEmpty=1;}
else {
if(i==logLikVector.length-1){isEmpty=1;}
i++;}
}
return i;
}
/*
* find max Full
*/
public int maxFull(double[] logLikVector){
int isEmpty=1;
int i =logLikVector.length-1;
while (isEmpty==1){
if(logLikVector[i]!=0){
isEmpty=0;}
else {i--;}
}
return i;
}
/*
* find customers connected to i
*/
public int[] connected(int i, Parameter clusteringParameter){
int n = clusteringParameter.getDimension();
int[] visited = new int[n+1];
visited[0]=i+1;
int tv=1;
for(int j=0;j<n;j++){
if(visited[j]!=0){
int curr = visited[j]-1;
/*look forward
*/
int forward = (int) clusteringParameter.getParameterValue(curr);
visited[tv] = forward+1;
tv++;
// Check to see if is isn't already on the list
for(int ii=0; ii<tv-1; ii++){
if(visited[ii]==forward+1){
tv--;
visited[tv]=0;
}
}
/*look back
*/
for (int jj=0; jj<n;jj++){
if((int)clusteringParameter.getParameterValue(jj)==curr){
visited[tv]= jj+1;
tv++;
for(int ii=0; ii<tv-1; ii++){
if(visited[ii]==jj+1){
tv--;
visited[tv]=0;
}
}
}
}
}}
return visited;
}
public void accept(double deviation) {
super.accept(deviation);
// System.out.println("Accepted!");
}
public void reject(){
super.reject();
// System.out.println("Rejected");
}
//MCMCOperator INTERFACE
public final String getOperatorName() {
return CLUSTER_OPERATOR;
}
public final void optimize(double targetProb) {
throw new RuntimeException("This operator cannot be optimized!");
}
public boolean isOptimizing() {
return false;
}
public void setOptimizing(boolean opt) {
throw new RuntimeException("This operator cannot be optimized!");
}
public double getMinimumAcceptanceLevel() {
return 0.1;
}
public double getMaximumAcceptanceLevel() {
return 0.4;
}
public double getMinimumGoodAcceptanceLevel() {
return 0.20;
}
public double getMaximumGoodAcceptanceLevel() {
return 0.30;
}
public String getPerformanceSuggestion() {
if (Utils.getAcceptanceProbability(this) < getMinimumAcceptanceLevel()) {
return "";
} else if (Utils.getAcceptanceProbability(this) > getMaximumAcceptanceLevel()) {
return "";
} else {
return "";
}
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public final static String ASSIGNMENTS = "assignments";
public final static String VIRUS_LOCATIONS = "virusLocations";
public final static String LIKELIHOOD = "likelihood";
public final static String LINKS = "links";
public String getParserName() {
return CLUSTER_OPERATOR;
}
/* (non-Javadoc)
* @see dr.xml.AbstractXMLObjectParser#parseXMLObject(dr.xml.XMLObject)
*/
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT);
// double windowSize = xo.getDoubleAttribute(WINDOW_SIZE);
XMLObject cxo = xo.getChild(ASSIGNMENTS);
Parameter assignments = (Parameter) cxo.getChild(Parameter.class);
MatrixParameter virusLocationsParameter = null;
if (xo.hasChildNamed(VIRUS_LOCATIONS)) {
virusLocationsParameter = (MatrixParameter) xo.getElementFirstChild(VIRUS_LOCATIONS);
}
cxo = xo.getChild(LINKS);
Parameter links = (Parameter) cxo.getChild(Parameter.class);
cxo = xo.getChild(LIKELIHOOD);
NPAntigenicLikelihood likelihood = (NPAntigenicLikelihood)cxo.getChild(NPAntigenicLikelihood.class);
//set window size to be 1
return new ClusterOperator(assignments, virusLocationsParameter, weight, 1.0, likelihood, links);
// public ClusterOperator(Parameter assignments, MatrixParameter virusLocations, double weight, double windowSize, NPAntigenicLikelihood Likelihood, Parameter links) {
}
//************************************************************************
// AbstractXMLObjectParser implementation
//************************************************************************
public String getParserDescription() {
return "An operator that picks a new allocation of an item to a cluster under the Dirichlet process.";
}
public Class getReturnType() {
return ClusterOperator.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(MCMCOperator.WEIGHT),
// AttributeRule.newDoubleRule(WINDOW_SIZE),
new ElementRule(ASSIGNMENTS,
new XMLSyntaxRule[]{new ElementRule(Parameter.class)}),
new ElementRule(VIRUS_LOCATIONS, MatrixParameter.class, "Parameter of locations of all virus"),
new ElementRule(LINKS,
new XMLSyntaxRule[]{new ElementRule(Parameter.class)}),
new ElementRule(LIKELIHOOD, new XMLSyntaxRule[] {
new ElementRule(Likelihood.class),}, true),
};
};
public int getStepCount() {
return 1;
}
}
| 17,228
|
Java
|
.java
| 307
| 33.325733
| 186
| 0.509726
|
pbousquets/beast-mcmc-flipflop
| 2
| 0
| 8
|
LGPL-2.1
|
9/5/2024, 12:19:08 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
| 17,228
|
4,788,373
|
BasicPermission2Test.java
|
mateor_PDroidHistory/libcore/luni/src/test/java/org/apache/harmony/security/tests/java/security/BasicPermission2Test.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.security.tests.java.security;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargets;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetNew;
import java.security.BasicPermission;
import java.security.PermissionCollection;
@TestTargetClass(BasicPermission.class)
public class BasicPermission2Test extends junit.framework.TestCase {
public static class BasicPermissionSubclass extends BasicPermission {
public BasicPermissionSubclass(String name) {
super(name);
}
public BasicPermissionSubclass(String name, String actions) {
super(name, actions);
}
}
BasicPermission bp = new BasicPermissionSubclass("aName");
BasicPermission bp2 = new BasicPermissionSubclass("aName", "anAction");
BasicPermission bp3 = new BasicPermissionSubclass("*");
BasicPermission bp4 = new BasicPermissionSubclass("this.that");
BasicPermission bp5 = new BasicPermissionSubclass("this.*");
/**
* @tests java.security.BasicPermission#BasicPermission(java.lang.String)
*/
@TestTargetNew(
level = TestLevel.PARTIAL,
notes = "Test cases, where parameter name is null (expect NullPointerException) and parameter name is empty (expect IllegalArgumentException) are absent",
method = "BasicPermission",
args = {java.lang.String.class}
)
public void test_ConstructorLjava_lang_String() {
// Test for method java.security.BasicPermission(java.lang.String)
assertEquals("Incorrect name returned", "aName", bp.getName());
}
/**
* @tests java.security.BasicPermission#BasicPermission(java.lang.String,
* java.lang.String)
*/
@TestTargetNew(
level = TestLevel.PARTIAL,
notes = "Test cases, where parameter name is null (expect NullPointerException) and parameter name is empty (expect IllegalArgumentException) are absent",
method = "BasicPermission",
args = {java.lang.String.class, java.lang.String.class}
)
public void test_ConstructorLjava_lang_StringLjava_lang_String() {
// Test for method java.security.BasicPermission(java.lang.String,
// java.lang.String)
assertEquals("Incorrect name returned", "aName", bp2.getName());
}
/**
* @tests java.security.BasicPermission#equals(java.lang.Object)
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "equals",
args = {java.lang.Object.class}
)
public void test_equalsLjava_lang_Object() {
// Test for method boolean
// java.security.BasicPermission.equals(java.lang.Object)
assertTrue("a) Equal objects returned non-equal", bp.equals(bp2));
assertTrue("b) Equal objects returned non-equal", bp2.equals(bp));
assertTrue("a) Unequal objects returned equal", !bp.equals(bp3));
assertTrue("b) Unequal objects returned equal", !bp4.equals(bp5));
}
/**
* @tests java.security.BasicPermission#getActions()
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "getActions",
args = {}
)
public void test_getActions() {
// Test for method java.lang.String
// java.security.BasicPermission.getActions()
assertTrue("a) Incorrect actions returned, wanted the empty String", bp
.getActions().equals(""));
assertTrue("b) Incorrect actions returned, wanted the empty String",
bp2.getActions().equals(""));
}
/**
* @tests java.security.BasicPermission#hashCode()
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "hashCode",
args = {}
)
public void test_hashCode() {
// Test for method int java.security.BasicPermission.hashCode()
assertTrue("Equal objects should return same hash",
bp.hashCode() == bp2.hashCode());
}
/**
* @tests java.security.BasicPermission#implies(java.security.Permission)
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "implies",
args = {java.security.Permission.class}
)
public void test_impliesLjava_security_Permission() {
// Test for method boolean
// java.security.BasicPermission.implies(java.security.Permission)
assertTrue("Equal objects should imply each other", bp.implies(bp2));
assertTrue("a) should not imply", !bp.implies(bp3));
assertTrue("b) should not imply", !bp4.implies(bp5));
assertTrue("a) should imply", bp3.implies(bp5));
assertTrue("b) should imply", bp5.implies(bp4));
}
/**
* @tests java.security.BasicPermission#newPermissionCollection()
*/
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
method = "newPermissionCollection",
args = {}
)
public void test_newPermissionCollection() {
// Test for method java.security.PermissionCollection
// java.security.BasicPermission.newPermissionCollection()
PermissionCollection bpc = bp.newPermissionCollection();
bpc.add(bp5);
bpc.add(bp);
assertTrue("Should imply", bpc.implies(bp4));
assertTrue("Should not imply", !bpc.implies(bp3));
}
}
| 6,222
|
Java
|
.java
| 151
| 34.562914
| 162
| 0.680324
|
mateor/PDroidHistory
| 1
| 2
| 0
|
GPL-3.0
|
9/5/2024, 12:31:53 AM (Europe/Amsterdam)
| true
| true
| true
| false
| true
| true
| true
| false
| 6,222
|
905,079
|
JigsawStructureDataPacket.java
|
MemoriesOfTime_Nukkit-MOT/src/main/java/cn/nukkit/network/protocol/JigsawStructureDataPacket.java
|
package cn.nukkit.network.protocol;
import cn.nukkit.nbt.tag.CompoundTag;
import lombok.ToString;
/**
* @author glorydark
*/
@ToString
public class JigsawStructureDataPacket extends DataPacket {
public static final int NETWORK_ID = ProtocolInfo.JIGSAW_STRUCTURE_DATA_PACKET;
public CompoundTag nbt;
@Override
public int packetId() {
return NETWORK_ID;
}
@Override
public byte pid() {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public void decode() {
this.nbt = this.getTag();
}
@Override
public void encode() {
this.putNbtTag(this.nbt);
}
}
| 667
|
Java
|
.java
| 27
| 20.074074
| 83
| 0.693038
|
MemoriesOfTime/Nukkit-MOT
| 64
| 35
| 21
|
LGPL-3.0
|
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 667
|
3,731,776
|
PreloadingNetworkStoreClient.java
|
powsybl_powsybl-network-store/network-store-client/src/main/java/com/powsybl/network/store/client/PreloadingNetworkStoreClient.java
|
/**
* Copyright (c) 2019, RTE (http://www.rte-france.com)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.powsybl.network.store.client;
import com.google.common.base.Stopwatch;
import com.powsybl.network.store.client.util.ExecutorUtil;
import com.powsybl.network.store.iidm.impl.AbstractForwardingNetworkStoreClient;
import com.powsybl.network.store.iidm.impl.CachedNetworkStoreClient;
import com.powsybl.network.store.iidm.impl.NetworkCollectionIndex;
import com.powsybl.network.store.iidm.impl.NetworkStoreClient;
import com.powsybl.network.store.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* Per collection preloading.
* @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com>
* @author Etienne Homer <etienne.homer at rte-france.com>
*/
public class PreloadingNetworkStoreClient extends AbstractForwardingNetworkStoreClient implements NetworkStoreClient {
private static final Logger LOGGER = LoggerFactory.getLogger(PreloadingNetworkStoreClient.class);
static final Set<ResourceType> RESOURCE_TYPES_NEEDED_FOR_BUS_VIEW = Set.of(
ResourceType.SUBSTATION,
ResourceType.VOLTAGE_LEVEL,
ResourceType.LOAD,
ResourceType.GENERATOR,
ResourceType.BATTERY,
ResourceType.SHUNT_COMPENSATOR,
ResourceType.VSC_CONVERTER_STATION,
ResourceType.LCC_CONVERTER_STATION,
ResourceType.STATIC_VAR_COMPENSATOR,
ResourceType.BUSBAR_SECTION, // FIXME this should not be in the list but as connectable visitor also visit busbar sections we need to keep it
ResourceType.GROUND,
ResourceType.TWO_WINDINGS_TRANSFORMER,
ResourceType.THREE_WINDINGS_TRANSFORMER,
ResourceType.LINE,
ResourceType.HVDC_LINE,
ResourceType.DANGLING_LINE,
ResourceType.TIE_LINE
);
private final boolean allCollectionsNeededForBusView;
private final ExecutorService executorService;
private final NetworkCollectionIndex<Set<ResourceType>> cachedResourceTypes
= new NetworkCollectionIndex<>(() -> EnumSet.noneOf(ResourceType.class));
public PreloadingNetworkStoreClient(CachedNetworkStoreClient delegate, boolean allCollectionsNeededForBusView,
ExecutorService executorService) {
super(delegate);
this.allCollectionsNeededForBusView = allCollectionsNeededForBusView;
this.executorService = Objects.requireNonNull(executorService);
}
private void loadToCache(ResourceType resourceType, UUID networkUuid, int variantNum) {
switch (resourceType) {
case SUBSTATION -> delegate.getSubstations(networkUuid, variantNum);
case VOLTAGE_LEVEL -> delegate.getVoltageLevels(networkUuid, variantNum);
case LOAD -> delegate.getLoads(networkUuid, variantNum);
case GENERATOR -> delegate.getGenerators(networkUuid, variantNum);
case BATTERY -> delegate.getBatteries(networkUuid, variantNum);
case SHUNT_COMPENSATOR -> delegate.getShuntCompensators(networkUuid, variantNum);
case VSC_CONVERTER_STATION -> delegate.getVscConverterStations(networkUuid, variantNum);
case LCC_CONVERTER_STATION -> delegate.getLccConverterStations(networkUuid, variantNum);
case STATIC_VAR_COMPENSATOR -> delegate.getStaticVarCompensators(networkUuid, variantNum);
case BUSBAR_SECTION -> delegate.getBusbarSections(networkUuid, variantNum);
case SWITCH -> delegate.getSwitches(networkUuid, variantNum);
case GROUND -> delegate.getGrounds(networkUuid, variantNum);
case TWO_WINDINGS_TRANSFORMER -> delegate.getTwoWindingsTransformers(networkUuid, variantNum);
case THREE_WINDINGS_TRANSFORMER -> delegate.getThreeWindingsTransformers(networkUuid, variantNum);
case LINE -> delegate.getLines(networkUuid, variantNum);
case HVDC_LINE -> delegate.getHvdcLines(networkUuid, variantNum);
case DANGLING_LINE -> delegate.getDanglingLines(networkUuid, variantNum);
case CONFIGURED_BUS -> delegate.getConfiguredBuses(networkUuid, variantNum);
case TIE_LINE -> delegate.getTieLines(networkUuid, variantNum);
default -> {
// Do nothing
}
}
}
private void loadAllCollectionsNeededForBusView(UUID networkUuid, int variantNum, Set<ResourceType> resourceTypes) {
// directly load all collections
Stopwatch stopwatch = Stopwatch.createStarted();
List<Future<?>> futures = new ArrayList<>(RESOURCE_TYPES_NEEDED_FOR_BUS_VIEW.size());
for (ResourceType resourceType : RESOURCE_TYPES_NEEDED_FOR_BUS_VIEW) {
futures.add(executorService.submit(() -> loadToCache(resourceType, networkUuid, variantNum)));
}
ExecutorUtil.waitAllFutures(futures);
resourceTypes.addAll(RESOURCE_TYPES_NEEDED_FOR_BUS_VIEW);
stopwatch.stop();
LOGGER.info("All collections needed for bus view loaded in {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
boolean isResourceTypeCached(UUID networkUuid, int variantNum, ResourceType resourceType) {
Set<ResourceType> resourceTypes = cachedResourceTypes.getCollection(networkUuid, variantNum);
Objects.requireNonNull(resourceType);
return resourceTypes.contains(resourceType);
}
private void ensureCached(ResourceType resourceType, UUID networkUuid, int variantNum) {
Objects.requireNonNull(resourceType);
Objects.requireNonNull(networkUuid);
Set<ResourceType> resourceTypes = cachedResourceTypes.getCollection(networkUuid, variantNum);
if (!resourceTypes.contains(resourceType)) {
if (allCollectionsNeededForBusView && RESOURCE_TYPES_NEEDED_FOR_BUS_VIEW.contains(resourceType)) {
loadAllCollectionsNeededForBusView(networkUuid, variantNum, resourceTypes);
} else {
loadToCache(resourceType, networkUuid, variantNum);
resourceTypes.add(resourceType);
}
}
}
@Override
public void deleteNetwork(UUID networkUuid) {
delegate.deleteNetwork(networkUuid);
cachedResourceTypes.removeCollection(networkUuid);
}
@Override
public void deleteNetwork(UUID networkUuid, int variantNum) {
delegate.deleteNetwork(networkUuid, variantNum);
cachedResourceTypes.removeCollection(networkUuid, variantNum);
}
@Override
public void createSubstations(UUID networkUuid, List<Resource<SubstationAttributes>> substationResources) {
for (Resource<SubstationAttributes> substationResource : substationResources) {
ensureCached(ResourceType.SUBSTATION, networkUuid, substationResource.getVariantNum());
}
delegate.createSubstations(networkUuid, substationResources);
}
@Override
public List<Resource<SubstationAttributes>> getSubstations(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.SUBSTATION, networkUuid, variantNum);
return delegate.getSubstations(networkUuid, variantNum);
}
@Override
public Optional<Resource<SubstationAttributes>> getSubstation(UUID networkUuid, int variantNum, String substationId) {
ensureCached(ResourceType.SUBSTATION, networkUuid, variantNum);
return delegate.getSubstation(networkUuid, variantNum, substationId);
}
@Override
public void removeSubstations(UUID networkUuid, int variantNum, List<String> substationsId) {
ensureCached(ResourceType.SUBSTATION, networkUuid, variantNum);
delegate.removeSubstations(networkUuid, variantNum, substationsId);
}
@Override
public void updateSubstations(UUID networkUuid, List<Resource<SubstationAttributes>> substationResources, AttributeFilter attributeFilter) {
for (Resource<SubstationAttributes> substationResource : substationResources) {
ensureCached(ResourceType.SUBSTATION, networkUuid, substationResource.getVariantNum());
}
delegate.updateSubstations(networkUuid, substationResources, attributeFilter);
}
@Override
public void createVoltageLevels(UUID networkUuid, List<Resource<VoltageLevelAttributes>> voltageLevelResources) {
for (Resource<VoltageLevelAttributes> voltageLevelResource : voltageLevelResources) {
ensureCached(ResourceType.VOLTAGE_LEVEL, networkUuid, voltageLevelResource.getVariantNum());
}
delegate.createVoltageLevels(networkUuid, voltageLevelResources);
}
@Override
public Optional<Resource<VoltageLevelAttributes>> getVoltageLevel(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.VOLTAGE_LEVEL, networkUuid, variantNum);
return delegate.getVoltageLevel(networkUuid, variantNum, voltageLevelId);
}
@Override
public List<Resource<VoltageLevelAttributes>> getVoltageLevels(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.VOLTAGE_LEVEL, networkUuid, variantNum);
return delegate.getVoltageLevels(networkUuid, variantNum);
}
@Override
public List<Resource<VoltageLevelAttributes>> getVoltageLevelsInSubstation(UUID networkUuid, int variantNum, String substationId) {
ensureCached(ResourceType.VOLTAGE_LEVEL, networkUuid, variantNum);
return delegate.getVoltageLevelsInSubstation(networkUuid, variantNum, substationId);
}
@Override
public void removeVoltageLevels(UUID networkUuid, int variantNum, List<String> voltageLevelsId) {
ensureCached(ResourceType.VOLTAGE_LEVEL, networkUuid, variantNum);
delegate.removeVoltageLevels(networkUuid, variantNum, voltageLevelsId);
}
@Override
public List<Resource<BusbarSectionAttributes>> getVoltageLevelBusbarSections(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.BUSBAR_SECTION, networkUuid, variantNum);
return delegate.getVoltageLevelBusbarSections(networkUuid, variantNum, voltageLevelId);
}
@Override
public void removeBusBarSections(UUID networkUuid, int variantNum, List<String> busBarSectionsId) {
ensureCached(ResourceType.BUSBAR_SECTION, networkUuid, variantNum);
delegate.removeBusBarSections(networkUuid, variantNum, busBarSectionsId);
}
@Override
public List<Resource<SwitchAttributes>> getVoltageLevelSwitches(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.SWITCH, networkUuid, variantNum);
return delegate.getVoltageLevelSwitches(networkUuid, variantNum, voltageLevelId);
}
@Override
public List<Resource<GeneratorAttributes>> getVoltageLevelGenerators(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.GENERATOR, networkUuid, variantNum);
return delegate.getVoltageLevelGenerators(networkUuid, variantNum, voltageLevelId);
}
@Override
public void removeGenerators(UUID networkUuid, int variantNum, List<String> generatorsId) {
ensureCached(ResourceType.GENERATOR, networkUuid, variantNum);
delegate.removeGenerators(networkUuid, variantNum, generatorsId);
}
@Override
public List<Resource<BatteryAttributes>> getVoltageLevelBatteries(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.BATTERY, networkUuid, variantNum);
return delegate.getVoltageLevelBatteries(networkUuid, variantNum, voltageLevelId);
}
@Override
public void removeBatteries(UUID networkUuid, int variantNum, List<String> batteriesId) {
ensureCached(ResourceType.BATTERY, networkUuid, variantNum);
delegate.removeBatteries(networkUuid, variantNum, batteriesId);
}
@Override
public List<Resource<LoadAttributes>> getVoltageLevelLoads(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.LOAD, networkUuid, variantNum);
return delegate.getVoltageLevelLoads(networkUuid, variantNum, voltageLevelId);
}
@Override
public void removeLoads(UUID networkUuid, int variantNum, List<String> loadsId) {
ensureCached(ResourceType.LOAD, networkUuid, variantNum);
delegate.removeLoads(networkUuid, variantNum, loadsId);
}
@Override
public List<Resource<ShuntCompensatorAttributes>> getVoltageLevelShuntCompensators(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.SHUNT_COMPENSATOR, networkUuid, variantNum);
return delegate.getVoltageLevelShuntCompensators(networkUuid, variantNum, voltageLevelId);
}
@Override
public void removeShuntCompensators(UUID networkUuid, int variantNum, List<String> shuntCompensatorsId) {
ensureCached(ResourceType.SHUNT_COMPENSATOR, networkUuid, variantNum);
delegate.removeShuntCompensators(networkUuid, variantNum, shuntCompensatorsId);
}
@Override
public List<Resource<StaticVarCompensatorAttributes>> getVoltageLevelStaticVarCompensators(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.STATIC_VAR_COMPENSATOR, networkUuid, variantNum);
return delegate.getVoltageLevelStaticVarCompensators(networkUuid, variantNum, voltageLevelId);
}
@Override
public void removeStaticVarCompensators(UUID networkUuid, int variantNum, List<String> staticVarCompensatorsId) {
ensureCached(ResourceType.STATIC_VAR_COMPENSATOR, networkUuid, variantNum);
delegate.removeStaticVarCompensators(networkUuid, variantNum, staticVarCompensatorsId);
}
@Override
public List<Resource<VscConverterStationAttributes>> getVoltageLevelVscConverterStations(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.VSC_CONVERTER_STATION, networkUuid, variantNum);
return delegate.getVoltageLevelVscConverterStations(networkUuid, variantNum, voltageLevelId);
}
@Override
public void removeVscConverterStations(UUID networkUuid, int variantNum, List<String> vscConverterStationsId) {
ensureCached(ResourceType.VSC_CONVERTER_STATION, networkUuid, variantNum);
delegate.removeVscConverterStations(networkUuid, variantNum, vscConverterStationsId);
}
@Override
public List<Resource<LccConverterStationAttributes>> getVoltageLevelLccConverterStations(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.LCC_CONVERTER_STATION, networkUuid, variantNum);
return delegate.getVoltageLevelLccConverterStations(networkUuid, variantNum, voltageLevelId);
}
@Override
public void removeLccConverterStations(UUID networkUuid, int variantNum, List<String> lccConverterStationsId) {
ensureCached(ResourceType.LCC_CONVERTER_STATION, networkUuid, variantNum);
delegate.removeLccConverterStations(networkUuid, variantNum, lccConverterStationsId);
}
@Override
public List<Resource<GroundAttributes>> getVoltageLevelGrounds(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.GROUND, networkUuid, variantNum);
return delegate.getVoltageLevelGrounds(networkUuid, variantNum, voltageLevelId);
}
@Override
public void removeGrounds(UUID networkUuid, int variantNum, List<String> groundsId) {
ensureCached(ResourceType.GROUND, networkUuid, variantNum);
delegate.removeGrounds(networkUuid, variantNum, groundsId);
}
@Override
public List<Resource<TwoWindingsTransformerAttributes>> getVoltageLevelTwoWindingsTransformers(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.TWO_WINDINGS_TRANSFORMER, networkUuid, variantNum);
return delegate.getVoltageLevelTwoWindingsTransformers(networkUuid, variantNum, voltageLevelId);
}
@Override
public void removeTwoWindingsTransformers(UUID networkUuid, int variantNum, List<String> twoWindingsTransformersId) {
ensureCached(ResourceType.TWO_WINDINGS_TRANSFORMER, networkUuid, variantNum);
delegate.removeTwoWindingsTransformers(networkUuid, variantNum, twoWindingsTransformersId);
}
@Override
public List<Resource<ThreeWindingsTransformerAttributes>> getVoltageLevelThreeWindingsTransformers(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.THREE_WINDINGS_TRANSFORMER, networkUuid, variantNum);
return delegate.getVoltageLevelThreeWindingsTransformers(networkUuid, variantNum, voltageLevelId);
}
@Override
public void removeThreeWindingsTransformers(UUID networkUuid, int variantNum, List<String> threeWindingsTransformersId) {
ensureCached(ResourceType.THREE_WINDINGS_TRANSFORMER, networkUuid, variantNum);
delegate.removeThreeWindingsTransformers(networkUuid, variantNum, threeWindingsTransformersId);
}
@Override
public List<Resource<LineAttributes>> getVoltageLevelLines(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.LINE, networkUuid, variantNum);
return delegate.getVoltageLevelLines(networkUuid, variantNum, voltageLevelId);
}
@Override
public void removeLines(UUID networkUuid, int variantNum, List<String> linesId) {
ensureCached(ResourceType.LINE, networkUuid, variantNum);
delegate.removeLines(networkUuid, variantNum, linesId);
}
@Override
public List<Resource<DanglingLineAttributes>> getVoltageLevelDanglingLines(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.DANGLING_LINE, networkUuid, variantNum);
return delegate.getVoltageLevelDanglingLines(networkUuid, variantNum, voltageLevelId);
}
@Override
public void createSwitches(UUID networkUuid, List<Resource<SwitchAttributes>> switchResources) {
for (Resource<SwitchAttributes> switchResource : switchResources) {
ensureCached(ResourceType.SWITCH, networkUuid, switchResource.getVariantNum());
}
delegate.createSwitches(networkUuid, switchResources);
}
@Override
public List<Resource<SwitchAttributes>> getSwitches(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.SWITCH, networkUuid, variantNum);
return delegate.getSwitches(networkUuid, variantNum);
}
@Override
public Optional<Resource<SwitchAttributes>> getSwitch(UUID networkUuid, int variantNum, String switchId) {
ensureCached(ResourceType.SWITCH, networkUuid, variantNum);
return delegate.getSwitch(networkUuid, variantNum, switchId);
}
@Override
public void updateSwitches(UUID networkUuid, List<Resource<SwitchAttributes>> switchResources, AttributeFilter attributeFilter) {
for (Resource<SwitchAttributes> switchResource : switchResources) {
ensureCached(ResourceType.SWITCH, networkUuid, switchResource.getVariantNum());
}
delegate.updateSwitches(networkUuid, switchResources, attributeFilter);
}
@Override
public void removeSwitches(UUID networkUuid, int variantNum, List<String> switchesId) {
ensureCached(ResourceType.SWITCH, networkUuid, variantNum);
delegate.removeSwitches(networkUuid, variantNum, switchesId);
}
@Override
public void createBusbarSections(UUID networkUuid, List<Resource<BusbarSectionAttributes>> busbarSectionResources) {
for (Resource<BusbarSectionAttributes> busbarSectionResource : busbarSectionResources) {
ensureCached(ResourceType.BUSBAR_SECTION, networkUuid, busbarSectionResource.getVariantNum());
}
delegate.createBusbarSections(networkUuid, busbarSectionResources);
}
@Override
public List<Resource<BusbarSectionAttributes>> getBusbarSections(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.BUSBAR_SECTION, networkUuid, variantNum);
return delegate.getBusbarSections(networkUuid, variantNum);
}
@Override
public Optional<Resource<BusbarSectionAttributes>> getBusbarSection(UUID networkUuid, int variantNum, String busbarSectionId) {
ensureCached(ResourceType.BUSBAR_SECTION, networkUuid, variantNum);
return delegate.getBusbarSection(networkUuid, variantNum, busbarSectionId);
}
@Override
public void updateBusbarSections(UUID networkUuid, List<Resource<BusbarSectionAttributes>> busbarSectionResources, AttributeFilter attributeFilter) {
for (Resource<BusbarSectionAttributes> busbarSectionResource : busbarSectionResources) {
ensureCached(ResourceType.BUSBAR_SECTION, networkUuid, busbarSectionResource.getVariantNum());
}
delegate.updateBusbarSections(networkUuid, busbarSectionResources, attributeFilter);
}
@Override
public void createLoads(UUID networkUuid, List<Resource<LoadAttributes>> loadResources) {
for (Resource<LoadAttributes> loadResource : loadResources) {
ensureCached(ResourceType.LOAD, networkUuid, loadResource.getVariantNum());
}
delegate.createLoads(networkUuid, loadResources);
}
@Override
public List<Resource<LoadAttributes>> getLoads(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.LOAD, networkUuid, variantNum);
return delegate.getLoads(networkUuid, variantNum);
}
@Override
public Optional<Resource<LoadAttributes>> getLoad(UUID networkUuid, int variantNum, String loadId) {
ensureCached(ResourceType.LOAD, networkUuid, variantNum);
return delegate.getLoad(networkUuid, variantNum, loadId);
}
@Override
public void updateLoads(UUID networkUuid, List<Resource<LoadAttributes>> loadResources, AttributeFilter attributeFilter) {
for (Resource<LoadAttributes> loadResource : loadResources) {
ensureCached(ResourceType.LOAD, networkUuid, loadResource.getVariantNum());
}
delegate.updateLoads(networkUuid, loadResources, attributeFilter);
}
@Override
public void createGenerators(UUID networkUuid, List<Resource<GeneratorAttributes>> generatorResources) {
for (Resource<GeneratorAttributes> generatorResource : generatorResources) {
ensureCached(ResourceType.GENERATOR, networkUuid, generatorResource.getVariantNum());
}
delegate.createGenerators(networkUuid, generatorResources);
}
@Override
public List<Resource<GeneratorAttributes>> getGenerators(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.GENERATOR, networkUuid, variantNum);
return delegate.getGenerators(networkUuid, variantNum);
}
@Override
public Optional<Resource<GeneratorAttributes>> getGenerator(UUID networkUuid, int variantNum, String generatorId) {
ensureCached(ResourceType.GENERATOR, networkUuid, variantNum);
return delegate.getGenerator(networkUuid, variantNum, generatorId);
}
@Override
public void updateGenerators(UUID networkUuid, List<Resource<GeneratorAttributes>> generatorResources, AttributeFilter attributeFilter) {
for (Resource<GeneratorAttributes> generatorResource : generatorResources) {
ensureCached(ResourceType.GENERATOR, networkUuid, generatorResource.getVariantNum());
}
delegate.updateGenerators(networkUuid, generatorResources, attributeFilter);
}
@Override
public void createBatteries(UUID networkUuid, List<Resource<BatteryAttributes>> batteryResources) {
for (Resource<BatteryAttributes> batteryResource : batteryResources) {
ensureCached(ResourceType.BATTERY, networkUuid, batteryResource.getVariantNum());
}
delegate.createBatteries(networkUuid, batteryResources);
}
@Override
public List<Resource<BatteryAttributes>> getBatteries(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.BATTERY, networkUuid, variantNum);
return delegate.getBatteries(networkUuid, variantNum);
}
@Override
public Optional<Resource<BatteryAttributes>> getBattery(UUID networkUuid, int variantNum, String batteryId) {
ensureCached(ResourceType.BATTERY, networkUuid, variantNum);
return delegate.getBattery(networkUuid, variantNum, batteryId);
}
@Override
public void updateBatteries(UUID networkUuid, List<Resource<BatteryAttributes>> batteryResources, AttributeFilter attributeFilter) {
for (Resource<BatteryAttributes> batteryResource : batteryResources) {
ensureCached(ResourceType.BATTERY, networkUuid, batteryResource.getVariantNum());
}
delegate.updateBatteries(networkUuid, batteryResources, attributeFilter);
}
@Override
public void createGrounds(UUID networkUuid, List<Resource<GroundAttributes>> groundResources) {
for (Resource<GroundAttributes> groundResource : groundResources) {
ensureCached(ResourceType.GROUND, networkUuid, groundResource.getVariantNum());
}
delegate.createGrounds(networkUuid, groundResources);
}
@Override
public List<Resource<GroundAttributes>> getGrounds(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.GROUND, networkUuid, variantNum);
return delegate.getGrounds(networkUuid, variantNum);
}
@Override
public Optional<Resource<GroundAttributes>> getGround(UUID networkUuid, int variantNum, String groundId) {
ensureCached(ResourceType.GROUND, networkUuid, variantNum);
return delegate.getGround(networkUuid, variantNum, groundId);
}
@Override
public void updateGrounds(UUID networkUuid, List<Resource<GroundAttributes>> groundResources, AttributeFilter attributeFilter) {
for (Resource<GroundAttributes> groundResource : groundResources) {
ensureCached(ResourceType.GROUND, networkUuid, groundResource.getVariantNum());
}
delegate.updateGrounds(networkUuid, groundResources, attributeFilter);
}
@Override
public void createTwoWindingsTransformers(UUID networkUuid, List<Resource<TwoWindingsTransformerAttributes>> twoWindingsTransformerResources) {
for (Resource<TwoWindingsTransformerAttributes> twoWindingsTransformerResource : twoWindingsTransformerResources) {
ensureCached(ResourceType.TWO_WINDINGS_TRANSFORMER, networkUuid, twoWindingsTransformerResource.getVariantNum());
}
delegate.createTwoWindingsTransformers(networkUuid, twoWindingsTransformerResources);
}
@Override
public List<Resource<TwoWindingsTransformerAttributes>> getTwoWindingsTransformers(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.TWO_WINDINGS_TRANSFORMER, networkUuid, variantNum);
return delegate.getTwoWindingsTransformers(networkUuid, variantNum);
}
@Override
public Optional<Resource<TwoWindingsTransformerAttributes>> getTwoWindingsTransformer(UUID networkUuid, int variantNum, String twoWindingsTransformerId) {
ensureCached(ResourceType.TWO_WINDINGS_TRANSFORMER, networkUuid, variantNum);
return delegate.getTwoWindingsTransformer(networkUuid, variantNum, twoWindingsTransformerId);
}
@Override
public void updateTwoWindingsTransformers(UUID networkUuid, List<Resource<TwoWindingsTransformerAttributes>> twoWindingsTransformerResources, AttributeFilter attributeFilter) {
for (Resource<TwoWindingsTransformerAttributes> twoWindingsTransformerResource : twoWindingsTransformerResources) {
ensureCached(ResourceType.TWO_WINDINGS_TRANSFORMER, networkUuid, twoWindingsTransformerResource.getVariantNum());
}
delegate.updateTwoWindingsTransformers(networkUuid, twoWindingsTransformerResources, attributeFilter);
}
// 3 windings transformer
@Override
public void createThreeWindingsTransformers(UUID networkUuid, List<Resource<ThreeWindingsTransformerAttributes>> threeWindingsTransformerResources) {
for (Resource<ThreeWindingsTransformerAttributes> threeWindingsTransformerResource : threeWindingsTransformerResources) {
ensureCached(ResourceType.THREE_WINDINGS_TRANSFORMER, networkUuid, threeWindingsTransformerResource.getVariantNum());
}
delegate.createThreeWindingsTransformers(networkUuid, threeWindingsTransformerResources);
}
@Override
public List<Resource<ThreeWindingsTransformerAttributes>> getThreeWindingsTransformers(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.THREE_WINDINGS_TRANSFORMER, networkUuid, variantNum);
return delegate.getThreeWindingsTransformers(networkUuid, variantNum);
}
@Override
public Optional<Resource<ThreeWindingsTransformerAttributes>> getThreeWindingsTransformer(UUID networkUuid, int variantNum, String threeWindingsTransformerId) {
ensureCached(ResourceType.THREE_WINDINGS_TRANSFORMER, networkUuid, variantNum);
return delegate.getThreeWindingsTransformer(networkUuid, variantNum, threeWindingsTransformerId);
}
@Override
public void updateThreeWindingsTransformers(UUID networkUuid, List<Resource<ThreeWindingsTransformerAttributes>> threeWindingsTransformerResources, AttributeFilter attributeFilter) {
for (Resource<ThreeWindingsTransformerAttributes> threeWindingsTransformerResource : threeWindingsTransformerResources) {
ensureCached(ResourceType.THREE_WINDINGS_TRANSFORMER, networkUuid, threeWindingsTransformerResource.getVariantNum());
}
delegate.updateThreeWindingsTransformers(networkUuid, threeWindingsTransformerResources, attributeFilter);
}
@Override
public void createLines(UUID networkUuid, List<Resource<LineAttributes>> lineResources) {
for (Resource<LineAttributes> lineResource : lineResources) {
ensureCached(ResourceType.LINE, networkUuid, lineResource.getVariantNum());
}
delegate.createLines(networkUuid, lineResources);
}
@Override
public List<Resource<LineAttributes>> getLines(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.LINE, networkUuid, variantNum);
return delegate.getLines(networkUuid, variantNum);
}
@Override
public Optional<Resource<LineAttributes>> getLine(UUID networkUuid, int variantNum, String lineId) {
ensureCached(ResourceType.LINE, networkUuid, variantNum);
return delegate.getLine(networkUuid, variantNum, lineId);
}
@Override
public void updateLines(UUID networkUuid, List<Resource<LineAttributes>> lineResources, AttributeFilter attributeFilter) {
for (Resource<LineAttributes> lineResource : lineResources) {
ensureCached(ResourceType.LINE, networkUuid, lineResource.getVariantNum());
}
delegate.updateLines(networkUuid, lineResources, attributeFilter);
}
@Override
public void createShuntCompensators(UUID networkUuid, List<Resource<ShuntCompensatorAttributes>> shuntCompensatorResources) {
for (Resource<ShuntCompensatorAttributes> shuntCompensatorResource : shuntCompensatorResources) {
ensureCached(ResourceType.SHUNT_COMPENSATOR, networkUuid, shuntCompensatorResource.getVariantNum());
}
delegate.createShuntCompensators(networkUuid, shuntCompensatorResources);
}
@Override
public List<Resource<ShuntCompensatorAttributes>> getShuntCompensators(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.SHUNT_COMPENSATOR, networkUuid, variantNum);
return delegate.getShuntCompensators(networkUuid, variantNum);
}
@Override
public Optional<Resource<ShuntCompensatorAttributes>> getShuntCompensator(UUID networkUuid, int variantNum, String shuntCompensatorId) {
ensureCached(ResourceType.SHUNT_COMPENSATOR, networkUuid, variantNum);
return delegate.getShuntCompensator(networkUuid, variantNum, shuntCompensatorId);
}
@Override
public void updateShuntCompensators(UUID networkUuid, List<Resource<ShuntCompensatorAttributes>> shuntCompensatorResources, AttributeFilter attributeFilter) {
for (Resource<ShuntCompensatorAttributes> shuntCompensatorResource : shuntCompensatorResources) {
ensureCached(ResourceType.SHUNT_COMPENSATOR, networkUuid, shuntCompensatorResource.getVariantNum());
}
delegate.updateShuntCompensators(networkUuid, shuntCompensatorResources, attributeFilter);
}
@Override
public void createVscConverterStations(UUID networkUuid, List<Resource<VscConverterStationAttributes>> vscConverterStationResources) {
for (Resource<VscConverterStationAttributes> vscConverterStationResource : vscConverterStationResources) {
ensureCached(ResourceType.VSC_CONVERTER_STATION, networkUuid, vscConverterStationResource.getVariantNum());
}
delegate.createVscConverterStations(networkUuid, vscConverterStationResources);
}
@Override
public List<Resource<VscConverterStationAttributes>> getVscConverterStations(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.VSC_CONVERTER_STATION, networkUuid, variantNum);
return delegate.getVscConverterStations(networkUuid, variantNum);
}
@Override
public Optional<Resource<VscConverterStationAttributes>> getVscConverterStation(UUID networkUuid, int variantNum, String vscConverterStationId) {
ensureCached(ResourceType.VSC_CONVERTER_STATION, networkUuid, variantNum);
return delegate.getVscConverterStation(networkUuid, variantNum, vscConverterStationId);
}
@Override
public void updateVscConverterStations(UUID networkUuid, List<Resource<VscConverterStationAttributes>> vscConverterStationResources, AttributeFilter attributeFilter) {
for (Resource<VscConverterStationAttributes> vscConverterStationResource : vscConverterStationResources) {
ensureCached(ResourceType.VSC_CONVERTER_STATION, networkUuid, vscConverterStationResource.getVariantNum());
}
delegate.updateVscConverterStations(networkUuid, vscConverterStationResources, attributeFilter);
}
@Override
public void createLccConverterStations(UUID networkUuid, List<Resource<LccConverterStationAttributes>> lccConverterStationResources) {
for (Resource<LccConverterStationAttributes> lccConverterStationResource : lccConverterStationResources) {
ensureCached(ResourceType.LCC_CONVERTER_STATION, networkUuid, lccConverterStationResource.getVariantNum());
}
delegate.createLccConverterStations(networkUuid, lccConverterStationResources);
}
@Override
public List<Resource<LccConverterStationAttributes>> getLccConverterStations(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.LCC_CONVERTER_STATION, networkUuid, variantNum);
return delegate.getLccConverterStations(networkUuid, variantNum);
}
@Override
public Optional<Resource<LccConverterStationAttributes>> getLccConverterStation(UUID networkUuid, int variantNum, String lccConverterStationId) {
ensureCached(ResourceType.LCC_CONVERTER_STATION, networkUuid, variantNum);
return delegate.getLccConverterStation(networkUuid, variantNum, lccConverterStationId);
}
@Override
public void updateLccConverterStations(UUID networkUuid, List<Resource<LccConverterStationAttributes>> lccConverterStationResources, AttributeFilter attributeFilter) {
for (Resource<LccConverterStationAttributes> lccConverterStationResource : lccConverterStationResources) {
ensureCached(ResourceType.LCC_CONVERTER_STATION, networkUuid, lccConverterStationResource.getVariantNum());
}
delegate.updateLccConverterStations(networkUuid, lccConverterStationResources, attributeFilter);
}
@Override
public void createStaticVarCompensators(UUID networkUuid, List<Resource<StaticVarCompensatorAttributes>> svcResources) {
for (Resource<StaticVarCompensatorAttributes> svcResource : svcResources) {
ensureCached(ResourceType.STATIC_VAR_COMPENSATOR, networkUuid, svcResource.getVariantNum());
}
delegate.createStaticVarCompensators(networkUuid, svcResources);
}
@Override
public List<Resource<StaticVarCompensatorAttributes>> getStaticVarCompensators(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.STATIC_VAR_COMPENSATOR, networkUuid, variantNum);
return delegate.getStaticVarCompensators(networkUuid, variantNum);
}
@Override
public Optional<Resource<StaticVarCompensatorAttributes>> getStaticVarCompensator(UUID networkUuid, int variantNum, String staticVarCompensatorId) {
ensureCached(ResourceType.STATIC_VAR_COMPENSATOR, networkUuid, variantNum);
return delegate.getStaticVarCompensator(networkUuid, variantNum, staticVarCompensatorId);
}
@Override
public void updateStaticVarCompensators(UUID networkUuid, List<Resource<StaticVarCompensatorAttributes>> svcResources, AttributeFilter attributeFilter) {
for (Resource<StaticVarCompensatorAttributes> svcResource : svcResources) {
ensureCached(ResourceType.STATIC_VAR_COMPENSATOR, networkUuid, svcResource.getVariantNum());
}
delegate.updateStaticVarCompensators(networkUuid, svcResources, attributeFilter);
}
@Override
public void createHvdcLines(UUID networkUuid, List<Resource<HvdcLineAttributes>> hvdcLineResources) {
for (Resource<HvdcLineAttributes> hvdcLineResource : hvdcLineResources) {
ensureCached(ResourceType.HVDC_LINE, networkUuid, hvdcLineResource.getVariantNum());
}
delegate.createHvdcLines(networkUuid, hvdcLineResources);
}
@Override
public List<Resource<HvdcLineAttributes>> getHvdcLines(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.HVDC_LINE, networkUuid, variantNum);
return delegate.getHvdcLines(networkUuid, variantNum);
}
@Override
public Optional<Resource<HvdcLineAttributes>> getHvdcLine(UUID networkUuid, int variantNum, String hvdcLineId) {
ensureCached(ResourceType.HVDC_LINE, networkUuid, variantNum);
return delegate.getHvdcLine(networkUuid, variantNum, hvdcLineId);
}
@Override
public void removeHvdcLines(UUID networkUuid, int variantNum, List<String> hvdcLinesId) {
ensureCached(ResourceType.HVDC_LINE, networkUuid, variantNum);
delegate.removeHvdcLines(networkUuid, variantNum, hvdcLinesId);
}
@Override
public void updateHvdcLines(UUID networkUuid, List<Resource<HvdcLineAttributes>> hvdcLineResources, AttributeFilter attributeFilter) {
for (Resource<HvdcLineAttributes> hvdcLineResource : hvdcLineResources) {
ensureCached(ResourceType.HVDC_LINE, networkUuid, hvdcLineResource.getVariantNum());
}
delegate.updateHvdcLines(networkUuid, hvdcLineResources, attributeFilter);
}
@Override
public void createDanglingLines(UUID networkUuid, List<Resource<DanglingLineAttributes>> danglingLineResources) {
for (Resource<DanglingLineAttributes> danglingLineResource : danglingLineResources) {
ensureCached(ResourceType.DANGLING_LINE, networkUuid, danglingLineResource.getVariantNum());
}
delegate.createDanglingLines(networkUuid, danglingLineResources);
}
@Override
public List<Resource<DanglingLineAttributes>> getDanglingLines(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.DANGLING_LINE, networkUuid, variantNum);
return delegate.getDanglingLines(networkUuid, variantNum);
}
@Override
public Optional<Resource<DanglingLineAttributes>> getDanglingLine(UUID networkUuid, int variantNum, String danglingLineId) {
ensureCached(ResourceType.DANGLING_LINE, networkUuid, variantNum);
return delegate.getDanglingLine(networkUuid, variantNum, danglingLineId);
}
@Override
public void updateDanglingLines(UUID networkUuid, List<Resource<DanglingLineAttributes>> danglingLineResources, AttributeFilter attributeFilter) {
for (Resource<DanglingLineAttributes> danglingLineResource : danglingLineResources) {
ensureCached(ResourceType.DANGLING_LINE, networkUuid, danglingLineResource.getVariantNum());
}
delegate.updateDanglingLines(networkUuid, danglingLineResources, attributeFilter);
}
@Override
public void removeDanglingLines(UUID networkUuid, int variantNum, List<String> danglingLinesId) {
ensureCached(ResourceType.DANGLING_LINE, networkUuid, variantNum);
delegate.removeDanglingLines(networkUuid, variantNum, danglingLinesId);
}
@Override
public void createTieLines(UUID networkUuid, List<Resource<TieLineAttributes>> tieLineResources) {
for (Resource<TieLineAttributes> tieLineResource : tieLineResources) {
ensureCached(ResourceType.TIE_LINE, networkUuid, tieLineResource.getVariantNum());
}
delegate.createTieLines(networkUuid, tieLineResources);
}
@Override
public List<Resource<TieLineAttributes>> getTieLines(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.TIE_LINE, networkUuid, variantNum);
return delegate.getTieLines(networkUuid, variantNum);
}
@Override
public Optional<Resource<TieLineAttributes>> getTieLine(UUID networkUuid, int variantNum, String tieLineId) {
ensureCached(ResourceType.TIE_LINE, networkUuid, variantNum);
return delegate.getTieLine(networkUuid, variantNum, tieLineId);
}
@Override
public void removeTieLines(UUID networkUuid, int variantNum, List<String> tieLinesId) {
ensureCached(ResourceType.TIE_LINE, networkUuid, variantNum);
delegate.removeTieLines(networkUuid, variantNum, tieLinesId);
}
@Override
public void updateTieLines(UUID networkUuid, List<Resource<TieLineAttributes>> tieLineResources, AttributeFilter attributeFilter) {
for (Resource<TieLineAttributes> tieLineResource : tieLineResources) {
ensureCached(ResourceType.TIE_LINE, networkUuid, tieLineResource.getVariantNum());
}
delegate.updateTieLines(networkUuid, tieLineResources, attributeFilter);
}
@Override
public void createConfiguredBuses(UUID networkUuid, List<Resource<ConfiguredBusAttributes>> busResources) {
for (Resource<ConfiguredBusAttributes> busResource : busResources) {
ensureCached(ResourceType.CONFIGURED_BUS, networkUuid, busResource.getVariantNum());
}
delegate.createConfiguredBuses(networkUuid, busResources);
}
@Override
public List<Resource<ConfiguredBusAttributes>> getConfiguredBuses(UUID networkUuid, int variantNum) {
ensureCached(ResourceType.CONFIGURED_BUS, networkUuid, variantNum);
return delegate.getConfiguredBuses(networkUuid, variantNum);
}
@Override
public List<Resource<ConfiguredBusAttributes>> getVoltageLevelConfiguredBuses(UUID networkUuid, int variantNum, String voltageLevelId) {
ensureCached(ResourceType.CONFIGURED_BUS, networkUuid, variantNum);
return delegate.getVoltageLevelConfiguredBuses(networkUuid, variantNum, voltageLevelId);
}
@Override
public Optional<Resource<ConfiguredBusAttributes>> getConfiguredBus(UUID networkUuid, int variantNum, String busId) {
ensureCached(ResourceType.CONFIGURED_BUS, networkUuid, variantNum);
return delegate.getConfiguredBus(networkUuid, variantNum, busId);
}
@Override
public void updateConfiguredBuses(UUID networkUuid, List<Resource<ConfiguredBusAttributes>> busResources, AttributeFilter attributeFilter) {
for (Resource<ConfiguredBusAttributes> busResource : busResources) {
ensureCached(ResourceType.CONFIGURED_BUS, networkUuid, busResource.getVariantNum());
}
delegate.updateConfiguredBuses(networkUuid, busResources, attributeFilter);
}
@Override
public void removeConfiguredBuses(UUID networkUuid, int variantNum, List<String> configuredBusesId) {
ensureCached(ResourceType.CONFIGURED_BUS, networkUuid, variantNum);
delegate.removeConfiguredBuses(networkUuid, variantNum, configuredBusesId);
}
@Override
public Optional<ExtensionAttributes> getExtensionAttributes(UUID networkUuid, int variantNum, ResourceType resourceType, String identifiableId, String extensionName) {
delegate.getAllExtensionsAttributesByResourceTypeAndExtensionName(networkUuid, variantNum, resourceType, extensionName);
return delegate.getExtensionAttributes(networkUuid, variantNum, resourceType, identifiableId, extensionName);
}
@Override
public Map<String, ExtensionAttributes> getAllExtensionsAttributesByIdentifiableId(UUID networkUuid, int variantNum, ResourceType resourceType, String id) {
delegate.getAllExtensionsAttributesByResourceType(networkUuid, variantNum, resourceType);
return delegate.getAllExtensionsAttributesByIdentifiableId(networkUuid, variantNum, resourceType, id);
}
}
| 45,520
|
Java
|
.java
| 758
| 52.634565
| 186
| 0.774387
|
powsybl/powsybl-network-store
| 3
| 6
| 33
|
MPL-2.0
|
9/4/2024, 11:40:22 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 45,520
|
4,779,132
|
SqlResDialog.java
|
patrickbr_ferryleaks/src/com/algebraweb/editor/client/dialogs/SqlResDialog.java
|
package com.algebraweb.editor.client.dialogs;
import java.util.List;
import java.util.Map;
import com.algebraweb.editor.client.SqlResTable;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* A simple dialog to present sql results provided by a JDBC instance using a
* SqlResTable
*
* @author Patrick Brosi
*
*/
public class SqlResDialog extends DialogBox {
/**
* @param result
* the JDBC sql result
*/
public SqlResDialog(List<Map<String, String>> result) {
this.setText("Evaluation results");
SqlResTable t = new SqlResTable(result.size() + 1, result.get(0).size());
t.fill(result);
VerticalPanel p = new VerticalPanel();
ScrollPanel s = new ScrollPanel();
s.add(t);
p.add(s);
Button ok = new Button("Close");
ok.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
SqlResDialog.this.hide();
}
});
p.add(ok);
this.add(p);
this.center();
this.show();
}
}
| 1,223
|
Java
|
.java
| 43
| 25.837209
| 77
| 0.737382
|
patrickbr/ferryleaks
| 1
| 1
| 0
|
GPL-2.0
|
9/5/2024, 12:31:25 AM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
| 1,223
|
4,600,863
|
AerobaticLootTables.java
|
endorh_aerobatic-elytra/src/main/java/endorh/aerobaticelytra/server/loot/AerobaticLootTables.java
|
package endorh.aerobaticelytra.server.loot;
import endorh.aerobaticelytra.AerobaticElytra;
import net.minecraft.resources.ResourceLocation;
public class AerobaticLootTables {
public static final ResourceLocation END_SHIP_ELYTRA = AerobaticElytra.prefix("end_ship_elytra");
}
| 278
|
Java
|
.java
| 6
| 44.833333
| 98
| 0.862963
|
endorh/aerobatic-elytra
| 2
| 0
| 1
|
LGPL-3.0
|
9/5/2024, 12:18:57 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 278
|
2,793,592
|
ObjectFactory.java
|
minova-afis_aero_minova_rcp/bundles/aero.minova.rcp.form.setup/src/aero/minova/rcp/form/setup/xbs/ObjectFactory.java
|
package aero.minova.rcp.form.setup.xbs;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the aero.minova.rcp.form.setup.xbs package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: aero.minova.rcp.form.setup.xbs
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link WrapperConf }
*
*/
public WrapperConf createWrapperConf() {
return new WrapperConf();
}
/**
* Create an instance of {@link Log4JConf }
*
*/
public Log4JConf createLog4JConf() {
return new Log4JConf();
}
/**
* Create an instance of {@link Menu }
*
*/
public Menu createMenu() {
return new Menu();
}
/**
* Create an instance of {@link ExecuteJava }
*
*/
public ExecuteJava createExecuteJava() {
return new ExecuteJava();
}
/**
* Create an instance of {@link Preferences }
*
*/
public Preferences createPreferences() {
return new Preferences();
}
/**
* Create an instance of {@link Map }
*
*/
public Map createMap() {
return new Map();
}
/**
* Create an instance of {@link Setup }
*
*/
public Setup createSetup() {
return new Setup();
}
/**
* Create an instance of {@link RequiredModules }
*
*/
public RequiredModules createRequiredModules() {
return new RequiredModules();
}
/**
* Create an instance of {@link Module }
*
*/
public Module createModule() {
return new Module();
}
/**
* Create an instance of {@link Version }
*
*/
public Version createVersion() {
return new Version();
}
/**
* Create an instance of {@link OneOf }
*
*/
public OneOf createOneOf() {
return new OneOf();
}
/**
* Create an instance of {@link MinRequired }
*
*/
public MinRequired createMinRequired() {
return new MinRequired();
}
/**
* Create an instance of {@link RequiredService }
*
*/
public RequiredService createRequiredService() {
return new RequiredService();
}
/**
* Create an instance of {@link Service }
*
*/
public Service createService() {
return new Service();
}
/**
* Create an instance of {@link WrapperConf.Entry }
*
*/
public WrapperConf.Entry createWrapperConfEntry() {
return new WrapperConf.Entry();
}
/**
* Create an instance of {@link Log4JConf.Entry }
*
*/
public Log4JConf.Entry createLog4JConfEntry() {
return new Log4JConf.Entry();
}
/**
* Create an instance of {@link SqlCode }
*
*/
public SqlCode createSqlCode() {
return new SqlCode();
}
/**
* Create an instance of {@link Script }
*
*/
public Script createScript() {
return new Script();
}
/**
* Create an instance of {@link MdiCode }
*
*/
public MdiCode createMdiCode() {
return new MdiCode();
}
/**
* Create an instance of {@link Action }
*
*/
public Action createAction() {
return new Action();
}
/**
* Create an instance of {@link Menu.Entry }
*
*/
public Menu.Entry createMenuEntry() {
return new Menu.Entry();
}
/**
* Create an instance of {@link Toolbar }
*
*/
public Toolbar createToolbar() {
return new Toolbar();
}
/**
* Create an instance of {@link aero.minova.rcp.form.setup.xbs.Entry }
*
*/
public aero.minova.rcp.form.setup.xbs.Entry createEntry() {
return new aero.minova.rcp.form.setup.xbs.Entry();
}
/**
* Create an instance of {@link XbsCode }
*
*/
public XbsCode createXbsCode() {
return new XbsCode();
}
/**
* Create an instance of {@link Node }
*
*/
public Node createNode() {
return new Node();
}
/**
* Create an instance of {@link StaticCode }
*
*/
public StaticCode createStaticCode() {
return new StaticCode();
}
/**
* Create an instance of {@link Static }
*
*/
public Static createStatic() {
return new Static();
}
/**
* Create an instance of {@link CopyFile }
*
*/
public CopyFile createCopyFile() {
return new CopyFile();
}
/**
* Create an instance of {@link Filecopy }
*
*/
public Filecopy createFilecopy() {
return new Filecopy();
}
/**
* Create an instance of {@link Dircopy }
*
*/
public Dircopy createDircopy() {
return new Dircopy();
}
/**
* Create an instance of {@link Schema }
*
*/
public Schema createSchema() {
return new Schema();
}
/**
* Create an instance of {@link Tableschema }
*
*/
public Tableschema createTableschema() {
return new Tableschema();
}
/**
* Create an instance of {@link ExecuteJava.Parameter }
*
*/
public ExecuteJava.Parameter createExecuteJavaParameter() {
return new ExecuteJava.Parameter();
}
/**
* Create an instance of {@link Preferences.Root }
*
*/
public Preferences.Root createPreferencesRoot() {
return new Preferences.Root();
}
/**
* Create an instance of {@link Main }
*
*/
public Main createMain() {
return new Main();
}
/**
* Create an instance of {@link Map.Entry }
*
*/
public Map.Entry createMapEntry() {
return new Map.Entry();
}
}
| 6,445
|
Java
|
.java
| 277
| 17.245487
| 144
| 0.577633
|
minova-afis/aero.minova.rcp
| 6
| 2
| 82
|
EPL-2.0
|
9/4/2024, 10:15:27 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 6,445
|
4,478,002
|
ExitButton.java
|
Smujb_pixel-dungeon-souls/core/src/main/java/com/shatteredpixel/yasd/general/ui/ExitButton.java
|
/*
*
* * Pixel Dungeon
* * Copyright (C) 2012-2015 Oleg Dolya
* *
* * Shattered Pixel Dungeon
* * Copyright (C) 2014-2019 Evan Debenham
* *
* * Powered Pixel Dungeon
* * Copyright (C) 2014-2020 Samuel Braithwaite
* *
* * This program is free software: you can redistribute it and/or modify
* * it under the terms of the GNU General Public License as published by
* * the Free Software Foundation, either version 3 of the License, or
* * (at your option) any later version.
* *
* * This program is distributed in the hope that it will be useful,
* * but WITHOUT ANY WARRANTY; without even the implied warranty of
* * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* * GNU General Public License for more details.
* *
* * You should have received a copy of the GNU General Public License
* * along with this program. If not, see <http://www.gnu.org/licenses/>
*
*
*/
package com.shatteredpixel.yasd.general.ui;
import com.shatteredpixel.yasd.general.PDSGame;
import com.shatteredpixel.yasd.general.scenes.TitleScene;
import com.watabou.noosa.Game;
import com.watabou.noosa.Image;
public class ExitButton extends IconButton {
protected Image image;
public ExitButton() {
super(Icons.EXIT.get());
width = 20;
height = 20;
}
@Override
protected void onClick() {
if (Game.scene() instanceof TitleScene) {
Game.instance.finish();
} else {
PDSGame.switchNoFade( TitleScene.class );
}
}
}
| 1,473
|
Java
|
.java
| 47
| 29.148936
| 74
| 0.725159
|
Smujb/pixel-dungeon-souls
| 2
| 1
| 0
|
GPL-3.0
|
9/5/2024, 12:14:28 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
| 1,473
|
3,612,866
|
GrammarBlock.java
|
CARiSMA-Tool_carisma-tool/plugins/carisma.evolution.uml2.umlchange/src/carisma/evolution/uml2/umlchange/datatype/GrammarBlock.java
|
/*******************************************************************************
* Copyright (c) 2011 Software Engineering Institute, TU Dortmund.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* {SecSE group} - initial API and implementation and/or initial documentation
*******************************************************************************/
package carisma.evolution.uml2.umlchange.datatype;
import java.util.ArrayList;
import java.util.List;
/**
* A class to encapsulate UMLchange grammar strings.
* @author Daniel Warzecha
*
*/
public class GrammarBlock {
/**
* The original String function the GrammarBlock
* is initialized with.
*/
private String grammarString = null;
/**
* The alternatives.
*/
private List<GrammarAlternative> alternatives = null;
public GrammarBlock(final String grammar) {
this.grammarString = grammar.trim();
this.alternatives = new ArrayList<>();
List<String> extractedAlternatives =
ParserUtils.extract(
this.grammarString, ',');
for (String extractedAlternative : extractedAlternatives) {
this.alternatives.add(new GrammarAlternative(extractedAlternative));
}
}
public String getGrammarString() {
return this.grammarString;
}
public List<GrammarAlternative> getAlternatives() {
return this.alternatives;
}
public boolean hasNamespaceDescriptions() {
for (GrammarAlternative alt : this.alternatives) {
if (alt.hasNamespaceDescription()) {
return true;
}
}
return false;
}
public boolean isValid() {
if (this.alternatives == null || this.alternatives.isEmpty()) {
return false;
}
if (this.grammarString == null || this.grammarString.isEmpty()) {
return false;
}
for (GrammarAlternative alt : this.alternatives) {
if (!alt.isValid()) {
return false;
}
}
return true;
}
}
| 2,133
|
Java
|
.java
| 67
| 27.731343
| 82
| 0.664047
|
CARiSMA-Tool/carisma-tool
| 3
| 5
| 13
|
EPL-1.0
|
9/4/2024, 11:35:33 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 2,133
|
2,947,302
|
VariableErrorEvent.java
|
mhdirkse_counting-language/counting-language-impl/src/main/java/com/github/mhdirkse/countlang/analysis/VariableErrorEvent.java
|
/*
* Copyright Martijn Dirkse 2021
*
* This file is part of counting-language.
*
* counting-language is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.github.mhdirkse.countlang.analysis;
import com.github.mhdirkse.countlang.tasks.StatusCode;
import com.github.mhdirkse.countlang.tasks.StatusReporter;
import com.github.mhdirkse.countlang.type.CountlangType;
import lombok.Getter;
class VariableErrorEvent {
static enum Kind {
DOES_NOT_EXIST,
DUPLICATE_PARAMETER,
TYPE_MISMATCH;
}
private final @Getter Kind kind;
private final @Getter String name;
private final @Getter int line;
private final @Getter int column;
private final @Getter CountlangType variableType;
private final @Getter CountlangType typeMismatch;
VariableErrorEvent(Kind kind, String name, int line, int column) {
if(kind == Kind.TYPE_MISMATCH) {
throw new IllegalArgumentException("Do not use this constructor for type mismatches - you need to set the types involved");
}
this.kind = kind;
this.name = name;
this.line = line;
this.column = column;
this.variableType = null;
this.typeMismatch = null;
}
VariableErrorEvent(String name, int line, int column, CountlangType variableType, CountlangType typeMismatch) {
this.kind = Kind.TYPE_MISMATCH;
this.name = name;
this.line = line;
this.column = column;
this.variableType = variableType;
this.typeMismatch = typeMismatch;
}
public void report(StatusReporter reporter) {
switch(kind) {
case DOES_NOT_EXIST:
reporter.report(StatusCode.VAR_UNDEFINED, line, column, name);
break;
case DUPLICATE_PARAMETER:
reporter.report(StatusCode.DUPLICATE_PARAMETER, line, column, name);
break;
case TYPE_MISMATCH:
reporter.report(StatusCode.VAR_TYPE_CHANGED, line, column, name);
break;
}
}
}
| 2,628
|
Java
|
.java
| 68
| 32.632353
| 135
| 0.700627
|
mhdirkse/counting-language
| 5
| 0
| 7
|
AGPL-3.0
|
9/4/2024, 10:37:18 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 2,628
|
3,227,159
|
UserService.java
|
eduyayo_gamesboard/modules/HubServer/src/main/java/com/pigdroid/hub/service/impl/UserService.java
|
package com.pigdroid.hub.service.impl;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.sendgrid.SendGrid;
import com.pigdroid.hub.dao.CRUDInterface;
import com.pigdroid.hub.dao.UserDAOInterface;
import com.pigdroid.hub.model.message.HubMessage;
import com.pigdroid.hub.model.message.MessageContext;
import com.pigdroid.hub.model.persistent.User;
import com.pigdroid.hub.model.persistent.UserExample;
import com.pigdroid.hub.service.MessageServiceInterface;
import com.pigdroid.hub.service.UserServiceInterface;
import com.pigdroid.hub.service.exception.UserCredentialsException;
import flexjson.JSONSerializer;
@Service
@Transactional
public class UserService extends BaseService<User> implements UserServiceInterface {
private MessageServiceInterface messageService;
public void setMessageService(MessageServiceInterface messageService) {
this.messageService = messageService;
}
public void setUserDAO(CRUDInterface<User> in) {
this.dao = in;
}
private UserDAOInterface getUserDao() {
return (UserDAOInterface) dao;
}
public User createUserIfNotExists(String email, String password, String alias) throws UserCredentialsException {
User user = new User();
user.setEmail(email);
user.setNickName(alias);
boolean exists = count(user) == 1;
user.setPassword(password);
boolean hasCredentials = count(user) == 1;
if (!exists) {
save(user);
} else if (!hasCredentials) {
throw new UserCredentialsException();
}
return user;
}
public boolean exists(String email) {
User user = new User();
user.setEmail(email);
boolean exists = count(user) == 1;
return exists;
}
public void doLogin(MessageContext context) {
HubMessage msg = context.getMessage();
User user = checkUser(msg);
if (user != null) {
context.setUserEmail(msg.getFrom());
HubMessage newMsg = new HubMessage(HubMessage.TYPE_ACK,
HubMessage.TYPE_LOGIN);
newMsg.setPayload(createSerializer().deepSerialize(user));
newMsg.addTo(msg.getFrom());
messageService.sendMessage(context, newMsg);
} else {
// Login failed
messageService.sendErrorMessage(context);
}
}
private User checkUser(HubMessage msg) {
String email = msg.getFrom();
String password = msg.getWhat();
User user = null;
User example = new User();
example.setPassword(password);
example.setEmail(email);
user = get(example);
return user; }
public User checkUser(MessageContext context) {
HubMessage msg = context.getMessage();
return checkUser(msg);
}
public void doRegister(MessageContext context) {
HubMessage msg = context.getMessage();
String email = msg.getFrom();
String password = msg.getWhat();
String alias = msg.getPayload();
HubMessage message = null;
try {
createUserIfNotExists(email, password, alias);
message = new HubMessage(HubMessage.TYPE_ACK,
HubMessage.TYPE_REGISTER);
} catch (UserCredentialsException e) {
message = new HubMessage(HubMessage.TYPE_ERROR,
HubMessage.TYPE_REGISTER, "USER_EXISTS");
messageService.sendMessage(context, message);
}
messageService.sendMessageToSession(context, message);
}
@Override
public void doAddContact(MessageContext context) {
HubMessage msg = context.getMessage();
String email = msg.getTo().get(0);
User addedUser = new User();
addedUser.setEmail(email);
addedUser = get(addedUser);
if (addedUser != null) {
JSONSerializer serializer = createSerializer();
//Found the user, add him to the list of contacts for this session.
HubMessage messageToUserInSession = new HubMessage(HubMessage.TYPE_ACK, HubMessage.TYPE_ADD_CONTACT);
messageToUserInSession.addTo(context.getUserEmail());
messageToUserInSession.setPayload(serializer.deepSerialize(addedUser));
//Notify the destination of the contact about this event
HubMessage messageToAddedUser = new HubMessage(HubMessage.TYPE_ADD_CONTACT);
messageToAddedUser.addTo(addedUser.getEmail());
User contextUser = getContextUser(context);
contextUser.getContacts().add(addedUser);
save(contextUser);
//Avoid the serialization of private data.
messageToAddedUser.setPayload(serializer.deepSerialize(contextUser));
messageService.sendMessage(context, messageToAddedUser, true);
messageService.sendMessage(context, messageToUserInSession);
} else {
HubMessage message = new HubMessage(HubMessage.TYPE_ERROR, HubMessage.TYPE_ADD_CONTACT);
message.setTo(msg.getTo());
message.setType("NOT_FOUND");
messageService.sendMessage(context, message);
}
}
private JSONSerializer createSerializer() {
JSONSerializer serializer = new JSONSerializer().exclude("contacts", "password", "games", "messages");
return serializer;
}
private User getContextUser(MessageContext context) {
User userInSession = new User();
userInSession.setEmail(context.getUserEmail());
userInSession = get(userInSession);
return userInSession;
}
@Override
public void doRemoveContact(MessageContext context) {
// TODO Auto-generated method stub
}
@Override
public void doRetrieveRooster(MessageContext context) {
User user = getContextUser(context);
Set<User> contacts = new HashSet<User>(user.getContacts());
Set<User> invited = new HashSet<User>(contacts);
List<User> inverseRooster = getWhoAdded(user);
invited.removeAll(inverseRooster);
contacts.retainAll(inverseRooster);
inverseRooster.removeAll(contacts);
HubMessage msg = new HubMessage(HubMessage.TYPE_ACK, HubMessage.TYPE_REQUEST_ROOSTER);
JSONSerializer serializer = createSerializer();
StringBuilder builder = new StringBuilder();
builder.append("[");
builder.append(serializer.deepSerialize(invited)); // Users that I invited but have not added me.
builder.append(",");
builder.append(serializer.deepSerialize(contacts)); // Users present for game. Added and added back
builder.append(",");
builder.append(serializer.deepSerialize(inverseRooster)); // Users that have added me but I have not added back.
builder.append("]");
msg.setPayload(builder.toString());
msg.addTo(user.getEmail());
messageService.sendMessage(context, msg);
}
private List<User> getWhoAdded(User user) {
UserDAOInterface dao = getUserDao();
return dao.getWhoAdded(user);
}
@Override
public void doListUsers(MessageContext context) {
String searchTerm = context.getMessage().getPayload();
UserExample userExample = new UserExample();
userExample.setEmailLike(searchTerm);
userExample.setNickNameLike(searchTerm);
User user = getContextUser(context);
List<String> emailNotIn = new LinkedList<String>();
for (User contact : user.getContacts()) {
emailNotIn.add(contact.getEmail());
}
emailNotIn.add(context.getUserEmail());
userExample.setEmailNotIn(emailNotIn);
List<User> list = list(userExample);
HubMessage msg = new HubMessage(HubMessage.TYPE_ACK, HubMessage.TYPE_USER_LIST);
msg.addTo(context.getUserEmail());
JSONSerializer serializer = createSerializer();
msg.setPayload(serializer.deepSerialize(list));
messageService.sendMessage(context, msg);
}
@Override
public void doSendPassword(MessageContext context) {
HubMessage msg = context.getMessage();
User user = getContextUser(context);
if (user != null) {
SendGrid sendgrid = new SendGrid("eduyayo", "mirapuru1");
sendgrid.addTo(user.getEmail());
sendgrid.setFrom("[email protected]");
sendgrid.setSubject("Game Board Password reminder!");
sendgrid.setText("Your current password is: " + user.getPassword()
+ ".");
sendgrid.send();
HubMessage newmsg = new HubMessage(HubMessage.TYPE_ACK, HubMessage.TYPE_SEND_PASS);
newmsg.addTo(user.getEmail());
messageService.sendMessage(context, newmsg);
}
}
@Override
public User getByEmail(String email) {
UserExample example = new UserExample();
example.setEmail(email);
return get(example);
}
}
| 8,029
|
Java
|
.java
| 211
| 34.976303
| 114
| 0.775418
|
eduyayo/gamesboard
| 4
| 1
| 0
|
GPL-3.0
|
9/4/2024, 11:06:42 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 8,029
|
879,224
|
DisplayUtils.java
|
activityworkshop_GpsPrune/src/tim/prune/gui/DisplayUtils.java
|
package tim.prune.gui;
import java.text.NumberFormat;
import tim.prune.I18nManager;
/**
* Class to provide general display util methods
*/
public abstract class DisplayUtils
{
/** Number formatter for one decimal place */
private static final NumberFormat FORMAT_ONE_DP = NumberFormat.getNumberInstance();
/** Static block to initialise the one d.p. formatter */
static
{
FORMAT_ONE_DP.setMaximumFractionDigits(1);
FORMAT_ONE_DP.setMinimumFractionDigits(1);
}
/** Flexible number formatter with different decimal places */
private static final NumberFormat FORMAT_FLEX = NumberFormat.getNumberInstance();
/**
* Build a String to describe a time duration
* @param inNumSecs number of seconds
* @return time as a string, days, hours, mins, secs as appropriate
*/
public static String buildDurationString(long inNumSecs)
{
if (inNumSecs <= 0L) return "";
if (inNumSecs < 60L) return "" + inNumSecs + I18nManager.getText("display.range.time.secs");
if (inNumSecs < 3600L) return "" + (inNumSecs / 60) + I18nManager.getText("display.range.time.mins")
+ " " + (inNumSecs % 60) + I18nManager.getText("display.range.time.secs");
if (inNumSecs < 86400L) return "" + (inNumSecs / 60 / 60) + I18nManager.getText("display.range.time.hours")
+ " " + ((inNumSecs / 60) % 60) + I18nManager.getText("display.range.time.mins");
if (inNumSecs < 432000L) return "" + (inNumSecs / 86400L) + I18nManager.getText("display.range.time.days")
+ " " + (inNumSecs / 60 / 60) % 24 + I18nManager.getText("display.range.time.hours")
+ " " + ((inNumSecs / 60) % 60) + I18nManager.getText("display.range.time.mins");
if (inNumSecs < 86400000L) return "" + (inNumSecs / 86400L) + I18nManager.getText("display.range.time.days");
return "big";
}
/**
* @param inNumber number to format
* @return formatted number to one decimal place
*/
public static String formatOneDp(double inNumber)
{
return FORMAT_ONE_DP.format(inNumber);
}
/**
* Format a number to a sensible precision
* @param inVal value to format
* @return formatted String using local format
*/
public static String roundedNumber(double inVal)
{
// Set precision of formatter
int numDigits = 0;
if (inVal < 1.0)
numDigits = 3;
else if (inVal < 10.0)
numDigits = 2;
else if (inVal < 100.0)
numDigits = 1;
// set formatter
FORMAT_FLEX.setMaximumFractionDigits(numDigits);
FORMAT_FLEX.setMinimumFractionDigits(numDigits);
return FORMAT_FLEX.format(inVal);
}
/**
* Convert the given hour and minute values into a string H:MM
* @param inHour hour of day, 0-24
* @param inMinute minute, 0-59
* @return string, either H:MM or HH:MM
*/
public static String makeTimeString(int inHour, int inMinute)
{
StringBuilder sb = new StringBuilder();
final int hour = (inHour >= 0 && inHour <= 24) ? inHour : 0;
sb.append(hour);
sb.append(':');
final int minute = (inMinute >= 0 && inMinute <= 59) ? inMinute : 0;
if (minute <= 9) {sb.append('0');}
sb.append(minute);
return sb.toString();
}
}
| 3,044
|
Java
|
.java
| 83
| 33.939759
| 111
| 0.709492
|
activityworkshop/GpsPrune
| 68
| 21
| 25
|
GPL-2.0
|
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
| 3,044
|
4,881,669
|
BestellungServiceDelegate.java
|
heliumv_lpclientpc/src/com/lp/client/frame/delegate/BestellungServiceDelegate.java
|
/*******************************************************************************
* HELIUM V, Open Source ERP software for sustained success
* at small and medium-sized enterprises.
* Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of theLicense, or
* (at your option) any later version.
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "HELIUM V" and "HELIUM 5" are registered trademarks of
* HELIUM V IT-Solutions GmbH. The licensing of the program under the
* AGPL does not imply a trademark license. Therefore any rights, title and
* interest in our trademarks remain entirely with us. If you want to propagate
* modified versions of the Program under the name "HELIUM V" or "HELIUM 5",
* you may only do so if you have a written permission by HELIUM V IT-Solutions
* GmbH (to acquire a permission please contact HELIUM V IT-Solutions
* at [email protected]).
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact: [email protected]
******************************************************************************/
package com.lp.client.frame.delegate;
import java.util.Locale;
import java.util.Map;
import javax.naming.Context;
import javax.naming.InitialContext;
import com.lp.client.frame.ExceptionLP;
import com.lp.client.pc.LPMain;
import com.lp.server.bestellung.service.BestellpositionartDto;
import com.lp.server.bestellung.service.BestellungServiceFac;
import com.lp.server.bestellung.service.BestellungsartDto;
import com.lp.server.bestellung.service.BestellungstatusDto;
import com.lp.server.bestellung.service.BestellungtextDto;
import com.lp.server.bestellung.service.MahngruppeDto;
import com.lp.server.system.service.MediaFac;
import com.lp.util.EJBExceptionLP;
@SuppressWarnings("static-access")
/**
* <p>Delegate fuer Bestellung Services.</p>
*
* <p>Copyright Logistik Pur Software GmbH (c) 2004-2008</p>
*
* <p>Erstellung: Uli Walch, 27. 04. 2005</p>
*
* <p>@author Uli Walch</p>
*
* @version 1.0
*
* @version $Revision: 1.8 $ Date $Date: 2011/05/26 09:16:55 $
*/
public class BestellungServiceDelegate extends Delegate {
private Context context = null;
private BestellungServiceFac bestellungServiceFac = null;
public BestellungServiceDelegate() throws ExceptionLP {
try {
context = new InitialContext();
bestellungServiceFac = (BestellungServiceFac) context
.lookup("lpserver/BestellungServiceFacBean/remote");
} catch (Throwable t) {
throw new ExceptionLP(EJBExceptionLP.FEHLER, t.toString(), null);
}
}
public BestellungtextDto bestellungtextFindByPrimaryKey(Integer iId)
throws ExceptionLP {
BestellungtextDto oBestellungtextDto = null;
try {
oBestellungtextDto = bestellungServiceFac
.bestellungtextFindByPrimaryKey(iId);
} catch (Throwable ex) {
handleThrowable(ex);
}
return oBestellungtextDto;
}
/**
* Den default Kopftext einer Bestellung holen.
*
* @param pLocKunde
* die Sprache des Kunden
* @return BestellungtextDto der Kopftext
* @throws ExceptionLP
*/
public BestellungtextDto getBestellungkopfDefault(String pLocKunde)
throws ExceptionLP {
BestellungtextDto oKoftextDto = null;
try {
oKoftextDto = bestellungServiceFac
.bestellungtextFindByMandantLocaleCNr(LPMain.getInstance()
.getTheClient().getMandant(), pLocKunde,
MediaFac.MEDIAART_KOPFTEXT, LPMain.getInstance()
.getTheClient());
} catch (Throwable t) {
handleThrowable(t);
}
return oKoftextDto;
}
/**
* Den default Fusstext einer Bestellung holen.
*
* @param pLocKunde
* die Sprache des Kunden
* @return BestellungtextDto der Fusstext
* @throws ExceptionLP
*/
public BestellungtextDto getBestellungfussDefault(String pLocKunde)
throws ExceptionLP {
BestellungtextDto oFusstextDto = null;
try {
oFusstextDto = bestellungServiceFac
.bestellungtextFindByMandantLocaleCNr(LPMain.getInstance()
.getTheClient().getMandant(), pLocKunde,
MediaFac.MEDIAART_FUSSTEXT, LPMain.getInstance()
.getTheClient());
} catch (Throwable t) {
handleThrowable(t);
}
return oFusstextDto;
}
public Integer createBestellungtext(BestellungtextDto bestellungtextDto)
throws ExceptionLP {
Integer iId = null;
try {
// fuer StammdatenCRUD : alle Felder, die in der UI nicht vorhanden
// sind selbst befuellen
bestellungtextDto.setMandantCNr(LPMain.getInstance().getTheClient()
.getMandant());
bestellungtextDto.setLocaleCNr(LPMain.getInstance().getTheClient()
.getLocUiAsString());
iId = bestellungServiceFac.createBestellungtext(bestellungtextDto);
} catch (Throwable ex) {
handleThrowable(ex);
}
return iId;
}
public void removeBestellungtext(BestellungtextDto bestellungtextDto)
throws ExceptionLP {
try {
bestellungServiceFac.removeBestellungtext(bestellungtextDto);
} catch (Throwable ex) {
handleThrowable(ex);
}
}
public void updateBestellungtext(BestellungtextDto bestellungtextDto)
throws ExceptionLP {
try {
bestellungServiceFac.updateBestellungtext(bestellungtextDto);
} catch (Throwable ex) {
handleThrowable(ex);
}
}
public BestellungtextDto bestellungtextFindByMandantLocaleCNr(
String sLocaleI, String sCNrI) throws ExceptionLP {
BestellungtextDto bestellungtextDto = null;
try {
bestellungtextDto = bestellungServiceFac
.bestellungtextFindByMandantLocaleCNr(LPMain.getInstance()
.getTheClient().getMandant(), sLocaleI, sCNrI,
LPMain.getInstance().getTheClient());
} catch (Throwable ex) {
handleThrowable(ex);
}
return bestellungtextDto;
}
public BestellungtextDto createDefaultBestellungtext(String sMediaartI,
String sTextinhaltI) throws ExceptionLP {
BestellungtextDto bestellungtextDto = null;
try {
bestellungtextDto = bestellungServiceFac
.createDefaultBestellungtext(sMediaartI, sTextinhaltI,
LPMain.getInstance().getTheClient());
} catch (Throwable t) {
handleThrowable(t);
}
return bestellungtextDto;
}
public String createBestellungstatus(BestellungstatusDto bestellungstatusDto)
throws ExceptionLP {
String cNr = null;
try {
cNr = bestellungServiceFac
.createBestellungstatus(bestellungstatusDto);
} catch (Throwable ex) {
handleThrowable(ex);
}
return cNr;
}
public void createMahngruppe(MahngruppeDto mahngruppeDto)
throws ExceptionLP {
try {
bestellungServiceFac.createMahngruppe(mahngruppeDto);
} catch (Throwable ex) {
handleThrowable(ex);
}
}
public void removeBestellungsart(BestellungsartDto bestellungartDto)
throws ExceptionLP {
try {
bestellungServiceFac.removeBestellungart(bestellungartDto, LPMain
.getInstance().getTheClient());
} catch (Throwable ex) {
handleThrowable(ex);
}
}
public void removeMahngruppe(MahngruppeDto mahngruppeDto)
throws ExceptionLP {
try {
bestellungServiceFac.removeMahngruppe(mahngruppeDto);
} catch (Throwable ex) {
handleThrowable(ex);
}
}
public void removeBestellungstatus(BestellungstatusDto bestellungstatusDto)
throws ExceptionLP {
try {
bestellungServiceFac.removeBestellungstatus(bestellungstatusDto);
} catch (Throwable ex) {
handleThrowable(ex);
}
}
public void updateBestellungstatus(BestellungstatusDto bestellungstatusDto)
throws ExceptionLP {
try {
bestellungServiceFac.updateBestellungstatus(bestellungstatusDto);
} catch (Throwable ex) {
handleThrowable(ex);
}
}
public void updateBestellungsart(BestellungsartDto bestellungartDto)
throws ExceptionLP {
try {
bestellungServiceFac.updateBestellungart(bestellungartDto, LPMain
.getInstance().getTheClient());
} catch (Throwable ex) {
handleThrowable(ex);
}
}
public String createBestellungsart(BestellungsartDto bestellungartDto)
throws ExceptionLP {
String sBestellungart = null;
try {
sBestellungart = bestellungServiceFac.createBestellungart(
bestellungartDto, LPMain.getInstance().getTheClient());
} catch (Throwable ex) {
handleThrowable(ex);
}
return sBestellungart;
}
public BestellungsartDto bestellungsartFindByPrimaryKey(String cNr)
throws ExceptionLP {
BestellungsartDto dto = null;
try {
dto = bestellungServiceFac.bestellungartFindByPrimaryKey(cNr,
LPMain.getInstance().getTheClient());
} catch (Throwable ex) {
handleThrowable(ex);
}
return dto;
}
public MahngruppeDto mahngruppeFindByPrimaryKey(Integer artgruIId)
throws ExceptionLP {
MahngruppeDto dto = null;
try {
dto = bestellungServiceFac.mahngruppeFindByPrimaryKey(artgruIId);
} catch (Throwable ex) {
handleThrowable(ex);
}
return dto;
}
public BestellungstatusDto bestellungstatusFindByPrimaryKey(String cNr)
throws ExceptionLP {
BestellungstatusDto dto = null;
try {
dto = bestellungServiceFac.bestellungstatusFindByPrimaryKey(cNr);
} catch (Throwable ex) {
handleThrowable(ex);
}
return dto;
}
/**
* Alle Bestellungarten in bestmoeglicher Uebersetzung von der DB holen.
*
* @param pLocLieferant
* das Locale des Lieferanten
* @return Map die Bestellungarten mit ihrer Uebersetzung
* @throws ExceptionLP
* @throws Throwable
*/
public Map<?, ?> getBestellungsart(Locale pLocLieferant) throws ExceptionLP {
Map<?, ?> arten = null;
try {
arten = bestellungServiceFac.getBestellungart(pLocLieferant, LPMain
.getInstance().getUISprLocale());
} catch (Throwable t) {
handleThrowable(t);
}
return arten;
}
/**
* Alle verfuegbaren Bestellpositionsarten in bestmoeglicher Uebersetzung
* aus der DB holen.
*
* @param pLocKunde
* Locale
* @return Map
* @throws ExceptionLP
* @throws Throwable
*/
public Map<String, String> getBestellpositionart(Locale pLocKunde)
throws ExceptionLP {
Map<String, String> posarten = null;
try {
posarten = bestellungServiceFac.getBestellpositionart(pLocKunde,
LPMain.getInstance().getUISprLocale());
} catch (Throwable t) {
handleThrowable(t);
}
return posarten;
}
public String createBestellpositionart(
BestellpositionartDto bestellpositionartDtoI) throws ExceptionLP {
String bestellpositionartCNr = null;
try {
bestellpositionartCNr = bestellungServiceFac
.createBestellpositionart(bestellpositionartDtoI, LPMain
.getInstance().getTheClient());
} catch (Throwable t) {
handleThrowable(t);
}
return bestellpositionartCNr;
}
public void updateBestellpositionart(
BestellpositionartDto bestellpositionartDtoI) throws ExceptionLP {
try {
bestellungServiceFac
.updateBestellpositionart(bestellpositionartDtoI, LPMain
.getInstance().getTheClient());
} catch (Throwable t) {
handleThrowable(t);
}
}
public BestellpositionartDto bestellpositionartFindByPrimaryKey(
String cNrBestellpositionartI) throws ExceptionLP {
BestellpositionartDto bestellpositionartDto = null;
try {
bestellpositionartDto = bestellungServiceFac
.bestellpositionartFindByPrimaryKey(cNrBestellpositionartI,
LPMain.getInstance().getTheClient());
} catch (Throwable t) {
handleThrowable(t);
}
return bestellpositionartDto;
}
public BestellungsartDto[] getAllBestellungsArt() throws ExceptionLP {
BestellungsartDto[] toReturn = null;
try {
toReturn = bestellungServiceFac.getAllBestellungsArt();
} catch (Throwable t) {
handleThrowable(t);
}
return toReturn;
}
}
| 12,107
|
Java
|
.java
| 372
| 29.198925
| 80
| 0.759825
|
heliumv/lpclientpc
| 1
| 3
| 0
|
AGPL-3.0
|
9/5/2024, 12:34:40 AM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
| 12,107
|
3,187,555
|
DescribeRegionsResponse.java
|
kuiwang_my-dev/src/main/java/com/aliyun/api/ecs/ecs20140526/response/DescribeRegionsResponse.java
|
package com.aliyun.api.ecs.ecs20140526.response;
import java.util.List;
import com.aliyun.api.AliyunResponse;
import com.aliyun.api.domain.Region;
import com.taobao.api.internal.mapping.ApiField;
import com.taobao.api.internal.mapping.ApiListField;
/**
* TOP API: ecs.aliyuncs.com.DescribeRegions.2014-05-26 response.
*
* @author auto create
* @since 1.0, null
*/
public class DescribeRegionsResponse extends AliyunResponse {
private static final long serialVersionUID = 5139833691291141898L;
/**
* 地域信息组成的集合
*/
@ApiListField("Regions")
@ApiField("Region")
private List<Region> regions;
/**
* 请求ID
*/
@ApiField("RequestId")
private String requestId;
public List<Region> getRegions() {
return this.regions;
}
public String getRequestId() {
return this.requestId;
}
public void setRegions(List<Region> regions) {
this.regions = regions;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
}
| 1,069
|
Java
|
.java
| 38
| 23.052632
| 70
| 0.708417
|
kuiwang/my-dev
| 4
| 2
| 0
|
GPL-3.0
|
9/4/2024, 11:03:38 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
| 1,047
|
4,398,958
|
Eventual.java
|
httpobjects-org_httpobjects/core/src/main/java/org/httpobjects/eventual/Eventual.java
|
package org.httpobjects.eventual;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
public interface Eventual<T> {
void then(Consumer<T> fn);
<R> Eventual<R> map(Function<T, R> fn);
<R> Eventual<R> flatMap(Function<T, Eventual<R>> fn);
T join();
static <T> Eventual<T> resolved(T resolution){
final Resolvable<T> r = new Resolvable<T>();
r.resolve(resolution);
return r;
}
static <T> Eventual<T> resolveTo(Supplier<T> action){
final Resolvable<T> r = new Resolvable<T>();
r.resolve(action.get());
return r;
}
static <T> Eventual<T> resolveAsyncTo(Executor executor, Supplier<T> action){
final Resolvable<T> r = new Resolvable<T>();
executor.execute(()->{
r.resolve(action.get());
});
return r;
}
}
| 939
|
Java
|
.java
| 28
| 27.357143
| 81
| 0.643653
|
httpobjects-org/httpobjects
| 2
| 0
| 0
|
GPL-2.0
|
9/5/2024, 12:11:47 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 939
|
878,206
|
FeatureVector.java
|
cemfi_meico/src/meico/pitches/FeatureVector.java
|
package meico.pitches;
import com.github.cliftonlabs.json_simple.JsonArray;
import com.github.cliftonlabs.json_simple.JsonObject;
/**
* This class represents one pitch feature, i.e. an array of FeatureElements that form the feature vector.
* @author Axel Berndt.
*/
public class FeatureVector {
private FeatureElement[] feature = null; // a feature vector is an array of feature elements
/**
* constructor
* @param feature the feature vector, i.e. array of FeatureElements
*/
public FeatureVector(FeatureElement[] feature) {
this.feature = feature;
}
/**
* constructor
* @param key initializes a 0-vector that conforms the given key
*/
public FeatureVector(Key key) {
this.feature = new FeatureElement[key.getSize()];
for (int i = 0; i < this.feature.length; ++i) {
this.feature[i] = new FeatureElement();
}
}
/**
* retrun the getSize of the feature vector
* @return
*/
public int getSize() {
return this.feature.length;
}
/**
* this method returns the element of this vector at the given index
* @param index
* @return
*/
public FeatureElement getFeatureElement(int index) {
return this.feature[index];
}
/**
* This adds up the energy and note ids of two feature vectors.
* But be aware that the vectors should have the same size. Otherwise correctness of this operation cannot be ensured.
* @param feature the feature vector to be added
* @return
*/
public boolean add(FeatureVector feature) {
int maxIndex = (this.getSize() < feature.getSize()) ? this.getSize() : feature.getSize(); // to avoid IndexOutOfBounds we can only iterate to the smallest maximum index of both vectors
for (int i=0; i < maxIndex; ++i) { // go through the vector elements
FeatureElement e = feature.getFeatureElement(i); // get the element of the vector to be added
this.feature[i].addEnergy(e.getEnergy()); // add its energy
this.feature[i].addNoteIds(e.getNoteIds()); // add its note ids
}
return this.feature.length == feature.getSize(); // if this is true, everything is fine, otherwise it is at the discretion of the application
}
/**
* This adds only an energy vector to the feature vector, no ids.
* But be aware that the vectors should have the same size. Otherwise correctness of this operation cannot be ensured.
* @param energy
* @return
*/
public boolean addEnergy(double[] energy) {
int maxIndex = (this.feature.length < energy.length) ? this.feature.length : energy.length; // to avoid IndexOutOfBounds we can only iterate to the smallest maximum index of both vectors
for (int i=0; i < maxIndex; ++i) // go through the vector elements
this.feature[i].addEnergy(energy[i]); // add energy
return this.feature.length == energy.length; // if this is true, everything is fine, otherwise it is at the discretion of the application
}
/**
* converts this class instance into a JSONObject
* @return
*/
protected JsonObject toJson() {
JsonArray energyVector = new JsonArray(); // the energy vector (e.g. chroma vector)
JsonArray idVector = new JsonArray(); // the corresponding array of note ids
for (int i=0; i < this.feature.length; ++i) { // go through all feature elements
FeatureElement fe = feature[i];
energyVector.add(fe.getEnergy()); // write its energy level to the json energy vector
JsonArray ids = new JsonArray();
ids.addAll(fe.getNoteIds()); // collect all the note ids that contribute to the energy
idVector.add(ids); // fill the note id vector
}
// create the json representative of this feature vector
JsonObject json = new JsonObject();
json.put("nrg", energyVector);
json.put("ids", idVector);
return json;
}
}
| 4,314
|
Java
|
.java
| 89
| 41.460674
| 196
| 0.620157
|
cemfi/meico
| 69
| 13
| 3
|
GPL-3.0
|
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
| 4,314
|
543,802
|
ItemElement51Stack.java
|
AllayMC_Allay/api/src/main/java/org/allaymc/api/item/interfaces/element/ItemElement51Stack.java
|
package org.allaymc.api.item.interfaces.element;
import org.allaymc.api.item.ItemStack;
public interface ItemElement51Stack extends ItemStack {
}
| 148
|
Java
|
.java
| 4
| 35.5
| 55
| 0.859155
|
AllayMC/Allay
| 157
| 12
| 40
|
LGPL-3.0
|
9/4/2024, 7:07:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 148
|
2,411,257
|
Transformation.java
|
vionta_Salvora/src/main/java/net/vionta/salvora/config/dto/Transformation.java
|
package net.vionta.salvora.config.dto;
import java.util.ArrayList;
import java.util.List;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "transformation")
public class Transformation implements NetworkPathConfiguration {
public static final String LOCAL_SOURCE_TYPE = "local_file";
public static final String LOCAL_DIRECTORY_LISTING= "directory_listing";
public static final String REMOTE_NETWORK_SOURCE_TYPE = "remote_network";
public static final String LOCAL_NETWORK_SOURCE_TYPE = "local_network";
@XmlAttribute(name = "name", required = true)
protected String name;
@XmlAttribute(name = "path")
protected String path;
@XmlAttribute(name = "base-path")
protected String basePath;
@XmlAttribute(name = "base-internal-path")
protected String baseInternalPath;
@XmlAttribute(name = "internal-path")
protected String internalPath;
@XmlElement(name="step", type = TransformationStep.class)
protected List<TransformationStep> transformationSteps = new ArrayList<TransformationStep>();
@XmlElement(name="trigger", type = Trigger.class)
protected List<Trigger> triggers = new ArrayList<Trigger>();
@Override
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Override
public String getInternalPath() {
return internalPath;
}
public void setInternalPath(String url) {
this.internalPath = url;
}
@XmlAttribute(name = "type")
protected String type = "file";
public List<Trigger> getTriggers() {
return triggers;
}
public void setTriggers(List<Trigger> triggers) {
this.triggers = triggers;
}
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
@Override
public String getBasePath() {
return basePath;
}
public void setBasePath(String value) {
this.basePath = value;
}
@Override
public String getBaseInternalPath() {
return (baseInternalPath == null) ? getBasePath() : baseInternalPath;
}
public void setBaseInternal(String value) {
this.baseInternalPath = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<TransformationStep> getTransformationSteps() {
return transformationSteps;
}
public void setTransformationSteps(List<TransformationStep> transformationSteps) {
this.transformationSteps = transformationSteps;
}
@Override
public String toString() {
StringBuilder rep = new StringBuilder("Transformation ");
if(name!=null) rep.append(name);
rep.append(" : ");
if(basePath!=null) rep.append(basePath);
if(path!=null) rep.append(" " ).append(path);
rep.append(" -> ");
if(baseInternalPath!=null) rep.append(baseInternalPath);
if(internalPath!=null) rep.append(" " ).append(internalPath);
rep.append("\n");
rep.append(" Steps :").append(transformationSteps.size());
rep.append(" Triggers :").append(triggers.size());
return rep.toString();
}
}
| 3,447
|
Java
|
.java
| 99
| 29.747475
| 98
| 0.719122
|
vionta/Salvora
| 8
| 0
| 4
|
GPL-3.0
|
9/4/2024, 9:21:30 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 3,447
|
4,328,190
|
WeightedRandom.java
|
yxzhou_footprints/util/random/WeightedRandom.java
|
package util.random;
public class WeightedRandom
{
/*
* Weighted random sampling with a reservoir
*
* given a big table (checkIn - occurrence), and we need to write an efficient function to randomly select 1 checkIn
* where probability is based on the occurrence.
*
* Example:
* input (q1 - 20)(q2 - 10 )( q3 - 30)
* the probability of q1 is 20/(20+10+30) = 20/60
*
*/
static int res; // The resultant random number
static int sum = 0; //Count of numbers visited so far in stream
public static int selectRandom(int query, int weight){
int precount = sum;
sum += weight; // increment count of numbers seen so far
// If this is the first element from stream, return it
if (sum == 1) {
res = query;
} else {
// Generate a random number from 0 to count - 1
java.util.Random random = new java.util.Random();
int i = random.nextInt(sum);
// Replace the prev random number with new number with weight/(count+weight) probability
if (i > precount) { // or (i <= weight)
res = query;
}
}
return res;
}
// Driver program to test above function.
public static void main(String[] args)
{
int[] query = {1, 3, 5};
int[] occurrence = {20, 10, 30};
int n = query.length;
for (int i = 0; i < n; ++i)
System.out.printf("random number from first %d numbers is %d \n",
i+1, selectRandom(query[i], occurrence[i]));
}
class Query{
int id;
int occurrence;
}
}
| 1,720
|
Java
|
.java
| 48
| 27
| 119
| 0.57721
|
yxzhou/footprints
| 2
| 0
| 0
|
GPL-3.0
|
9/5/2024, 12:09:19 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 1,720
|
3,586,009
|
Pq.java
|
moozd_JTel/src/com/jtel/mtproto/auth/pq/Pq.java
|
package com.jtel.mtproto.auth.pq;
/**
* This file is part of JTel
* IntelliJ idea.
* Date : 6/9/16
* Package : com.jtel.mtproto.auth.pq
*
* @author <a href="mailto:[email protected]">Mohammad Mohammad Zade</a>
*/
/**
* This class store pq number
* p and q are prime factors of pq number
* where p < q
*/
public class Pq {
/**
* pq number in bytes
*/
public byte[] pq;
/**
* p number in bytes
*/
public byte[] p;
/**
* q number in bytes
*/
public byte[] q;
/**
* constructor accepts one parameter, to store p and q numbers
* we will do the math elsewhere.
* @param pq one of the parameters of the req_pq method from tl schema is pq number in bytes
* . do not generate random numbers to pass as pq number, you must getAuth it from ser
* ver throw req_pq method.
*/
public Pq(byte[] pq){
this.pq = pq;
}
}
| 960
|
Java
|
.java
| 38
| 21.052632
| 101
| 0.602186
|
moozd/JTel
| 3
| 0
| 0
|
GPL-3.0
|
9/4/2024, 11:34:01 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
| 960
|
3,116,980
|
AddAsciiOutputStream.java
|
d-fens_drftpd/src/common/src/org/drftpd/io/AddAsciiOutputStream.java
|
/*
* This file is part of DrFTPD, Distributed FTP Daemon.
*
* DrFTPD is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* DrFTPD 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 DrFTPD; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.drftpd.io;
import java.io.IOException;
import java.io.OutputStream;
/**
* AddAsciiOutputStream that ensures that there's an \r before every \n.
*
* @author <a href="mailto:[email protected]">Rana Bhattacharyya</a>
* @version $Id$
*/
public class AddAsciiOutputStream extends OutputStream {
private OutputStream _out;
private boolean _lastWasCarriageReturn = false;
/**
* Constructor.
*
* @param os
* <code>java.io.OutputStream</code> to be filtered.
*/
public AddAsciiOutputStream(OutputStream os) {
_out = os;
}
/**
* Write a single byte. ASCII characters are defined to be the lower half of
* an eight-bit code set (i.e., the most significant bit is zero). Change
* "\n" to "\r\n".
*/
public void write(int i) throws IOException {
if ((i == '\n') && !_lastWasCarriageReturn) {
_out.write('\r');
}
_lastWasCarriageReturn = false;
if (i == '\r') {
_lastWasCarriageReturn = true;
}
_out.write(i);
}
public void close() throws IOException {
_out.close();
}
public void flush() throws IOException {
_out.flush();
}
}
| 1,868
|
Java
|
.java
| 60
| 28.683333
| 77
| 0.715239
|
d-fens/drftpd
| 4
| 7
| 0
|
GPL-2.0
|
9/4/2024, 10:55:06 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
| 1,868
|
4,669,887
|
RecordApp.java
|
europeana_record-api/record-api-web/src/main/java/eu/europeana/api/record/RecordApp.java
|
package eu.europeana.api.record;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.jena.riot.RDFFormat;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import dev.morphia.query.filters.Filters;
import dev.morphia.query.MorphiaCursor;
import eu.europeana.api.format.RdfFormat;
import eu.europeana.api.record.profile.ViewProfileRegistry;
import eu.europeana.api.record.db.repository.RecordRepository;
import eu.europeana.api.record.io.FormatHandlerRegistry;
import eu.europeana.api.record.io.FormatHandlerRegistryV2;
import eu.europeana.api.record.io.json.v2.JsonV2Writer;
import eu.europeana.api.record.model.ProvidedCHO;
/**
* Main application. Allows deploying as a war and logs instance data when deployed in Cloud Foundry
*/
@SpringBootApplication(
scanBasePackages = {"eu.europeana.api.record"},
exclude = {
// Remove these exclusions to re-enable security
SecurityAutoConfiguration.class,
ManagementWebSecurityAutoConfiguration.class,
// DataSources are manually configured (for EM and batch DBs)
DataSourceAutoConfiguration.class
})
public class RecordApp extends SpringBootServletInitializer {
private static final Logger LOG = LogManager.getLogger(RecordApp.class);
/**
* Main entry point of this application
*
* @param args command-line arguments
* @throws IOException
*/
public static void main(String[] args) throws IOException {
LOG.info("No args provided to application. Starting web server");
ConfigurableApplicationContext ctx = SpringApplication.run(RecordApp.class, args);
/*
RecordRepository repo = ctx.getBean(RecordRepository.class);
ViewProfileRegistry vr = new ViewProfileRegistry();
try ( MorphiaCursor<ProvidedCHO> cursor = repo.findAll(
// Filters.eq("proxies.proxyIn.datasetName", "9200515_NL_Photographs_Serbia")
, vr.getProjection("media.full"))) {
FormatHandlerRegistry reg = ctx.getBean(FormatHandlerRegistry.class);
// reg.get(RdfFormat.JSONLD).write(cho, System.out);
File dir = new File("C:\\Work\\incoming\\Record v3\\formats");
RdfFormat[] formats = { RdfFormat.XML };
for ( RdfFormat format : formats ) {
File file = new File(dir, "records." + format.getExtension());
try ( FileOutputStream fos = new FileOutputStream(file) ) {
reg.get(format).write(cursor, Math.min(cursor.available(), 10), fos);
fos.flush();
}
}
//new JsonV2Writer().write(cho, System.out);
}
*/
}
}
| 3,551
|
Java
|
.java
| 68
| 42.808824
| 110
| 0.686869
|
europeana/record-api
| 2
| 0
| 0
|
EUPL-1.2
|
9/5/2024, 12:20:49 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 3,551
|
3,163,158
|
Description.java
|
learning-spring-boot_contest-votesapp/src/main/java/de/votesapp/commands/Description.java
|
package de.votesapp.commands;
import lombok.Value;
@Value
public class Description {
int priority;
String name;
String[] trigger;
String description;
public static class DescriptionBuilder {
private final String name;
private String[] trigger;
private String description;
private int priority;
private DescriptionBuilder(final String name) {
this.name = name;
}
public static DescriptionBuilder describe(final String name) {
return new DescriptionBuilder(name);
}
public DescriptionBuilder withTrigger(final String... trigger) {
this.trigger = trigger;
return this;
}
public DescriptionBuilder withDescription(final String description) {
this.description = description;
return this;
}
public DescriptionBuilder onPosition(final int priority) {
this.priority = priority;
return this;
}
public Description done() {
return new Description(priority, name, trigger, description);
}
}
}
| 955
|
Java
|
.java
| 36
| 23.472222
| 71
| 0.773626
|
learning-spring-boot/contest-votesapp
| 4
| 2
| 0
|
GPL-3.0
|
9/4/2024, 11:02:10 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
| 955
|
722,333
|
CompositeProjector.java
|
saalfeldlab_paintera/src/main/java/org/janelia/saalfeldlab/paintera/composition/CompositeProjector.java
|
package org.janelia.saalfeldlab.paintera.composition;
import bdv.viewer.Source;
import bdv.viewer.SourceAndConverter;
import bdv.viewer.render.AccumulateProjector;
import bdv.viewer.render.AccumulateProjectorFactory;
import bdv.viewer.render.VolatileProjector;
import net.imglib2.Cursor;
import net.imglib2.RandomAccessible;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
/**
* @author Stephan Saalfeld
*/
public class CompositeProjector<A extends Type<A>> extends AccumulateProjector<A, A> {
public static class CompositeProjectorFactory<A extends Type<A>> implements AccumulateProjectorFactory<A> {
final private Map<Source<?>, Composite<A, A>> composites;
/**
* Constructor with a map that associates sources and {@link Composite Composites}.
*
* @param composites
*/
public CompositeProjectorFactory(final Map<Source<?>, Composite<A, A>> composites) {
this.composites = composites;
}
@Override
public VolatileProjector createProjector(
List<VolatileProjector> sourceProjectors,
List<SourceAndConverter<?>> sources,
List<? extends RandomAccessible<? extends A>> sourceScreenImages,
RandomAccessibleInterval<A> targetScreenImage,
int numThreads,
ExecutorService executorService) {
final CompositeProjector<A> projector = new CompositeProjector<>(
sourceProjectors,
sourceScreenImages,
targetScreenImage
);
final ArrayList<Composite<A, A>> activeComposites = new ArrayList<>();
for (final var activeSource : sources) {
activeComposites.add(composites.get(activeSource.getSpimSource()));
}
projector.setComposites(activeComposites);
return projector;
}
}
final protected ArrayList<Composite<A, A>> composites = new ArrayList<>();
public CompositeProjector(
final List<VolatileProjector> sourceProjectors,
final List<? extends RandomAccessible<? extends A>> sources,
final RandomAccessibleInterval<A> target) {
super(sourceProjectors, sources, target);
}
public void setComposites(final List<Composite<A, A>> composites) {
this.composites.clear();
this.composites.addAll(composites);
}
@Override
protected void accumulate(final Cursor<? extends A>[] accesses, final A t) {
for (int i = 0; i < composites.size(); ++i) {
composites.get(i).compose(t, accesses[i].get());
}
}
}
| 2,465
|
Java
|
.java
| 67
| 33.61194
| 108
| 0.777217
|
saalfeldlab/paintera
| 99
| 17
| 78
|
GPL-2.0
|
9/4/2024, 7:08:37 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 2,465
|
4,763,298
|
Utf16TransformationStrategy.java
|
abramsm_DSI-Utilities/src/it/unimi/dsi/bits/Utf16TransformationStrategy.java
|
package it.unimi.dsi.bits;
/*
* DSI utilities
*
* Copyright (C) 2007-2012 Sebastiano Vigna
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
import java.io.Serializable;
/**
* @deprecated Use {@link TransformationStrategies#utf16()} and {@link TransformationStrategies#prefixFreeUtf16()}.
*/
@Deprecated
public class Utf16TransformationStrategy implements TransformationStrategy<CharSequence>, Serializable {
private static final long serialVersionUID = 1L;
/** Creates a prefix-free UTF16 transformation strategy. The
* strategy will map a string to its natural UTF16 bit sequence, and the resulting set of binary words will be made prefix free by adding
*
*/
public Utf16TransformationStrategy() {}
public long length( final CharSequence s ) {
return ( s.length() + 1 ) * (long)Character.SIZE;
}
private static class Utf16CharSequenceBitVector extends AbstractBitVector implements Serializable {
private static final long serialVersionUID = 1L;
private transient CharSequence s;
private transient long length;
private transient long actualEnd;
public Utf16CharSequenceBitVector( final CharSequence s ) {
this.s = s;
actualEnd = s.length() * (long)Character.SIZE;
length = actualEnd + Character.SIZE;
}
public boolean getBoolean( long index ) {
if ( index > length ) throw new IndexOutOfBoundsException();
if ( index >= actualEnd ) return false;
final int charIndex = (int)( index / Character.SIZE );
return ( s.charAt( charIndex ) & 0x8000 >>> index % Character.SIZE ) != 0;
}
public long getLong( final long from, final long to ) {
if ( from % Long.SIZE == 0 && to % Character.SIZE == 0 ) {
long l;
int pos = (int)( from / Character.SIZE );
if ( to == from + Long.SIZE ) l = ( ( to > actualEnd ? 0 : (long)s.charAt( pos + 3 ) ) << 48 | (long)s.charAt( pos + 2 ) << 32 | (long)s.charAt( pos + 1 ) << 16 | s.charAt( pos ) );
else {
l = 0;
final int residual = (int)( Math.min( actualEnd, to ) - from );
for( int i = residual / Character.SIZE; i-- != 0; )
l |= (long)s.charAt( pos + i ) << i * Character.SIZE;
}
l = ( l & 0x5555555555555555L ) << 1 | ( l >>> 1 ) & 0x5555555555555555L;
l = ( l & 0x3333333333333333L ) << 2 | ( l >>> 2 ) & 0x3333333333333333L;
l = ( l & 0x0f0f0f0f0f0f0f0fL ) << 4 | ( l >>> 4 ) & 0x0f0f0f0f0f0f0f0fL;
return ( l & 0x00ff00ff00ff00ffL ) << 8 | ( l >>> 8 ) & 0x00ff00ff00ff00ffL;
}
return super.getLong( from, to );
}
public long length() {
return length;
}
}
public BitVector toBitVector( final CharSequence s ) {
return new Utf16CharSequenceBitVector( s );
}
public long numBits() { return 0; }
public TransformationStrategy<CharSequence> copy() {
return new Utf16TransformationStrategy();
}
}
| 3,437
|
Java
|
.java
| 81
| 39.098765
| 185
| 0.695561
|
abramsm/DSI-Utilities
| 1
| 0
| 0
|
LGPL-3.0
|
9/5/2024, 12:30:20 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
| 3,437
|
4,439,823
|
AdventureService.java
|
exasky_dnd-parker-online/back/src/main/java/com/exasky/dnd/adventure/service/AdventureService.java
|
package com.exasky.dnd.adventure.service;
import com.exasky.dnd.adventure.model.Adventure;
import com.exasky.dnd.adventure.model.Campaign;
import com.exasky.dnd.adventure.model.Character;
import com.exasky.dnd.adventure.model.Initiative;
import com.exasky.dnd.adventure.model.card.CharacterItem;
import com.exasky.dnd.adventure.model.layer.item.LayerItem;
import com.exasky.dnd.adventure.model.template.CharacterTemplate;
import com.exasky.dnd.adventure.repository.*;
import com.exasky.dnd.adventure.rest.dto.card.ValidateCardDto;
import com.exasky.dnd.adventure.rest.dto.switch_equipment.ValidateSwitchDto;
import com.exasky.dnd.adventure.rest.dto.trade.ValidateTradeDto;
import com.exasky.dnd.common.Constant;
import com.exasky.dnd.common.exception.ValidationCheckException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.exasky.dnd.common.Utils.getCurrentUser;
@Service
public class AdventureService {
private final AdventureRepository repository;
private final CampaignRepository campaignRepository;
private final CharacterRepository characterRepository;
private final CharacterItemRepository characterItemRepository;
private final CharacterTemplateRepository characterTemplateRepository;
private final BridgeLayerItemService layerItemService;
private final BoardService boardService;
@Autowired
public AdventureService(AdventureRepository repository,
CampaignRepository campaignRepository,
CharacterRepository characterRepository,
CharacterItemRepository characterItemRepository,
CharacterTemplateRepository characterTemplateRepository,
BridgeLayerItemService layerItemService,
BoardService boardService) {
this.repository = repository;
this.campaignRepository = campaignRepository;
this.characterRepository = characterRepository;
this.characterItemRepository = characterItemRepository;
this.characterTemplateRepository = characterTemplateRepository;
this.layerItemService = layerItemService;
this.boardService = boardService;
}
public List<CharacterTemplate> getAllCharacterTemplate() {
return characterTemplateRepository.findAll();
}
public List<Adventure> getAdventures() {
return this.repository.findAll();
}
public Adventure getById(Long id) {
return this.repository.getOne(id);
}
@Transactional
public Adventure createOrUpdate(Adventure adventure, Campaign attachedCampaign) {
Adventure attachedAdventure = Objects.nonNull(adventure.getId())
? repository.getOne(adventure.getId())
: repository.save(new Adventure(attachedCampaign));
attachedAdventure.setName(adventure.getName());
attachedAdventure.setLevel(adventure.getLevel());
attachedAdventure.updateBoards(boardService.createOrUpdate(attachedAdventure, adventure.getBoards()));
return attachedAdventure;
}
public Adventure copy(Adventure toCopy, Campaign campaign) {
Adventure newAdventure = new Adventure(campaign);
newAdventure.setName(toCopy.getName());
newAdventure.setLevel(toCopy.getLevel());
newAdventure.setBoards(boardService.copy(toCopy.getBoards(), newAdventure));
newAdventure.setTraps(layerItemService.copy(toCopy.getTraps(), newAdventure));
newAdventure.setDoors(layerItemService.copy(toCopy.getDoors(), newAdventure));
newAdventure.setChests(layerItemService.copy(toCopy.getChests(), newAdventure));
newAdventure.setMonsters(layerItemService.copy(toCopy.getMonsters(), newAdventure));
newAdventure.setOtherItems(layerItemService.copy(toCopy.getOtherItems(), newAdventure));
return newAdventure;
}
public void delete(Adventure attachedAdventure) {
repository.delete(attachedAdventure);
}
public List<Campaign> getCampaignsForCurrentUser() {
return campaignRepository.findAllForUser(getCurrentUser().getId());
}
public Character updateCharacter(Long adventureId, Long characterId, Character toBo) {
Campaign campaign = campaignRepository.getByAdventureId(adventureId);
if (Objects.isNull(campaign)) {
ValidationCheckException.throwError(HttpStatus.NOT_FOUND, Constant.Errors.CAMPAIGN.NOT_FOUND);
}
Optional<Character> first = campaign.getCharacters().stream().filter(character -> character.getId().equals(characterId)).findFirst();
if (!first.isPresent()) {
ValidationCheckException.throwError(HttpStatus.NOT_FOUND, Constant.Errors.CHARACTER.NOT_FOUND);
}
Character toUpdate = first.get();
toUpdate.setMaxHp(toBo.getMaxHp());
toUpdate.setHp(toBo.getHp());
toUpdate.setMaxMp(toBo.getMaxMp());
toUpdate.setMp(toBo.getMp());
toUpdate.updateEquipments(toBo.getEquipments().stream()
.map(characterItem -> characterItemRepository.getOne(characterItem.getId()))
.collect(Collectors.toList()));
toUpdate.updateBackPack(toBo.getBackPack().stream()
.map(characterItem -> characterItemRepository.getOne(characterItem.getId()))
.collect(Collectors.toList()));
return characterRepository.save(toUpdate);
}
@Transactional
public <T extends LayerItem> T addLayerItem(Long adventureId, T toAdd) {
Adventure attachedAdventure = repository.getOne(adventureId);
T newLayerItem = layerItemService.createOrUpdate(toAdd, attachedAdventure);
List<T> elementListForLayerItem = getElementListForLayerItem(attachedAdventure, toAdd);
elementListForLayerItem.add(newLayerItem);
return newLayerItem;
}
@Transactional
public <T extends LayerItem> T updateLayerItem(Long adventureId, T toAdd) {
Adventure attachedAdventure = repository.getOne(adventureId);
T attachedLayerItem = this.layerItemService.createOrUpdate(toAdd, attachedAdventure);
List<T> elementListForLayerItem = getElementListForLayerItem(attachedAdventure, toAdd);
T prevItem = elementListForLayerItem.stream().filter(item -> item.getId().equals(attachedLayerItem.getId()))
.findFirst()
.orElse(null);
if (Objects.isNull(prevItem)) {
ValidationCheckException.throwError(Constant.Errors.ADVENTURE.LAYER_ITEM_NOT_FOUND);
}
int idx = elementListForLayerItem.indexOf(prevItem);
elementListForLayerItem.set(idx, attachedLayerItem);
return attachedLayerItem;
}
@Transactional
public <T extends LayerItem> void deleteLayerItem(Long adventureId, T toDelete) {
Adventure attachedAdventure = repository.getOne(adventureId);
T attachedLayerItem = layerItemService.getOne(toDelete);
List<T> elementListForLayerItem = getElementListForLayerItem(attachedAdventure, attachedLayerItem);
elementListForLayerItem.remove(attachedLayerItem);
}
@SuppressWarnings("unchecked")
private <T extends LayerItem> List<T> getElementListForLayerItem(Adventure adv, T layerItem) {
switch (layerItem.getLayerElement().getType()) {
case TRAP:
return (List<T>) adv.getTraps();
case DOOR:
return (List<T>) adv.getDoors();
case CHEST:
return (List<T>) adv.getChests();
case MONSTER:
return (List<T>) adv.getMonsters();
case CHARACTER:
return (List<T>) adv.getCharacters();
default:
return (List<T>) adv.getOtherItems();
}
}
public CharacterItem getNextCardToDraw(Long adventureId) {
Campaign campaign = this.campaignRepository.getByAdventureId(adventureId);
if (Objects.isNull(campaign)) {
ValidationCheckException.throwError(HttpStatus.NOT_FOUND, Constant.Errors.CAMPAIGN.NOT_FOUND);
}
//noinspection OptionalGetWithoutIsPresent
Short adventureLevel = campaign.getAdventures()
.stream()
.filter(a -> a.getId().equals(adventureId)).findFirst().get().getLevel();
List<Long> itemOnCharacterIds = campaign.getCharacters().stream()
.flatMap(c -> Stream.of(c.getEquipments(), c.getBackPack()).flatMap(Collection::stream))
.map(CharacterItem::getId)
.collect(Collectors.toList());
List<Long> drawnCardIds = campaign.getDrawnItems().stream()
.map(CharacterItem::getId)
.collect(Collectors.toList());
Set<Long> usedItemIds = Stream.of(itemOnCharacterIds, drawnCardIds)
.flatMap(Collection::stream)
.collect(Collectors.toSet());
List<CharacterItem> availableCards = usedItemIds.isEmpty()
? characterItemRepository.findAllByLevelLessThanEqual(adventureLevel)
: characterItemRepository.findAllByIdNotInAndLevelLessThanEqual(usedItemIds, adventureLevel);
// Clear the discard
if (availableCards.isEmpty()) {
campaign.getDrawnItems().clear();
campaignRepository.save(campaign);
availableCards = itemOnCharacterIds.isEmpty()
? characterItemRepository.findAllByLevelLessThanEqual(adventureLevel)
: characterItemRepository.findAllByIdNotInAndLevelLessThanEqual(usedItemIds, adventureLevel);
}
return availableCards.get(new Random().nextInt(availableCards.size()));
}
/**
* Does not add the card to the drawn items because the card should be a unique item (like star level items)
*/
@PreAuthorize("hasRole('ROLE_GM')")
public CharacterItem drawSpecificCard(Long characterItemId) {
Optional<CharacterItem> byId = characterItemRepository.findById(characterItemId);
if (!byId.isPresent()) {
ValidationCheckException.throwError(HttpStatus.NOT_FOUND, Constant.Errors.CHARACTER_ITEM.NOT_FOUND);
}
return byId.get();
}
@PreAuthorize("hasRole('ROLE_GM')")
public Character validateDrawnCard(Long adventureId, ValidateCardDto dto) {
Campaign campaign = campaignRepository.getByAdventureId(adventureId);
if (Objects.isNull(campaign)) {
ValidationCheckException.throwError(HttpStatus.NOT_FOUND, Constant.Errors.CAMPAIGN.NOT_FOUND);
}
Optional<CharacterItem> optCharacterItem = characterItemRepository.findById(dto.getCharacterItemId());
if (!optCharacterItem.isPresent()) {
ValidationCheckException.throwError(HttpStatus.NOT_FOUND, Constant.Errors.CHARACTER_ITEM.NOT_FOUND);
}
CharacterItem drawnCard = optCharacterItem.get();
if (Objects.isNull(dto.getEquipToEquipment())) {
campaign.getDrawnItems().add(drawnCard);
campaignRepository.save(campaign);
} else {
Character character = characterRepository.getOne(dto.getCharacterId());
(dto.getEquipToEquipment() ? character.getEquipments() : character.getBackPack()).add(drawnCard);
return characterRepository.save(character);
}
return null;
}
@PreAuthorize("hasRole('ROLE_GM')")
public Initiative nextTurn(Long adventureId) {
Adventure adventure = getById(adventureId);
if (Objects.isNull(adventure)) {
ValidationCheckException.throwError(HttpStatus.NOT_FOUND, Constant.Errors.ADVENTURE.NOT_FOUND);
}
List<Initiative> characterTurns = adventure.getCampaign().getCharacterTurns();
short nextNumber = (short) (adventure.getCurrentInitiative().getNumber() + 1);
if (nextNumber > characterTurns.size()) {
nextNumber = 1;
}
for (Initiative init : characterTurns) {
if (init.getNumber() == nextNumber) {
adventure.setCurrentInitiative(init);
break;
}
}
repository.save(adventure);
return adventure.getCurrentInitiative();
}
@PreAuthorize("hasRole('ROLE_GM')")
@Transactional
public List<Character> trade(ValidateTradeDto trade) {
Character from = this.characterRepository.getOne(trade.getFromCharacterId());
Character to = this.characterRepository.getOne(trade.getToCharacterId());
simpleTrade(from, to,
trade.getFromCharacterEquipment(), trade.getFromCharacterIsEquipment(),
trade.getToCharacterIsEquipment());
simpleTrade(to, from,
trade.getToCharacterEquipment(), trade.getToCharacterIsEquipment(),
trade.getFromCharacterIsEquipment());
return Arrays.asList(from, to);
}
private void simpleTrade(Character from, Character to,
Long fromCharacterEquipmentId, Boolean fromCharacterIsEquipment,
Boolean toCharacterIsEquipment) {
if (Objects.nonNull(fromCharacterEquipmentId)) {
List<CharacterItem> items = fromCharacterIsEquipment ? from.getEquipments() : from.getBackPack();
Optional<CharacterItem> optFromItem = items.stream().filter(item -> item.getId().equals(fromCharacterEquipmentId)).findFirst();
if (optFromItem.isPresent()) {
CharacterItem fromItem = optFromItem.get();
items.remove(fromItem);
(toCharacterIsEquipment != null && toCharacterIsEquipment ? to.getEquipments() : to.getBackPack()).add(fromItem);
}
}
}
@PreAuthorize("hasRole('ROLE_GM')")
@Transactional
public Character switchEquipment(ValidateSwitchDto switchDto) {
Character toUpdate = characterRepository.getOne(switchDto.getCharacterId());
if (Objects.nonNull(switchDto.getCharacterEquippedItemId())) {
Optional<CharacterItem> optEq = toUpdate.getEquipments().stream().
filter(eq -> eq.getId().equals(switchDto.getCharacterEquippedItemId())).findFirst();
if (optEq.isPresent()) {
CharacterItem eq = optEq.get();
toUpdate.getEquipments().remove(eq);
toUpdate.getBackPack().add(eq);
}
}
if (Objects.nonNull(switchDto.getCharacterBackpackItemId())) {
Optional<CharacterItem> optBp = toUpdate.getBackPack().stream()
.filter(eq -> eq.getId().equals(switchDto.getCharacterBackpackItemId())).findFirst();
if (optBp.isPresent()) {
CharacterItem bp = optBp.get();
toUpdate.getBackPack().remove(bp);
toUpdate.getEquipments().add(bp);
}
}
return toUpdate;
}
}
| 15,231
|
Java
|
.java
| 289
| 42.719723
| 141
| 0.694418
|
exasky/dnd-parker-online
| 2
| 0
| 22
|
LGPL-3.0
|
9/5/2024, 12:13:19 AM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
| 15,231
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 116