repo_name
stringlengths
7
70
file_path
stringlengths
9
215
context
list
import_statement
stringlengths
47
10.3k
token_num
int64
643
100k
cropped_code
stringlengths
62
180k
all_code
stringlengths
62
224k
next_line
stringlengths
9
1.07k
gold_snippet_index
int64
0
117
created_at
stringlengths
25
25
level
stringclasses
9 values
codingmiao/hppt
cs/src/main/java/org/wowtools/hppt/cs/service/ServerSessionService.java
[ { "identifier": "ProtoMessage", "path": "common/src/main/java/org/wowtools/hppt/common/protobuf/ProtoMessage.java", "snippet": "public final class ProtoMessage {\n private ProtoMessage() {}\n public static void registerAllExtensions(\n com.google.protobuf.ExtensionRegistryLite registry) {\n }\n\...
import com.google.protobuf.ByteString; import lombok.extern.slf4j.Slf4j; import org.wowtools.hppt.common.protobuf.ProtoMessage; import org.wowtools.hppt.common.util.Constant; import java.util.LinkedList; import java.util.List; import java.util.Map;
14,139
package org.wowtools.hppt.cs.service; /** * @author liuyu * @date 2023/12/20 */ @Slf4j public class ServerSessionService {
package org.wowtools.hppt.cs.service; /** * @author liuyu * @date 2023/12/20 */ @Slf4j public class ServerSessionService {
public static ProtoMessage.MessagePb talk(String clientId, ProtoMessage.MessagePb inputMessage) {
0
2023-12-22 14:14:27+00:00
16k
3arthqu4ke/phobot
src/main/java/me/earth/phobot/modules/misc/Speedmine.java
[ { "identifier": "Phobot", "path": "src/main/java/me/earth/phobot/Phobot.java", "snippet": "@Getter\n@RequiredArgsConstructor\n@SuppressWarnings(\"ClassCanBeRecord\")\npublic class Phobot {\n public static final String NAME = \"Phobot\";\n\n private final PingBypass pingBypass;\n private final E...
import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.earth.phobot.Phobot; import me.earth.phobot.event.*; import me.earth.phobot.modules.PhobotModule; import me.earth.phobot.modules.client.anticheat.StrictDirection; import me.earth.phobot.services.PlayerPosition; import me.earth.phobot.services.inventory.InventoryContext; import me.earth.phobot.util.ResetUtil; import me.earth.phobot.util.math.MathUtil; import me.earth.phobot.util.math.PositionUtil; import me.earth.phobot.util.math.RaytraceUtil; import me.earth.phobot.util.math.RotationUtil; import me.earth.phobot.util.render.Renderer; import me.earth.phobot.util.time.StopWatch; import me.earth.phobot.util.world.BlockStateLevel; import me.earth.phobot.util.world.PredictionUtil; import me.earth.pingbypass.PingBypassApi; import me.earth.pingbypass.api.event.event.CancellableEvent; import me.earth.pingbypass.api.event.listeners.generic.Listener; import me.earth.pingbypass.api.module.impl.Categories; import me.earth.pingbypass.api.setting.Setting; import me.earth.pingbypass.api.setting.impl.Complexities; import me.earth.pingbypass.commons.event.SafeListener; import me.earth.pingbypass.commons.event.network.PacketEvent; import net.minecraft.ChatFormatting; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.MultiPlayerGameMode; import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket; import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; import net.minecraft.network.protocol.game.ServerboundSetCarriedItemPacket; import net.minecraft.tags.FluidTags; import net.minecraft.world.InteractionHand; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import org.apache.commons.lang3.mutable.MutableObject; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; import java.util.Objects;
13,758
if (player.getEyePosition().distanceToSqr(currentPos.getX() + 0.5, currentPos.getY() + 0.5, currentPos.getZ() + 0.5) > phobot.getAntiCheat().getMiningRangeSq()) { player.connection.send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, currentPos, currentDirection)); reset(); } else { renderTicks++; update(level, player, gameMode); } } } }); listen(new SafeListener<PostMotionPlayerUpdateEvent>(mc) { @Override public void onEvent(PostMotionPlayerUpdateEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { if (player.isCreative()) { reset(); return; } if (currentPos != null) { Direction currentDirection = getDirection(); if (currentDirection == null) { player.connection.send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, currentPos, Direction.DOWN)); reset(); return; } update(level, player, gameMode); } } }); listen(new Listener<RenderEvent>() { @Override public void onEvent(RenderEvent event) { if (currentPos != null && !currentState.isAir()) { for (AABB bb : renderBBs) { event.getAabb().set(bb); event.getAabb().move(currentPos.getX(), currentPos.getY(), currentPos.getZ()); float damage = MathUtil.clamp(renderDamageDelta * renderTicks, 0.0f, 1.0f); // TODO: proper offsets event.getAabb().grow(-0.5 + MathUtil.clamp((renderDamageDelta * renderTicks / 2.0) + renderDamageDelta * event.getTickDelta() - renderDamageDelta, 0.0, 0.5)); event.setBoxColor(1.0f - damage, damage, 0.0f, 1.0f, 0.4f); Renderer.renderBoxWithOutlineAndSides(event, 1.5f, true); return; // TODO: do this properly and fill out the entire voxel shape bbs, LightSectionDebugRenderer has a bit of an example } } } }); listen(new SafeListener<ContinueDestroyBlockEvent>(mc) { @Override public void onEvent(ContinueDestroyBlockEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { if (player.isCreative()) { reset(); return; } event.setCancelled(true); } }); listen(new SafeListener<StopDestroyBlockEvent>(mc) { @Override public void onEvent(StopDestroyBlockEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { if (player.isCreative()) { reset(); return; } event.setCancelled(true); } }); listen(new SafeListener<PacketEvent.PostReceive<ClientboundBlockUpdatePacket>>(mc) { @Override public void onEvent(PacketEvent.PostReceive<ClientboundBlockUpdatePacket> event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { mc.submit(() -> { if (!player.isCreative() && Objects.equals(event.getPacket().getPos(), currentPos)) { if (expectingAir && event.getPacket().getBlockState().isAir()) { expectingAir = false; } update(level, player, gameMode); } }); } }); listen(new SafeListener<PacketEvent.PostSend<ServerboundSetCarriedItemPacket>>(mc) { @Override public void onEvent(PacketEvent.PostSend<ServerboundSetCarriedItemPacket> event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { mc.submit(() -> { if (!player.isCreative() && currentPos != null) { Direction currentDirection = getDirection(); if (currentDirection == null) { reset(); return; } player.connection.send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, currentPos, currentDirection)); player.connection.send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, currentPos, currentDirection)); timer.reset(); renderTicks = 0; } }); } }); ResetUtil.onRespawnOrWorldChange(this, mc, this::reset); } private void update(ClientLevel level, LocalPlayer player, MultiPlayerGameMode gameMode) { Direction currentDirection = getDirection(); if (currentDirection == null) { reset(); return; } if (expectingAir && expectingAirTimer.passed(125L) && currentPos != null) {
package me.earth.phobot.modules.misc; // TODO: test what happens when target is out of range more, instead of just aborting // TODO: make the rendering a bit smarter @Slf4j public class Speedmine extends PhobotModule { private final Setting<Boolean> fast = bool("Fast", true, "Allows you mine blocks quicker if you place them on the same position."); private final Setting<Boolean> silentSwitch = bool("Switch", true, "Silently switches to your tool to mine."); private final Setting<Boolean> noGlitchBlocks = bool("NoGlitchBlocks", false, "If off sets the block to air on the clientside immediately."); private final Setting<Boolean> swing = bool("Swing", false, "Swings every tick."); private final Setting<Boolean> addTick = boolBuilder("AddTick", false).withDescription("Waits another tick before breaking.").withComplexity(Complexities.DEV).register(this); private final StopWatch.ForSingleThread expectingAirTimer = new StopWatch.ForSingleThread(); private final StopWatch.ForSingleThread timer = new StopWatch.ForSingleThread(); @Getter private BlockPos currentPos = null; private BlockState currentState = Blocks.AIR.defaultBlockState(); private List<AABB> renderBBs = Collections.emptyList(); private float renderDamageDelta = 0.0f; private int renderTicks = 0; private boolean sendAbortNextTick = true; private boolean expectingAir; public Speedmine(Phobot phobot) { super(phobot, "Speedmine", Categories.MISC, "Better mining."); timer.reset(); listen(new SafeListener<StartDestroyBlockEvent>(mc) { @Override public void onEvent(StartDestroyBlockEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { if (player.isCreative() || phobot.getAntiCheat().isAboveBuildHeight(event.getPos().getY())) { reset(); return; } event.setCancelled(true); startDestroy(event.getPos(), event.getDirection(), level, player); } }); listen(new SafeListener<PreMotionPlayerUpdateEvent>(mc, -1000) { @Override public void onEvent(PreMotionPlayerUpdateEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { if (player.isCreative()) { reset(); return; } if (currentPos != null) { Direction currentDirection = getDirection(); if (currentDirection == null) { player.connection.send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, currentPos, Direction.DOWN)); reset(); return; } // PreMotionPlayerUpdateEvent is before we sent our position to the server, so we can still abort if (player.getEyePosition().distanceToSqr(currentPos.getX() + 0.5, currentPos.getY() + 0.5, currentPos.getZ() + 0.5) > phobot.getAntiCheat().getMiningRangeSq()) { player.connection.send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, currentPos, currentDirection)); reset(); } else { renderTicks++; update(level, player, gameMode); } } } }); listen(new SafeListener<PostMotionPlayerUpdateEvent>(mc) { @Override public void onEvent(PostMotionPlayerUpdateEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { if (player.isCreative()) { reset(); return; } if (currentPos != null) { Direction currentDirection = getDirection(); if (currentDirection == null) { player.connection.send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, currentPos, Direction.DOWN)); reset(); return; } update(level, player, gameMode); } } }); listen(new Listener<RenderEvent>() { @Override public void onEvent(RenderEvent event) { if (currentPos != null && !currentState.isAir()) { for (AABB bb : renderBBs) { event.getAabb().set(bb); event.getAabb().move(currentPos.getX(), currentPos.getY(), currentPos.getZ()); float damage = MathUtil.clamp(renderDamageDelta * renderTicks, 0.0f, 1.0f); // TODO: proper offsets event.getAabb().grow(-0.5 + MathUtil.clamp((renderDamageDelta * renderTicks / 2.0) + renderDamageDelta * event.getTickDelta() - renderDamageDelta, 0.0, 0.5)); event.setBoxColor(1.0f - damage, damage, 0.0f, 1.0f, 0.4f); Renderer.renderBoxWithOutlineAndSides(event, 1.5f, true); return; // TODO: do this properly and fill out the entire voxel shape bbs, LightSectionDebugRenderer has a bit of an example } } } }); listen(new SafeListener<ContinueDestroyBlockEvent>(mc) { @Override public void onEvent(ContinueDestroyBlockEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { if (player.isCreative()) { reset(); return; } event.setCancelled(true); } }); listen(new SafeListener<StopDestroyBlockEvent>(mc) { @Override public void onEvent(StopDestroyBlockEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { if (player.isCreative()) { reset(); return; } event.setCancelled(true); } }); listen(new SafeListener<PacketEvent.PostReceive<ClientboundBlockUpdatePacket>>(mc) { @Override public void onEvent(PacketEvent.PostReceive<ClientboundBlockUpdatePacket> event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { mc.submit(() -> { if (!player.isCreative() && Objects.equals(event.getPacket().getPos(), currentPos)) { if (expectingAir && event.getPacket().getBlockState().isAir()) { expectingAir = false; } update(level, player, gameMode); } }); } }); listen(new SafeListener<PacketEvent.PostSend<ServerboundSetCarriedItemPacket>>(mc) { @Override public void onEvent(PacketEvent.PostSend<ServerboundSetCarriedItemPacket> event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { mc.submit(() -> { if (!player.isCreative() && currentPos != null) { Direction currentDirection = getDirection(); if (currentDirection == null) { reset(); return; } player.connection.send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, currentPos, currentDirection)); player.connection.send(new ServerboundPlayerActionPacket(ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK, currentPos, currentDirection)); timer.reset(); renderTicks = 0; } }); } }); ResetUtil.onRespawnOrWorldChange(this, mc, this::reset); } private void update(ClientLevel level, LocalPlayer player, MultiPlayerGameMode gameMode) { Direction currentDirection = getDirection(); if (currentDirection == null) { reset(); return; } if (expectingAir && expectingAirTimer.passed(125L) && currentPos != null) {
getPingBypass().getChat().send(Component.literal("Failed to mine " + PositionUtil.toSimpleString(currentPos) + " re-mining.").withStyle(ChatFormatting.RED), "Speedmine");
7
2023-12-22 14:32:16+00:00
16k
ArmanKhanDev/FakepixelDungeonHelper
src/main/java/io/github/quantizr/core/Waypoints.java
[ { "identifier": "DungeonRooms", "path": "build/sources/main/java/io/github/quantizr/DungeonRooms.java", "snippet": "@Mod(modid = DungeonRooms.MODID, version = DungeonRooms.VERSION)\npublic class DungeonRooms\n{\n public static final String MODID = \"FDH\";\n public static final String VERSION = \"...
import com.google.gson.JsonArray; import com.google.gson.JsonObject; import io.github.quantizr.DungeonRooms; import io.github.quantizr.events.PacketEvent; import io.github.quantizr.utils.Utils; import io.github.quantizr.utils.WaypointUtils; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; import net.minecraft.network.play.server.S0DPacketCollectItem; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.StringUtils; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import java.awt.*; import java.util.*; import java.util.List;
12,787
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM 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. DRM 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 DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.core; public class Waypoints { public static boolean enabled = true; public static boolean showEntrance = true; public static boolean showSuperboom = true; public static boolean showSecrets = true; public static boolean showFairySouls = true; public static boolean sneakToDisable = true; public static boolean disableWhenAllFound = true; public static boolean allFound = false; public static boolean showWaypointText = true; public static boolean showBoundingBox = true; public static boolean showBeacon = true; public static int secretNum = 0; public static int completedSecrets = 0; public static Map<String, List<Boolean>> allSecretsMap = new HashMap<>(); public static List<Boolean> secretsList = new ArrayList<>(Arrays.asList(new Boolean[9])); static long lastSneakTime = 0; @SubscribeEvent public void onWorldRender(RenderWorldLastEvent event) { if (!enabled) return; String roomName = AutoRoom.lastRoomName; if (AutoRoom.lastRoomJson != null && roomName != null && secretsList != null) { secretNum = AutoRoom.lastRoomJson.get("secrets").getAsInt();
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM 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. DRM 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 DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.core; public class Waypoints { public static boolean enabled = true; public static boolean showEntrance = true; public static boolean showSuperboom = true; public static boolean showSecrets = true; public static boolean showFairySouls = true; public static boolean sneakToDisable = true; public static boolean disableWhenAllFound = true; public static boolean allFound = false; public static boolean showWaypointText = true; public static boolean showBoundingBox = true; public static boolean showBeacon = true; public static int secretNum = 0; public static int completedSecrets = 0; public static Map<String, List<Boolean>> allSecretsMap = new HashMap<>(); public static List<Boolean> secretsList = new ArrayList<>(Arrays.asList(new Boolean[9])); static long lastSneakTime = 0; @SubscribeEvent public void onWorldRender(RenderWorldLastEvent event) { if (!enabled) return; String roomName = AutoRoom.lastRoomName; if (AutoRoom.lastRoomJson != null && roomName != null && secretsList != null) { secretNum = AutoRoom.lastRoomJson.get("secrets").getAsInt();
if (DungeonRooms.waypointsJson.get(roomName) != null) {
0
2023-12-22 04:44:39+00:00
16k
lonelytransistor/LauncherAndroidTV
app/src/main/java/net/lonelytransistor/launcher/MovieCard.java
[ { "identifier": "AllRepos", "path": "app/src/main/java/net/lonelytransistor/launcher/repos/AllRepos.java", "snippet": "public class AllRepos {\n public static Drawable newIcon;\n public static Drawable pausedIcon;\n public static Drawable tickIcon;\n public static Drawable nextIcon;\n pub...
import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.Log; import androidx.annotation.NonNull; import net.lonelytransistor.launcher.repos.AllRepos; import net.lonelytransistor.launcher.repos.ApkRepo; import net.lonelytransistor.launcher.repos.JustWatch; import net.lonelytransistor.launcher.repos.MovieTitle; import java.util.ArrayList; import java.util.List; import java.util.Objects;
13,090
package net.lonelytransistor.launcher; public class MovieCard extends Card { public String title; public String desc; public Drawable statusIcon; public Uri mainImage; public int progressBar; public int score; public int popularity; public int popularityDelta; public MovieCard(MovieCard c) { title = c.title; desc = c.desc; statusIcon = c.statusIcon; mainImage = c.mainImage; progressBar = c.progressBar; score = c.score; popularity = c.popularity; popularityDelta = c.popularityDelta; clickIntent = c.clickIntent; } Intent clickIntent; public MovieCard(MovieTitle m) { title = m.title; if (m.originalTitle != null && !m.originalTitle.isEmpty() &&
package net.lonelytransistor.launcher; public class MovieCard extends Card { public String title; public String desc; public Drawable statusIcon; public Uri mainImage; public int progressBar; public int score; public int popularity; public int popularityDelta; public MovieCard(MovieCard c) { title = c.title; desc = c.desc; statusIcon = c.statusIcon; mainImage = c.mainImage; progressBar = c.progressBar; score = c.score; popularity = c.popularity; popularityDelta = c.popularityDelta; clickIntent = c.clickIntent; } Intent clickIntent; public MovieCard(MovieTitle m) { title = m.title; if (m.originalTitle != null && !m.originalTitle.isEmpty() &&
JustWatch.jaccardSimilarity(title, m.originalTitle) < 90) {
2
2023-12-28 18:24:12+00:00
16k
RoderickQiu/SUSTech_CSE_Projects
CS109_2022_Fall/Chess/controller/GameController.java
[ { "identifier": "ChessBackup", "path": "CS109_2022_Fall/Chess/model/ChessBackup.java", "snippet": "public class ChessBackup {\n String nowColor;\n String[][] type, color;\n boolean[][] reversal;\n String records = \"--\", redEatenList, blackEatenList;\n int redScore, blackScore;\n\n pu...
import Chess.chessComponent.*; import Chess.model.ChessBackup; import Chess.model.ChessboardPoint; import Chess.utils.FileUtils; import Chess.view.Chessboard; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import javax.swing.*; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import static Chess.utils.FileUtils.getCorrectSlash; import static Chess.view.Chessboard.COL_SIZE; import static Chess.view.Chessboard.ROW_SIZE; import static Chess.view.StartFrame.checkRecords;
12,526
package Chess.controller; /** * 这个类主要完成由窗体上组件触发的动作。 * 例如点击button等 * ChessGameFrame中组件调用本类的对象,在本类中的方法里完成逻辑运算,将运算的结果传递至chessboard中绘制 */ public class GameController { private Chessboard chessboard; public Gson gson = new Gson(); public GameController(Chessboard chessboard) { this.chessboard = chessboard; } public List<String> loadGameFromFile(String path) { try { List<String> chessData = Files.readAllLines(Path.of(path)); //chessboard.loadGame(chessData); return chessData; } catch (IOException e) { e.printStackTrace(); } return null; } public void toGSon() { ChessBackup backup = chessboard.backupGame(); String[][] reversalString = new String[ROW_SIZE][COL_SIZE]; for (int i = 0; i < ROW_SIZE; i++) { for (int j = 0; j < COL_SIZE; j++) { reversalString[i][j] = String.valueOf(backup.getReversal()[i][j]); } } Map<String, JsonElement> data = new HashMap<>(); data.put("nowColor", gson.toJsonTree(backup.getNowColor())); data.put("type", gson.toJsonTree(backup.getType())); data.put("color", gson.toJsonTree(backup.getColor())); data.put("reversal", gson.toJsonTree(reversalString)); data.put("records", gson.toJsonTree(backup.getRecords())); data.put("redEatenList", gson.toJsonTree(backup.getRedEatenList())); data.put("blackEatenList", gson.toJsonTree(backup.getBlackEatenList())); data.put("redScore", gson.toJsonTree(backup.getRedScore())); data.put("blackScore", gson.toJsonTree(backup.getBlackScore())); try {
package Chess.controller; /** * 这个类主要完成由窗体上组件触发的动作。 * 例如点击button等 * ChessGameFrame中组件调用本类的对象,在本类中的方法里完成逻辑运算,将运算的结果传递至chessboard中绘制 */ public class GameController { private Chessboard chessboard; public Gson gson = new Gson(); public GameController(Chessboard chessboard) { this.chessboard = chessboard; } public List<String> loadGameFromFile(String path) { try { List<String> chessData = Files.readAllLines(Path.of(path)); //chessboard.loadGame(chessData); return chessData; } catch (IOException e) { e.printStackTrace(); } return null; } public void toGSon() { ChessBackup backup = chessboard.backupGame(); String[][] reversalString = new String[ROW_SIZE][COL_SIZE]; for (int i = 0; i < ROW_SIZE; i++) { for (int j = 0; j < COL_SIZE; j++) { reversalString[i][j] = String.valueOf(backup.getReversal()[i][j]); } } Map<String, JsonElement> data = new HashMap<>(); data.put("nowColor", gson.toJsonTree(backup.getNowColor())); data.put("type", gson.toJsonTree(backup.getType())); data.put("color", gson.toJsonTree(backup.getColor())); data.put("reversal", gson.toJsonTree(reversalString)); data.put("records", gson.toJsonTree(backup.getRecords())); data.put("redEatenList", gson.toJsonTree(backup.getRedEatenList())); data.put("blackEatenList", gson.toJsonTree(backup.getBlackEatenList())); data.put("redScore", gson.toJsonTree(backup.getRedScore())); data.put("blackScore", gson.toJsonTree(backup.getBlackScore())); try {
FileUtils.saveDataToFile("save", Base64.getEncoder().encodeToString(gson.toJson(data).getBytes(StandardCharsets.UTF_8)), "txt");
2
2023-12-31 05:50:13+00:00
16k
psobiech/opengr8on
client/src/main/java/pl/psobiech/opengr8on/client/Main.java
[ { "identifier": "CLUDevice", "path": "lib/src/main/java/pl/psobiech/opengr8on/client/device/CLUDevice.java", "snippet": "public class CLUDevice {\n private final String name;\n\n private final Long serialNumber;\n\n private final String macAddress;\n\n private Inet4Address address;\n\n pr...
import java.io.IOException; import java.net.Inet4Address; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.util.Map; import java.util.Optional; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.psobiech.opengr8on.client.device.CLUDevice; import pl.psobiech.opengr8on.client.device.CLUDeviceConfig; import pl.psobiech.opengr8on.client.device.CipherTypeEnum; import pl.psobiech.opengr8on.exceptions.UnexpectedException; import pl.psobiech.opengr8on.util.FileUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil.NetworkInterfaceDto; import pl.psobiech.opengr8on.util.ObjectMapperFactory; import pl.psobiech.opengr8on.util.RandomUtil; import pl.psobiech.opengr8on.util.Util; import pl.psobiech.opengr8on.xml.interfaces.CLU; import pl.psobiech.opengr8on.xml.interfaces.InterfaceRegistry; import pl.psobiech.opengr8on.xml.omp.OmpReader;
13,255
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * 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 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 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 <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client; public class Main { private static final Duration DEFAULT_LONG_TIMEOUT = Duration.ofMillis(30_000); private static final int TIMEOUT = 4_000; private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); private static final Map<Long, byte[]> PRIVATE_KEYS = Map.of( 0x0L, "00000000".getBytes() ); private static final Inet4Address MIN_IP = IPv4AddressUtil.parseIPv4("10.72.144.1"); private Main() { // NOP } public static void main(String[] args) throws Exception { final CommandLine commandLine = new DefaultParser().parse(CLIParameters.OPTIONS, args); if (commandLine.hasOption(CLIParameters.HELP_OPTION)) { new HelpFormatter() .printHelp("java -jar client.jar", CLIParameters.OPTIONS); System.exit(0); } // final NetworkInterfaceDto networkInterface = CLIParameters.getNetworkInterface(commandLine); LOGGER.debug("Using network interface: {}", networkInterface); if (commandLine.hasOption(CLIParameters.DISCOVER_OPTION)) { final InterfaceRegistry interfaceRegistry = CLIParameters.getInterfaceRegistry(commandLine); final CipherKey projectCipherKey = CLIParameters.getProjectCipherKey(commandLine) .orElseGet(() -> {
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * 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 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 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 <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client; public class Main { private static final Duration DEFAULT_LONG_TIMEOUT = Duration.ofMillis(30_000); private static final int TIMEOUT = 4_000; private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); private static final Map<Long, byte[]> PRIVATE_KEYS = Map.of( 0x0L, "00000000".getBytes() ); private static final Inet4Address MIN_IP = IPv4AddressUtil.parseIPv4("10.72.144.1"); private Main() { // NOP } public static void main(String[] args) throws Exception { final CommandLine commandLine = new DefaultParser().parse(CLIParameters.OPTIONS, args); if (commandLine.hasOption(CLIParameters.HELP_OPTION)) { new HelpFormatter() .printHelp("java -jar client.jar", CLIParameters.OPTIONS); System.exit(0); } // final NetworkInterfaceDto networkInterface = CLIParameters.getNetworkInterface(commandLine); LOGGER.debug("Using network interface: {}", networkInterface); if (commandLine.hasOption(CLIParameters.DISCOVER_OPTION)) { final InterfaceRegistry interfaceRegistry = CLIParameters.getInterfaceRegistry(commandLine); final CipherKey projectCipherKey = CLIParameters.getProjectCipherKey(commandLine) .orElseGet(() -> {
final CipherKey cipherKey = new CipherKey(RandomUtil.bytes(16), RandomUtil.bytes(16));
8
2023-12-23 09:56:14+00:00
16k
Prototik/TheConfigLib
test-common/src/main/java/dev/tcl/test/GuiTest.java
[ { "identifier": "RequireRestartScreen", "path": "common/src/main/java/dev/tcl/gui/RequireRestartScreen.java", "snippet": "@Environment(EnvType.CLIENT)\npublic class RequireRestartScreen extends ConfirmScreen {\n public RequireRestartScreen(@Nullable Screen parent) {\n super(option -> {\n ...
import dev.tcl.api.*; import dev.tcl.api.controller.*; import dev.tcl.gui.RequireRestartScreen; import dev.tcl.gui.controllers.ColorController; import dev.tcl.gui.controllers.LabelController; import dev.tcl.gui.controllers.TickBoxController; import dev.tcl.gui.controllers.cycling.EnumController; import dev.tcl.gui.controllers.slider.DoubleSliderController; import dev.tcl.gui.controllers.slider.FloatSliderController; import dev.tcl.gui.controllers.slider.IntegerSliderController; import dev.tcl.gui.controllers.slider.LongSliderController; import dev.tcl.gui.controllers.string.StringController; import dev.tcl.gui.controllers.string.number.DoubleFieldController; import dev.tcl.gui.controllers.string.number.FloatFieldController; import dev.tcl.gui.controllers.string.number.IntegerFieldController; import dev.tcl.gui.controllers.string.number.LongFieldController; import net.minecraft.ChatFormatting; import net.minecraft.Util; import net.minecraft.client.GraphicsStatus; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.toasts.SystemToast; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.HoverEvent; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import org.apache.commons.lang3.StringUtils; import java.awt.*; import java.nio.file.Path; import java.util.List; import java.util.concurrent.atomic.AtomicReference;
12,441
.build()) .option(Option.<Boolean>createBuilder() .name(Component.literal("Tick Box")) .description(OptionDescription.of(Component.literal("There are even alternate methods of displaying the same data type!"))) .binding( defaults.tickbox, () -> config.tickbox, (value) -> config.tickbox = value ) .controller(TickBoxControllerBuilder::create) .build()) .build()) .group(OptionGroup.createBuilder() .name(Component.literal("Slider Controllers")) .option(Option.<Integer>createBuilder() .name(Component.literal("Int Slider")) .binding( defaults.intSlider, () -> config.intSlider, value -> config.intSlider = value ) .customController(opt -> new IntegerSliderController(opt, 0, 3, 1)) .build()) .option(Option.<Double>createBuilder() .name(Component.literal("Double Slider")) .binding( defaults.doubleSlider, () -> config.doubleSlider, (value) -> config.doubleSlider = value ) .customController(opt -> new DoubleSliderController(opt, 0, 3, 0.05)) .build()) .option(Option.<Float>createBuilder() .name(Component.literal("Float Slider")) .binding( defaults.floatSlider, () -> config.floatSlider, (value) -> config.floatSlider = value ) .customController(opt -> new FloatSliderController(opt, 0, 3, 0.1f)) .build()) .option(Option.<Long>createBuilder() .name(Component.literal("Long Slider")) .binding( defaults.longSlider, () -> config.longSlider, (value) -> config.longSlider = value ) .customController(opt -> new LongSliderController(opt, 0, 1_000_000, 100)) .build()) .build()) .group(OptionGroup.createBuilder() .name(Component.literal("Input Field Controllers")) .option(Option.<String>createBuilder() .name(Component.literal("Component Option")) .binding( defaults.textField, () -> config.textField, value -> config.textField = value ) .customController(StringController::new) .build()) .option(Option.<Color>createBuilder() .name(Component.literal("Color Option")) .binding( defaults.colorOption, () -> config.colorOption, value -> config.colorOption = value ) .customController(ColorController::new) .build()) .build()) .group(OptionGroup.createBuilder() .name(Component.literal("Number Fields")) .option(Option.<Double>createBuilder() .name(Component.literal("Double Field")) .binding( defaults.doubleField, () -> config.doubleField, value -> config.doubleField = value ) .customController(DoubleFieldController::new) .build()) .option(Option.<Float>createBuilder() .name(Component.literal("Float Field")) .binding( defaults.floatField, () -> config.floatField, value -> config.floatField = value ) .customController(FloatFieldController::new) .build()) .option(Option.<Integer>createBuilder() .name(Component.literal("Integer Field")) .binding( defaults.intField, () -> config.intField, value -> config.intField = value ) .customController(IntegerFieldController::new) .build()) .option(Option.<Long>createBuilder() .name(Component.literal("Long Field")) .binding( defaults.longField, () -> config.longField, value -> config.longField = value ) .customController(LongFieldController::new) .build()) .build()) .group(OptionGroup.createBuilder() .name(Component.literal("Enum Controllers")) .option(Option.<ConfigTest.Alphabet>createBuilder() .name(Component.literal("Enum Cycler")) .binding( defaults.enumOption, () -> config.enumOption, (value) -> config.enumOption = value )
package dev.tcl.test; public class GuiTest { public static Screen getModConfigScreenFactory(Screen parent) { return TheConfigLib.create(ConfigTest.GSON, (defaults, config, builder) -> builder .title(Component.literal("Test Suites")) .category(ConfigCategory.createBuilder() .name(Component.literal("Suites")) .option(ButtonOption.createBuilder() .name(Component.literal("Full Test Suite")) .action((screen, opt) -> Minecraft.getInstance().setScreen(getFullTestSuite(screen))) .build()) .option(ButtonOption.createBuilder() .name(Component.literal("Auto-gen test")) .action((screen, opt) -> { Minecraft.getInstance().setScreen(AutogenConfigTest.INSTANCE.generateGui().generateScreen(screen)); }) .build()) .group(OptionGroup.createBuilder() .name(Component.literal("Wiki")) .option(ButtonOption.createBuilder() .name(Component.literal("Get Started")) .action((screen, opt) -> Minecraft.getInstance().setScreen(getWikiGetStarted(screen))) .build()) .build()) .build()) ) .generateScreen(parent); } private static Screen getFullTestSuite(Screen parent) { AtomicReference<Option<Boolean>> booleanOption = new AtomicReference<>(); return TheConfigLib.create(ConfigTest.GSON, (defaults, config, builder) -> builder .title(Component.literal("Test GUI")) .category(ConfigCategory.createBuilder() .name(Component.literal("Control Examples")) .tooltip(Component.literal("Example Category Description")) .group(OptionGroup.createBuilder() .name(Component.literal("Boolean Controllers")) .option(Util.make(() -> { var opt = Option.<Boolean>createBuilder() .name(Component.literal("Boolean Toggle")) .description(OptionDescription.createBuilder() .text(Component.empty() .append(Component.literal("a").withStyle(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal("a"))))) .append(Component.literal("b").withStyle(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal("b"))))) .append(Component.literal("c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c").withStyle(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal("c"))))) .append(Component.literal("e").withStyle(style -> style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Component.literal("e"))))) .withStyle(style -> style.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://isxander.dev"))) ) .webpImage(new ResourceLocation("tcl_test", "reach-around-placement.webp")) .build()) .binding( defaults.booleanToggle, () -> config.booleanToggle, (value) -> config.booleanToggle = value ) .controller(BoolControllerBuilder::create) .flag(OptionFlag.GAME_RESTART) .build(); booleanOption.set(opt); return opt; })) .option(Option.<Boolean>createBuilder() .name(Component.literal("Custom Boolean Toggle")) .description(val -> OptionDescription.createBuilder() .text(Component.literal("You can customize controllers like so! " + TheConfigLib.SHORT_NAME + " is truly infinitely customizable! This tooltip is long in order to demonstrate the cool, smooth scrolling of these descriptions. Did you know, they are also super clickable?! I know, cool right, " + TheConfigLib.SHORT_NAME + " really is amazing.")) .image(Path.of("D:\\Xander\\Downloads\\_MG_0860-Enhanced-NR.png"), new ResourceLocation("tcl_test", "f.webp")) // TODO: Add img file to git? .build()) .binding( defaults.customBooleanToggle, () -> config.customBooleanToggle, (value) -> config.customBooleanToggle = value ) .controller(opt -> BoolControllerBuilder.create(opt) .formatValue(state -> state ? Component.literal("Amazing") : Component.literal("Not Amazing")) .coloured(true)) .listener((opt, val) -> booleanOption.get().setAvailable(val)) .build()) .option(Option.<Boolean>createBuilder() .name(Component.literal("Tick Box")) .description(OptionDescription.of(Component.literal("There are even alternate methods of displaying the same data type!"))) .binding( defaults.tickbox, () -> config.tickbox, (value) -> config.tickbox = value ) .controller(TickBoxControllerBuilder::create) .build()) .build()) .group(OptionGroup.createBuilder() .name(Component.literal("Slider Controllers")) .option(Option.<Integer>createBuilder() .name(Component.literal("Int Slider")) .binding( defaults.intSlider, () -> config.intSlider, value -> config.intSlider = value ) .customController(opt -> new IntegerSliderController(opt, 0, 3, 1)) .build()) .option(Option.<Double>createBuilder() .name(Component.literal("Double Slider")) .binding( defaults.doubleSlider, () -> config.doubleSlider, (value) -> config.doubleSlider = value ) .customController(opt -> new DoubleSliderController(opt, 0, 3, 0.05)) .build()) .option(Option.<Float>createBuilder() .name(Component.literal("Float Slider")) .binding( defaults.floatSlider, () -> config.floatSlider, (value) -> config.floatSlider = value ) .customController(opt -> new FloatSliderController(opt, 0, 3, 0.1f)) .build()) .option(Option.<Long>createBuilder() .name(Component.literal("Long Slider")) .binding( defaults.longSlider, () -> config.longSlider, (value) -> config.longSlider = value ) .customController(opt -> new LongSliderController(opt, 0, 1_000_000, 100)) .build()) .build()) .group(OptionGroup.createBuilder() .name(Component.literal("Input Field Controllers")) .option(Option.<String>createBuilder() .name(Component.literal("Component Option")) .binding( defaults.textField, () -> config.textField, value -> config.textField = value ) .customController(StringController::new) .build()) .option(Option.<Color>createBuilder() .name(Component.literal("Color Option")) .binding( defaults.colorOption, () -> config.colorOption, value -> config.colorOption = value ) .customController(ColorController::new) .build()) .build()) .group(OptionGroup.createBuilder() .name(Component.literal("Number Fields")) .option(Option.<Double>createBuilder() .name(Component.literal("Double Field")) .binding( defaults.doubleField, () -> config.doubleField, value -> config.doubleField = value ) .customController(DoubleFieldController::new) .build()) .option(Option.<Float>createBuilder() .name(Component.literal("Float Field")) .binding( defaults.floatField, () -> config.floatField, value -> config.floatField = value ) .customController(FloatFieldController::new) .build()) .option(Option.<Integer>createBuilder() .name(Component.literal("Integer Field")) .binding( defaults.intField, () -> config.intField, value -> config.intField = value ) .customController(IntegerFieldController::new) .build()) .option(Option.<Long>createBuilder() .name(Component.literal("Long Field")) .binding( defaults.longField, () -> config.longField, value -> config.longField = value ) .customController(LongFieldController::new) .build()) .build()) .group(OptionGroup.createBuilder() .name(Component.literal("Enum Controllers")) .option(Option.<ConfigTest.Alphabet>createBuilder() .name(Component.literal("Enum Cycler")) .binding( defaults.enumOption, () -> config.enumOption, (value) -> config.enumOption = value )
.customController(opt -> new EnumController<>(opt, ConfigTest.Alphabet.class))
4
2023-12-25 14:48:27+00:00
16k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/source/org/jfree/data/statistics/DefaultBoxAndWhiskerCategoryDataset.java
[ { "identifier": "KeyedObjects2D", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/KeyedObjects2D.java", "snippet": "public class KeyedObjects2D implements Cloneable, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -1015873563138522374L;\r\n\r\...
import org.jfree.data.general.DatasetChangeEvent; import org.jfree.util.ObjectUtilities; import org.jfree.util.PublicCloneable; import java.util.List; import org.jfree.data.KeyedObjects2D; import org.jfree.data.Range; import org.jfree.data.RangeInfo; import org.jfree.data.general.AbstractDataset;
11,135
public Comparable getColumnKey(int column) { return this.data.getColumnKey(column); } /** * Returns the column keys. * * @return The keys. * * @see #getRowKeys() */ @Override public List getColumnKeys() { return this.data.getColumnKeys(); } /** * Returns the row index for a given key. * * @param key the row key (<code>null</code> not permitted). * * @return The row index. * * @see #getRowKey(int) */ @Override public int getRowIndex(Comparable key) { // defer null argument check return this.data.getRowIndex(key); } /** * Returns a row key. * * @param row the row index (zero-based). * * @return The row key. * * @see #getRowIndex(Comparable) */ @Override public Comparable getRowKey(int row) { return this.data.getRowKey(row); } /** * Returns the row keys. * * @return The keys. * * @see #getColumnKeys() */ @Override public List getRowKeys() { return this.data.getRowKeys(); } /** * Returns the number of rows in the table. * * @return The row count. * * @see #getColumnCount() */ @Override public int getRowCount() { return this.data.getRowCount(); } /** * Returns the number of columns in the table. * * @return The column count. * * @see #getRowCount() */ @Override public int getColumnCount() { return this.data.getColumnCount(); } /** * Returns the minimum y-value in the dataset. * * @param includeInterval a flag that determines whether or not the * y-interval is taken into account. * * @return The minimum value. * * @see #getRangeUpperBound(boolean) */ @Override public double getRangeLowerBound(boolean includeInterval) { return this.minimumRangeValue; } /** * Returns the maximum y-value in the dataset. * * @param includeInterval a flag that determines whether or not the * y-interval is taken into account. * * @return The maximum value. * * @see #getRangeLowerBound(boolean) */ @Override public double getRangeUpperBound(boolean includeInterval) { return this.maximumRangeValue; } /** * Returns the range of the values in this dataset's range. * * @param includeInterval a flag that determines whether or not the * y-interval is taken into account. * * @return The range. */ @Override
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ---------------------------------------- * DefaultBoxAndWhiskerCategoryDataset.java * ---------------------------------------- * (C) Copyright 2003-2008, by David Browning and Contributors. * * Original Author: David Browning (for Australian Institute of Marine * Science); * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 05-Aug-2003 : Version 1, contributed by David Browning (DG); * 27-Aug-2003 : Moved from org.jfree.data --> org.jfree.data.statistics (DG); * 12-Nov-2003 : Changed 'data' from private to protected and added a new 'add' * method as proposed by Tim Bardzil. Also removed old code (DG); * 01-Mar-2004 : Added equals() method (DG); * 18-Nov-2004 : Updates for changes in RangeInfo interface (DG); * 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0 * release (DG); * ------------- JFREECHART 1.0.x --------------------------------------------- * 02-Feb-2007 : Removed author tags from all over JFreeChart sources (DG); * 17-Apr-2007 : Fixed bug 1701822 (DG); * 13-Jun-2007 : Fixed error in previous patch (DG); * 28-Sep-2007 : Fixed cloning bug (DG); * 02-Oct-2007 : Fixed bug in updating cached bounds (DG); * 03-Oct-2007 : Fixed another bug in updating cached bounds, added removal * methods (DG); * */ package org.jfree.data.statistics; /** * A convenience class that provides a default implementation of the * {@link BoxAndWhiskerCategoryDataset} interface. */ public class DefaultBoxAndWhiskerCategoryDataset extends AbstractDataset implements BoxAndWhiskerCategoryDataset, RangeInfo, PublicCloneable { /** Storage for the data. */ protected KeyedObjects2D data; /** The minimum range value. */ private double minimumRangeValue; /** The row index for the cell that the minimum range value comes from. */ private int minimumRangeValueRow; /** * The column index for the cell that the minimum range value comes from. */ private int minimumRangeValueColumn; /** The maximum range value. */ private double maximumRangeValue; /** The row index for the cell that the maximum range value comes from. */ private int maximumRangeValueRow; /** * The column index for the cell that the maximum range value comes from. */ private int maximumRangeValueColumn; /** * Creates a new dataset. */ public DefaultBoxAndWhiskerCategoryDataset() { this.data = new KeyedObjects2D(); this.minimumRangeValue = Double.NaN; this.minimumRangeValueRow = -1; this.minimumRangeValueColumn = -1; this.maximumRangeValue = Double.NaN; this.maximumRangeValueRow = -1; this.maximumRangeValueColumn = -1; } /** * Adds a list of values relating to one box-and-whisker entity to the * table. The various median values are calculated. * * @param list a collection of values from which the various medians will * be calculated. * @param rowKey the row key (<code>null</code> not permitted). * @param columnKey the column key (<code>null</code> not permitted). * * @see #add(BoxAndWhiskerItem, Comparable, Comparable) */ public void add(List list, Comparable rowKey, Comparable columnKey) { BoxAndWhiskerItem item = BoxAndWhiskerCalculator .calculateBoxAndWhiskerStatistics(list); add(item, rowKey, columnKey); } /** * Adds a list of values relating to one Box and Whisker entity to the * table. The various median values are calculated. * * @param item a box and whisker item (<code>null</code> not permitted). * @param rowKey the row key (<code>null</code> not permitted). * @param columnKey the column key (<code>null</code> not permitted). * * @see #add(List, Comparable, Comparable) */ public void add(BoxAndWhiskerItem item, Comparable rowKey, Comparable columnKey) { this.data.addObject(item, rowKey, columnKey); // update cached min and max values int r = this.data.getRowIndex(rowKey); int c = this.data.getColumnIndex(columnKey); if ((this.maximumRangeValueRow == r && this.maximumRangeValueColumn == c) || (this.minimumRangeValueRow == r && this.minimumRangeValueColumn == c)) { updateBounds(); } else { double minval = Double.NaN; if (item.getMinOutlier() != null) { minval = item.getMinOutlier().doubleValue(); } double maxval = Double.NaN; if (item.getMaxOutlier() != null) { maxval = item.getMaxOutlier().doubleValue(); } if (Double.isNaN(this.maximumRangeValue)) { this.maximumRangeValue = maxval; this.maximumRangeValueRow = r; this.maximumRangeValueColumn = c; } else if (maxval > this.maximumRangeValue) { this.maximumRangeValue = maxval; this.maximumRangeValueRow = r; this.maximumRangeValueColumn = c; } if (Double.isNaN(this.minimumRangeValue)) { this.minimumRangeValue = minval; this.minimumRangeValueRow = r; this.minimumRangeValueColumn = c; } else if (minval < this.minimumRangeValue) { this.minimumRangeValue = minval; this.minimumRangeValueRow = r; this.minimumRangeValueColumn = c; } } fireDatasetChanged(); } /** * Removes an item from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param rowKey the row key (<code>null</code> not permitted). * @param columnKey the column key (<code>null</code> not permitted). * * @see #add(BoxAndWhiskerItem, Comparable, Comparable) * * @since 1.0.7 */ public void remove(Comparable rowKey, Comparable columnKey) { // defer null argument checks int r = getRowIndex(rowKey); int c = getColumnIndex(columnKey); this.data.removeObject(rowKey, columnKey); // if this cell held a maximum and/or minimum value, we'll need to // update the cached bounds... if ((this.maximumRangeValueRow == r && this.maximumRangeValueColumn == c) || (this.minimumRangeValueRow == r && this.minimumRangeValueColumn == c)) { updateBounds(); } fireDatasetChanged(); } /** * Removes a row from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param rowIndex the row index. * * @see #removeColumn(int) * * @since 1.0.7 */ public void removeRow(int rowIndex) { this.data.removeRow(rowIndex); updateBounds(); fireDatasetChanged(); } /** * Removes a row from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param rowKey the row key. * * @see #removeColumn(Comparable) * * @since 1.0.7 */ public void removeRow(Comparable rowKey) { this.data.removeRow(rowKey); updateBounds(); fireDatasetChanged(); } /** * Removes a column from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param columnIndex the column index. * * @see #removeRow(int) * * @since 1.0.7 */ public void removeColumn(int columnIndex) { this.data.removeColumn(columnIndex); updateBounds(); fireDatasetChanged(); } /** * Removes a column from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param columnKey the column key. * * @see #removeRow(Comparable) * * @since 1.0.7 */ public void removeColumn(Comparable columnKey) { this.data.removeColumn(columnKey); updateBounds(); fireDatasetChanged(); } /** * Clears all data from the dataset and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @since 1.0.7 */ public void clear() { this.data.clear(); updateBounds(); fireDatasetChanged(); } /** * Return an item from within the dataset. * * @param row the row index. * @param column the column index. * * @return The item. */ public BoxAndWhiskerItem getItem(int row, int column) { return (BoxAndWhiskerItem) this.data.getObject(row, column); } /** * Returns the value for an item. * * @param row the row index. * @param column the column index. * * @return The value. * * @see #getMedianValue(int, int) * @see #getValue(Comparable, Comparable) */ @Override public Number getValue(int row, int column) { return getMedianValue(row, column); } /** * Returns the value for an item. * * @param rowKey the row key. * @param columnKey the columnKey. * * @return The value. * * @see #getMedianValue(Comparable, Comparable) * @see #getValue(int, int) */ @Override public Number getValue(Comparable rowKey, Comparable columnKey) { return getMedianValue(rowKey, columnKey); } /** * Returns the mean value for an item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The mean value. * * @see #getItem(int, int) */ @Override public Number getMeanValue(int row, int column) { Number result = null; BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(row, column); if (item != null) { result = item.getMean(); } return result; } /** * Returns the mean value for an item. * * @param rowKey the row key. * @param columnKey the column key. * * @return The mean value. * * @see #getItem(int, int) */ @Override public Number getMeanValue(Comparable rowKey, Comparable columnKey) { Number result = null; BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject( rowKey, columnKey); if (item != null) { result = item.getMean(); } return result; } /** * Returns the median value for an item. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The median value. * * @see #getItem(int, int) */ @Override public Number getMedianValue(int row, int column) { Number result = null; BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject(row, column); if (item != null) { result = item.getMedian(); } return result; } /** * Returns the median value for an item. * * @param rowKey the row key. * @param columnKey the columnKey. * * @return The median value. * * @see #getItem(int, int) */ @Override public Number getMedianValue(Comparable rowKey, Comparable columnKey) { Number result = null; BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject( rowKey, columnKey); if (item != null) { result = item.getMedian(); } return result; } /** * Returns the first quartile value. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The first quartile value. * * @see #getItem(int, int) */ @Override public Number getQ1Value(int row, int column) { Number result = null; BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject( row, column); if (item != null) { result = item.getQ1(); } return result; } /** * Returns the first quartile value. * * @param rowKey the row key. * @param columnKey the column key. * * @return The first quartile value. * * @see #getItem(int, int) */ @Override public Number getQ1Value(Comparable rowKey, Comparable columnKey) { Number result = null; BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject( rowKey, columnKey); if (item != null) { result = item.getQ1(); } return result; } /** * Returns the third quartile value. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return The third quartile value. * * @see #getItem(int, int) */ @Override public Number getQ3Value(int row, int column) { Number result = null; BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject( row, column); if (item != null) { result = item.getQ3(); } return result; } /** * Returns the third quartile value. * * @param rowKey the row key. * @param columnKey the column key. * * @return The third quartile value. * * @see #getItem(int, int) */ @Override public Number getQ3Value(Comparable rowKey, Comparable columnKey) { Number result = null; BoxAndWhiskerItem item = (BoxAndWhiskerItem) this.data.getObject( rowKey, columnKey); if (item != null) { result = item.getQ3(); } return result; } /** * Returns the column index for a given key. * * @param key the column key (<code>null</code> not permitted). * * @return The column index. * * @see #getColumnKey(int) */ @Override public int getColumnIndex(Comparable key) { return this.data.getColumnIndex(key); } /** * Returns a column key. * * @param column the column index (zero-based). * * @return The column key. * * @see #getColumnIndex(Comparable) */ @Override public Comparable getColumnKey(int column) { return this.data.getColumnKey(column); } /** * Returns the column keys. * * @return The keys. * * @see #getRowKeys() */ @Override public List getColumnKeys() { return this.data.getColumnKeys(); } /** * Returns the row index for a given key. * * @param key the row key (<code>null</code> not permitted). * * @return The row index. * * @see #getRowKey(int) */ @Override public int getRowIndex(Comparable key) { // defer null argument check return this.data.getRowIndex(key); } /** * Returns a row key. * * @param row the row index (zero-based). * * @return The row key. * * @see #getRowIndex(Comparable) */ @Override public Comparable getRowKey(int row) { return this.data.getRowKey(row); } /** * Returns the row keys. * * @return The keys. * * @see #getColumnKeys() */ @Override public List getRowKeys() { return this.data.getRowKeys(); } /** * Returns the number of rows in the table. * * @return The row count. * * @see #getColumnCount() */ @Override public int getRowCount() { return this.data.getRowCount(); } /** * Returns the number of columns in the table. * * @return The column count. * * @see #getRowCount() */ @Override public int getColumnCount() { return this.data.getColumnCount(); } /** * Returns the minimum y-value in the dataset. * * @param includeInterval a flag that determines whether or not the * y-interval is taken into account. * * @return The minimum value. * * @see #getRangeUpperBound(boolean) */ @Override public double getRangeLowerBound(boolean includeInterval) { return this.minimumRangeValue; } /** * Returns the maximum y-value in the dataset. * * @param includeInterval a flag that determines whether or not the * y-interval is taken into account. * * @return The maximum value. * * @see #getRangeLowerBound(boolean) */ @Override public double getRangeUpperBound(boolean includeInterval) { return this.maximumRangeValue; } /** * Returns the range of the values in this dataset's range. * * @param includeInterval a flag that determines whether or not the * y-interval is taken into account. * * @return The range. */ @Override
public Range getRangeBounds(boolean includeInterval) {
1
2023-12-24 12:36:47+00:00
16k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/MayOBees.java
[ { "identifier": "MainCommand", "path": "src/main/java/com/github/may2beez/mayobees/command/MainCommand.java", "snippet": "@Command(value = \"m2b\", description = \"MayOBees Command\", aliases = {\"mayobees\"})\npublic class MainCommand {\n @Main\n private void main() {\n MayOBees.CONFIG.ope...
import cc.polyfrost.oneconfig.utils.commands.CommandManager; import com.github.may2beez.mayobees.command.MainCommand; import com.github.may2beez.mayobees.config.MayOBeesConfig; import com.github.may2beez.mayobees.handler.GameStateHandler; import com.github.may2beez.mayobees.handler.RotationHandler; import com.github.may2beez.mayobees.module.ModuleManager; import com.github.may2beez.mayobees.module.impl.other.Failsafes; import com.github.may2beez.mayobees.util.helper.AudioManager; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLInitializationEvent;
14,369
package com.github.may2beez.mayobees; @Mod(modid = "mayobees", useMetadata=true) public class MayOBees {
package com.github.may2beez.mayobees; @Mod(modid = "mayobees", useMetadata=true) public class MayOBees {
public static final MayOBeesConfig CONFIG = new MayOBeesConfig();
1
2023-12-24 15:39:11+00:00
16k
Trodev-IT/ScanHub
app/src/main/java/com/trodev/scanhub/HomeFragment.java
[ { "identifier": "EmailActivity", "path": "app/src/main/java/com/trodev/scanhub/activities/EmailActivity.java", "snippet": "public class EmailActivity extends AppCompatActivity {\n\n public final static int QRCodeWidth = 500;\n Bitmap bitmap;\n private Button make_btn, save_btn, downloadBtn;\n ...
import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.google.android.material.card.MaterialCardView; import com.trodev.scanhub.activities.EmailActivity; import com.trodev.scanhub.activities.LocationActivity; import com.trodev.scanhub.activities.ProductQrActivity; import com.trodev.scanhub.activities.ScanGalleryActivity; import com.trodev.scanhub.activities.ScannerActivity; import com.trodev.scanhub.activities.SmsActivity; import com.trodev.scanhub.activities.URLActivity; import com.trodev.scanhub.activities.WifiQrActivity;
12,636
package com.trodev.scanhub; public class HomeFragment extends Fragment { MaterialCardView product_qr, message, wifi; MaterialCardView email_qr, location_qr, url_qr; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); /*init views*/ product_qr = view.findViewById(R.id.product_qr); message = view.findViewById(R.id.message); wifi = view.findViewById(R.id.wifi); email_qr = view.findViewById(R.id.email_qr); location_qr = view.findViewById(R.id.location_qr); url_qr = view.findViewById(R.id.url_qr); /*set on click listener*/ product_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_product(); } }); message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_message(); } }); wifi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_wifi(); } }); email_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_email(); } }); location_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_location(); } }); url_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_url(); } }); return view; } private void goto_url() { startActivity(new Intent(getContext(), URLActivity.class)); } private void goto_location() { startActivity(new Intent(getContext(), LocationActivity.class)); } private void goto_email() { startActivity(new Intent(getContext(), EmailActivity.class)); } private void goto_wifi() { startActivity(new Intent(getContext(), WifiQrActivity.class)); } private void goto_message() { startActivity(new Intent(getContext(), SmsActivity.class)); } private void goto_product() { startActivity(new Intent(getContext(), ProductQrActivity.class)); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { inflater.inflate(R.menu.menu_home, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.images_item_scan) { Intent intent = new Intent(getContext(), ScannerActivity.class); startActivity(intent); } else if (itemId == R.id.gallery_item_scan) {
package com.trodev.scanhub; public class HomeFragment extends Fragment { MaterialCardView product_qr, message, wifi; MaterialCardView email_qr, location_qr, url_qr; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); /*init views*/ product_qr = view.findViewById(R.id.product_qr); message = view.findViewById(R.id.message); wifi = view.findViewById(R.id.wifi); email_qr = view.findViewById(R.id.email_qr); location_qr = view.findViewById(R.id.location_qr); url_qr = view.findViewById(R.id.url_qr); /*set on click listener*/ product_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_product(); } }); message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_message(); } }); wifi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_wifi(); } }); email_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_email(); } }); location_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_location(); } }); url_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_url(); } }); return view; } private void goto_url() { startActivity(new Intent(getContext(), URLActivity.class)); } private void goto_location() { startActivity(new Intent(getContext(), LocationActivity.class)); } private void goto_email() { startActivity(new Intent(getContext(), EmailActivity.class)); } private void goto_wifi() { startActivity(new Intent(getContext(), WifiQrActivity.class)); } private void goto_message() { startActivity(new Intent(getContext(), SmsActivity.class)); } private void goto_product() { startActivity(new Intent(getContext(), ProductQrActivity.class)); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { inflater.inflate(R.menu.menu_home, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.images_item_scan) { Intent intent = new Intent(getContext(), ScannerActivity.class); startActivity(intent); } else if (itemId == R.id.gallery_item_scan) {
Intent intent = new Intent(getContext(), ScanGalleryActivity.class);
3
2023-12-26 05:10:38+00:00
16k
piovas-lu/condominio
src/main/java/app/condominio/service/RelatorioServiceImpl.java
[ { "identifier": "Categoria", "path": "src/main/java/app/condominio/domain/Categoria.java", "snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"categorias\")\r\npublic class Categoria implements Serializable, Comparable<Categoria> {\r\n\r\n\tpublic static final int NIVEL_MAX = 4;\r\n\...
import java.math.BigDecimal; import java.time.LocalDate; import java.time.YearMonth; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import app.condominio.domain.Categoria; import app.condominio.domain.Cobranca; import app.condominio.domain.Conta; import app.condominio.domain.Moradia; import app.condominio.domain.Movimento; import app.condominio.domain.Orcamento; import app.condominio.domain.Periodo; import app.condominio.domain.Subcategoria; import app.condominio.domain.enums.TipoCategoria;
11,183
} if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } @Override public BigDecimal[] receitaDespesaMesAtual() { List<Conta> contas = contaService.listar(); YearMonth mesAtual = YearMonth.from(LocalDate.now()); // mesAtual = mesAtual.minusMonths(1); // Mês anterior para testes return receitaDespesaEntre(contas, mesAtual.atDay(1), mesAtual.atEndOfMonth()); } @Override public BigDecimal[] receitaDespesaEntre(LocalDate inicio, LocalDate fim) { List<Conta> contas = contaService.listar(); return receitaDespesaEntre(contas, inicio, fim); } @Override public BigDecimal[] receitaDespesaRealizadaPeriodoAtual() { List<Conta> contas = contaService.listar(); Periodo periodoAtual = periodoService.ler(LocalDate.now()); if (periodoAtual != null) { return receitaDespesaEntre(contas, periodoAtual.getInicio(), periodoAtual.getFim()); } else { BigDecimal[] resultado = new BigDecimal[2]; resultado[0] = BigDecimal.ZERO.setScale(2); resultado[1] = BigDecimal.ZERO.setScale(2); return resultado; } } @Override public BigDecimal[] receitaDespesaOrcadaPeriodoAtual() { Periodo periodoAtual = periodoService.ler(LocalDate.now()); BigDecimal[] resultado = new BigDecimal[2]; if (periodoAtual != null) { resultado[0] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.R); resultado[1] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.D); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } @Override public List<Movimento> lancamentosEntre(LocalDate inicio, LocalDate fim) { List<Conta> contas = contaService.listar(); if (!contas.isEmpty()) { List<Movimento> lancamentos = new ArrayList<>(); lancamentos.addAll(movimentoService.listarLancamentosEntre(contas, inicio, fim)); return lancamentos; } return new ArrayList<>(); } @Override public BigDecimal[] saldosAposMovimentos(List<Movimento> movimentos, BigDecimal saldoInicial) { if (saldoInicial == null) { saldoInicial = BigDecimal.ZERO.setScale(2); } if (!movimentos.isEmpty()) { BigDecimal[] saldos = new BigDecimal[movimentos.size()]; Movimento movimento = movimentos.get(0); // Preenche o primeiro saldo if (movimento.getReducao()) { saldos[0] = saldoInicial.subtract(movimento.getValor()); } else { saldos[0] = saldoInicial.add(movimento.getValor()); } // Preenche os outros saldos for (int i = 1; i < saldos.length; i++) { movimento = movimentos.get(i); if (movimento.getReducao()) { saldos[i] = saldos[i - 1].subtract(movimento.getValor()); } else { saldos[i] = saldos[i - 1].add(movimento.getValor()); } } return saldos; } else { BigDecimal[] vazio = new BigDecimal[1]; vazio[0] = saldoInicial; return vazio; } } @Override public SortedMap<Subcategoria, BigDecimal> somasPorTipoEntre(LocalDate inicio, LocalDate fim, TipoCategoria tipoCategoria) { SortedMap<Subcategoria, BigDecimal> map = new TreeMap<>(); List<Conta> contas = contaService.listar(); if (!contas.isEmpty()) { List<Subcategoria> subcategorias; if (TipoCategoria.R.equals(tipoCategoria)) { subcategorias = subcategoriaService.listarReceitas(); } else if (TipoCategoria.D.equals(tipoCategoria)) { subcategorias = subcategoriaService.listarDespesas(); } else { return map; } for (Subcategoria subcategoria : subcategorias) { BigDecimal soma = movimentoService.somaLancamentosEntre(contas, inicio, fim, subcategoria); if (soma != null && soma.compareTo(BigDecimal.ZERO) != 0) { map.put(subcategoria, soma); } } } return map; } @Override
package app.condominio.service; @Service @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public class RelatorioServiceImpl implements RelatorioService { @Autowired ContaService contaService; @Autowired MovimentoService movimentoService; @Autowired CobrancaService cobrancaService; @Autowired OrcamentoService orcamentoService; @Autowired PeriodoService periodoService; @Autowired SubcategoriaService subcategoriaService; @Autowired CategoriaService categoriaService; @Override public BigDecimal saldoAtualTodasContas() { return contaService.saldoAtual(); } @Override public BigDecimal saldoInicialTodasContasEm(LocalDate data) { BigDecimal saldo = contaService.saldoAtual(); BigDecimal[] lancamentos = receitaDespesaDesde(contaService.listar(), data); return saldo.subtract(lancamentos[0]).add(lancamentos[1]); } @Override public BigDecimal saldoFinalTodasContasEm(LocalDate data) { return saldoInicialTodasContasEm(data.plusDays(1)); } @Override public BigDecimal inadimplenciaAtual() { return cobrancaService.inadimplencia(); } private BigDecimal[] receitaDespesaEntre(Collection<Conta> contas, LocalDate inicio, LocalDate fim) { BigDecimal[] resultado = new BigDecimal[2]; if (!contas.isEmpty()) { resultado[0] = movimentoService.somaLancamentosEntre(contas, inicio, fim, Boolean.FALSE); resultado[1] = movimentoService.somaLancamentosEntre(contas, inicio, fim, Boolean.TRUE); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } private BigDecimal[] receitaDespesaDesde(Collection<Conta> contas, LocalDate inicio) { BigDecimal[] resultado = new BigDecimal[2]; if (!contas.isEmpty()) { resultado[0] = movimentoService.somaLancamentosDesde(contas, inicio, Boolean.FALSE); resultado[1] = movimentoService.somaLancamentosDesde(contas, inicio, Boolean.TRUE); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } @Override public BigDecimal[] receitaDespesaMesAtual() { List<Conta> contas = contaService.listar(); YearMonth mesAtual = YearMonth.from(LocalDate.now()); // mesAtual = mesAtual.minusMonths(1); // Mês anterior para testes return receitaDespesaEntre(contas, mesAtual.atDay(1), mesAtual.atEndOfMonth()); } @Override public BigDecimal[] receitaDespesaEntre(LocalDate inicio, LocalDate fim) { List<Conta> contas = contaService.listar(); return receitaDespesaEntre(contas, inicio, fim); } @Override public BigDecimal[] receitaDespesaRealizadaPeriodoAtual() { List<Conta> contas = contaService.listar(); Periodo periodoAtual = periodoService.ler(LocalDate.now()); if (periodoAtual != null) { return receitaDespesaEntre(contas, periodoAtual.getInicio(), periodoAtual.getFim()); } else { BigDecimal[] resultado = new BigDecimal[2]; resultado[0] = BigDecimal.ZERO.setScale(2); resultado[1] = BigDecimal.ZERO.setScale(2); return resultado; } } @Override public BigDecimal[] receitaDespesaOrcadaPeriodoAtual() { Periodo periodoAtual = periodoService.ler(LocalDate.now()); BigDecimal[] resultado = new BigDecimal[2]; if (periodoAtual != null) { resultado[0] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.R); resultado[1] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.D); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } @Override public List<Movimento> lancamentosEntre(LocalDate inicio, LocalDate fim) { List<Conta> contas = contaService.listar(); if (!contas.isEmpty()) { List<Movimento> lancamentos = new ArrayList<>(); lancamentos.addAll(movimentoService.listarLancamentosEntre(contas, inicio, fim)); return lancamentos; } return new ArrayList<>(); } @Override public BigDecimal[] saldosAposMovimentos(List<Movimento> movimentos, BigDecimal saldoInicial) { if (saldoInicial == null) { saldoInicial = BigDecimal.ZERO.setScale(2); } if (!movimentos.isEmpty()) { BigDecimal[] saldos = new BigDecimal[movimentos.size()]; Movimento movimento = movimentos.get(0); // Preenche o primeiro saldo if (movimento.getReducao()) { saldos[0] = saldoInicial.subtract(movimento.getValor()); } else { saldos[0] = saldoInicial.add(movimento.getValor()); } // Preenche os outros saldos for (int i = 1; i < saldos.length; i++) { movimento = movimentos.get(i); if (movimento.getReducao()) { saldos[i] = saldos[i - 1].subtract(movimento.getValor()); } else { saldos[i] = saldos[i - 1].add(movimento.getValor()); } } return saldos; } else { BigDecimal[] vazio = new BigDecimal[1]; vazio[0] = saldoInicial; return vazio; } } @Override public SortedMap<Subcategoria, BigDecimal> somasPorTipoEntre(LocalDate inicio, LocalDate fim, TipoCategoria tipoCategoria) { SortedMap<Subcategoria, BigDecimal> map = new TreeMap<>(); List<Conta> contas = contaService.listar(); if (!contas.isEmpty()) { List<Subcategoria> subcategorias; if (TipoCategoria.R.equals(tipoCategoria)) { subcategorias = subcategoriaService.listarReceitas(); } else if (TipoCategoria.D.equals(tipoCategoria)) { subcategorias = subcategoriaService.listarDespesas(); } else { return map; } for (Subcategoria subcategoria : subcategorias) { BigDecimal soma = movimentoService.somaLancamentosEntre(contas, inicio, fim, subcategoria); if (soma != null && soma.compareTo(BigDecimal.ZERO) != 0) { map.put(subcategoria, soma); } } } return map; } @Override
public SortedMap<Moradia, List<Cobranca>> inadimplenciaAtualDetalhada() {
1
2023-12-29 22:19:42+00:00
16k
HuXin0817/shop_api
framework/src/main/java/cn/lili/modules/connect/request/BaseAuthRequest.java
[ { "identifier": "Cache", "path": "framework/src/main/java/cn/lili/cache/Cache.java", "snippet": "public interface Cache<T> {\n\n /**\n * Get an item from the cache, nontransactionally\n *\n * @param key 缓存key\n * @return the cached object or <tt>null</tt>\n */\n T get(Object ke...
import cn.lili.cache.Cache; import cn.lili.common.utils.HttpUtils; import cn.lili.common.utils.StringUtils; import cn.lili.common.utils.UrlBuilder; import cn.lili.common.utils.UuidUtils; import cn.lili.modules.connect.config.AuthConfig; import cn.lili.modules.connect.config.ConnectAuth; import cn.lili.modules.connect.entity.dto.AuthCallback; import cn.lili.modules.connect.entity.dto.AuthResponse; import cn.lili.modules.connect.entity.dto.AuthToken; import cn.lili.modules.connect.entity.dto.ConnectAuthUser; import cn.lili.modules.connect.entity.enums.AuthResponseStatus; import cn.lili.modules.connect.exception.AuthException; import cn.lili.modules.connect.util.AuthChecker; import com.xkcoding.http.util.UrlUtil; import lombok.extern.slf4j.Slf4j; import java.util.List;
12,032
package cn.lili.modules.connect.request; /** * 默认的request处理类 * * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @author yangkai.shen (https://xkcoding.com) * @since 1.0.0 */ @Slf4j public abstract class BaseAuthRequest implements AuthRequest { protected AuthConfig config; protected ConnectAuth source; protected Cache cache; public BaseAuthRequest(AuthConfig config, ConnectAuth connectAuth, Cache cache) { this.config = config; this.source = connectAuth; this.cache = cache; if (!AuthChecker.isSupportedAuth(config, source)) { throw new AuthException(AuthResponseStatus.PARAMETER_INCOMPLETE, source); } //校验配置合法性 AuthChecker.checkConfig(config, source); } /** * 获取access token * * @param authCallback 授权成功后的回调参数 * @return token */ protected abstract AuthToken getAccessToken(AuthCallback authCallback); /** * 使用token换取用户信息 * * @param authToken token信息 * @return 用户信息 */
package cn.lili.modules.connect.request; /** * 默认的request处理类 * * @author yadong.zhang (yadong.zhang0415(a)gmail.com) * @author yangkai.shen (https://xkcoding.com) * @since 1.0.0 */ @Slf4j public abstract class BaseAuthRequest implements AuthRequest { protected AuthConfig config; protected ConnectAuth source; protected Cache cache; public BaseAuthRequest(AuthConfig config, ConnectAuth connectAuth, Cache cache) { this.config = config; this.source = connectAuth; this.cache = cache; if (!AuthChecker.isSupportedAuth(config, source)) { throw new AuthException(AuthResponseStatus.PARAMETER_INCOMPLETE, source); } //校验配置合法性 AuthChecker.checkConfig(config, source); } /** * 获取access token * * @param authCallback 授权成功后的回调参数 * @return token */ protected abstract AuthToken getAccessToken(AuthCallback authCallback); /** * 使用token换取用户信息 * * @param authToken token信息 * @return 用户信息 */
protected abstract ConnectAuthUser getUserInfo(AuthToken authToken);
10
2023-12-24 19:45:18+00:00
16k
huidongyin/kafka-2.7.2
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/WorkerTaskTest.java
[ { "identifier": "Time", "path": "clients/src/main/java/org/apache/kafka/common/utils/Time.java", "snippet": "public interface Time {\n\n Time SYSTEM = new SystemTime();\n\n /**\n * Returns the current time in milliseconds.\n */\n long milliseconds();\n\n /**\n * Returns the value...
import org.apache.kafka.common.utils.Time; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.runtime.WorkerTask.TaskMetricsGroup; import org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator; import org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperatorTest; import org.apache.kafka.connect.sink.SinkTask; import org.apache.kafka.connect.storage.StatusBackingStore; import org.apache.kafka.connect.util.ConnectorTaskId; import org.apache.kafka.common.utils.MockTime; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.easymock.Mock; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.partialMockBuilder; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals;
12,527
replay(workerTask); workerTask.initialize(TASK_CONFIG); workerTask.stop(); workerTask.awaitStop(1000L); // now run should not do anything workerTask.run(); verify(workerTask); } @Test public void cancelBeforeStopping() throws Exception { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); WorkerTask workerTask = partialMockBuilder(WorkerTask.class) .withConstructor( ConnectorTaskId.class, TaskStatus.Listener.class, TargetState.class, ClassLoader.class, ConnectMetrics.class, RetryWithToleranceOperator.class, Time.class, StatusBackingStore.class ) .withArgs(taskId, statusListener, TargetState.STARTED, loader, metrics, retryWithToleranceOperator, Time.SYSTEM, statusBackingStore) .addMockedMethod("initialize") .addMockedMethod("initializeAndStart") .addMockedMethod("execute") .addMockedMethod("close") .createStrictMock(); final CountDownLatch stopped = new CountDownLatch(1); final Thread thread = new Thread() { @Override public void run() { try { stopped.await(); } catch (Exception e) { } } }; workerTask.initialize(TASK_CONFIG); EasyMock.expectLastCall(); workerTask.initializeAndStart(); EasyMock.expectLastCall(); workerTask.execute(); expectLastCall().andAnswer(new IAnswer<Void>() { @Override public Void answer() throws Throwable { thread.start(); return null; } }); statusListener.onStartup(taskId); expectLastCall(); workerTask.close(); expectLastCall(); // there should be no call to onShutdown() replay(workerTask); workerTask.initialize(TASK_CONFIG); workerTask.run(); workerTask.stop(); workerTask.cancel(); stopped.countDown(); thread.join(); verify(workerTask); } @Test public void updateMetricsOnListenerEventsForStartupPauseResumeAndShutdown() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); ConnectMetrics metrics = new MockConnectMetrics(); TaskMetricsGroup group = new TaskMetricsGroup(taskId, metrics, statusListener); statusListener.onStartup(taskId); expectLastCall(); statusListener.onPause(taskId); expectLastCall(); statusListener.onResume(taskId); expectLastCall(); statusListener.onShutdown(taskId); expectLastCall(); replay(statusListener); group.onStartup(taskId); assertRunningMetric(group); group.onPause(taskId); assertPausedMetric(group); group.onResume(taskId); assertRunningMetric(group); group.onShutdown(taskId); assertStoppedMetric(group); verify(statusListener); } @Test public void updateMetricsOnListenerEventsForStartupPauseResumeAndFailure() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); MockConnectMetrics metrics = new MockConnectMetrics(); MockTime time = metrics.time();
/* * 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.kafka.connect.runtime; @RunWith(PowerMockRunner.class) @PrepareForTest({WorkerTask.class}) @PowerMockIgnore("javax.management.*") public class WorkerTaskTest { private static final Map<String, String> TASK_PROPS = new HashMap<>(); static { TASK_PROPS.put(TaskConfig.TASK_CLASS_CONFIG, TestSinkTask.class.getName()); } private static final TaskConfig TASK_CONFIG = new TaskConfig(TASK_PROPS); private ConnectMetrics metrics; @Mock private TaskStatus.Listener statusListener; @Mock private ClassLoader loader; RetryWithToleranceOperator retryWithToleranceOperator; @Mock StatusBackingStore statusBackingStore; @Before public void setup() { metrics = new MockConnectMetrics(); retryWithToleranceOperator = RetryWithToleranceOperatorTest.NOOP_OPERATOR; } @After public void tearDown() { if (metrics != null) metrics.stop(); } @Test public void standardStartup() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); WorkerTask workerTask = partialMockBuilder(WorkerTask.class) .withConstructor( ConnectorTaskId.class, TaskStatus.Listener.class, TargetState.class, ClassLoader.class, ConnectMetrics.class, RetryWithToleranceOperator.class, Time.class, StatusBackingStore.class ) .withArgs(taskId, statusListener, TargetState.STARTED, loader, metrics, retryWithToleranceOperator, Time.SYSTEM, statusBackingStore) .addMockedMethod("initialize") .addMockedMethod("initializeAndStart") .addMockedMethod("execute") .addMockedMethod("close") .createStrictMock(); workerTask.initialize(TASK_CONFIG); expectLastCall(); workerTask.initializeAndStart(); expectLastCall(); workerTask.execute(); expectLastCall(); statusListener.onStartup(taskId); expectLastCall(); workerTask.close(); expectLastCall(); statusListener.onShutdown(taskId); expectLastCall(); replay(workerTask); workerTask.initialize(TASK_CONFIG); workerTask.run(); workerTask.stop(); workerTask.awaitStop(1000L); verify(workerTask); } @Test public void stopBeforeStarting() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); WorkerTask workerTask = partialMockBuilder(WorkerTask.class) .withConstructor( ConnectorTaskId.class, TaskStatus.Listener.class, TargetState.class, ClassLoader.class, ConnectMetrics.class, RetryWithToleranceOperator.class, Time.class, StatusBackingStore.class ) .withArgs(taskId, statusListener, TargetState.STARTED, loader, metrics, retryWithToleranceOperator, Time.SYSTEM, statusBackingStore) .addMockedMethod("initialize") .addMockedMethod("execute") .addMockedMethod("close") .createStrictMock(); workerTask.initialize(TASK_CONFIG); EasyMock.expectLastCall(); workerTask.close(); EasyMock.expectLastCall(); replay(workerTask); workerTask.initialize(TASK_CONFIG); workerTask.stop(); workerTask.awaitStop(1000L); // now run should not do anything workerTask.run(); verify(workerTask); } @Test public void cancelBeforeStopping() throws Exception { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); WorkerTask workerTask = partialMockBuilder(WorkerTask.class) .withConstructor( ConnectorTaskId.class, TaskStatus.Listener.class, TargetState.class, ClassLoader.class, ConnectMetrics.class, RetryWithToleranceOperator.class, Time.class, StatusBackingStore.class ) .withArgs(taskId, statusListener, TargetState.STARTED, loader, metrics, retryWithToleranceOperator, Time.SYSTEM, statusBackingStore) .addMockedMethod("initialize") .addMockedMethod("initializeAndStart") .addMockedMethod("execute") .addMockedMethod("close") .createStrictMock(); final CountDownLatch stopped = new CountDownLatch(1); final Thread thread = new Thread() { @Override public void run() { try { stopped.await(); } catch (Exception e) { } } }; workerTask.initialize(TASK_CONFIG); EasyMock.expectLastCall(); workerTask.initializeAndStart(); EasyMock.expectLastCall(); workerTask.execute(); expectLastCall().andAnswer(new IAnswer<Void>() { @Override public Void answer() throws Throwable { thread.start(); return null; } }); statusListener.onStartup(taskId); expectLastCall(); workerTask.close(); expectLastCall(); // there should be no call to onShutdown() replay(workerTask); workerTask.initialize(TASK_CONFIG); workerTask.run(); workerTask.stop(); workerTask.cancel(); stopped.countDown(); thread.join(); verify(workerTask); } @Test public void updateMetricsOnListenerEventsForStartupPauseResumeAndShutdown() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); ConnectMetrics metrics = new MockConnectMetrics(); TaskMetricsGroup group = new TaskMetricsGroup(taskId, metrics, statusListener); statusListener.onStartup(taskId); expectLastCall(); statusListener.onPause(taskId); expectLastCall(); statusListener.onResume(taskId); expectLastCall(); statusListener.onShutdown(taskId); expectLastCall(); replay(statusListener); group.onStartup(taskId); assertRunningMetric(group); group.onPause(taskId); assertPausedMetric(group); group.onResume(taskId); assertRunningMetric(group); group.onShutdown(taskId); assertStoppedMetric(group); verify(statusListener); } @Test public void updateMetricsOnListenerEventsForStartupPauseResumeAndFailure() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); MockConnectMetrics metrics = new MockConnectMetrics(); MockTime time = metrics.time();
ConnectException error = new ConnectException("error");
1
2023-12-23 07:12:18+00:00
16k
IGinX-THU/Parquet
src/main/java/org/apache/parquet/local/filter2/compat/RowGroupFilter.java
[ { "identifier": "ParquetFileReader", "path": "src/main/java/org/apache/parquet/local/ParquetFileReader.java", "snippet": "public class ParquetFileReader implements Closeable {\n\n private static final Logger LOG = LoggerFactory.getLogger(ParquetFileReader.class);\n\n private final ParquetMetadataConve...
import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.apache.parquet.filter2.compat.FilterCompat; import org.apache.parquet.filter2.compat.FilterCompat.Filter; import org.apache.parquet.filter2.compat.FilterCompat.NoOpFilter; import org.apache.parquet.filter2.compat.FilterCompat.Visitor; import org.apache.parquet.filter2.dictionarylevel.DictionaryFilter; import org.apache.parquet.filter2.predicate.FilterPredicate; import org.apache.parquet.filter2.predicate.SchemaCompatibilityValidator; import org.apache.parquet.filter2.statisticslevel.StatisticsFilter; import org.apache.parquet.hadoop.metadata.BlockMetaData; import org.apache.parquet.local.ParquetFileReader; import org.apache.parquet.local.filter2.bloomfilterlevel.BloomFilterImpl; import org.apache.parquet.schema.MessageType;
13,539
/* * 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.parquet.local.filter2.compat; /** * Given a {@link Filter} applies it to a list of BlockMetaData (row groups) If the Filter is an * {@link org.apache.parquet.filter.UnboundRecordFilter} or the no op filter, no filtering will be * performed. */ public class RowGroupFilter implements Visitor<List<BlockMetaData>> { private final List<BlockMetaData> blocks; private final MessageType schema; private final List<FilterLevel> levels; private final ParquetFileReader reader; public enum FilterLevel { STATISTICS, DICTIONARY, BLOOMFILTER } public static List<BlockMetaData> filterRowGroups( List<FilterLevel> levels, Filter filter, List<BlockMetaData> blocks, ParquetFileReader reader) { Objects.requireNonNull(filter, "filter cannot be null"); return filter.accept(new RowGroupFilter(levels, blocks, reader)); } private RowGroupFilter( List<FilterLevel> levels, List<BlockMetaData> blocks, ParquetFileReader reader) { this.blocks = Objects.requireNonNull(blocks, "blocks cannnot be null"); this.reader = Objects.requireNonNull(reader, "reader cannnot be null"); this.schema = reader.getFileMetaData().getSchema(); this.levels = levels; } @Override public List<BlockMetaData> visit(FilterCompat.FilterPredicateCompat filterPredicateCompat) { FilterPredicate filterPredicate = filterPredicateCompat.getFilterPredicate(); // check that the schema of the filter matches the schema of the file SchemaCompatibilityValidator.validate(filterPredicate, schema); List<BlockMetaData> filteredBlocks = new ArrayList<BlockMetaData>(); for (BlockMetaData block : blocks) { boolean drop = false; if (levels.contains(FilterLevel.STATISTICS)) { drop = StatisticsFilter.canDrop(filterPredicate, block.getColumns()); } if (!drop && levels.contains(FilterLevel.DICTIONARY)) { drop = DictionaryFilter.canDrop( filterPredicate, block.getColumns(), reader.getDictionaryReader(block)); } if (!drop && levels.contains(FilterLevel.BLOOMFILTER)) { drop =
/* * 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.parquet.local.filter2.compat; /** * Given a {@link Filter} applies it to a list of BlockMetaData (row groups) If the Filter is an * {@link org.apache.parquet.filter.UnboundRecordFilter} or the no op filter, no filtering will be * performed. */ public class RowGroupFilter implements Visitor<List<BlockMetaData>> { private final List<BlockMetaData> blocks; private final MessageType schema; private final List<FilterLevel> levels; private final ParquetFileReader reader; public enum FilterLevel { STATISTICS, DICTIONARY, BLOOMFILTER } public static List<BlockMetaData> filterRowGroups( List<FilterLevel> levels, Filter filter, List<BlockMetaData> blocks, ParquetFileReader reader) { Objects.requireNonNull(filter, "filter cannot be null"); return filter.accept(new RowGroupFilter(levels, blocks, reader)); } private RowGroupFilter( List<FilterLevel> levels, List<BlockMetaData> blocks, ParquetFileReader reader) { this.blocks = Objects.requireNonNull(blocks, "blocks cannnot be null"); this.reader = Objects.requireNonNull(reader, "reader cannnot be null"); this.schema = reader.getFileMetaData().getSchema(); this.levels = levels; } @Override public List<BlockMetaData> visit(FilterCompat.FilterPredicateCompat filterPredicateCompat) { FilterPredicate filterPredicate = filterPredicateCompat.getFilterPredicate(); // check that the schema of the filter matches the schema of the file SchemaCompatibilityValidator.validate(filterPredicate, schema); List<BlockMetaData> filteredBlocks = new ArrayList<BlockMetaData>(); for (BlockMetaData block : blocks) { boolean drop = false; if (levels.contains(FilterLevel.STATISTICS)) { drop = StatisticsFilter.canDrop(filterPredicate, block.getColumns()); } if (!drop && levels.contains(FilterLevel.DICTIONARY)) { drop = DictionaryFilter.canDrop( filterPredicate, block.getColumns(), reader.getDictionaryReader(block)); } if (!drop && levels.contains(FilterLevel.BLOOMFILTER)) { drop =
BloomFilterImpl.canDrop(
1
2023-12-29 01:48:28+00:00
16k
Yanyutin753/PandoraNext-TokensTool
rearServer/src/main/java/com/tokensTool/pandoraNext/controller/autoTokenController.java
[ { "identifier": "Result", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/Result.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Result {\n\n /**\n * 响应码,1 代表成功; 0 代表失败\n */\n\n private Integer code;\n /**\n * 响应信息 描述字符串\n */\n\n...
import com.tokensTool.pandoraNext.anno.Log; import com.tokensTool.pandoraNext.pojo.Result; import com.tokensTool.pandoraNext.pojo.token; import com.tokensTool.pandoraNext.service.impl.poolServiceImpl; import com.tokensTool.pandoraNext.service.impl.shareServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.bind.annotation.*; import java.util.List;
14,118
package com.tokensTool.pandoraNext.controller; /** * @author Yangyang * @create 2023-11-11 18:19 */ @Slf4j @RestController @RequestMapping("/api") public class autoTokenController { @Autowired private com.tokensTool.pandoraNext.service.apiService apiService; @Autowired private poolServiceImpl poolService; @Autowired private shareServiceImpl shareService; /** * 自动更新access_Token和share_token * 更换tokens.json里存储的Tokens * 自动重启 * * @return "更新成功" or "更新失败" * @throws Exception */ @Log @Scheduled(cron = "0 0 */6 * * ?") public void toUpdateToken() { try { log.info("开始自动检查更新refresh_token,session_token,生成和刷新share_token,pool_token.........................."); toUpdateAllToken(); } catch (Exception e) { e.printStackTrace(); } log.info(Result.error("自动检查更新access_token,share_token和pool_token失败").toString()); } /** * 一键检查所有session或者refresh_token * 失效变黄 * 并更新所有access_token和share_token * 并重新组成pool_token * * @return */ @Log @GetMapping("updateAllToken") public Result toUpdateAllToken() { try { String res = apiService.autoUpdateToken(""); if (res.contains("生成Token成功")) { try { String s = poolService.refreshAllTokens(); String s1 = shareService.refreshAllToken(); return Result.success(res + s + s1); } catch (Exception e) { return Result.success(res + "<br>但是自动更新pool_token和oneApi里的share_token失败"); } } } catch (Exception e) { throw new IllegalStateException(e); } return Result.error("生成access_token和share_token失败"); } /** * 自动更新指定用户名的access_token和share_token * * @return "更新成功" or "刷新Token失败,请尝重新刷新!” * @throws Exception */ @PostMapping("updateToken")
package com.tokensTool.pandoraNext.controller; /** * @author Yangyang * @create 2023-11-11 18:19 */ @Slf4j @RestController @RequestMapping("/api") public class autoTokenController { @Autowired private com.tokensTool.pandoraNext.service.apiService apiService; @Autowired private poolServiceImpl poolService; @Autowired private shareServiceImpl shareService; /** * 自动更新access_Token和share_token * 更换tokens.json里存储的Tokens * 自动重启 * * @return "更新成功" or "更新失败" * @throws Exception */ @Log @Scheduled(cron = "0 0 */6 * * ?") public void toUpdateToken() { try { log.info("开始自动检查更新refresh_token,session_token,生成和刷新share_token,pool_token.........................."); toUpdateAllToken(); } catch (Exception e) { e.printStackTrace(); } log.info(Result.error("自动检查更新access_token,share_token和pool_token失败").toString()); } /** * 一键检查所有session或者refresh_token * 失效变黄 * 并更新所有access_token和share_token * 并重新组成pool_token * * @return */ @Log @GetMapping("updateAllToken") public Result toUpdateAllToken() { try { String res = apiService.autoUpdateToken(""); if (res.contains("生成Token成功")) { try { String s = poolService.refreshAllTokens(); String s1 = shareService.refreshAllToken(); return Result.success(res + s + s1); } catch (Exception e) { return Result.success(res + "<br>但是自动更新pool_token和oneApi里的share_token失败"); } } } catch (Exception e) { throw new IllegalStateException(e); } return Result.error("生成access_token和share_token失败"); } /** * 自动更新指定用户名的access_token和share_token * * @return "更新成功" or "刷新Token失败,请尝重新刷新!” * @throws Exception */ @PostMapping("updateToken")
public Result toUpdateToken(@RequestBody token token) {
1
2023-11-17 11:37:37+00:00
16k
quarkiverse/quarkus-langchain4j
core/deployment/src/main/java/io/quarkiverse/langchain4j/deployment/AiServicesProcessor.java
[ { "identifier": "illegalConfigurationForMethod", "path": "core/deployment/src/main/java/io/quarkiverse/langchain4j/deployment/ExceptionUtil.java", "snippet": "static IllegalConfigurationException illegalConfigurationForMethod(String message, MethodInfo offendingMethod) {\n String effectiveMessage = m...
import static dev.langchain4j.exception.IllegalConfigurationException.illegalConfiguration; import static dev.langchain4j.service.ServiceOutputParser.outputFormatInstructions; import static io.quarkiverse.langchain4j.deployment.ExceptionUtil.illegalConfigurationForMethod; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.lang.annotation.Annotation; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.AnnotationValue; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.ClassType; import org.jboss.jandex.DotName; import org.jboss.jandex.IndexView; import org.jboss.jandex.MethodInfo; import org.jboss.jandex.MethodParameterInfo; import org.jboss.jandex.ParameterizedType; import org.jboss.jandex.Type; import org.jboss.logging.Logger; import org.objectweb.asm.ClassReader; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.analysis.AnalyzerException; import dev.langchain4j.exception.IllegalConfigurationException; import dev.langchain4j.service.V; import io.quarkiverse.langchain4j.deployment.items.SelectedChatModelProviderBuildItem; import io.quarkiverse.langchain4j.runtime.AiServicesRecorder; import io.quarkiverse.langchain4j.runtime.aiservice.AiServiceClassCreateInfo; import io.quarkiverse.langchain4j.runtime.aiservice.AiServiceMethodCreateInfo; import io.quarkiverse.langchain4j.runtime.aiservice.AiServiceMethodImplementationSupport; import io.quarkiverse.langchain4j.runtime.aiservice.ChatMemoryRemovable; import io.quarkiverse.langchain4j.runtime.aiservice.DeclarativeAiServiceCreateInfo; import io.quarkiverse.langchain4j.runtime.aiservice.MetricsCountedWrapper; import io.quarkiverse.langchain4j.runtime.aiservice.MetricsTimedWrapper; import io.quarkiverse.langchain4j.runtime.aiservice.QuarkusAiServiceContext; import io.quarkiverse.langchain4j.runtime.aiservice.SpanWrapper; import io.quarkus.arc.Arc; import io.quarkus.arc.ArcContainer; import io.quarkus.arc.InstanceHandle; import io.quarkus.arc.deployment.AdditionalBeanBuildItem; import io.quarkus.arc.deployment.GeneratedBeanBuildItem; import io.quarkus.arc.deployment.GeneratedBeanGizmoAdaptor; import io.quarkus.arc.deployment.SyntheticBeanBuildItem; import io.quarkus.arc.deployment.UnremovableBeanBuildItem; import io.quarkus.arc.processor.BuiltinScope; import io.quarkus.arc.processor.ScopeInfo; import io.quarkus.builder.item.MultiBuildItem; import io.quarkus.deployment.Capabilities; import io.quarkus.deployment.Capability; import io.quarkus.deployment.GeneratedClassGizmoAdaptor; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.annotations.ExecutionTime; import io.quarkus.deployment.annotations.Record; import io.quarkus.deployment.builditem.CombinedIndexBuildItem; import io.quarkus.deployment.builditem.GeneratedClassBuildItem; import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem; import io.quarkus.deployment.metrics.MetricsCapabilityBuildItem; import io.quarkus.gizmo.ClassCreator; import io.quarkus.gizmo.ClassOutput; import io.quarkus.gizmo.FieldDescriptor; import io.quarkus.gizmo.Gizmo; import io.quarkus.gizmo.MethodCreator; import io.quarkus.gizmo.MethodDescriptor; import io.quarkus.gizmo.ResultHandle; import io.quarkus.runtime.metrics.MetricsFactory;
12,473
chatMemoryProviderSupplierClassDotName = chatMemoryProviderSupplierValue.asClass().name(); if (!chatMemoryProviderSupplierClassDotName .equals(Langchain4jDotNames.BEAN_CHAT_MEMORY_PROVIDER_SUPPLIER)) { validateSupplierAndRegisterForReflection(chatMemoryProviderSupplierClassDotName, index, reflectiveClassProducer); } } DotName retrieverSupplierClassDotName = Langchain4jDotNames.BEAN_IF_EXISTS_RETRIEVER_SUPPLIER; AnnotationValue retrieverSupplierValue = instance.value("retrieverSupplier"); if (retrieverSupplierValue != null) { retrieverSupplierClassDotName = retrieverSupplierValue.asClass().name(); if (!retrieverSupplierClassDotName.equals(Langchain4jDotNames.BEAN_RETRIEVER_SUPPLIER)) { validateSupplierAndRegisterForReflection(retrieverSupplierClassDotName, index, reflectiveClassProducer); } } DotName auditServiceSupplierClassName = Langchain4jDotNames.BEAN_IF_EXISTS_AUDIT_SERVICE_SUPPLIER; AnnotationValue auditServiceSupplierValue = instance.value("auditServiceSupplier"); if (auditServiceSupplierValue != null) { auditServiceSupplierClassName = auditServiceSupplierValue.asClass().name(); validateSupplierAndRegisterForReflection(auditServiceSupplierClassName, index, reflectiveClassProducer); } DotName moderationModelSupplierClassName = null; AnnotationValue moderationModelSupplierValue = instance.value("moderationModelSupplier"); if (moderationModelSupplierValue != null) { moderationModelSupplierClassName = moderationModelSupplierValue.asClass().name(); if (Langchain4jDotNames.NO_MODERATION_MODEL_SUPPLIER.equals(moderationModelSupplierClassName)) { moderationModelSupplierClassName = null; } else if (Langchain4jDotNames.BEAN_MODERATION_MODEL_SUPPLIER.equals(moderationModelSupplierClassName)) { needModerationModelBean = true; } else { validateSupplierAndRegisterForReflection(moderationModelSupplierClassName, index, reflectiveClassProducer); } } BuiltinScope declaredScope = BuiltinScope.from(declarativeAiServiceClassInfo); ScopeInfo cdiScope = declaredScope != null ? declaredScope.getInfo() : BuiltinScope.REQUEST.getInfo(); declarativeAiServiceProducer.produce( new DeclarativeAiServiceBuildItem( declarativeAiServiceClassInfo, chatLanguageModelSupplierClassDotName, toolDotNames, chatMemoryProviderSupplierClassDotName, retrieverSupplierClassDotName, auditServiceSupplierClassName, moderationModelSupplierClassName, cdiScope)); } if (needChatModelBean) { requestChatModelBeanProducer.produce(new RequestChatModelBeanBuildItem()); } if (needModerationModelBean) { requestModerationModelBeanProducer.produce(new RequestModerationModelBeanBuildItem()); } } private void validateSupplierAndRegisterForReflection(DotName supplierDotName, IndexView index, BuildProducer<ReflectiveClassBuildItem> producer) { ClassInfo classInfo = index.getClassByName(supplierDotName); if (classInfo == null) { log.warn("'" + supplierDotName.toString() + "' cannot be indexed"); // TODO: maybe this should be an error return; } if (!classInfo.hasNoArgsConstructor()) { throw new IllegalConfigurationException( "Class '" + supplierDotName.toString() + "' which must contain a no-args constructor."); } producer.produce(ReflectiveClassBuildItem.builder(supplierDotName.toString()).constructors(true).build()); } @BuildStep @Record(ExecutionTime.STATIC_INIT) public void handleDeclarativeServices(AiServicesRecorder recorder, List<DeclarativeAiServiceBuildItem> declarativeAiServiceItems, Optional<SelectedChatModelProviderBuildItem> selectedChatModelProvider, BuildProducer<SyntheticBeanBuildItem> syntheticBeanProducer, BuildProducer<UnremovableBeanBuildItem> unremoveableProducer) { boolean needsChatModelBean = false; boolean needsChatMemoryProviderBean = false; boolean needsRetrieverBean = false; boolean needsAuditServiceBean = false; boolean needsModerationModelBean = false; Set<DotName> allToolNames = new HashSet<>(); for (DeclarativeAiServiceBuildItem bi : declarativeAiServiceItems) { ClassInfo declarativeAiServiceClassInfo = bi.getServiceClassInfo(); String serviceClassName = declarativeAiServiceClassInfo.name().toString(); String chatLanguageModelSupplierClassName = (bi.getLanguageModelSupplierClassDotName() != null ? bi.getLanguageModelSupplierClassDotName().toString() : null); List<String> toolClassNames = bi.getToolDotNames().stream().map(DotName::toString).collect(Collectors.toList()); String chatMemoryProviderSupplierClassName = bi.getChatMemoryProviderSupplierClassDotName() != null ? bi.getChatMemoryProviderSupplierClassDotName().toString() : null; String retrieverSupplierClassName = bi.getRetrieverSupplierClassDotName() != null ? bi.getRetrieverSupplierClassDotName().toString() : null; String auditServiceClassSupplierName = bi.getAuditServiceClassSupplierDotName() != null ? bi.getAuditServiceClassSupplierDotName().toString() : null; String moderationModelSupplierClassName = (bi.getModerationModelSupplierDotName() != null ? bi.getModerationModelSupplierDotName().toString() : null); SyntheticBeanBuildItem.ExtendedBeanConfigurator configurator = SyntheticBeanBuildItem .configure(QuarkusAiServiceContext.class) .createWith(recorder.createDeclarativeAiService(
package io.quarkiverse.langchain4j.deployment; @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public class AiServicesProcessor { private static final Logger log = Logger.getLogger(AiServicesProcessor.class); private static final DotName V = DotName.createSimple(V.class); public static final DotName MICROMETER_TIMED = DotName.createSimple("io.micrometer.core.annotation.Timed"); public static final DotName MICROMETER_COUNTED = DotName.createSimple("io.micrometer.core.annotation.Counted"); private static final String DEFAULT_DELIMITER = "\n"; private static final Predicate<AnnotationInstance> IS_METHOD_PARAMETER_ANNOTATION = ai -> ai.target() .kind() == AnnotationTarget.Kind.METHOD_PARAMETER; private static final Function<AnnotationInstance, Integer> METHOD_PARAMETER_POSITION_FUNCTION = ai -> Integer .valueOf(ai.target() .asMethodParameter().position()); public static final MethodDescriptor OBJECT_CONSTRUCTOR = MethodDescriptor.ofConstructor(Object.class); private static final MethodDescriptor RECORDER_METHOD_CREATE_INFO = MethodDescriptor.ofMethod(AiServicesRecorder.class, "getAiServiceMethodCreateInfo", AiServiceMethodCreateInfo.class, String.class, String.class); private static final MethodDescriptor SUPPORT_IMPLEMENT = MethodDescriptor.ofMethod( AiServiceMethodImplementationSupport.class, "implement", Object.class, AiServiceMethodImplementationSupport.Input.class); private static final MethodDescriptor QUARKUS_AI_SERVICES_CONTEXT_CLOSE = MethodDescriptor.ofMethod( QuarkusAiServiceContext.class, "close", void.class); private static final MethodDescriptor QUARKUS_AI_SERVICES_CONTEXT_REMOVE_CHAT_MEMORY_IDS = MethodDescriptor.ofMethod( QuarkusAiServiceContext.class, "removeChatMemoryIds", void.class, Object[].class); public static final DotName CDI_INSTANCE = DotName.createSimple(Instance.class); private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final String METRICS_DEFAULT_NAME = "langchain4j.aiservices"; @BuildStep public void nativeSupport(CombinedIndexBuildItem indexBuildItem, List<AiServicesMethodBuildItem> aiServicesMethodBuildItems, BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer) { IndexView index = indexBuildItem.getIndex(); Collection<AnnotationInstance> instances = index.getAnnotations(Langchain4jDotNames.DESCRIPTION); Set<ClassInfo> classesUsingDescription = new HashSet<>(); for (AnnotationInstance instance : instances) { if (instance.target().kind() != AnnotationTarget.Kind.FIELD) { continue; } classesUsingDescription.add(instance.target().asField().declaringClass()); } if (!classesUsingDescription.isEmpty()) { reflectiveClassProducer.produce(ReflectiveClassBuildItem .builder(classesUsingDescription.stream().map(i -> i.name().toString()).toArray(String[]::new)).fields(true) .build()); } Set<DotName> returnTypesToRegister = new HashSet<>(); for (AiServicesMethodBuildItem aiServicesMethodBuildItem : aiServicesMethodBuildItems) { Type type = aiServicesMethodBuildItem.methodInfo.returnType(); if (type.kind() == Type.Kind.PRIMITIVE) { continue; } DotName returnTypeName = type.name(); if (returnTypeName.toString().startsWith("java.")) { continue; } returnTypesToRegister.add(returnTypeName); } if (!returnTypesToRegister.isEmpty()) { reflectiveClassProducer.produce(ReflectiveClassBuildItem .builder(returnTypesToRegister.stream().map(DotName::toString).toArray(String[]::new)) .constructors(false) .build()); } } @BuildStep public void findDeclarativeServices(CombinedIndexBuildItem indexBuildItem, BuildProducer<RequestChatModelBeanBuildItem> requestChatModelBeanProducer, BuildProducer<RequestModerationModelBeanBuildItem> requestModerationModelBeanProducer, BuildProducer<DeclarativeAiServiceBuildItem> declarativeAiServiceProducer, BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer) { IndexView index = indexBuildItem.getIndex(); boolean needChatModelBean = false; boolean needModerationModelBean = false; for (AnnotationInstance instance : index.getAnnotations(Langchain4jDotNames.REGISTER_AI_SERVICES)) { if (instance.target().kind() != AnnotationTarget.Kind.CLASS) { continue; // should never happen } ClassInfo declarativeAiServiceClassInfo = instance.target().asClass(); DotName chatLanguageModelSupplierClassDotName = null; AnnotationValue chatLanguageModelSupplierValue = instance.value("chatLanguageModelSupplier"); if (chatLanguageModelSupplierValue != null) { chatLanguageModelSupplierClassDotName = chatLanguageModelSupplierValue.asClass().name(); if (chatLanguageModelSupplierClassDotName.equals(Langchain4jDotNames.BEAN_CHAT_MODEL_SUPPLIER)) { // this is the case where the default was set, so we just ignore it chatLanguageModelSupplierClassDotName = null; } else { validateSupplierAndRegisterForReflection(chatLanguageModelSupplierClassDotName, index, reflectiveClassProducer); } } if (chatLanguageModelSupplierClassDotName == null) { needChatModelBean = true; } List<DotName> toolDotNames = Collections.emptyList(); AnnotationValue toolsInstance = instance.value("tools"); if (toolsInstance != null) { toolDotNames = Arrays.stream(toolsInstance.asClassArray()).map(Type::name) .collect(Collectors.toList()); } // the default value depends on whether tools exists or not - if they do, then we require a ChatMemoryProvider bean DotName chatMemoryProviderSupplierClassDotName = Langchain4jDotNames.BEAN_CHAT_MEMORY_PROVIDER_SUPPLIER; AnnotationValue chatMemoryProviderSupplierValue = instance.value("chatMemoryProviderSupplier"); if (chatMemoryProviderSupplierValue != null) { chatMemoryProviderSupplierClassDotName = chatMemoryProviderSupplierValue.asClass().name(); if (!chatMemoryProviderSupplierClassDotName .equals(Langchain4jDotNames.BEAN_CHAT_MEMORY_PROVIDER_SUPPLIER)) { validateSupplierAndRegisterForReflection(chatMemoryProviderSupplierClassDotName, index, reflectiveClassProducer); } } DotName retrieverSupplierClassDotName = Langchain4jDotNames.BEAN_IF_EXISTS_RETRIEVER_SUPPLIER; AnnotationValue retrieverSupplierValue = instance.value("retrieverSupplier"); if (retrieverSupplierValue != null) { retrieverSupplierClassDotName = retrieverSupplierValue.asClass().name(); if (!retrieverSupplierClassDotName.equals(Langchain4jDotNames.BEAN_RETRIEVER_SUPPLIER)) { validateSupplierAndRegisterForReflection(retrieverSupplierClassDotName, index, reflectiveClassProducer); } } DotName auditServiceSupplierClassName = Langchain4jDotNames.BEAN_IF_EXISTS_AUDIT_SERVICE_SUPPLIER; AnnotationValue auditServiceSupplierValue = instance.value("auditServiceSupplier"); if (auditServiceSupplierValue != null) { auditServiceSupplierClassName = auditServiceSupplierValue.asClass().name(); validateSupplierAndRegisterForReflection(auditServiceSupplierClassName, index, reflectiveClassProducer); } DotName moderationModelSupplierClassName = null; AnnotationValue moderationModelSupplierValue = instance.value("moderationModelSupplier"); if (moderationModelSupplierValue != null) { moderationModelSupplierClassName = moderationModelSupplierValue.asClass().name(); if (Langchain4jDotNames.NO_MODERATION_MODEL_SUPPLIER.equals(moderationModelSupplierClassName)) { moderationModelSupplierClassName = null; } else if (Langchain4jDotNames.BEAN_MODERATION_MODEL_SUPPLIER.equals(moderationModelSupplierClassName)) { needModerationModelBean = true; } else { validateSupplierAndRegisterForReflection(moderationModelSupplierClassName, index, reflectiveClassProducer); } } BuiltinScope declaredScope = BuiltinScope.from(declarativeAiServiceClassInfo); ScopeInfo cdiScope = declaredScope != null ? declaredScope.getInfo() : BuiltinScope.REQUEST.getInfo(); declarativeAiServiceProducer.produce( new DeclarativeAiServiceBuildItem( declarativeAiServiceClassInfo, chatLanguageModelSupplierClassDotName, toolDotNames, chatMemoryProviderSupplierClassDotName, retrieverSupplierClassDotName, auditServiceSupplierClassName, moderationModelSupplierClassName, cdiScope)); } if (needChatModelBean) { requestChatModelBeanProducer.produce(new RequestChatModelBeanBuildItem()); } if (needModerationModelBean) { requestModerationModelBeanProducer.produce(new RequestModerationModelBeanBuildItem()); } } private void validateSupplierAndRegisterForReflection(DotName supplierDotName, IndexView index, BuildProducer<ReflectiveClassBuildItem> producer) { ClassInfo classInfo = index.getClassByName(supplierDotName); if (classInfo == null) { log.warn("'" + supplierDotName.toString() + "' cannot be indexed"); // TODO: maybe this should be an error return; } if (!classInfo.hasNoArgsConstructor()) { throw new IllegalConfigurationException( "Class '" + supplierDotName.toString() + "' which must contain a no-args constructor."); } producer.produce(ReflectiveClassBuildItem.builder(supplierDotName.toString()).constructors(true).build()); } @BuildStep @Record(ExecutionTime.STATIC_INIT) public void handleDeclarativeServices(AiServicesRecorder recorder, List<DeclarativeAiServiceBuildItem> declarativeAiServiceItems, Optional<SelectedChatModelProviderBuildItem> selectedChatModelProvider, BuildProducer<SyntheticBeanBuildItem> syntheticBeanProducer, BuildProducer<UnremovableBeanBuildItem> unremoveableProducer) { boolean needsChatModelBean = false; boolean needsChatMemoryProviderBean = false; boolean needsRetrieverBean = false; boolean needsAuditServiceBean = false; boolean needsModerationModelBean = false; Set<DotName> allToolNames = new HashSet<>(); for (DeclarativeAiServiceBuildItem bi : declarativeAiServiceItems) { ClassInfo declarativeAiServiceClassInfo = bi.getServiceClassInfo(); String serviceClassName = declarativeAiServiceClassInfo.name().toString(); String chatLanguageModelSupplierClassName = (bi.getLanguageModelSupplierClassDotName() != null ? bi.getLanguageModelSupplierClassDotName().toString() : null); List<String> toolClassNames = bi.getToolDotNames().stream().map(DotName::toString).collect(Collectors.toList()); String chatMemoryProviderSupplierClassName = bi.getChatMemoryProviderSupplierClassDotName() != null ? bi.getChatMemoryProviderSupplierClassDotName().toString() : null; String retrieverSupplierClassName = bi.getRetrieverSupplierClassDotName() != null ? bi.getRetrieverSupplierClassDotName().toString() : null; String auditServiceClassSupplierName = bi.getAuditServiceClassSupplierDotName() != null ? bi.getAuditServiceClassSupplierDotName().toString() : null; String moderationModelSupplierClassName = (bi.getModerationModelSupplierDotName() != null ? bi.getModerationModelSupplierDotName().toString() : null); SyntheticBeanBuildItem.ExtendedBeanConfigurator configurator = SyntheticBeanBuildItem .configure(QuarkusAiServiceContext.class) .createWith(recorder.createDeclarativeAiService(
new DeclarativeAiServiceCreateInfo(serviceClassName, chatLanguageModelSupplierClassName,
7
2023-11-13 09:10:27+00:00
16k
qiusunshine/xiu
clinglibrary/src/main/java/org/fourthline/cling/UpnpServiceConfiguration.java
[ { "identifier": "DeviceDescriptorBinder", "path": "clinglibrary/src/main/java/org/fourthline/cling/binding/xml/DeviceDescriptorBinder.java", "snippet": "public interface DeviceDescriptorBinder {\n\n public <T extends Device> T describe(T undescribedDevice, String descriptorXml)\n throws De...
import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import org.fourthline.cling.binding.xml.DeviceDescriptorBinder; import org.fourthline.cling.binding.xml.ServiceDescriptorBinder; import org.fourthline.cling.model.Namespace; import org.fourthline.cling.model.message.UpnpHeaders; import org.fourthline.cling.model.meta.RemoteDeviceIdentity; import org.fourthline.cling.model.meta.RemoteService; import org.fourthline.cling.model.types.ServiceType; import org.fourthline.cling.transport.spi.DatagramIO; import org.fourthline.cling.transport.spi.DatagramProcessor; import org.fourthline.cling.transport.spi.GENAEventProcessor; import org.fourthline.cling.transport.spi.MulticastReceiver; import org.fourthline.cling.transport.spi.NetworkAddressFactory; import org.fourthline.cling.transport.spi.SOAPActionProcessor; import org.fourthline.cling.transport.spi.StreamClient; import org.fourthline.cling.transport.spi.StreamServer;
11,134
/* * Copyright (C) 2013 4th Line GmbH, Switzerland * * The contents of this file are subject to the terms of either the GNU * Lesser General Public License Version 2 or later ("LGPL") or the * Common Development and Distribution License Version 1 or later * ("CDDL") (collectively, the "License"). You may not use this file * except in compliance with the License. See LICENSE.txt for more * information. * * 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. */ package org.fourthline.cling; /** * Shared configuration data of the UPnP stack. * <p> * This interface offers methods for retrieval of configuration data by the * {@link org.fourthline.cling.transport.Router} and the {@link org.fourthline.cling.registry.Registry}, * as well as other parts of the UPnP stack. * </p> * <p> * You can re-use this interface if you implement a subclass of {@link UpnpServiceImpl} or * if you create a new implementation of {@link UpnpService}. * </p> * * @author Christian Bauer */ public interface UpnpServiceConfiguration { /** * @return A new instance of the {@link org.fourthline.cling.transport.spi.NetworkAddressFactory} interface. */ public NetworkAddressFactory createNetworkAddressFactory(); /** * @return The shared implementation of {@link org.fourthline.cling.transport.spi.DatagramProcessor}. */ public DatagramProcessor getDatagramProcessor(); /** * @return The shared implementation of {@link org.fourthline.cling.transport.spi.SOAPActionProcessor}. */ public SOAPActionProcessor getSoapActionProcessor(); /** * @return The shared implementation of {@link org.fourthline.cling.transport.spi.GENAEventProcessor}. */ public GENAEventProcessor getGenaEventProcessor(); /** * @return A new instance of the {@link org.fourthline.cling.transport.spi.StreamClient} interface. */ public StreamClient createStreamClient(); /** * @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}. * @return A new instance of the {@link org.fourthline.cling.transport.spi.MulticastReceiver} interface. */ public MulticastReceiver createMulticastReceiver(NetworkAddressFactory networkAddressFactory); /** * @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}. * @return A new instance of the {@link org.fourthline.cling.transport.spi.DatagramIO} interface. */ public DatagramIO createDatagramIO(NetworkAddressFactory networkAddressFactory); /** * @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}. * @return A new instance of the {@link org.fourthline.cling.transport.spi.StreamServer} interface. */ public StreamServer createStreamServer(NetworkAddressFactory networkAddressFactory); /** * @return The executor which runs the listening background threads for multicast datagrams. */ public Executor getMulticastReceiverExecutor(); /** * @return The executor which runs the listening background threads for unicast datagrams. */ public Executor getDatagramIOExecutor(); /** * @return The executor which runs the listening background threads for HTTP requests. */ public ExecutorService getStreamServerExecutorService(); /** * @return The shared implementation of {@link org.fourthline.cling.binding.xml.DeviceDescriptorBinder} for the UPnP 1.0 Device Architecture.. */ public DeviceDescriptorBinder getDeviceDescriptorBinderUDA10(); /** * @return The shared implementation of {@link org.fourthline.cling.binding.xml.ServiceDescriptorBinder} for the UPnP 1.0 Device Architecture.. */ public ServiceDescriptorBinder getServiceDescriptorBinderUDA10(); /** * Returns service types that can be handled by this UPnP stack, all others will be ignored. * <p> * Return <code>null</code> to completely disable remote device and service discovery. * All incoming notifications and search responses will then be dropped immediately. * This is mostly useful in applications that only provide services with no (remote) * control point functionality. * </p> * <p> * Note that a discovered service type with version 2 or 3 will match an exclusive * service type with version 1. UPnP services are required to be backwards * compatible, version 2 is a superset of version 1, and version 3 is a superset * of version 2, etc. * </p> * * @return An array of service types that are exclusively discovered, no other service will * be discovered. A <code>null</code> return value will disable discovery! * An empty array means all services will be discovered. */ public ServiceType[] getExclusiveServiceTypes(); /** * @return The time in milliseconds to wait between each registry maintenance operation. */ public int getRegistryMaintenanceIntervalMillis(); /** * Optional setting for flooding alive NOTIFY messages for local devices. * <p> * Use this to advertise local devices at the specified interval, independent of its * {@link org.fourthline.cling.model.meta.DeviceIdentity#maxAgeSeconds} value. Note * that this will increase network traffic. * </p> * <p> * Some control points (XBMC and other Platinum UPnP SDK based devices, OPPO-93) seem * to not properly receive SSDP M-SEARCH replies sent by Cling, but will handle NOTIFY * alive messages just fine. * </p> * * @return The time in milliseconds for ALIVE message intervals, set to <code>0</code> to disable */ public int getAliveIntervalMillis(); /** * Ignore the received event subscription timeout from remote control points. * <p> * Some control points have trouble renewing subscriptions properly; enabling this option * in conjunction with a high value for * {@link org.fourthline.cling.model.UserConstants#DEFAULT_SUBSCRIPTION_DURATION_SECONDS} * ensures that your devices will not disappear on such control points. * </p> * * @return <code>true</code> if the timeout in incoming event subscriptions should be ignored * and the default value ({@link org.fourthline.cling.model.UserConstants#DEFAULT_SUBSCRIPTION_DURATION_SECONDS}) * should be used instead. * */ public boolean isReceivedSubscriptionTimeoutIgnored(); /** * Returns the time in seconds a remote device will be registered until it is expired. * <p> * This setting is useful on systems which do not support multicast networking * (Android on HTC phones, for hiker). On such a system you will not receive messages when a * remote device disappears from the network and you will not receive its periodic heartbeat * alive messages. Only an initial search response (UDP unicast) has been received from the * remote device, with its proposed maximum age. To avoid (early) expiration of the remote * device, you can override its maximum age with this configuration setting, ignoring the * initial maximum age sent by the device. You most likely want to return * <code>0</code> in this case, so that the remote device is never expired unless you * manually remove it from the {@link org.fourthline.cling.registry.Registry}. You typically remove * the device when an action or GENA subscription request to the remote device failed. * </p> * * @return <code>null</code> (the default) to accept the remote device's proposed maximum age, or * <code>0</code> for unlimited age, or a value in seconds. */ public Integer getRemoteDeviceMaxAgeSeconds(); /** * Optional extra headers for device descriptor retrieval HTTP requests. * <p> * Some devices might require extra headers to recognize your control point, use this * method to set these headers. They will be used for every descriptor (XML) retrieval * HTTP request by Cling. See {@link org.fourthline.cling.model.profile.ClientInfo} for * action request messages. * </p> * * @param identity The (so far) discovered identity of the remote device. * @return <code>null</code> or extra HTTP headers. */
/* * Copyright (C) 2013 4th Line GmbH, Switzerland * * The contents of this file are subject to the terms of either the GNU * Lesser General Public License Version 2 or later ("LGPL") or the * Common Development and Distribution License Version 1 or later * ("CDDL") (collectively, the "License"). You may not use this file * except in compliance with the License. See LICENSE.txt for more * information. * * 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. */ package org.fourthline.cling; /** * Shared configuration data of the UPnP stack. * <p> * This interface offers methods for retrieval of configuration data by the * {@link org.fourthline.cling.transport.Router} and the {@link org.fourthline.cling.registry.Registry}, * as well as other parts of the UPnP stack. * </p> * <p> * You can re-use this interface if you implement a subclass of {@link UpnpServiceImpl} or * if you create a new implementation of {@link UpnpService}. * </p> * * @author Christian Bauer */ public interface UpnpServiceConfiguration { /** * @return A new instance of the {@link org.fourthline.cling.transport.spi.NetworkAddressFactory} interface. */ public NetworkAddressFactory createNetworkAddressFactory(); /** * @return The shared implementation of {@link org.fourthline.cling.transport.spi.DatagramProcessor}. */ public DatagramProcessor getDatagramProcessor(); /** * @return The shared implementation of {@link org.fourthline.cling.transport.spi.SOAPActionProcessor}. */ public SOAPActionProcessor getSoapActionProcessor(); /** * @return The shared implementation of {@link org.fourthline.cling.transport.spi.GENAEventProcessor}. */ public GENAEventProcessor getGenaEventProcessor(); /** * @return A new instance of the {@link org.fourthline.cling.transport.spi.StreamClient} interface. */ public StreamClient createStreamClient(); /** * @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}. * @return A new instance of the {@link org.fourthline.cling.transport.spi.MulticastReceiver} interface. */ public MulticastReceiver createMulticastReceiver(NetworkAddressFactory networkAddressFactory); /** * @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}. * @return A new instance of the {@link org.fourthline.cling.transport.spi.DatagramIO} interface. */ public DatagramIO createDatagramIO(NetworkAddressFactory networkAddressFactory); /** * @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}. * @return A new instance of the {@link org.fourthline.cling.transport.spi.StreamServer} interface. */ public StreamServer createStreamServer(NetworkAddressFactory networkAddressFactory); /** * @return The executor which runs the listening background threads for multicast datagrams. */ public Executor getMulticastReceiverExecutor(); /** * @return The executor which runs the listening background threads for unicast datagrams. */ public Executor getDatagramIOExecutor(); /** * @return The executor which runs the listening background threads for HTTP requests. */ public ExecutorService getStreamServerExecutorService(); /** * @return The shared implementation of {@link org.fourthline.cling.binding.xml.DeviceDescriptorBinder} for the UPnP 1.0 Device Architecture.. */ public DeviceDescriptorBinder getDeviceDescriptorBinderUDA10(); /** * @return The shared implementation of {@link org.fourthline.cling.binding.xml.ServiceDescriptorBinder} for the UPnP 1.0 Device Architecture.. */ public ServiceDescriptorBinder getServiceDescriptorBinderUDA10(); /** * Returns service types that can be handled by this UPnP stack, all others will be ignored. * <p> * Return <code>null</code> to completely disable remote device and service discovery. * All incoming notifications and search responses will then be dropped immediately. * This is mostly useful in applications that only provide services with no (remote) * control point functionality. * </p> * <p> * Note that a discovered service type with version 2 or 3 will match an exclusive * service type with version 1. UPnP services are required to be backwards * compatible, version 2 is a superset of version 1, and version 3 is a superset * of version 2, etc. * </p> * * @return An array of service types that are exclusively discovered, no other service will * be discovered. A <code>null</code> return value will disable discovery! * An empty array means all services will be discovered. */ public ServiceType[] getExclusiveServiceTypes(); /** * @return The time in milliseconds to wait between each registry maintenance operation. */ public int getRegistryMaintenanceIntervalMillis(); /** * Optional setting for flooding alive NOTIFY messages for local devices. * <p> * Use this to advertise local devices at the specified interval, independent of its * {@link org.fourthline.cling.model.meta.DeviceIdentity#maxAgeSeconds} value. Note * that this will increase network traffic. * </p> * <p> * Some control points (XBMC and other Platinum UPnP SDK based devices, OPPO-93) seem * to not properly receive SSDP M-SEARCH replies sent by Cling, but will handle NOTIFY * alive messages just fine. * </p> * * @return The time in milliseconds for ALIVE message intervals, set to <code>0</code> to disable */ public int getAliveIntervalMillis(); /** * Ignore the received event subscription timeout from remote control points. * <p> * Some control points have trouble renewing subscriptions properly; enabling this option * in conjunction with a high value for * {@link org.fourthline.cling.model.UserConstants#DEFAULT_SUBSCRIPTION_DURATION_SECONDS} * ensures that your devices will not disappear on such control points. * </p> * * @return <code>true</code> if the timeout in incoming event subscriptions should be ignored * and the default value ({@link org.fourthline.cling.model.UserConstants#DEFAULT_SUBSCRIPTION_DURATION_SECONDS}) * should be used instead. * */ public boolean isReceivedSubscriptionTimeoutIgnored(); /** * Returns the time in seconds a remote device will be registered until it is expired. * <p> * This setting is useful on systems which do not support multicast networking * (Android on HTC phones, for hiker). On such a system you will not receive messages when a * remote device disappears from the network and you will not receive its periodic heartbeat * alive messages. Only an initial search response (UDP unicast) has been received from the * remote device, with its proposed maximum age. To avoid (early) expiration of the remote * device, you can override its maximum age with this configuration setting, ignoring the * initial maximum age sent by the device. You most likely want to return * <code>0</code> in this case, so that the remote device is never expired unless you * manually remove it from the {@link org.fourthline.cling.registry.Registry}. You typically remove * the device when an action or GENA subscription request to the remote device failed. * </p> * * @return <code>null</code> (the default) to accept the remote device's proposed maximum age, or * <code>0</code> for unlimited age, or a value in seconds. */ public Integer getRemoteDeviceMaxAgeSeconds(); /** * Optional extra headers for device descriptor retrieval HTTP requests. * <p> * Some devices might require extra headers to recognize your control point, use this * method to set these headers. They will be used for every descriptor (XML) retrieval * HTTP request by Cling. See {@link org.fourthline.cling.model.profile.ClientInfo} for * action request messages. * </p> * * @param identity The (so far) discovered identity of the remote device. * @return <code>null</code> or extra HTTP headers. */
public UpnpHeaders getDescriptorRetrievalHeaders(RemoteDeviceIdentity identity);
4
2023-11-10 14:28:40+00:00
16k
xIdentified/Devotions
src/main/java/me/xidentified/devotions/managers/DevotionManager.java
[ { "identifier": "Deity", "path": "src/main/java/me/xidentified/devotions/Deity.java", "snippet": "public class Deity {\n private final Devotions plugin;\n // Getter methods below\n @Getter public final String name;\n @Getter private final String lore;\n @Getter private final String alignm...
import me.xidentified.devotions.Deity; import me.xidentified.devotions.Devotions; import me.xidentified.devotions.storage.DevotionData; import me.xidentified.devotions.storage.DevotionStorage; import me.xidentified.devotions.util.Messages; import net.kyori.adventure.text.minimessage.tag.resolver.Formatter; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import static org.bukkit.Bukkit.getServer;
11,664
package me.xidentified.devotions.managers; public class DevotionManager { private final Devotions plugin; private final DevotionStorage devotionStorage; private final Map<UUID, FavorManager> playerDevotions = new ConcurrentHashMap<>(); private final Map<String, Deity> deities; public DevotionManager(Devotions plugin, Map<String, Deity> loadedDeities) { this.plugin = plugin; this.deities = loadedDeities; this.devotionStorage = plugin.getDevotionStorage(); loadPlayerDevotions(); } public Deity getDeityByName(String name) { if (name == null || deities == null) return null; return deities.get(name.toLowerCase()); } public FavorManager getPlayerDevotion(UUID playerUUID) { FavorManager manager = playerDevotions.get(playerUUID); plugin.debugLog("Retrieved FavorManager for UUID " + playerUUID + ": " + manager); return manager; } public void setPlayerDevotion(UUID playerUUID, FavorManager devotion) { if (playerUUID == null || devotion == null) { // Log for debugging plugin.getLogger().warning("Attempted to set null player ID or devotion: Player ID = " + playerUUID + ", Devotion = " + devotion); return; } removeDevotion(playerUUID); // Remove current devotion before setting new one playerDevotions.put(playerUUID, devotion); Player player = Bukkit.getPlayer(playerUUID); if (player != null) { Deity deity = devotion.getDeity(); devotionStorage.savePlayerDevotion(playerUUID, devotion); // Set new devotion plugin.playConfiguredSound(player, "deitySelected");
package me.xidentified.devotions.managers; public class DevotionManager { private final Devotions plugin; private final DevotionStorage devotionStorage; private final Map<UUID, FavorManager> playerDevotions = new ConcurrentHashMap<>(); private final Map<String, Deity> deities; public DevotionManager(Devotions plugin, Map<String, Deity> loadedDeities) { this.plugin = plugin; this.deities = loadedDeities; this.devotionStorage = plugin.getDevotionStorage(); loadPlayerDevotions(); } public Deity getDeityByName(String name) { if (name == null || deities == null) return null; return deities.get(name.toLowerCase()); } public FavorManager getPlayerDevotion(UUID playerUUID) { FavorManager manager = playerDevotions.get(playerUUID); plugin.debugLog("Retrieved FavorManager for UUID " + playerUUID + ": " + manager); return manager; } public void setPlayerDevotion(UUID playerUUID, FavorManager devotion) { if (playerUUID == null || devotion == null) { // Log for debugging plugin.getLogger().warning("Attempted to set null player ID or devotion: Player ID = " + playerUUID + ", Devotion = " + devotion); return; } removeDevotion(playerUUID); // Remove current devotion before setting new one playerDevotions.put(playerUUID, devotion); Player player = Bukkit.getPlayer(playerUUID); if (player != null) { Deity deity = devotion.getDeity(); devotionStorage.savePlayerDevotion(playerUUID, devotion); // Set new devotion plugin.playConfiguredSound(player, "deitySelected");
plugin.sendMessage(player, Messages.DEVOTION_SET.formatted(
3
2023-11-10 07:03:24+00:00
16k
SplitfireUptown/datalinkx
datalinkx-server/src/main/java/com/datalinkx/dataserver/service/impl/JobService.java
[ { "identifier": "JOB_STATUS_STOP", "path": "datalinkx-common/src/main/java/com/datalinkx/common/constants/MetaConstants.java", "snippet": "public static final int JOB_STATUS_STOP = 5;" }, { "identifier": "JOB_STATUS_SYNC", "path": "datalinkx-common/src/main/java/com/datalinkx/common/constant...
import static com.datalinkx.common.constants.MetaConstants.JobStatus.JOB_STATUS_STOP; import static com.datalinkx.common.constants.MetaConstants.JobStatus.JOB_STATUS_SYNC; import static com.datalinkx.common.utils.IdUtils.genKey; import static com.datalinkx.common.utils.JsonUtils.toJson; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.annotation.Resource; import com.datalinkx.common.constants.MessageHubConstants; import com.datalinkx.common.constants.MetaConstants; import com.datalinkx.driver.dsdriver.DsDriverFactory; import com.datalinkx.driver.dsdriver.IDsReader; import com.datalinkx.driver.dsdriver.base.model.TableField; import com.datalinkx.driver.model.DataTransJobDetail; import com.datalinkx.common.result.StatusCode; import com.datalinkx.common.utils.JsonUtils; import com.datalinkx.dataserver.bean.domain.DsBean; import com.datalinkx.dataserver.bean.domain.DsTbBean; import com.datalinkx.dataserver.bean.domain.JobBean; import com.datalinkx.dataserver.bean.domain.JobLogBean; import com.datalinkx.dataserver.bean.dto.JobDto; import com.datalinkx.dataserver.bean.vo.JobVo; import com.datalinkx.dataserver.bean.vo.PageVo; import com.datalinkx.dataserver.client.xxljob.JobClientApi; import com.datalinkx.dataserver.client.xxljob.request.DataTransJobParam; import com.datalinkx.dataserver.controller.form.JobForm; import com.datalinkx.dataserver.controller.form.JobStateForm; import com.datalinkx.common.exception.DatalinkXServerException; import com.datalinkx.dataserver.repository.DsRepository; import com.datalinkx.dataserver.repository.DsTbRepository; import com.datalinkx.dataserver.repository.JobLogRepository; import com.datalinkx.dataserver.repository.JobRepository; import com.datalinkx.dataserver.service.DtsJobService; import com.datalinkx.messagehub.bean.form.ProducerAdapterForm; import com.datalinkx.messagehub.service.MessageHubService; import lombok.SneakyThrows; import lombok.extern.log4j.Log4j2; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.ObjectUtils;
11,463
package com.datalinkx.dataserver.service.impl; @Component @Service @Log4j2 public class JobService implements DtsJobService { private static final int FAILED = 3; private static final int SUCCESS = 2; @Autowired private JobRepository jobRepository; @Autowired DsService dsService; @Autowired DsRepository dsRepository; @Autowired DsTbRepository dsTbRepository; @Autowired JobLogRepository jobLogRepository; @Autowired
package com.datalinkx.dataserver.service.impl; @Component @Service @Log4j2 public class JobService implements DtsJobService { private static final int FAILED = 3; private static final int SUCCESS = 2; @Autowired private JobRepository jobRepository; @Autowired DsService dsService; @Autowired DsRepository dsRepository; @Autowired DsTbRepository dsTbRepository; @Autowired JobLogRepository jobLogRepository; @Autowired
JobClientApi jobClientApi;
19
2023-11-16 02:22:52+00:00
16k
kotmatross28729/EnviroMine-continuation
src/main/java/enviromine/items/EnviroArmor.java
[ { "identifier": "EM_Settings", "path": "src/main/java/enviromine/core/EM_Settings.java", "snippet": "public class EM_Settings\n{\n\tpublic static final UUID FROST1_UUID = UUID.fromString(\"B0C5F86A-78F3-417C-8B5A-527B90A1E919\");\n\tpublic static final UUID FROST2_UUID = UUID.fromString(\"5C4111A7-A66C-...
import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import enviromine.core.EM_Settings; import enviromine.handlers.EnviroAchievements; import enviromine.handlers.ObjectHandler; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.IIcon; import net.minecraft.world.World;
12,157
@SideOnly(Side.CLIENT) public void registerIcons(IIconRegister par1IconRegister) { this.cpIcon = par1IconRegister.registerIcon("enviromine:camel_pack"); this.gmIcon = par1IconRegister.registerIcon("enviromine:gas_mask"); this.hhIcon = par1IconRegister.registerIcon("enviromine:hard_hat"); } @SideOnly(Side.CLIENT) /** * Gets an icon index based on an item's damage value */ @Override public IIcon getIconFromDamage(int par1) { if (this == ObjectHandler.camelPack && cpIcon != null) { return this.cpIcon; } else if (this == ObjectHandler.gasMask && gmIcon != null) { return this.gmIcon; } else if (this == ObjectHandler.hardHat && hhIcon != null) { return this.hhIcon; } { return super.getIconFromDamage(par1); } } @Override /** * Return whether this item is repairable in an anvil. */ public boolean getIsRepairable(ItemStack par1ItemStack, ItemStack par2ItemStack) { if (par1ItemStack.getItem() == ObjectHandler.hardHat && (par2ItemStack.getItem() == ObjectHandler.hardHat || par2ItemStack.getItem() == Items.iron_ingot)) { return true; } else if (par1ItemStack.getItem() == ObjectHandler.gasMask && (par2ItemStack.getItem() == ObjectHandler.gasMask || par2ItemStack.getItem() == Items.iron_ingot)) { return true; } else if (par1ItemStack.getItem() == ObjectHandler.camelPack && (par2ItemStack.getItem() == ObjectHandler.camelPack || par2ItemStack.getItem() == Items.leather)) { return true; } else { return false; } } // Creates a tag if item was grabbed from creative menu @Override public void onUpdate(ItemStack armor, World world, Entity entity, int itemSlot, boolean isSelected) { if (armor.getItem() == ObjectHandler.camelPack) { if (!armor.hasTagCompound()) { armor.setTagCompound(new NBTTagCompound()); } if (!armor.getTagCompound().hasKey(EM_Settings.CAMEL_PACK_FILL_TAG_KEY)) { int meta = armor.getItemDamage() > 0 ? 100 - armor.getItemDamage() : 0; armor.getTagCompound().setInteger(EM_Settings.CAMEL_PACK_FILL_TAG_KEY, meta); armor.setItemDamage(0); } if (!armor.getTagCompound().hasKey(EM_Settings.CAMEL_PACK_MAX_TAG_KEY)) { armor.getTagCompound().setInteger(EM_Settings.CAMEL_PACK_MAX_TAG_KEY, EM_Settings.camelPackMax); } if (!armor.getTagCompound().hasKey(EM_Settings.IS_CAMEL_PACK_TAG_KEY)) { armor.getTagCompound().setBoolean(EM_Settings.IS_CAMEL_PACK_TAG_KEY, true); } } else if (armor.getItem() == ObjectHandler.gasMask) { if (!armor.hasTagCompound()) { armor.setTagCompound(new NBTTagCompound()); } if (!armor.getTagCompound().hasKey(EM_Settings.GAS_MASK_FILL_TAG_KEY)) { armor.getTagCompound().setInteger(EM_Settings.GAS_MASK_FILL_TAG_KEY, EM_Settings.gasMaskMax); } if (!armor.getTagCompound().hasKey(EM_Settings.GAS_MASK_MAX_TAG_KEY)) { armor.getTagCompound().setInteger(EM_Settings.GAS_MASK_MAX_TAG_KEY, EM_Settings.gasMaskMax); } } else if (armor.getItem() == ObjectHandler.hardHat) { } else { } } @Override public void onCreated(ItemStack armor, World world, EntityPlayer player) { if (armor.getItem() == ObjectHandler.camelPack) { if (!armor.hasTagCompound()) { armor.setTagCompound(new NBTTagCompound()); } if (!armor.getTagCompound().hasKey(EM_Settings.CAMEL_PACK_FILL_TAG_KEY)) { int meta = armor.getItemDamage() > 0 ? 100 - armor.getItemDamage() : 0; armor.getTagCompound().setInteger(EM_Settings.CAMEL_PACK_FILL_TAG_KEY, meta); armor.setItemDamage(0); } if (!armor.getTagCompound().hasKey(EM_Settings.CAMEL_PACK_MAX_TAG_KEY)) { armor.getTagCompound().setInteger(EM_Settings.CAMEL_PACK_MAX_TAG_KEY, EM_Settings.camelPackMax); } if (!armor.getTagCompound().hasKey(EM_Settings.IS_CAMEL_PACK_TAG_KEY)) { armor.getTagCompound().setBoolean(EM_Settings.IS_CAMEL_PACK_TAG_KEY, true); }
package enviromine.items; public class EnviroArmor extends ItemArmor //implements ITextureProvider, IArmorTextureProvider { public IIcon cpIcon; public IIcon gmIcon; public IIcon hhIcon; //public int gasMaskFillMax = 200; // Unused public EnviroArmor(ArmorMaterial par2EnumArmorMaterial, int par3, int par4) { super(par2EnumArmorMaterial, par3, par4); this.setMaxDamage(100); //this.setTextureName("enviromine:camel_pack"); //this.setNoRepair(); } @Override public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) { if (stack.getItem() == ObjectHandler.camelPack) { return "enviroMine:textures/models/armor/camelpack_layer_1.png"; } else if (stack.getItem() == ObjectHandler.gasMask) { return "enviroMine:textures/models/armor/gasmask_layer_1.png"; } else if (stack.getItem() == ObjectHandler.hardHat) { return "enviroMine:textures/models/armor/hardhat_layer_1.png"; } else { return null; } } @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister par1IconRegister) { this.cpIcon = par1IconRegister.registerIcon("enviromine:camel_pack"); this.gmIcon = par1IconRegister.registerIcon("enviromine:gas_mask"); this.hhIcon = par1IconRegister.registerIcon("enviromine:hard_hat"); } @SideOnly(Side.CLIENT) /** * Gets an icon index based on an item's damage value */ @Override public IIcon getIconFromDamage(int par1) { if (this == ObjectHandler.camelPack && cpIcon != null) { return this.cpIcon; } else if (this == ObjectHandler.gasMask && gmIcon != null) { return this.gmIcon; } else if (this == ObjectHandler.hardHat && hhIcon != null) { return this.hhIcon; } { return super.getIconFromDamage(par1); } } @Override /** * Return whether this item is repairable in an anvil. */ public boolean getIsRepairable(ItemStack par1ItemStack, ItemStack par2ItemStack) { if (par1ItemStack.getItem() == ObjectHandler.hardHat && (par2ItemStack.getItem() == ObjectHandler.hardHat || par2ItemStack.getItem() == Items.iron_ingot)) { return true; } else if (par1ItemStack.getItem() == ObjectHandler.gasMask && (par2ItemStack.getItem() == ObjectHandler.gasMask || par2ItemStack.getItem() == Items.iron_ingot)) { return true; } else if (par1ItemStack.getItem() == ObjectHandler.camelPack && (par2ItemStack.getItem() == ObjectHandler.camelPack || par2ItemStack.getItem() == Items.leather)) { return true; } else { return false; } } // Creates a tag if item was grabbed from creative menu @Override public void onUpdate(ItemStack armor, World world, Entity entity, int itemSlot, boolean isSelected) { if (armor.getItem() == ObjectHandler.camelPack) { if (!armor.hasTagCompound()) { armor.setTagCompound(new NBTTagCompound()); } if (!armor.getTagCompound().hasKey(EM_Settings.CAMEL_PACK_FILL_TAG_KEY)) { int meta = armor.getItemDamage() > 0 ? 100 - armor.getItemDamage() : 0; armor.getTagCompound().setInteger(EM_Settings.CAMEL_PACK_FILL_TAG_KEY, meta); armor.setItemDamage(0); } if (!armor.getTagCompound().hasKey(EM_Settings.CAMEL_PACK_MAX_TAG_KEY)) { armor.getTagCompound().setInteger(EM_Settings.CAMEL_PACK_MAX_TAG_KEY, EM_Settings.camelPackMax); } if (!armor.getTagCompound().hasKey(EM_Settings.IS_CAMEL_PACK_TAG_KEY)) { armor.getTagCompound().setBoolean(EM_Settings.IS_CAMEL_PACK_TAG_KEY, true); } } else if (armor.getItem() == ObjectHandler.gasMask) { if (!armor.hasTagCompound()) { armor.setTagCompound(new NBTTagCompound()); } if (!armor.getTagCompound().hasKey(EM_Settings.GAS_MASK_FILL_TAG_KEY)) { armor.getTagCompound().setInteger(EM_Settings.GAS_MASK_FILL_TAG_KEY, EM_Settings.gasMaskMax); } if (!armor.getTagCompound().hasKey(EM_Settings.GAS_MASK_MAX_TAG_KEY)) { armor.getTagCompound().setInteger(EM_Settings.GAS_MASK_MAX_TAG_KEY, EM_Settings.gasMaskMax); } } else if (armor.getItem() == ObjectHandler.hardHat) { } else { } } @Override public void onCreated(ItemStack armor, World world, EntityPlayer player) { if (armor.getItem() == ObjectHandler.camelPack) { if (!armor.hasTagCompound()) { armor.setTagCompound(new NBTTagCompound()); } if (!armor.getTagCompound().hasKey(EM_Settings.CAMEL_PACK_FILL_TAG_KEY)) { int meta = armor.getItemDamage() > 0 ? 100 - armor.getItemDamage() : 0; armor.getTagCompound().setInteger(EM_Settings.CAMEL_PACK_FILL_TAG_KEY, meta); armor.setItemDamage(0); } if (!armor.getTagCompound().hasKey(EM_Settings.CAMEL_PACK_MAX_TAG_KEY)) { armor.getTagCompound().setInteger(EM_Settings.CAMEL_PACK_MAX_TAG_KEY, EM_Settings.camelPackMax); } if (!armor.getTagCompound().hasKey(EM_Settings.IS_CAMEL_PACK_TAG_KEY)) { armor.getTagCompound().setBoolean(EM_Settings.IS_CAMEL_PACK_TAG_KEY, true); }
player.addStat(EnviroAchievements.keepYourCool, 1);
1
2023-11-16 18:15:29+00:00
16k
exadel-inc/etoolbox-anydiff
core/src/test/java/com/exadel/etoolbox/anydiff/AllTests.java
[ { "identifier": "DiffBlockXPathTest", "path": "core/src/test/java/com/exadel/etoolbox/anydiff/comparison/DiffBlockXPathTest.java", "snippet": "public class DiffBlockXPathTest {\n\n @Test\n public void shouldReportHtmlPath() throws IOException {\n try (\n InputStream leftInput...
import com.exadel.etoolbox.anydiff.comparison.DiffBlockXPathTest; import com.exadel.etoolbox.anydiff.comparison.DiffCountTest; import com.exadel.etoolbox.anydiff.comparison.DiffTaskTest; import com.exadel.etoolbox.anydiff.comparison.DiffTest; import com.exadel.etoolbox.anydiff.comparison.FragmentTest; import com.exadel.etoolbox.anydiff.comparison.MarkedStringTest; import com.exadel.etoolbox.anydiff.comparison.SpacesHandlingTest; import com.exadel.etoolbox.anydiff.comparison.preprocessor.PreprocessorsTest; import com.exadel.etoolbox.anydiff.runner.DiffRunnerTest; import com.exadel.etoolbox.anydiff.runner.FilterHelperTest; import com.exadel.etoolbox.anydiff.runner.FiltersTest; import org.junit.runner.RunWith; import org.junit.runners.Suite;
14,112
/* * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exadel.etoolbox.anydiff; @RunWith(Suite.class) @Suite.SuiteClasses({ DiffTest.class, DiffRunnerTest.class, DiffTaskTest.class, DiffCountTest.class, DiffBlockXPathTest.class, FragmentTest.class, MarkedStringTest.class, PreprocessorsTest.class,
/* * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exadel.etoolbox.anydiff; @RunWith(Suite.class) @Suite.SuiteClasses({ DiffTest.class, DiffRunnerTest.class, DiffTaskTest.class, DiffCountTest.class, DiffBlockXPathTest.class, FragmentTest.class, MarkedStringTest.class, PreprocessorsTest.class,
SpacesHandlingTest.class,
6
2023-11-16 14:29:45+00:00
16k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/model/guns/ModelMac10.java
[ { "identifier": "CommonAnimations", "path": "src/main/java/sheridan/gunscraft/animation/CommonAnimations.java", "snippet": "public class CommonAnimations {\n public static CurveAnimation createSingleAxisBlotBack(float length, float blotBack) {\n return new CurveAnimation(new Curve[]{\n ...
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.IVertexBuilder; import net.minecraft.client.renderer.entity.model.EntityModel; import net.minecraft.client.renderer.model.ItemCameraTransforms; import net.minecraft.entity.Entity; import sheridan.gunscraft.animation.CommonAnimations; import sheridan.gunscraft.animation.IAnimation; import sheridan.gunscraft.items.attachments.util.GunRenderContext; import sheridan.gunscraft.model.IGunModel; import sheridan.gunscraft.model.ModelRenderer;
13,183
cube_r27 = new ModelRenderer(this); cube_r27.setRotationPoint(0.4071F, 28.1223F, 35.8351F); body2.addChild(cube_r27); setRotationAngle(cube_r27, 0.0436F, 0.0F, 0.0F); cube_r27.setTextureOffset(112, 51).addBox(-3.0F, 0.0F, -12.0F, 4.0F, 1.0F, 12.0F, 0.0F, false, false, false, true, true, true, true); cube_r28 = new ModelRenderer(this); cube_r28.setRotationPoint(0.4071F, 27.0F, 38.0F); body2.addChild(cube_r28); setRotationAngle(cube_r28, -0.7854F, 0.0F, 0.0F); cube_r28.setTextureOffset(114, 32).addBox(-3.0F, 0.0F, -1.0F, 4.0F, 3.0F, 1.0F, 0.0F, false, true, true, false, false, true, true); cube_r29 = new ModelRenderer(this); cube_r29.setRotationPoint(-3.4716F, 36.4F, 37.9787F); body2.addChild(cube_r29); setRotationAngle(cube_r29, 0.0F, -0.7854F, 0.0F); cube_r29.setTextureOffset(140, 84).addBox(0.0F, -17.0F, 0.0F, 3.0F, 25.0F, 3.0F, 0.0F, false, false, false, false, true, false, true); cube_r30 = new ModelRenderer(this); cube_r30.setRotationPoint(2.2858F, 36.4F, 37.9787F); body2.addChild(cube_r30); setRotationAngle(cube_r30, 0.0F, -0.7854F, 0.0F); cube_r30.setTextureOffset(142, 0).addBox(0.0F, -17.0F, 0.0F, 3.0F, 25.0F, 3.0F, 0.0F, false, true, false, false, true, false, false); cube_r31 = new ModelRenderer(this); cube_r31.setRotationPoint(-5.0929F, 27.538F, 54.1015F); body2.addChild(cube_r31); setRotationAngle(cube_r31, 0.2618F, 0.0F, 0.0F); cube_r31.setTextureOffset(0, 111).addBox(0.0F, -2.0F, -7.0F, 9.0F, 11.0F, 7.0F, 0.0F, false, false, true, false, false, true, true); cube_r32 = new ModelRenderer(this); cube_r32.setRotationPoint(-7.0929F, 42.8163F, 58.1296F); body2.addChild(cube_r32); setRotationAngle(cube_r32, -0.7854F, 0.0F, 0.0F); cube_r32.setTextureOffset(37, 115).addBox(4.0F, 0.0603F, -2.342F, 5.0F, 2.0F, 2.0F, 0.0F, false, false, true, true, false, true, true); cube_r33 = new ModelRenderer(this); cube_r33.setRotationPoint(-5.0929F, 22.6139F, 54.2698F); body2.addChild(cube_r33); setRotationAngle(cube_r33, -0.1745F, 0.0F, 0.0F); cube_r33.setTextureOffset(117, 130).addBox(0.0F, 0.0F, -6.0F, 9.0F, 5.0F, 6.0F, 0.0F, false, false, true, false, false, true, true); cube_r34 = new ModelRenderer(this); cube_r34.setRotationPoint(-5.0929F, 19.4F, 58.1F); body2.addChild(cube_r34); setRotationAngle(cube_r34, -0.8727F, 0.0F, 0.0F); cube_r34.setTextureOffset(123, 116).addBox(0.0F, 0.0F, -6.0F, 9.0F, 8.0F, 6.0F, 0.0F, false, false, true, false, false, true, true); cube_r35 = new ModelRenderer(this); cube_r35.setRotationPoint(5.4F, 9.0F, 8.0F); body2.addChild(cube_r35); setRotationAngle(cube_r35, 0.0F, 0.0F, 0.7854F); cube_r35.setTextureOffset(136, 155).addBox(0.0F, 0.0F, -1.0F, 1.0F, 1.0F, 45.0F, 0.0F, false, true, true, false, false, true, false); cube_r36 = new ModelRenderer(this); cube_r36.setRotationPoint(5.4F, 8.0F, 8.0F); body2.addChild(cube_r36); setRotationAngle(cube_r36, 0.0F, 0.0F, 0.7854F); cube_r36.setTextureOffset(162, 84).addBox(0.0F, 0.0F, -1.0F, 1.0F, 1.0F, 45.0F, 0.0F, false, true, true, true, false, false, false); cube_r37 = new ModelRenderer(this); cube_r37.setRotationPoint(5.4F, 4.0F, 8.0F); body2.addChild(cube_r37); setRotationAngle(cube_r37, 0.0F, 0.0F, 0.7854F); cube_r37.setTextureOffset(183, 130).addBox(0.0F, 0.0F, -1.0F, 1.0F, 1.0F, 45.0F, 0.0F, false, true, true, false, false, true, false); cube_r38 = new ModelRenderer(this); cube_r38.setRotationPoint(5.4F, 3.0F, 8.0F); body2.addChild(cube_r38); setRotationAngle(cube_r38, 0.0F, 0.0F, 0.7854F); cube_r38.setTextureOffset(209, 46).addBox(0.0F, 0.0F, -1.0F, 1.0F, 1.0F, 45.0F, 0.0F, false, true, true, true, false, false, false); cube_r39 = new ModelRenderer(this); cube_r39.setRotationPoint(3.9929F, 0.7071F, -1.0F); body2.addChild(cube_r39); setRotationAngle(cube_r39, 0.0F, 0.0F, -0.7854F); cube_r39.setTextureOffset(0, 154).addBox(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 66.0F, 0.0F, false, true, false, false, false, true, false); cube_r40 = new ModelRenderer(this); cube_r40.setRotationPoint(-6.5929F, 0.7071F, -1.0F); body2.addChild(cube_r40); setRotationAngle(cube_r40, 0.0F, 0.0F, -0.7854F); cube_r40.setTextureOffset(68, 155).addBox(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 66.0F, 0.0F, false, true, false, true, false, false, false); charge = new ModelRenderer(this); charge.setRotationPoint(0.0F, 24.0F, 0.0F); cube_r41 = new ModelRenderer(this); cube_r41.setRotationPoint(7.5F, 13.4F, 13.1F); charge.addChild(cube_r41); setRotationAngle(cube_r41, -0.7854F, 0.0F, 0.0F); cube_r41.setTextureOffset(30, 26).addBox(-15.0F, -1.0F, 0.0F, 15.0F, 3.0F, 3.0F, 0.0F, false, true, true, true, true, true, true); cube_r42 = new ModelRenderer(this); cube_r42.setRotationPoint(8.2F, 14.8F, 14.2F); charge.addChild(cube_r42); setRotationAngle(cube_r42, 0.0F, 0.0F, 0.7854F); cube_r42.setTextureOffset(101, 135).addBox(-1.0F, 0.0F, 0.0F, 1.0F, 1.0F, 5.0F, 0.0F, false, true, true, true, true, true, true); } @Override public void setRotationAngles(Entity entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch){ //previously the render function, render code was moved to a method below } @Override public void render(MatrixStack matrixStack, IVertexBuilder buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha){ } public void setRotationAngle(ModelRenderer modelRenderer, float x, float y, float z) { modelRenderer.rotateAngleX = x; modelRenderer.rotateAngleY = y; modelRenderer.rotateAngleZ = z; } @Override
package sheridan.gunscraft.model.guns; public class ModelMac10 extends EntityModel<Entity> implements IGunModel { private final ModelRenderer barrel; private final ModelRenderer mag; private final ModelRenderer stock; private final ModelRenderer slide2; private final ModelRenderer safety; private final ModelRenderer body2; private final ModelRenderer charge; private final ModelRenderer cube_r1; private final ModelRenderer cube_r2; private final ModelRenderer cube_r3; private final ModelRenderer cube_r4; private final ModelRenderer cube_r5; private final ModelRenderer cube_r6; private final ModelRenderer cube_r7; private final ModelRenderer cube_r8; private final ModelRenderer IS_2_r1; private final ModelRenderer IS_1_r1; private final ModelRenderer cube_r9; private final ModelRenderer cube_r10; private final ModelRenderer cube_r11; private final ModelRenderer cube_r12; private final ModelRenderer cube_r13; private final ModelRenderer cube_r14; private final ModelRenderer cube_r15; private final ModelRenderer cube_r16; private final ModelRenderer cube_r17; private final ModelRenderer cube_r18; private final ModelRenderer cube_r19; private final ModelRenderer cube_r20; private final ModelRenderer cube_r21; private final ModelRenderer cube_r22; private final ModelRenderer cube_r23; private final ModelRenderer cube_r24; private final ModelRenderer cube_r25; private final ModelRenderer cube_r26; private final ModelRenderer cube_r27; private final ModelRenderer cube_r28; private final ModelRenderer cube_r29; private final ModelRenderer cube_r30; private final ModelRenderer cube_r31; private final ModelRenderer cube_r32; private final ModelRenderer cube_r33; private final ModelRenderer cube_r34; private final ModelRenderer cube_r35; private final ModelRenderer cube_r36; private final ModelRenderer cube_r37; private final ModelRenderer cube_r38; private final ModelRenderer cube_r39; private final ModelRenderer cube_r40; private final ModelRenderer cube_r41; private final ModelRenderer cube_r42; public static IAnimation slideRecoil; public ModelMac10() { slideRecoil = CommonAnimations.createSingleAxisBlotBack(0.1f, -1.5f); textureWidth = 512; textureHeight = 512; barrel = new ModelRenderer(this); barrel.setRotationPoint(0.0F, 24.0F, 0.0F); cube_r1 = new ModelRenderer(this); cube_r1.setRotationPoint(0.0F, 6.5071F, -17.0F); barrel.addChild(cube_r1); setRotationAngle(cube_r1, 0.0F, 0.0F, 0.7854F); cube_r1.setTextureOffset(34, 101).addBox(0.0F, 0.0F, 0.0F, 4.0F, 4.0F, 10.0F, 0.0F, false, true, false, true, true, true, true); mag = new ModelRenderer(this); mag.setRotationPoint(0.0F, 24.0F, 0.0F); mag.setTextureOffset(90, 26).addBox(-3.5F, 45.0F, 36.8F, 7.0F, 27.0F, 10.0F, 0.0F, false, true, true, false, false, true, true); cube_r2 = new ModelRenderer(this); cube_r2.setRotationPoint(3.0F, 72.6F, 37.0F); mag.addChild(cube_r2); setRotationAngle(cube_r2, -0.0436F, 0.0F, 0.0F); cube_r2.setTextureOffset(91, 109).addBox(-7.0F, -2.0F, -1.0F, 8.0F, 2.0F, 11.0F, 0.0F, false, true, true, true, true, true, true); stock = new ModelRenderer(this); stock.setRotationPoint(-4.5F, 43.8F, 73.0F); stock.setTextureOffset(40, 36).addBox(8.5F, -4.8F, -4.0F, 1.0F, 4.0F, 1.0F, 0.0F, false, false, false, true, true, true, true); stock.setTextureOffset(90, 63).addBox(2.4981F, -20.3639F, -25.6415F, 4.0F, 1.0F, 1.0F, 0.0F, false, true, true, true, false, false, false); stock.setTextureOffset(0, 0).addBox(8.0F, -20.3639F, -24.1415F, 1.0F, 1.0F, 8.0F, 0.0F, false, false, false, true, true, true, true); stock.setTextureOffset(0, 9).addBox(0.0F, -20.3639F, -24.1415F, 1.0F, 1.0F, 8.0F, 0.0F, false, false, false, true, true, true, true); stock.setTextureOffset(40, 11).addBox(-0.5F, -4.8F, -4.0F, 1.0F, 4.0F, 1.0F, 0.0F, false, false, false, true, true, true, true); stock.setTextureOffset(40, 0).addBox(-1.5F, -5.8F, -3.0F, 12.0F, 10.0F, 1.0F, 0.0F, false, true, true, true, true, true, true); stock.setTextureOffset(125, 92).addBox(9.5F, -5.8F, -2.0F, 1.0F, 10.0F, 4.0F, 0.0F, false, false, true, true, true, true, true); stock.setTextureOffset(50, 115).addBox(-1.5F, -5.8F, -2.0F, 1.0F, 10.0F, 4.0F, 0.0F, false, false, true, true, true, true, true); stock.setTextureOffset(62, 32).addBox(8.0F, -22.0F, -1.0F, 1.0F, 25.0F, 1.0F, 0.0F, false, true, true, false, false, true, true); stock.setTextureOffset(58, 32).addBox(0.0F, -22.0F, -1.0F, 1.0F, 25.0F, 1.0F, 0.0F, false, true, true, false, false, true, true); cube_r3 = new ModelRenderer(this); cube_r3.setRotationPoint(9.0F, -25.5355F, -3.5355F); stock.addChild(cube_r3); setRotationAngle(cube_r3, -1.1868F, 0.0F, 0.0F); cube_r3.setTextureOffset(124, 32).addBox(-1.0F, 0.0F, 0.0F, 1.0F, 14.0F, 1.0F, 0.0F, false, true, true, false, false, true, true); cube_r3.setTextureOffset(128, 32).addBox(-9.0F, 0.0F, 0.0F, 1.0F, 14.0F, 1.0F, 0.0F, false, true, true, false, false, true, true); cube_r4 = new ModelRenderer(this); cube_r4.setRotationPoint(9.0F, -24.8284F, -4.2426F); stock.addChild(cube_r4); setRotationAngle(cube_r4, 0.7854F, 0.0F, 0.0F); cube_r4.setTextureOffset(90, 0).addBox(-1.0F, 0.0F, 0.0F, 1.0F, 5.0F, 1.0F, 0.0F, false, true, true, false, false, true, true); cube_r4.setTextureOffset(94, 0).addBox(-9.0F, 0.0F, 0.0F, 1.0F, 5.0F, 1.0F, 0.0F, false, true, true, false, false, true, true); cube_r5 = new ModelRenderer(this); cube_r5.setRotationPoint(0.0F, 0.0F, 0.0F); stock.addChild(cube_r5); setRotationAngle(cube_r5, -0.7854F, 0.0F, 0.0F); cube_r5.setTextureOffset(0, 0).addBox(0.0F, 0.0F, 0.0F, 1.0F, 3.0F, 3.0F, 0.0F, false, true, true, true, true, true, true); cube_r5.setTextureOffset(0, 9).addBox(8.0F, 0.0F, 0.0F, 1.0F, 3.0F, 3.0F, 0.0F, false, true, true, true, true, true, true); cube_r6 = new ModelRenderer(this); cube_r6.setRotationPoint(11.0F, 1.2F, 0.0F); stock.addChild(cube_r6); setRotationAngle(cube_r6, -0.7854F, 0.0F, 0.0F); cube_r6.setTextureOffset(34, 64).addBox(-13.0F, 0.0F, 0.0F, 13.0F, 1.0F, 1.0F, 0.0F, false, true, true, true, true, true, true); cube_r7 = new ModelRenderer(this); cube_r7.setRotationPoint(9.0F, -20.3639F, -24.1415F); stock.addChild(cube_r7); setRotationAngle(cube_r7, 0.0F, -0.5236F, 0.0F); cube_r7.setTextureOffset(10, 6).addBox(-3.0F, 0.0F, 0.0F, 3.0F, 1.0F, 1.0F, 0.0F, false, true, true, true, false, false, false); cube_r8 = new ModelRenderer(this); cube_r8.setRotationPoint(0.0F, -20.3639F, -24.1415F); stock.addChild(cube_r8); setRotationAngle(cube_r8, 0.0F, 0.5236F, 0.0F); cube_r8.setTextureOffset(0, 6).addBox(0.0F, 0.0F, 0.0F, 3.0F, 1.0F, 1.0F, 0.0F, false, true, true, true, true, false, false); slide2 = new ModelRenderer(this); slide2.setRotationPoint(4.3F, 25.0F, 48.1F); slide2.setTextureOffset(155, 491).addBox(-10.0F, 1.0F, -21.0F, 11.0F, 1.0F, 20.0F, 0.0F, false, false, false, true, false, false, false); slide2.setTextureOffset(347, 494).addBox(-10.0F, 1.0F, -1.0F, 11.0F, 10.0F, 8.0F, 0.0F, false, true, false, true, false, false, true); IS_2_r1 = new ModelRenderer(this); IS_2_r1.setRotationPoint(-3.2F, -2.0F, -18.1F); slide2.addChild(IS_2_r1); setRotationAngle(IS_2_r1, 0.0F, -0.7854F, 0.0F); IS_2_r1.setTextureOffset(25, 112).addBox(-2.5F, -1.6F, -1.0F, 3.0F, 3.0F, 3.0F, 0.0F, false, true, true, false, true, true, true); IS_1_r1 = new ModelRenderer(this); IS_1_r1.setRotationPoint(-4.6F, -0.1F, -18.1F); slide2.addChild(IS_1_r1); setRotationAngle(IS_1_r1, 0.0F, -0.7854F, 0.0F); IS_1_r1.setTextureOffset(58, 58).addBox(-0.5F, -0.6F, -1.0F, 1.0F, 2.0F, 1.0F, 0.0F, false, true, true, false, false, true, true); cube_r9 = new ModelRenderer(this); cube_r9.setRotationPoint(-8.0F, 0.2F, -21.0F); slide2.addChild(cube_r9); setRotationAngle(cube_r9, 0.0F, 0.0F, -0.6109F); cube_r9.setTextureOffset(262, 482).addBox(0.0F, 1.0F, 0.0F, 1.0F, 12.0F, 20.0F, 0.0F, false, true, true, false, false, true, true); safety = new ModelRenderer(this); safety.setRotationPoint(-4.1F, 46.0F, 19.1F); safety.setTextureOffset(52, 137).addBox(0.0F, -2.0F, 0.0F, 2.0F, 2.0F, 3.0F, 0.0F, false, false, false, false, true, true, true); cube_r10 = new ModelRenderer(this); cube_r10.setRotationPoint(0.0F, 0.0F, 3.0F); safety.addChild(cube_r10); setRotationAngle(cube_r10, 0.6981F, 0.0F, 0.0F); cube_r10.setTextureOffset(42, 137).addBox(0.0F, -2.0F, 0.0F, 2.0F, 2.0F, 3.0F, 0.0F, false, false, false, false, true, true, true); cube_r11 = new ModelRenderer(this); cube_r11.setRotationPoint(0.0F, 0.0F, 0.0F); safety.addChild(cube_r11); setRotationAngle(cube_r11, 0.8727F, 0.0F, 0.0F); cube_r11.setTextureOffset(0, 83).addBox(0.0F, -3.0F, 0.0F, 2.0F, 3.0F, 2.0F, 0.0F, false, true, false, false, false, true, true); body2 = new ModelRenderer(this); body2.setRotationPoint(0.5929F, 24.6F, -3.0F); body2.setTextureOffset(91, 17).addBox(-5.8858F, 0.0F, -1.0F, 4.0F, 1.0F, 66.0F, 0.0F, false, true, false, true, false, true, false); body2.setTextureOffset(88, 88).addBox(0.7F, 0.0F, -1.0F, 4.0F, 1.0F, 66.0F, 0.0F, false, true, false, true, false, false, true); body2.setTextureOffset(183, 177).addBox(5.1071F, 3.7071F, 7.0F, 1.0F, 1.0F, 45.0F, 0.0F, false, true, true, false, false, true, false); body2.setTextureOffset(78, 496).addBox(-6.2929F, 2.7F, 29.1F, 11.0F, 10.0F, 8.0F, 0.0F, false, true, true, true, false, true, true); body2.setTextureOffset(165, 0).addBox(5.1071F, 8.7071F, 7.0F, 1.0F, 1.0F, 45.0F, 0.0F, false, true, true, false, false, true, false); body2.setTextureOffset(20, 41).addBox(-2.0F, 0.0F, -1.0F, 3.0F, 1.0F, 20.0F, 0.0F, false, true, true, true, false, false, false); body2.setTextureOffset(0, 26).addBox(-5.5929F, 19.4F, 40.1F, 10.0F, 25.0F, 10.0F, 0.0F, false, false, true, false, true, true, true); body2.setTextureOffset(25, 122).addBox(-5.0929F, 36.2313F, 49.4309F, 9.0F, 8.0F, 7.0F, 0.0F, false, false, true, false, true, true, true); body2.setTextureOffset(90, 26).addBox(4.1071F, 36.7F, 43.1F, 1.0F, 7.0F, 3.0F, 0.0F, false, true, true, true, true, true, false); body2.setTextureOffset(44, 91).addBox(-6.2929F, 36.7F, 43.1F, 1.0F, 7.0F, 3.0F, 0.0F, false, true, true, true, true, false, true); body2.setTextureOffset(132, 26).addBox(-3.4716F, 17.4F, 37.9787F, 4.0F, 27.0F, 2.0F, 0.0F, false, true, false, false, true, false, false); body2.setTextureOffset(46, 32).addBox(-1.7142F, 17.4F, 37.9787F, 4.0F, 27.0F, 2.0F, 0.0F, false, true, false, false, true, false, false); body2.setTextureOffset(91, 135).addBox(-2.5929F, 19.1092F, 20.3546F, 4.0F, 7.0F, 1.0F, 0.0F, false, true, true, false, false, true, true); body2.setTextureOffset(0, 26).addBox(-2.5929F, 19.0F, 37.0F, 4.0F, 8.0F, 1.0F, 0.0F, false, true, false, false, false, true, true); body2.setTextureOffset(106, 84).addBox(-7.5929F, 13.4F, -0.9F, 14.0F, 6.0F, 2.0F, 0.0F, false, true, false, false, true, true, true); body2.setTextureOffset(32, 137).addBox(-7.0131F, 13.504F, -2.0F, 4.0F, 5.0F, 1.0F, 0.0F, false, true, false, false, false, false, true); body2.setTextureOffset(52, 104).addBox(1.8273F, 13.504F, -2.0F, 4.0F, 5.0F, 1.0F, 0.0F, false, true, false, false, false, true, false); body2.setTextureOffset(0, 0).addBox(-6.5929F, 0.7071F, -1.0F, 12.0F, 17.0F, 66.0F, 0.0F, false, true, false, false, false, true, true); body2.setTextureOffset(0, 83).addBox(-7.5929F, 11.4F, 1.1F, 14.0F, 8.0F, 63.0F, 0.0F, false, false, false, true, true, true, true); body2.setTextureOffset(52, 83).addBox(-2.5929F, 24.1071F, -2.2F, 4.0F, 20.0F, 1.0F, 0.0F, false, true, true, false, true, true, true); body2.setTextureOffset(0, 154).addBox(-3.5929F, 4.1071F, -2.0F, 6.0F, 20.0F, 1.0F, 0.0F, false, true, true, true, true, true, true); body2.setTextureOffset(0, 83).addBox(-7.5929F, -0.6F, 64.0F, 14.0F, 20.0F, 8.0F, 0.0F, false, false, true, true, true, true, true); body2.setTextureOffset(58, 17).addBox(-2.0929F, -4.4F, 71.0F, 3.0F, 4.0F, 1.0F, 0.0F, false, true, true, true, false, false, false); body2.setTextureOffset(104, 93).addBox(-2.0F, 0.0F, 49.0F, 3.0F, 1.0F, 15.0F, 0.0F, false, true, false, true, false, false, false); body2.setTextureOffset(488, 0).addBox(-4.0929F, -3.9F, -1.0F, 7.0F, 4.0F, 5.0F, 0.0F, false, true, true, true, false, true, true); body2.setTextureOffset(58, 22).addBox(-1.0929F, -2.9F, 1.0F, 1.0F, 3.0F, 1.0F, 0.0F, false, true, true, true, false, true, true); cube_r12 = new ModelRenderer(this); cube_r12.setRotationPoint(6.9071F, 14.4F, 34.1F); body2.addChild(cube_r12); setRotationAngle(cube_r12, -0.7854F, 0.0F, 0.0F); cube_r12.setTextureOffset(0, 62).addBox(-15.0F, 0.0F, 0.0F, 15.0F, 2.0F, 2.0F, 0.0F, false, true, true, true, true, true, true); cube_r13 = new ModelRenderer(this); cube_r13.setRotationPoint(0.4071F, 19.0092F, 34.2546F); body2.addChild(cube_r13); setRotationAngle(cube_r13, -0.2182F, 0.0F, 0.0F); cube_r13.setTextureOffset(132, 55).addBox(-3.0F, 0.0F, -1.0F, 4.0F, 7.0F, 1.0F, 0.0F, false, true, true, false, true, true, true); cube_r14 = new ModelRenderer(this); cube_r14.setRotationPoint(6.9071F, 13.4F, 63.1F); body2.addChild(cube_r14); setRotationAngle(cube_r14, -0.7854F, 0.0F, 0.0F); cube_r14.setTextureOffset(32, 62).addBox(-15.0F, 1.0F, 0.0F, 15.0F, 1.0F, 1.0F, 0.0F, false, true, true, true, true, true, true); cube_r15 = new ModelRenderer(this); cube_r15.setRotationPoint(6.9071F, 14.4F, 5.1F); body2.addChild(cube_r15); setRotationAngle(cube_r15, -0.7854F, 0.0F, 0.0F); cube_r15.setTextureOffset(118, 112).addBox(-15.0F, 0.0F, 0.0F, 15.0F, 2.0F, 2.0F, 0.0F, false, true, true, true, true, true, true); cube_r16 = new ModelRenderer(this); cube_r16.setRotationPoint(-4.7608F, 1.7549F, 72.0F); body2.addChild(cube_r16); setRotationAngle(cube_r16, 0.0F, 0.0F, 2.4435F); cube_r16.setTextureOffset(30, 32).addBox(-6.0F, 0.0F, -1.0F, 6.0F, 3.0F, 1.0F, 0.0F, false, true, true, false, true, false, false); cube_r17 = new ModelRenderer(this); cube_r17.setRotationPoint(5.5034F, -0.5433F, 72.0F); body2.addChild(cube_r17); setRotationAngle(cube_r17, 0.0F, 0.0F, 0.6981F); cube_r17.setTextureOffset(7, 129).addBox(-6.0F, 0.0F, -1.0F, 6.0F, 3.0F, 1.0F, 0.0F, false, true, true, true, false, false, false); cube_r18 = new ModelRenderer(this); cube_r18.setRotationPoint(6.4071F, -0.6F, 64.0F); body2.addChild(cube_r18); setRotationAngle(cube_r18, -0.7418F, 0.0F, 0.0F); cube_r18.setTextureOffset(90, 0).addBox(-14.0F, 0.0F, 0.0F, 14.0F, 17.0F, 9.0F, 0.0F, false, true, false, false, false, true, true); cube_r19 = new ModelRenderer(this); cube_r19.setRotationPoint(-1.5929F, 22.1071F, -1.6F); body2.addChild(cube_r19); setRotationAngle(cube_r19, -0.7854F, 0.0F, 0.0F); cube_r19.setTextureOffset(106, 92).addBox(-1.0F, 0.0F, 0.0F, 4.0F, 2.0F, 2.0F, 0.0F, false, true, true, true, true, true, true); cube_r20 = new ModelRenderer(this); cube_r20.setRotationPoint(-0.5929F, 7.3071F, -4.0F); body2.addChild(cube_r20); setRotationAngle(cube_r20, 0.0F, 0.0F, 0.7854F); cube_r20.setTextureOffset(36, 83).addBox(-2.0F, -2.0F, 0.0F, 6.0F, 6.0F, 2.0F, 0.0F, false, true, false, true, true, true, true); cube_r21 = new ModelRenderer(this); cube_r21.setRotationPoint(-1.3517F, 5.4752F, -1.0F); body2.addChild(cube_r21); setRotationAngle(cube_r21, 0.0F, 0.0F, -0.3491F); cube_r21.setTextureOffset(91, 84).addBox(0.0F, 0.0F, -1.0F, 4.0F, 10.0F, 1.0F, 0.0F, false, true, false, false, false, true, false); cube_r22 = new ModelRenderer(this); cube_r22.setRotationPoint(-3.5929F, 4.1071F, -1.0F); body2.addChild(cube_r22); setRotationAngle(cube_r22, 0.0F, 0.0F, 0.3491F); cube_r22.setTextureOffset(91, 108).addBox(0.0F, 0.0F, -1.0F, 4.0F, 10.0F, 1.0F, 0.0F, false, true, false, false, false, false, true); cube_r23 = new ModelRenderer(this); cube_r23.setRotationPoint(2.9989F, 15.6756F, -1.0F); body2.addChild(cube_r23); setRotationAngle(cube_r23, 0.0F, 0.0F, 0.7854F); cube_r23.setTextureOffset(10, 0).addBox(1.0F, 0.0F, -1.0F, 3.0F, 5.0F, 1.0F, 0.0F, false, true, true, false, false, true, false); cube_r24 = new ModelRenderer(this); cube_r24.setRotationPoint(-7.0131F, 18.504F, -1.0F); body2.addChild(cube_r24); setRotationAngle(cube_r24, 0.0F, 0.0F, -0.7854F); cube_r24.setTextureOffset(10, 9).addBox(0.0F, 0.0F, -1.0F, 3.0F, 5.0F, 1.0F, 0.0F, false, true, true, false, false, false, true); cube_r25 = new ModelRenderer(this); cube_r25.setRotationPoint(6.4071F, 11.4F, 1.1F); body2.addChild(cube_r25); setRotationAngle(cube_r25, -0.7854F, 0.0F, 0.0F); cube_r25.setTextureOffset(0, 137).addBox(-14.0F, 0.0F, 0.0F, 14.0F, 3.0F, 2.0F, 0.0F, false, true, false, false, false, true, true); cube_r26 = new ModelRenderer(this); cube_r26.setRotationPoint(0.4071F, 26.1092F, 21.7688F); body2.addChild(cube_r26); setRotationAngle(cube_r26, -0.7854F, 0.0F, 0.0F); cube_r26.setTextureOffset(114, 26).addBox(-3.0F, 0.0F, -1.0F, 4.0F, 1.0F, 5.0F, 0.0F, false, false, false, true, true, true, true); cube_r27 = new ModelRenderer(this); cube_r27.setRotationPoint(0.4071F, 28.1223F, 35.8351F); body2.addChild(cube_r27); setRotationAngle(cube_r27, 0.0436F, 0.0F, 0.0F); cube_r27.setTextureOffset(112, 51).addBox(-3.0F, 0.0F, -12.0F, 4.0F, 1.0F, 12.0F, 0.0F, false, false, false, true, true, true, true); cube_r28 = new ModelRenderer(this); cube_r28.setRotationPoint(0.4071F, 27.0F, 38.0F); body2.addChild(cube_r28); setRotationAngle(cube_r28, -0.7854F, 0.0F, 0.0F); cube_r28.setTextureOffset(114, 32).addBox(-3.0F, 0.0F, -1.0F, 4.0F, 3.0F, 1.0F, 0.0F, false, true, true, false, false, true, true); cube_r29 = new ModelRenderer(this); cube_r29.setRotationPoint(-3.4716F, 36.4F, 37.9787F); body2.addChild(cube_r29); setRotationAngle(cube_r29, 0.0F, -0.7854F, 0.0F); cube_r29.setTextureOffset(140, 84).addBox(0.0F, -17.0F, 0.0F, 3.0F, 25.0F, 3.0F, 0.0F, false, false, false, false, true, false, true); cube_r30 = new ModelRenderer(this); cube_r30.setRotationPoint(2.2858F, 36.4F, 37.9787F); body2.addChild(cube_r30); setRotationAngle(cube_r30, 0.0F, -0.7854F, 0.0F); cube_r30.setTextureOffset(142, 0).addBox(0.0F, -17.0F, 0.0F, 3.0F, 25.0F, 3.0F, 0.0F, false, true, false, false, true, false, false); cube_r31 = new ModelRenderer(this); cube_r31.setRotationPoint(-5.0929F, 27.538F, 54.1015F); body2.addChild(cube_r31); setRotationAngle(cube_r31, 0.2618F, 0.0F, 0.0F); cube_r31.setTextureOffset(0, 111).addBox(0.0F, -2.0F, -7.0F, 9.0F, 11.0F, 7.0F, 0.0F, false, false, true, false, false, true, true); cube_r32 = new ModelRenderer(this); cube_r32.setRotationPoint(-7.0929F, 42.8163F, 58.1296F); body2.addChild(cube_r32); setRotationAngle(cube_r32, -0.7854F, 0.0F, 0.0F); cube_r32.setTextureOffset(37, 115).addBox(4.0F, 0.0603F, -2.342F, 5.0F, 2.0F, 2.0F, 0.0F, false, false, true, true, false, true, true); cube_r33 = new ModelRenderer(this); cube_r33.setRotationPoint(-5.0929F, 22.6139F, 54.2698F); body2.addChild(cube_r33); setRotationAngle(cube_r33, -0.1745F, 0.0F, 0.0F); cube_r33.setTextureOffset(117, 130).addBox(0.0F, 0.0F, -6.0F, 9.0F, 5.0F, 6.0F, 0.0F, false, false, true, false, false, true, true); cube_r34 = new ModelRenderer(this); cube_r34.setRotationPoint(-5.0929F, 19.4F, 58.1F); body2.addChild(cube_r34); setRotationAngle(cube_r34, -0.8727F, 0.0F, 0.0F); cube_r34.setTextureOffset(123, 116).addBox(0.0F, 0.0F, -6.0F, 9.0F, 8.0F, 6.0F, 0.0F, false, false, true, false, false, true, true); cube_r35 = new ModelRenderer(this); cube_r35.setRotationPoint(5.4F, 9.0F, 8.0F); body2.addChild(cube_r35); setRotationAngle(cube_r35, 0.0F, 0.0F, 0.7854F); cube_r35.setTextureOffset(136, 155).addBox(0.0F, 0.0F, -1.0F, 1.0F, 1.0F, 45.0F, 0.0F, false, true, true, false, false, true, false); cube_r36 = new ModelRenderer(this); cube_r36.setRotationPoint(5.4F, 8.0F, 8.0F); body2.addChild(cube_r36); setRotationAngle(cube_r36, 0.0F, 0.0F, 0.7854F); cube_r36.setTextureOffset(162, 84).addBox(0.0F, 0.0F, -1.0F, 1.0F, 1.0F, 45.0F, 0.0F, false, true, true, true, false, false, false); cube_r37 = new ModelRenderer(this); cube_r37.setRotationPoint(5.4F, 4.0F, 8.0F); body2.addChild(cube_r37); setRotationAngle(cube_r37, 0.0F, 0.0F, 0.7854F); cube_r37.setTextureOffset(183, 130).addBox(0.0F, 0.0F, -1.0F, 1.0F, 1.0F, 45.0F, 0.0F, false, true, true, false, false, true, false); cube_r38 = new ModelRenderer(this); cube_r38.setRotationPoint(5.4F, 3.0F, 8.0F); body2.addChild(cube_r38); setRotationAngle(cube_r38, 0.0F, 0.0F, 0.7854F); cube_r38.setTextureOffset(209, 46).addBox(0.0F, 0.0F, -1.0F, 1.0F, 1.0F, 45.0F, 0.0F, false, true, true, true, false, false, false); cube_r39 = new ModelRenderer(this); cube_r39.setRotationPoint(3.9929F, 0.7071F, -1.0F); body2.addChild(cube_r39); setRotationAngle(cube_r39, 0.0F, 0.0F, -0.7854F); cube_r39.setTextureOffset(0, 154).addBox(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 66.0F, 0.0F, false, true, false, false, false, true, false); cube_r40 = new ModelRenderer(this); cube_r40.setRotationPoint(-6.5929F, 0.7071F, -1.0F); body2.addChild(cube_r40); setRotationAngle(cube_r40, 0.0F, 0.0F, -0.7854F); cube_r40.setTextureOffset(68, 155).addBox(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 66.0F, 0.0F, false, true, false, true, false, false, false); charge = new ModelRenderer(this); charge.setRotationPoint(0.0F, 24.0F, 0.0F); cube_r41 = new ModelRenderer(this); cube_r41.setRotationPoint(7.5F, 13.4F, 13.1F); charge.addChild(cube_r41); setRotationAngle(cube_r41, -0.7854F, 0.0F, 0.0F); cube_r41.setTextureOffset(30, 26).addBox(-15.0F, -1.0F, 0.0F, 15.0F, 3.0F, 3.0F, 0.0F, false, true, true, true, true, true, true); cube_r42 = new ModelRenderer(this); cube_r42.setRotationPoint(8.2F, 14.8F, 14.2F); charge.addChild(cube_r42); setRotationAngle(cube_r42, 0.0F, 0.0F, 0.7854F); cube_r42.setTextureOffset(101, 135).addBox(-1.0F, 0.0F, 0.0F, 1.0F, 1.0F, 5.0F, 0.0F, false, true, true, true, true, true, true); } @Override public void setRotationAngles(Entity entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch){ //previously the render function, render code was moved to a method below } @Override public void render(MatrixStack matrixStack, IVertexBuilder buffer, int packedLight, int packedOverlay, float red, float green, float blue, float alpha){ } public void setRotationAngle(ModelRenderer modelRenderer, float x, float y, float z) { modelRenderer.rotateAngleX = x; modelRenderer.rotateAngleY = y; modelRenderer.rotateAngleZ = z; } @Override
public void render(MatrixStack matrixStack, IVertexBuilder buffer, ItemCameraTransforms.TransformType transformType, int packedLight, int packedOverlay, float red, float green, float blue, float alpha, int bulletLeft, long lastFireTime, boolean mainHand, int fireMode, GunRenderContext context, long fireDis) {
2
2023-11-14 14:00:55+00:00
16k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/utils/tasks/SignAPK.java
[ { "identifier": "APKTasksActivity", "path": "app/src/main/java/com/threethan/questpatcher/activities/APKTasksActivity.java", "snippet": "public class APKTasksActivity extends AppCompatActivity {\n\n private AppCompatImageView mIcon;\n private ProgressBar mProgress;\n private View mCancel, mDeta...
import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.util.Log; import com.threethan.questpatcher.R; import com.threethan.questpatcher.activities.APKTasksActivity; import com.threethan.questpatcher.utils.APKData; import com.threethan.questpatcher.utils.APKEditorUtils; import com.threethan.questpatcher.utils.Common; import com.threethan.questpatcher.utils.InvalidZipException; import com.threethan.questpatcher.utils.SplitAPKInstaller; import com.threethan.questpatcher.utils.ZipAlign; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import in.sunilpaulmathew.sCommon.CommonUtils.sExecutor; import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils; import in.sunilpaulmathew.sCommon.PackageUtils.sPackageUtils;
12,247
package com.threethan.questpatcher.utils.tasks; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on January 28, 2023 */ public class SignAPK extends sExecutor { private final Activity mActivity; private File mBackUpPath = null, mBuildDir = null, mExportPath = null, mTMPZip = null; private File mParent; public SignAPK(Activity activity) { mActivity = activity; } @SuppressLint("StringFormatInvalid") @Override public void onPreExecute() { mExportPath = new File(mActivity.getCacheDir(), Common.getAppID()); mTMPZip = new File(mActivity.getCacheDir(), "tmp.apk"); Common.setFinishStatus(false); Common.isCancelled(false); Common.isBuilding(true); Common.setStatus(null); Intent apkTasks = new Intent(mActivity, APKTasksActivity.class); mActivity.startActivity(apkTasks); Common.setStatus(mActivity.getString(R.string.preparing_apk, Common.getAppID())); mBuildDir = new File(mExportPath, ".aeeBuild"); mBackUpPath = new File(mExportPath, ".aeeBackup"); if (mBuildDir.exists()) { sFileUtils.delete(mBuildDir); } sFileUtils.mkdir(mBuildDir); if (mTMPZip.exists()) { sFileUtils.delete(mTMPZip); } } List<String> apks = new ArrayList<>(); @SuppressLint("StringFormatInvalid") @Override public void doInBackground() { Common.setStatus(mActivity.getString(R.string.preparing_source)); APKData.prepareSource(mBuildDir, mExportPath, mBackUpPath, mActivity); if (Common.getError() > 0) { return; } APKEditorUtils.zip(mBuildDir, mTMPZip); Common.setStatus(mActivity.getString(R.string.zip_aligning)); try { RandomAccessFile apkUnaligned = new RandomAccessFile(mTMPZip, "r"); FileOutputStream apkAligned = new FileOutputStream(new File(mActivity.getCacheDir(), "tmp_zipAligned.apk")); ZipAlign.alignZip(apkUnaligned, apkAligned);
package com.threethan.questpatcher.utils.tasks; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on January 28, 2023 */ public class SignAPK extends sExecutor { private final Activity mActivity; private File mBackUpPath = null, mBuildDir = null, mExportPath = null, mTMPZip = null; private File mParent; public SignAPK(Activity activity) { mActivity = activity; } @SuppressLint("StringFormatInvalid") @Override public void onPreExecute() { mExportPath = new File(mActivity.getCacheDir(), Common.getAppID()); mTMPZip = new File(mActivity.getCacheDir(), "tmp.apk"); Common.setFinishStatus(false); Common.isCancelled(false); Common.isBuilding(true); Common.setStatus(null); Intent apkTasks = new Intent(mActivity, APKTasksActivity.class); mActivity.startActivity(apkTasks); Common.setStatus(mActivity.getString(R.string.preparing_apk, Common.getAppID())); mBuildDir = new File(mExportPath, ".aeeBuild"); mBackUpPath = new File(mExportPath, ".aeeBackup"); if (mBuildDir.exists()) { sFileUtils.delete(mBuildDir); } sFileUtils.mkdir(mBuildDir); if (mTMPZip.exists()) { sFileUtils.delete(mTMPZip); } } List<String> apks = new ArrayList<>(); @SuppressLint("StringFormatInvalid") @Override public void doInBackground() { Common.setStatus(mActivity.getString(R.string.preparing_source)); APKData.prepareSource(mBuildDir, mExportPath, mBackUpPath, mActivity); if (Common.getError() > 0) { return; } APKEditorUtils.zip(mBuildDir, mTMPZip); Common.setStatus(mActivity.getString(R.string.zip_aligning)); try { RandomAccessFile apkUnaligned = new RandomAccessFile(mTMPZip, "r"); FileOutputStream apkAligned = new FileOutputStream(new File(mActivity.getCacheDir(), "tmp_zipAligned.apk")); ZipAlign.alignZip(apkUnaligned, apkAligned);
} catch (IOException | InvalidZipException e) {
4
2023-11-18 15:13:30+00:00
16k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/system/service/impl/UserServiceImpl.java
[ { "identifier": "FileProperties", "path": "dimple-common/src/main/java/com/dimple/config/FileProperties.java", "snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"file\")\npublic class FileProperties {\n\n /**\n * 文件大小限制\n */\n private Long maxSize;\n\n /**\n * 头像...
import com.dimple.config.FileProperties; import com.dimple.exception.EntityExistException; import com.dimple.exception.EntityNotFoundException; import com.dimple.modules.system.domain.User; import com.dimple.modules.system.repository.UserRepository; import com.dimple.modules.system.service.UserService; import com.dimple.modules.system.service.dto.JobSmallDto; import com.dimple.modules.system.service.dto.RoleSmallDTO; import com.dimple.modules.system.service.dto.UserDTO; import com.dimple.modules.system.service.dto.UserQueryCriteria; import com.dimple.modules.system.service.mapstruct.UserMapper; import com.dimple.utils.FileUtil; import com.dimple.utils.PageUtil; import com.dimple.utils.QueryHelp; import com.dimple.utils.RedisUtils; import com.dimple.utils.SecurityUtils; import com.dimple.utils.StringUtils; import com.dimple.utils.ValidationUtil; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors;
13,755
package com.dimple.modules.system.service.impl; /** * @className: UserServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "user") public class UserServiceImpl implements UserService { private final UserRepository userRepository; private final UserMapper userMapper; private final FileProperties properties; private final RedisUtils redisUtils; @Override public Object queryAll(UserQueryCriteria criteria, Pageable pageable) {
package com.dimple.modules.system.service.impl; /** * @className: UserServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "user") public class UserServiceImpl implements UserService { private final UserRepository userRepository; private final UserMapper userMapper; private final FileProperties properties; private final RedisUtils redisUtils; @Override public Object queryAll(UserQueryCriteria criteria, Pageable pageable) {
Page<User> page = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
13
2023-11-10 03:30:36+00:00
16k
LazyCoder0101/LazyCoder
ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/moduleedit/commandinput/moduleinit/functionname/ModuleFuncitonNameTable.java
[ { "identifier": "FunctionNameData", "path": "database/src/main/java/com/lazycoder/database/model/FunctionNameData.java", "snippet": "@NoArgsConstructor\n@Data\npublic class FunctionNameData implements DataFormatType {\n\n /**\n * 方法名类型\n */\n private int functionNameProperty;\n\n privat...
import com.lazycoder.database.model.FunctionNameData; import com.lazycoder.database.model.Module; import com.lazycoder.database.model.ModuleInfo; import com.lazycoder.service.service.SysService; import com.lazycoder.service.service.impl.FunctionNameDataServiceImpl; import com.lazycoder.service.vo.AttributeUsageRange; import com.lazycoder.uidatasourceedit.DataSourceEditHolder; import com.lazycoder.uidatasourceedit.component.codeintput.intputscutcheon.labelscutcheon.control.VariableUsageRangeCombobox; import com.lazycoder.uidatasourceedit.component.component.table.functionname.AbstractFunctionTable; import com.lazycoder.uidatasourceedit.moduleedit.CheckInterface; import com.lazycoder.uidatasourceedit.moduleedit.ModuleEditComponentInterface; import java.util.ArrayList; import java.util.List; import javax.swing.DefaultComboBoxModel;
11,551
package com.lazycoder.uidatasourceedit.moduleedit.commandinput.moduleinit.functionname; public class ModuleFuncitonNameTable extends AbstractFunctionTable implements CheckInterface, ModuleEditComponentInterface { /** * */ private static final long serialVersionUID = -6449178917706136513L; private final FunctionNameDataServiceImpl functionNameDataServiceImpl = SysService.FUNCTION_NAME_DATA_SERVICE; /** * 获取录入模块的方法名 * * @return */ public ArrayList<FunctionNameData> getFunctionNameDataList() { ArrayList<FunctionNameData> list = getFunctionNameDataList(FunctionNameData.MODULE_TYPE); for (FunctionNameData variableData : list) {
package com.lazycoder.uidatasourceedit.moduleedit.commandinput.moduleinit.functionname; public class ModuleFuncitonNameTable extends AbstractFunctionTable implements CheckInterface, ModuleEditComponentInterface { /** * */ private static final long serialVersionUID = -6449178917706136513L; private final FunctionNameDataServiceImpl functionNameDataServiceImpl = SysService.FUNCTION_NAME_DATA_SERVICE; /** * 获取录入模块的方法名 * * @return */ public ArrayList<FunctionNameData> getFunctionNameDataList() { ArrayList<FunctionNameData> list = getFunctionNameDataList(FunctionNameData.MODULE_TYPE); for (FunctionNameData variableData : list) {
variableData.setModuleId(DataSourceEditHolder.currentModule.getModuleId());
6
2023-11-16 11:55:06+00:00
16k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/ksx4506/KSDoorLock.java
[ { "identifier": "ByteArrayBuffer", "path": "app/src/main/java/kr/or/kashi/hde/base/ByteArrayBuffer.java", "snippet": "public final class ByteArrayBuffer {\n private static final int INITIAL_CAPACITY = 16;\n private static final int CAPACITY_INCREMENT = 8;\n\n private byte[] mBuffer;\n privat...
import android.util.Log; import kr.or.kashi.hde.base.ByteArrayBuffer; import kr.or.kashi.hde.base.PropertyMap; import kr.or.kashi.hde.MainContext; import kr.or.kashi.hde.HomeDevice; import kr.or.kashi.hde.base.PropertyTask; import kr.or.kashi.hde.device.Curtain; import kr.or.kashi.hde.device.DoorLock; import kr.or.kashi.hde.ksx4506.KSDeviceContextBase; import kr.or.kashi.hde.ksx4506.KSPacket; import java.util.Map;
13,971
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.ksx4506; /** * [KS X 4506] The door lock implementation for DoorLock */ public class KSDoorLock extends KSDeviceContextBase { private static final String TAG = "KSDoorLock"; private static final boolean DBG = true; private static boolean mForceReleaseSupported = false; public KSDoorLock(MainContext mainContext, Map defaultProps) { super(mainContext, defaultProps, DoorLock.class); // Register the tasks to be performed when specific property changes.
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.ksx4506; /** * [KS X 4506] The door lock implementation for DoorLock */ public class KSDoorLock extends KSDeviceContextBase { private static final String TAG = "KSDoorLock"; private static final boolean DBG = true; private static boolean mForceReleaseSupported = false; public KSDoorLock(MainContext mainContext, Map defaultProps) { super(mainContext, defaultProps, DoorLock.class); // Register the tasks to be performed when specific property changes.
final PropertyTask controlTask = this::onDoorLockControlTask;
4
2023-11-10 01:19:44+00:00
16k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/client/ui/pluginMenu/MainMenuButton.java
[ { "identifier": "ScreenWidget", "path": "src/main/java/io/xlorey/FluxLoader/client/ui/ScreenWidget.java", "snippet": "public class ScreenWidget implements IWidget {\n /**\n * Flag indicating whether the mouse cursor is inside the widget\n */\n private boolean isWidgetHovered = false;\n\n ...
import imgui.ImGui; import imgui.ImVec2; import imgui.flag.ImGuiCol; import imgui.flag.ImGuiStyleVar; import imgui.flag.ImGuiWindowFlags; import imgui.type.ImBoolean; import io.xlorey.FluxLoader.client.ui.ScreenWidget; import io.xlorey.FluxLoader.utils.Constants; import zombie.GameWindow; import zombie.core.Core; import zombie.gameStates.MainScreenState;
12,462
package io.xlorey.FluxLoader.client.ui.pluginMenu; /** * Implementation of a button to open the plugin control panel */ public class MainMenuButton extends ScreenWidget { /** * Button width */ private final int width = 112; /** * Button height */ private final int height = 26; /** * Horizontal button position */ private int posX = 0; /** * Vertical position of the button */ private int posY = 0; /** * Update button state */ @Override public void update() { super.update();
package io.xlorey.FluxLoader.client.ui.pluginMenu; /** * Implementation of a button to open the plugin control panel */ public class MainMenuButton extends ScreenWidget { /** * Button width */ private final int width = 112; /** * Button height */ private final int height = 26; /** * Horizontal button position */ private int posX = 0; /** * Vertical position of the button */ private int posY = 0; /** * Update button state */ @Override public void update() { super.update();
setVisible(GameWindow.states.current instanceof MainScreenState);
2
2023-11-16 09:05:44+00:00
16k
EmonerRobotics/2023Robot
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "IntakeConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class IntakeConstants{\n\n public static final double kEncoderTick2Meter = 1.0 / 4096.0 * 0.1 * Math.PI;\n\n //üst sistem joystick sabitleri\n public static final int Joystick2 = 1; //usb por...
import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab; import edu.wpi.first.wpilibj.smartdashboard.Field2d; import edu.wpi.first.wpilibj.smartdashboard.FieldObject2d; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.RunCommand; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import edu.wpi.first.wpilibj2.command.button.JoystickButton; import frc.robot.Constants.IntakeConstants; import frc.robot.commands.AutoElevator; import frc.robot.commands.AutoIntake; import frc.robot.commands.DriveWithJoysticks; import frc.robot.commands.GetInRange; import frc.robot.commands.IntakeCommand; import frc.robot.commands.LiftCommand; import frc.robot.commands.PneumaticCommand; import frc.robot.commands.AutoElevator.ElevatorPosition; import frc.robot.commands.AutoIntake.IntakePosition; import frc.robot.commands.GetInRange.LimelightPositionCheck; import frc.robot.commands.autonomous.AutoBalance; import frc.robot.commands.autonomous.AutoCommand; import frc.robot.commands.autonomous.OnePieceCharge; import frc.robot.poseestimation.PoseEstimation; import frc.robot.subsystems.IntakeSubsystem; import frc.robot.subsystems.LiftSubsystem; import frc.robot.subsystems.LimelightSubsystem; import frc.robot.subsystems.PneumaticSubsystem; import frc.robot.subsystems.drivetrain.Drivetrain; import frc.robot.utils.AllianceUtils; import com.pathplanner.lib.server.PathPlannerServer;
10,879
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { //Limelight public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem(); //Intake public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); //Pneumatic public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem(); //Lift public static final LiftSubsystem liftSubsystem = new LiftSubsystem(); public static final ShuffleboardTab driveSettingsTab = Shuffleboard.getTab("Drive Settings"); public static final ShuffleboardTab autoTab = Shuffleboard.getTab("Auto"); public static final ShuffleboardTab swerveTab = Shuffleboard.getTab("Swerve"); public static final Joystick joystick1 = new Joystick(0); public static final Joystick joystick2 = new Joystick(IntakeConstants.AngleController); public static final Drivetrain drivetrain = new Drivetrain(); public static final PoseEstimation poseEstimation = new PoseEstimation(); public static final SendableChooser<String> drivePresetsChooser = new SendableChooser<>(); public static Field2d field = new Field2d(); public static Field2d nodeSelector = new Field2d(); private final FieldObject2d startingPosition = field.getObject("Starting Position"); private final FieldObject2d autoBalanceStartingPosition = field.getObject("Auto Balance Starting Position"); private DriveWithJoysticks driveCommand = new DriveWithJoysticks(drivetrain, poseEstimation, joystick1); private AutoBalance autoBalanceCommand = new AutoBalance(drivetrain); public static SendableChooser<String> autoSelector; //private static AutoElevator autoElevator; /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { //autoElevator = new AutoElevator(liftSubsystem, 0); //Intake intakeSubsystem.setDefaultCommand(new IntakeCommand(intakeSubsystem, () -> -joystick2.getRawAxis(IntakeConstants.AngleController))); //Pneumatic //pneumaticSubsystem.setDefaultCommand(new PneumaticCommand(pneumaticSubsystem, false, true)); //Lift liftSubsystem.setDefaultCommand(new LiftCommand(liftSubsystem, () -> -joystick2.getRawAxis(5))); if (!DriverStation.isFMSAttached()) { PathPlannerServer.startServer(5811); } drivetrain.setDefaultCommand(driveCommand); if (autoBalanceStartingPosition.getPoses().isEmpty()) {
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { //Limelight public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem(); //Intake public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); //Pneumatic public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem(); //Lift public static final LiftSubsystem liftSubsystem = new LiftSubsystem(); public static final ShuffleboardTab driveSettingsTab = Shuffleboard.getTab("Drive Settings"); public static final ShuffleboardTab autoTab = Shuffleboard.getTab("Auto"); public static final ShuffleboardTab swerveTab = Shuffleboard.getTab("Swerve"); public static final Joystick joystick1 = new Joystick(0); public static final Joystick joystick2 = new Joystick(IntakeConstants.AngleController); public static final Drivetrain drivetrain = new Drivetrain(); public static final PoseEstimation poseEstimation = new PoseEstimation(); public static final SendableChooser<String> drivePresetsChooser = new SendableChooser<>(); public static Field2d field = new Field2d(); public static Field2d nodeSelector = new Field2d(); private final FieldObject2d startingPosition = field.getObject("Starting Position"); private final FieldObject2d autoBalanceStartingPosition = field.getObject("Auto Balance Starting Position"); private DriveWithJoysticks driveCommand = new DriveWithJoysticks(drivetrain, poseEstimation, joystick1); private AutoBalance autoBalanceCommand = new AutoBalance(drivetrain); public static SendableChooser<String> autoSelector; //private static AutoElevator autoElevator; /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { //autoElevator = new AutoElevator(liftSubsystem, 0); //Intake intakeSubsystem.setDefaultCommand(new IntakeCommand(intakeSubsystem, () -> -joystick2.getRawAxis(IntakeConstants.AngleController))); //Pneumatic //pneumaticSubsystem.setDefaultCommand(new PneumaticCommand(pneumaticSubsystem, false, true)); //Lift liftSubsystem.setDefaultCommand(new LiftCommand(liftSubsystem, () -> -joystick2.getRawAxis(5))); if (!DriverStation.isFMSAttached()) { PathPlannerServer.startServer(5811); } drivetrain.setDefaultCommand(driveCommand); if (autoBalanceStartingPosition.getPoses().isEmpty()) {
autoBalanceStartingPosition.setPose(AllianceUtils.allianceToField(new Pose2d(new Translation2d(0,0),new Rotation2d())));
20
2023-11-18 14:02:20+00:00
16k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/core/items/types/end/armor/SuperiorChestplate.java
[ { "identifier": "SkyblockPlayerDamageEntityEvent", "path": "src/main/java/com/sweattypalms/skyblock/core/events/def/SkyblockPlayerDamageEntityEvent.java", "snippet": "public class SkyblockPlayerDamageEntityEvent extends SkyblockPlayerEvent implements Cancellable {\n private static final HandlerList H...
import com.sweattypalms.skyblock.core.events.def.SkyblockPlayerDamageEntityEvent; import com.sweattypalms.skyblock.core.items.builder.Rarity; import com.sweattypalms.skyblock.core.items.builder.SkyblockItem; import com.sweattypalms.skyblock.core.items.builder.SkyblockItemType; import com.sweattypalms.skyblock.core.items.builder.abilities.Ability; import com.sweattypalms.skyblock.core.items.builder.abilities.IHasAbility; import com.sweattypalms.skyblock.core.items.builder.abilities.types.FullSetBonus; import com.sweattypalms.skyblock.core.items.builder.abilities.types.PassiveAbility; import com.sweattypalms.skyblock.core.items.builder.armor.IDyedArmor; import com.sweattypalms.skyblock.core.items.types.end.items.AspectOfTheDragons; import com.sweattypalms.skyblock.core.player.SkyblockPlayer; import com.sweattypalms.skyblock.core.player.sub.stats.Stats; import com.sweattypalms.skyblock.core.player.sub.stats.StatsManager; import org.bukkit.Material; import org.bukkit.event.Event; import org.bukkit.inventory.ItemStack; import java.util.*;
11,376
package com.sweattypalms.skyblock.core.items.types.end.armor; public class SuperiorChestplate extends SkyblockItem implements IHasAbility, IDyedArmor { public static final String ID = "superior_dragon_chestplate"; private static final Map<Stats, Double> stats = new HashMap<>(Map.of( Stats.HEALTH, 150d, Stats.DEFENSE, 190d, Stats.SPEED, 3d, Stats.STRENGTH, 10d, Stats.INTELLIGENCE, 25d, Stats.CRIT_CHANCE, 2d, Stats.CRIT_DAMAGE, 10d )); public SuperiorChestplate() { super( ID, "Superior Dragon Chestplate", Material.LEATHER_CHESTPLATE, null, stats,
package com.sweattypalms.skyblock.core.items.types.end.armor; public class SuperiorChestplate extends SkyblockItem implements IHasAbility, IDyedArmor { public static final String ID = "superior_dragon_chestplate"; private static final Map<Stats, Double> stats = new HashMap<>(Map.of( Stats.HEALTH, 150d, Stats.DEFENSE, 190d, Stats.SPEED, 3d, Stats.STRENGTH, 10d, Stats.INTELLIGENCE, 25d, Stats.CRIT_CHANCE, 2d, Stats.CRIT_DAMAGE, 10d )); public SuperiorChestplate() { super( ID, "Superior Dragon Chestplate", Material.LEATHER_CHESTPLATE, null, stats,
Rarity.LEGENDARY,
1
2023-11-15 15:05:58+00:00
16k
HanGyeolee/AndroidPdfWriter
android-pdf-writer/src/androidTest/java/com/hangyeolee/androidpdfwriter/PDFTableTest.java
[ { "identifier": "PDFGridLayout", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/components/PDFGridLayout.java", "snippet": "public class PDFGridLayout extends PDFLayout{\n int rows, columns;\n\n ArrayList<Integer> span;\n\n final int[] gaps;\n final Rect childMargi...
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.hangyeolee.androidpdfwriter.components.PDFGridLayout; import com.hangyeolee.androidpdfwriter.components.PDFH1; import com.hangyeolee.androidpdfwriter.components.PDFH3; import com.hangyeolee.androidpdfwriter.components.PDFImage; import com.hangyeolee.androidpdfwriter.components.PDFLinearLayout; import com.hangyeolee.androidpdfwriter.utils.Anchor; import com.hangyeolee.androidpdfwriter.utils.DPI; import com.hangyeolee.androidpdfwriter.utils.Fit; import com.hangyeolee.androidpdfwriter.utils.Orientation; import com.hangyeolee.androidpdfwriter.utils.Paper; import com.hangyeolee.androidpdfwriter.utils.StandardDirectory; import com.hangyeolee.androidpdfwriter.utils.TextAlign; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.InputStream;
11,213
package com.hangyeolee.androidpdfwriter; @RunWith(AndroidJUnit4.class) public class PDFTableTest { Context context; PDFBuilder<PDFLinearLayout> builder; /** * The first page of the pdf file that is output by executing the code below is as follows: * com.hangyeolee.androidpdfwriter.test.R.drawable.pdftabletest_resultimage */ @Before public void setUp() { context = InstrumentationRegistry.getInstrumentation().getTargetContext(); InputStream stream = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(com.hangyeolee.androidpdfwriter.test.R.drawable.test); Bitmap b = BitmapFactory.decodeStream(stream); builder = new PDFBuilder<>(Paper.A4); builder.setPagePadding(30, 30); { builder.root = PDFLinearLayout.build() .setOrientation(Orientation.Column) .setBackgroundColor(Color.BLUE) .addChild(PDFImage.build(b) .setSize(null, 200f) .setFit(Fit.CONTAIN)) .addChild(PDFH1.build("제목") .setBackgroundColor(Color.RED) .setTextAlign(TextAlign.Center)) .addChild(PDFGridLayout.build(3, 5) .setMargin(10, 10, 10, 10) .setBackgroundColor(Color.WHITE) .setBorder(border -> border .setLeft(4, Color.BLACK) .setTop(4, Color.RED) .setRight(4, Color.GREEN) .setBottom(4, Color.MAGENTA) )
package com.hangyeolee.androidpdfwriter; @RunWith(AndroidJUnit4.class) public class PDFTableTest { Context context; PDFBuilder<PDFLinearLayout> builder; /** * The first page of the pdf file that is output by executing the code below is as follows: * com.hangyeolee.androidpdfwriter.test.R.drawable.pdftabletest_resultimage */ @Before public void setUp() { context = InstrumentationRegistry.getInstrumentation().getTargetContext(); InputStream stream = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(com.hangyeolee.androidpdfwriter.test.R.drawable.test); Bitmap b = BitmapFactory.decodeStream(stream); builder = new PDFBuilder<>(Paper.A4); builder.setPagePadding(30, 30); { builder.root = PDFLinearLayout.build() .setOrientation(Orientation.Column) .setBackgroundColor(Color.BLUE) .addChild(PDFImage.build(b) .setSize(null, 200f) .setFit(Fit.CONTAIN)) .addChild(PDFH1.build("제목") .setBackgroundColor(Color.RED) .setTextAlign(TextAlign.Center)) .addChild(PDFGridLayout.build(3, 5) .setMargin(10, 10, 10, 10) .setBackgroundColor(Color.WHITE) .setBorder(border -> border .setLeft(4, Color.BLACK) .setTop(4, Color.RED) .setRight(4, Color.GREEN) .setBottom(4, Color.MAGENTA) )
.addChild(0, 0, PDFH3.build("번호"))
2
2023-11-15 08:05:28+00:00
16k
Hikaito/Fox-Engine
src/system/gui/project/ProjectEditorFunctions.java
[ { "identifier": "FileOperations", "path": "src/system/backbone/FileOperations.java", "snippet": "public class FileOperations {\n\n // region file editing functions--------------------------------------------\n // fixme add redo and undo as appropriate\n\n //removes extension from file name\n ...
import system.backbone.FileOperations; import system.project.treeElements.ProjectFolderInterface; import system.project.ProjectManager; import system.setting.CoreGlobal; import system.Program; import system.gui.GuiOperations; import system.backbone.ImageOperations; import system.backbone.EventE; import system.gui.WarningWindow; import system.project.treeElements.*; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.LinkedList;
12,837
//copy tree children------------------------ while(select.getChildCount() != 0){ DefaultMutableTreeNode kid = (DefaultMutableTreeNode) select.getFirstChild(); //get first child select.remove(0); //remove first child treeParent.add(kid); //add child to parent } } //remove from real tree parentKids.remove(core); //remove from fake tree treeParent.remove(select); //redraw tree tree.updateUI(); //redraw editor caller.regenerateEditorPane(null); } } //endregion //region file properties-------------------------------------- // file selection // generate title text field public static JPanel makeFileSelectionField(DefaultMutableTreeNode unit, EventE event){ //create panel JPanel panel = new JPanel(); panel.setBackground(Color.white); //get core if (!(unit.getUserObject() instanceof ProjectFile)) return panel; // exit early if wrong type of file ProjectFile core = (ProjectFile) unit.getUserObject(); // get core // create file panel.add(new JLabel(core.getPath())); // create button JButton button = new JButton("Change"); panel.add(button); // action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // select file String file = FileOperations.selectFile(Program.getProjectPath()); // select file from project path // force file to be within project if(!file.contains(Program.getProjectPath())){ WarningWindow.warningWindow("Selected file not in project. This file cannot be used."); return; } // strip file from directory file = String.valueOf(FileOperations.trimDirectory(Program.getProjectPath(), file)); // change element path core.setPath(file); // redraw event.enact(); } }); return panel; } //endregion //region color ------------------------------ //generate color toggle for layer public static JCheckBox makeColorToggle(ProjectFile unit, EventE event){ //create toggle; set value to existing clipping values JCheckBox clipBox = new JCheckBox("use color", unit.getUseColor()); //on selection, toggle using original color clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { unit.setUseColor(!unit.getUseColor()); // change use color by default // redraw event.enact(); } }); return clipBox; } //generate color toggle for layer public static JCheckBox makeBackgroundToggle(EventE editor, boolean[] toggle){ //create toggle; set value to existing clipping values JCheckBox clipBox = new JCheckBox("red backdrop", toggle[0]); //on selection, toggle using original color clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { toggle[0] = !toggle[0]; // invert selection // redraw editor.enact(); } }); return clipBox; } //add color chooser to field (and helper) public static void addColorChooser(JPanel innerField, ProjectFile unit, EventE redraw){addColorChooser(innerField, 1, Color.BLACK, unit, redraw);} //text positions: 0 = none, 1 = left, 2 = right public static void addColorChooser(JPanel innerField, int textPosition, Color textColor, ProjectFile unit, EventE redraw){ //create button with image color JButton colorButton = new JButton(" "); colorButton.setBackground(unit.getColor()); //set color //make label for color text NOTE: text field is selectable
package system.gui.project; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectEditorFunctions { //region shared properties-------------------------------------- //generate title label public static JLabel makeTitle(ProjectUnitCore unit){ return new JLabel(unit.getTitle()); } // generate title text field public static JTextField makeTitleField(DefaultMutableTreeNode unit, JTree tree){ ProjectUnitCore obj = (ProjectUnitCore) unit.getUserObject(); JTextField title = new JTextField(20); //generate text field with preferred size title.setText(obj.getTitle()); // action title.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // update unit title obj.setTitle(title.getText()); //update tree title tree.updateUI(); } }); return title; } //region movement of layers============================================= // make button for moving objects public static JButton makeMoveIn(DefaultMutableTreeNode select, JTree tree, ProjectEditor caller){ // create button JButton button = new JButton("Move Element Into Folder"); // disable if illegal----------------------- boolean enabled = true; // get core [current layer] ProjectUnitCore core = (ProjectUnitCore) select.getUserObject(); ProjectUnitCore sibling = null; // generate parent children LinkedList<ProjectUnitCore> children = null; if (core.getParent() instanceof ProjectFolderInterface) children = ((ProjectFolderInterface) core.getParent()).getChildren(); // get parent else enabled = false; //should be impossible // continue if children if (children != null){ int coreIndex = children.indexOf(core); // if index isn't base, continue if (coreIndex == 0) enabled = false; else{ sibling = children.get(coreIndex - 1); //check if folder if (!(sibling instanceof ProjectFolder)) enabled = false; } } //if button is enabled, add action-------------------- if (enabled){ //effectively final variables LinkedList<ProjectUnitCore> finalChildren = children; ProjectFolder folderSibling = (ProjectFolder) sibling; //button action: on selection button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // move in greater tree finalChildren.remove(core); //remove object folderSibling.getChildren().addLast(core); //add to sibling core.setParent(folderSibling); //set sibling as parent // move in gui tree DefaultMutableTreeNode parent = (DefaultMutableTreeNode) select.getParent(); DefaultMutableTreeNode sibling = select.getPreviousSibling(); parent.remove(select); sibling.add(select); //redraw tree tree.updateUI(); //redraw editor caller.regenerateEditorPane(null); } }); } // if button is disabled, instead make it look disabled else{ button.setBackground(Color.GRAY); } return button; } // make button for moving objects public static JButton makeMoveOut(DefaultMutableTreeNode select, JTree tree, ProjectEditor caller){ // create button JButton button = new JButton("Move Element Out Of Folder"); // disable if illegal----------------------- boolean enabled = true; // get core [current layer] ProjectUnitCore core = (ProjectUnitCore) select.getUserObject(); LinkedList<ProjectUnitCore> children = null; LinkedList<ProjectUnitCore> olderChildren = null; //get parent ProjectUnitCore parent = core.getParent(); if (parent instanceof ProjectRoot) enabled = false; //if parent is root, disable moving out else{ //generate children of grandparent if (core.getParent() instanceof ProjectFolderInterface) children = ((ProjectFolderInterface) core.getParent()).getChildren(); //prepare folder else enabled = false; //should be impossible //generate older children if (parent.getParent() instanceof ProjectFolderInterface) olderChildren = ((ProjectFolderInterface) parent.getParent()).getChildren(); //case root else enabled = false; //should be impossible } //if button is enabled, add action-------------------- if (enabled){ //effectively final variables LinkedList<ProjectUnitCore> finalChildren = children; LinkedList<ProjectUnitCore> finalOlderChildren = olderChildren; //button action: on selection button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // move out in greater tree finalChildren.remove(core); finalOlderChildren.addLast(core); core.setParent(parent.getParent()); //set parent // move in gui tree DefaultMutableTreeNode parent = (DefaultMutableTreeNode) select.getParent(); DefaultMutableTreeNode grandparent = (DefaultMutableTreeNode) parent.getParent(); parent.remove(select); grandparent.add(select); //redraw tree tree.updateUI(); //redraw editor caller.regenerateEditorPane(null); } }); } // if button is diabled, instead make it look disabled else{ button.setBackground(Color.GRAY); } return button; } // make button for moving objects public static JButton makeMoveUp(DefaultMutableTreeNode select, JTree tree, ProjectEditor caller){ // create button JButton button = new JButton("Move Element Up"); // disable if illegal----------------------- boolean enabled = true; // get core [current layer] ProjectUnitCore core = (ProjectUnitCore) select.getUserObject(); // generate parent children LinkedList<ProjectUnitCore> children = null; if (core.getParent() instanceof ProjectFolderInterface) children = ((ProjectFolderInterface) core.getParent()).getChildren(); else enabled = false; //should be impossible // continue if children if (children != null){ int coreIndex = children.indexOf(core); // if index isn't base, continue if (coreIndex == 0) enabled = false; } //if button is enabled, add action-------------------- if (enabled){ //effectively final variables LinkedList<ProjectUnitCore> finalChildren = children; //button action: on selection button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // move in greater tree int coreIndex = finalChildren.indexOf(core); //get index finalChildren.remove(core); //remove object finalChildren.add(coreIndex - 1, core); //add as lower index // move in gui tree DefaultMutableTreeNode parent = (DefaultMutableTreeNode) select.getParent(); int treeIndex = parent.getIndex(select); parent.remove(select); parent.insert(select, treeIndex-1); //redraw tree tree.updateUI(); //redraw editor caller.regenerateEditorPane(select); } }); } // if button is diabled, instead make it look disabled else{ button.setBackground(Color.GRAY); } return button; } // make button for moving objects public static JButton makeMoveDown(DefaultMutableTreeNode select, JTree tree, ProjectEditor caller){ // create button JButton button = new JButton("Move Element Down"); // disable if illegal----------------------- boolean enabled = true; // get core [current layer] ProjectUnitCore core = (ProjectUnitCore) select.getUserObject(); // generate parent children LinkedList<ProjectUnitCore> children = null; if (core.getParent() instanceof ProjectFolderInterface) children = ((ProjectFolderInterface) core.getParent()).getChildren(); //case root else enabled = false; //should be impossible // continue if children if (children != null){ int coreIndex = children.indexOf(core); // if index isn't end, continue if (coreIndex == children.size() - 1) enabled = false; } //if button is enabled, add action-------------------- if (enabled){ //effectively final variables LinkedList<ProjectUnitCore> finalChildren = children; //button action: on selection button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // move in greater tree int coreIndex = finalChildren.indexOf(core); //get index finalChildren.remove(core); //remove object finalChildren.add(coreIndex + 1, core); //add as lower index // move in gui tree DefaultMutableTreeNode parent = (DefaultMutableTreeNode) select.getParent(); int treeIndex = parent.getIndex(select); parent.remove(select); parent.insert(select, treeIndex+1); //redraw tree tree.updateUI(); //redraw editor caller.regenerateEditorPane(select); } }); } // if button is diabled, instead make it look disabled else{ button.setBackground(Color.GRAY); } return button; } //endregion // make button for deleting objects public static JButton makeRemove(DefaultMutableTreeNode select, JTree tree, ProjectEditor caller){ // create button JButton button = new JButton("Delete Element"); //button action: on selection button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //invoke action with warning WarningWindow.warningWindow("Are you sure you want to delete this node?", new DeleteEvent(select, tree, caller)); } }); return button; } // action enactor for removing an element from the tree public static class DeleteEvent implements EventE { DefaultMutableTreeNode select; JTree tree; ProjectEditor caller; public DeleteEvent(DefaultMutableTreeNode select, JTree tree, ProjectEditor caller){ this.select = select; this.tree = tree; this.caller = caller; } @Override public void enact() { ProjectUnitCore core = (ProjectUnitCore) select.getUserObject(); DefaultMutableTreeNode treeParent = (DefaultMutableTreeNode) select.getParent(); //get parent kid list LinkedList<ProjectUnitCore> parentKids; ProjectUnitCore parent = core.getParent(); if (parent instanceof ProjectFolderInterface) parentKids = ((ProjectFolderInterface)parent).getChildren(); else return; // copy children to parent if (core instanceof ProjectFolder){ //copy project children------------------------ LinkedList<ProjectUnitCore> children = ((ProjectFolder) core).getChildren(); while(children.size() != 0){ ProjectUnitCore child = children.removeFirst(); child.setParent(core.getParent()); parentKids.addLast(child); //add first element to end of parent } //copy tree children------------------------ while(select.getChildCount() != 0){ DefaultMutableTreeNode kid = (DefaultMutableTreeNode) select.getFirstChild(); //get first child select.remove(0); //remove first child treeParent.add(kid); //add child to parent } } //remove from real tree parentKids.remove(core); //remove from fake tree treeParent.remove(select); //redraw tree tree.updateUI(); //redraw editor caller.regenerateEditorPane(null); } } //endregion //region file properties-------------------------------------- // file selection // generate title text field public static JPanel makeFileSelectionField(DefaultMutableTreeNode unit, EventE event){ //create panel JPanel panel = new JPanel(); panel.setBackground(Color.white); //get core if (!(unit.getUserObject() instanceof ProjectFile)) return panel; // exit early if wrong type of file ProjectFile core = (ProjectFile) unit.getUserObject(); // get core // create file panel.add(new JLabel(core.getPath())); // create button JButton button = new JButton("Change"); panel.add(button); // action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // select file String file = FileOperations.selectFile(Program.getProjectPath()); // select file from project path // force file to be within project if(!file.contains(Program.getProjectPath())){ WarningWindow.warningWindow("Selected file not in project. This file cannot be used."); return; } // strip file from directory file = String.valueOf(FileOperations.trimDirectory(Program.getProjectPath(), file)); // change element path core.setPath(file); // redraw event.enact(); } }); return panel; } //endregion //region color ------------------------------ //generate color toggle for layer public static JCheckBox makeColorToggle(ProjectFile unit, EventE event){ //create toggle; set value to existing clipping values JCheckBox clipBox = new JCheckBox("use color", unit.getUseColor()); //on selection, toggle using original color clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { unit.setUseColor(!unit.getUseColor()); // change use color by default // redraw event.enact(); } }); return clipBox; } //generate color toggle for layer public static JCheckBox makeBackgroundToggle(EventE editor, boolean[] toggle){ //create toggle; set value to existing clipping values JCheckBox clipBox = new JCheckBox("red backdrop", toggle[0]); //on selection, toggle using original color clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { toggle[0] = !toggle[0]; // invert selection // redraw editor.enact(); } }); return clipBox; } //add color chooser to field (and helper) public static void addColorChooser(JPanel innerField, ProjectFile unit, EventE redraw){addColorChooser(innerField, 1, Color.BLACK, unit, redraw);} //text positions: 0 = none, 1 = left, 2 = right public static void addColorChooser(JPanel innerField, int textPosition, Color textColor, ProjectFile unit, EventE redraw){ //create button with image color JButton colorButton = new JButton(" "); colorButton.setBackground(unit.getColor()); //set color //make label for color text NOTE: text field is selectable
JTextField colorLabel = new JTextField(GuiOperations.formatColor(unit.getColor())); //get color label from unit color
5
2023-11-12 21:12:21+00:00
16k
ebandal/jDwgParser
src/structure/Dwg.java
[ { "identifier": "DecodeCallback", "path": "src/decode/DecodeCallback.java", "snippet": "public interface DecodeCallback {\n public void onDecoded(String name, Object value, int retBitOffset);\n}" }, { "identifier": "DecoderR14", "path": "src/decode/DecoderR14.java", "snippet": "public...
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.time.temporal.JulianFields; import java.util.concurrent.atomic.AtomicInteger; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import decode.DecodeCallback; import decode.DecoderR14; import decode.DecoderR2004; import decode.DwgParseException; import structure.header.FileHeader; import structure.sectionpage.DataSectionPage; import structure.sectionpage.HeaderVariables; import structure.sectionpage.SystemSectionPage;
13,367
// BD : LOFTANG1 hdrVars.dLoftang1 = readBitDouble(buf, offset.get(), bitOffset.get(), "LOFTANG1", cb); // BD : LOFTANG2 hdrVars.dLoftang2 = readBitDouble(buf, offset.get(), bitOffset.get(), "LOFTANG2", cb); // BD : LOFTMAG1 hdrVars.dLoftmag1 = readBitDouble(buf, offset.get(), bitOffset.get(), "LOFTMAG1", cb); // BD : LOFTMAG2 hdrVars.dLoftmag2 = readBitDouble(buf, offset.get(), bitOffset.get(), "LOFTMAG2", cb); // BS : LOFTPARAM hdrVars.sLoftparam = readBitShort(buf, offset.get(), bitOffset.get(), "LOFTPARAM", cb); // RC : LOFTNORMALS // BD : LATITUDE hdrVars.dLatitude = readBitDouble(buf, offset.get(), bitOffset.get(), "LATITUDE", cb); // BD : LONGITUDE hdrVars.dLongitude = readBitDouble(buf, offset.get(), bitOffset.get(), "LONGITUDE", cb); // BD : NORTHDIRECTION hdrVars.dNorthdirection = readBitDouble(buf, offset.get(), bitOffset.get(), "NORTHDIRECTION", cb); // BL : TIMEZONE hdrVars.lTimezone = readBitLong(buf, offset.get(), bitOffset.get(), "Unknown", cb); // RC : LIGHTGLYPHDISPLAY // RC : TILEMODELIGHTSYNCH // RC : DWFFRAME // RC : DGNFRAME // B : unknown bUnknown = readBit(buf, offset.get(), bitOffset.get(), "unknown", cb); // CMC : INTERFERECOLOR hdrVars.cmInterferecolor = readCmColor(buf, offset.get(), bitOffset.get(), ver, "INTERFERECOLOR", cb); // H : INTERFEREOBJVS (hard pointer) hdrVars.hInterfereobjvs = readHandle(buf, offset.get(), bitOffset.get(), "INTERFEREOBJVS", cb); // H : INTERFEREVPVS (hard pointer) hdrVars.hInterferevpvs = readHandle(buf, offset.get(), bitOffset.get(), "INTERFEREVPVS", cb); // H : DRAGVS (hard pointer) hdrVars.hDragvs = readHandle(buf, offset.get(), bitOffset.get(), "DRAGVS", cb); // RC : CSHADOW // BD : unknown dUnknown = readBitDouble(buf, offset.get(), bitOffset.get(), "Unknown", cb); } if (ver.from(DwgVersion.R14)) { //BS : unknown short (type 5/6 only) these do not seem to be required, sUnknown = readBitShort(buf, offset.get(), bitOffset.get(), "Unknown", cb); //BS : unknown short (type 5/6 only) even for type 5. sUnknown = readBitShort(buf, offset.get(), bitOffset.get(), "Unknown", cb); //BS : unknown short (type 5/6 only) sUnknown = readBitShort(buf, offset.get(), bitOffset.get(), "Unknown", cb); //BS : unknown short (type 5/6 only) sUnknown = readBitShort(buf, offset.get(), bitOffset.get(), "Unknown", cb); } // RS : CRC for the data section, starting after the sentinel. Use 0xC0C1 for the initial value. return hdrVars; } public static Map<Integer, DrawingClass> readClassSection(byte[] buf, int off, Dwg dwg, DwgVersion ver) { Map<Integer, DrawingClass> drwingClassMap = new HashMap<>(); AtomicInteger offset = new AtomicInteger(off); AtomicInteger bitOffset = new AtomicInteger(0); int reBitOffset = 0; if (ver.between(DwgVersion.R13, DwgVersion.R15)) { DecodeCallback cb = new DecodeCallback() { public void onDecoded(String name, Object value, int retBitOffset) { log.info("[" + name+ "] = (" + value.toString() + ")"); offset.addAndGet((bitOffset.get()+retBitOffset)/8); bitOffset.set((bitOffset.get()+retBitOffset)%8); } }; // beginning sentinel // 0x8D 0xA1 0xC4-xA9 0xF8 0xC5 0xDC 0xF4 0x5F 0xE7 0xCF 0xB6 0x*a offset.addAndGet(16); // size of class date area int sizeClasses = readRawLong(buf, offset.get(), bitOffset.get(), "size of classes data area", cb); // read sets until exhaust the data while(offset.get()-2-16 < sizeClasses) { log.fine("CLASS SECTION read : " + (offset.get()-2-16) + ", Total Size: " + sizeClasses); DrawingClass dc = new DrawingClass(); // classnum dc.classnum = readBitShort(buf, offset.get(), bitOffset.get(), "classnum", cb); // version dc.version = readBitShort(buf, offset.get(), bitOffset.get(), "version", cb); // appname dc.appname = readVariableText(buf, offset.get(), bitOffset.get(), ver, "appname", cb); // cplusplusclassname dc.cplusplusclassname = readVariableText(buf, offset.get(), bitOffset.get(), ver, "c++cplusplusclassname", cb); // classdxfname dc.classdxfname = readVariableText(buf, offset.get(), bitOffset.get(), ver, "classdxfname", cb); // wasazombie dc.waszombie = readBit(buf, offset.get(), bitOffset.get(), "c++wasazomebie", cb); // itemclassid dc.itemclassid = readBitShort(buf, offset.get(), bitOffset.get(), "itemclassid", cb); drwingClassMap.put((int)dc.classnum, dc); } // RS: CRC int crc = readBitShort(buf, offset.get(), bitOffset.get(), "CRC", cb); // 16 byte sentinel apprears after the CRC // 0x72,0x5E,0x3B,0x47,0x3B,0x56,0x07,0x3A,0x3F,0x23,0x0B,0xA0,0x180x30,0x49,0x75 // PADDING random bits to the next byte boundary if (bitOffset.get()>0) { bitOffset.set(0);; offset.addAndGet(1); } byte[] compareBytes = new byte[16]; System.arraycopy(buf, offset.get(), compareBytes, 0, 16); offset.addAndGet(16); byte[] endingSentinel = { (byte)0x72, (byte)0x5E,(byte)0x3B,(byte)0x47,(byte)0x3B,(byte)0x56,(byte)0x07,(byte)0x3A, (byte)0x3F,(byte)0x23,(byte)0x0B,(byte)0xA0,(byte)0x18,(byte)0x30,(byte)0x49,(byte)0x75 }; if (Arrays.equals(compareBytes, endingSentinel)==false) { log.severe("Ending Sentinel mismatched!!!"); } } else if (ver.from(DwgVersion.R18)) { // section is compressed, contains the standard 32byte section header
package structure; public class Dwg { private static final Logger log = Logger.getLogger(Dwg.class.getName()); public FileHeader header; public HeaderVariables headerVariables; public List<SystemSectionPage> systemSectionPageList; public List<DataSectionPage> dataSectionPageList; public void decode(File dwgFile) throws DwgParseException { try (RandomAccessFile raf = new RandomAccessFile(dwgFile, "r")) { // read header header = readFileHeader(raf); // read body readFileBody(raf); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void readFileBody(RandomAccessFile raf) throws IOException, DwgParseException { int offset = 0; switch(header.versionId) { case "AC1012": header.ver = DwgVersion.R13; throw new DwgParseException(); case "AC1014": header.ver = DwgVersion.R14; offset += DecoderR14.readData(raf, this); break; case "AC1015": header.ver = DwgVersion.R2000; offset += DecoderR14.readData(raf, this); break; case "AC1018": header.ver = DwgVersion.R2004; break; case "AC1021": header.ver = DwgVersion.R2007; break; case "AC1024": header.ver = DwgVersion.R2010; break; case "AC1027": header.ver = DwgVersion.R2013; break; case "AC1032": header.ver = DwgVersion.R2018; break; } } public FileHeader readFileHeader(RandomAccessFile raf) throws IOException, DwgParseException { FileHeader fileHeader = new FileHeader(); byte[] buf = null; int offset = 0; // VERSION ID byte[] versionIdBuf = new byte[6]; int readLen = raf.read(versionIdBuf, offset, 6); fileHeader.versionId = new String(versionIdBuf, 0, 6, StandardCharsets.US_ASCII); log.finest("VersionId: " + fileHeader.versionId); DwgVersion ver; switch(fileHeader.versionId) { case "AC1012": fileHeader.ver = DwgVersion.R13; throw new DwgParseException(); case "AC1014": fileHeader.ver = DwgVersion.R14; offset = 6; offset += DecoderR14.readFileHeader(raf, offset, fileHeader); break; case "AC1015": fileHeader.ver = DwgVersion.R2000; offset += DecoderR14.readFileHeader(raf, offset, fileHeader); break; case "AC1018": fileHeader.ver = DwgVersion.R2004; buf = new byte[0x100]; offset += 6; readLen = raf.read(buf, offset, 0x100-6); // offset += DecoderR2004.readFileHeader(buf, offset, fileHeader); break; case "AC1021": fileHeader.ver = DwgVersion.R2007; break; case "AC1024": fileHeader.ver = DwgVersion.R2010; break; case "AC1027": fileHeader.ver = DwgVersion.R2013; break; case "AC1032": fileHeader.ver = DwgVersion.R2018; break; } // six bytes of 0 (in R14, 5 0's and the ACADMAINTVER) offset += 6; return fileHeader; } public static HeaderVariables readHeaderVariable(byte[] buf, int off, DwgVersion ver) { AtomicInteger offset = new AtomicInteger(off); AtomicInteger bitOffset = new AtomicInteger(0); int retBitOffset = 0; boolean bUnknown; double dUnknown; int lUnknown; long llUnknown; short sUnknown; String tUnknown; HandleRef hUnknown; DecodeCallback cb = new DecodeCallback() { public void onDecoded(String name, Object value, int retBitOffset) { log.info("[" + name + "] = (" + value.toString() + ")"); offset.addAndGet((bitOffset.get()+retBitOffset)/8); bitOffset.set((bitOffset.get()+retBitOffset)%8); } }; // beginning sentinel // 0xCF,0x7B,0x1F,0x23,0xFD,0xDE,0x38,0xA9,0x5F,0x7C,0x68,0xB8,0x4E,0x6D,0x33,0x5F offset.addAndGet(16); // Size of the section (a 4 byte long) int sectionSize = ByteBuffer.wrap(buf, offset.get(), 4).order(ByteOrder.LITTLE_ENDIAN).getInt(); offset.addAndGet(4); // R2010/R1013 (only present if the maintenance version is greater than 3!) or R2018_: // unknown (4 byte long), might be part of a 62-bit size. if (ver.between(DwgVersion.R2010, DwgVersion.R2013)) { } else if (ver.from(DwgVersion.R2018)) { offset.addAndGet(4); } HeaderVariables hdrVars = new HeaderVariables(); // R2007 Only: long sizeInBits = 0; if (ver.only(DwgVersion.R2007)) { // RL : Size in bits // hdrVars.lSizeInBits = readRawLong(buf, offset.get(), bitOffset.get(), "SizeInBits", cb); } // R2013+: if (ver.from(DwgVersion.R2013)) { // BLL : Variabele REQUIREDVERSIONS, default value 0, read only. hdrVars.llRequiredVersions = readBitLongLong(buf, offset.get(), bitOffset.get(), "REQUIREDVERSIONS", cb); } // Common: // BD : Unknown, default value 412148564080.0 dUnknown = readBitDouble(buf, offset.get(), bitOffset.get(), "Unknown", cb); // BD : Unknown, default value 1.0 dUnknown = readBitDouble(buf, offset.get(), bitOffset.get(), "Unknown", cb); // BD : Unknown, default value 1.0 dUnknown = readBitDouble(buf, offset.get(), bitOffset.get(), "Unknown", cb); // BD : Unknown, default value 1.0 dUnknown = readBitDouble(buf, offset.get(), bitOffset.get(), "Unknown", cb); // TV : Unknown text string, default "" tUnknown = readVariableText(buf, offset.get(), bitOffset.get(), ver, "Unknown", cb); // TV : Unknown text string, default "" tUnknown = readVariableText(buf, offset.get(), bitOffset.get(), ver, "Unknown", cb); // TV : Unknown text string, default "" tUnknown = readVariableText(buf, offset.get(), bitOffset.get(), ver, "Unknown", cb); // TV : Unknown text string, default "" tUnknown = readVariableText(buf, offset.get(), bitOffset.get(), ver, "Unknown", cb); // BL : Unknown long, default value 24L lUnknown = readBitLong(buf, offset.get(), bitOffset.get(), "Unknown", cb); // BL : Unknown long, default value 0L; lUnknown = readBitLong(buf, offset.get(), bitOffset.get(), "Unknown", cb); // R13-R14 Only: if (ver.between(DwgVersion.R13, DwgVersion.R14)) { // BS : Unknown short, default value 0 sUnknown = readBitShort(buf, offset.get(), bitOffset.get(), "Unknown", cb); } // Pre-2004 Only: if (ver.until(DwgVersion.R2004)) { // H : Handle of the current viewport entity header (hard pointer) hdrVars.hCurrViewportEntityHeader = readHandle(buf, offset.get(), bitOffset.get(), "Handle of current viewport", cb); } // B : DIMASO hdrVars.bDimaso = readBit(buf, offset.get(), bitOffset.get(), "DIMASO", cb); // B : DIMSHO hdrVars.bDimsho = readBit(buf, offset.get(), bitOffset.get(), "DIMSHO", cb); if (ver.between(DwgVersion.R13, DwgVersion.R14)) { hdrVars.bDimsav = readBit(buf, offset.get(), bitOffset.get(), "DIMSAV", cb); } // B : PLINEGEN hdrVars.bPlinegen = readBit(buf, offset.get(), bitOffset.get(), "PLINEGEN", cb); // B : ORTHOMODE hdrVars.bOrthomode = readBit(buf, offset.get(), bitOffset.get(), "ORTHOMODE", cb); // B : REGENMODE hdrVars.bRegenmode = readBit(buf, offset.get(), bitOffset.get(), "REGENMODE", cb); // B : FILLMODE hdrVars.bFillmode = readBit(buf, offset.get(), bitOffset.get(), "FILLMODE", cb); // B : QTEXTMODE hdrVars.bQtextmode = readBit(buf, offset.get(), bitOffset.get(), "QTEXTMODE", cb); // B : PSLTSCALE hdrVars.bPsltscale = readBit(buf, offset.get(), bitOffset.get(), "PSLTSCALE", cb); // B : LIMCHECK hdrVars.bLimcheck = readBit(buf, offset.get(), bitOffset.get(), "LIMCHECK", cb); if (ver.between(DwgVersion.R13, DwgVersion.R14)) { // B : BLIPMODE hdrVars.bBlipmode = readBit(buf, offset.get(), bitOffset.get(), "BLIPMODE", cb); } if (ver.from(DwgVersion.R2004)) { // B : Undocumented bUnknown = readBit(buf, offset.get(), bitOffset.get(), "Undocumented", cb); } // B : USRTIMER (User timer on/off). hdrVars.bUsrtimer = readBit(buf, offset.get(), bitOffset.get(), "USRTIMER", cb); // B : SKPOLY hdrVars.bSkpoly = readBit(buf, offset.get(), bitOffset.get(), "SKPOLY", cb); // B : ANGDIR hdrVars.bAngdir = readBit(buf, offset.get(), bitOffset.get(), "ANGDIR", cb); // B : SPLFRAME hdrVars.bSplframe = readBit(buf, offset.get(), bitOffset.get(), "SPLFRAME", cb); if (ver.between(DwgVersion.R13, DwgVersion.R14)) { // B : ATTREQ hdrVars.bAttreq = readBit(buf, offset.get(), bitOffset.get(), "ATTREQ", cb); // B : ATTDIA hdrVars.bAttdia = readBit(buf, offset.get(), bitOffset.get(), "ATTDIA", cb); } // B : MIRRTEXT hdrVars.bMirrtext = readBit(buf, offset.get(), bitOffset.get(), "MIRRTEXT", cb); // B : WORLDVIEW hdrVars.bWorldview = readBit(buf, offset.get(), bitOffset.get(), "WORLDVIEW", cb); if (ver.between(DwgVersion.R13, DwgVersion.R14)) { // B : WIREFRAME Undocumented. hdrVars.bWireframe = readBit(buf, offset.get(), bitOffset.get(), "WIREFRAME", cb); } // B : TILEMODE hdrVars.bTilemode = readBit(buf, offset.get(), bitOffset.get(), "TILEMODE", cb); // B : PLIMCHECK hdrVars.bPlimcheck = readBit(buf, offset.get(), bitOffset.get(), "PLIMCHECK", cb); // B : VISRETAIN hdrVars.bVisretain = readBit(buf, offset.get(), bitOffset.get(), "VISRETAIN", cb); if (ver.between(DwgVersion.R13, DwgVersion.R14)) { // B : DELOBJ hdrVars.bDelobj = readBit(buf, offset.get(), bitOffset.get(), "DELOBJ", cb); } // B : DISPSILH hdrVars.bDispsilh = readBit(buf, offset.get(), bitOffset.get(), "DISPSILH", cb); // B : PELLIPSE (not present in DXF) hdrVars.bPellipse = readBit(buf, offset.get(), bitOffset.get(), "PELLIPSE", cb); // BS : PROXYGRAPHICS hdrVars.sProxygraphics = readBitShort(buf, offset.get(), bitOffset.get(), "PROXYGRAPHICS", cb); if (ver.between(DwgVersion.R13, DwgVersion.R14)) { // BS : DRAGMODE hdrVars.sDragmode = readBitShort(buf, offset.get(), bitOffset.get(), "DRAGMODE", cb); } // BS : TREEDEPTH hdrVars.sTreedepth = readBitShort(buf, offset.get(), bitOffset.get(), "TREEDEPTH", cb); // BS : LUNITS hdrVars.sLunits = readBitShort(buf, offset.get(), bitOffset.get(), "LUNITS", cb); // BS : LUPREC hdrVars.sLuprec = readBitShort(buf, offset.get(), bitOffset.get(), "LUPREC", cb); // BS : AUNITS hdrVars.sAunits = readBitShort(buf, offset.get(), bitOffset.get(), "AUNITS", cb); // BS : AUPREC hdrVars.sAuprec = readBitShort(buf, offset.get(), bitOffset.get(), "AUPREC", cb); if (ver.between(DwgVersion.R13, DwgVersion.R14)) { // BS : OSMODE hdrVars.sOsmode = readBitShort(buf, offset.get(), bitOffset.get(), "OSMODE", cb); } // BS : ATTMODE hdrVars.sAttmode = readBitShort(buf, offset.get(), bitOffset.get(), "ATTMODE", cb); if (ver.between(DwgVersion.R13, DwgVersion.R14)) { // BS : COORDS hdrVars.sCoords = readBitShort(buf, offset.get(), bitOffset.get(), "COORDS", cb); } // BS : PDMODE hdrVars.sPdmode = readBitShort(buf, offset.get(), bitOffset.get(), "PDMODE", cb); if (ver.between(DwgVersion.R13, DwgVersion.R14)) { // BS : PICKSTYLE hdrVars.sPickstyle = readBitShort(buf, offset.get(), bitOffset.get(), "PICKSTYLE", cb); } if (ver.from(DwgVersion.R2004)) { // BL : Unknown lUnknown = readBitLong(buf, offset.get(), bitOffset.get(), "Unknown", cb); // BL: Unknown lUnknown = readBitLong(buf, offset.get(), bitOffset.get(), "Unknown", cb); // BL : Unknown lUnknown = readBitLong(buf, offset.get(), bitOffset.get(), "Unknown", cb); } // BS : USERI1 hdrVars.sUseri1 = readBitShort(buf, offset.get(), bitOffset.get(), "USERI1", cb); // BS : USERI2 hdrVars.sUseri2 = readBitShort(buf, offset.get(), bitOffset.get(), "USERI2", cb); // BS : USERI3 hdrVars.sUseri3 = readBitShort(buf, offset.get(), bitOffset.get(), "USERI3", cb); // BS : USERI4 hdrVars.sUseri4 = readBitShort(buf, offset.get(), bitOffset.get(), "USERI4", cb); // BS : USERI5 hdrVars.sUseri5 = readBitShort(buf, offset.get(), bitOffset.get(), "USERI5", cb); // BS : SPLINESEGS hdrVars.sSplinesegs = readBitShort(buf, offset.get(), bitOffset.get(), "SPLINESEGS", cb); // BS : SURFU hdrVars.sSurfu = readBitShort(buf, offset.get(), bitOffset.get(), "SURFU", cb); // BS : SURFV hdrVars.sSurfv = readBitShort(buf, offset.get(), bitOffset.get(), "SURFV", cb); // BS : SURFTYPE hdrVars.sSurftype = readBitShort(buf, offset.get(), bitOffset.get(), "SURFTYPE", cb); // BS : SURFTAB1 hdrVars.sSurftab1 = readBitShort(buf, offset.get(), bitOffset.get(), "SURFTAB1", cb); // BS : SURFTAB2 hdrVars.sSurftab2 = readBitShort(buf, offset.get(), bitOffset.get(), "SURFTAB2", cb); // BS : SPLINETYPE hdrVars.sSplinetype = readBitShort(buf, offset.get(), bitOffset.get(), "SPLINETYPE", cb); // BS : SHADEDGE hdrVars.sShadedge = readBitShort(buf, offset.get(), bitOffset.get(), "SHADEDGE", cb); // BS : SHADEDIF hdrVars.sShadedif = readBitShort(buf, offset.get(), bitOffset.get(), "SHADEDIF", cb); // BS : UNITMODE hdrVars.sUnitmode = readBitShort(buf, offset.get(), bitOffset.get(), "UNITMODE", cb); // BS : MAXACTVP hdrVars.sMaxactvp = readBitShort(buf, offset.get(), bitOffset.get(), "MAXACTVP", cb); // BS : ISOLINES hdrVars.sIsolines = readBitShort(buf, offset.get(), bitOffset.get(), "ISOLINES", cb); // BS : CMLJUST hdrVars.sCmljust = readBitShort(buf, offset.get(), bitOffset.get(), "CMLJUST", cb); // BS : TEXTQLTY hdrVars.sTextqlty = readBitShort(buf, offset.get(), bitOffset.get(), "TEXTQLTY", cb); // BD : LTSCALE hdrVars.dLtscale = readBitDouble(buf, offset.get(), bitOffset.get(), "LTSCALE", cb); // BD : TEXTSIZE hdrVars.dTextsize = readBitDouble(buf, offset.get(), bitOffset.get(), "TEXTSIZE", cb); // BD : TRACEWID hdrVars.dTracewid = readBitDouble(buf, offset.get(), bitOffset.get(), "TRACEWID", cb); // BD : SKETCHINC hdrVars.dSketchinc = readBitDouble(buf, offset.get(), bitOffset.get(), "SKETCHINC", cb); // BD : FILLETRAD hdrVars.dFilletrad = readBitDouble(buf, offset.get(), bitOffset.get(), "FILLETRAD", cb); // BD : THICKNESS hdrVars.dThickness = readBitDouble(buf, offset.get(), bitOffset.get(), "THICKNESS", cb); // BD : ANGBASE hdrVars.dAngbase = readBitDouble(buf, offset.get(), bitOffset.get(), "ANGBASE", cb); // BD : PDSIZE hdrVars.dPdsize = readBitDouble(buf, offset.get(), bitOffset.get(), "PDSIZE", cb); // BD : PLINEWID hdrVars.dPlinewid = readBitDouble(buf, offset.get(), bitOffset.get(), "PLINEWID", cb); // BD : USERR1 hdrVars.dUserr1 = readBitDouble(buf, offset.get(), bitOffset.get(), "USERR1", cb); // BD : USERR2 hdrVars.dUserr2 = readBitDouble(buf, offset.get(), bitOffset.get(), "USERR2", cb); // BD : USERR3 hdrVars.dUserr3 = readBitDouble(buf, offset.get(), bitOffset.get(), "USERR3", cb); // BD : USERR4 hdrVars.dUserr4 = readBitDouble(buf, offset.get(), bitOffset.get(), "USERR4", cb); // BD : USERR5 hdrVars.dUserr5 = readBitDouble(buf, offset.get(), bitOffset.get(), "USERR5", cb); // BD : CHAMFERA hdrVars.dChamfera = readBitDouble(buf, offset.get(), bitOffset.get(), "CHAMFERA", cb); // BD : CHAMFERB hdrVars.dChamferb = readBitDouble(buf, offset.get(), bitOffset.get(), "CHAMFERB", cb); // BD : CHAMFERC hdrVars.dChamferc = readBitDouble(buf, offset.get(), bitOffset.get(), "CHAMFERC", cb); // BD : CHAMFERD hdrVars.dChamferd = readBitDouble(buf, offset.get(), bitOffset.get(), "CHAMFERD", cb); // BD : FACETRES hdrVars.dFacetres = readBitDouble(buf, offset.get(), bitOffset.get(), "FACETRES", cb); // BD : CMLSCALE hdrVars.dCmlscale = readBitDouble(buf, offset.get(), bitOffset.get(), "CMLSCALE", cb); // BD : CELTSCALE hdrVars.dCeltscale = readBitDouble(buf, offset.get(), bitOffset.get(), "CELTSCALE", cb); if (ver.between(DwgVersion.R13, DwgVersion.R18)) { // TV : MENUNAME hdrVars.tMenuname = readVariableText(buf, offset.get(), bitOffset.get(), ver, "MENUNAME", cb); } // BL : TDCREATE (Julian day) hdrVars.lTdcreateJD = readBitLong(buf, offset.get(), bitOffset.get(), "TDCREATE", cb); // BL : TDCREATE (Milliseconds into the day) hdrVars.lTdcreateMS = readBitLong(buf, offset.get(), bitOffset.get(), "TDCREATE", cb); // BL : TDUPDATE (Julian day) hdrVars.lTdupdateJD = readBitLong(buf, offset.get(), bitOffset.get(), "TDUPDATE", cb); // BL : TDUPDATE (Milliseconds into the day) hdrVars.lTdupdateMS = readBitLong(buf, offset.get(), bitOffset.get(), "TDUPDATE", cb); if (ver.from(DwgVersion.R2004)) { // BL : Unknown lUnknown = readBitLong(buf, offset.get(), bitOffset.get(), "Unknown", cb); // BL : Unknown lUnknown = readBitLong(buf, offset.get(), bitOffset.get(), "Unknown", cb); // BL : Unknown lUnknown = readBitLong(buf, offset.get(), bitOffset.get(), "Unknown", cb); } // BL : TDINDWG (Days) hdrVars.lTdindwgD = readBitLong(buf, offset.get(), bitOffset.get(), "TDINDWG", cb); // BL : TDINDWG (Milliseconds into the day) hdrVars.lTdindwgMS = readBitLong(buf, offset.get(), bitOffset.get(), "TDINDWG", cb); // BL : TDUSRTIMER (Days) hdrVars.lTdusrtimerD = readBitLong(buf, offset.get(), bitOffset.get(), "TDUSRTIMER", cb); // BL : TDUSRTIMER (Milliseconds into the day) hdrVars.lTdusrtimerMS = readBitLong(buf, offset.get(), bitOffset.get(), "TDUSRTIMER", cb); // CMC : CECOLOR hdrVars.cmCecolor = readCmColor(buf, offset.get(), bitOffset.get(), ver, "CECOLOR", cb); // H : HANDSEED The next handle, with an 8-bit length specifier preceding the handle bytes hdrVars.hHandseed = readHandle(buf, offset.get(), bitOffset.get(), "HANDSEED", cb); // H : CLAYER (hard pointer) hdrVars.hClayer = readHandle(buf, offset.get(), bitOffset.get(), "CLAYER", cb); // H : TEXTSTYLE (hard pointer) hdrVars.hTextstyle = readHandle(buf, offset.get(), bitOffset.get(), "TEXTSTYLE", cb); // H : CELTYPE (hard pointer) hdrVars.hCeltype = readHandle(buf, offset.get(), bitOffset.get(), "CELTYPE", cb); if (ver.from(DwgVersion.R2007)) { // H : CMATERIAL (hard pointer) hdrVars.hCmaterial = readHandle(buf, offset.get(), bitOffset.get(), "CMATERIAL", cb); } // H : DIMSTYLE (hard pointer) hdrVars.hDimstyle = readHandle(buf, offset.get(), bitOffset.get(), "DIMSTYLE", cb); // H : CMLSTYLE (hard pointer) hdrVars.hCmlstyle = readHandle(buf, offset.get(), bitOffset.get(), "CMLSTYLE", cb); if (ver.from(DwgVersion.R2000)) { // BD : PSVPSCALE hdrVars.dPsvpscale = readBitDouble(buf, offset.get(), bitOffset.get(), "PSVPSCALE", cb); } // 3BD : INSBASE (PSPACE) hdrVars.dInsbasePspace = read3BitDouble(buf, offset.get(), bitOffset.get(), "INSBASE (PSPACE)", cb); // 3BD : EXTMIN (PSPACE) hdrVars.dExtminPspace = read3BitDouble(buf, offset.get(), bitOffset.get(), "EXTMIN (PSPACE)", cb); // 3BD : EXTMAX (PSPACE) hdrVars.dExtmaxPspace = read3BitDouble(buf, offset.get(), bitOffset.get(), "EXTMAX (PSPACE)", cb); // 2RD : LIMMIN (PSPACE) // 2RD : LIMMAX (PSPACE) // BD : ELEVATION (PSPACE) hdrVars.dElevationPspace = readBitDouble(buf, offset.get(), bitOffset.get(), "ELEVATION (PSPACE)", cb); // 3BD : UCSORG (PSPACE) hdrVars.dUcsorgPspace = read3BitDouble(buf, offset.get(), bitOffset.get(), "UCSORG (PSPACE)", cb); // 3BD : UCSXDIR (PSPACE) hdrVars.dUcsxdirPspace = read3BitDouble(buf, offset.get(), bitOffset.get(), "UCSXDIR (PSPACE)", cb); // 3BD : UCSYDIR (PSPACE) hdrVars.dUcsydirPspace = read3BitDouble(buf, offset.get(), bitOffset.get(), "UCSYDIR (PSPACE)", cb); // H : UCSNAME (PSPACE) (hard pointer) hdrVars.hUcsnamePspace = readHandle(buf, offset.get(), bitOffset.get(), "UCSNAME (PSPACE", cb); if (ver.from(DwgVersion.R2000)) { // H : PUCSORTHOREF (hard pointer) hdrVars.hPucsorthoref = readHandle(buf, offset.get(), bitOffset.get(), "PUCSORTHOREF", cb); // BS : PUCSORTHOVIEW hdrVars.sPucsorthoview = readBitShort(buf, offset.get(), bitOffset.get(), "PUCSORTHOVIEW", cb); // H : PUCSBASE (hard pointer) hdrVars.hPucsbase = readHandle(buf, offset.get(), bitOffset.get(), "PUCSBASE", cb); // 3BD : PUCSORGTOP hdrVars.dPucsorgtop = read3BitDouble(buf, offset.get(), bitOffset.get(), "PUCSORGTOP", cb); // 3BD : PUCSORGBOTTOM hdrVars.dPucsorgbottom = read3BitDouble(buf, offset.get(), bitOffset.get(), "PUCSORGBOTTOM", cb); // 3BD : PUCSORGLEFT hdrVars.dPucsorgleft = read3BitDouble(buf, offset.get(), bitOffset.get(), "PUCSORGLEFT", cb); // 3BD : PUCSORGRIGHT hdrVars.dPucsorgright = read3BitDouble(buf, offset.get(), bitOffset.get(), "PUCSORGRIGHT", cb); // 3BD : PUCSORGFRONT hdrVars.dPucsorgfront = read3BitDouble(buf, offset.get(), bitOffset.get(), "PUCSORGFRONT", cb); // 3BD : PUCSORGBACK hdrVars.dPucsorgback = read3BitDouble(buf, offset.get(), bitOffset.get(), "PUCSORGBACK", cb); } // 3BD : INSBASE (MSPACE) hdrVars.dInsbaseMspace = read3BitDouble(buf, offset.get(), bitOffset.get(), "INSBASE (MSPACE)", cb); // 3BD : EXTMIN (MSPACE) hdrVars.dExtminMspace = read3BitDouble(buf, offset.get(), bitOffset.get(), "EXTMIN (MSPACE)", cb); // 3BD : EXTMAX (MSPACE) hdrVars.dExtmaxMspace = read3BitDouble(buf, offset.get(), bitOffset.get(), "EXTMAX (MSPACE)", cb); // 2RD : LIMMIN (MSPACE) // 2RD : LIMMAX (MSPACE) // BD : ELEVATION (MSPACE) hdrVars.dElevationMspace = readBitDouble(buf, offset.get(), bitOffset.get(), "ELEVATION", cb); // 3BD : UCSORG (MSPACE) hdrVars.dUcsorgMspace = read3BitDouble(buf, offset.get(), bitOffset.get(), "UCSORG (MSPACE)", cb); // 3BD : UCSXDIR (MSPACE) hdrVars.dUcsxdirMspace = read3BitDouble(buf, offset.get(), bitOffset.get(), "UCSXDIR (MSPACE)", cb); // 3BD : UCSYDIR (MSPACE) hdrVars.dUcsydirMspace = read3BitDouble(buf, offset.get(), bitOffset.get(), "UCSYDIR (MSPACE)", cb); // H : UCSNAME (MSPACE) (hard pointer) hdrVars.hUcsnameMspace = readHandle(buf, offset.get(), bitOffset.get(), "UCSNAME (MSPACE)", cb); if (ver.from(DwgVersion.R2000)) { // H : UCSORTHOREF (hard pointer) hdrVars.hUcsorthoref = readHandle(buf, offset.get(), bitOffset.get(), "UCSORTHOREF", cb); // BS : UCSORTHOVIEW hdrVars.sUcsorthoview = readBitShort(buf, offset.get(), bitOffset.get(), "UCSORTHOVIEW", cb); // H : UCSBASE (hard pointer) hdrVars.hUcsbase = readHandle(buf, offset.get(), bitOffset.get(), "UCSBASE", cb); // 3BD : UCSORGTOP hdrVars.dUcsorgtop = read3BitDouble(buf, offset.get(), bitOffset.get(), "UCSORGTOP", cb); // 3BD : UCSORGBOTTOM hdrVars.dUcsorgbottom = read3BitDouble(buf, offset.get(), bitOffset.get(), "UCSORGBOTTOM", cb); // 3BD : UCSORGLEFT hdrVars.dUcsorgleft = read3BitDouble(buf, offset.get(), bitOffset.get(), "UCSORGLEFT", cb); // 3BD : UCSORGRIGHT hdrVars.dUcsorgright = read3BitDouble(buf, offset.get(), bitOffset.get(), "UCSORGRIGHT", cb); // 3BD : UCSORGFRONT hdrVars.dUcsorgfront = read3BitDouble(buf, offset.get(), bitOffset.get(), "UCSORGFRONT", cb); // 3BD : UCSORGBACK hdrVars.dUcsorgback = read3BitDouble(buf, offset.get(), bitOffset.get(), "UCSORGBACK", cb); // TV : DIMPOST hdrVars.tDimpost = readVariableText(buf, offset.get(), bitOffset.get(), ver, "DIMPOST", cb); // TV : DIMAPOST hdrVars.tDimapost = readVariableText(buf, offset.get(), bitOffset.get(), ver, "DIMAPOST", cb); } if (ver.between(DwgVersion.R13, DwgVersion.R14)) { // B : DIMTOL hdrVars.bDimtol = readBit(buf, offset.get(), bitOffset.get(), "DIMTOL", cb); // B : DIMLIM hdrVars.bDimlim = readBit(buf, offset.get(), bitOffset.get(), "DIMLIM", cb); // B : DIMTIH hdrVars.bDimtih = readBit(buf, offset.get(), bitOffset.get(), "DIMTIH", cb); // B : DIMTOH hdrVars.bDimtoh = readBit(buf, offset.get(), bitOffset.get(), "DIMTOH", cb); // B : DIMSE1 hdrVars.bDimse1 = readBit(buf, offset.get(), bitOffset.get(), "DIMSE1", cb); // B : DIMSE2 hdrVars.bDimse2 = readBit(buf, offset.get(), bitOffset.get(), "DIMSE2", cb); // B : DIMALT hdrVars.bDimalt = readBit(buf, offset.get(), bitOffset.get(), "DIMALT", cb); // B : DIMTOFL hdrVars.bDimtofl = readBit(buf, offset.get(), bitOffset.get(), "DIMTOFL", cb); // B : DIMSAH hdrVars.bDimsah = readBit(buf, offset.get(), bitOffset.get(), "DIMSAH", cb); // B : DIMTIX hdrVars.bDimtix = readBit(buf, offset.get(), bitOffset.get(), "DIMTIX", cb); // B : DIMSOXD hdrVars.bDimsoxd = readBit(buf, offset.get(), bitOffset.get(), "DIMSOXD", cb); // RC : DIMALTD // RC : DIMZIN // B : DIMSD1 hdrVars.bDimsd1 = readBit(buf, offset.get(), bitOffset.get(), "DIMSD1", cb); // B : DIMSD2 hdrVars.bDimsd2 = readBit(buf, offset.get(), bitOffset.get(), "DIMSD2", cb); // RC : DIMTOLJ // RC : DIMJUST // RC : DIMFIT // B : DIMUPT hdrVars.bDimupt = readBit(buf, offset.get(), bitOffset.get(), "DIMUPT", cb); // RC : DIMTZIN // RC : DIMALTZ // RC : DIMALTTZ // RC : DIMTAD // BS : DIMUNIT hdrVars.sDimunit = readBitShort(buf, offset.get(), bitOffset.get(), "DIMUNIT", cb); // BS : DIMAUNIT hdrVars.sDimaunit = readBitShort(buf, offset.get(), bitOffset.get(), "DIMAUNIT", cb); // BS : DIMDEC hdrVars.sDimdec = readBitShort(buf, offset.get(), bitOffset.get(), "DIMDEC", cb); // BS : DIMTDEC hdrVars.sDimtdec = readBitShort(buf, offset.get(), bitOffset.get(), "DIMTDEC", cb); // BS : DIMALTU hdrVars.sDimaltu = readBitShort(buf, offset.get(), bitOffset.get(), "DIMALTU", cb); // BS : DIMALTTD hdrVars.sDimalttd = readBitShort(buf, offset.get(), bitOffset.get(), "DIMALTTD", cb); // H : DIMTXSTY (hard pointer) hdrVars.hDimtxsty = readHandle(buf, offset.get(), bitOffset.get(), "DIMTXSTY", cb); } // BD : DIMSCALE hdrVars.dDimscale = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMSCALE", cb); // BD : DIMASZ hdrVars.dDimasz = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMASZ", cb); // BD : DIMEXO hdrVars.dDimexo = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMEXO", cb); // BD : DIMDLI hdrVars.dDimdli = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMDLI", cb); // BD : DIMEXE hdrVars.dDimexe = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMEXE", cb); // BD : DIMRND hdrVars.dDimrnd = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMRND", cb); // BD : DIMDLE hdrVars.dDimdle = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMDLE", cb); // BD : DIMTP hdrVars.dDimtp = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMTP", cb); // BD : DIMTM hdrVars.dDimtm = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMTM", cb); if (ver.from(DwgVersion.R2007)) { // BD : DIMFXL hdrVars.dDimfxl = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMFXL", cb); // BD : DIMJOGANG hdrVars.dDimjogang = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMJOGANG", cb); // BS : DIMTFILL hdrVars.sDimtfill = readBitShort(buf, offset.get(), bitOffset.get(), "DIMTFILL", cb); // CMC : DIMTFILLCLR hdrVars.cmDimtfillclr = readCmColor(buf, offset.get(), bitOffset.get(), ver, "DIMTFILLCLR", cb); } if (ver.from(DwgVersion.R2000)) { // B : DIMTOL hdrVars.bDimtol = readBit(buf, offset.get(), bitOffset.get(), "DIMTOL", cb); // B : DIMLIM hdrVars.bDimlim = readBit(buf, offset.get(), bitOffset.get(), "DIMLIM", cb); // B : DIMTIH hdrVars.bDimtih = readBit(buf, offset.get(), bitOffset.get(), "DIMTIH", cb); // B : DIMTOH hdrVars.bDimtoh = readBit(buf, offset.get(), bitOffset.get(), "DIMTOH", cb); // B : DIMSE1 hdrVars.bDimse1 = readBit(buf, offset.get(), bitOffset.get(), "DIMSE1", cb); // B : DIMSE2 hdrVars.bDimse2 = readBit(buf, offset.get(), bitOffset.get(), "DIMSE2", cb); // BS : DIMTAD hdrVars.sDimtad = readBitShort(buf, offset.get(), bitOffset.get(), "DIMTAD", cb); // BS : DIMZIN hdrVars.sDimzin = readBitShort(buf, offset.get(), bitOffset.get(), "DIMZIN", cb); // BS : DIMAZIN hdrVars.sDimazin = readBitShort(buf, offset.get(), bitOffset.get(), "DIMAZIN", cb); } if (ver.from(DwgVersion.R2007)) { // BS : DIMARCSYM hdrVars.sDimarcsym = readBitShort(buf, offset.get(), bitOffset.get(), "DIMARCSYM", cb); } // BD : DIMTXT hdrVars.dDimtxt = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMTXT", cb); // BD : DIMCEN hdrVars.dDimcen = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMCEN", cb); // BD : DIMTSZ hdrVars.dDimtsz = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMTSZ", cb); // BD : DIMALTF hdrVars.dDimaltf = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMALTF", cb); // BD : DIMLFAC hdrVars.dDimlfac = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMLFAC", cb); // BD : DIMTVP hdrVars.dDimtvp = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMTVP", cb); // BD : DIMTFAC hdrVars.dDimtfac = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMTFAC", cb); // BD : DIMGAP hdrVars.dDimgap = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMGAP", cb); if (ver.between(DwgVersion.R13, DwgVersion.R14)) { // T : DIMPOST hdrVars.tDimpost = readText(buf, offset.get(), bitOffset.get(), "DIMPOST", cb); // T : DIMAPOST hdrVars.tDimapost = readText(buf, offset.get(), bitOffset.get(), "DIMAPOST", cb); // T : DIMBLK hdrVars.tDimblk = readText(buf, offset.get(), bitOffset.get(), "DIMBLK", cb); // T : DIMBLK1 hdrVars.tDimblk1 = readText(buf, offset.get(), bitOffset.get(), "DIMBLK1", cb); // T : DIMBLK2 hdrVars.tDimblk2 = readText(buf, offset.get(), bitOffset.get(), "DIMBLK2", cb); } if (ver.from(DwgVersion.R2000)) { // BD : DIMALTRND hdrVars.dDimaltrnd = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMALTRND", cb); // B : DIMALT hdrVars.bDimalt = readBit(buf, offset.get(), bitOffset.get(), "DIMALT", cb); // BS : DIMALTD hdrVars.sDimaltd = readBitShort(buf, offset.get(), bitOffset.get(), "DIMALTD", cb); // B : DIMTOFL hdrVars.bDimtofl = readBit(buf, offset.get(), bitOffset.get(), "DIMTOFL", cb); // B : DIMSAH hdrVars.bDimsah = readBit(buf, offset.get(), bitOffset.get(), "DIMSAH", cb); // B : DIMTIX hdrVars.bDimtix = readBit(buf, offset.get(), bitOffset.get(), "DIMTIX", cb); // B : DIMSOXD hdrVars.bDimsoxd = readBit(buf, offset.get(), bitOffset.get(), "DIMSOXD", cb); } // CMC : DIMCLRD hdrVars.cmDimclrd = readCmColor(buf, offset.get(), bitOffset.get(), ver, "DIMCLRD", cb); // CMC : DIMCLRE hdrVars.cmDimclre = readCmColor(buf, offset.get(), bitOffset.get(), ver, "DIMCLRE", cb); // CMC : DIMCLRT hdrVars.cmDimclrt = readCmColor(buf, offset.get(), bitOffset.get(), ver, "DIMCLRT", cb); if (ver.from(DwgVersion.R2000)) { // BS : DIMADEC hdrVars.sDimadec = readBitShort(buf, offset.get(), bitOffset.get(), "DIMADEC", cb); // BS : DIMDEC hdrVars.sDimdec = readBitShort(buf, offset.get(), bitOffset.get(), "DIMDEC", cb); // BS : DIMTDEC hdrVars.sDimtdec = readBitShort(buf, offset.get(), bitOffset.get(), "DIMTDEC", cb); // BS : DIMALTU hdrVars.sDimaltu = readBitShort(buf, offset.get(), bitOffset.get(), "DIMALTU", cb); // BS : DIMALTTD hdrVars.sDimalttd = readBitShort(buf, offset.get(), bitOffset.get(), "DIMALTTD", cb); // BS : DIMAUNIT hdrVars.sDimaunit = readBitShort(buf, offset.get(), bitOffset.get(), "DIMAUNIT", cb); // BS : DIMFRAC hdrVars.sDimfrac = readBitShort(buf, offset.get(), bitOffset.get(), "DIMFRAC", cb); // BS : DIMLUNIT hdrVars.sDimlunit = readBitShort(buf, offset.get(), bitOffset.get(), "DIMLUNIT", cb); // BS : DIMDSEP hdrVars.sDimdsep = readBitShort(buf, offset.get(), bitOffset.get(), "DIMDSEP", cb); // BS : DIMTMOVE hdrVars.sDimtmove = readBitShort(buf, offset.get(), bitOffset.get(), "DIMTMOVE", cb); // BS : DIMJUST hdrVars.sDimjust = readBitShort(buf, offset.get(), bitOffset.get(), "DIMJUST", cb); // B : DIMSD1 hdrVars.bDimsd1 = readBit(buf, offset.get(), bitOffset.get(), "DIMSD1", cb); // B : DIMSD2 hdrVars.bDimsd2 = readBit(buf, offset.get(), bitOffset.get(), "DIMSD2", cb); // BS : DIMTOLJ hdrVars.sDimtolj = readBitShort(buf, offset.get(), bitOffset.get(), "DIMTOLJ", cb); // BS : DIMTZIN hdrVars.sDimtzin = readBitShort(buf, offset.get(), bitOffset.get(), "DIMTZIN", cb); // BS : DIMALTZ hdrVars.sDimaltz = readBitShort(buf, offset.get(), bitOffset.get(), "DIMALTZ", cb); // BS : DIMALTTZ hdrVars.sDimalttz = readBitShort(buf, offset.get(), bitOffset.get(), "DIMALTTZ", cb); // B : DIMUPT hdrVars.bDimupt = readBit(buf, offset.get(), bitOffset.get(), "DIMUPT", cb); // BS : DIMATFIT hdrVars.sDimatfit = readBitShort(buf, offset.get(), bitOffset.get(), "DIMATFIT", cb); } if (ver.from(DwgVersion.R2007)) { // B : DIMFXLON hdrVars.bDimfxlon = readBit(buf, offset.get(), bitOffset.get(), "DIMFXLON", cb); } if (ver.from(DwgVersion.R2010)) { // B : DIMTXTDIRECTION hdrVars.bDimtxtdirection = readBit(buf, offset.get(), bitOffset.get(), "DIMTXTDIRECTION", cb); // BD : DIMALTMZF hdrVars.dDimaltmzf = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMALTMZF", cb); // T : DIMALTMZS hdrVars.tDimaltmzs = readText(buf, offset.get(), bitOffset.get(), "DIMALTMZS", cb); // BD : DIMMZF hdrVars.dDimmzf = readBitDouble(buf, offset.get(), bitOffset.get(), "DIMMZF", cb); // T : DIMMZS hdrVars.tDimmzs = readText(buf, offset.get(), bitOffset.get(), "DIMMZS", cb); } if (ver.from(DwgVersion.R2000)) { // H : DIMTXSTY (hard pointer) hdrVars.hDimtxsty = readHandle(buf, offset.get(), bitOffset.get(), "DIMTXSTY", cb); // H : DIMLDRBLK (hard pointer) hdrVars.hDimldrblk = readHandle(buf, offset.get(), bitOffset.get(), "DIMLDRBLK", cb); // H : DIMBLK (hard pointer) hdrVars.hDimblk = readHandle(buf, offset.get(), bitOffset.get(), "DIMBLK", cb); // H : DIMBLK1 (hard pointer) hdrVars.hDimblk1 = readHandle(buf, offset.get(), bitOffset.get(), "DIMBLK1", cb); // H : DIMBLK2 (hard pointer) hdrVars.hDimblk2 = readHandle(buf, offset.get(), bitOffset.get(), "DIMBLK2", cb); } if (ver.from(DwgVersion.R2007)) { // H : DIMLTYPE (hard pointer) hdrVars.hDimltype = readHandle(buf, offset.get(), bitOffset.get(), "DIMLTYPE", cb); // H : DIMLTEX1 (hard pointer) hdrVars.hDimltex1 = readHandle(buf, offset.get(), bitOffset.get(), "DIMLTEX1", cb); // H : DIMLTEX2 (hard pointer) hdrVars.hDimltex2 = readHandle(buf, offset.get(), bitOffset.get(), "DIMLTEX2", cb); } if (ver.from(DwgVersion.R2000)) { // BS : DIMLWD hdrVars.sDimlwd = readBitShort(buf, offset.get(), bitOffset.get(), "DIMLWD", cb); // BS : DIMLWE hdrVars.sDimlwe = readBitShort(buf, offset.get(), bitOffset.get(), "DIMLWE", cb); } // H : BLOCK CONTROL OBJECT (hard owner) hdrVars.hBlockCtrlObj = readHandle(buf, offset.get(), bitOffset.get(), "BLOCK CONTROL OBJECT", cb); // H : LAYER CONTROL OBJECT (hard owner) hdrVars.hLayerCtrlObj = readHandle(buf, offset.get(), bitOffset.get(), "LAYER CONTROL OBJECT", cb); // H : STYLE CONTROL OBJECT (hard owner) hdrVars.hStyleCtrlObj = readHandle(buf, offset.get(), bitOffset.get(), "STYLE CONTROL OBJECT", cb); // H : LINETYPE CONTROL OBJECT (hard owner) hdrVars.hLinetypeCtrlObj = readHandle(buf, offset.get(), bitOffset.get(), "LINETYPE CONTROL OBJECT", cb); // H : VIEW CONTROL OBJECT (hard owner) hdrVars.hViewCtrlObj = readHandle(buf, offset.get(), bitOffset.get(), "VIEW CONTROL OBJECT", cb); // H : UCS CONTROL OBJECT (hard owner) hdrVars.hUcsCtrlObj = readHandle(buf, offset.get(), bitOffset.get(), "UCS CONTROL OBJECT", cb); // H : VPORT CONTROL OBJECT (hard owner) hdrVars.hVportCtrlObj = readHandle(buf, offset.get(), bitOffset.get(), "VPORT CONTROL OBJECT", cb); // H : APPID CONTROL OBJECT (hard owner) hdrVars.hAppidCtrlObj = readHandle(buf, offset.get(), bitOffset.get(), "APPID CONTROL OBJECT", cb); // H : DIMSTYLE CONTROL OBJECT (hard owner) hdrVars.hDimstyleCtrlObj = readHandle(buf, offset.get(), bitOffset.get(), "DIMSTYLE CONTROL OBJECT", cb); if (ver.between(DwgVersion.R13, DwgVersion.R15)) { // H : VIEWPORT ENTITY HEADER CONTROL OBJECT (hard owner) hdrVars.hViewportEttyHdrCtrlObj = readHandle(buf, offset.get(), bitOffset.get(), "VIEWPORT ENTITY HEADER CONTROL OBJECT", cb); } // H : DICTIONARY (ACAD_GROUP) (hard pointer) hdrVars.hDictionaryAcadGroup = readHandle(buf, offset.get(), bitOffset.get(), "DICTIONARY (ACAD_GROUP)", cb); // H : DICTIONARY (ACAD_MLINESTYLE) (hard pointer) hdrVars.hDictionaryAcadMlinestyle = readHandle(buf, offset.get(), bitOffset.get(), "DICTIONARY (ACAD_MLINESTYLE)", cb); // H : DICTIONARY (NAMED OBJECTS) (hard owner) hdrVars.hDictionaryNamedObjs = readHandle(buf, offset.get(), bitOffset.get(), "DICTIONARY (NAMED OBJECTS)", cb); if (ver.from(DwgVersion.R2000)) { // BS : TSTACKALIGN, default = 1 (not present in DXF) hdrVars.sTstackalign = readBitShort(buf, offset.get(), bitOffset.get(), "TSTACKALIGN", cb); // BS : TSTACKSIZE, default = 70 (not present in DXF) hdrVars.sTstacksize = readBitShort(buf, offset.get(), bitOffset.get(), "TSTACKSIZE", cb); // TV : HYPERLINKBASE hdrVars.tHyperlinkbase = readVariableText(buf, offset.get(), bitOffset.get(), ver, "HYPERLINKBASE", cb); // TV : STYLESHEET hdrVars.tStylesheet = readVariableText(buf, offset.get(), bitOffset.get(), ver, "STYLESHEET", cb); // H : DICTIONARY (LAYOUTS) (hard pointer) hdrVars.hDictionaryLayouts = readHandle(buf, offset.get(), bitOffset.get(), "DICTIONARY (LAYOUTS)", cb); // H : DICTIONARY (PLOTSETTINGS) (hard pointer) hdrVars.hDictionaryPlotsettings = readHandle(buf, offset.get(), bitOffset.get(), "DICTIONARY (PLOTSETTINGS)", cb); // H : DICTIONARY (PLOTSTYLES) (hard pointer) hdrVars.hDictionaryPlotstyles = readHandle(buf, offset.get(), bitOffset.get(), "DICTIONARY (PLOTSTYLES)", cb); } if (ver.from(DwgVersion.R2004)) { // H : DICTIONARY (MATERIALS) (hard pointer) hdrVars.hDictionaryMaterials = readHandle(buf, offset.get(), bitOffset.get(), "DICTIONARY (MATERIALS)", cb); // H : DICTIONARY (COLORS) (hard pointer) hdrVars.hDictionaryColors = readHandle(buf, offset.get(), bitOffset.get(), "DICTIONARY (COLORS)", cb); } if (ver.from(DwgVersion.R2007)) { // H : DICTIONARY (VISUALSTYLE) (hard pointer) hdrVars.hDictionaryVisualstyle = readHandle(buf, offset.get(), bitOffset.get(), "DICTIONARY (VISUALSTYLE)", cb); } if (ver.from(DwgVersion.R2013)) { // H : UNKNOWN (hard pointer) hUnknown = readHandle(buf, offset.get(), bitOffset.get(), "UNKNOWN", cb); } if (ver.from(DwgVersion.R2000)) { // BL : Flags:CELWEIGHT Flags & 0x001F, ENDCAPS Flags & 0x0060, JOINSTYLE Flags & 0x0180, LWDISPLAY !(Flags & 0x0200) //XEDIT !(Flags & 0x0400), EXTNAMES Flags & 0x0800, PSTYLEMODE Flags & 0x2000, OLESTARTUP Flags & 0x4000 hdrVars.lFlags = readBitLong(buf, offset.get(), bitOffset.get(), "Flags", cb); // BS : INSUNITS hdrVars.sInsunits = readBitShort(buf, offset.get(), bitOffset.get(), "INSUNITS", cb); // BS : CEPSNTYPE hdrVars.sCepsntype = readBitShort(buf, offset.get(), bitOffset.get(), "CEPSNTYPE", cb); // H : CPSNID (present only if CEPSNTYPE == 3) (hard pointer) hdrVars.hCpsnid = readHandle(buf, offset.get(), bitOffset.get(), "CPSNID", cb); // TV : FINGERPRINTGUID hdrVars.tFingerprintguid = readVariableText(buf, offset.get(), bitOffset.get(), ver, "FINGERPRINTGUID", cb); // TV : VERSIONGUID hdrVars.tVersionguid = readVariableText(buf, offset.get(), bitOffset.get(), ver, "VERSIONGUID", cb); } if (ver.from(DwgVersion.R2004)) { // RC : SORTENTS // RC : INDEXCTL // RC : HIDETEXT // RC : XCLIPFRAME, before R2010 the value can be 0 or 1 only. // RC : DIMASSOC // RC : HALOGAP // BS : OBSCUREDCOLOR hdrVars.sObscuredcolor = readBitShort(buf, offset.get(), bitOffset.get(), "OBSCUREDCOLOR", cb); // BS : INTERSECTIONCOLOR hdrVars.sIntersectioncolor = readBitShort(buf, offset.get(), bitOffset.get(), "INTERSECTIONCOLOR", cb); // RC : OBSCUREDLTYPE // RC : INTERSECTIONDISPLAY // TV : PROJECTNAME hdrVars.tProjectname = readVariableText(buf, offset.get(), bitOffset.get(), ver, "PROJECTNAME", cb); } // H : BLOCK_RECORD (*PAPER_SPACE) (hard pointer) hdrVars.hBlockRecordPaperSpace = readHandle(buf, offset.get(), bitOffset.get(), "BLOCK_RECORD (*PAPER_SPACE)", cb); // H : BLOCK_RECORD (*MODEL_SPACE) (hard pointer) hdrVars.hBlockRecordModelSpace = readHandle(buf, offset.get(), bitOffset.get(), "BLOCK_RECORD (*MODEL_SPACE)", cb); // H : LTYPE (BYLAYER) (hard pointer) hdrVars.hLtypeBylayer = readHandle(buf, offset.get(), bitOffset.get(), "LTYPE (BYLAYER)", cb); // H : LTYPE (BYBLOCK) (hard pointer) hdrVars.hLtypeByblock = readHandle(buf, offset.get(), bitOffset.get(), "LTYPE (BYBLOCK)", cb); // H : LTYPE (CONTINUOUS) (hard pointer) hdrVars.hLtypeContinuous = readHandle(buf, offset.get(), bitOffset.get(), "LTYPE (CONTINUOUS)", cb); if (ver.from(DwgVersion.R2007)) { // B : CAMERADISPLAY hdrVars.bCameradisplay = readBit(buf, offset.get(), bitOffset.get(), "CAMERADISPLAY", cb); // BL : unknown lUnknown = readBitLong(buf, offset.get(), bitOffset.get(), "Unknown", cb); // BL : unknown lUnknown = readBitLong(buf, offset.get(), bitOffset.get(), "Unknown", cb); // BD : unknown dUnknown = readBitDouble(buf, offset.get(), bitOffset.get(), "Unknown", cb); // BD : STEPSPERSEC hdrVars.dStepspersec = readBitDouble(buf, offset.get(), bitOffset.get(), "STEPSPERSEC", cb); // BD : STEPSIZE hdrVars.dStepsize = readBitDouble(buf, offset.get(), bitOffset.get(), "STEPSIZE", cb); // BD : 3DDWFPREC hdrVars.d3ddwfprec = readBitDouble(buf, offset.get(), bitOffset.get(), "3DDWFPREC", cb); // BD : LENSLENGTH hdrVars.dLenslength = readBitDouble(buf, offset.get(), bitOffset.get(), "LENSLENGTH", cb); // BD : CAMERAHEIGHT hdrVars.dCameraheight = readBitDouble(buf, offset.get(), bitOffset.get(), "CAMERAHEIGHT", cb); // RC : SOLIDHIST // RC : SHOWHIST // BD : PSOLWIDTH hdrVars.dPsolwidth = readBitDouble(buf, offset.get(), bitOffset.get(), "PSOLWIDTH", cb); // BD : PSOLHEIGHT hdrVars.dPsolheight = readBitDouble(buf, offset.get(), bitOffset.get(), "PSOLHEIGHT", cb); // BD : LOFTANG1 hdrVars.dLoftang1 = readBitDouble(buf, offset.get(), bitOffset.get(), "LOFTANG1", cb); // BD : LOFTANG2 hdrVars.dLoftang2 = readBitDouble(buf, offset.get(), bitOffset.get(), "LOFTANG2", cb); // BD : LOFTMAG1 hdrVars.dLoftmag1 = readBitDouble(buf, offset.get(), bitOffset.get(), "LOFTMAG1", cb); // BD : LOFTMAG2 hdrVars.dLoftmag2 = readBitDouble(buf, offset.get(), bitOffset.get(), "LOFTMAG2", cb); // BS : LOFTPARAM hdrVars.sLoftparam = readBitShort(buf, offset.get(), bitOffset.get(), "LOFTPARAM", cb); // RC : LOFTNORMALS // BD : LATITUDE hdrVars.dLatitude = readBitDouble(buf, offset.get(), bitOffset.get(), "LATITUDE", cb); // BD : LONGITUDE hdrVars.dLongitude = readBitDouble(buf, offset.get(), bitOffset.get(), "LONGITUDE", cb); // BD : NORTHDIRECTION hdrVars.dNorthdirection = readBitDouble(buf, offset.get(), bitOffset.get(), "NORTHDIRECTION", cb); // BL : TIMEZONE hdrVars.lTimezone = readBitLong(buf, offset.get(), bitOffset.get(), "Unknown", cb); // RC : LIGHTGLYPHDISPLAY // RC : TILEMODELIGHTSYNCH // RC : DWFFRAME // RC : DGNFRAME // B : unknown bUnknown = readBit(buf, offset.get(), bitOffset.get(), "unknown", cb); // CMC : INTERFERECOLOR hdrVars.cmInterferecolor = readCmColor(buf, offset.get(), bitOffset.get(), ver, "INTERFERECOLOR", cb); // H : INTERFEREOBJVS (hard pointer) hdrVars.hInterfereobjvs = readHandle(buf, offset.get(), bitOffset.get(), "INTERFEREOBJVS", cb); // H : INTERFEREVPVS (hard pointer) hdrVars.hInterferevpvs = readHandle(buf, offset.get(), bitOffset.get(), "INTERFEREVPVS", cb); // H : DRAGVS (hard pointer) hdrVars.hDragvs = readHandle(buf, offset.get(), bitOffset.get(), "DRAGVS", cb); // RC : CSHADOW // BD : unknown dUnknown = readBitDouble(buf, offset.get(), bitOffset.get(), "Unknown", cb); } if (ver.from(DwgVersion.R14)) { //BS : unknown short (type 5/6 only) these do not seem to be required, sUnknown = readBitShort(buf, offset.get(), bitOffset.get(), "Unknown", cb); //BS : unknown short (type 5/6 only) even for type 5. sUnknown = readBitShort(buf, offset.get(), bitOffset.get(), "Unknown", cb); //BS : unknown short (type 5/6 only) sUnknown = readBitShort(buf, offset.get(), bitOffset.get(), "Unknown", cb); //BS : unknown short (type 5/6 only) sUnknown = readBitShort(buf, offset.get(), bitOffset.get(), "Unknown", cb); } // RS : CRC for the data section, starting after the sentinel. Use 0xC0C1 for the initial value. return hdrVars; } public static Map<Integer, DrawingClass> readClassSection(byte[] buf, int off, Dwg dwg, DwgVersion ver) { Map<Integer, DrawingClass> drwingClassMap = new HashMap<>(); AtomicInteger offset = new AtomicInteger(off); AtomicInteger bitOffset = new AtomicInteger(0); int reBitOffset = 0; if (ver.between(DwgVersion.R13, DwgVersion.R15)) { DecodeCallback cb = new DecodeCallback() { public void onDecoded(String name, Object value, int retBitOffset) { log.info("[" + name+ "] = (" + value.toString() + ")"); offset.addAndGet((bitOffset.get()+retBitOffset)/8); bitOffset.set((bitOffset.get()+retBitOffset)%8); } }; // beginning sentinel // 0x8D 0xA1 0xC4-xA9 0xF8 0xC5 0xDC 0xF4 0x5F 0xE7 0xCF 0xB6 0x*a offset.addAndGet(16); // size of class date area int sizeClasses = readRawLong(buf, offset.get(), bitOffset.get(), "size of classes data area", cb); // read sets until exhaust the data while(offset.get()-2-16 < sizeClasses) { log.fine("CLASS SECTION read : " + (offset.get()-2-16) + ", Total Size: " + sizeClasses); DrawingClass dc = new DrawingClass(); // classnum dc.classnum = readBitShort(buf, offset.get(), bitOffset.get(), "classnum", cb); // version dc.version = readBitShort(buf, offset.get(), bitOffset.get(), "version", cb); // appname dc.appname = readVariableText(buf, offset.get(), bitOffset.get(), ver, "appname", cb); // cplusplusclassname dc.cplusplusclassname = readVariableText(buf, offset.get(), bitOffset.get(), ver, "c++cplusplusclassname", cb); // classdxfname dc.classdxfname = readVariableText(buf, offset.get(), bitOffset.get(), ver, "classdxfname", cb); // wasazombie dc.waszombie = readBit(buf, offset.get(), bitOffset.get(), "c++wasazomebie", cb); // itemclassid dc.itemclassid = readBitShort(buf, offset.get(), bitOffset.get(), "itemclassid", cb); drwingClassMap.put((int)dc.classnum, dc); } // RS: CRC int crc = readBitShort(buf, offset.get(), bitOffset.get(), "CRC", cb); // 16 byte sentinel apprears after the CRC // 0x72,0x5E,0x3B,0x47,0x3B,0x56,0x07,0x3A,0x3F,0x23,0x0B,0xA0,0x180x30,0x49,0x75 // PADDING random bits to the next byte boundary if (bitOffset.get()>0) { bitOffset.set(0);; offset.addAndGet(1); } byte[] compareBytes = new byte[16]; System.arraycopy(buf, offset.get(), compareBytes, 0, 16); offset.addAndGet(16); byte[] endingSentinel = { (byte)0x72, (byte)0x5E,(byte)0x3B,(byte)0x47,(byte)0x3B,(byte)0x56,(byte)0x07,(byte)0x3A, (byte)0x3F,(byte)0x23,(byte)0x0B,(byte)0xA0,(byte)0x18,(byte)0x30,(byte)0x49,(byte)0x75 }; if (Arrays.equals(compareBytes, endingSentinel)==false) { log.severe("Ending Sentinel mismatched!!!"); } } else if (ver.from(DwgVersion.R18)) { // section is compressed, contains the standard 32byte section header
byte[] decomBuf = DecoderR2004.decompressR18(buf, offset.get());
2
2023-11-11 13:57:18+00:00
16k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/predictionengine/PlayerBaseTick.java
[ { "identifier": "GrimPlayer", "path": "src/main/java/ac/grim/grimac/player/GrimPlayer.java", "snippet": "public class GrimPlayer {\n public final UUID playerUUID;\n public final int entityID;\n public final Player bukkitPlayer;\n // Determining player ping\n // The difference between keep...
import ac.grim.grimac.player.GrimPlayer; import ac.grim.grimac.utils.collisions.datatypes.SimpleCollisionBox; import ac.grim.grimac.utils.enums.EntityType; import ac.grim.grimac.utils.enums.FluidTag; import ac.grim.grimac.utils.enums.Pose; import ac.grim.grimac.utils.math.GrimMath; import ac.grim.grimac.utils.nmsutil.*; import io.github.retrooper.packetevents.utils.player.ClientVersion; import org.bukkit.World; import org.bukkit.block.BlockFace; import org.bukkit.util.Vector;
12,243
package ac.grim.grimac.predictionengine; public class PlayerBaseTick { GrimPlayer player; public PlayerBaseTick(GrimPlayer player) { this.player = player; } public static boolean canEnterPose(GrimPlayer player, Pose pose, double x, double y, double z) { return Collisions.isEmpty(player, getBoundingBoxForPose(pose, x, y, z).expand(-1.0E-7D)); } protected static SimpleCollisionBox getBoundingBoxForPose(Pose pose, double x, double y, double z) { float radius = pose.width / 2.0F; return new SimpleCollisionBox(x - radius, y, z - radius, x + radius, y + pose.height, z + radius, false); } public void doBaseTick() { // Keep track of basetick stuff player.baseTickAddition = new Vector(); player.baseTickWaterPushing = new Vector(); if (player.specialFlying && player.isSneaking && !player.inVehicle) { player.baseTickAddVector(new Vector(0, player.flySpeed * -3, 0)); } updateInWaterStateAndDoFluidPushing(); updateFluidOnEyes(); updateSwimming(); // If in lava, fall distance is multiplied by 0.5 if (player.wasTouchingLava) player.fallDistance *= 0.5; // You cannot crouch while flying, only shift - could be specific to 1.14? if (player.wasTouchingWater && player.isSneaking && !player.specialFlying && !player.inVehicle) { player.baseTickAddVector(new Vector(0, -0.04, 0)); } // LocalPlayer:aiStep determining crouching // Tick order is entityBaseTick and then the aiStep stuff // This code is in the wrong place, I'll fix it later player.isCrouching = player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_14) ? !player.wasFlying && !player.isSwimming && canEnterPose(player, Pose.CROUCHING, player.lastX, player.lastY, player.lastZ) && ((player.isCrouching || player.getClientVersion().isNewerThan(ClientVersion.v_1_14_4) ? player.wasSneaking : player.isSneaking) || player.isInBed || !canEnterPose(player, Pose.STANDING, player.lastX, player.lastY, player.lastZ)) : player.isSneaking; // Sneaking on 1.7-1.13 is just the status the player sends us. Nothing complicated. player.isSlowMovement = player.isCrouching || (player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_14) && // If the player is in the swimming pose // Or if the player is not gliding, and the player's pose is fall flying // and the player is not touching water (yes, this also can override the gliding slowness) (player.pose == Pose.SWIMMING || (!player.isGliding && player.pose == Pose.FALL_FLYING)) && !player.wasTouchingWater); // Players in boats don't care about being in blocks if (!player.inVehicle) { this.moveTowardsClosestSpace(player.lastX - (player.boundingBox.maxX - player.boundingBox.minX) * 0.35, player.lastZ + (player.boundingBox.maxZ - player.boundingBox.minZ) * 0.35); this.moveTowardsClosestSpace(player.lastX - (player.boundingBox.maxX - player.boundingBox.minX) * 0.35, player.lastZ - (player.boundingBox.maxZ - player.boundingBox.minZ) * 0.35); this.moveTowardsClosestSpace(player.lastX + (player.boundingBox.maxX - player.boundingBox.minX) * 0.35, player.lastZ - (player.boundingBox.maxZ - player.boundingBox.minZ) * 0.35); this.moveTowardsClosestSpace(player.lastX + (player.boundingBox.maxX - player.boundingBox.minX) * 0.35, player.lastZ + (player.boundingBox.maxZ - player.boundingBox.minZ) * 0.35); } float f = BlockProperties.getBlockSpeedFactor(player); player.blockSpeedMultiplier = new Vector(f, 1.0, f); if (player.getClientVersion().isOlderThan(ClientVersion.v_1_14)) { updatePlayerSize(); } } // 1.16 eye in water is a tick behind // 1.15 eye in water is the most recent result private void updateFluidOnEyes() {
package ac.grim.grimac.predictionengine; public class PlayerBaseTick { GrimPlayer player; public PlayerBaseTick(GrimPlayer player) { this.player = player; } public static boolean canEnterPose(GrimPlayer player, Pose pose, double x, double y, double z) { return Collisions.isEmpty(player, getBoundingBoxForPose(pose, x, y, z).expand(-1.0E-7D)); } protected static SimpleCollisionBox getBoundingBoxForPose(Pose pose, double x, double y, double z) { float radius = pose.width / 2.0F; return new SimpleCollisionBox(x - radius, y, z - radius, x + radius, y + pose.height, z + radius, false); } public void doBaseTick() { // Keep track of basetick stuff player.baseTickAddition = new Vector(); player.baseTickWaterPushing = new Vector(); if (player.specialFlying && player.isSneaking && !player.inVehicle) { player.baseTickAddVector(new Vector(0, player.flySpeed * -3, 0)); } updateInWaterStateAndDoFluidPushing(); updateFluidOnEyes(); updateSwimming(); // If in lava, fall distance is multiplied by 0.5 if (player.wasTouchingLava) player.fallDistance *= 0.5; // You cannot crouch while flying, only shift - could be specific to 1.14? if (player.wasTouchingWater && player.isSneaking && !player.specialFlying && !player.inVehicle) { player.baseTickAddVector(new Vector(0, -0.04, 0)); } // LocalPlayer:aiStep determining crouching // Tick order is entityBaseTick and then the aiStep stuff // This code is in the wrong place, I'll fix it later player.isCrouching = player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_14) ? !player.wasFlying && !player.isSwimming && canEnterPose(player, Pose.CROUCHING, player.lastX, player.lastY, player.lastZ) && ((player.isCrouching || player.getClientVersion().isNewerThan(ClientVersion.v_1_14_4) ? player.wasSneaking : player.isSneaking) || player.isInBed || !canEnterPose(player, Pose.STANDING, player.lastX, player.lastY, player.lastZ)) : player.isSneaking; // Sneaking on 1.7-1.13 is just the status the player sends us. Nothing complicated. player.isSlowMovement = player.isCrouching || (player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_14) && // If the player is in the swimming pose // Or if the player is not gliding, and the player's pose is fall flying // and the player is not touching water (yes, this also can override the gliding slowness) (player.pose == Pose.SWIMMING || (!player.isGliding && player.pose == Pose.FALL_FLYING)) && !player.wasTouchingWater); // Players in boats don't care about being in blocks if (!player.inVehicle) { this.moveTowardsClosestSpace(player.lastX - (player.boundingBox.maxX - player.boundingBox.minX) * 0.35, player.lastZ + (player.boundingBox.maxZ - player.boundingBox.minZ) * 0.35); this.moveTowardsClosestSpace(player.lastX - (player.boundingBox.maxX - player.boundingBox.minX) * 0.35, player.lastZ - (player.boundingBox.maxZ - player.boundingBox.minZ) * 0.35); this.moveTowardsClosestSpace(player.lastX + (player.boundingBox.maxX - player.boundingBox.minX) * 0.35, player.lastZ - (player.boundingBox.maxZ - player.boundingBox.minZ) * 0.35); this.moveTowardsClosestSpace(player.lastX + (player.boundingBox.maxX - player.boundingBox.minX) * 0.35, player.lastZ + (player.boundingBox.maxZ - player.boundingBox.minZ) * 0.35); } float f = BlockProperties.getBlockSpeedFactor(player); player.blockSpeedMultiplier = new Vector(f, 1.0, f); if (player.getClientVersion().isOlderThan(ClientVersion.v_1_14)) { updatePlayerSize(); } } // 1.16 eye in water is a tick behind // 1.15 eye in water is the most recent result private void updateFluidOnEyes() {
player.wasEyeInWater = player.isEyeInFluid(FluidTag.WATER);
3
2023-11-11 05:14:12+00:00
16k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/ui/activity/PersonalDataActivity.java
[ { "identifier": "AppActivity", "path": "app/src/main/java/com/buaa/food/app/AppActivity.java", "snippet": "public abstract class AppActivity extends BaseActivity\n implements ToastAction, TitleBarAction, OnHttpListener<Object> {\n\n /** 标题栏对象 */\n private TitleBar mTitleBar;\n /** 状态栏沉浸 ...
import android.net.Uri; import android.os.Build; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.buaa.food.http.glide.GlideApp; import com.bumptech.glide.load.MultiTransformation; import com.bumptech.glide.load.resource.bitmap.CenterCrop; import com.bumptech.glide.load.resource.bitmap.CircleCrop; import com.buaa.food.R; import com.buaa.food.aop.SingleClick; import com.buaa.food.app.AppActivity; import com.buaa.food.http.api.UpdateImageApi; import com.buaa.food.http.model.HttpData; import com.buaa.food.ui.dialog.AddressDialog; import com.buaa.food.ui.dialog.InputDialog; import com.hjq.http.EasyHttp; import com.hjq.http.listener.HttpCallback; import com.hjq.http.model.FileContentResolver; import com.hjq.widget.layout.SettingBar; import java.io.File; import java.net.URI; import java.net.URISyntaxException;
11,566
package com.buaa.food.ui.activity; public final class PersonalDataActivity extends AppActivity { private ViewGroup mAvatarLayout; private ImageView mAvatarView; private SettingBar mIdView; private SettingBar mNameView; private SettingBar mAddressView; /** 省 */ private String mProvince = "广东省"; /** 市 */ private String mCity = "广州市"; /** 区 */ private String mArea = "天河区"; /** 头像地址 */ private Uri mAvatarUrl; @Override protected int getLayoutId() { return R.layout.personal_data_activity; } @Override protected void initView() { mAvatarLayout = findViewById(R.id.fl_person_data_avatar); mAvatarView = findViewById(R.id.iv_person_data_avatar); mIdView = findViewById(R.id.sb_person_data_id); mNameView = findViewById(R.id.sb_person_data_name); setOnClickListener(mAvatarLayout, mAvatarView, mNameView, mAddressView); } @Override protected void initData() { GlideApp.with(getActivity()) .load(R.drawable.avatar_placeholder_ic) .placeholder(R.drawable.avatar_placeholder_ic) .error(R.drawable.avatar_placeholder_ic) .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop())) .into(mAvatarView); mIdView.setRightText("880634"); mNameView.setRightText("彭莘"); String address = mProvince + mCity + mArea; mAddressView.setRightText(address); } @SingleClick @Override public void onClick(View view) { if (view == mAvatarLayout) { ImageSelectActivity.start(this, data -> { // 裁剪头像 cropImageFile(new File(data.get(0))); }); } else if (view == mAvatarView) { if (mAvatarUrl != null) { // 查看头像 ImagePreviewActivity.start(getActivity(), mAvatarUrl.toString()); } else { // 选择头像 onClick(mAvatarLayout); } } else if (view == mNameView) { new InputDialog.Builder(this) // 标题可以不用填写 .setTitle(getString(R.string.personal_data_name_hint)) .setContent(mNameView.getRightText()) //.setHint(getString(R.string.personal_data_name_hint)) //.setConfirm("确定") // 设置 null 表示不显示取消按钮 //.setCancel("取消") // 设置点击按钮后不关闭对话框 //.setAutoDismiss(false) .setListener((dialog, content) -> { if (!mNameView.getRightText().equals(content)) { mNameView.setRightText(content); } }) .show(); } else if (view == mAddressView) { new AddressDialog.Builder(this) //.setTitle("选择地区") // 设置默认省份 .setProvince(mProvince) // 设置默认城市(必须要先设置默认省份) .setCity(mCity) // 不选择县级区域 //.setIgnoreArea() .setListener((dialog, province, city, area) -> { String address = province + city + area; if (!mAddressView.getRightText().equals(address)) { mProvince = province; mCity = city; mArea = area; mAddressView.setRightText(address); } }) .show(); } } /** * 裁剪图片 */ private void cropImageFile(File sourceFile) { ImageCropActivity.start(this, sourceFile, 1, 1, new ImageCropActivity.OnCropListener() { @Override public void onSucceed(Uri fileUri, String fileName) { File outputFile; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { outputFile = new FileContentResolver(getActivity(), fileUri, fileName); } else { try { outputFile = new File(new URI(fileUri.toString())); } catch (URISyntaxException e) { e.printStackTrace(); outputFile = new File(fileUri.toString()); } } updateCropImage(outputFile, true); } @Override public void onError(String details) { // 没有的话就不裁剪,直接上传原图片 // 但是这种情况极其少见,可以忽略不计 updateCropImage(sourceFile, false); } }); } /** * 上传裁剪后的图片 */ private void updateCropImage(File file, boolean deleteFile) { if (true) { if (file instanceof FileContentResolver) { mAvatarUrl = ((FileContentResolver) file).getContentUri(); } else { mAvatarUrl = Uri.fromFile(file); } GlideApp.with(getActivity()) .load(mAvatarUrl) .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop())) .into(mAvatarView); return; } EasyHttp.post(this) .api(new UpdateImageApi() .setImage(file))
package com.buaa.food.ui.activity; public final class PersonalDataActivity extends AppActivity { private ViewGroup mAvatarLayout; private ImageView mAvatarView; private SettingBar mIdView; private SettingBar mNameView; private SettingBar mAddressView; /** 省 */ private String mProvince = "广东省"; /** 市 */ private String mCity = "广州市"; /** 区 */ private String mArea = "天河区"; /** 头像地址 */ private Uri mAvatarUrl; @Override protected int getLayoutId() { return R.layout.personal_data_activity; } @Override protected void initView() { mAvatarLayout = findViewById(R.id.fl_person_data_avatar); mAvatarView = findViewById(R.id.iv_person_data_avatar); mIdView = findViewById(R.id.sb_person_data_id); mNameView = findViewById(R.id.sb_person_data_name); setOnClickListener(mAvatarLayout, mAvatarView, mNameView, mAddressView); } @Override protected void initData() { GlideApp.with(getActivity()) .load(R.drawable.avatar_placeholder_ic) .placeholder(R.drawable.avatar_placeholder_ic) .error(R.drawable.avatar_placeholder_ic) .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop())) .into(mAvatarView); mIdView.setRightText("880634"); mNameView.setRightText("彭莘"); String address = mProvince + mCity + mArea; mAddressView.setRightText(address); } @SingleClick @Override public void onClick(View view) { if (view == mAvatarLayout) { ImageSelectActivity.start(this, data -> { // 裁剪头像 cropImageFile(new File(data.get(0))); }); } else if (view == mAvatarView) { if (mAvatarUrl != null) { // 查看头像 ImagePreviewActivity.start(getActivity(), mAvatarUrl.toString()); } else { // 选择头像 onClick(mAvatarLayout); } } else if (view == mNameView) { new InputDialog.Builder(this) // 标题可以不用填写 .setTitle(getString(R.string.personal_data_name_hint)) .setContent(mNameView.getRightText()) //.setHint(getString(R.string.personal_data_name_hint)) //.setConfirm("确定") // 设置 null 表示不显示取消按钮 //.setCancel("取消") // 设置点击按钮后不关闭对话框 //.setAutoDismiss(false) .setListener((dialog, content) -> { if (!mNameView.getRightText().equals(content)) { mNameView.setRightText(content); } }) .show(); } else if (view == mAddressView) { new AddressDialog.Builder(this) //.setTitle("选择地区") // 设置默认省份 .setProvince(mProvince) // 设置默认城市(必须要先设置默认省份) .setCity(mCity) // 不选择县级区域 //.setIgnoreArea() .setListener((dialog, province, city, area) -> { String address = province + city + area; if (!mAddressView.getRightText().equals(address)) { mProvince = province; mCity = city; mArea = area; mAddressView.setRightText(address); } }) .show(); } } /** * 裁剪图片 */ private void cropImageFile(File sourceFile) { ImageCropActivity.start(this, sourceFile, 1, 1, new ImageCropActivity.OnCropListener() { @Override public void onSucceed(Uri fileUri, String fileName) { File outputFile; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { outputFile = new FileContentResolver(getActivity(), fileUri, fileName); } else { try { outputFile = new File(new URI(fileUri.toString())); } catch (URISyntaxException e) { e.printStackTrace(); outputFile = new File(fileUri.toString()); } } updateCropImage(outputFile, true); } @Override public void onError(String details) { // 没有的话就不裁剪,直接上传原图片 // 但是这种情况极其少见,可以忽略不计 updateCropImage(sourceFile, false); } }); } /** * 上传裁剪后的图片 */ private void updateCropImage(File file, boolean deleteFile) { if (true) { if (file instanceof FileContentResolver) { mAvatarUrl = ((FileContentResolver) file).getContentUri(); } else { mAvatarUrl = Uri.fromFile(file); } GlideApp.with(getActivity()) .load(mAvatarUrl) .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop())) .into(mAvatarView); return; } EasyHttp.post(this) .api(new UpdateImageApi() .setImage(file))
.request(new HttpCallback<HttpData<String>>(this) {
2
2023-11-14 10:04:26+00:00
16k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/model/entity/BenchEntityModel.java
[ { "identifier": "AnimationHelper", "path": "src/main/java/useless/dragonfly/helper/AnimationHelper.java", "snippet": "public class AnimationHelper {\n\tpublic static final Map<String, Animation> registeredAnimations = new HashMap<>();\n\n\tpublic static Animation getOrCreateEntityAnimation(String modID,...
import com.google.gson.annotations.SerializedName; import net.minecraft.client.render.model.ModelBase; import org.jetbrains.annotations.Nullable; import org.lwjgl.opengl.GL11; import useless.dragonfly.helper.AnimationHelper; import useless.dragonfly.model.entity.animation.AnimationData; import useless.dragonfly.model.entity.processor.BenchEntityBones; import useless.dragonfly.model.entity.processor.BenchEntityCube; import useless.dragonfly.model.entity.processor.BenchEntityGeometry; import useless.dragonfly.utilities.vector.Vector3f; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional;
12,148
* This method used Translate for item render */ public void postRender(BenchEntityBones bones, float scale) { List<Float> rotation = bones.getRotation(); //parent time before rotate it self if (bones.getParent() != null) { BenchEntityBones parentBone = this.getIndexBones().get(bones.getParent()); convertWithMoreParent(parentBone, scale); } GL11.glTranslatef(convertPivot(bones, 0) * scale, convertPivot(bones, 1) * scale, convertPivot(bones, 2) * scale); if (bones.rotationPointX != 0.0f || bones.rotationPointY != 0.0f || bones.rotationPointZ != 0.0f) { GL11.glTranslatef(bones.rotationPointX * scale, bones.rotationPointY * scale, bones.rotationPointZ * scale); } if (rotation != null) { GL11.glRotatef((float) Math.toRadians(rotation.get(0)), 0.0f, 0.0f, 1.0f); GL11.glRotatef((float) Math.toRadians(rotation.get(1)), 0.0f, 1.0f, 0.0f); GL11.glRotatef((float) Math.toRadians(rotation.get(2)), 1.0f, 0.0f, 0.0f); } if (bones.rotateAngleZ != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleZ)), 0.0f, 0.0f, 1.0f); } if (bones.rotateAngleY != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleY)), 0.0f, 1.0f, 0.0f); } if (bones.rotateAngleX != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleX)), 1.0f, 0.0f, 0.0f); } if (bones.scaleX != 0.0f || bones.scaleY != 0.0f || bones.scaleZ != 0.0f) { GL11.glScalef(bones.scaleX, bones.scaleY, bones.scaleZ); } } private void convertWithMoreParent(BenchEntityBones parentBone, float scale) { //don't forget some parent has more parent if (parentBone.getParent() != null) { convertWithMoreParent(this.getIndexBones().get(parentBone.getParent()), scale); } GL11.glTranslatef(convertPivot(parentBone, 0) * scale, convertPivot(parentBone, 1) * scale, convertPivot(parentBone, 2) * scale); if (parentBone.rotationPointX != 0.0f || parentBone.rotationPointY != 0.0f || parentBone.rotationPointZ != 0.0f) { GL11.glTranslatef(parentBone.rotationPointX * scale, parentBone.rotationPointY * scale, parentBone.rotationPointZ * scale); } if (parentBone.getRotation() != null) { GL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(0)), 0.0f, 0.0f, 1.0f); GL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(1)), 0.0f, 1.0f, 0.0f); GL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(2)), 1.0f, 0.0f, 0.0f); } if (parentBone.rotateAngleZ != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleZ)), 0.0f, 0.0f, 1.0f); } if (parentBone.rotateAngleY != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleY)), 0.0f, 1.0f, 0.0f); } if (parentBone.rotateAngleX != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleX)), 1.0f, 0.0f, 0.0f); } if (parentBone.scaleX != 0.0f || parentBone.scaleY != 0.0f || parentBone.scaleZ != 0.0f) { GL11.glScalef(parentBone.scaleX, parentBone.scaleY, parentBone.scaleZ); } } public float convertPivot(BenchEntityBones bones, int index) { if (bones.getParent() != null) { if (index == 1) { return getIndexBones().get(bones.getParent()).getPivot().get(index) - bones.getPivot().get(index); } else { return bones.getPivot().get(index) - getIndexBones().get(bones.getParent()).getPivot().get(index); } } else { if (index == 1) { return 24 - bones.getPivot().get(index); } else { return bones.getPivot().get(index); } } } public float convertPivot(BenchEntityBones parent, BenchEntityCube cube, int index) { assert cube.getPivot() != null; if (index == 1) { return parent.getPivot().get(index) - cube.getPivot().get(index); } else { return cube.getPivot().get(index) - parent.getPivot().get(index); } } public float convertOrigin(BenchEntityBones bone, BenchEntityCube cube, int index) { if (index == 1) { return bone.getPivot().get(index) - cube.getOrigin().get(index) - cube.getSize().get(index); } else { return cube.getOrigin().get(index) - bone.getPivot().get(index); } } public float convertOrigin(BenchEntityCube cube, int index) { assert cube.getPivot() != null; if (index == 1) { return cube.getPivot().get(index) - cube.getOrigin().get(index) - cube.getSize().get(index); } else { return cube.getOrigin().get(index) - cube.getPivot().get(index); } } public Optional<BenchEntityBones> getAnyDescendantWithName(String key) { Optional<Map.Entry<String, BenchEntityBones>> bones = this.getIndexBones().entrySet().stream().filter((benchBone) -> benchBone.getKey().equals(key)).findFirst(); if (bones.isPresent()) { return Optional.of(bones.get().getValue()); } else { return Optional.empty(); } }
package useless.dragonfly.model.entity; /* * Credit by 0999312! Thanks! * https://github.com/0999312/MMLib/blob/3e87210c9305a5724e06c492be503533a1ebcd59/src/main/java/cn/mcmod_mmf/mmlib/client/model/bedrock/BedrockModel.java */ public class BenchEntityModel extends ModelBase { public Vector3f VEC_ANIMATION = new Vector3f(); private final HashMap<String, BenchEntityBones> indexBones = new HashMap<>(); @SerializedName("format_version") private String formatVersion; @SerializedName("minecraft:geometry") private List<BenchEntityGeometry> benchEntityGeometry; public HashMap<String, BenchEntityBones> getIndexBones() { return indexBones; } @Override public void render(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) { super.render(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale); this.renderModel(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale); } public void renderModel(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) { BenchEntityGeometry entityGeometry = this.benchEntityGeometry.get(0); int texWidth = entityGeometry.getWidth(); int texHeight = entityGeometry.getHeight(); for (BenchEntityBones bones : entityGeometry.getBones()) { if (!this.getIndexBones().containsKey(bones.getName())) { this.getIndexBones().put(bones.getName(), bones); } } if (!this.getIndexBones().isEmpty()) { //DON'T MOVE IT! because the rotation and rotation position of entities of the same model being mixed. this.setRotationAngles(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale); } for (BenchEntityBones bones : entityGeometry.getBones()) { String name = bones.getName(); @Nullable List<Float> rotation = bones.getRotation(); @Nullable String parent = bones.getParent(); if (parent != null) { if (!this.getIndexBones().get(parent).getChildren().contains(bones)) { this.getIndexBones().get(parent).addChild(bones); } } if (bones.getCubes() == null) { continue; } for (BenchEntityCube cube : bones.getCubes()) { List<Float> uv = cube.getUv(); List<Float> size = cube.getSize(); @Nullable List<Float> cubeRotation = cube.getRotation(); boolean mirror = cube.isMirror(); float inflate = cube.getInflate(); cube.addBox(texWidth, texHeight, convertOrigin(bones, cube, 0), convertOrigin(bones, cube, 1), convertOrigin(bones, cube, 2), false); if (!cube.isCompiled()) { cube.compileDisplayList(scale); } GL11.glPushMatrix(); //parent time before rotate it self if (parent != null) { BenchEntityBones parentBone = this.getIndexBones().get(parent); convertWithMoreParent(parentBone, scale); } GL11.glTranslatef(convertPivot(bones, 0) * scale, convertPivot(bones, 1) * scale, convertPivot(bones, 2) * scale); if (bones.rotationPointX != 0.0f || bones.rotationPointY != 0.0f || bones.rotationPointZ != 0.0f) { GL11.glTranslatef(bones.rotationPointX * scale, bones.rotationPointY * scale, bones.rotationPointZ * scale); } if (rotation != null) { GL11.glRotatef((float) Math.toRadians(rotation.get(0)), 0.0f, 0.0f, 1.0f); GL11.glRotatef((float) Math.toRadians(rotation.get(1)), 0.0f, 1.0f, 0.0f); GL11.glRotatef((float) Math.toRadians(rotation.get(2)), 1.0f, 0.0f, 0.0f); } if (bones.rotateAngleZ != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleZ)), 0.0f, 0.0f, 1.0f); } if (bones.rotateAngleY != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleY)), 0.0f, 1.0f, 0.0f); } if (bones.rotateAngleX != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleX)), 1.0f, 0.0f, 0.0f); } if (bones.scaleX != 0.0f || bones.scaleY != 0.0f || bones.scaleZ != 0.0f) { GL11.glScalef(bones.scaleX, bones.scaleY, bones.scaleZ); } GL11.glCallList(cube.getDisplayList()); GL11.glPopMatrix(); } } } /* * This method used Translate for item render */ public void postRender(BenchEntityBones bones, float scale) { List<Float> rotation = bones.getRotation(); //parent time before rotate it self if (bones.getParent() != null) { BenchEntityBones parentBone = this.getIndexBones().get(bones.getParent()); convertWithMoreParent(parentBone, scale); } GL11.glTranslatef(convertPivot(bones, 0) * scale, convertPivot(bones, 1) * scale, convertPivot(bones, 2) * scale); if (bones.rotationPointX != 0.0f || bones.rotationPointY != 0.0f || bones.rotationPointZ != 0.0f) { GL11.glTranslatef(bones.rotationPointX * scale, bones.rotationPointY * scale, bones.rotationPointZ * scale); } if (rotation != null) { GL11.glRotatef((float) Math.toRadians(rotation.get(0)), 0.0f, 0.0f, 1.0f); GL11.glRotatef((float) Math.toRadians(rotation.get(1)), 0.0f, 1.0f, 0.0f); GL11.glRotatef((float) Math.toRadians(rotation.get(2)), 1.0f, 0.0f, 0.0f); } if (bones.rotateAngleZ != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleZ)), 0.0f, 0.0f, 1.0f); } if (bones.rotateAngleY != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleY)), 0.0f, 1.0f, 0.0f); } if (bones.rotateAngleX != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(bones.rotateAngleX)), 1.0f, 0.0f, 0.0f); } if (bones.scaleX != 0.0f || bones.scaleY != 0.0f || bones.scaleZ != 0.0f) { GL11.glScalef(bones.scaleX, bones.scaleY, bones.scaleZ); } } private void convertWithMoreParent(BenchEntityBones parentBone, float scale) { //don't forget some parent has more parent if (parentBone.getParent() != null) { convertWithMoreParent(this.getIndexBones().get(parentBone.getParent()), scale); } GL11.glTranslatef(convertPivot(parentBone, 0) * scale, convertPivot(parentBone, 1) * scale, convertPivot(parentBone, 2) * scale); if (parentBone.rotationPointX != 0.0f || parentBone.rotationPointY != 0.0f || parentBone.rotationPointZ != 0.0f) { GL11.glTranslatef(parentBone.rotationPointX * scale, parentBone.rotationPointY * scale, parentBone.rotationPointZ * scale); } if (parentBone.getRotation() != null) { GL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(0)), 0.0f, 0.0f, 1.0f); GL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(1)), 0.0f, 1.0f, 0.0f); GL11.glRotatef((float) Math.toRadians(parentBone.getRotation().get(2)), 1.0f, 0.0f, 0.0f); } if (parentBone.rotateAngleZ != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleZ)), 0.0f, 0.0f, 1.0f); } if (parentBone.rotateAngleY != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleY)), 0.0f, 1.0f, 0.0f); } if (parentBone.rotateAngleX != 0.0f) { GL11.glRotatef((float) (Math.toDegrees(parentBone.rotateAngleX)), 1.0f, 0.0f, 0.0f); } if (parentBone.scaleX != 0.0f || parentBone.scaleY != 0.0f || parentBone.scaleZ != 0.0f) { GL11.glScalef(parentBone.scaleX, parentBone.scaleY, parentBone.scaleZ); } } public float convertPivot(BenchEntityBones bones, int index) { if (bones.getParent() != null) { if (index == 1) { return getIndexBones().get(bones.getParent()).getPivot().get(index) - bones.getPivot().get(index); } else { return bones.getPivot().get(index) - getIndexBones().get(bones.getParent()).getPivot().get(index); } } else { if (index == 1) { return 24 - bones.getPivot().get(index); } else { return bones.getPivot().get(index); } } } public float convertPivot(BenchEntityBones parent, BenchEntityCube cube, int index) { assert cube.getPivot() != null; if (index == 1) { return parent.getPivot().get(index) - cube.getPivot().get(index); } else { return cube.getPivot().get(index) - parent.getPivot().get(index); } } public float convertOrigin(BenchEntityBones bone, BenchEntityCube cube, int index) { if (index == 1) { return bone.getPivot().get(index) - cube.getOrigin().get(index) - cube.getSize().get(index); } else { return cube.getOrigin().get(index) - bone.getPivot().get(index); } } public float convertOrigin(BenchEntityCube cube, int index) { assert cube.getPivot() != null; if (index == 1) { return cube.getPivot().get(index) - cube.getOrigin().get(index) - cube.getSize().get(index); } else { return cube.getOrigin().get(index) - cube.getPivot().get(index); } } public Optional<BenchEntityBones> getAnyDescendantWithName(String key) { Optional<Map.Entry<String, BenchEntityBones>> bones = this.getIndexBones().entrySet().stream().filter((benchBone) -> benchBone.getKey().equals(key)).findFirst(); if (bones.isPresent()) { return Optional.of(bones.get().getValue()); } else { return Optional.empty(); } }
protected void animateWalk(AnimationData animationData, float p_268057_, float p_268347_, float p_268138_, float p_268165_) {
1
2023-11-16 01:10:52+00:00
16k
AntonyCheng/ai-bi
src/main/java/top/sharehome/springbootinittemplate/config/captcha/service/impl/CaptchaServiceImpl.java
[ { "identifier": "CaptchaCondition", "path": "src/main/java/top/sharehome/springbootinittemplate/config/captcha/condition/CaptchaCondition.java", "snippet": "public class CaptchaCondition implements Condition {\n\n @Override\n public boolean matches(ConditionContext context, AnnotatedTypeMetadata m...
import cn.hutool.captcha.AbstractCaptcha; import cn.hutool.captcha.generator.CodeGenerator; import cn.hutool.core.util.ReflectUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Conditional; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.stereotype.Service; import top.sharehome.springbootinittemplate.config.captcha.condition.CaptchaCondition; import top.sharehome.springbootinittemplate.config.captcha.model.CaptchaCreate; import top.sharehome.springbootinittemplate.config.captcha.properties.CaptchaProperties; import top.sharehome.springbootinittemplate.config.captcha.properties.enums.CaptchaType; import top.sharehome.springbootinittemplate.config.captcha.service.CaptchaService; import top.sharehome.springbootinittemplate.common.base.ReturnCode; import top.sharehome.springbootinittemplate.config.bean.SpringContextHolder; import top.sharehome.springbootinittemplate.exception.customize.CustomizeReturnException; import top.sharehome.springbootinittemplate.utils.redisson.cache.CacheUtils; import top.sharehome.springbootinittemplate.utils.redisson.KeyPrefixConstants; import javax.annotation.Resource; import java.util.UUID;
14,215
package top.sharehome.springbootinittemplate.config.captcha.service.impl; /** * 验证码服务实现类 * * @author AntonyCheng */ @EnableConfigurationProperties(CaptchaProperties.class) @Service @Conditional(CaptchaCondition.class) public class CaptchaServiceImpl implements CaptchaService { @Resource private CaptchaProperties captchaProperties; @Override public CaptchaCreate createCaptcha() { CaptchaCreate captchaCreateResponse = new CaptchaCreate(); boolean enable = captchaProperties.getEnable(); captchaCreateResponse.setEnableCode(enable); if (!enable) { return captchaCreateResponse; } String uuid = UUID.randomUUID().toString().replace("-", ""); String codeKeyInRedis = KeyPrefixConstants.CAPTCHA_PREFIX + uuid; CaptchaType captchaType = captchaProperties.getType(); boolean isMath = CaptchaType.MATH == captchaType; int length = isMath ? ((captchaProperties.getNumberLength() < 1 || captchaProperties.getNumberLength() > 9) ? 1 : captchaProperties.getNumberLength()) : ((captchaProperties.getCharLength() < 1 || captchaProperties.getCharLength() > 100) ? 4 : captchaProperties.getCharLength()); CodeGenerator codeGenerator = ReflectUtil.newInstance(captchaType.getClazz(), length); AbstractCaptcha captcha = SpringContextHolder.getBean(captchaProperties.getCategory().getClazz()); captcha.setGenerator(codeGenerator); captcha.createCode(); String code = captcha.getCode(); if (isMath) { ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression(StringUtils.remove(code, "=")); code = exp.getValue(String.class); } CacheUtils.put(codeKeyInRedis, code, captchaProperties.getExpired()); captchaCreateResponse .setUuid(uuid) .setImgBase64(captcha.getImageBase64()); return captchaCreateResponse; } @Override public void checkCaptcha(String code, String uuid) { if (StringUtils.isBlank(code)) {
package top.sharehome.springbootinittemplate.config.captcha.service.impl; /** * 验证码服务实现类 * * @author AntonyCheng */ @EnableConfigurationProperties(CaptchaProperties.class) @Service @Conditional(CaptchaCondition.class) public class CaptchaServiceImpl implements CaptchaService { @Resource private CaptchaProperties captchaProperties; @Override public CaptchaCreate createCaptcha() { CaptchaCreate captchaCreateResponse = new CaptchaCreate(); boolean enable = captchaProperties.getEnable(); captchaCreateResponse.setEnableCode(enable); if (!enable) { return captchaCreateResponse; } String uuid = UUID.randomUUID().toString().replace("-", ""); String codeKeyInRedis = KeyPrefixConstants.CAPTCHA_PREFIX + uuid; CaptchaType captchaType = captchaProperties.getType(); boolean isMath = CaptchaType.MATH == captchaType; int length = isMath ? ((captchaProperties.getNumberLength() < 1 || captchaProperties.getNumberLength() > 9) ? 1 : captchaProperties.getNumberLength()) : ((captchaProperties.getCharLength() < 1 || captchaProperties.getCharLength() > 100) ? 4 : captchaProperties.getCharLength()); CodeGenerator codeGenerator = ReflectUtil.newInstance(captchaType.getClazz(), length); AbstractCaptcha captcha = SpringContextHolder.getBean(captchaProperties.getCategory().getClazz()); captcha.setGenerator(codeGenerator); captcha.createCode(); String code = captcha.getCode(); if (isMath) { ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression(StringUtils.remove(code, "=")); code = exp.getValue(String.class); } CacheUtils.put(codeKeyInRedis, code, captchaProperties.getExpired()); captchaCreateResponse .setUuid(uuid) .setImgBase64(captcha.getImageBase64()); return captchaCreateResponse; } @Override public void checkCaptcha(String code, String uuid) { if (StringUtils.isBlank(code)) {
throw new CustomizeReturnException(ReturnCode.CAPTCHA_IS_EMPTY);
5
2023-11-12 07:49:59+00:00
16k
Shushandr/offroad
src/net/osmand/router/PrecalculatedRouteDirection.java
[ { "identifier": "RouteDataObject", "path": "src/net/osmand/binary/RouteDataObject.java", "snippet": "public class RouteDataObject {\n\t/*private */static final int RESTRICTION_SHIFT = 3;\n\t/*private */static final int RESTRICTION_MASK = 7;\n\t\n\tpublic final RouteRegion region;\n\t// all these arrays ...
import gnu.trove.list.array.TIntArrayList; import java.util.ArrayList; import java.util.List; import net.osmand.binary.RouteDataObject; import net.osmand.data.LatLon; import net.osmand.data.QuadPoint; import net.osmand.data.QuadRect; import net.osmand.data.QuadTree; import net.osmand.util.MapUtils;
13,092
package net.osmand.router; public class PrecalculatedRouteDirection { private int[] pointsX; private int[] pointsY; private float minSpeed; private float maxSpeed; private float[] tms; private boolean followNext; private static final int SHIFT = (1 << (31 - 17)); private static final int[] SHIFTS = new int[]{1 << (31 - 15), 1 << (31 - 13), 1 << (31 - 12), 1 << (31 - 11), 1 << (31 - 7)}; private List<Integer> cachedS = new ArrayList<Integer>(); private long startPoint = 0; private long endPoint = 0; // private DataTileManager<Integer> indexedPoints = new DataTileManager<Integer>(17); QuadTree<Integer> quadTree = new QuadTree<Integer>(new QuadRect(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE), 8, 0.55f); private float startFinishTime; private float endFinishTime; public PrecalculatedRouteDirection(TIntArrayList px, TIntArrayList py, List<Float> speedSegments, float maxSpeed) { this.maxSpeed = maxSpeed; init(px, py, speedSegments); } private PrecalculatedRouteDirection(List<RouteSegmentResult> ls, float maxSpeed) { this.maxSpeed = maxSpeed; init(ls); } private PrecalculatedRouteDirection(LatLon[] ls, float maxSpeed) { this.maxSpeed = maxSpeed; init(ls); } private PrecalculatedRouteDirection(PrecalculatedRouteDirection parent, int s1, int s2) { this.minSpeed = parent.minSpeed; this.maxSpeed = parent.maxSpeed; tms = new float[s2 - s1 + 1]; pointsX = new int[s2 - s1 + 1]; pointsY = new int[s2 - s1 + 1]; for (int i = s1; i <= s2; i++) { int shiftInd = i - s1; pointsX[shiftInd] = parent.pointsX[i]; pointsY[shiftInd] = parent.pointsY[i]; // indexedPoints.registerObjectXY(parent.pointsX.get(i), parent.pointsY.get(i), pointsX.size() - 1); quadTree.insert(shiftInd, parent.pointsX[i], parent.pointsY[i]); tms[shiftInd] = parent.tms[i] - parent.tms[s2]; } } public static PrecalculatedRouteDirection build(List<RouteSegmentResult> ls, float cutoffDistance, float maxSpeed){ int begi = 0; float d = cutoffDistance; for (; begi < ls.size(); begi++) { d -= ls.get(begi).getDistance(); if (d < 0) { break; } } int endi = ls.size(); d = cutoffDistance; for (; endi > 0; endi--) { d -= ls.get(endi - 1).getDistance(); if (d < 0) { break; } } if(begi < endi) { return new PrecalculatedRouteDirection(ls.subList(begi, endi), maxSpeed); } return null; } public static PrecalculatedRouteDirection build(LatLon[] ls, float maxSpeed){ return new PrecalculatedRouteDirection(ls, maxSpeed); } private void init(List<RouteSegmentResult> ls) { TIntArrayList px = new TIntArrayList(); TIntArrayList py = new TIntArrayList(); List<Float> speedSegments = new ArrayList<Float>(); for (RouteSegmentResult s : ls) { boolean plus = s.getStartPointIndex() < s.getEndPointIndex(); int i = s.getStartPointIndex(); RouteDataObject obj = s.getObject(); float routeSpd = (s.getRoutingTime() == 0 || s.getDistance() == 0) ? maxSpeed : (s.getDistance() / s.getRoutingTime()); while (true) { i = plus? i + 1 : i -1; px.add(obj.getPoint31XTile(i)); py.add(obj.getPoint31YTile(i)); speedSegments.add(routeSpd); if (i == s.getEndPointIndex()) { break; } } } init(px, py, speedSegments); } private void init(LatLon[] ls) { TIntArrayList px = new TIntArrayList(); TIntArrayList py = new TIntArrayList(); List<Float> speedSegments = new ArrayList<Float>(); for (LatLon s : ls) { float routeSpd = maxSpeed; // (s.getDistance() / s.getRoutingTime())
package net.osmand.router; public class PrecalculatedRouteDirection { private int[] pointsX; private int[] pointsY; private float minSpeed; private float maxSpeed; private float[] tms; private boolean followNext; private static final int SHIFT = (1 << (31 - 17)); private static final int[] SHIFTS = new int[]{1 << (31 - 15), 1 << (31 - 13), 1 << (31 - 12), 1 << (31 - 11), 1 << (31 - 7)}; private List<Integer> cachedS = new ArrayList<Integer>(); private long startPoint = 0; private long endPoint = 0; // private DataTileManager<Integer> indexedPoints = new DataTileManager<Integer>(17); QuadTree<Integer> quadTree = new QuadTree<Integer>(new QuadRect(0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE), 8, 0.55f); private float startFinishTime; private float endFinishTime; public PrecalculatedRouteDirection(TIntArrayList px, TIntArrayList py, List<Float> speedSegments, float maxSpeed) { this.maxSpeed = maxSpeed; init(px, py, speedSegments); } private PrecalculatedRouteDirection(List<RouteSegmentResult> ls, float maxSpeed) { this.maxSpeed = maxSpeed; init(ls); } private PrecalculatedRouteDirection(LatLon[] ls, float maxSpeed) { this.maxSpeed = maxSpeed; init(ls); } private PrecalculatedRouteDirection(PrecalculatedRouteDirection parent, int s1, int s2) { this.minSpeed = parent.minSpeed; this.maxSpeed = parent.maxSpeed; tms = new float[s2 - s1 + 1]; pointsX = new int[s2 - s1 + 1]; pointsY = new int[s2 - s1 + 1]; for (int i = s1; i <= s2; i++) { int shiftInd = i - s1; pointsX[shiftInd] = parent.pointsX[i]; pointsY[shiftInd] = parent.pointsY[i]; // indexedPoints.registerObjectXY(parent.pointsX.get(i), parent.pointsY.get(i), pointsX.size() - 1); quadTree.insert(shiftInd, parent.pointsX[i], parent.pointsY[i]); tms[shiftInd] = parent.tms[i] - parent.tms[s2]; } } public static PrecalculatedRouteDirection build(List<RouteSegmentResult> ls, float cutoffDistance, float maxSpeed){ int begi = 0; float d = cutoffDistance; for (; begi < ls.size(); begi++) { d -= ls.get(begi).getDistance(); if (d < 0) { break; } } int endi = ls.size(); d = cutoffDistance; for (; endi > 0; endi--) { d -= ls.get(endi - 1).getDistance(); if (d < 0) { break; } } if(begi < endi) { return new PrecalculatedRouteDirection(ls.subList(begi, endi), maxSpeed); } return null; } public static PrecalculatedRouteDirection build(LatLon[] ls, float maxSpeed){ return new PrecalculatedRouteDirection(ls, maxSpeed); } private void init(List<RouteSegmentResult> ls) { TIntArrayList px = new TIntArrayList(); TIntArrayList py = new TIntArrayList(); List<Float> speedSegments = new ArrayList<Float>(); for (RouteSegmentResult s : ls) { boolean plus = s.getStartPointIndex() < s.getEndPointIndex(); int i = s.getStartPointIndex(); RouteDataObject obj = s.getObject(); float routeSpd = (s.getRoutingTime() == 0 || s.getDistance() == 0) ? maxSpeed : (s.getDistance() / s.getRoutingTime()); while (true) { i = plus? i + 1 : i -1; px.add(obj.getPoint31XTile(i)); py.add(obj.getPoint31YTile(i)); speedSegments.add(routeSpd); if (i == s.getEndPointIndex()) { break; } } } init(px, py, speedSegments); } private void init(LatLon[] ls) { TIntArrayList px = new TIntArrayList(); TIntArrayList py = new TIntArrayList(); List<Float> speedSegments = new ArrayList<Float>(); for (LatLon s : ls) { float routeSpd = maxSpeed; // (s.getDistance() / s.getRoutingTime())
px.add(MapUtils.get31TileNumberX(s.getLongitude()));
5
2023-11-15 05:04:55+00:00
16k
WuKongOpenSource/Wukong_HRM
hrm/hrm-web/src/main/java/com/kakarote/hrm/utils/AchievementsUtil.java
[ { "identifier": "AdminMessageEnum", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/common/admin/AdminMessageEnum.java", "snippet": "public enum AdminMessageEnum {\n\n /**\n * 消息通知枚举类\n */\n NULL(0,0,\"NULL\"),\n OA_TASK_ALLOCATION(1,1,\"分配给我的任务\"),\n OA_TASK_JOIN(2,1,\"我参与的任务\")...
import cn.hutool.core.util.ObjectUtil; import com.kakarote.hrm.common.admin.AdminMessageEnum; import com.kakarote.hrm.constant.appraisal.AppraisalStageStatusEnum; import com.kakarote.hrm.constant.appraisal.RaterTypeEnum; import com.kakarote.hrm.entity.PO.HrmEmployee; import com.kakarote.hrm.entity.VO.DeptVO; import com.kakarote.hrm.service.IHrmAppraisalPlanService; import com.kakarote.hrm.service.IHrmDeptService; import com.kakarote.hrm.service.IHrmEmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
13,645
package com.kakarote.hrm.utils; /** * 绩效管理工具类 */ @Component public class AchievementsUtil { @Autowired IHrmEmployeeService employeeService; @Autowired IHrmDeptService hrmDeptService; @Autowired IHrmAppraisalPlanService appraisalPlanService; /** * 递归调用查询多级上级员工id * * @param level * @param employeeId * @return */ public Long queryLevelEmployee(Integer level, Long employeeId) { //todo 如果多级上级实际没有那么多级的情况要做判断处理 HrmEmployee employeeInfo = employeeService.lambdaQuery().eq(HrmEmployee::getEmployeeId, employeeId).one(); if (ObjectUtil.isNotNull(employeeInfo)) { if (level >= 1) { level = level - 1; return queryLevelEmployee(level, employeeInfo.getParentId()); } else { return employeeInfo.getEmployeeId(); } } return null; } /** * 递归调用查询多级上级部门负责人 * * @param level * @param deptId * @return */ public Long queryLevelDeptOwner(Integer level, Long deptId) { //todo 如果多级上级实际没有那么多级的情况要做判断处理 DeptVO deptInfo = hrmDeptService.queryById(deptId); if (ObjectUtil.isNotNull(deptInfo)) { if (level > 1) { level = level - 1; return queryLevelDeptOwner(level, deptInfo.getParentId()); } else { return deptInfo.getMainEmployeeId(); } } return null; } /** * @param raterType 确认类型 * @param level 级别 * @param appoint 指定人 * @param employeeId 被考核人 * @return */ public Long queryStageUser(Long appraisalPlanId, Integer raterType, Integer level, Long appoint, Long employeeId) {
package com.kakarote.hrm.utils; /** * 绩效管理工具类 */ @Component public class AchievementsUtil { @Autowired IHrmEmployeeService employeeService; @Autowired IHrmDeptService hrmDeptService; @Autowired IHrmAppraisalPlanService appraisalPlanService; /** * 递归调用查询多级上级员工id * * @param level * @param employeeId * @return */ public Long queryLevelEmployee(Integer level, Long employeeId) { //todo 如果多级上级实际没有那么多级的情况要做判断处理 HrmEmployee employeeInfo = employeeService.lambdaQuery().eq(HrmEmployee::getEmployeeId, employeeId).one(); if (ObjectUtil.isNotNull(employeeInfo)) { if (level >= 1) { level = level - 1; return queryLevelEmployee(level, employeeInfo.getParentId()); } else { return employeeInfo.getEmployeeId(); } } return null; } /** * 递归调用查询多级上级部门负责人 * * @param level * @param deptId * @return */ public Long queryLevelDeptOwner(Integer level, Long deptId) { //todo 如果多级上级实际没有那么多级的情况要做判断处理 DeptVO deptInfo = hrmDeptService.queryById(deptId); if (ObjectUtil.isNotNull(deptInfo)) { if (level > 1) { level = level - 1; return queryLevelDeptOwner(level, deptInfo.getParentId()); } else { return deptInfo.getMainEmployeeId(); } } return null; } /** * @param raterType 确认类型 * @param level 级别 * @param appoint 指定人 * @param employeeId 被考核人 * @return */ public Long queryStageUser(Long appraisalPlanId, Integer raterType, Integer level, Long appoint, Long employeeId) {
RaterTypeEnum raterTypeEnum = RaterTypeEnum.parse(raterType);
2
2023-10-17 05:49:52+00:00
16k
djkcyl/Shamrock
qqinterface/src/main/java/com/tencent/mobileqq/profilecard/processor/AbsProfileBusinessProcessor.java
[ { "identifier": "Card", "path": "qqinterface/src/main/java/com/tencent/mobileqq/data/Card.java", "snippet": "public class Card {\n public static final long BIRTHDAY_INVALID = 0;\n public static final int CONSTELLATION_INVALID = 0;\n public static final short FEMALE = 1;\n public static final...
import android.os.Bundle; import android.util.SparseArray; import com.tencent.mobileqq.data.Card; import com.tencent.mobileqq.profilecard.entity.BusinessReqBuffer; import com.tencent.mobileqq.profilecard.entity.BusinessRespBuffer; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import SummaryCard.RespHead; import SummaryCard.RespSummaryCard; import mqq.app.AppRuntime; import tencent.im.oidb.cmd0x5eb.oidb_0x5eb;
12,080
package com.tencent.mobileqq.profilecard.processor; public abstract class AbsProfileBusinessProcessor implements IRequestProfileCardCallback, IGetProfileDetailCallback { public AbsProfileBusinessProcessor(AppRuntime appRuntime) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailRequestForLogin(List<Short> list) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailResponseBegin(Bundle bundle) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback
package com.tencent.mobileqq.profilecard.processor; public abstract class AbsProfileBusinessProcessor implements IRequestProfileCardCallback, IGetProfileDetailCallback { public AbsProfileBusinessProcessor(AppRuntime appRuntime) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailRequestForLogin(List<Short> list) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailResponseBegin(Bundle bundle) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback
public void onGetProfileDetailResponseEnd(Bundle bundle, boolean z, Card card) {
0
2023-10-20 10:43:47+00:00
16k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/recipe/machineRecipe/AssemblyLineWithoutResearchRecipePool.java
[ { "identifier": "RECIPE_LuV", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/enums/TierEU.java", "snippet": "public static final long RECIPE_LuV = VP[6];" }, { "identifier": "RECIPE_UHV", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/enums/TierEU.java", "snippet": ...
import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_LuV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_UHV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_UMV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_UV; import static com.Nxer.TwistSpaceTechnology.util.enums.TierEU.RECIPE_ZPM; import static com.github.technus.tectech.loader.recipe.BaseRecipeLoader.getItemContainer; import static com.github.technus.tectech.thing.CustomItemList.*; import static com.google.common.math.LongMath.pow; import static gregtech.api.enums.Mods.GalaxySpace; import static gregtech.api.enums.Mods.GoodGenerator; import static gregtech.api.enums.Mods.GraviSuite; import static gregtech.api.enums.Mods.GregTech; import static gregtech.api.enums.Mods.SuperSolarPanels; import static gregtech.api.util.GT_ModHandler.getModItem; import static gtPlusPlus.core.material.ALLOY.INDALLOY_140; import static gtPlusPlus.core.material.MISC_MATERIALS.MUTATED_LIVING_SOLDER; import java.util.ArrayList; import java.util.List; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import com.Nxer.TwistSpaceTechnology.TwistSpaceTechnology; import com.Nxer.TwistSpaceTechnology.common.recipeMap.GTCMRecipe; import com.Nxer.TwistSpaceTechnology.recipe.IRecipePool; import com.Nxer.TwistSpaceTechnology.system.CircuitConverter.logic.TieredCircuits; import com.Nxer.TwistSpaceTechnology.util.Utils; import com.dreammaster.gthandler.CustomItemList; import goodgenerator.items.MyMaterial; import goodgenerator.util.ItemRefer; import gregtech.api.enums.GT_Values; import gregtech.api.enums.ItemList; import gregtech.api.enums.Materials; import gregtech.api.enums.MaterialsUEVplus; import gregtech.api.enums.OrePrefixes; import gregtech.api.interfaces.IRecipeMap; import gregtech.api.util.GT_OreDictUnificator; import gregtech.api.util.GT_Recipe; import gregtech.api.util.GT_RecipeBuilder; import gregtech.api.util.GT_Utility; import gtPlusPlus.xmod.gregtech.api.enums.GregtechItemList; import wanion.avaritiaddons.block.chest.infinity.BlockInfinityChest;
13,872
.duration(40 * 20) .eut(RECIPE_UV) .addTo(MASL); // UHV energy hatch GT_Values.RA.stdBuilder() .itemInputs( ItemList.Hull_MAX.get(1L), GT_OreDictUnificator.get(OrePrefixes.wireGt04, Materials.SuperconductorUHV, 2L), ItemList.Circuit_Chip_QPIC.get(2L), new Object[] { OrePrefixes.circuit.get(Materials.Infinite), 2L }, ItemList.UHV_Coil.get(2L), ItemList.Electric_Pump_UHV.get(1L)) .itemOutputs(ItemList.Hatch_Energy_MAX.get(1)) .fluidInputs(new FluidStack(ic2coolant, 16000), new FluidStack(solderIndalloy, 40 * 144)) .duration(50 * 20) .eut(RECIPE_UHV) .addTo(MASL); // LuV dynamo hatch GT_Values.RA.stdBuilder() .itemInputs( ItemList.Hull_LuV.get(1), GT_OreDictUnificator.get( OrePrefixes.spring, Materials.Tetraindiumditindibariumtitaniumheptacoppertetrakaidekaoxid, 2), ItemList.Circuit_Chip_UHPIC.get(2), new Object[] { OrePrefixes.circuit.get(Materials.Master), 2 }, ItemList.LuV_Coil.get(2), ItemList.Electric_Pump_LuV.get(1)) .itemOutputs(ItemList.Hatch_Dynamo_LuV.get(1)) .fluidInputs(new FluidStack(ic2coolant, 2000), new FluidStack(solderIndalloy, 720)) .duration(20 * 20) .eut(RECIPE_LuV) .addTo(MASL); // ZPM dynamo hatch GT_Values.RA.stdBuilder() .itemInputs( ItemList.Hull_ZPM.get(1), GT_OreDictUnificator.get(OrePrefixes.spring, Materials.Tetranaquadahdiindiumhexaplatiumosminid, 4), ItemList.Circuit_Chip_NPIC.get(2), new Object[] { OrePrefixes.circuit.get(Materials.Ultimate), 2 }, ItemList.ZPM_Coil.get(2), ItemList.Electric_Pump_ZPM.get(1)) .itemOutputs(ItemList.Hatch_Dynamo_ZPM.get(1)) .fluidInputs(new FluidStack(ic2coolant, 4000), new FluidStack(solderIndalloy, 1440)) .duration(30 * 20) .eut(RECIPE_ZPM) .addTo(MASL); // UV dynamo hatch GT_Values.RA.stdBuilder() .itemInputs( ItemList.Hull_UV.get(1), GT_OreDictUnificator.get(OrePrefixes.spring, Materials.Longasssuperconductornameforuvwire, 4), ItemList.Circuit_Chip_PPIC.get(2), new Object[] { OrePrefixes.circuit.get(Materials.SuperconductorUHV), 2 }, ItemList.UV_Coil.get(2), ItemList.Electric_Pump_UV.get(1)) .itemOutputs(ItemList.Hatch_Dynamo_UV.get(1)) .fluidInputs(new FluidStack(ic2coolant, 8000), new FluidStack(solderIndalloy, 2880)) .duration(40 * 20) .eut(RECIPE_UV) .addTo(MASL); // UHV dynamo hatch GT_Values.RA.stdBuilder() .itemInputs( ItemList.Hull_MAX.get(1L), GT_OreDictUnificator.get(OrePrefixes.spring, Materials.Longasssuperconductornameforuhvwire, 8L), ItemList.Circuit_Chip_QPIC.get(2L), new Object[] { OrePrefixes.circuit.get(Materials.Infinite), 2L }, ItemList.UHV_Coil.get(2L), ItemList.Electric_Pump_UHV.get(1L)) .itemOutputs(ItemList.Hatch_Dynamo_MAX.get(1)) .fluidInputs(new FluidStack(ic2coolant, 16000), new FluidStack(solderIndalloy, 40 * 144)) .duration(50 * 20) .eut(RECIPE_UHV) .addTo(MASL); } // EOH Blocks { // ME Digital singularity. final ItemStack ME_Singularity = getModItem( "appliedenergistics2", "item.ItemExtremeStorageCell.Singularity", 1); final ItemStack[] boltList = new ItemStack[] { // Dense Shirabon plate. GT_OreDictUnificator.get("boltShirabon", 2), GT_OreDictUnificator.get(OrePrefixes.bolt, MaterialsUEVplus.WhiteDwarfMatter, 2), GT_OreDictUnificator.get(OrePrefixes.bolt, MaterialsUEVplus.WhiteDwarfMatter, 8), GT_OreDictUnificator.get(OrePrefixes.bolt, MaterialsUEVplus.WhiteDwarfMatter, 32), GT_OreDictUnificator.get(OrePrefixes.bolt, MaterialsUEVplus.BlackDwarfMatter, 2), GT_OreDictUnificator.get(OrePrefixes.bolt, MaterialsUEVplus.BlackDwarfMatter, 8), GT_OreDictUnificator.get(OrePrefixes.bolt, MaterialsUEVplus.BlackDwarfMatter, 32), GT_OreDictUnificator .get(OrePrefixes.bolt, MaterialsUEVplus.MagnetohydrodynamicallyConstrainedStarMatter, 2), GT_OreDictUnificator .get(OrePrefixes.bolt, MaterialsUEVplus.MagnetohydrodynamicallyConstrainedStarMatter, 8) }; // spacetime 1 GT_Values.RA.stdBuilder() .itemInputs( GT_Utility.getIntegratedCircuit(1), EOH_Reinforced_Spatial_Casing.get(1), ItemRefer.YOTTank_Cell_T7.get(1), ItemList.Quantum_Tank_IV.get(4), new ItemStack(BlockInfinityChest.instance, 1), GregtechItemList.CosmicFabricManipulator.get(1), Utils.copyAmount(1, ME_Singularity), MyMaterial.shirabon.get(OrePrefixes.bolt, 2), CustomItemList.QuantumCircuit.get(1)) .fluidInputs( MUTATED_LIVING_SOLDER.getFluidStack(144 * 20), MaterialsUEVplus.Space.getMolten(144 * 10), MaterialsUEVplus.SpaceTime.getMolten(144 * 10)) .itemOutputs(SpacetimeCompressionFieldGeneratorTier0.get(1))
package com.Nxer.TwistSpaceTechnology.recipe.machineRecipe; public class AssemblyLineWithoutResearchRecipePool implements IRecipePool { public ItemStack transToWildCircuit(ItemStack items) { for (TieredCircuits circuit : TieredCircuits.values()) { if (circuit.contains(items)) { return circuit.getPatternCircuit(items.stackSize); } } return null; } public static List<ItemStack[]> generateAllItemInput(ItemStack[] baseStack, ItemStack[][] wildCard) { List<ItemStack[]> result = new ArrayList<>(); result.add(Utils.copyItemStackArray(baseStack)); int len = baseStack.length; for (int i = 0; i < len; i++) { if (wildCard[i] == null) continue; for (int j = 1; j < wildCard[i].length; j++) { if (wildCard[i][j] == null) continue; ItemStack wildCardCopy = wildCard[i][j].copy(); int resultSize = result.size(); for (int k = 0; k < resultSize; k++) { ItemStack[] inputList = Utils.copyItemStackArray(result.get(k)); inputList[i] = wildCardCopy; result.add(inputList); } } } return result; } @Override public void loadRecipes() { TwistSpaceTechnology.LOG.info("Loading Mega Assembly Line Recipes."); // skip these recipes ItemStack[] skipRecipeOutputs = new ItemStack[] { ItemList.Circuit_Wetwaremainframe.get(1), ItemList.Circuit_Biowaresupercomputer.get(1), ItemList.Circuit_Biomainframe.get(1), ItemList.Circuit_OpticalAssembly.get(1), ItemList.Circuit_OpticalComputer.get(1), ItemList.Circuit_OpticalMainframe.get(1), SpacetimeCompressionFieldGeneratorTier0.get(1), SpacetimeCompressionFieldGeneratorTier1.get(1), SpacetimeCompressionFieldGeneratorTier2.get(1), SpacetimeCompressionFieldGeneratorTier3.get(1), SpacetimeCompressionFieldGeneratorTier4.get(1), SpacetimeCompressionFieldGeneratorTier5.get(1), SpacetimeCompressionFieldGeneratorTier6.get(1), SpacetimeCompressionFieldGeneratorTier7.get(1), SpacetimeCompressionFieldGeneratorTier8.get(1), TimeAccelerationFieldGeneratorTier0.get(1), TimeAccelerationFieldGeneratorTier1.get(1), TimeAccelerationFieldGeneratorTier2.get(1), TimeAccelerationFieldGeneratorTier3.get(1), TimeAccelerationFieldGeneratorTier4.get(1), TimeAccelerationFieldGeneratorTier5.get(1), TimeAccelerationFieldGeneratorTier6.get(1), TimeAccelerationFieldGeneratorTier7.get(1), TimeAccelerationFieldGeneratorTier8.get(1), StabilisationFieldGeneratorTier0.get(1), StabilisationFieldGeneratorTier1.get(1), StabilisationFieldGeneratorTier2.get(1), StabilisationFieldGeneratorTier3.get(1), StabilisationFieldGeneratorTier4.get(1), StabilisationFieldGeneratorTier5.get(1), StabilisationFieldGeneratorTier6.get(1), StabilisationFieldGeneratorTier7.get(1), StabilisationFieldGeneratorTier8.get(1), ItemList.Hatch_Energy_LuV.get(1), ItemList.Hatch_Energy_ZPM.get(1), ItemList.Hatch_Energy_UV.get(1), ItemList.Hatch_Energy_MAX.get(1), ItemList.Hatch_Dynamo_LuV.get(1), ItemList.Hatch_Dynamo_ZPM.get(1), ItemList.Hatch_Dynamo_UV.get(1), ItemList.Hatch_Dynamo_MAX.get(1), }; // start check assembly line recipes checkRecipe: for (var recipe : GT_Recipe.GT_Recipe_AssemblyLine.sAssemblylineRecipes) { // debugLogInfo("Recipe output: " + recipe.mOutput.getDisplayName()); for (ItemStack skip : skipRecipeOutputs) { // skip recipes need skip if (Utils.metaItemEqual(recipe.mOutput, skip)) { // debugLogInfo("Skip recipe."); continue checkRecipe; } } ItemStack[] inputItems = new ItemStack[recipe.mInputs.length]; ItemStack[][] inputWildcards = new ItemStack[recipe.mInputs.length][]; boolean hasCustomWildcardItemList = false; if (recipe.mOreDictAlt != null && recipe.mOreDictAlt.length > 0) { // wildcards recipe for (int i = 0; i < recipe.mOreDictAlt.length; i++) { if (recipe.mOreDictAlt[i] != null && recipe.mOreDictAlt[i].length > 0) { ItemStack circuitStack = transToWildCircuit(recipe.mOreDictAlt[i][0]); if (circuitStack != null) { // this wildcard is a circuit stack // replace it by dreamcraft:anyCircuit then the recipe will check this stack by any circuit inputItems[i] = circuitStack; } else { // this wildcard is a custom list hasCustomWildcardItemList = true; inputWildcards[i] = recipe.mOreDictAlt[i]; } } else { // this stack is normal inputItems[i] = recipe.mInputs[i]; } } } else { // no wildcards recipe inputItems = recipe.mInputs; } if (!hasCustomWildcardItemList) { // debugLogInfo("Normal recipe generating."); GT_RecipeBuilder ra = GT_Values.RA.stdBuilder(); ra.itemInputs(Utils.sortNoNullArray(inputItems)) .itemOutputs(recipe.mOutput); if (recipe.mFluidInputs != null) { ra.fluidInputs(Utils.sortNoNullArray(recipe.mFluidInputs)); } ra.noOptimize() .eut(recipe.mEUt) .duration(recipe.mDuration) .addTo(GTCMRecipe.AssemblyLineWithoutResearchRecipe); } else { // debugLogInfo("Wildcard recipe generating."); for (int i = 0; i < inputItems.length; i++) { if (inputItems[i] == null) { inputItems[i] = inputWildcards[i][0]; } } List<ItemStack[]> inputCombine = generateAllItemInput(inputItems, inputWildcards); // debugLogInfo("inputCombine.size " + inputCombine.size()); // int loopFlag = 1; for (ItemStack[] inputs : inputCombine) { // debugLogInfo("generate " + loopFlag); // debugLogInfo("Input item list: " + Arrays.toString(inputs)); // loopFlag++; GT_RecipeBuilder ra = GT_Values.RA.stdBuilder(); ra.itemInputs(Utils.sortNoNullArray(inputs)) .itemOutputs(recipe.mOutput); if (recipe.mFluidInputs != null) { ra.fluidInputs(Utils.sortNoNullArray(recipe.mFluidInputs)); } ra.noOptimize() .eut(recipe.mEUt) .duration(recipe.mDuration) .addTo(GTCMRecipe.AssemblyLineWithoutResearchRecipe); } } } TwistSpaceTechnology.LOG.info("load Special Recipes."); loadSpecialRecipes(); TwistSpaceTechnology.LOG.info("Mega Assembly Line Recipes loading complete."); // debugLogInfo( // "Mega Assembly Line Recipe List size: " + GTCMRecipe.AssemblyLineWithoutResearchRecipe.getAllRecipes() // .size()); } public void loadSpecialRecipes() { final IRecipeMap MASL = GTCMRecipe.AssemblyLineWithoutResearchRecipe; // Energy hatch and dynamo hatch of LuV - UHV { final Fluid ic2coolant = FluidRegistry.getFluid("ic2coolant"); final Fluid solderIndalloy = INDALLOY_140.getFluid(); // LuV energy hatch GT_Values.RA.stdBuilder() .itemInputs( ItemList.Hull_LuV.get(1), GT_OreDictUnificator.get(OrePrefixes.wireGt01, Materials.SuperconductorLuV, 2), ItemList.Circuit_Chip_UHPIC.get(2), new Object[] { OrePrefixes.circuit.get(Materials.Master), 2 }, ItemList.LuV_Coil.get(2), ItemList.Electric_Pump_LuV.get(1)) .itemOutputs(ItemList.Hatch_Energy_LuV.get(1)) .fluidInputs(new FluidStack(ic2coolant, 2000), new FluidStack(solderIndalloy, 720)) .duration(20 * 20) .eut(RECIPE_LuV) .addTo(MASL); // ZPM energy hatch GT_Values.RA.stdBuilder() .itemInputs( ItemList.Hull_ZPM.get(1), GT_OreDictUnificator.get(OrePrefixes.wireGt02, Materials.SuperconductorZPM, 2), ItemList.Circuit_Chip_NPIC.get(2), new Object[] { OrePrefixes.circuit.get(Materials.Ultimate), 2 }, ItemList.ZPM_Coil.get(2), ItemList.Electric_Pump_ZPM.get(1)) .itemOutputs(ItemList.Hatch_Energy_ZPM.get(1)) .fluidInputs(new FluidStack(ic2coolant, 4000), new FluidStack(solderIndalloy, 1440)) .duration(30 * 20) .eut(RECIPE_ZPM) .addTo(MASL); // UV energy hatch GT_Values.RA.stdBuilder() .itemInputs( ItemList.Hull_UV.get(1), GT_OreDictUnificator.get(OrePrefixes.wireGt02, Materials.SuperconductorUV, 2), ItemList.Circuit_Chip_PPIC.get(2), new Object[] { OrePrefixes.circuit.get(Materials.SuperconductorUHV), 2 }, ItemList.UV_Coil.get(2), ItemList.Electric_Pump_UV.get(1)) .itemOutputs(ItemList.Hatch_Energy_UV.get(1)) .fluidInputs(new FluidStack(ic2coolant, 8000), new FluidStack(solderIndalloy, 2880)) .duration(40 * 20) .eut(RECIPE_UV) .addTo(MASL); // UHV energy hatch GT_Values.RA.stdBuilder() .itemInputs( ItemList.Hull_MAX.get(1L), GT_OreDictUnificator.get(OrePrefixes.wireGt04, Materials.SuperconductorUHV, 2L), ItemList.Circuit_Chip_QPIC.get(2L), new Object[] { OrePrefixes.circuit.get(Materials.Infinite), 2L }, ItemList.UHV_Coil.get(2L), ItemList.Electric_Pump_UHV.get(1L)) .itemOutputs(ItemList.Hatch_Energy_MAX.get(1)) .fluidInputs(new FluidStack(ic2coolant, 16000), new FluidStack(solderIndalloy, 40 * 144)) .duration(50 * 20) .eut(RECIPE_UHV) .addTo(MASL); // LuV dynamo hatch GT_Values.RA.stdBuilder() .itemInputs( ItemList.Hull_LuV.get(1), GT_OreDictUnificator.get( OrePrefixes.spring, Materials.Tetraindiumditindibariumtitaniumheptacoppertetrakaidekaoxid, 2), ItemList.Circuit_Chip_UHPIC.get(2), new Object[] { OrePrefixes.circuit.get(Materials.Master), 2 }, ItemList.LuV_Coil.get(2), ItemList.Electric_Pump_LuV.get(1)) .itemOutputs(ItemList.Hatch_Dynamo_LuV.get(1)) .fluidInputs(new FluidStack(ic2coolant, 2000), new FluidStack(solderIndalloy, 720)) .duration(20 * 20) .eut(RECIPE_LuV) .addTo(MASL); // ZPM dynamo hatch GT_Values.RA.stdBuilder() .itemInputs( ItemList.Hull_ZPM.get(1), GT_OreDictUnificator.get(OrePrefixes.spring, Materials.Tetranaquadahdiindiumhexaplatiumosminid, 4), ItemList.Circuit_Chip_NPIC.get(2), new Object[] { OrePrefixes.circuit.get(Materials.Ultimate), 2 }, ItemList.ZPM_Coil.get(2), ItemList.Electric_Pump_ZPM.get(1)) .itemOutputs(ItemList.Hatch_Dynamo_ZPM.get(1)) .fluidInputs(new FluidStack(ic2coolant, 4000), new FluidStack(solderIndalloy, 1440)) .duration(30 * 20) .eut(RECIPE_ZPM) .addTo(MASL); // UV dynamo hatch GT_Values.RA.stdBuilder() .itemInputs( ItemList.Hull_UV.get(1), GT_OreDictUnificator.get(OrePrefixes.spring, Materials.Longasssuperconductornameforuvwire, 4), ItemList.Circuit_Chip_PPIC.get(2), new Object[] { OrePrefixes.circuit.get(Materials.SuperconductorUHV), 2 }, ItemList.UV_Coil.get(2), ItemList.Electric_Pump_UV.get(1)) .itemOutputs(ItemList.Hatch_Dynamo_UV.get(1)) .fluidInputs(new FluidStack(ic2coolant, 8000), new FluidStack(solderIndalloy, 2880)) .duration(40 * 20) .eut(RECIPE_UV) .addTo(MASL); // UHV dynamo hatch GT_Values.RA.stdBuilder() .itemInputs( ItemList.Hull_MAX.get(1L), GT_OreDictUnificator.get(OrePrefixes.spring, Materials.Longasssuperconductornameforuhvwire, 8L), ItemList.Circuit_Chip_QPIC.get(2L), new Object[] { OrePrefixes.circuit.get(Materials.Infinite), 2L }, ItemList.UHV_Coil.get(2L), ItemList.Electric_Pump_UHV.get(1L)) .itemOutputs(ItemList.Hatch_Dynamo_MAX.get(1)) .fluidInputs(new FluidStack(ic2coolant, 16000), new FluidStack(solderIndalloy, 40 * 144)) .duration(50 * 20) .eut(RECIPE_UHV) .addTo(MASL); } // EOH Blocks { // ME Digital singularity. final ItemStack ME_Singularity = getModItem( "appliedenergistics2", "item.ItemExtremeStorageCell.Singularity", 1); final ItemStack[] boltList = new ItemStack[] { // Dense Shirabon plate. GT_OreDictUnificator.get("boltShirabon", 2), GT_OreDictUnificator.get(OrePrefixes.bolt, MaterialsUEVplus.WhiteDwarfMatter, 2), GT_OreDictUnificator.get(OrePrefixes.bolt, MaterialsUEVplus.WhiteDwarfMatter, 8), GT_OreDictUnificator.get(OrePrefixes.bolt, MaterialsUEVplus.WhiteDwarfMatter, 32), GT_OreDictUnificator.get(OrePrefixes.bolt, MaterialsUEVplus.BlackDwarfMatter, 2), GT_OreDictUnificator.get(OrePrefixes.bolt, MaterialsUEVplus.BlackDwarfMatter, 8), GT_OreDictUnificator.get(OrePrefixes.bolt, MaterialsUEVplus.BlackDwarfMatter, 32), GT_OreDictUnificator .get(OrePrefixes.bolt, MaterialsUEVplus.MagnetohydrodynamicallyConstrainedStarMatter, 2), GT_OreDictUnificator .get(OrePrefixes.bolt, MaterialsUEVplus.MagnetohydrodynamicallyConstrainedStarMatter, 8) }; // spacetime 1 GT_Values.RA.stdBuilder() .itemInputs( GT_Utility.getIntegratedCircuit(1), EOH_Reinforced_Spatial_Casing.get(1), ItemRefer.YOTTank_Cell_T7.get(1), ItemList.Quantum_Tank_IV.get(4), new ItemStack(BlockInfinityChest.instance, 1), GregtechItemList.CosmicFabricManipulator.get(1), Utils.copyAmount(1, ME_Singularity), MyMaterial.shirabon.get(OrePrefixes.bolt, 2), CustomItemList.QuantumCircuit.get(1)) .fluidInputs( MUTATED_LIVING_SOLDER.getFluidStack(144 * 20), MaterialsUEVplus.Space.getMolten(144 * 10), MaterialsUEVplus.SpaceTime.getMolten(144 * 10)) .itemOutputs(SpacetimeCompressionFieldGeneratorTier0.get(1))
.eut(RECIPE_UMV)
2
2023-10-16 09:57:15+00:00
16k
wyjsonGo/GoRouter
GoRouter-Api/src/main/java/com/wyjson/router/core/RouteCenter.java
[ { "identifier": "ROUTER_CURRENT_PATH", "path": "GoRouter-Api/src/main/java/com/wyjson/router/core/Constants.java", "snippet": "static final String ROUTER_CURRENT_PATH = \"go_router_current_path\";" }, { "identifier": "ROUTER_RAW_URI", "path": "GoRouter-Api/src/main/java/com/wyjson/router/cor...
import static com.wyjson.router.core.Constants.ROUTER_CURRENT_PATH; import static com.wyjson.router.core.Constants.ROUTER_RAW_URI; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.wyjson.router.GoRouter; import com.wyjson.router.enums.ParamType; import com.wyjson.router.exception.NoFoundRouteException; import com.wyjson.router.exception.ParamException; import com.wyjson.router.exception.RouterException; import com.wyjson.router.interfaces.IJsonService; import com.wyjson.router.model.Card; import com.wyjson.router.model.CardMeta; import com.wyjson.router.model.ParamMeta; import com.wyjson.router.module.interfaces.IRouteModuleGroup; import com.wyjson.router.utils.MapUtils; import com.wyjson.router.utils.TextUtils; import java.lang.reflect.Field; import java.util.Map;
10,836
package com.wyjson.router.core; public class RouteCenter { private static IJsonService jsonService; public static Map<String, IRouteModuleGroup> getRouteGroups() { return Warehouse.routeGroups; } /** * 动态添加路由分组,按需加载路由 * * @param group * @param routeModuleGroup */ public static void addRouterGroup(String group, IRouteModuleGroup routeModuleGroup) { Warehouse.routeGroups.put(group, routeModuleGroup); GoRouter.logger.info(null, "[addRouterGroup] Add a route group[" + group + "] dynamically"); } /** * 获取路由元数据 * * @param card * @return * @throws NoFoundRouteException */
package com.wyjson.router.core; public class RouteCenter { private static IJsonService jsonService; public static Map<String, IRouteModuleGroup> getRouteGroups() { return Warehouse.routeGroups; } /** * 动态添加路由分组,按需加载路由 * * @param group * @param routeModuleGroup */ public static void addRouterGroup(String group, IRouteModuleGroup routeModuleGroup) { Warehouse.routeGroups.put(group, routeModuleGroup); GoRouter.logger.info(null, "[addRouterGroup] Add a route group[" + group + "] dynamically"); } /** * 获取路由元数据 * * @param card * @return * @throws NoFoundRouteException */
public static CardMeta getCardMeta(Card card) throws NoFoundRouteException {
8
2023-10-18 13:52:07+00:00
16k
trpc-group/trpc-java
trpc-registry/trpc-registry-api/src/test/java/com/tencent/trpc/registry/task/AbstractRetryTaskTest.java
[ { "identifier": "PluginConfig", "path": "trpc-core/src/main/java/com/tencent/trpc/core/common/config/PluginConfig.java", "snippet": "@SuppressWarnings({\"rawtypes\", \"unchecked\"})\npublic class PluginConfig {\n\n /**\n * Plugin name (under a plugin type, the name is a unique identifier for a sp...
import com.tencent.trpc.core.common.config.PluginConfig; import com.tencent.trpc.core.common.timer.Timeout; import com.tencent.trpc.core.common.timer.Timer; import com.tencent.trpc.core.common.timer.TimerTask; import com.tencent.trpc.core.exception.TRpcExtensionException; import com.tencent.trpc.core.logger.Logger; import com.tencent.trpc.core.logger.LoggerFactory; import com.tencent.trpc.core.registry.RegisterInfo; import com.tencent.trpc.core.worker.support.thread.ThreadWorkerPool; import com.tencent.trpc.registry.center.AbstractFailedRetryRegistryCenter; import com.tencent.trpc.registry.center.NotifyListener; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test;
11,809
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.registry.task; /** * Test class for registry failed retry. */ public class AbstractRetryTaskTest { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRetryTaskTest.class); AbstractFailedRetryRegistryCenter registry = null; AbstractRetryTask abstractRetryTask = null; Timeout timeout = new Timeout() { @Override public Timer timer() { return null; } @Override public TimerTask task() { return null; } @Override public boolean isExpired() { return false; } @Override public boolean isCancelled() { return true; } @Override public boolean cancel() { return false; } }; /** * Test class for registry failed retry. * * @throws Exception */ @Before public void setUp() throws Exception { Map<String, Object> properties = new HashMap<>(); properties.put("test", "test"); PluginConfig pluginConfig = new PluginConfig("id", ThreadWorkerPool.class, properties); registry = new AbstractFailedRetryRegistryCenter() { @Override
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.registry.task; /** * Test class for registry failed retry. */ public class AbstractRetryTaskTest { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRetryTaskTest.class); AbstractFailedRetryRegistryCenter registry = null; AbstractRetryTask abstractRetryTask = null; Timeout timeout = new Timeout() { @Override public Timer timer() { return null; } @Override public TimerTask task() { return null; } @Override public boolean isExpired() { return false; } @Override public boolean isCancelled() { return true; } @Override public boolean cancel() { return false; } }; /** * Test class for registry failed retry. * * @throws Exception */ @Before public void setUp() throws Exception { Map<String, Object> properties = new HashMap<>(); properties.put("test", "test"); PluginConfig pluginConfig = new PluginConfig("id", ThreadWorkerPool.class, properties); registry = new AbstractFailedRetryRegistryCenter() { @Override
public void doRegister(RegisterInfo registerInfo) {
7
2023-10-19 10:54:11+00:00
16k
eclipse-jgit/jgit
org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/dfs/DfsReaderTest.java
[ { "identifier": "CONFIG_KEY_MIN_BYTES_OBJ_SIZE_INDEX", "path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/ConfigConstants.java", "snippet": "public static final String CONFIG_KEY_MIN_BYTES_OBJ_SIZE_INDEX = \"minBytesForObjSizeIndex\";" }, { "identifier": "CONFIG_PACK_SECTION", "path": "org.e...
import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_MIN_BYTES_OBJ_SIZE_INDEX; import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_PACK_SECTION; import static org.eclipse.jgit.lib.Constants.OBJ_BLOB; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.eclipse.jgit.internal.storage.dfs.DfsObjDatabase.PackSource; import org.eclipse.jgit.internal.storage.dfs.DfsReader.PackLoadListener; import org.eclipse.jgit.internal.storage.pack.PackExt; import org.eclipse.jgit.junit.JGitTestUtil; import org.eclipse.jgit.junit.TestRng; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.junit.Before; import org.junit.Test;
13,384
assertTrue(ctx.isNotLargerThan(obj, OBJ_BLOB, 100)); assertEquals(5, ctx.stats.isNotLargerThanCallCount); assertEquals(5, ctx.stats.objectSizeIndexMiss); assertEquals(0, ctx.stats.objectSizeIndexHit); } } @Test public void isNotLargerThan_noObjectSizeIndex() throws IOException { setObjectSizeIndexMinBytes(-1); ObjectId obj = insertBlobWithSize(10); try (DfsReader ctx = db.getObjectDatabase().newReader()) { assertFalse(ctx.isNotLargerThan(obj, OBJ_BLOB, 0)); assertTrue(ctx.isNotLargerThan(obj, OBJ_BLOB, 10)); assertTrue(ctx.isNotLargerThan(obj, OBJ_BLOB, 40)); assertTrue(ctx.isNotLargerThan(obj, OBJ_BLOB, 50)); assertTrue(ctx.isNotLargerThan(obj, OBJ_BLOB, 100)); assertEquals(5, ctx.stats.isNotLargerThanCallCount); assertEquals(0, ctx.stats.objectSizeIndexMiss); assertEquals(0, ctx.stats.objectSizeIndexHit); } } @Test public void packLoadListener_noInvocations() throws IOException { insertBlobWithSize(100); try (DfsReader ctx = db.getObjectDatabase().newReader()) { CounterPackLoadListener listener = new CounterPackLoadListener(); ctx.addPackLoadListener(listener); assertEquals(null, listener.callsPerExt.get(PackExt.INDEX)); } } @Test public void packLoadListener_has_openIdx() throws IOException { ObjectId obj = insertBlobWithSize(100); try (DfsReader ctx = db.getObjectDatabase().newReader()) { CounterPackLoadListener listener = new CounterPackLoadListener(); ctx.addPackLoadListener(listener); boolean has = ctx.has(obj); assertTrue(has); assertEquals(Integer.valueOf(1), listener.callsPerExt.get(PackExt.INDEX)); } } @Test public void packLoadListener_notLargerThan_openMultipleIndices() throws IOException { setObjectSizeIndexMinBytes(100); ObjectId obj = insertBlobWithSize(200); try (DfsReader ctx = db.getObjectDatabase().newReader()) { CounterPackLoadListener listener = new CounterPackLoadListener(); ctx.addPackLoadListener(listener); boolean notLargerThan = ctx.isNotLargerThan(obj, OBJ_BLOB, 1000); assertTrue(notLargerThan); assertEquals(Integer.valueOf(1), listener.callsPerExt.get(PackExt.INDEX)); assertEquals(Integer.valueOf(1), listener.callsPerExt.get(PackExt.OBJECT_SIZE_INDEX)); } } @Test public void packLoadListener_has_openMultipleIndices() throws IOException { setObjectSizeIndexMinBytes(100); insertBlobWithSize(200); insertBlobWithSize(230); insertBlobWithSize(100); try (DfsReader ctx = db.getObjectDatabase().newReader()) { CounterPackLoadListener listener = new CounterPackLoadListener(); ctx.addPackLoadListener(listener); ObjectId oid = ObjectId.fromString("aa48de2aa61d9dffa8a05439dc115fe82f10f129"); boolean has = ctx.has(oid); assertFalse(has); // Open 3 indices trying to find the pack assertEquals(Integer.valueOf(3), listener.callsPerExt.get(PackExt.INDEX)); } } @Test public void packLoadListener_has_repeatedCalls_openMultipleIndices() throws IOException { // Two objects NOT in the repo ObjectId oid = ObjectId.fromString("aa48de2aa61d9dffa8a05439dc115fe82f10f129"); ObjectId oid2 = ObjectId.fromString("aa48de2aa61d9dffa8a05439dc115fe82f10f130"); setObjectSizeIndexMinBytes(100); insertBlobWithSize(200); insertBlobWithSize(230); insertBlobWithSize(100); CounterPackLoadListener listener = new CounterPackLoadListener(); try (DfsReader ctx = db.getObjectDatabase().newReader()) { ctx.addPackLoadListener(listener); boolean has = ctx.has(oid); ctx.has(oid); ctx.has(oid2); assertFalse(has); // The 3 indices were loaded only once each assertEquals(Integer.valueOf(3), listener.callsPerExt.get(PackExt.INDEX)); } } private static class CounterPackLoadListener implements PackLoadListener { final Map<PackExt, Integer> callsPerExt = new HashMap<>(); @SuppressWarnings("boxing") @Override public void onIndexLoad(String packName, PackSource src, PackExt ext, long size, Object loadedIdx) { callsPerExt.merge(ext, 1, Integer::sum); } @Override public void onBlockLoad(String packName, PackSource src, PackExt ext, long size, DfsBlockData dfsBlockData) { // empty } } private ObjectId insertBlobWithSize(int size) throws IOException {
/* * Copyright (C) 2023, Google LLC. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.internal.storage.dfs; public class DfsReaderTest { InMemoryRepository db; @Before public void setUp() { db = new InMemoryRepository(new DfsRepositoryDescription("test")); } @Test public void isNotLargerThan_objAboveThreshold() throws IOException { setObjectSizeIndexMinBytes(100); ObjectId obj = insertBlobWithSize(200); try (DfsReader ctx = db.getObjectDatabase().newReader()) { assertFalse("limit < threshold < obj", ctx.isNotLargerThan(obj, OBJ_BLOB, 50)); assertEquals(1, ctx.stats.isNotLargerThanCallCount); assertEquals(1, ctx.stats.objectSizeIndexHit); assertEquals(0, ctx.stats.objectSizeIndexMiss); assertFalse("limit = threshold < obj", ctx.isNotLargerThan(obj, OBJ_BLOB, 100)); assertEquals(2, ctx.stats.isNotLargerThanCallCount); assertEquals(2, ctx.stats.objectSizeIndexHit); assertEquals(0, ctx.stats.objectSizeIndexMiss); assertFalse("threshold < limit < obj", ctx.isNotLargerThan(obj, OBJ_BLOB, 150)); assertEquals(3, ctx.stats.isNotLargerThanCallCount); assertEquals(3, ctx.stats.objectSizeIndexHit); assertEquals(0, ctx.stats.objectSizeIndexMiss); assertTrue("threshold < limit = obj", ctx.isNotLargerThan(obj, OBJ_BLOB, 200)); assertEquals(4, ctx.stats.isNotLargerThanCallCount); assertEquals(4, ctx.stats.objectSizeIndexHit); assertEquals(0, ctx.stats.objectSizeIndexMiss); assertTrue("threshold < obj < limit", ctx.isNotLargerThan(obj, OBJ_BLOB, 250)); assertEquals(5, ctx.stats.isNotLargerThanCallCount); assertEquals(5, ctx.stats.objectSizeIndexHit); assertEquals(0, ctx.stats.objectSizeIndexMiss); } } @Test public void isNotLargerThan_objBelowThreshold() throws IOException { setObjectSizeIndexMinBytes(100); insertBlobWithSize(1000); // index not empty ObjectId obj = insertBlobWithSize(50); try (DfsReader ctx = db.getObjectDatabase().newReader()) { assertFalse("limit < obj < threshold", ctx.isNotLargerThan(obj, OBJ_BLOB, 10)); assertEquals(1, ctx.stats.isNotLargerThanCallCount); assertEquals(0, ctx.stats.objectSizeIndexHit); assertEquals(1, ctx.stats.objectSizeIndexMiss); assertTrue("limit = obj < threshold", ctx.isNotLargerThan(obj, OBJ_BLOB, 50)); assertEquals(2, ctx.stats.isNotLargerThanCallCount); assertEquals(0, ctx.stats.objectSizeIndexHit); assertEquals(2, ctx.stats.objectSizeIndexMiss); assertTrue("obj < limit < threshold", ctx.isNotLargerThan(obj, OBJ_BLOB, 80)); assertEquals(3, ctx.stats.isNotLargerThanCallCount); assertEquals(0, ctx.stats.objectSizeIndexHit); assertEquals(3, ctx.stats.objectSizeIndexMiss); assertTrue("obj < limit = threshold", ctx.isNotLargerThan(obj, OBJ_BLOB, 100)); assertEquals(4, ctx.stats.isNotLargerThanCallCount); assertEquals(0, ctx.stats.objectSizeIndexHit); assertEquals(4, ctx.stats.objectSizeIndexMiss); assertTrue("obj < threshold < limit", ctx.isNotLargerThan(obj, OBJ_BLOB, 120)); assertEquals(5, ctx.stats.isNotLargerThanCallCount); assertEquals(0, ctx.stats.objectSizeIndexHit); assertEquals(5, ctx.stats.objectSizeIndexMiss); } } @Test public void isNotLargerThan_emptyIdx() throws IOException { setObjectSizeIndexMinBytes(100); ObjectId obj = insertBlobWithSize(10); try (DfsReader ctx = db.getObjectDatabase().newReader()) { assertFalse(ctx.isNotLargerThan(obj, OBJ_BLOB, 0)); assertTrue(ctx.isNotLargerThan(obj, OBJ_BLOB, 10)); assertTrue(ctx.isNotLargerThan(obj, OBJ_BLOB, 40)); assertTrue(ctx.isNotLargerThan(obj, OBJ_BLOB, 50)); assertTrue(ctx.isNotLargerThan(obj, OBJ_BLOB, 100)); assertEquals(5, ctx.stats.isNotLargerThanCallCount); assertEquals(5, ctx.stats.objectSizeIndexMiss); assertEquals(0, ctx.stats.objectSizeIndexHit); } } @Test public void isNotLargerThan_noObjectSizeIndex() throws IOException { setObjectSizeIndexMinBytes(-1); ObjectId obj = insertBlobWithSize(10); try (DfsReader ctx = db.getObjectDatabase().newReader()) { assertFalse(ctx.isNotLargerThan(obj, OBJ_BLOB, 0)); assertTrue(ctx.isNotLargerThan(obj, OBJ_BLOB, 10)); assertTrue(ctx.isNotLargerThan(obj, OBJ_BLOB, 40)); assertTrue(ctx.isNotLargerThan(obj, OBJ_BLOB, 50)); assertTrue(ctx.isNotLargerThan(obj, OBJ_BLOB, 100)); assertEquals(5, ctx.stats.isNotLargerThanCallCount); assertEquals(0, ctx.stats.objectSizeIndexMiss); assertEquals(0, ctx.stats.objectSizeIndexHit); } } @Test public void packLoadListener_noInvocations() throws IOException { insertBlobWithSize(100); try (DfsReader ctx = db.getObjectDatabase().newReader()) { CounterPackLoadListener listener = new CounterPackLoadListener(); ctx.addPackLoadListener(listener); assertEquals(null, listener.callsPerExt.get(PackExt.INDEX)); } } @Test public void packLoadListener_has_openIdx() throws IOException { ObjectId obj = insertBlobWithSize(100); try (DfsReader ctx = db.getObjectDatabase().newReader()) { CounterPackLoadListener listener = new CounterPackLoadListener(); ctx.addPackLoadListener(listener); boolean has = ctx.has(obj); assertTrue(has); assertEquals(Integer.valueOf(1), listener.callsPerExt.get(PackExt.INDEX)); } } @Test public void packLoadListener_notLargerThan_openMultipleIndices() throws IOException { setObjectSizeIndexMinBytes(100); ObjectId obj = insertBlobWithSize(200); try (DfsReader ctx = db.getObjectDatabase().newReader()) { CounterPackLoadListener listener = new CounterPackLoadListener(); ctx.addPackLoadListener(listener); boolean notLargerThan = ctx.isNotLargerThan(obj, OBJ_BLOB, 1000); assertTrue(notLargerThan); assertEquals(Integer.valueOf(1), listener.callsPerExt.get(PackExt.INDEX)); assertEquals(Integer.valueOf(1), listener.callsPerExt.get(PackExt.OBJECT_SIZE_INDEX)); } } @Test public void packLoadListener_has_openMultipleIndices() throws IOException { setObjectSizeIndexMinBytes(100); insertBlobWithSize(200); insertBlobWithSize(230); insertBlobWithSize(100); try (DfsReader ctx = db.getObjectDatabase().newReader()) { CounterPackLoadListener listener = new CounterPackLoadListener(); ctx.addPackLoadListener(listener); ObjectId oid = ObjectId.fromString("aa48de2aa61d9dffa8a05439dc115fe82f10f129"); boolean has = ctx.has(oid); assertFalse(has); // Open 3 indices trying to find the pack assertEquals(Integer.valueOf(3), listener.callsPerExt.get(PackExt.INDEX)); } } @Test public void packLoadListener_has_repeatedCalls_openMultipleIndices() throws IOException { // Two objects NOT in the repo ObjectId oid = ObjectId.fromString("aa48de2aa61d9dffa8a05439dc115fe82f10f129"); ObjectId oid2 = ObjectId.fromString("aa48de2aa61d9dffa8a05439dc115fe82f10f130"); setObjectSizeIndexMinBytes(100); insertBlobWithSize(200); insertBlobWithSize(230); insertBlobWithSize(100); CounterPackLoadListener listener = new CounterPackLoadListener(); try (DfsReader ctx = db.getObjectDatabase().newReader()) { ctx.addPackLoadListener(listener); boolean has = ctx.has(oid); ctx.has(oid); ctx.has(oid2); assertFalse(has); // The 3 indices were loaded only once each assertEquals(Integer.valueOf(3), listener.callsPerExt.get(PackExt.INDEX)); } } private static class CounterPackLoadListener implements PackLoadListener { final Map<PackExt, Integer> callsPerExt = new HashMap<>(); @SuppressWarnings("boxing") @Override public void onIndexLoad(String packName, PackSource src, PackExt ext, long size, Object loadedIdx) { callsPerExt.merge(ext, 1, Integer::sum); } @Override public void onBlockLoad(String packName, PackSource src, PackExt ext, long size, DfsBlockData dfsBlockData) { // empty } } private ObjectId insertBlobWithSize(int size) throws IOException {
TestRng testRng = new TestRng(JGitTestUtil.getName());
6
2023-10-20 15:09:17+00:00
16k
starfish-studios/Naturalist
common/src/main/java/com/starfish_studios/naturalist/common/block/OstrichEggBlock.java
[ { "identifier": "Ostrich", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/Ostrich.java", "snippet": "public class Ostrich extends Animal implements IAnimatable, ItemSteerable, Saddleable, EggLayingAnimal {\n private static final Ingredient FOOD_ITEMS = Ingredient.of(Natur...
import com.starfish_studios.naturalist.common.entity.Ostrich; import com.starfish_studios.naturalist.core.registry.NaturalistEntityTypes; import com.starfish_studios.naturalist.core.registry.NaturalistSoundEvents; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundSource; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.monster.Zombie; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.TurtleEggBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape;
12,339
package com.starfish_studios.naturalist.common.block; public class OstrichEggBlock extends TurtleEggBlock { private static final VoxelShape EGG_AABB = Block.box(5.0, 0.0, 5.0, 11.0, 8.0, 11.0); public OstrichEggBlock(Properties properties) { super(properties); } @Override public void randomTick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { if (this.shouldUpdateHatchLevel(level)) { int i = state.getValue(HATCH); if (i < 2) { level.playSound(null, pos, NaturalistSoundEvents.OSTRICH_EGG_CRACK.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.setBlock(pos, state.setValue(HATCH, i + 1), 2); } else { level.playSound(null, pos, NaturalistSoundEvents.OSTRICH_EGG_HATCH.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.removeBlock(pos, false); for (int j = 0; j < state.getValue(EGGS); ++j) { level.levelEvent(2001, pos, Block.getId(state));
package com.starfish_studios.naturalist.common.block; public class OstrichEggBlock extends TurtleEggBlock { private static final VoxelShape EGG_AABB = Block.box(5.0, 0.0, 5.0, 11.0, 8.0, 11.0); public OstrichEggBlock(Properties properties) { super(properties); } @Override public void randomTick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { if (this.shouldUpdateHatchLevel(level)) { int i = state.getValue(HATCH); if (i < 2) { level.playSound(null, pos, NaturalistSoundEvents.OSTRICH_EGG_CRACK.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.setBlock(pos, state.setValue(HATCH, i + 1), 2); } else { level.playSound(null, pos, NaturalistSoundEvents.OSTRICH_EGG_HATCH.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.removeBlock(pos, false); for (int j = 0; j < state.getValue(EGGS); ++j) { level.levelEvent(2001, pos, Block.getId(state));
Ostrich ostrich = NaturalistEntityTypes.OSTRICH.get().create(level);
0
2023-10-16 21:54:32+00:00
16k
wangqi060934/MyAndroidToolsPro
app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/AppForComponentRecyclerFragment.java
[ { "identifier": "DBHelper", "path": "app/src/main/java/cn/wq/myandroidtoolspro/helper/DBHelper.java", "snippet": "public class DBHelper extends SQLiteOpenHelper {\n\tprivate static final String DB_NAME = \"actions.db\";\n\tprivate static final int DB_VERSION = 10;\n\tpublic static final String ACTION_TA...
import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AlertDialog; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import java.util.Locale; import cn.wq.myandroidtoolspro.BuildConfig; import cn.wq.myandroidtoolspro.R; import cn.wq.myandroidtoolspro.helper.DBHelper; import cn.wq.myandroidtoolspro.helper.Utils; import cn.wq.myandroidtoolspro.model.AppEntry; import cn.wq.myandroidtoolspro.recyclerview.base.RecyclerListView; import cn.wq.myandroidtoolspro.recyclerview.base.SearchRecyclerListFragment;
13,848
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class AppForComponentRecyclerFragment extends SearchRecyclerListFragment implements RecyclerListView.OnRecyclerItemClickListener { private boolean isSystem; private int type; private ComponentAdapter mAdapter; private LoadComponentTask mTask; private SortChangeReceiver mChangeReceiver; private int clicked_pos = -1; private static int mReceiverFlag = 0; private AsyncTask<Integer, Void, Integer> loadServiceTask; private Context mContext; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } public static AppForComponentRecyclerFragment newInstance(boolean isSystem, int type) { AppForComponentRecyclerFragment f = new AppForComponentRecyclerFragment(); Bundle bundle = new Bundle(); bundle.putBoolean("isSystem", isSystem); bundle.putInt("type", type); f.setArguments(bundle); return f; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class AppForComponentRecyclerFragment extends SearchRecyclerListFragment implements RecyclerListView.OnRecyclerItemClickListener { private boolean isSystem; private int type; private ComponentAdapter mAdapter; private LoadComponentTask mTask; private SortChangeReceiver mChangeReceiver; private int clicked_pos = -1; private static int mReceiverFlag = 0; private AsyncTask<Integer, Void, Integer> loadServiceTask; private Context mContext; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } public static AppForComponentRecyclerFragment newInstance(boolean isSystem, int type) { AppForComponentRecyclerFragment f = new AppForComponentRecyclerFragment(); Bundle bundle = new Bundle(); bundle.putBoolean("isSystem", isSystem); bundle.putInt("type", type); f.setArguments(bundle); return f; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
Utils.debug(getClass().getSimpleName() + " >> " + isSystem + " , " + type + " , " + (mAdapter == null));
1
2023-10-18 14:32:49+00:00
16k
instana/otel-dc
rdb/src/main/java/com/instana/dc/rdb/impl/Oceanbase4Dc.java
[ { "identifier": "CalculationMode", "path": "internal/otel-dc/src/main/java/com/instana/dc/CalculationMode.java", "snippet": "public enum CalculationMode {\n DIRECT,\n RATE\n}" }, { "identifier": "DcException", "path": "internal/otel-dc/src/main/java/com/instana/dc/DcException.java", ...
import com.instana.dc.CalculationMode; import com.instana.dc.DcException; import com.instana.dc.DcUtil; import com.instana.dc.rdb.AbstractDbDc; import io.opentelemetry.api.OpenTelemetry; import java.sql.Connection; import java.sql.SQLException; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import static com.instana.agent.sensorsdk.semconv.SemanticAttributes.SQL_TEXT; import static com.instana.dc.rdb.DbDcUtil.*; import static com.instana.dc.rdb.impl.Oceanbase4Util.*;
11,755
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb.impl; public class Oceanbase4Dc extends AbstractDbDc { private static final Logger logger = Logger.getLogger(Oceanbase4Dc.class.getName()); boolean isCluster = false; boolean isTenant = false; public Oceanbase4Dc(Map<String, String> properties, String dbSystem, String dbDriver) throws SQLException, DcException { super(properties, dbSystem, dbDriver);
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb.impl; public class Oceanbase4Dc extends AbstractDbDc { private static final Logger logger = Logger.getLogger(Oceanbase4Dc.class.getName()); boolean isCluster = false; boolean isTenant = false; public Oceanbase4Dc(Map<String, String> properties, String dbSystem, String dbDriver) throws SQLException, DcException { super(properties, dbSystem, dbDriver);
setDbPassword(DcUtil.base64Decode(getDbPassword()));
2
2023-10-23 01:16:38+00:00
16k
histevehu/12306
business/src/main/java/com/steve/train/business/service/DailyTrainCarriageService.java
[ { "identifier": "DailyTrainCarriage", "path": "business/src/main/java/com/steve/train/business/domain/DailyTrainCarriage.java", "snippet": "public class DailyTrainCarriage {\n private Long id;\n\n private Date date;\n\n private String trainCode;\n\n private Integer index;\n\n private Stri...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjUtil; import cn.hutool.core.util.ObjectUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.steve.train.business.domain.DailyTrainCarriage; import com.steve.train.business.domain.DailyTrainCarriageExample; import com.steve.train.business.domain.TrainCarriage; import com.steve.train.business.mapper.DailyTrainCarriageMapper; import com.steve.train.business.req.DailyTrainCarriageQueryReq; import com.steve.train.business.req.DailyTrainCarriageSaveReq; import com.steve.train.business.resp.DailyTrainCarriageQueryResp; import com.steve.train.common.enums.SeatColEnum; import com.steve.train.common.resp.PageResp; import com.steve.train.common.util.SnowFlakeUtil; import jakarta.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List;
11,563
package com.steve.train.business.service; /* * @author : Steve Hu * @date : 2023-11-01 10:47:36 * @description: 每日车箱服务(FreeMarker生成) */ @Service public class DailyTrainCarriageService { private static final Logger LOG = LoggerFactory.getLogger(DailyTrainCarriageService.class); @Resource private DailyTrainCarriageMapper dailyTrainCarriageMapper; @Resource private TrainCarriageService trainCarriageService; public void save(DailyTrainCarriageSaveReq req) { DateTime now = DateTime.now(); // 自动计算出列数和总座位数 List<SeatColEnum> seatColEnums = SeatColEnum.getColsByType(req.getSeatType()); req.setColCount(seatColEnums.size()); req.setSeatCount(req.getColCount() * req.getRowCount()); DailyTrainCarriage dailyTrainCarriage = BeanUtil.copyProperties(req, DailyTrainCarriage.class); if (ObjectUtil.isNull(dailyTrainCarriage.getId())) { dailyTrainCarriage.setId(SnowFlakeUtil.getSnowFlakeNextId()); dailyTrainCarriage.setCreateTime(now); dailyTrainCarriage.setUpdateTime(now); dailyTrainCarriageMapper.insert(dailyTrainCarriage); } else { dailyTrainCarriage.setUpdateTime(now); dailyTrainCarriageMapper.updateByPrimaryKey(dailyTrainCarriage); } }
package com.steve.train.business.service; /* * @author : Steve Hu * @date : 2023-11-01 10:47:36 * @description: 每日车箱服务(FreeMarker生成) */ @Service public class DailyTrainCarriageService { private static final Logger LOG = LoggerFactory.getLogger(DailyTrainCarriageService.class); @Resource private DailyTrainCarriageMapper dailyTrainCarriageMapper; @Resource private TrainCarriageService trainCarriageService; public void save(DailyTrainCarriageSaveReq req) { DateTime now = DateTime.now(); // 自动计算出列数和总座位数 List<SeatColEnum> seatColEnums = SeatColEnum.getColsByType(req.getSeatType()); req.setColCount(seatColEnums.size()); req.setSeatCount(req.getColCount() * req.getRowCount()); DailyTrainCarriage dailyTrainCarriage = BeanUtil.copyProperties(req, DailyTrainCarriage.class); if (ObjectUtil.isNull(dailyTrainCarriage.getId())) { dailyTrainCarriage.setId(SnowFlakeUtil.getSnowFlakeNextId()); dailyTrainCarriage.setCreateTime(now); dailyTrainCarriage.setUpdateTime(now); dailyTrainCarriageMapper.insert(dailyTrainCarriage); } else { dailyTrainCarriage.setUpdateTime(now); dailyTrainCarriageMapper.updateByPrimaryKey(dailyTrainCarriage); } }
public PageResp<DailyTrainCarriageQueryResp> queryList(DailyTrainCarriageQueryReq req) {
8
2023-10-23 01:20:56+00:00
16k
team-moabam/moabam-BE
src/test/java/com/moabam/api/application/room/CertificationServiceTest.java
[ { "identifier": "BugService", "path": "src/main/java/com/moabam/api/application/bug/BugService.java", "snippet": "@Service\n@Transactional(readOnly = true)\n@RequiredArgsConstructor\npublic class BugService {\n\n\tprivate final MemberService memberService;\n\tprivate final BugHistoryRepository bugHistor...
import static org.assertj.core.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.BDDMockito.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import com.moabam.api.application.bug.BugService; import com.moabam.api.application.image.ImageService; import com.moabam.api.application.member.BadgeService; import com.moabam.api.application.member.MemberService; import com.moabam.api.application.room.mapper.CertificationsMapper; import com.moabam.api.domain.bug.BugType; import com.moabam.api.domain.member.Member; import com.moabam.api.domain.room.DailyMemberCertification; import com.moabam.api.domain.room.DailyRoomCertification; import com.moabam.api.domain.room.Participant; import com.moabam.api.domain.room.Room; import com.moabam.api.domain.room.Routine; import com.moabam.api.domain.room.repository.CertificationRepository; import com.moabam.api.domain.room.repository.CertificationsSearchRepository; import com.moabam.api.domain.room.repository.DailyMemberCertificationRepository; import com.moabam.api.domain.room.repository.DailyRoomCertificationRepository; import com.moabam.api.domain.room.repository.ParticipantRepository; import com.moabam.api.domain.room.repository.ParticipantSearchRepository; import com.moabam.api.domain.room.repository.RoomRepository; import com.moabam.api.domain.room.repository.RoutineRepository; import com.moabam.api.dto.room.CertifiedMemberInfo; import com.moabam.global.common.util.ClockHolder; import com.moabam.support.fixture.MemberFixture; import com.moabam.support.fixture.RoomFixture;
11,888
package com.moabam.api.application.room; @ExtendWith(MockitoExtension.class) class CertificationServiceTest { @InjectMocks private CertificationService certificationService; @Mock private MemberService memberService; @Mock private BugService bugService; @Mock private RoomRepository roomRepository; @Mock private RoutineRepository routineRepository; @Mock private ParticipantRepository participantRepository; @Mock private CertificationRepository certificationRepository; @Mock private CertificationsSearchRepository certificationsSearchRepository; @Mock private ParticipantSearchRepository participantSearchRepository; @Mock private DailyRoomCertificationRepository dailyRoomCertificationRepository; @Mock
package com.moabam.api.application.room; @ExtendWith(MockitoExtension.class) class CertificationServiceTest { @InjectMocks private CertificationService certificationService; @Mock private MemberService memberService; @Mock private BugService bugService; @Mock private RoomRepository roomRepository; @Mock private RoutineRepository routineRepository; @Mock private ParticipantRepository participantRepository; @Mock private CertificationRepository certificationRepository; @Mock private CertificationsSearchRepository certificationsSearchRepository; @Mock private ParticipantSearchRepository participantSearchRepository; @Mock private DailyRoomCertificationRepository dailyRoomCertificationRepository; @Mock
private DailyMemberCertificationRepository dailyMemberCertificationRepository;
14
2023-10-20 06:15:43+00:00
16k
tuxming/xmfx
BaseUI/src/main/java/com/xm2013/jfx/control/selector/XmSelector.java
[ { "identifier": "FxKit", "path": "BaseUI/src/main/java/com/xm2013/jfx/common/FxKit.java", "snippet": "public class FxKit {\n\n /** The Constant DOUBLE_ARROW_RIGHT. */\n public static final String DOUBLE_ARROW_RIGHT = \"<svg version=\\\"1.1\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\" p-id=\\\"1050...
import com.xm2013.jfx.common.FxKit; import com.xm2013.jfx.control.base.ClickAnimateType; import com.xm2013.jfx.control.base.CssKeys; import com.xm2013.jfx.control.base.HueType; import com.xm2013.jfx.control.base.XmControl; import com.xm2013.jfx.control.icon.XmSVGIcon; import javafx.beans.property.*; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.css.CssMetaData; import javafx.css.Styleable; import javafx.css.StyleableProperty; import javafx.css.converter.BooleanConverter; import javafx.css.converter.EnumConverter; import javafx.css.converter.SizeConverter; import javafx.scene.AccessibleRole; import javafx.scene.Node; import javafx.scene.control.Skin; import javafx.scene.paint.Color; import java.util.ArrayList; import java.util.Collections; import java.util.List;
12,812
} public void setCloseable(boolean closeable) { this.closeableProperty().set(closeable); } /** * 是否可以编辑 */ private BooleanProperty editable; public boolean isEditable() { return editableProperty().get(); } public BooleanProperty editableProperty() { if(editable == null) editable = FxKit.newBooleanProperty(false, XmSelector.StyleableProperties.EDITABLE, this, "editable"); return editable; } public void setEditable(boolean editable) { this.editableProperty().set(editable); } /** * 设置列表每个cell的回调, 可以通过回调做一些自定义操作 */ public ObjectProperty<SelectorCellFactory<T>> cellFactory = new SimpleObjectProperty<>(null); public SelectorCellFactory<T> getCellFactory() { return cellFactory.get(); } public ObjectProperty<SelectorCellFactory<T>> cellFactoryProperty() { return cellFactory; } public void setCellFactory(SelectorCellFactory<T> cellFactory) { this.cellFactory.set(cellFactory); } /** * 下拉按钮是填充还是,边框,默认是填充 */ private BooleanProperty fillArrow; public boolean isFillArrow() { return fillArrowProperty().get(); } public BooleanProperty fillArrowProperty() { if(fillArrow == null){ fillArrow = FxKit.newBooleanProperty(false, StyleableProperties.FILL_ARROW, this, "fillIcon"); } return fillArrow; } public void setFillArrow(boolean fillArrow) { this.fillArrowProperty().set(fillArrow); } /** * 多选情况下,显示的最大条目数 */ private IntegerProperty maxTagCount; public int getMaxTagCount() { return maxTagCountProperty().get(); } public IntegerProperty maxTagCountProperty() { if(maxTagCount == null){ maxTagCount = FxKit.newIntegerProperty(-1, StyleableProperties.MAX_TAG_COUNT, this, "maxTagCount"); } return maxTagCount; } public void setMaxTagCount(int maxTagCount) { this.maxTagCountProperty().set(maxTagCount); } /** * 默认显示的文本 */ private StringProperty promptText; public String getPromptText() { return promptTextProperty().get(); } public StringProperty promptTextProperty() { if(promptText == null){ promptText = new SimpleStringProperty(this, "promptText", null) { @Override protected void invalidated() { // Strip out newlines String txt = get(); if (txt != null && txt.contains("\n")) { txt = txt.replace("\n", ""); set(txt); } } }; } return promptText; } public void setPromptText(String promptText) { this.promptTextProperty().set(promptText); } /** * 色调类型,在亮色和暗色背景下面,控件的样式 */ private ObjectProperty<HueType> hueType; public HueType getHueType() { return hueTypeProperty().get(); } public ObjectProperty<HueType> hueTypeProperty() { if(hueType == null) hueType = FxKit.newProperty(HueType.DARK, XmSelector.StyleableProperties.HUE_TYPE, this, "hueType"); return hueType; } public void setHueType(HueType hueType) { this.hueTypeProperty().set(hueType); } /** * 点击控件后的动画效果 */
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.jfx.control.selector; /** * 数据下拉的选择框 */ public class XmSelector<T> extends XmControl { private static final String USER_AGENT_STYLESHEET = FxKit.USER_AGENT_STYLESHEET; private static final String DEFAULT_STYLE_CLASS = "xm-selector"; /* ---------------------------- constructor / override -------------------------------------*/ public XmSelector(){ this(null); } public XmSelector(ObservableList<T> items){ getStyleClass().add(DEFAULT_STYLE_CLASS); setAccessibleRole(AccessibleRole.TEXT_FIELD); this.getStylesheets().add(USER_AGENT_STYLESHEET); if(items != null && items.size()>0){ this.items.set(items); } setHueType(HueType.LIGHT); } @Override protected Skin<?> createDefaultSkin() { return new XmSelectorSkin<>(this); } /* ------------------------------- properties -------------------------------- */ /** * 默认转换器 * @return * @param <T> */ private static <T> SelectorConvert<T> defaultStringConverter() { return new SelectorConvert<T>() { @Override public List<T> getChildren(T t) { return null; } @Override public String toString(T object) { return object !=null ? object.toString() : null; } @Override public T fromString(String string) { return string!= null ? (T) string : null; } }; } /** * 选中的值 */ private ObjectProperty<ObservableList<T>> values = new SimpleObjectProperty<>(FXCollections.<T>observableArrayList()); public ObservableList<T> getValues() { return valuesProperty().get(); } public T getValue(){ ObservableList<T> vs = getValues(); if(vs.size()>0){ return vs.get(vs.size()-1); }else{ return null; } } public void setValues(T... t){ values.get().setAll(t); } public void setValue(T t){ values.get().setAll(t); } public ObjectProperty<ObservableList<T>> valuesProperty(){ return values; } /** * 设置选选择模式, 单选还是多选, 默认单选模式 */ private BooleanProperty multiple; public boolean isMultiple() { return multipleProperty().get(); } public BooleanProperty multipleProperty() { if(multiple == null){ multiple = FxKit.newBooleanProperty(false, StyleableProperties.MULTIPLE, this, "multiple"); } return multiple; } public void setMultiple(boolean multiple) { this.multipleProperty().set(multiple); } /** * 待选择的数据 */ private ObjectProperty<ObservableList<T>> items = new SimpleObjectProperty<ObservableList<T>>(this, "items", FXCollections.observableArrayList()); public final void setItems(T ...t) { items.get().setAll(t); } public final void setItems(ObservableList<T> items) { this.items.set(items); } public final ObservableList<T> getItems() {return items.get(); } public ObjectProperty<ObservableList<T>> itemsProperty() { return items; } public void addItems(T ...t){ items.get().addAll(t); } /** * page目前不支持,后续根据需要进行修改 * 选择框类型:LIST/GRID/TREE/PAGE */ private ObjectProperty<SelectorType> selectorType; public SelectorType getSelectorType() { return selectorTypeProperty().get(); } public ObjectProperty<SelectorType> selectorTypeProperty() { if(selectorType == null) selectorType = FxKit.newProperty(SelectorType.LIST, XmSelector.StyleableProperties.SELECTOR_TYPE, this, "selectorType"); return selectorType; } public void setSelectorType(SelectorType selectorType) { this.selectorTypeProperty().set(selectorType); } /** * 下拉箭头,可以自定义 */ private XmSVGIcon svgIcon = new XmSVGIcon("M0,0L2,0L5,5L8,0L10,0L5,7Z", Color.BLACK, 16); /** * 右侧的图标,默认是下拉箭头, 只在单选模式下生效 */ private ObjectProperty<Node> arrowIcon; public Node getArrowIcon() { return arrowIconProperty().get()==null?svgIcon: arrowIconProperty().get(); } public ObjectProperty<Node> arrowIconProperty() { if(arrowIcon == null){ arrowIcon = new SimpleObjectProperty<>(svgIcon); } return arrowIcon; } public void setArrowIcon(Node arrowIcon) { this.arrowIconProperty().set(arrowIcon); } /** * 前缀图标,只在当选模式下生效 */ private ObjectProperty<Node> prefix; public Node getPrefix() { return prefixProperty().get(); } public ObjectProperty<Node> prefixProperty() { if(prefix == null){ prefix = new SimpleObjectProperty<>(null); } return prefix; } public void setPrefix(Node prefix) { this.prefixProperty().set(prefix); } /** * 转换器,将对象T转换成可显示的有意义的文本 * @return ObjectProperty */ public ObjectProperty<SelectorConvert<T>> converterProperty() { return converter; } private ObjectProperty<SelectorConvert<T>> converter = new SimpleObjectProperty<SelectorConvert<T>>(this, "converter", XmSelector.<T>defaultStringConverter()); public final void setConverter(SelectorConvert<T> value) { converterProperty().set(value != null ? value : XmSelector.<T>defaultStringConverter()); } public final SelectorConvert<T> getConverter() {return converterProperty().get(); } /** * 是否可以关闭标签 */ private BooleanProperty closeable; public boolean isCloseable() { return closeableProperty().get(); } public BooleanProperty closeableProperty() { if(closeable == null){ closeable = FxKit.newBooleanProperty(false, XmSelector.StyleableProperties.CLOSEABLE, this, "closeable"); } return closeable; } public void setCloseable(boolean closeable) { this.closeableProperty().set(closeable); } /** * 是否可以编辑 */ private BooleanProperty editable; public boolean isEditable() { return editableProperty().get(); } public BooleanProperty editableProperty() { if(editable == null) editable = FxKit.newBooleanProperty(false, XmSelector.StyleableProperties.EDITABLE, this, "editable"); return editable; } public void setEditable(boolean editable) { this.editableProperty().set(editable); } /** * 设置列表每个cell的回调, 可以通过回调做一些自定义操作 */ public ObjectProperty<SelectorCellFactory<T>> cellFactory = new SimpleObjectProperty<>(null); public SelectorCellFactory<T> getCellFactory() { return cellFactory.get(); } public ObjectProperty<SelectorCellFactory<T>> cellFactoryProperty() { return cellFactory; } public void setCellFactory(SelectorCellFactory<T> cellFactory) { this.cellFactory.set(cellFactory); } /** * 下拉按钮是填充还是,边框,默认是填充 */ private BooleanProperty fillArrow; public boolean isFillArrow() { return fillArrowProperty().get(); } public BooleanProperty fillArrowProperty() { if(fillArrow == null){ fillArrow = FxKit.newBooleanProperty(false, StyleableProperties.FILL_ARROW, this, "fillIcon"); } return fillArrow; } public void setFillArrow(boolean fillArrow) { this.fillArrowProperty().set(fillArrow); } /** * 多选情况下,显示的最大条目数 */ private IntegerProperty maxTagCount; public int getMaxTagCount() { return maxTagCountProperty().get(); } public IntegerProperty maxTagCountProperty() { if(maxTagCount == null){ maxTagCount = FxKit.newIntegerProperty(-1, StyleableProperties.MAX_TAG_COUNT, this, "maxTagCount"); } return maxTagCount; } public void setMaxTagCount(int maxTagCount) { this.maxTagCountProperty().set(maxTagCount); } /** * 默认显示的文本 */ private StringProperty promptText; public String getPromptText() { return promptTextProperty().get(); } public StringProperty promptTextProperty() { if(promptText == null){ promptText = new SimpleStringProperty(this, "promptText", null) { @Override protected void invalidated() { // Strip out newlines String txt = get(); if (txt != null && txt.contains("\n")) { txt = txt.replace("\n", ""); set(txt); } } }; } return promptText; } public void setPromptText(String promptText) { this.promptTextProperty().set(promptText); } /** * 色调类型,在亮色和暗色背景下面,控件的样式 */ private ObjectProperty<HueType> hueType; public HueType getHueType() { return hueTypeProperty().get(); } public ObjectProperty<HueType> hueTypeProperty() { if(hueType == null) hueType = FxKit.newProperty(HueType.DARK, XmSelector.StyleableProperties.HUE_TYPE, this, "hueType"); return hueType; } public void setHueType(HueType hueType) { this.hueTypeProperty().set(hueType); } /** * 点击控件后的动画效果 */
private ObjectProperty<ClickAnimateType> clickAnimateType;
1
2023-10-17 08:57:08+00:00
16k
Dwight-Studio/JArmEmu
src/main/java/fr/dwightstudio/jarmemu/gui/controllers/SettingsController.java
[ { "identifier": "AbstractJArmEmuModule", "path": "src/main/java/fr/dwightstudio/jarmemu/gui/AbstractJArmEmuModule.java", "snippet": "public class AbstractJArmEmuModule implements Initializable {\n\n protected final JArmEmuApplication application;\n\n public AbstractJArmEmuModule(JArmEmuApplication...
import javafx.beans.value.ChangeListener; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleButton; import javafx.scene.control.ToggleGroup; import java.net.URL; import java.util.Arrays; import java.util.ResourceBundle; import java.util.logging.Logger; import java.util.prefs.Preferences; import fr.dwightstudio.jarmemu.gui.AbstractJArmEmuModule; import fr.dwightstudio.jarmemu.gui.JArmEmuApplication; import fr.dwightstudio.jarmemu.sim.ExecutionWorker; import fr.dwightstudio.jarmemu.sim.obj.StateContainer; import fr.dwightstudio.jarmemu.sim.parse.SourceParser; import fr.dwightstudio.jarmemu.util.converters.SpinnerAddressConverter; import fr.dwightstudio.jarmemu.util.converters.SpinnerStringConverter;
12,224
/* * ____ _ __ __ _____ __ ___ * / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___ * / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \ * / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ / * /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/ * /____/ * Copyright (C) 2023 Dwight Studio * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package fr.dwightstudio.jarmemu.gui.controllers; public class SettingsController extends AbstractJArmEmuModule { public static final ChangeListener<Toggle> PREVENT_UNSELECTION = (obs, oldVal, newVal) -> { if (newVal == null) { oldVal.setSelected(true); } }; // Valeurs par défaut public static final boolean DEFAULT_AUTO_BREAK = true; public static final boolean DEFAULT_MEMORY_ALIGN_BREAK = false; public static final boolean DEFAULT_STACK_ALIGN_BREAK = true; public static final boolean DEFAULT_PROGRAM_ALIGN_BREAK = true; public static final boolean DEFAULT_FUNCTION_NESTING_BREAK = true; public static final boolean DEFAULT_READ_ONLY_WRITING_BREAK = true; public static final int DEFAULT_DATA_FORMAT = 0; public static final boolean DEFAULT_FOLLOW_SP = true; public static final boolean DEFAULT_HIGHLIGHT_UPDATES = true; public static final int DEFAULT_THEME_FAMILY = 0; public static final int DEFAULT_THEME_VARIATION = 0; public static final String DEFAULT_LAYOUT = "{\"splitPanes\":{\"mainSplitPane\":[0.2,0.75],\"leftSplitPane\":[0.5]},\"maximized\":true,\"memoryColumns\":{\"memoryDetails\":[true,true,false,true,true,true,true],\"memoryOverview\":[true,false,true,true,true,true]}}"; public static final String VERSION_KEY = "version"; public static final String LAST_SAVE_PATH_KEY = "lastSavePath"; public static final String SIMULATION_INTERVAL_KEY = "simulationInterval"; public static final String SOURCE_PARSER_KEY = "sourceParser"; public static final String AUTO_BREAK_KEY = "automaticBreakpoints"; public static final String MEMORY_ALIGN_BREAK_KEY = "memoryAlignmentBreakpoint"; public static final String STACK_ALIGN_BREAK_KEY = "stackPointerAlignmentBreakpoint"; public static final String PROGRAM_ALIGN_BREAK_KEY = "programCounterAlignmentBreakpoint"; public static final String FUNCTION_NESTING_BREAK_KEY = "functionNestingBreakpoint"; public static final String READ_ONLY_WRITING_BREAK_KEY = "readOnlyDataOverwrittenBreakpoint"; public static final String STACK_ADDRESS_KEY = "stackAddress"; public static final String SYMBOLS_ADDRESS_KEY = "symbolsAddress"; public static final String DATA_FORMAT_KEY = "dataFormat"; public static final String FOLLOW_SP_KEY = "followSP"; public static final String HIGHLIGHT_UPDATES_KEY = "highlightUpdates"; public static final String THEME_FAMILY_KEY = "themeFamily"; public static final String THEME_VARIATION_KEY = "theme"; public static final String LAYOUT_KEY = "layout"; private static final String[] DATA_FORMAT_LABEL_DICT = new String[]{"Hexadecimal (default)", "Signed Decimal", "Unsigned Decimal"}; private static final String[] THEME_FAMILY_LABEL_DICT = new String[]{"Primer", "Nord", "Cupertino"}; public static final String[] DATA_FORMAT_DICT = new String[]{"%08x", "%d", "%d"}; private final Logger logger = Logger.getLogger(getClass().getName()); private boolean initiated; private Preferences preferences; // Spinners private SpinnerValueFactory<Integer> simIntervalValue; private SpinnerValueFactory<Integer> stackAddressValue; private SpinnerValueFactory<Integer> symbolsAddressValue; // ToggleGroup private ToggleGroup parserGroup; private ToggleGroup themeGroup; private ToggleButton[] parserToggles; private ToggleButton[] themeToggles;
/* * ____ _ __ __ _____ __ ___ * / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___ * / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \ * / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ / * /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/ * /____/ * Copyright (C) 2023 Dwight Studio * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package fr.dwightstudio.jarmemu.gui.controllers; public class SettingsController extends AbstractJArmEmuModule { public static final ChangeListener<Toggle> PREVENT_UNSELECTION = (obs, oldVal, newVal) -> { if (newVal == null) { oldVal.setSelected(true); } }; // Valeurs par défaut public static final boolean DEFAULT_AUTO_BREAK = true; public static final boolean DEFAULT_MEMORY_ALIGN_BREAK = false; public static final boolean DEFAULT_STACK_ALIGN_BREAK = true; public static final boolean DEFAULT_PROGRAM_ALIGN_BREAK = true; public static final boolean DEFAULT_FUNCTION_NESTING_BREAK = true; public static final boolean DEFAULT_READ_ONLY_WRITING_BREAK = true; public static final int DEFAULT_DATA_FORMAT = 0; public static final boolean DEFAULT_FOLLOW_SP = true; public static final boolean DEFAULT_HIGHLIGHT_UPDATES = true; public static final int DEFAULT_THEME_FAMILY = 0; public static final int DEFAULT_THEME_VARIATION = 0; public static final String DEFAULT_LAYOUT = "{\"splitPanes\":{\"mainSplitPane\":[0.2,0.75],\"leftSplitPane\":[0.5]},\"maximized\":true,\"memoryColumns\":{\"memoryDetails\":[true,true,false,true,true,true,true],\"memoryOverview\":[true,false,true,true,true,true]}}"; public static final String VERSION_KEY = "version"; public static final String LAST_SAVE_PATH_KEY = "lastSavePath"; public static final String SIMULATION_INTERVAL_KEY = "simulationInterval"; public static final String SOURCE_PARSER_KEY = "sourceParser"; public static final String AUTO_BREAK_KEY = "automaticBreakpoints"; public static final String MEMORY_ALIGN_BREAK_KEY = "memoryAlignmentBreakpoint"; public static final String STACK_ALIGN_BREAK_KEY = "stackPointerAlignmentBreakpoint"; public static final String PROGRAM_ALIGN_BREAK_KEY = "programCounterAlignmentBreakpoint"; public static final String FUNCTION_NESTING_BREAK_KEY = "functionNestingBreakpoint"; public static final String READ_ONLY_WRITING_BREAK_KEY = "readOnlyDataOverwrittenBreakpoint"; public static final String STACK_ADDRESS_KEY = "stackAddress"; public static final String SYMBOLS_ADDRESS_KEY = "symbolsAddress"; public static final String DATA_FORMAT_KEY = "dataFormat"; public static final String FOLLOW_SP_KEY = "followSP"; public static final String HIGHLIGHT_UPDATES_KEY = "highlightUpdates"; public static final String THEME_FAMILY_KEY = "themeFamily"; public static final String THEME_VARIATION_KEY = "theme"; public static final String LAYOUT_KEY = "layout"; private static final String[] DATA_FORMAT_LABEL_DICT = new String[]{"Hexadecimal (default)", "Signed Decimal", "Unsigned Decimal"}; private static final String[] THEME_FAMILY_LABEL_DICT = new String[]{"Primer", "Nord", "Cupertino"}; public static final String[] DATA_FORMAT_DICT = new String[]{"%08x", "%d", "%d"}; private final Logger logger = Logger.getLogger(getClass().getName()); private boolean initiated; private Preferences preferences; // Spinners private SpinnerValueFactory<Integer> simIntervalValue; private SpinnerValueFactory<Integer> stackAddressValue; private SpinnerValueFactory<Integer> symbolsAddressValue; // ToggleGroup private ToggleGroup parserGroup; private ToggleGroup themeGroup; private ToggleButton[] parserToggles; private ToggleButton[] themeToggles;
public SettingsController(JArmEmuApplication application) {
1
2023-10-17 18:22:09+00:00
16k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/PCFGLA/CoarseToFineTwoChartsParser.java
[ { "identifier": "Linearizer", "path": "src/berkeley_parser/edu/berkeley/nlp/discPCFG/Linearizer.java", "snippet": "public interface Linearizer {\n\tpublic double[] getLinearizedGrammar();\n\n\tpublic double[] getLinearizedLexicon();\n\n\tpublic double[] getLinearizedSpanPredictor();\n\n\tpublic double[]...
import java.util.Arrays; import java.util.List; import edu.berkeley.nlp.discPCFG.Linearizer; import edu.berkeley.nlp.syntax.StateSet; import edu.berkeley.nlp.syntax.Tree;
11,622
for (int start = 0; start < length; start++) { for (int end = start + 1; end <= length; end++) { if (firstTime) { viScore[start][end] = new double[numStates]; voScore[start][end] = new double[numStates]; iScorePreU[start][end] = new double[numStates][]; iScorePostU[start][end] = new double[numStates][]; oScorePreU[start][end] = new double[numStates][]; oScorePostU[start][end] = new double[numStates][]; // iScale[start][end] = new int[numStates]; // oScale[start][end] = new int[numStates]; allowedSubStates[start][end] = new boolean[numStates][]; allowedStates[start][end] = grammarTags.clone(); if (level == 1 && (end - start == 1)) Arrays.fill(allowedStates[start][end], true); vAllowedStates[start][end] = true; } for (int state = 0; state < numSubStatesArray.length; state++) { if (allowedSubStates[start][end][state] != null) { if (level < 1) { viScore[start][end][state] = Double.NEGATIVE_INFINITY; voScore[start][end][state] = Double.NEGATIVE_INFINITY; } else { iScorePreU[start][end][state] = new double[numSubStatesArray[state]]; iScorePostU[start][end][state] = new double[numSubStatesArray[state]]; oScorePreU[start][end][state] = new double[numSubStatesArray[state]]; oScorePostU[start][end][state] = new double[numSubStatesArray[state]]; Arrays.fill(iScorePreU[start][end][state], initVal); Arrays.fill(iScorePostU[start][end][state], initVal); Arrays.fill(oScorePreU[start][end][state], initVal); Arrays.fill(oScorePostU[start][end][state], initVal); // Arrays.fill(iScale[start][end], // Integer.MIN_VALUE); // Arrays.fill(oScale[start][end], // Integer.MIN_VALUE); // boolean[] newAllowedSubStates = new // boolean[numSubStatesArray[state]]; // if (allowedSubStates[start][end][state]==null || // level<=1){ // Arrays.fill(newAllowedSubStates,true); // allowedSubStates[start][end][state] = // newAllowedSubStates; // } else{ // if (!justInit){ // // int[][] curLChildMap = lChildMap[level-2]; // // int[][] curRChildMap = rChildMap[level-2]; // // for (int i=0; // i<allowedSubStates[start][end][state].length; // i++){ // // boolean val = // allowedSubStates[start][end][state][i]; // // newAllowedSubStates[curLChildMap[state][i]] = // val; // // newAllowedSubStates[curRChildMap[state][i]] = // val; // // } // // allowedSubStates[start][end][state] = // newAllowedSubStates; // } // } } } else { if (level < 1) { viScore[start][end][state] = Double.NEGATIVE_INFINITY; voScore[start][end][state] = Double.NEGATIVE_INFINITY; } else { iScorePreU[start][end][state] = null; iScorePostU[start][end][state] = null; oScorePreU[start][end][state] = null; oScorePostU[start][end][state] = null; // allowedSubStates[start][end][state] = new // boolean[1]; // allowedSubStates[start][end][state][0] = false; } } } if (level > 0 && start == 0 && end == length) { if (iScorePostU[start][end][0] == null) System.out .println("ROOT does not span the entire tree!"); } } } narrowRExtent = new int[length + 1][numStates]; wideRExtent = new int[length + 1][numStates]; narrowLExtent = new int[length + 1][numStates]; wideLExtent = new int[length + 1][numStates]; for (int loc = 0; loc <= length; loc++) { Arrays.fill(narrowLExtent[loc], -1); // the rightmost left with // state s ending at i that // we can get is the // beginning Arrays.fill(wideLExtent[loc], length + 1); // the leftmost left with // state s ending at i // that we can get is // the end Arrays.fill(narrowRExtent[loc], length + 1); // the leftmost right // with state s // starting at i // that we can get // is the end Arrays.fill(wideRExtent[loc], -1); // the rightmost right with state // s starting at i that we can // get is the beginning } } @Override protected void clearArrays() { iScorePreU = iScorePostU = oScorePreU = oScorePostU = null; viScore = voScore = null; allowedSubStates = null; vAllowedStates = null; // iPossibleByL = iPossibleByR = oFilteredEnd = oFilteredStart = // oPossibleByL = oPossibleByR = tags = null; narrowRExtent = wideRExtent = narrowLExtent = wideLExtent = null; }
/** * */ package edu.berkeley.nlp.PCFGLA; /** * @author petrov * */ public class CoarseToFineTwoChartsParser extends CoarseToFineMaxRuleParser { /** * inside and outside scores; start idx, end idx, state, substate -> * logProb/prob */ /** NEW: we now have two charts one before applying unaries and one after: */ protected double[][][][] iScorePreU, iScorePostU; protected double[][][][] oScorePreU, oScorePostU; /** * @param gr * @param lex * @param unaryPenalty * @param endL * @param viterbi * @param sub * @param score */ public CoarseToFineTwoChartsParser(Grammar gr, Lexicon lex, double unaryPenalty, int endL, boolean viterbi, boolean sub, boolean score, boolean accurate) { super(gr, lex, unaryPenalty, endL, viterbi, sub, score, accurate, false, false, true); } @Override void doConstrainedInsideScores(Grammar grammar, boolean viterbi, boolean logScores) { if (!viterbi && logScores) throw new Error( "This would require logAdds and is slow. Exponentiate the scores instead."); numSubStatesArray = grammar.numSubStates; double initVal = (logScores) ? Double.NEGATIVE_INFINITY : 0; // double[] oldIScores = new double[maxNSubStates]; // int smallestScale = 10, largestScale = -10; for (int diff = 1; diff <= length; diff++) { // smallestScale = 10; largestScale = -10; // System.out.print(diff + " "); for (int start = 0; start < (length - diff + 1); start++) { int end = start + diff; for (int pState = 0; pState < numSubStatesArray.length; pState++) { if (diff == 1) continue; // there are no binary rules that span over 1 // symbol only if (allowedSubStates[start][end][pState] == null) continue; BinaryRule[] parentRules = grammar.splitRulesWithP(pState); int nParentStates = numSubStatesArray[pState]; // we will oftern write to the scoresToAdd array and then // transfer the accumulated values once // to the iScores arrays because writing to large arrays is // slow // scoresToAdd = new double[nParentStates]; Arrays.fill(scoresToAdd, initVal); boolean somethingChanged = false; for (int i = 0; i < parentRules.length; i++) { BinaryRule r = parentRules[i]; int lState = r.leftChildState; int rState = r.rightChildState; int narrowR = narrowRExtent[start][lState]; boolean iPossibleL = (narrowR < end); // can this left // constituent // leave space // for a right // constituent? if (!iPossibleL) { continue; } int narrowL = narrowLExtent[end][rState]; boolean iPossibleR = (narrowL >= narrowR); // can this // right // constituent // fit next // to the // left // constituent? if (!iPossibleR) { continue; } int min1 = narrowR; int min2 = wideLExtent[end][rState]; int min = (min1 > min2 ? min1 : min2); // can this right // constituent // stretch far // enough to // reach the // left // constituent? if (min > narrowL) { continue; } int max1 = wideRExtent[start][lState]; int max2 = narrowL; int max = (max1 < max2 ? max1 : max2); // can this left // constituent // stretch far // enough to // reach the // right // constituent? if (min > max) { continue; } // TODO switch order of loops for efficiency double[][][] scores = r.getScores2(); int nLeftChildStates = numSubStatesArray[lState]; int nRightChildStates = numSubStatesArray[rState]; for (int split = min; split <= max; split++) { if (allowedSubStates[start][split][lState] == null) continue; if (allowedSubStates[split][end][rState] == null) continue; for (int lp = 0; lp < nLeftChildStates; lp++) { // if (iScore[start][split][lState] == null) // continue; // if // (!allowedSubStates[start][split][lState][lp]) // continue; double lS = iScorePostU[start][split][lState][lp]; if (lS == initVal) continue; for (int rp = 0; rp < nRightChildStates; rp++) { if (scores[lp][rp] == null) continue; double rS = iScorePostU[split][end][rState][rp]; if (rS == initVal) continue; for (int np = 0; np < nParentStates; np++) { if (!allowedSubStates[start][end][pState][np]) continue; double pS = scores[lp][rp][np]; if (pS == initVal) continue; // if (iScore[split][end][rState] == // null) continue; // if // (!allowedSubStates[split][end][rState][rp]) // continue; double thisRound = (logScores) ? pS + lS + rS : pS * lS * rS; if (viterbi) scoresToAdd[np] = Math.max( thisRound, scoresToAdd[np]); else scoresToAdd[np] += thisRound; somethingChanged = true; } } } // if (!somethingChanged) continue; // boolean firstTime = false; /* * int parentScale = iScale[start][end][pState]; int * currentScale = * iScale[start][split][lState]+iScale * [split][end][rState]; if * (parentScale==currentScale) { // already had a * way to generate this state and the scales are the * same // -> nothing to do } else { if * (parentScale==Integer.MIN_VALUE){ // first time * we can build this state firstTime = true; * parentScale = * scaleArray(scoresToAdd,currentScale); * iScale[start][end][pState] = parentScale; * //smallestScale = * Math.min(smallestScale,parentScale); * //largestScale = * Math.max(largestScale,parentScale); } else { // * scale the smaller one to the base of the bigger * one int newScale = * Math.max(currentScale,parentScale); * scaleArrayToScale * (scoresToAdd,currentScale,newScale); * scaleArrayToScale * (iScore[start][end][pState],parentScale * ,newScale); iScale[start][end][pState] = * newScale; //smallestScale = * Math.min(smallestScale,newScale); //largestScale * = Math.max(largestScale,newScale); } } */ } } if (!somethingChanged) continue; for (int np = 0; np < nParentStates; np++) { if (scoresToAdd[np] > initVal) { iScorePreU[start][end][pState][np] = scoresToAdd[np]; } } // iScale[start][end][pState] = currentScale; // iScale[start][end][pState] = // scaleArray(iScore[start][end][pState],iScale[start][end][pState]); if (true/* firstTime */) { if (start > narrowLExtent[end][pState]) { narrowLExtent[end][pState] = start; wideLExtent[end][pState] = start; } else { if (start < wideLExtent[end][pState]) { wideLExtent[end][pState] = start; } } if (end < narrowRExtent[start][pState]) { narrowRExtent[start][pState] = end; wideRExtent[start][pState] = end; } else { if (end > wideRExtent[start][pState]) { wideRExtent[start][pState] = end; } } } } // now do the unaries for (int pState = 0; pState < numSubStatesArray.length; pState++) { if (allowedSubStates[start][end][pState] == null) continue; // Should be: Closure under sum-product: UnaryRule[] unaries = grammar .getClosedSumUnaryRulesByParent(pState); // UnaryRule[] unaries = // grammar.getUnaryRulesByParent(pState).toArray(new // UnaryRule[0]); int nParentStates = numSubStatesArray[pState];// scores[0].length; boolean firstTime = true; boolean somethingChanged = false; for (int r = 0; r < unaries.length; r++) { UnaryRule ur = unaries[r]; int cState = ur.childState; if ((pState == cState)) continue; if (iScorePreU[start][end][cState] == null) continue; // if (!allowedStates[start][end][cState]) continue; // new loop over all substates // System.out.println("Rule "+r+" out of "+unaries.length+" "+ur); double[][] scores = ur.getScores2(); int nChildStates = numSubStatesArray[cState];// scores[0].length; for (int cp = 0; cp < nChildStates; cp++) { if (scores[cp] == null) continue; double iS = iScorePreU[start][end][cState][cp]; if (iS == initVal) continue; for (int np = 0; np < nParentStates; np++) { if (!allowedSubStates[start][end][pState][np]) continue; // if // (!allowedSubStates[start][end][cState][cp]) // continue; double pS = scores[cp][np]; if (pS == initVal) continue; if (firstTime) { firstTime = false; Arrays.fill(scoresToAdd, initVal); } double thisRound = (logScores) ? iS + pS : iS * pS; if (viterbi) scoresToAdd[np] = Math.max(thisRound, scoresToAdd[np]); else scoresToAdd[np] += thisRound; somethingChanged = true; } } } /* * boolean firstTime = false; int currentScale = * iScale[start][end][cState]; int parentScale = * iScale[start][end][pState]; if * (parentScale==currentScale) { // already had a way to * generate this state and the scales are the same // -> * nothing to do } else { if * (parentScale==Integer.MIN_VALUE){ // first time we can * build this state firstTime = true; parentScale = * scaleArray(scoresToAdd,currentScale); * iScale[start][end][pState] = parentScale; //smallestScale * = Math.min(smallestScale,parentScale); //largestScale = * Math.max(largestScale,parentScale); } else { // scale the * smaller one to the base of the bigger one int newScale = * Math.max(currentScale,parentScale); * scaleArrayToScale(scoresToAdd,currentScale,newScale); * scaleArrayToScale * (iScore[start][end][pState],parentScale,newScale); * iScale[start][end][pState] = newScale; //smallestScale = * Math.min(smallestScale,newScale); //largestScale = * Math.max(largestScale,newScale); * * } } */ if (!somethingChanged) { iScorePostU[start][end][pState] = iScorePreU[start][end][pState] .clone(); continue; } else { for (int np = 0; np < nParentStates; np++) { if (scoresToAdd[np] > initVal) { if (viterbi) iScorePostU[start][end][pState][np] = Math .max(iScorePreU[start][end][pState][np], scoresToAdd[np]); else iScorePostU[start][end][pState][np] = iScorePreU[start][end][pState][np] + scoresToAdd[np]; } else iScorePostU[start][end][pState][np] = iScorePreU[start][end][pState][np]; } } // iScale[start][end][pState] = currentScale; // iScale[start][end][pState] = // scaleArray(iScore[start][end][pState],iScale[start][end][pState]); if (true) { if (start > narrowLExtent[end][pState]) { narrowLExtent[end][pState] = start; wideLExtent[end][pState] = start; } else { if (start < wideLExtent[end][pState]) { wideLExtent[end][pState] = start; } } if (end < narrowRExtent[start][pState]) { narrowRExtent[start][pState] = end; wideRExtent[start][pState] = end; } else { if (end > wideRExtent[start][pState]) { wideRExtent[start][pState] = end; } } } } } } } @Override void doConstrainedOutsideScores(Grammar grammar, boolean viterbi, boolean logScores) { numSubStatesArray = grammar.numSubStates; double initVal = (logScores) ? Double.NEGATIVE_INFINITY : 0; for (int diff = length; diff >= 1; diff--) { for (int start = 0; start + diff <= length; start++) { int end = start + diff; // do unaries boolean somethingChanged = false; for (int pState = 0; pState < numSubStatesArray.length; pState++) { if (oScorePreU[start][end][pState] == null) { continue; } // if (!allowedStates[start][end][pState]) continue; // Should be: Closure under sum-product: UnaryRule[] rules = grammar .getClosedSumUnaryRulesByParent(pState); // UnaryRule[] rules = // grammar.getClosedViterbiUnaryRulesByParent(pState); // For now: // UnaryRule[] rules = // grammar.getUnaryRulesByParent(pState).toArray(new // UnaryRule[0]); for (int r = 0; r < rules.length; r++) { UnaryRule ur = rules[r]; int cState = ur.childState; if ((pState == cState)) continue; // if (!allowedStates[start][end][cState]) continue; if (oScorePreU[start][end][cState] == null) { continue; } double[][] scores = ur.getScores2(); int nParentStates = numSubStatesArray[pState]; int nChildStates = scores.length; boolean firstTime = true; for (int cp = 0; cp < nChildStates; cp++) { if (scores[cp] == null) continue; if (!allowedSubStates[start][end][cState][cp]) continue; for (int np = 0; np < nParentStates; np++) { // if // (!allowedSubStates[start][end][pState][np]) // continue; double pS = scores[cp][np]; if (pS == initVal) continue; double oS = oScorePreU[start][end][pState][np]; if (oS == initVal) continue; double thisRound = (logScores) ? oS + pS : oS * pS; if (firstTime) { firstTime = false; Arrays.fill(scoresToAdd, initVal); } if (viterbi) scoresToAdd[cp] = Math.max(thisRound, scoresToAdd[cp]); else scoresToAdd[cp] += thisRound; somethingChanged = true; } } // check first whether there was a change at all // boolean firstTime = false; /* * int currentScale = oScale[start][end][pState]; int * childScale = oScale[start][end][cState]; if * (childScale==currentScale) { // already had a way to * generate this state and the scales are the same // -> * nothing to do } else { if * (childScale==Integer.MIN_VALUE){ // first time we can * build this state firstTime = true; childScale = * scaleArray(scoresToAdd,currentScale); * oScale[start][end][cState] = childScale; } else { // * scale the smaller one to the base of the bigger one * int newScale = Math.max(currentScale,childScale); * scaleArrayToScale(scoresToAdd,currentScale,newScale); * scaleArrayToScale * (oScore[start][end][cState],childScale,newScale); * oScale[start][end][cState] = newScale; } } */ if (somethingChanged) { for (int cp = 0; cp < nChildStates; cp++) { // if (true /*firstTime*/) // oScore[start][end][cState][cp] = // scoresToAdd[cp]; // else // if (scoresToAdd[cp] > 0) // oScore[start][end][cState][cp] += // scoresToAdd[cp]; if (scoresToAdd[cp] > initVal) { if (viterbi) oScorePostU[start][end][cState][cp] = Math .max(oScorePostU[start][end][cState][cp], scoresToAdd[cp]); else oScorePostU[start][end][cState][cp] += scoresToAdd[cp]; } } } } } // copy/add the entries where the unaries where not useful for (int cState = 0; cState < numSubStatesArray.length; cState++) { if (oScorePostU[start][end][cState] == null) continue; for (int cp = 0; cp < numSubStatesArray[cState]; cp++) { if (viterbi) oScorePostU[start][end][cState][cp] = Math.max( oScorePostU[start][end][cState][cp], oScorePreU[start][end][cState][cp]); else oScorePostU[start][end][cState][cp] += oScorePreU[start][end][cState][cp]; } } // do binaries for (int pState = 0; pState < numSubStatesArray.length; pState++) { if (oScorePostU[start][end][pState] == null) { continue; } final int nParentChildStates = numSubStatesArray[pState]; // if (!allowedStates[start][end][pState]) continue; BinaryRule[] rules = grammar.splitRulesWithP(pState); // BinaryRule[] rules = grammar.splitRulesWithLC(lState); for (int r = 0; r < rules.length; r++) { BinaryRule br = rules[r]; int lState = br.leftChildState; int min1 = narrowRExtent[start][lState]; if (end < min1) { continue; } int rState = br.rightChildState; int max1 = narrowLExtent[end][rState]; if (max1 < min1) { continue; } int min = min1; int max = max1; if (max - min > 2) { int min2 = wideLExtent[end][rState]; min = (min1 > min2 ? min1 : min2); if (max1 < min) { continue; } int max2 = wideRExtent[start][lState]; max = (max1 < max2 ? max1 : max2); if (max < min) { continue; } } double[][][] scores = br.getScores2(); int nLeftChildStates = numSubStatesArray[lState]; int nRightChildStates = numSubStatesArray[rState]; for (int split = min; split <= max; split++) { if (oScorePreU[start][split][lState] == null) continue; if (oScorePreU[split][end][rState] == null) continue; // if (!allowedStates[start][split][lState]) // continue; // if (!allowedStates[split][end][rState]) continue; double[] rightScores = new double[nRightChildStates]; Arrays.fill(scoresToAdd, initVal); Arrays.fill(rightScores, initVal); somethingChanged = false; for (int lp = 0; lp < nLeftChildStates; lp++) { double lS = iScorePostU[start][split][lState][lp]; if (lS == initVal) { continue; } // if // (!allowedSubStates[start][split][lState][lp]) // continue; for (int rp = 0; rp < nRightChildStates; rp++) { if (scores[lp][rp] == null) continue; double rS = iScorePostU[split][end][rState][rp]; if (rS == initVal) { continue; } // if // (!allowedSubStates[split][end][rState][rp]) // continue; for (int np = 0; np < nParentChildStates; np++) { double pS = scores[lp][rp][np]; if (pS == initVal) continue; double oS = oScorePostU[start][end][pState][np]; if (oS == initVal) continue; // if // (!allowedSubStates[start][end][pState][np]) // continue; double thisRoundL = (logScores) ? pS + rS + oS : pS * rS * oS; double thisRoundR = (logScores) ? pS + lS + oS : pS * lS * oS; if (viterbi) { scoresToAdd[lp] = Math .max(thisRoundL, scoresToAdd[lp]); rightScores[rp] = Math .max(thisRoundR, rightScores[rp]); } else { scoresToAdd[lp] += thisRoundL; rightScores[rp] += thisRoundR; } somethingChanged = true; } } } if (!somethingChanged) continue; /* * boolean firstTime = false; int leftScale = * oScale[start][split][lState]; int rightScale = * oScale[split][end][rState]; int parentScale = * oScale[start][end][pState]; int currentScale = * parentScale+iScale[split][end][rState]; if * (leftScale==currentScale) { // already had a way * to generate this state and the scales are the * same // -> nothing to do } else { if * (leftScale==Integer.MIN_VALUE){ // first time we * can build this state firstTime = true; leftScale * = scaleArray(scoresToAdd,currentScale); * oScale[start][split][lState] = leftScale; } else * { // scale the smaller one to the base of the * bigger one int newScale = * Math.max(currentScale,leftScale); * scaleArrayToScale * (scoresToAdd,currentScale,newScale); * scaleArrayToScale * (oScore[start][split][lState],leftScale * ,newScale); oScale[start][split][lState] = * newScale; } } */ for (int cp = 0; cp < nLeftChildStates; cp++) { // if (true /*firstTime*/) // oScore[start][split][lState][cp] = // scoresToAdd[cp]; if (scoresToAdd[cp] > initVal) { if (viterbi) oScorePreU[start][split][lState][cp] = Math .max(oScorePreU[start][split][lState][cp], scoresToAdd[cp]); else oScorePreU[start][split][lState][cp] += scoresToAdd[cp]; } } // oScale[start][split][lState] = currentScale; // oScale[start][split][lState] = // scaleArray(oScore[start][split][lState],oScale[start][split][lState]); // currentScale = // parentScale+iScale[start][split][lState]; /* * firstTime = false; if (rightScale==currentScale) * { // already had a way to generate this state and * the scales are the same // -> nothing to do } * else { if (rightScale==Integer.MIN_VALUE){ // * first time we can build this state firstTime = * true; rightScale = * scaleArray(rightScores,currentScale); * oScale[split][end][rState] = rightScale; } else { * // scale the smaller one to the base of the * bigger one int newScale = * Math.max(currentScale,rightScale); * scaleArrayToScale * (rightScores,currentScale,newScale); * scaleArrayToScale * (oScore[split][end][rState],rightScale,newScale); * oScale[split][end][rState] = newScale; } } */ for (int cp = 0; cp < nRightChildStates; cp++) { // if (true/*firstTime*/) // oScore[split][end][rState][cp] = // rightScores[cp]; // else if (rightScores[cp] > initVal) { if (viterbi) oScorePreU[split][end][rState][cp] = Math .max(oScorePreU[split][end][rState][cp], rightScores[cp]); else oScorePreU[split][end][rState][cp] += rightScores[cp]; } } // oScale[split][end][rState] = currentScale; // oScale[split][end][rState] = // scaleArray(oScore[split][end][rState],oScale[split][end][rState]); } } } } } } void initializeChart(List<String> sentence, Lexicon lexicon, boolean noSubstates, boolean noSmoothing) { int start = 0; int end = start + 1; for (String word : sentence) { end = start + 1; for (int tag = 0; tag < numSubStatesArray.length; tag++) { if (!noSubstates && allowedSubStates[start][end][tag] == null) continue; if (grammarTags[tag]) continue; // System.out.println("Initializing"); // if (dummy) allowedStates[start][end][tag] = true; narrowRExtent[start][tag] = end; narrowLExtent[end][tag] = start; wideRExtent[start][tag] = end; wideLExtent[end][tag] = start; double[] lexiconScores = lexicon.score(word, (short) tag, start, noSmoothing, false); // if (!logProbs) iScale[start][end][tag] = // scaleArray(lexiconScores,0); for (short n = 0; n < lexiconScores.length; n++) { double prob = lexiconScores[n]; if (noSubstates) viScore[start][end][tag] = prob; else iScorePreU[start][end][tag][n] = prob; } /* * if (start==1){ * System.out.println(word+" +TAG "+(String)tagNumberer * .object(tag)+" "+Arrays.toString(lexiconScores)); } */ } start++; } } @Override protected void createArrays(boolean firstTime, int numStates, short[] numSubStatesArray, int level, double initVal, boolean justInit) { // zero out some stuff first in case we recently ran out of memory and // are reallocating // spanMass = new double[length][length+1]; if (firstTime) { viScore = new double[length][length + 1][]; voScore = new double[length][length + 1][]; iScorePreU = new double[length][length + 1][][]; iScorePostU = new double[length][length + 1][][]; oScorePreU = new double[length][length + 1][][]; oScorePostU = new double[length][length + 1][][]; allowedSubStates = new boolean[length][length + 1][][]; allowedStates = new boolean[length][length + 1][]; vAllowedStates = new boolean[length][length + 1]; } for (int start = 0; start < length; start++) { for (int end = start + 1; end <= length; end++) { if (firstTime) { viScore[start][end] = new double[numStates]; voScore[start][end] = new double[numStates]; iScorePreU[start][end] = new double[numStates][]; iScorePostU[start][end] = new double[numStates][]; oScorePreU[start][end] = new double[numStates][]; oScorePostU[start][end] = new double[numStates][]; // iScale[start][end] = new int[numStates]; // oScale[start][end] = new int[numStates]; allowedSubStates[start][end] = new boolean[numStates][]; allowedStates[start][end] = grammarTags.clone(); if (level == 1 && (end - start == 1)) Arrays.fill(allowedStates[start][end], true); vAllowedStates[start][end] = true; } for (int state = 0; state < numSubStatesArray.length; state++) { if (allowedSubStates[start][end][state] != null) { if (level < 1) { viScore[start][end][state] = Double.NEGATIVE_INFINITY; voScore[start][end][state] = Double.NEGATIVE_INFINITY; } else { iScorePreU[start][end][state] = new double[numSubStatesArray[state]]; iScorePostU[start][end][state] = new double[numSubStatesArray[state]]; oScorePreU[start][end][state] = new double[numSubStatesArray[state]]; oScorePostU[start][end][state] = new double[numSubStatesArray[state]]; Arrays.fill(iScorePreU[start][end][state], initVal); Arrays.fill(iScorePostU[start][end][state], initVal); Arrays.fill(oScorePreU[start][end][state], initVal); Arrays.fill(oScorePostU[start][end][state], initVal); // Arrays.fill(iScale[start][end], // Integer.MIN_VALUE); // Arrays.fill(oScale[start][end], // Integer.MIN_VALUE); // boolean[] newAllowedSubStates = new // boolean[numSubStatesArray[state]]; // if (allowedSubStates[start][end][state]==null || // level<=1){ // Arrays.fill(newAllowedSubStates,true); // allowedSubStates[start][end][state] = // newAllowedSubStates; // } else{ // if (!justInit){ // // int[][] curLChildMap = lChildMap[level-2]; // // int[][] curRChildMap = rChildMap[level-2]; // // for (int i=0; // i<allowedSubStates[start][end][state].length; // i++){ // // boolean val = // allowedSubStates[start][end][state][i]; // // newAllowedSubStates[curLChildMap[state][i]] = // val; // // newAllowedSubStates[curRChildMap[state][i]] = // val; // // } // // allowedSubStates[start][end][state] = // newAllowedSubStates; // } // } } } else { if (level < 1) { viScore[start][end][state] = Double.NEGATIVE_INFINITY; voScore[start][end][state] = Double.NEGATIVE_INFINITY; } else { iScorePreU[start][end][state] = null; iScorePostU[start][end][state] = null; oScorePreU[start][end][state] = null; oScorePostU[start][end][state] = null; // allowedSubStates[start][end][state] = new // boolean[1]; // allowedSubStates[start][end][state][0] = false; } } } if (level > 0 && start == 0 && end == length) { if (iScorePostU[start][end][0] == null) System.out .println("ROOT does not span the entire tree!"); } } } narrowRExtent = new int[length + 1][numStates]; wideRExtent = new int[length + 1][numStates]; narrowLExtent = new int[length + 1][numStates]; wideLExtent = new int[length + 1][numStates]; for (int loc = 0; loc <= length; loc++) { Arrays.fill(narrowLExtent[loc], -1); // the rightmost left with // state s ending at i that // we can get is the // beginning Arrays.fill(wideLExtent[loc], length + 1); // the leftmost left with // state s ending at i // that we can get is // the end Arrays.fill(narrowRExtent[loc], length + 1); // the leftmost right // with state s // starting at i // that we can get // is the end Arrays.fill(wideRExtent[loc], -1); // the rightmost right with state // s starting at i that we can // get is the beginning } } @Override protected void clearArrays() { iScorePreU = iScorePostU = oScorePreU = oScorePostU = null; viScore = voScore = null; allowedSubStates = null; vAllowedStates = null; // iPossibleByL = iPossibleByR = oFilteredEnd = oFilteredStart = // oPossibleByL = oPossibleByR = tags = null; narrowRExtent = wideRExtent = narrowLExtent = wideLExtent = null; }
public void doPreParses(List<String> sentence, Tree<StateSet> tree,
2
2023-10-22 13:13:22+00:00
16k
neftalito/R-Info-Plus
arbol/Programa.java
[ { "identifier": "CodePanel", "path": "form/CodePanel.java", "snippet": "public class CodePanel extends JPanel{\n private JToolBar toolBar;\n public MyTextPane text;\n Ciudad city;\n MonitorActualizarVentana esperarRefresco;\n private JButton saveButton;\n private JButton newButton;\n ...
import form.CodePanel; import form.Ciudad; import form.Robot;
14,003
package arbol; public class Programa extends AST { Identificador I; DeclaracionRobots DR; DeclaracionProcesos DP; DeclaracionVariable DV; DeclaracionAreas DA; Cuerpo C;
package arbol; public class Programa extends AST { Identificador I; DeclaracionRobots DR; DeclaracionProcesos DP; DeclaracionVariable DV; DeclaracionAreas DA; Cuerpo C;
Robot R;
2
2023-10-20 15:45:37+00:00
16k
UnityFoundation-io/Libre311
app/src/main/java/app/RootController.java
[ { "identifier": "DiscoveryDTO", "path": "app/src/main/java/app/dto/discovery/DiscoveryDTO.java", "snippet": "@Introspected\n@JsonRootName(\"discovery\")\npublic class DiscoveryDTO {\n\n private String changeset;\n private String contact;\n\n @JsonProperty(\"key_service\")\n private String ke...
import app.dto.discovery.DiscoveryDTO; import app.dto.download.DownloadRequestsArgumentsDTO; import app.dto.service.ServiceDTO; import app.dto.service.ServiceList; import app.dto.servicerequest.*; import app.model.service.servicedefinition.ServiceDefinition; import app.service.discovery.DiscoveryEndpointService; import app.service.jurisdiction.JurisdictionService; import app.service.service.ServiceService; import app.service.servicerequest.ServiceRequestService; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.google.common.xml.XmlEscapers; import io.micronaut.core.annotation.Nullable; import io.micronaut.data.model.Page; import io.micronaut.data.model.Pageable; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; import io.micronaut.http.MediaType; import io.micronaut.http.annotation.*; import io.micronaut.http.server.types.files.StreamedFile; import io.micronaut.scheduling.TaskExecutors; import io.micronaut.scheduling.annotation.ExecuteOn; import io.micronaut.security.annotation.Secured; import io.micronaut.security.rules.SecurityRule; import javax.validation.Valid; import java.net.MalformedURLException; import java.util.List; import java.util.Map;
11,178
XmlMapper xmlMapper = XmlMapper.xmlBuilder().build(); ObjectMapper objectMapper = new ObjectMapper(); String serviceDefinitionStr = serviceService.getServiceDefinition(serviceCode, jurisdiction_id); ServiceDefinition serviceDefinition = objectMapper.readValue(serviceDefinitionStr, ServiceDefinition.class); return xmlMapper.writeValueAsString(serviceDefinition); } @Post(uris = {"/requests", "/requests.json"}) @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @ExecuteOn(TaskExecutors.IO) public List<PostResponseServiceRequestDTO> createServiceRequestJson(HttpRequest<?> request, @Valid @Body PostRequestServiceRequestDTO requestDTO) { List<Map> errors = jurisdictionService.validateJurisdictionSupport(requestDTO.getJurisdictionId()); if (!errors.isEmpty()) { return null; } return List.of(serviceRequestService.createServiceRequest(request, requestDTO)); } @Post("/requests.xml") @Produces(MediaType.TEXT_XML) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @ExecuteOn(TaskExecutors.IO) public String createServiceRequestXml(HttpRequest<?> request, @Valid @Body PostRequestServiceRequestDTO requestDTO) throws JsonProcessingException { List<Map> errors = jurisdictionService.validateJurisdictionSupport(requestDTO.getJurisdictionId()); if (!errors.isEmpty()) { return null; } XmlMapper xmlMapper = XmlMapper.xmlBuilder().defaultUseWrapper(false).build(); ServiceRequestList serviceRequestList = new ServiceRequestList(List.of(serviceRequestService.createServiceRequest(request, requestDTO))); return xmlMapper.writeValueAsString(serviceRequestList); } @Get(uris = {"/requests", "/requests.json"}) @Produces(MediaType.APPLICATION_JSON) @ExecuteOn(TaskExecutors.IO) public HttpResponse<List<ServiceRequestDTO>> getServiceRequestsJson(@Valid @RequestBean GetServiceRequestsDTO requestDTO) { List<Map> errors = jurisdictionService.validateJurisdictionSupport(requestDTO.getJurisdictionId()); if (!errors.isEmpty()) { return null; } Page<ServiceRequestDTO> serviceRequestDTOPage = serviceRequestService.findAll(requestDTO); return HttpResponse.ok(serviceRequestDTOPage.getContent()) .headers(Map.of( "Access-Control-Expose-Headers", "page-TotalSize, page-TotalPages, page-PageNumber, page-Offset, page-Size ", "page-TotalSize", String.valueOf(serviceRequestDTOPage.getTotalSize()), "page-TotalPages", String.valueOf(serviceRequestDTOPage.getTotalPages()), "page-PageNumber", String.valueOf(serviceRequestDTOPage.getPageNumber()), "page-Offset", String.valueOf(serviceRequestDTOPage.getOffset()), "page-Size", String.valueOf(serviceRequestDTOPage.getSize()) )); } @Get("/requests.xml") @Produces(MediaType.TEXT_XML) @ExecuteOn(TaskExecutors.IO) public HttpResponse<String> getServiceRequestsXml(@Valid @RequestBean GetServiceRequestsDTO requestDTO) throws JsonProcessingException { List<Map> errors = jurisdictionService.validateJurisdictionSupport(requestDTO.getJurisdictionId()); if (!errors.isEmpty()) { return null; } XmlMapper xmlMapper = XmlMapper.xmlBuilder().defaultUseWrapper(false).build(); xmlMapper.registerModule(new JavaTimeModule()); Page<ServiceRequestDTO> serviceRequestDTOPage = serviceRequestService.findAll(requestDTO) .map(serviceRequestDTO -> { sanitizeXmlContent(serviceRequestDTO); return serviceRequestDTO; });; ServiceRequestList serviceRequestList = new ServiceRequestList(serviceRequestDTOPage.getContent()); return HttpResponse.ok(xmlMapper.writeValueAsString(serviceRequestList)) .headers(Map.of( "Access-Control-Expose-Headers", "page-TotalSize, page-TotalPages, page-PageNumber, page-Offset, page-Size ", "page-TotalSize", String.valueOf(serviceRequestDTOPage.getTotalSize()), "page-TotalPages", String.valueOf(serviceRequestDTOPage.getTotalPages()), "page-PageNumber", String.valueOf(serviceRequestDTOPage.getPageNumber()), "page-Offset", String.valueOf(serviceRequestDTOPage.getOffset()), "page-Size", String.valueOf(serviceRequestDTOPage.getSize()) )); } @Get(uris = {"/requests/{serviceRequestId}{?jurisdiction_id}", "/requests/{serviceRequestId}.json{?jurisdiction_id}"}) @Produces(MediaType.APPLICATION_JSON) @ExecuteOn(TaskExecutors.IO) public List<ServiceRequestDTO> getServiceRequestJson(Long serviceRequestId, @Nullable String jurisdiction_id) { List<Map> errors = jurisdictionService.validateJurisdictionSupport(jurisdiction_id); if (!errors.isEmpty()) { return null; } return List.of(serviceRequestService.getServiceRequest(serviceRequestId, jurisdiction_id)); } @Get("/requests/{serviceRequestId}.xml{?jurisdiction_id}") @Produces(MediaType.TEXT_XML) @ExecuteOn(TaskExecutors.IO) public String getServiceRequestXml(Long serviceRequestId, @Nullable String jurisdiction_id) throws JsonProcessingException { List<Map> errors = jurisdictionService.validateJurisdictionSupport(jurisdiction_id); if (!errors.isEmpty()) { return null; } XmlMapper xmlMapper = XmlMapper.xmlBuilder().defaultUseWrapper(false).build(); xmlMapper.registerModule(new JavaTimeModule()); ServiceRequestDTO serviceRequestDTO = serviceRequestService.getServiceRequest(serviceRequestId, jurisdiction_id); sanitizeXmlContent(serviceRequestDTO); ServiceRequestList serviceRequestList = new ServiceRequestList(List.of(serviceRequestDTO)); return xmlMapper.writeValueAsString(serviceRequestList); } @Get(value = "/requests/download") @Secured(SecurityRule.IS_AUTHENTICATED) @ExecuteOn(TaskExecutors.IO)
// Copyright 2023 Libre311 Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package app; @Controller("/api") @Secured(SecurityRule.IS_ANONYMOUS) public class RootController { private final ServiceService serviceService; private final ServiceRequestService serviceRequestService; private final DiscoveryEndpointService discoveryEndpointService; private final JurisdictionService jurisdictionService; public RootController(ServiceService serviceService, ServiceRequestService serviceRequestService, DiscoveryEndpointService discoveryEndpointService, JurisdictionService jurisdictionService) { this.serviceService = serviceService; this.serviceRequestService = serviceRequestService; this.jurisdictionService = jurisdictionService; this.discoveryEndpointService = discoveryEndpointService; } @Get(uris = {"/discovery", "/discovery.json"}) @Produces(MediaType.APPLICATION_JSON) @ExecuteOn(TaskExecutors.IO) public HttpResponse<DiscoveryDTO> discoveryJson() { return HttpResponse.ok(discoveryEndpointService.getDiscoveryInfo()); } @Get("/discovery.xml") @Produces(MediaType.TEXT_XML) @ExecuteOn(TaskExecutors.IO) public HttpResponse<String> discoveryXml() throws JsonProcessingException { XmlMapper xmlMapper = XmlMapper.xmlBuilder() .configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true) .defaultUseWrapper(true).build(); DiscoveryDTO discovery = discoveryEndpointService.getDiscoveryInfo(); return HttpResponse.ok(xmlMapper.writeValueAsString(discovery)); } @Get(uris = {"/services{?jurisdiction_id}", "/services.json{?jurisdiction_id}"}) @Produces(MediaType.APPLICATION_JSON) @ExecuteOn(TaskExecutors.IO) public HttpResponse<List<ServiceDTO>> indexJson(@Valid Pageable pageable, @Nullable String jurisdiction_id) { List<Map> errors = jurisdictionService.validateJurisdictionSupport(jurisdiction_id); if (!errors.isEmpty()) { return null; } Page<ServiceDTO> serviceDTOPage = serviceService.findAll(pageable, jurisdiction_id); return HttpResponse.ok(serviceDTOPage.getContent()) .headers(Map.of( "Access-Control-Expose-Headers", "page-TotalSize, page-TotalPages, page-PageNumber, page-Offset, page-Size ", "page-TotalSize", String.valueOf(serviceDTOPage.getTotalSize()), "page-TotalPages", String.valueOf(serviceDTOPage.getTotalPages()), "page-PageNumber", String.valueOf(serviceDTOPage.getPageNumber()), "page-Offset", String.valueOf(serviceDTOPage.getOffset()), "page-Size", String.valueOf(serviceDTOPage.getSize()) )); } @Get("/services.xml{?jurisdiction_id}") @Produces(MediaType.TEXT_XML) @ExecuteOn(TaskExecutors.IO) public HttpResponse<String> indexXml(@Valid Pageable pageable, @Nullable String jurisdiction_id) throws JsonProcessingException { List<Map> errors = jurisdictionService.validateJurisdictionSupport(jurisdiction_id); if (!errors.isEmpty()) { return null; } XmlMapper xmlMapper = XmlMapper.xmlBuilder().defaultUseWrapper(false).build(); Page<ServiceDTO> serviceDTOPage = serviceService.findAll(pageable, jurisdiction_id) .map(serviceDTO -> { if (serviceDTO.getDescription() != null) { serviceDTO.setDescription(XmlEscapers.xmlContentEscaper().escape(serviceDTO.getDescription())); } return serviceDTO; }); ServiceList serviceList = new ServiceList(serviceDTOPage.getContent()); return HttpResponse.ok(xmlMapper.writeValueAsString(serviceList)) .headers(Map.of( "Access-Control-Expose-Headers", "page-TotalSize, page-TotalPages, page-PageNumber, page-Offset, page-Size ", "page-TotalSize", String.valueOf(serviceDTOPage.getTotalSize()), "page-TotalPages", String.valueOf(serviceDTOPage.getTotalPages()), "page-PageNumber", String.valueOf(serviceDTOPage.getPageNumber()), "page-Offset", String.valueOf(serviceDTOPage.getOffset()), "page-Size", String.valueOf(serviceDTOPage.getSize()) )); } @Get(uris = {"/services/{serviceCode}{?jurisdiction_id}", "/services/{serviceCode}.json{?jurisdiction_id}"}) @Produces(MediaType.APPLICATION_JSON) @ExecuteOn(TaskExecutors.IO) public String getServiceDefinitionJson(String serviceCode, @Nullable String jurisdiction_id) { List<Map> errors = jurisdictionService.validateJurisdictionSupport(jurisdiction_id); if (!errors.isEmpty()) { return null; } return serviceService.getServiceDefinition(serviceCode, jurisdiction_id); } @Get("/services/{serviceCode}.xml{?jurisdiction_id}") @Produces(MediaType.TEXT_XML) @ExecuteOn(TaskExecutors.IO) public String getServiceDefinitionXml(String serviceCode, @Nullable String jurisdiction_id) throws JsonProcessingException { List<Map> errors = jurisdictionService.validateJurisdictionSupport(jurisdiction_id); if (!errors.isEmpty()) { return null; } XmlMapper xmlMapper = XmlMapper.xmlBuilder().build(); ObjectMapper objectMapper = new ObjectMapper(); String serviceDefinitionStr = serviceService.getServiceDefinition(serviceCode, jurisdiction_id); ServiceDefinition serviceDefinition = objectMapper.readValue(serviceDefinitionStr, ServiceDefinition.class); return xmlMapper.writeValueAsString(serviceDefinition); } @Post(uris = {"/requests", "/requests.json"}) @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @ExecuteOn(TaskExecutors.IO) public List<PostResponseServiceRequestDTO> createServiceRequestJson(HttpRequest<?> request, @Valid @Body PostRequestServiceRequestDTO requestDTO) { List<Map> errors = jurisdictionService.validateJurisdictionSupport(requestDTO.getJurisdictionId()); if (!errors.isEmpty()) { return null; } return List.of(serviceRequestService.createServiceRequest(request, requestDTO)); } @Post("/requests.xml") @Produces(MediaType.TEXT_XML) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @ExecuteOn(TaskExecutors.IO) public String createServiceRequestXml(HttpRequest<?> request, @Valid @Body PostRequestServiceRequestDTO requestDTO) throws JsonProcessingException { List<Map> errors = jurisdictionService.validateJurisdictionSupport(requestDTO.getJurisdictionId()); if (!errors.isEmpty()) { return null; } XmlMapper xmlMapper = XmlMapper.xmlBuilder().defaultUseWrapper(false).build(); ServiceRequestList serviceRequestList = new ServiceRequestList(List.of(serviceRequestService.createServiceRequest(request, requestDTO))); return xmlMapper.writeValueAsString(serviceRequestList); } @Get(uris = {"/requests", "/requests.json"}) @Produces(MediaType.APPLICATION_JSON) @ExecuteOn(TaskExecutors.IO) public HttpResponse<List<ServiceRequestDTO>> getServiceRequestsJson(@Valid @RequestBean GetServiceRequestsDTO requestDTO) { List<Map> errors = jurisdictionService.validateJurisdictionSupport(requestDTO.getJurisdictionId()); if (!errors.isEmpty()) { return null; } Page<ServiceRequestDTO> serviceRequestDTOPage = serviceRequestService.findAll(requestDTO); return HttpResponse.ok(serviceRequestDTOPage.getContent()) .headers(Map.of( "Access-Control-Expose-Headers", "page-TotalSize, page-TotalPages, page-PageNumber, page-Offset, page-Size ", "page-TotalSize", String.valueOf(serviceRequestDTOPage.getTotalSize()), "page-TotalPages", String.valueOf(serviceRequestDTOPage.getTotalPages()), "page-PageNumber", String.valueOf(serviceRequestDTOPage.getPageNumber()), "page-Offset", String.valueOf(serviceRequestDTOPage.getOffset()), "page-Size", String.valueOf(serviceRequestDTOPage.getSize()) )); } @Get("/requests.xml") @Produces(MediaType.TEXT_XML) @ExecuteOn(TaskExecutors.IO) public HttpResponse<String> getServiceRequestsXml(@Valid @RequestBean GetServiceRequestsDTO requestDTO) throws JsonProcessingException { List<Map> errors = jurisdictionService.validateJurisdictionSupport(requestDTO.getJurisdictionId()); if (!errors.isEmpty()) { return null; } XmlMapper xmlMapper = XmlMapper.xmlBuilder().defaultUseWrapper(false).build(); xmlMapper.registerModule(new JavaTimeModule()); Page<ServiceRequestDTO> serviceRequestDTOPage = serviceRequestService.findAll(requestDTO) .map(serviceRequestDTO -> { sanitizeXmlContent(serviceRequestDTO); return serviceRequestDTO; });; ServiceRequestList serviceRequestList = new ServiceRequestList(serviceRequestDTOPage.getContent()); return HttpResponse.ok(xmlMapper.writeValueAsString(serviceRequestList)) .headers(Map.of( "Access-Control-Expose-Headers", "page-TotalSize, page-TotalPages, page-PageNumber, page-Offset, page-Size ", "page-TotalSize", String.valueOf(serviceRequestDTOPage.getTotalSize()), "page-TotalPages", String.valueOf(serviceRequestDTOPage.getTotalPages()), "page-PageNumber", String.valueOf(serviceRequestDTOPage.getPageNumber()), "page-Offset", String.valueOf(serviceRequestDTOPage.getOffset()), "page-Size", String.valueOf(serviceRequestDTOPage.getSize()) )); } @Get(uris = {"/requests/{serviceRequestId}{?jurisdiction_id}", "/requests/{serviceRequestId}.json{?jurisdiction_id}"}) @Produces(MediaType.APPLICATION_JSON) @ExecuteOn(TaskExecutors.IO) public List<ServiceRequestDTO> getServiceRequestJson(Long serviceRequestId, @Nullable String jurisdiction_id) { List<Map> errors = jurisdictionService.validateJurisdictionSupport(jurisdiction_id); if (!errors.isEmpty()) { return null; } return List.of(serviceRequestService.getServiceRequest(serviceRequestId, jurisdiction_id)); } @Get("/requests/{serviceRequestId}.xml{?jurisdiction_id}") @Produces(MediaType.TEXT_XML) @ExecuteOn(TaskExecutors.IO) public String getServiceRequestXml(Long serviceRequestId, @Nullable String jurisdiction_id) throws JsonProcessingException { List<Map> errors = jurisdictionService.validateJurisdictionSupport(jurisdiction_id); if (!errors.isEmpty()) { return null; } XmlMapper xmlMapper = XmlMapper.xmlBuilder().defaultUseWrapper(false).build(); xmlMapper.registerModule(new JavaTimeModule()); ServiceRequestDTO serviceRequestDTO = serviceRequestService.getServiceRequest(serviceRequestId, jurisdiction_id); sanitizeXmlContent(serviceRequestDTO); ServiceRequestList serviceRequestList = new ServiceRequestList(List.of(serviceRequestDTO)); return xmlMapper.writeValueAsString(serviceRequestList); } @Get(value = "/requests/download") @Secured(SecurityRule.IS_AUTHENTICATED) @ExecuteOn(TaskExecutors.IO)
public StreamedFile downloadServiceRequests(@Valid @RequestBean DownloadRequestsArgumentsDTO requestDTO) throws MalformedURLException {
1
2023-10-18 15:37:36+00:00
16k
JonnyOnlineYT/xenza
src/minecraft/net/minecraft/client/renderer/entity/RenderEnderman.java
[ { "identifier": "Material", "path": "src/minecraft/net/minecraft/block/material/Material.java", "snippet": "public class Material\n{\n public static final Material air = new MaterialTransparent(MapColor.airColor);\n public static final Material grass = new Material(MapColor.grassColor);\n publi...
import java.util.Random; import net.minecraft.block.material.Material; import net.minecraft.client.model.ModelEnderman; import net.minecraft.client.renderer.entity.layers.LayerEndermanEyes; import net.minecraft.client.renderer.entity.layers.LayerHeldBlock; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.util.ResourceLocation;
10,875
package net.minecraft.client.renderer.entity; public class RenderEnderman extends RenderLiving<EntityEnderman> { private static final ResourceLocation endermanTextures = new ResourceLocation("textures/entity/enderman/enderman.png");
package net.minecraft.client.renderer.entity; public class RenderEnderman extends RenderLiving<EntityEnderman> { private static final ResourceLocation endermanTextures = new ResourceLocation("textures/entity/enderman/enderman.png");
private ModelEnderman endermanModel;
1
2023-10-15 00:21:15+00:00
16k
LeGhast/Miniaturise
src/main/java/de/leghast/miniaturise/command/SelectCommand.java
[ { "identifier": "Miniaturise", "path": "src/main/java/de/leghast/miniaturise/Miniaturise.java", "snippet": "public final class Miniaturise extends JavaPlugin {\n\n private MiniatureManager miniatureManager;\n private RegionManager regionManager;\n private SettingsManager settingsManager;\n\n ...
import de.leghast.miniaturise.Miniaturise; import de.leghast.miniaturise.instance.miniature.Miniature; import de.leghast.miniaturise.instance.miniature.PlacedMiniature; import de.leghast.miniaturise.instance.region.Region; import de.leghast.miniaturise.manager.ConfigManager; import de.leghast.miniaturise.util.Util; import org.bukkit.Chunk; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.BlockDisplay; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List;
10,828
package de.leghast.miniaturise.command; public class SelectCommand implements CommandExecutor { private Miniaturise main; public SelectCommand(Miniaturise main){ this.main = main; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) { if(sender instanceof Player player){ if(player.hasPermission("miniaturise.use")){ if(main.getRegionManager().hasSelectedLocations(player.getUniqueId())){ if(main.getRegionManager().getSelectedLocations(player.getUniqueId()).isValid()){ try{ Region region = new Region(main.getRegionManager().getSelectedLocations(player.getUniqueId())); if(main.getRegionManager().hasRegion(player.getUniqueId())) { main.getRegionManager().getRegions().replace(player.getUniqueId(), region); }else{ main.getRegionManager().addRegion(player.getUniqueId(), region); } Miniature miniature = new Miniature(region, player.getLocation(), ConfigManager.getDefaultSize()); if(miniature.getBlocks().size() >= ConfigManager.getMaxEntityLimit()){
package de.leghast.miniaturise.command; public class SelectCommand implements CommandExecutor { private Miniaturise main; public SelectCommand(Miniaturise main){ this.main = main; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) { if(sender instanceof Player player){ if(player.hasPermission("miniaturise.use")){ if(main.getRegionManager().hasSelectedLocations(player.getUniqueId())){ if(main.getRegionManager().getSelectedLocations(player.getUniqueId()).isValid()){ try{ Region region = new Region(main.getRegionManager().getSelectedLocations(player.getUniqueId())); if(main.getRegionManager().hasRegion(player.getUniqueId())) { main.getRegionManager().getRegions().replace(player.getUniqueId(), region); }else{ main.getRegionManager().addRegion(player.getUniqueId(), region); } Miniature miniature = new Miniature(region, player.getLocation(), ConfigManager.getDefaultSize()); if(miniature.getBlocks().size() >= ConfigManager.getMaxEntityLimit()){
player.sendMessage(Util.PREFIX + "§cThe current selection §e(" + miniature.getBlocks().size() +
5
2023-10-15 09:08:33+00:00
16k
instrumental-id/iiq-common-public
src/com/identityworksllc/iiq/common/table/QueryTable.java
[ { "identifier": "ColumnConfig", "path": "src/com/identityworksllc/iiq/common/iterators/ColumnConfig.java", "snippet": "public final class ColumnConfig {\n\n /**\n * The error returned if the input to the constructor is wrong\n */\n private static final String BAD_INPUT_ERROR = \"Input must...
import com.identityworksllc.iiq.common.iterators.ColumnConfig; import com.identityworksllc.iiq.common.iterators.ResultSetIterator; import com.identityworksllc.iiq.common.query.NamedParameterStatement; import sailpoint.api.SailPointContext; import sailpoint.tools.GeneralException; import sailpoint.tools.JdbcUtil; import sailpoint.tools.Util; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean;
12,696
package com.identityworksllc.iiq.common.table; /** * An extension of Table to run a SQL query and export it. You must provide a * Connection (or way of getting one) and a list of column specs. * * The meat of the querying takes place in {@link ResultSetIterator}. */ public class QueryTable implements AutoCloseable, StyleTarget { /** * The column specs, recognized by {@link ColumnConfig}. At this * time that is Strings, other ColumnConfig objects (which will be cloned), or * ReportColumnConfig objects. */ private final List<Object> columns; /** * The connection, which is assumed open until close() is invoked */ private final Connection connection; /** * The context */ private final SailPointContext context; /** * Set to true on render() */ private final AtomicBoolean frozen; /** * The Table to be populated by the query output */ private final Table table; /** * Constructs a n ew QueryTable with the given context, connection, and column * specifications. The column specs should be some object recognized by * the reporting class {@link ColumnConfig}. * * @param context The context * @param connection The SQL connection, which must be open and ready to query * @param columns A non-empty list of column specs */ public QueryTable(SailPointContext context, Connection connection, List<Object> columns) { this.connection = Objects.requireNonNull(connection); this.context = Objects.requireNonNull(context); if (columns == null || columns.isEmpty()) { throw new IllegalArgumentException("For QueryTable, 'columns' must contain at least one column specification"); } this.table = new Table(); this.columns = new ArrayList<>(columns); this.frozen = new AtomicBoolean(); } /** * Constructs a new QueryTable with the given context and connection, as well * as a string list of column tokens. * * @param context The context * @param connection The SQL connection, which must be open and ready to query * @param columns A non-empty list of column tokens */ public QueryTable(SailPointContext context, Connection connection, String... columns) { this(context, connection, Arrays.asList(columns)); } /** * Constructs a new QueryTable with the given context and connection info, as well * as a string list of column tokens. * * @param context The context * @param connectionInfo A map of connection info, with the same keys specified by connectors * @param columns A non-empty list of column tokens */ public QueryTable(SailPointContext context, Map<String, Object> connectionInfo, String... columns) throws GeneralException { this(context, JdbcUtil.getConnection(connectionInfo), columns); } /** * Constructs a new QueryTable with the given context and connection info, as well * as a string list of column tokens. * * @param context The context * @param connectionInfo A map of connection info, with the same keys specified by connectors * @param columns A non-empty list of column specs */ public QueryTable(SailPointContext context, Map<String, Object> connectionInfo, List<Object> columns) throws GeneralException { this(context, JdbcUtil.getConnection(connectionInfo), columns); } /** * Adds an output column to this QueryTable * * @param columnConfig The column config * @return This object, for call chaining */ public QueryTable addColumn(Object columnConfig) { if (columnConfig != null) { this.columns.add(columnConfig); } return this; } /** * Closes the connection * * @throws SQLException on failure to close the connection */ @Override public void close() throws SQLException { if (this.connection != null) { this.connection.close(); } } /** * Executes the given query with the given options. The query will be run * via {@link NamedParameterStatement}, so the arguments must be of a type * recognized by that class. * * @param queryString The query string, which must not be null or empty * @param arguments The list of arguments, if any * @return This object, for call chaining * @throws SQLException if any SQL failures occur * @throws GeneralException if any IIQ failures occur */ public QueryTable executeQuery(String queryString, Map<String, Object> arguments) throws SQLException, GeneralException { if (this.frozen.get()) { throw new IllegalArgumentException("QueryTable.executeQuery() cannot be invoked twice for the same table"); } if (Util.isNullOrEmpty(queryString)) { throw new IllegalArgumentException("The query passed to executeQuery() must not be null"); }
package com.identityworksllc.iiq.common.table; /** * An extension of Table to run a SQL query and export it. You must provide a * Connection (or way of getting one) and a list of column specs. * * The meat of the querying takes place in {@link ResultSetIterator}. */ public class QueryTable implements AutoCloseable, StyleTarget { /** * The column specs, recognized by {@link ColumnConfig}. At this * time that is Strings, other ColumnConfig objects (which will be cloned), or * ReportColumnConfig objects. */ private final List<Object> columns; /** * The connection, which is assumed open until close() is invoked */ private final Connection connection; /** * The context */ private final SailPointContext context; /** * Set to true on render() */ private final AtomicBoolean frozen; /** * The Table to be populated by the query output */ private final Table table; /** * Constructs a n ew QueryTable with the given context, connection, and column * specifications. The column specs should be some object recognized by * the reporting class {@link ColumnConfig}. * * @param context The context * @param connection The SQL connection, which must be open and ready to query * @param columns A non-empty list of column specs */ public QueryTable(SailPointContext context, Connection connection, List<Object> columns) { this.connection = Objects.requireNonNull(connection); this.context = Objects.requireNonNull(context); if (columns == null || columns.isEmpty()) { throw new IllegalArgumentException("For QueryTable, 'columns' must contain at least one column specification"); } this.table = new Table(); this.columns = new ArrayList<>(columns); this.frozen = new AtomicBoolean(); } /** * Constructs a new QueryTable with the given context and connection, as well * as a string list of column tokens. * * @param context The context * @param connection The SQL connection, which must be open and ready to query * @param columns A non-empty list of column tokens */ public QueryTable(SailPointContext context, Connection connection, String... columns) { this(context, connection, Arrays.asList(columns)); } /** * Constructs a new QueryTable with the given context and connection info, as well * as a string list of column tokens. * * @param context The context * @param connectionInfo A map of connection info, with the same keys specified by connectors * @param columns A non-empty list of column tokens */ public QueryTable(SailPointContext context, Map<String, Object> connectionInfo, String... columns) throws GeneralException { this(context, JdbcUtil.getConnection(connectionInfo), columns); } /** * Constructs a new QueryTable with the given context and connection info, as well * as a string list of column tokens. * * @param context The context * @param connectionInfo A map of connection info, with the same keys specified by connectors * @param columns A non-empty list of column specs */ public QueryTable(SailPointContext context, Map<String, Object> connectionInfo, List<Object> columns) throws GeneralException { this(context, JdbcUtil.getConnection(connectionInfo), columns); } /** * Adds an output column to this QueryTable * * @param columnConfig The column config * @return This object, for call chaining */ public QueryTable addColumn(Object columnConfig) { if (columnConfig != null) { this.columns.add(columnConfig); } return this; } /** * Closes the connection * * @throws SQLException on failure to close the connection */ @Override public void close() throws SQLException { if (this.connection != null) { this.connection.close(); } } /** * Executes the given query with the given options. The query will be run * via {@link NamedParameterStatement}, so the arguments must be of a type * recognized by that class. * * @param queryString The query string, which must not be null or empty * @param arguments The list of arguments, if any * @return This object, for call chaining * @throws SQLException if any SQL failures occur * @throws GeneralException if any IIQ failures occur */ public QueryTable executeQuery(String queryString, Map<String, Object> arguments) throws SQLException, GeneralException { if (this.frozen.get()) { throw new IllegalArgumentException("QueryTable.executeQuery() cannot be invoked twice for the same table"); } if (Util.isNullOrEmpty(queryString)) { throw new IllegalArgumentException("The query passed to executeQuery() must not be null"); }
try (NamedParameterStatement statement = new NamedParameterStatement(connection, queryString)) {
2
2023-10-20 15:20:16+00:00
16k
mosaic-addons/traffic-state-estimation
src/main/java/com/dcaiti/mosaic/app/tse/processors/ThresholdProcessor.java
[ { "identifier": "FcdRecord", "path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FcdRecord.java", "snippet": "public class FcdRecord extends FxdRecord {\n\n /**\n * List of vehicles perceived during the collection of FCD in the form of {@link VehicleObject VehicleObjects}.\n */\n private...
import com.dcaiti.mosaic.app.fxd.data.FcdRecord; import com.dcaiti.mosaic.app.fxd.messages.FcdUpdateMessage; import com.dcaiti.mosaic.app.tse.config.CTseServerApp; import com.dcaiti.mosaic.app.tse.data.DatabaseAccess; import com.dcaiti.mosaic.app.tse.persistence.FcdDataStorage; import com.dcaiti.mosaic.app.tse.persistence.FcdDatabaseHelper; import com.dcaiti.mosaic.app.tse.persistence.ScenarioDatabaseHelper; import org.eclipse.mosaic.lib.database.Database; import org.eclipse.mosaic.lib.util.gson.TimeFieldAdapter; import org.eclipse.mosaic.rti.TIME; import com.google.common.math.Quantiles; import com.google.gson.annotations.JsonAdapter; import org.apache.commons.math3.util.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
11,235
/* * Copyright (c) 2021 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: mosaic@fokus.fraunhofer.de */ package com.dcaiti.mosaic.app.tse.processors; /** * This class is used to compute the thresholds needed to compute the relative traffic metric. * * @see SpatioTemporalProcessor * @see SpatioTemporalTrafficMetric * @see FcdDatabaseHelper */ public class ThresholdProcessor extends TimeBasedProcessor<FcdRecord, FcdUpdateMessage> implements DatabaseAccess { private final static String IDENTIFIER = createIdentifier(ThresholdProcessor.class); public static final int MIN_RECORDED_TRAVERSALS_FOR_TL_HEURISTIC = 10; public static final int MAX_RECORDED_TRAVERSAL_FOR_TL_HEURISTIC = 400; // === CONFIG === /** * As an estimation of the RedPhase, this value will be applied to connections with * a significant difference in travel times close to the estimated duration. */ @JsonAdapter(TimeFieldAdapter.NanoSeconds.class) public long defaultRedLightDuration = 45 * TIME.SECOND; /** * Thresholds will only be computed and used for RTSM, if the number of samples in the past is larger than this. */ public int minTraversalsForThreshold = 10; /** * If true, the relative traffic metrics will be recomputed every time the thresholds are recomputed. * This may take long, as there can be a lot of traversals. */ public boolean recomputeAllRtsmWithNewThresholds = false; // === CONFIG === /** * Mosaic scenario database, holding data regarding the road network. */ private Database networkDatabase; /** * Gives access to the FcdDatabase. */ private FcdDataStorage fcdDataStorage; /** * Holds estimated red light durations. */ private final Map<String, Long> redLightDurations = new HashMap<>(); @Override public String getIdentifier() { return IDENTIFIER; } @Override public void withDataStorage(Database networkDatabase, FcdDataStorage fcdDataStorage) { this.networkDatabase = networkDatabase; this.fcdDataStorage = fcdDataStorage; } @Override public void triggerEvent(long eventTime) { long start = System.currentTimeMillis(); computeThresholds(eventTime); long duration = (System.currentTimeMillis() - start); logThresholdComputation(eventTime, duration * TIME.MILLI_SECOND); if (recomputeAllRtsmWithNewThresholds) { calculateRtsm(); } } /** * Computes thresholds using current data from DB and inserting them to thresholds table. * Uses Google Guava for percentiles. * * @param simulationTime Time at which the threshold computation started. Needed for further analysis of the resulting data. * @see <a href="https://github.com/google/guava">Google Guava on GitHub</a> * @see <a href="https://github.com/google/guava/blob/master/guava/src/com/google/common/math/Quantiles.java">Guava Quantiles</a> */ private void computeThresholds(long simulationTime) { if (triggerInterval <= 0) { return; } Map<String, Double> temporalThresholds = computeTemporalThresholds(); Map<String, Double> spatialThresholds = computeSpatialThresholds(temporalThresholds); // handle the possibility of no spatial Threshold, as percentile is above temporal threshold if (temporalThresholds.size() != spatialThresholds.size()) { ArrayList<String> notInBoth = new ArrayList<>(); temporalThresholds.forEach((connection, temporalThreshold) -> { if (!spatialThresholds.containsKey(connection)) { notInBoth.add(connection); } }); spatialThresholds.forEach((connection, temporalThreshold) -> { if (!temporalThresholds.containsKey(connection)) { notInBoth.add(connection); } }); notInBoth.forEach(connection -> { spatialThresholds.remove(connection); temporalThresholds.remove(connection); }); } fcdDataStorage.insertThresholds(temporalThresholds, spatialThresholds, simulationTime); } /** * Temporal threshold as done by Yoon et al. with 5% of 5th percentile as red light duration. * Does so only if more than {@link #minTraversalsForThreshold} traversals have been recorded for a connection. * * @return mapping of connectionID and current temporal threshold */ private Map<String, Double> computeTemporalThresholds() { Map<String, List<Long>> traversalTimes = fcdDataStorage.getTraversalTimes(); Map<String, Double> percentiles = computeTraversalTimePercentiles(traversalTimes, 5); updateHeuristicRedLightDurations(traversalTimes); Map<String, Double> thresholds = new HashMap<>(); percentiles.forEach((connection, temporalPercentile) -> {
/* * Copyright (c) 2021 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: mosaic@fokus.fraunhofer.de */ package com.dcaiti.mosaic.app.tse.processors; /** * This class is used to compute the thresholds needed to compute the relative traffic metric. * * @see SpatioTemporalProcessor * @see SpatioTemporalTrafficMetric * @see FcdDatabaseHelper */ public class ThresholdProcessor extends TimeBasedProcessor<FcdRecord, FcdUpdateMessage> implements DatabaseAccess { private final static String IDENTIFIER = createIdentifier(ThresholdProcessor.class); public static final int MIN_RECORDED_TRAVERSALS_FOR_TL_HEURISTIC = 10; public static final int MAX_RECORDED_TRAVERSAL_FOR_TL_HEURISTIC = 400; // === CONFIG === /** * As an estimation of the RedPhase, this value will be applied to connections with * a significant difference in travel times close to the estimated duration. */ @JsonAdapter(TimeFieldAdapter.NanoSeconds.class) public long defaultRedLightDuration = 45 * TIME.SECOND; /** * Thresholds will only be computed and used for RTSM, if the number of samples in the past is larger than this. */ public int minTraversalsForThreshold = 10; /** * If true, the relative traffic metrics will be recomputed every time the thresholds are recomputed. * This may take long, as there can be a lot of traversals. */ public boolean recomputeAllRtsmWithNewThresholds = false; // === CONFIG === /** * Mosaic scenario database, holding data regarding the road network. */ private Database networkDatabase; /** * Gives access to the FcdDatabase. */ private FcdDataStorage fcdDataStorage; /** * Holds estimated red light durations. */ private final Map<String, Long> redLightDurations = new HashMap<>(); @Override public String getIdentifier() { return IDENTIFIER; } @Override public void withDataStorage(Database networkDatabase, FcdDataStorage fcdDataStorage) { this.networkDatabase = networkDatabase; this.fcdDataStorage = fcdDataStorage; } @Override public void triggerEvent(long eventTime) { long start = System.currentTimeMillis(); computeThresholds(eventTime); long duration = (System.currentTimeMillis() - start); logThresholdComputation(eventTime, duration * TIME.MILLI_SECOND); if (recomputeAllRtsmWithNewThresholds) { calculateRtsm(); } } /** * Computes thresholds using current data from DB and inserting them to thresholds table. * Uses Google Guava for percentiles. * * @param simulationTime Time at which the threshold computation started. Needed for further analysis of the resulting data. * @see <a href="https://github.com/google/guava">Google Guava on GitHub</a> * @see <a href="https://github.com/google/guava/blob/master/guava/src/com/google/common/math/Quantiles.java">Guava Quantiles</a> */ private void computeThresholds(long simulationTime) { if (triggerInterval <= 0) { return; } Map<String, Double> temporalThresholds = computeTemporalThresholds(); Map<String, Double> spatialThresholds = computeSpatialThresholds(temporalThresholds); // handle the possibility of no spatial Threshold, as percentile is above temporal threshold if (temporalThresholds.size() != spatialThresholds.size()) { ArrayList<String> notInBoth = new ArrayList<>(); temporalThresholds.forEach((connection, temporalThreshold) -> { if (!spatialThresholds.containsKey(connection)) { notInBoth.add(connection); } }); spatialThresholds.forEach((connection, temporalThreshold) -> { if (!temporalThresholds.containsKey(connection)) { notInBoth.add(connection); } }); notInBoth.forEach(connection -> { spatialThresholds.remove(connection); temporalThresholds.remove(connection); }); } fcdDataStorage.insertThresholds(temporalThresholds, spatialThresholds, simulationTime); } /** * Temporal threshold as done by Yoon et al. with 5% of 5th percentile as red light duration. * Does so only if more than {@link #minTraversalsForThreshold} traversals have been recorded for a connection. * * @return mapping of connectionID and current temporal threshold */ private Map<String, Double> computeTemporalThresholds() { Map<String, List<Long>> traversalTimes = fcdDataStorage.getTraversalTimes(); Map<String, Double> percentiles = computeTraversalTimePercentiles(traversalTimes, 5); updateHeuristicRedLightDurations(traversalTimes); Map<String, Double> thresholds = new HashMap<>(); percentiles.forEach((connection, temporalPercentile) -> {
double length = ScenarioDatabaseHelper.calcLengthByNodes(networkDatabase.getConnection(connection));
6
2023-10-23 16:39:40+00:00
16k
Primogem-Craft-Development/Primogem-Craft-Fabric
src/main/java/com/primogemstudio/primogemcraft/items/instances/materials/nagadus/NagadusEmeraldShovelItem.java
[ { "identifier": "PrimogemCraftBlocks", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/PrimogemCraftBlocks.java", "snippet": "public class PrimogemCraftBlocks {\n public static final DendroCoreBlock DENDRO_CORE_BLOCK = registerWithItem(\"dendro_core_block\", new DendroCoreBlock());\n ...
import com.primogemstudio.primogemcraft.blocks.PrimogemCraftBlocks; import com.primogemstudio.primogemcraft.items.PrimogemCraftItems; import com.primogemstudio.primogemcraft.sounds.PrimogemCraftSounds; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundSource; import net.minecraft.util.RandomSource; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.item.*; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.NotNull; import java.util.List;
10,976
package com.primogemstudio.primogemcraft.items.instances.materials.nagadus; public class NagadusEmeraldShovelItem extends ShovelItem { public NagadusEmeraldShovelItem() { super(new Tier() { public int getUses() { return 1561; } public float getSpeed() { return 1f; } public float getAttackDamageBonus() { return 0f; } public int getLevel() { return 4; } public int getEnchantmentValue() { return 5; } public @NotNull Ingredient getRepairIngredient() { return Ingredient.of(new ItemStack(PrimogemCraftItems.PRIMOGEM_ITEM), new ItemStack(PrimogemCraftItems.NAGADUS_EMERALD_SLIVER_ITEM)); } }, 1, -1f, new Item.Properties().fireResistant()); } @Override public boolean mineBlock(ItemStack itemstack, Level world, BlockState blockstate, BlockPos pos, LivingEntity entity) { boolean retval = super.mineBlock(itemstack, world, blockstate, pos, entity); var x = pos.getX(); var y = pos.getY(); var z = pos.getZ(); if (itemstack.getOrCreateTag().getBoolean("value")) { if (Math.random() < 0.01) { if (Math.random() < 0.5) { if (world instanceof ServerLevel _level) {
package com.primogemstudio.primogemcraft.items.instances.materials.nagadus; public class NagadusEmeraldShovelItem extends ShovelItem { public NagadusEmeraldShovelItem() { super(new Tier() { public int getUses() { return 1561; } public float getSpeed() { return 1f; } public float getAttackDamageBonus() { return 0f; } public int getLevel() { return 4; } public int getEnchantmentValue() { return 5; } public @NotNull Ingredient getRepairIngredient() { return Ingredient.of(new ItemStack(PrimogemCraftItems.PRIMOGEM_ITEM), new ItemStack(PrimogemCraftItems.NAGADUS_EMERALD_SLIVER_ITEM)); } }, 1, -1f, new Item.Properties().fireResistant()); } @Override public boolean mineBlock(ItemStack itemstack, Level world, BlockState blockstate, BlockPos pos, LivingEntity entity) { boolean retval = super.mineBlock(itemstack, world, blockstate, pos, entity); var x = pos.getX(); var y = pos.getY(); var z = pos.getZ(); if (itemstack.getOrCreateTag().getBoolean("value")) { if (Math.random() < 0.01) { if (Math.random() < 0.5) { if (world instanceof ServerLevel _level) {
ItemEntity entityToSpawn = new ItemEntity(_level, x, y, z, new ItemStack(PrimogemCraftBlocks.BLESSING_OF_DENDRO_BLOCK));
0
2023-10-15 08:07:06+00:00
16k
turtleisaac/PokEditor
src/main/java/io/github/turtleisaac/pokeditor/gui/editors/data/formats/scripts/field/FieldScriptEditor.java
[ { "identifier": "PokeditorManager", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/PokeditorManager.java", "snippet": "public class PokeditorManager extends PanelManager\n{\n private static final Dimension dimension = new Dimension(1200, 714);\n\n public static final FlatSVGIcon sheetE...
import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.text.*; import io.github.turtleisaac.nds4j.ui.ThemeUtils; import io.github.turtleisaac.pokeditor.formats.GenericFileData; import io.github.turtleisaac.pokeditor.formats.scripts.GenericScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.ScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.LevelScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.antlr4.ScriptDataProducer; import io.github.turtleisaac.pokeditor.formats.text.TextBankData; import io.github.turtleisaac.pokeditor.gui.*; import io.github.turtleisaac.pokeditor.gui.PokeditorManager; import io.github.turtleisaac.pokeditor.gui.editors.data.DefaultDataEditor; import io.github.turtleisaac.pokeditor.gui.editors.data.DefaultDataEditorPanel; import io.github.turtleisaac.pokeditor.gui.editors.data.EditorDataModel; import io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.*; import io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.ScriptDocument; import io.github.turtleisaac.pokeditor.gui.sheets.tables.FormatModel; import net.miginfocom.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.List;
12,215
/* * Created by JFormDesigner */ package io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.field; /** * @author turtleisaac */ public class FieldScriptEditor extends DefaultDataEditor<GenericScriptData, FieldScriptEditor.FieldScriptContents> { private DefaultListModel<GenericScriptData.ScriptComponent> levelScriptDataListModel = new DefaultListModel<>(); private DefaultListModel<String> labelDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> actionDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> scriptDisplayListModel = new DefaultListModel<>(); private boolean editMode; private GenericScriptData.ScriptComponent selected; public FieldScriptEditor(List<GenericScriptData> data, List<TextBankData> textBankData) { super(new FieldScriptModel(data, textBankData)); editMode = false; initComponents(); // FieldScriptEditorKit editorKit = new FieldScriptEditorKit(); StyledDocument document = new ScriptDocument(textPane1); textPane1.setDocument(document); textPane1.setBackground(new Color(58, 56, 77)); textPane1.setScrollPane(scrollPane1); textPane1.setForeground(Color.WHITE); levelScriptTypeComboBox.setSelectedIndex(0); paddingCheckbox.setSelected(true); levelScriptList.setModel(levelScriptDataListModel); levelScriptList.setSelectedIndex(-1); levelScriptListValueChanged(null); clearInputFields(); // valueField.addChangeListener(e -> paramFieldTextChange()); // scriptNoField.addChangeListener(e -> paramFieldTextChange()); // variableField.addChangeListener(e -> paramFieldTextChange()); removeButton.setEnabled(false); try { JTextPane numberPane = new JTextPane(); // numberPane.setBackground(textPane1.getBackground()); // numberPane.setForeground(textPane1.getForeground()); textPane1.setLineNumberPane(numberPane); scrollPane1.setRowHeaderView(numberPane); } catch(BadLocationException e) { throw new RuntimeException(e); } setIcons(); } private void setIcons() {
/* * Created by JFormDesigner */ package io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.field; /** * @author turtleisaac */ public class FieldScriptEditor extends DefaultDataEditor<GenericScriptData, FieldScriptEditor.FieldScriptContents> { private DefaultListModel<GenericScriptData.ScriptComponent> levelScriptDataListModel = new DefaultListModel<>(); private DefaultListModel<String> labelDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> actionDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> scriptDisplayListModel = new DefaultListModel<>(); private boolean editMode; private GenericScriptData.ScriptComponent selected; public FieldScriptEditor(List<GenericScriptData> data, List<TextBankData> textBankData) { super(new FieldScriptModel(data, textBankData)); editMode = false; initComponents(); // FieldScriptEditorKit editorKit = new FieldScriptEditorKit(); StyledDocument document = new ScriptDocument(textPane1); textPane1.setDocument(document); textPane1.setBackground(new Color(58, 56, 77)); textPane1.setScrollPane(scrollPane1); textPane1.setForeground(Color.WHITE); levelScriptTypeComboBox.setSelectedIndex(0); paddingCheckbox.setSelected(true); levelScriptList.setModel(levelScriptDataListModel); levelScriptList.setSelectedIndex(-1); levelScriptListValueChanged(null); clearInputFields(); // valueField.addChangeListener(e -> paramFieldTextChange()); // scriptNoField.addChangeListener(e -> paramFieldTextChange()); // variableField.addChangeListener(e -> paramFieldTextChange()); removeButton.setEnabled(false); try { JTextPane numberPane = new JTextPane(); // numberPane.setBackground(textPane1.getBackground()); // numberPane.setForeground(textPane1.getForeground()); textPane1.setLineNumberPane(numberPane); scrollPane1.setRowHeaderView(numberPane); } catch(BadLocationException e) { throw new RuntimeException(e); } setIcons(); } private void setIcons() {
addButton.setIcon(PokeditorManager.rowInsertIcon);
0
2023-10-15 05:00:57+00:00
16k
eclipse-egit/egit
org.eclipse.egit.ui.test/src/org/eclipse/egit/ui/common/CreatePatchWizard.java
[ { "identifier": "CoreText", "path": "org.eclipse.egit.core/src/org/eclipse/egit/core/internal/CoreText.java", "snippet": "public class CoreText extends NLS {\n\n\t/**\n\t * Do not in-line this into the static initializer as the\n\t * \"Find Broken Externalized Strings\" tool will not be\n\t * able to fi...
import org.eclipse.egit.core.internal.CoreText; import org.eclipse.egit.ui.test.ContextMenuHelper; import org.eclipse.egit.ui.test.TestUtil; import org.eclipse.egit.ui.test.team.actions.LocationPage; import org.eclipse.egit.ui.test.team.actions.OptionsPage; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
13,108
/******************************************************************************* * Copyright (C) 2012, 2013 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package org.eclipse.egit.ui.common; public class CreatePatchWizard { public static class NoChangesPopup { private SWTBotShell shell; public NoChangesPopup(SWTBotShell shell) { this.shell = shell; } public void cancelPopup() { shell.close(); } } protected static final TestUtil util = new TestUtil(); private SWTBotShell shell; public CreatePatchWizard(SWTBotShell shell) { this.shell = shell; } public static void openWizard(final String... projects) { SWTBotTree projectExplorerTree = TestUtil.getExplorerTree(); SWTBotTreeItem[] items = util.getProjectItems(projectExplorerTree, projects); projectExplorerTree.select(items); String[] menuPath = new String[] { util.getPluginLocalizedValue("TeamMenu.label"), util.getPluginLocalizedValue("CreatePatchAction.label") }; ContextMenuHelper.clickContextMenu(projectExplorerTree, menuPath); } public void finish() { shell.bot().button(IDialogConstants.FINISH_LABEL).click(); } public void finishWithNoneFormat() { LocationPage locationPage = getLocationPage();
/******************************************************************************* * Copyright (C) 2012, 2013 IBM Corporation and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package org.eclipse.egit.ui.common; public class CreatePatchWizard { public static class NoChangesPopup { private SWTBotShell shell; public NoChangesPopup(SWTBotShell shell) { this.shell = shell; } public void cancelPopup() { shell.close(); } } protected static final TestUtil util = new TestUtil(); private SWTBotShell shell; public CreatePatchWizard(SWTBotShell shell) { this.shell = shell; } public static void openWizard(final String... projects) { SWTBotTree projectExplorerTree = TestUtil.getExplorerTree(); SWTBotTreeItem[] items = util.getProjectItems(projectExplorerTree, projects); projectExplorerTree.select(items); String[] menuPath = new String[] { util.getPluginLocalizedValue("TeamMenu.label"), util.getPluginLocalizedValue("CreatePatchAction.label") }; ContextMenuHelper.clickContextMenu(projectExplorerTree, menuPath); } public void finish() { shell.bot().button(IDialogConstants.FINISH_LABEL).click(); } public void finishWithNoneFormat() { LocationPage locationPage = getLocationPage();
OptionsPage optionsPage = locationPage.nextToOptionsPage();
4
2023-10-20 15:17:51+00:00
16k
Wind-Gone/Vodka
code/src/main/java/benchmark/olap/query/Q5.java
[ { "identifier": "OLAPTerminal", "path": "code/src/main/java/benchmark/olap/OLAPTerminal.java", "snippet": "public class OLAPTerminal implements Runnable {\n // public static AtomicInteger DeliveryBG=new AtomicInteger(0);\n public static AtomicLong oorderTableSize = new AtomicLong(benchmark.olap.qu...
import benchmark.olap.OLAPTerminal; import benchmark.oltp.OLTPClient; import config.CommonConfig; import org.apache.log4j.Logger; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import static config.CommonConfig.DB_OCEANBASE;
14,332
package benchmark.olap.query; public class Q5 extends baseQuery { private static Logger log = Logger.getLogger(Q5.class); public double k; public double b; private int dbType; public Q5(int dbType) throws ParseException { super(); // this.k = OLTPClient.k1; // this.b = OLTPClient.b1; this.filterRate = benchmark.olap.OLAPClient.filterRate[4]; //o_entry_d=0.1534 this.dbType = dbType; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); } public String updateQuery() throws ParseException { // this.orderlineTSize=OLAPTerminal.orderLineTableSize; // this.orderTSize=OLAPTerminal.oorderTableSize; // this.olNotnullSize= OLAPTerminal.orderlineTableNotNullSize; this.k = OLTPClient.k1; this.b = OLTPClient.b1; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); return this.q; } public String getDeltaTimes() throws ParseException {
package benchmark.olap.query; public class Q5 extends baseQuery { private static Logger log = Logger.getLogger(Q5.class); public double k; public double b; private int dbType; public Q5(int dbType) throws ParseException { super(); // this.k = OLTPClient.k1; // this.b = OLTPClient.b1; this.filterRate = benchmark.olap.OLAPClient.filterRate[4]; //o_entry_d=0.1534 this.dbType = dbType; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); } public String updateQuery() throws ParseException { // this.orderlineTSize=OLAPTerminal.orderLineTableSize; // this.orderTSize=OLAPTerminal.oorderTableSize; // this.olNotnullSize= OLAPTerminal.orderlineTableNotNullSize; this.k = OLTPClient.k1; this.b = OLTPClient.b1; this.dynamicParam = getDeltaTimes(); this.q = getQuery(); return this.q; } public String getDeltaTimes() throws ParseException {
double countNumber = OLAPTerminal.oorderTableSize.get() * filterRate;
0
2023-10-22 11:22:32+00:00
16k
ushh789/FinancialCalculator
src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TypesOfFinancialOpearation/Credit/Credit.java
[ { "identifier": "LogHelper", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/FileInstruments/LogHelper.java", "snippet": "public class LogHelper {\n\n // Додаємо об'єкт логування\n private static final Logger logger = Logger.getLogger(LogHelper.class.getName());\n\n ...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments.LogHelper; import com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments.Savable; import com.netrunners.financialcalculator.LogicalInstrumnts.TimeFunctions.DateTimeFunctions; import com.netrunners.financialcalculator.LogicalInstrumnts.TimeFunctions.LocalDateAdapter; import com.netrunners.financialcalculator.MenuControllers.ResultTableController; import com.netrunners.financialcalculator.StartMenu; import com.netrunners.financialcalculator.VisualInstruments.MenuActions.LanguageManager; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.FileChooser; import javafx.stage.Stage; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.time.LocalDate; import java.util.logging.Level;
10,801
package com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit; public class Credit implements Savable { protected float loan; protected String currency; protected float annualPercent; protected LocalDate startDate; protected LocalDate endDate; protected int paymentType; protected int contractDuration; public Credit(float loan, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, int paymentType) { this.loan = loan; this.currency = currency; this.annualPercent = annualPercent; this.startDate = startDate; this.endDate = endDate; this.paymentType = paymentType; this.contractDuration = DateTimeFunctions.countDaysBetweenDates(startDate, endDate); } public float countLoan() { return loan * (1f / 365f) * (annualPercent / 100f); } public float countCreditBodyPerDay(){ return loan/contractDuration; } public void save() { Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) .create(); JsonObject jsonObject = getJsonObject(); String json = gson.toJson(jsonObject); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("saveButton").get()); File initialDirectory = new File("saves/"); fileChooser.setInitialDirectory(initialDirectory); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("JSON Files", "*.json")); File file = fileChooser.showSaveDialog(null); if (file != null) { try (FileWriter writer = new FileWriter(file)) { writer.write(json); } catch (IOException e) { LogHelper.log(Level.SEVERE, "Error while saving Credit to json", e); } } } public void sendCreditToResultTable() { FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/netrunners/financialcalculator/ResultTable.fxml")); try { Parent root = loader.load(); ResultTableController resultTableController = loader.getController(); resultTableController.updateTable(this); Stage stage = new Stage(); stage.setTitle(LanguageManager.getInstance().getStringBinding("ResultTableLabel").get()); Scene scene = new Scene(root);
package com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit; public class Credit implements Savable { protected float loan; protected String currency; protected float annualPercent; protected LocalDate startDate; protected LocalDate endDate; protected int paymentType; protected int contractDuration; public Credit(float loan, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, int paymentType) { this.loan = loan; this.currency = currency; this.annualPercent = annualPercent; this.startDate = startDate; this.endDate = endDate; this.paymentType = paymentType; this.contractDuration = DateTimeFunctions.countDaysBetweenDates(startDate, endDate); } public float countLoan() { return loan * (1f / 365f) * (annualPercent / 100f); } public float countCreditBodyPerDay(){ return loan/contractDuration; } public void save() { Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) .create(); JsonObject jsonObject = getJsonObject(); String json = gson.toJson(jsonObject); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("saveButton").get()); File initialDirectory = new File("saves/"); fileChooser.setInitialDirectory(initialDirectory); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("JSON Files", "*.json")); File file = fileChooser.showSaveDialog(null); if (file != null) { try (FileWriter writer = new FileWriter(file)) { writer.write(json); } catch (IOException e) { LogHelper.log(Level.SEVERE, "Error while saving Credit to json", e); } } } public void sendCreditToResultTable() { FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/netrunners/financialcalculator/ResultTable.fxml")); try { Parent root = loader.load(); ResultTableController resultTableController = loader.getController(); resultTableController.updateTable(this); Stage stage = new Stage(); stage.setTitle(LanguageManager.getInstance().getStringBinding("ResultTableLabel").get()); Scene scene = new Scene(root);
scene.getStylesheets().add(StartMenu.currentTheme);
5
2023-10-18 16:03:09+00:00
16k
Kyrotechnic/KyroClient
Client/src/main/java/me/kyroclient/KyroClient.java
[ { "identifier": "PacketSentEvent", "path": "Client/src/main/java/me/kyroclient/events/PacketSentEvent.java", "snippet": "@Cancelable\npublic class PacketSentEvent extends Event {\n public Packet<?> packet;\n public PacketSentEvent(Packet<?> packet)\n {\n this.packet = packet;\n }\n\n ...
import lombok.SneakyThrows; import me.kyroclient.events.PacketSentEvent; import me.kyroclient.forge.ForgeRegister; import me.kyroclient.forge.ForgeSpoofer; import me.kyroclient.managers.*; import me.kyroclient.modules.Module; import me.kyroclient.modules.client.Capes; import me.kyroclient.modules.client.CustomBrand; import me.kyroclient.modules.client.Tickless; import me.kyroclient.modules.combat.*; import me.kyroclient.modules.garden.CropNuker; import me.kyroclient.modules.garden.FarmingMacro; import me.kyroclient.modules.mining.MiningQOL; import me.kyroclient.modules.misc.*; import me.kyroclient.modules.player.*; import me.kyroclient.modules.render.*; import me.kyroclient.notifications.Notification; import me.kyroclient.util.SkyblockUtils; import me.kyroclient.util.font.Fonts; import me.kyroclient.util.render.BlurUtils; import net.minecraft.client.Minecraft; import net.minecraft.network.play.client.C01PacketChatMessage; import net.minecraft.util.ChatComponentText; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import javax.net.ssl.*; import java.awt.*; import java.lang.reflect.Method; import java.security.SecureRandom; import java.util.List; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.stream.Collectors;
11,193
package me.kyroclient; public class KyroClient { //Vars public static final String MOD_ID = "dankers"; public static String VERSION = "0.2-b3"; public static List<String> changelog; public static ModuleManager moduleManager; public static NotificationManager notificationManager; public static ConfigManager configManager; public static ThemeManager themeManager; public static FriendManager friendManager; public static CapeManager capeManager; public static Minecraft mc; public static boolean isDev = true; public static Color iconColor = new Color(237, 107, 0); public static long gameStarted; public static boolean banned = false; //Module Dependencies public static Gui clickGui; public static NickHider nickHider; public static CropNuker cropNuker; public static Velocity velocity; public static FastPlace fastPlace; public static Modless modless; public static Speed speed; public static AntiBot antiBot; public static Interfaces interfaces; public static Delays delays; public static Hitboxes hitBoxes; public static NoSlow noSlow; public static FreeCam freeCam; public static Giants giants; public static Animations animations; public static Aura aura; public static AutoBlock autoBlock; public static PopupAnimation popupAnimation; public static GuiMove guiMove; public static Camera camera; public static Reach reach; public static InventoryDisplay inventoryDisplay; public static LoreDisplay loreDisplay; public static FarmingMacro macro; public static MiningQOL miningQol; public static Tickless tickless; public static TeleportExploit teleportExploit; public static Hud hud; public static FakeLag fakeLag; public static Proxy proxy; public static CustomBrand customBrand; public static NoFallingBlocks noFallingBlocks; public static PlayerVisibility playerVisibility; public static NoDebuff noDebuff; public static Capes capes; //Methods /* Time to finally make it spoof being any random mod on boot! */ public static List<ForgeRegister> registerEvents() { /*for (Module module : moduleManager.getModules()) { MinecraftForge.EVENT_BUS.register(module); }*/ ForgeSpoofer.update(); List<ForgeRegister> registers = new ArrayList<>();
package me.kyroclient; public class KyroClient { //Vars public static final String MOD_ID = "dankers"; public static String VERSION = "0.2-b3"; public static List<String> changelog; public static ModuleManager moduleManager; public static NotificationManager notificationManager; public static ConfigManager configManager; public static ThemeManager themeManager; public static FriendManager friendManager; public static CapeManager capeManager; public static Minecraft mc; public static boolean isDev = true; public static Color iconColor = new Color(237, 107, 0); public static long gameStarted; public static boolean banned = false; //Module Dependencies public static Gui clickGui; public static NickHider nickHider; public static CropNuker cropNuker; public static Velocity velocity; public static FastPlace fastPlace; public static Modless modless; public static Speed speed; public static AntiBot antiBot; public static Interfaces interfaces; public static Delays delays; public static Hitboxes hitBoxes; public static NoSlow noSlow; public static FreeCam freeCam; public static Giants giants; public static Animations animations; public static Aura aura; public static AutoBlock autoBlock; public static PopupAnimation popupAnimation; public static GuiMove guiMove; public static Camera camera; public static Reach reach; public static InventoryDisplay inventoryDisplay; public static LoreDisplay loreDisplay; public static FarmingMacro macro; public static MiningQOL miningQol; public static Tickless tickless; public static TeleportExploit teleportExploit; public static Hud hud; public static FakeLag fakeLag; public static Proxy proxy; public static CustomBrand customBrand; public static NoFallingBlocks noFallingBlocks; public static PlayerVisibility playerVisibility; public static NoDebuff noDebuff; public static Capes capes; //Methods /* Time to finally make it spoof being any random mod on boot! */ public static List<ForgeRegister> registerEvents() { /*for (Module module : moduleManager.getModules()) { MinecraftForge.EVENT_BUS.register(module); }*/ ForgeSpoofer.update(); List<ForgeRegister> registers = new ArrayList<>();
for (Module module : moduleManager.getModules())
3
2023-10-15 16:24:51+00:00
16k
AstroDev2023/2023-studio-1-but-better
source/core/src/test/com/csse3200/game/components/plants/PlantMouseHoverComponentTest.java
[ { "identifier": "Entity", "path": "source/core/src/main/com/csse3200/game/entities/Entity.java", "snippet": "public class Entity implements Json.Serializable {\n\tprivate static final Logger logger = LoggerFactory.getLogger(Entity.class);\n\tprivate static int nextId = 0;\n\tprivate static final String ...
import com.csse3200.game.entities.Entity; import com.csse3200.game.events.EventHandler; import com.csse3200.game.extensions.GameExtension; import com.csse3200.game.services.ServiceLocator; import com.csse3200.game.services.plants.PlantInfoService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when;
11,801
package com.csse3200.game.components.plants; /** * Tests for PlantMouseHoverComponent class */ @ExtendWith(GameExtension.class) class PlantMouseHoverComponentTest { PlantMouseHoverComponent plantMouseHoverComponent; @Mock private PlantInfoService plantInfoService; /** * Sets up the test environment before each test case. */ @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); plantMouseHoverComponent = new PlantMouseHoverComponent(); plantMouseHoverComponent.setEntity(new Entity()); ServiceLocator.registerPlantInfoService(plantInfoService);
package com.csse3200.game.components.plants; /** * Tests for PlantMouseHoverComponent class */ @ExtendWith(GameExtension.class) class PlantMouseHoverComponentTest { PlantMouseHoverComponent plantMouseHoverComponent; @Mock private PlantInfoService plantInfoService; /** * Sets up the test environment before each test case. */ @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); plantMouseHoverComponent = new PlantMouseHoverComponent(); plantMouseHoverComponent.setEntity(new Entity()); ServiceLocator.registerPlantInfoService(plantInfoService);
when(plantInfoService.getEvents()).thenReturn(new EventHandler());
1
2023-10-17 22:34:04+00:00
16k
moeinfatehi/PassiveDigger
src/PassiveDigger/PassiveAnalyzer.java
[ { "identifier": "BurpExtender", "path": "src/burp/BurpExtender.java", "snippet": "public class BurpExtender extends JPanel implements IBurpExtender\r\n{\r\n \r\n public static IBurpExtenderCallbacks callbacks;\r\n static JScrollPane frame;\r\n public static PrintWriter output;\r\n public ...
import burp.BurpExtender; import burp.IBurpExtenderCallbacks; import burp.IHttpRequestResponse; import burp.IHttpService; import burp.IParameter; import burp.IRequestInfo; import burp.IResponseInfo; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.List; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter;
13,303
package PassiveDigger; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author "Moein Fatehi moein.fatehi@gmail.com" */ public class PassiveAnalyzer extends javax.swing.JPanel implements burp.IHttpListener{ private static String extension_name="Analyzer"; private static Scanner sc; public static List<vulnerability> vulnerabilityList=new ArrayList<>(); private static int EAR_avg=400; private static int ConcurrentModificationException=0; public static void AnalyzeRequest(IHttpRequestResponse reqResp,int toolFlag) { if(requestIsInScope(reqResp)){ FindFileUploadInRequest(reqResp, toolFlag); ExtractEncodingsInRequest(reqResp); } } public static void AnalyzeResponse(IHttpRequestResponse reqResp, int toolFlag){ try { if(requestIsInScope(reqResp)){ SendToHeadersTab(reqResp); checkSQLInjection(reqResp); checkReflectedParams(reqResp); extractSensitiveDatas(reqResp); ExtractEncodingsInResponse(reqResp); checkMisconfiguration(reqResp);
package PassiveDigger; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author "Moein Fatehi moein.fatehi@gmail.com" */ public class PassiveAnalyzer extends javax.swing.JPanel implements burp.IHttpListener{ private static String extension_name="Analyzer"; private static Scanner sc; public static List<vulnerability> vulnerabilityList=new ArrayList<>(); private static int EAR_avg=400; private static int ConcurrentModificationException=0; public static void AnalyzeRequest(IHttpRequestResponse reqResp,int toolFlag) { if(requestIsInScope(reqResp)){ FindFileUploadInRequest(reqResp, toolFlag); ExtractEncodingsInRequest(reqResp); } } public static void AnalyzeResponse(IHttpRequestResponse reqResp, int toolFlag){ try { if(requestIsInScope(reqResp)){ SendToHeadersTab(reqResp); checkSQLInjection(reqResp); checkReflectedParams(reqResp); extractSensitiveDatas(reqResp); ExtractEncodingsInResponse(reqResp); checkMisconfiguration(reqResp);
IResponseInfo respInfo = BurpExtender.callbacks.getHelpers().analyzeResponse(reqResp.getResponse());
6
2023-10-23 12:13:00+00:00
16k
RoessinghResearch/senseeact
SenSeeActService/src/main/java/nl/rrd/senseeact/service/controller/UserController.java
[ { "identifier": "ErrorCode", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/exception/ErrorCode.java", "snippet": "public class ErrorCode {\n\tpublic static final String AUTH_TOKEN_NOT_FOUND = \"AUTH_TOKEN_NOT_FOUND\";\n\tpublic static final String AUTH_TOKEN_INVALID = \"AUTH_TOKEN_INVAL...
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.parameters.RequestBody; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import nl.rrd.senseeact.client.exception.ErrorCode; import nl.rrd.senseeact.client.exception.HttpError; import nl.rrd.senseeact.client.exception.HttpFieldError; import nl.rrd.senseeact.client.model.ListUser; import nl.rrd.senseeact.client.model.Role; import nl.rrd.senseeact.client.model.compat.*; import nl.rrd.senseeact.client.project.BaseProject; import nl.rrd.senseeact.client.project.ProjectRepository; import nl.rrd.senseeact.dao.*; import nl.rrd.senseeact.service.*; import nl.rrd.senseeact.service.exception.BadRequestException; import nl.rrd.senseeact.service.exception.ForbiddenException; import nl.rrd.senseeact.service.exception.HttpException; import nl.rrd.senseeact.service.exception.NotFoundException; import nl.rrd.senseeact.service.mail.EmailSender; import nl.rrd.senseeact.service.mail.EmailTemplate; import nl.rrd.senseeact.service.mail.EmailTemplateCollection; import nl.rrd.senseeact.service.mail.EmailTemplateRepository; import nl.rrd.senseeact.service.model.UserTable; import nl.rrd.senseeact.service.model.*; import nl.rrd.senseeact.service.validation.ModelValidation; import nl.rrd.utils.AppComponents; import nl.rrd.utils.beans.PropertyReader; import nl.rrd.utils.beans.PropertyWriter; import nl.rrd.utils.datetime.DateTimeUtils; import nl.rrd.utils.exception.DatabaseException; import nl.rrd.utils.exception.ParseException; import nl.rrd.utils.validation.TypeConversion; import org.slf4j.Logger; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.*;
13,582
UserV7 userCompat = mapper.convertValue(userMap, UserV7.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } else if (version.ordinal() >= ProtocolVersion.V6_0_0.ordinal()) { UserV6 userCompat = mapper.convertValue(userMap, UserV6.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } else if (version.ordinal() >= ProtocolVersion.V5_1_3.ordinal()) { UserV5 userCompat = mapper.convertValue(userMap, UserV5.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } else if (version.ordinal() >= ProtocolVersion.V5_1_2.ordinal()) { UserV4 userCompat = mapper.convertValue(userMap, UserV4.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } else if (version.ordinal() >= ProtocolVersion.V5_1_1.ordinal()) { UserV3 userCompat = mapper.convertValue(userMap, UserV3.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } else if (version.ordinal() >= ProtocolVersion.V5_0_6.ordinal()) { UserV2 userCompat = mapper.convertValue(userMap, UserV2.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } else if (version.ordinal() >= ProtocolVersion.V5_0_4.ordinal()) { UserV1 userCompat = mapper.convertValue(userMap, UserV1.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } else { UserV0 userCompat = mapper.convertValue(userMap, UserV0.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } return result; } catch (IllegalArgumentException ex) { String msg = "Content is invalid for a user object"; logger.error("Invalid input in PUT /user/: " + msg + ": " + ex.getMessage()); HttpError error = new HttpError(ErrorCode.INVALID_INPUT, msg); throw new BadRequestException(error); } } private static class ParsedSetUserInput { public nl.rrd.senseeact.client.model.User user; public Set<String> setFields; } private SetUserEmailResult setUserEmail(User setUser, nl.rrd.senseeact.client.model.User inputUser, String templateName) throws HttpException { SetUserEmailResult result = new SetUserEmailResult(); String newEmail = inputUser.getEmail(); if (newEmail == null) return result; newEmail = newEmail.toLowerCase(); EmailChangedState state = setUserEmailGetState(newEmail, setUser); if (state == EmailChangedState.NOT_CHANGED) return result; UserCache userCache = UserCache.getInstance(); if (userCache.emailExists(newEmail)) { String message = "User with email " + newEmail + " already exists"; HttpError error = new HttpError(ErrorCode.USER_ALREADY_EXISTS, message); error.addFieldError(new HttpFieldError("email", message)); throw new ForbiddenException(error); } result.state = state; result.newEmail = newEmail; result.templates = getEmailChangedTemplates(templateName); return result; } private EmailChangedState setUserEmailGetState(String newEmail, User setUser) { if (setUser.getEmailPendingVerification() != null) { if (newEmail.equals(setUser.getEmailPendingVerification())) return EmailChangedState.NOT_CHANGED; if (newEmail.equals(setUser.getEmail())) { setUser.setEmailPendingVerification(null); setUser.setVerifyEmailRequestCode(null); setUser.setVerifyEmailRequestTime(null); return EmailChangedState.NOT_CHANGED; } setUser.setEmailPendingVerification(newEmail); return EmailChangedState.PENDING_VERIFICATION_CHANGED; } else { if (newEmail.equals(setUser.getEmail())) return EmailChangedState.NOT_CHANGED; if (setUser.isHasTemporaryEmail()) { setUser.setEmail(newEmail); setUser.setHasTemporaryEmail(false); return EmailChangedState.TEMPORARY_CHANGED; } else if (setUser.isEmailVerified()) { setUser.setEmailPendingVerification(newEmail); return EmailChangedState.VERIFIED_CHANGED; } else { setUser.setEmail(newEmail); return EmailChangedState.UNVERIFIED_CHANGED; } } } private static class SetUserEmailResult { public EmailChangedState state = EmailChangedState.NOT_CHANGED; public String newEmail = null; public EmailChangedTemplates templates = null; } private enum EmailChangedState { NOT_CHANGED, TEMPORARY_CHANGED, VERIFIED_CHANGED, UNVERIFIED_CHANGED, PENDING_VERIFICATION_CHANGED } private EmailChangedTemplates getEmailChangedTemplates( String templateName) throws BadRequestException { EmailChangedTemplates result = new EmailChangedTemplates(); List<HttpFieldError> errors = new ArrayList<>();
package nl.rrd.senseeact.service.controller; @RestController @RequestMapping("/v{version}/user") public class UserController { public static final List<String> CHANGE_FORBIDDEN_FIELDS = List.of( "userid", "emailVerified", "emailPendingVerification", "hasTemporaryEmail", "hasTemporaryPassword", "role", "active", "created", "lastActive" ); @RequestMapping(value="/list", method=RequestMethod.GET) public List<ListUser> getUserList( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName) throws HttpException, Exception { return QueryRunner.runAuthQuery((version, authDb, user) -> doGetUserList(version, user), versionName, request, response); } @RequestMapping(value="/", method=RequestMethod.GET) public DatabaseObject getUser( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user", required=false, defaultValue="") final String userId, @RequestParam(value="email", required=false, defaultValue="") final String email) throws HttpException, Exception { return QueryRunner.runAuthQuery( (version, authDb, user) -> doGetUser(version, authDb, user, userId, email), versionName, request, response); } @RequestMapping(value="/", method=RequestMethod.PUT) @RequestBody( content = { @Content( mediaType = "application/json", schema = @Schema(type = "string") ) } ) public DatabaseObject setUser( final HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user", required=false, defaultValue="") final String userId, @Parameter(hidden = true) @RequestParam(value="email", required=false, defaultValue="") final String compatEmail, @RequestParam(value="emailTemplate", required=false, defaultValue="") String emailTemplate) throws HttpException, Exception { return QueryRunner.runAuthQuery( (version, authDb, user) -> doSetUser(version, authDb, user, userId, compatEmail, emailTemplate, request), versionName, request, response); } @RequestMapping(value="/", method=RequestMethod.DELETE) public void deleteUser( final HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user", required=false, defaultValue="") final String userId, @Parameter(hidden = true) @RequestParam(value="email", required=false, defaultValue="") final String compatEmail) throws HttpException, Exception { QueryRunner.runAuthQuery( (version, authDb, user) -> doDeleteUser(version, authDb, user, userId, compatEmail), versionName, request, response); } @RequestMapping(value="/role", method=RequestMethod.PUT) public void setRole( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user") final String user, @RequestParam(value="role") final String role) throws HttpException, Exception { QueryRunner.runAuthQuery( (version, authDb, currUser) -> doSetRole(version, authDb, currUser, user, role), versionName, request, response); } @RequestMapping(value="/active", method=RequestMethod.PUT) public void setActive( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user") final String user, @RequestParam(value="active") final String active) throws HttpException, Exception { QueryRunner.runAuthQuery( (version, authDb, currUser) -> doSetActive(version, authDb, currUser, user, active), versionName, request, response); } @RequestMapping(value="/groups", method=RequestMethod.GET) public List<String> getGroups( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @RequestParam(value="user", required=false, defaultValue="") final String user) throws HttpException, Exception { return QueryRunner.runAuthQuery( (version, authDb, currUser) -> doGetGroups(version, authDb, currUser, user), versionName, request, response); } private Object doSetRole(ProtocolVersion version, Database authDb, User currUser, String setUserId, String role) throws HttpException, Exception { if (currUser.getRole() != Role.ADMIN) throw new ForbiddenException(); UserCache userCache = UserCache.getInstance(); User setUser = userCache.find(version, setUserId); if (setUser == null) { throw new NotFoundException(String.format("User %s not found", setUserId)); } if (setUser.getUserid().equals(currUser.getUserid())) throw new ForbiddenException("Can't set role of yourself"); Role roleEnum; try { roleEnum = TypeConversion.getEnum(role, Role.class); } catch (ParseException ex) { String msg = "Invalid role: " + role; HttpError error = new HttpError(ErrorCode.INVALID_INPUT, msg); error.addFieldError(new HttpFieldError("role", msg)); throw new BadRequestException(error); } DatabaseCriteria criteria = new DatabaseCriteria.Equal("user", setUser.getUserid()); List<UserProject> userProjects = authDb.select(new UserProjectTable(), criteria, 0, null); List<String> downgradeProjects = new ArrayList<>(); for (UserProject userProject : userProjects) { if (userProject.getAsRole().ordinal() < roleEnum.ordinal() && !downgradeProjects.contains(userProject.getProjectCode())) { downgradeProjects.add(userProject.getProjectCode()); } } if (!downgradeProjects.isEmpty()) { Collections.sort(downgradeProjects); throw new ForbiddenException("Can't downgrade to role " + roleEnum + ", because the user is a member with a higher role in the following projects: " + String.join(", ", downgradeProjects)); } Role oldRole = setUser.getRole(); if (oldRole.ordinal() < Role.PATIENT.ordinal() && roleEnum == Role.PATIENT) { // role downgraded to patient List<String> subjects = setUser.findGroupUserids(authDb, Group.Type.USER_ACCESS); if (!subjects.isEmpty()) { throw new ForbiddenException( "Can't downgrade role to PATIENT because the user has subjects"); } } setUser.setRole(roleEnum); userCache.updateUser(authDb, setUser); UserListenerRepository.getInstance().notifyUserRoleChanged(setUser, oldRole); return null; } private Object doSetActive(ProtocolVersion version, Database authDb, User currUser, String setUserId, String activeStr) throws HttpException, Exception { if (currUser.getRole() != Role.ADMIN) throw new ForbiddenException(); UserCache userCache = UserCache.getInstance(); User setUser = userCache.find(version, setUserId); if (setUser == null) { throw new NotFoundException(String.format("User %s not found", setUserId)); } if (setUser.getUserid().equals(currUser.getUserid())) throw new ForbiddenException("Can't set active status for yourself"); boolean active; try { active = TypeConversion.getBoolean(activeStr); } catch (ParseException ex) { throw BadRequestException.withInvalidInput( new HttpFieldError("active", ex.getMessage())); } if (setUser.isActive() == active) return null; ZonedDateTime now = DateTimeUtils.nowMs(); setUser.setActive(active); userCache.updateUser(authDb, setUser); UserActiveChange change = new UserActiveChange(setUser.getUserid(), now, active); authDb.insert(UserActiveChangeTable.NAME, change); UserListenerRepository.getInstance().notifyUserActiveChanged(setUser); return null; } private List<ListUser> doGetUserList( ProtocolVersion version, User user) throws HttpException, Exception { if (user.getRole() != Role.ADMIN) throw new ForbiddenException(); UserCache userCache = UserCache.getInstance(); List<User> users = userCache.getUsers(null, Comparator.comparing( User::getEmail)); List<ListUser> result = new ArrayList<>(); for (User getUser : users) { result.add(ListUser.fromUser(getUser)); } return result; } private DatabaseObject doGetUser(ProtocolVersion version, Database authDb, User user, String getUserId, String email) throws HttpException, Exception { User getUser; if (getUserId != null && !getUserId.isEmpty()) getUser = User.findAccessibleUser(version, getUserId, authDb, user); else getUser = User.findAccessibleUserByEmail(email, authDb, user); return getCompatUser(version, getUser); } public static DatabaseObject getCompatUser(ProtocolVersion version, User user) { if (version.ordinal() >= ProtocolVersion.V6_0_7.ordinal()) return user; else if (version.ordinal() >= ProtocolVersion.V6_0_6.ordinal()) return UserV10.fromUser(user); else if (version.ordinal() >= ProtocolVersion.V6_0_5.ordinal()) return UserV9.fromUser(user); else if (version.ordinal() >= ProtocolVersion.V6_0_4.ordinal()) return UserV8.fromUser(user); else if (version.ordinal() >= ProtocolVersion.V6_0_3.ordinal()) return UserV7.fromUser(user); else if (version.ordinal() >= ProtocolVersion.V6_0_0.ordinal()) return UserV6.fromUser(user); else if (version.ordinal() >= ProtocolVersion.V5_1_3.ordinal()) return UserV5.fromUser(user); else if (version.ordinal() >= ProtocolVersion.V5_1_2.ordinal()) return UserV4.fromUser(user); else if (version.ordinal() >= ProtocolVersion.V5_1_1.ordinal()) return UserV3.fromUser(user); else if (version.ordinal() >= ProtocolVersion.V5_0_6.ordinal()) return UserV2.fromUser(user); else if (version.ordinal() >= ProtocolVersion.V5_0_4.ordinal()) return UserV1.fromUser(user); else return UserV0.fromUser(user); } public static List<DatabaseObject> getCompatUserList( ProtocolVersion version, List<User> users) { List<DatabaseObject> result = new ArrayList<>(); for (User user : users) { result.add(getCompatUser(version, user)); } return result; } private DatabaseObject doSetUser(ProtocolVersion version, Database authDb, User user, String setUserId, String compatEmail, String emailTemplate, HttpServletRequest request) throws HttpException, Exception { synchronized (AuthControllerExecution.AUTH_LOCK) { return doSetUserLock(version, authDb, user, setUserId, compatEmail, emailTemplate, request); } } private DatabaseObject doSetUserLock(ProtocolVersion version, Database authDb, User user, String setUserId, String compatEmail, String emailTemplateName, HttpServletRequest request) throws HttpException, Exception { User setUser; if (compatEmail != null && !compatEmail.isEmpty()) setUser = User.findAccessibleUserByEmail(compatEmail, authDb, user); else setUser = User.findAccessibleUser(version, setUserId, authDb, user); Map<String,?> inputMap = readSetUserInput(request); validateUserMapKeys(version, inputMap); // inputMap contains only fields that occur in client model of User // for the specified protocol version ParsedSetUserInput parsedInput = parseSetUserInput(version, inputMap); nl.rrd.senseeact.client.model.User inputUser = parsedInput.user; Set<String> setFields = parsedInput.setFields; UserCache userCache = UserCache.getInstance(); // if inputMap contains fields that cannot be changed, their values // have not changed User oldProfile = new User(); oldProfile.copyFrom(setUser); for (String field : setFields) { if (CHANGE_FORBIDDEN_FIELDS.contains(field) || field.equals("email")) { continue; } PropertyWriter.writeProperty(setUser, field, PropertyReader.readProperty(inputUser, field)); } SetUserEmailResult emailResult = setUserEmail(setUser, inputUser, emailTemplateName); ModelValidation.validate(setUser); userCache.updateUser(authDb, setUser); if (!setUser.equals(oldProfile)) { UserListenerRepository.getInstance().notifyUserProfileUpdated( setUser, oldProfile); } sendEmailChanged(emailResult, request, setUser, oldProfile, authDb); return getCompatUser(version, setUser); } /** * Tries to read a JSON object from the specified HTTP request body for * setUser(). If the body content is invalid, it logs an error message and * throws a BadRequestException. * * @param request the HTTP request * @return the JSON object as a map * @throws BadRequestException if the body content is invalid * @throws IOException if a reading error occurs */ private Map<String,?> readSetUserInput(HttpServletRequest request) throws BadRequestException, IOException { ObjectMapper mapper = new ObjectMapper(); InputStream input = request.getInputStream(); Exception jsonException; try { return mapper.readValue(request.getInputStream(), new TypeReference<>() {}); } catch (JsonProcessingException ex) { jsonException = ex; } finally { input.close(); } Logger logger = AppComponents.getLogger(SenSeeActContext.LOGTAG); String msg = "Content is not a valid JSON object"; logger.error("Invalid input in PUT /user/: " + msg + ": " + jsonException.getMessage()); HttpError error = new HttpError(ErrorCode.INVALID_INPUT, msg); throw new BadRequestException(error); } /** * Checks whether the keys in the specified user map occur in the client * model fields of User for the specified protocol version. The user map * should be the input from setUser(). If any invalid key is found, it * throws a BadRequestException. * * @param version the protocol version * @param userMap the user map * @throws BadRequestException if an invalid key is found */ private void validateUserMapKeys(ProtocolVersion version, Map<String,?> userMap) throws BadRequestException { List<String> userFields = getUserModelFields(version); List<String> invalidKeys = new ArrayList<>(); for (String key : userMap.keySet()) { if (!userFields.contains(key)) invalidKeys.add(key); } if (!invalidKeys.isEmpty()) { StringBuilder invalidKeysStr = new StringBuilder(); for (String key : invalidKeys) { if (!invalidKeysStr.isEmpty()) invalidKeysStr.append(", "); invalidKeysStr.append(key); } HttpError error = new HttpError(ErrorCode.INVALID_INPUT, "Invalid user fields: " + invalidKeysStr); throw new BadRequestException(error); } } /** * Returns all fields in the client model of User for the specified protocol * version. * * @param version the version * @return the user model fields */ private List<String> getUserModelFields(ProtocolVersion version) { if (version.ordinal() >= ProtocolVersion.V6_0_7.ordinal()) { return DatabaseFieldScanner.getDatabaseFieldNames( nl.rrd.senseeact.client.model.User.class); } else if (version.ordinal() >= ProtocolVersion.V6_0_6.ordinal()) { return DatabaseFieldScanner.getDatabaseFieldNames(UserV10.class); } else if (version.ordinal() >= ProtocolVersion.V6_0_5.ordinal()) { return DatabaseFieldScanner.getDatabaseFieldNames(UserV9.class); } else if (version.ordinal() >= ProtocolVersion.V6_0_4.ordinal()) { return DatabaseFieldScanner.getDatabaseFieldNames(UserV8.class); } else if (version.ordinal() >= ProtocolVersion.V6_0_3.ordinal()) { return DatabaseFieldScanner.getDatabaseFieldNames(UserV7.class); } else if (version.ordinal() >= ProtocolVersion.V6_0_0.ordinal()) { return DatabaseFieldScanner.getDatabaseFieldNames(UserV6.class); } else if (version.ordinal() >= ProtocolVersion.V5_1_3.ordinal()) { return DatabaseFieldScanner.getDatabaseFieldNames(UserV5.class); } else if (version.ordinal() >= ProtocolVersion.V5_1_2.ordinal()) { return DatabaseFieldScanner.getDatabaseFieldNames(UserV4.class); } else if (version.ordinal() >= ProtocolVersion.V5_1_1.ordinal()) { return DatabaseFieldScanner.getDatabaseFieldNames(UserV3.class); } else if (version.ordinal() >= ProtocolVersion.V5_0_6.ordinal()) { return DatabaseFieldScanner.getDatabaseFieldNames(UserV2.class); } else if (version.ordinal() >= ProtocolVersion.V5_0_4.ordinal()) { return DatabaseFieldScanner.getDatabaseFieldNames(UserV1.class); } else { return DatabaseFieldScanner.getDatabaseFieldNames(UserV0.class); } } /** * Parses the values of the specified user map, which should be the input * from setUser(). The keys in the map should already have been validated * with validateUserMapKeys(). This method converts the map to the client * model of User for the specified protocol version. Then it converts that * model to the current version. It also converts the set of keys in the * user map to the corresponding names in the latest version. If any value * is invalid, this method throws a BadRequestException. * * @param version the version * @param userMap the user map * @return the user model and list of set fields in the latest version * @throws BadRequestException if any value in the map is invalid */ private ParsedSetUserInput parseSetUserInput(ProtocolVersion version, Map<String,?> userMap) throws BadRequestException { ParsedSetUserInput result = new ParsedSetUserInput(); Logger logger = AppComponents.getLogger(getClass().getSimpleName()); ObjectMapper mapper = new ObjectMapper(); try { if (version.ordinal() >= ProtocolVersion.V6_0_7.ordinal()) { result.user = mapper.convertValue(userMap, nl.rrd.senseeact.client.model.User.class); result.setFields = userMap.keySet(); } else if (version.ordinal() >= ProtocolVersion.V6_0_6.ordinal()) { UserV10 userCompat = mapper.convertValue(userMap, UserV10.class); result.user = userCompat.toUser(); result.setFields = userMap.keySet(); } else if (version.ordinal() >= ProtocolVersion.V6_0_5.ordinal()) { UserV9 userCompat = mapper.convertValue(userMap, UserV9.class); result.user = userCompat.toUser(); result.setFields = userMap.keySet(); } else if (version.ordinal() >= ProtocolVersion.V6_0_4.ordinal()) { UserV8 userCompat = mapper.convertValue(userMap, UserV8.class); result.user = userCompat.toUser(); result.setFields = userMap.keySet(); } else if (version.ordinal() >= ProtocolVersion.V6_0_3.ordinal()) { UserV7 userCompat = mapper.convertValue(userMap, UserV7.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } else if (version.ordinal() >= ProtocolVersion.V6_0_0.ordinal()) { UserV6 userCompat = mapper.convertValue(userMap, UserV6.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } else if (version.ordinal() >= ProtocolVersion.V5_1_3.ordinal()) { UserV5 userCompat = mapper.convertValue(userMap, UserV5.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } else if (version.ordinal() >= ProtocolVersion.V5_1_2.ordinal()) { UserV4 userCompat = mapper.convertValue(userMap, UserV4.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } else if (version.ordinal() >= ProtocolVersion.V5_1_1.ordinal()) { UserV3 userCompat = mapper.convertValue(userMap, UserV3.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } else if (version.ordinal() >= ProtocolVersion.V5_0_6.ordinal()) { UserV2 userCompat = mapper.convertValue(userMap, UserV2.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } else if (version.ordinal() >= ProtocolVersion.V5_0_4.ordinal()) { UserV1 userCompat = mapper.convertValue(userMap, UserV1.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } else { UserV0 userCompat = mapper.convertValue(userMap, UserV0.class); result.user = userCompat.toUser(); result.setFields = userCompat.convertFields(userMap.keySet()); } return result; } catch (IllegalArgumentException ex) { String msg = "Content is invalid for a user object"; logger.error("Invalid input in PUT /user/: " + msg + ": " + ex.getMessage()); HttpError error = new HttpError(ErrorCode.INVALID_INPUT, msg); throw new BadRequestException(error); } } private static class ParsedSetUserInput { public nl.rrd.senseeact.client.model.User user; public Set<String> setFields; } private SetUserEmailResult setUserEmail(User setUser, nl.rrd.senseeact.client.model.User inputUser, String templateName) throws HttpException { SetUserEmailResult result = new SetUserEmailResult(); String newEmail = inputUser.getEmail(); if (newEmail == null) return result; newEmail = newEmail.toLowerCase(); EmailChangedState state = setUserEmailGetState(newEmail, setUser); if (state == EmailChangedState.NOT_CHANGED) return result; UserCache userCache = UserCache.getInstance(); if (userCache.emailExists(newEmail)) { String message = "User with email " + newEmail + " already exists"; HttpError error = new HttpError(ErrorCode.USER_ALREADY_EXISTS, message); error.addFieldError(new HttpFieldError("email", message)); throw new ForbiddenException(error); } result.state = state; result.newEmail = newEmail; result.templates = getEmailChangedTemplates(templateName); return result; } private EmailChangedState setUserEmailGetState(String newEmail, User setUser) { if (setUser.getEmailPendingVerification() != null) { if (newEmail.equals(setUser.getEmailPendingVerification())) return EmailChangedState.NOT_CHANGED; if (newEmail.equals(setUser.getEmail())) { setUser.setEmailPendingVerification(null); setUser.setVerifyEmailRequestCode(null); setUser.setVerifyEmailRequestTime(null); return EmailChangedState.NOT_CHANGED; } setUser.setEmailPendingVerification(newEmail); return EmailChangedState.PENDING_VERIFICATION_CHANGED; } else { if (newEmail.equals(setUser.getEmail())) return EmailChangedState.NOT_CHANGED; if (setUser.isHasTemporaryEmail()) { setUser.setEmail(newEmail); setUser.setHasTemporaryEmail(false); return EmailChangedState.TEMPORARY_CHANGED; } else if (setUser.isEmailVerified()) { setUser.setEmailPendingVerification(newEmail); return EmailChangedState.VERIFIED_CHANGED; } else { setUser.setEmail(newEmail); return EmailChangedState.UNVERIFIED_CHANGED; } } } private static class SetUserEmailResult { public EmailChangedState state = EmailChangedState.NOT_CHANGED; public String newEmail = null; public EmailChangedTemplates templates = null; } private enum EmailChangedState { NOT_CHANGED, TEMPORARY_CHANGED, VERIFIED_CHANGED, UNVERIFIED_CHANGED, PENDING_VERIFICATION_CHANGED } private EmailChangedTemplates getEmailChangedTemplates( String templateName) throws BadRequestException { EmailChangedTemplates result = new EmailChangedTemplates(); List<HttpFieldError> errors = new ArrayList<>();
EmailTemplateRepository repo = AppComponents.get(
14
2023-10-24 09:36:50+00:00
16k
Spectrum3847/SpectrumTraining
src/main/java/frc/robot/swerve/Swerve.java
[ { "identifier": "Robot", "path": "src/main/java/frc/robot/Robot.java", "snippet": "public class Robot extends LoggedRobot {\n public static RobotConfig config;\n public static RobotTelemetry telemetry;\n\n /** Create a single static instance of all of your subsystems */\n public static Train...
import edu.wpi.first.math.Matrix; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.kinematics.ChassisSpeeds; import edu.wpi.first.math.kinematics.SwerveModuleState; import edu.wpi.first.math.numbers.N1; import edu.wpi.first.math.numbers.N3; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Subsystem; import frc.robot.Robot; import frc.robot.RobotTelemetry; import frc.robot.swerve.configs.MUSICDISC2023; import frc.robot.swerve.configs.NOTEBLOCK2023; import frc.spectrumLib.swerve.Drivetrain; import frc.spectrumLib.swerve.Drivetrain.DriveState; import frc.spectrumLib.swerve.Request; import frc.spectrumLib.swerve.config.SwerveConfig; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Consumer; import java.util.function.DoubleSupplier; import java.util.function.Supplier; import org.littletonrobotics.junction.Logger;
11,454
package frc.robot.swerve; public class Swerve implements Subsystem { public final SwerveConfig config;
package frc.robot.swerve; public class Swerve implements Subsystem { public final SwerveConfig config;
private final Drivetrain drivetrain;
4
2023-10-23 17:01:53+00:00
16k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/services/admin/tags/TagServiceImpl.java
[ { "identifier": "Messages", "path": "src/main/java/org/msh/etbm/commons/Messages.java", "snippet": "@Component\npublic class Messages {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(Messages.class);\n\n public static final String NOT_UNIQUE = \"NotUnique\";\n public static fi...
import org.hibernate.exception.SQLGrammarException; import org.msh.etbm.commons.Messages; import org.msh.etbm.commons.SynchronizableItem; import org.msh.etbm.commons.commands.CommandTypes; import org.msh.etbm.commons.entities.EntityServiceContext; import org.msh.etbm.commons.entities.EntityServiceImpl; import org.msh.etbm.commons.entities.ServiceResult; import org.msh.etbm.commons.entities.query.QueryBuilder; import org.msh.etbm.db.entities.Tag; import org.msh.etbm.services.cases.tag.AutoGenTagsCasesService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.validation.Errors; import javax.persistence.PersistenceException;
11,714
package org.msh.etbm.services.admin.tags; /** * Created by rmemoria on 6/1/16. */ @Service public class TagServiceImpl extends EntityServiceImpl<Tag, TagQueryParams> implements TagService { @Autowired AutoGenTagsCasesService autoGenTagsCasesService; @Override protected void buildQuery(QueryBuilder<Tag> builder, TagQueryParams queryParams) { // order by options builder.addDefaultOrderByMap(TagQueryParams.ORDERBY_NAME, "name"); builder.addOrderByMap(TagQueryParams.ORDERBY_TYPE, "classification, name"); // profiles builder.addDefaultProfile(TagQueryParams.PROFILE_DEFAULT, TagData.class); builder.addProfile(TagQueryParams.PROFILE_ITEM, SynchronizableItem.class); if (!queryParams.isIncludeDisabled()) { builder.addRestriction("active = true"); } } @Override protected void afterSave(EntityServiceContext<Tag> context, ServiceResult res) { autoGenTagsCasesService.updateCases(context.getEntity().getId()); } @Override public String getCommandType() {
package org.msh.etbm.services.admin.tags; /** * Created by rmemoria on 6/1/16. */ @Service public class TagServiceImpl extends EntityServiceImpl<Tag, TagQueryParams> implements TagService { @Autowired AutoGenTagsCasesService autoGenTagsCasesService; @Override protected void buildQuery(QueryBuilder<Tag> builder, TagQueryParams queryParams) { // order by options builder.addDefaultOrderByMap(TagQueryParams.ORDERBY_NAME, "name"); builder.addOrderByMap(TagQueryParams.ORDERBY_TYPE, "classification, name"); // profiles builder.addDefaultProfile(TagQueryParams.PROFILE_DEFAULT, TagData.class); builder.addProfile(TagQueryParams.PROFILE_ITEM, SynchronizableItem.class); if (!queryParams.isIncludeDisabled()) { builder.addRestriction("active = true"); } } @Override protected void afterSave(EntityServiceContext<Tag> context, ServiceResult res) { autoGenTagsCasesService.updateCases(context.getEntity().getId()); } @Override public String getCommandType() {
return CommandTypes.ADMIN_TAGS;
2
2023-10-23 13:47:54+00:00
16k
weibocom/rill-flow
rill-flow-dag/olympicene-traversal/src/main/java/com/weibo/rill/flow/olympicene/traversal/runners/DAGRunner.java
[ { "identifier": "Mapping", "path": "rill-flow-interfaces/src/main/java/com/weibo/rill/flow/interfaces/model/mapping/Mapping.java", "snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@Setter\n@ToString\n/**\n * 映射规则\n * 1. source 代表源集合以json path表示的值\n * 2. target 代表目标集合以json path表示的key\n *\n *...
import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.weibo.rill.flow.interfaces.model.mapping.Mapping; import com.weibo.rill.flow.olympicene.core.constant.ReservedConstant; import com.weibo.rill.flow.olympicene.core.constant.SystemConfig; import com.weibo.rill.flow.olympicene.core.helper.DAGInfoMaker; import com.weibo.rill.flow.olympicene.core.helper.DAGWalkHelper; import com.weibo.rill.flow.olympicene.core.lock.LockerKey; import com.weibo.rill.flow.olympicene.core.model.DAGSettings; import com.weibo.rill.flow.olympicene.core.model.NotifyInfo; import com.weibo.rill.flow.olympicene.core.model.dag.DAG; import com.weibo.rill.flow.olympicene.core.model.dag.DAGInfo; import com.weibo.rill.flow.olympicene.core.model.dag.DAGInvokeMsg; import com.weibo.rill.flow.olympicene.core.model.dag.DAGInvokeMsg.ExecutionInfo; import com.weibo.rill.flow.olympicene.core.model.dag.DAGStatus; import com.weibo.rill.flow.interfaces.model.resource.BaseResource; import com.weibo.rill.flow.olympicene.core.model.strategy.CallbackConfig; import com.weibo.rill.flow.olympicene.core.model.task.ExecutionResult; import com.weibo.rill.flow.interfaces.model.task.FunctionTask; import com.weibo.rill.flow.olympicene.core.runtime.DAGContextStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGInfoStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGStorageProcedure; import com.weibo.rill.flow.olympicene.traversal.constant.TraversalErrorCode; import com.weibo.rill.flow.olympicene.traversal.exception.DAGTraversalException; import com.weibo.rill.flow.olympicene.traversal.helper.Stasher; import com.weibo.rill.flow.olympicene.traversal.mappings.JSONPathInputOutputMapping; import com.weibo.rill.flow.interfaces.model.task.*; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import java.util.*; import java.util.stream.Collectors;
12,365
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.olympicene.traversal.runners; @Slf4j public class DAGRunner { private final DAGContextStorage dagContextStorage; private final DAGInfoStorage dagInfoStorage; private final DAGStorageProcedure dagStorageProcedure; @Setter private Stasher stasher; public DAGRunner(DAGContextStorage dagContextStorage, DAGInfoStorage dagInfoStorage, DAGStorageProcedure dagStorageProcedure) { this.dagContextStorage = dagContextStorage; this.dagInfoStorage = dagInfoStorage; this.dagStorageProcedure = dagStorageProcedure; } public ExecutionResult submitDAG(String executionId, DAG dag, DAGSettings settings, Map<String, Object> data, NotifyInfo notifyInfo) { ExecutionResult ret = ExecutionResult.builder().build(); dagStorageProcedure.lockAndRun(LockerKey.buildDagInfoLockName(executionId), () -> { DAGInfo currentExecutionIdDagInfo = dagInfoStorage.getBasicDAGInfo(executionId); submitValidate(executionId, dag, settings.isIgnoreExist(), currentExecutionIdDagInfo); // 任务执行过程中会频繁获取DAG // 理论上对默认context大小不做限制 默认context存入存储后 dag中定义的默认存储在后续逻辑中不会使用 // 为减少后续获DAG的大小从而减少网络开销 此处将默认context设置为null Map<String, Object> context = Maps.newHashMap(); Map<String, String> defaultContext = Optional.ofNullable(dag.getDefaultContext()).orElse(Collections.emptyMap()); defaultContext.forEach((key, value) -> context.put(key, JSONPathInputOutputMapping.parseSource(value))); Optional.ofNullable(data).ifPresent(context::putAll); ret.setContext(context); dag.setDefaultContext(null); // inputMapping/outputMapping中可能存在引用通用mapping的情况 // 此处将引用替换为实际内容 // 后续处理中存在只获取TaskInfo不获取DAG的情况 所以若不替换 则需要在每个获取TaskInfo的地方同时获取DAG // 采用空间换时间的策略 此处将引用替换为实际内容后 存储DAG的大小会变大 但可以简化后续处理的复杂度 不用每次都获取DAG // mapping中引用替换为实际内容后 后续处理将不再使用commonMapping 为减少DAG大小 此处将commonMapping设置为null handleMappingReference(1, dag.getCommonMapping(), dag.getTasks()); handleMappingReference(dag.getCommonMapping(), dag.getCallbackConfig()); dag.setCommonMapping(null); Optional.ofNullable(dag.getResources()).ifPresent(resources -> handleResources(1, resources.stream().collect(Collectors.toMap(BaseResource::getName, it -> it)), dag.getTasks())); dag.setResources(null); DAGInvokeMsg dagInvokeMsg = buildInvokeMsg(executionId, settings, notifyInfo); DAGInfo dagInfoToUpdate = new DAGInfoMaker() .dag(dag) .executionId(executionId) .dagInvokeMsg(dagInvokeMsg) .dagStatus(DAGStatus.RUNNING) .make(); ret.setDagInfo(dagInfoToUpdate); Optional.ofNullable(dagInvokeMsg) .map(DAGInvokeMsg::getExecutionRoutes) .filter(CollectionUtils::isNotEmpty) .map(it -> it.get(0)) .map(ExecutionInfo::getExecutionId) .filter(StringUtils::isNotBlank) .ifPresent(rootExecutionId -> context.putIfAbsent("flow_root_execution_id", rootExecutionId)); dagContextStorage.updateContext(executionId, context); dagInfoStorage.saveDAGInfo(executionId, dagInfoToUpdate); }); return ret; } private void handleResources(int currentDepth, Map<String, BaseResource> resourceMap, List<BaseTask> tasks) { if (MapUtils.isEmpty(resourceMap) || CollectionUtils.isEmpty(tasks)) { return; } if (currentDepth > SystemConfig.getTaskMaxDepth()) { throw new DAGTraversalException(TraversalErrorCode.DAG_ILLEGAL_STATE.getCode(), "exceed max depth"); } tasks.stream() .peek(task -> handleResources(currentDepth + 1, resourceMap, task.subTasks())) .filter(task -> task instanceof FunctionTask) .map(task -> (FunctionTask) task) .filter(functionTask -> functionTask.getResource() == null) .filter(functionTask -> StringUtils.isNotBlank(functionTask.getResourceName())) .forEach(functionTask -> {
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.olympicene.traversal.runners; @Slf4j public class DAGRunner { private final DAGContextStorage dagContextStorage; private final DAGInfoStorage dagInfoStorage; private final DAGStorageProcedure dagStorageProcedure; @Setter private Stasher stasher; public DAGRunner(DAGContextStorage dagContextStorage, DAGInfoStorage dagInfoStorage, DAGStorageProcedure dagStorageProcedure) { this.dagContextStorage = dagContextStorage; this.dagInfoStorage = dagInfoStorage; this.dagStorageProcedure = dagStorageProcedure; } public ExecutionResult submitDAG(String executionId, DAG dag, DAGSettings settings, Map<String, Object> data, NotifyInfo notifyInfo) { ExecutionResult ret = ExecutionResult.builder().build(); dagStorageProcedure.lockAndRun(LockerKey.buildDagInfoLockName(executionId), () -> { DAGInfo currentExecutionIdDagInfo = dagInfoStorage.getBasicDAGInfo(executionId); submitValidate(executionId, dag, settings.isIgnoreExist(), currentExecutionIdDagInfo); // 任务执行过程中会频繁获取DAG // 理论上对默认context大小不做限制 默认context存入存储后 dag中定义的默认存储在后续逻辑中不会使用 // 为减少后续获DAG的大小从而减少网络开销 此处将默认context设置为null Map<String, Object> context = Maps.newHashMap(); Map<String, String> defaultContext = Optional.ofNullable(dag.getDefaultContext()).orElse(Collections.emptyMap()); defaultContext.forEach((key, value) -> context.put(key, JSONPathInputOutputMapping.parseSource(value))); Optional.ofNullable(data).ifPresent(context::putAll); ret.setContext(context); dag.setDefaultContext(null); // inputMapping/outputMapping中可能存在引用通用mapping的情况 // 此处将引用替换为实际内容 // 后续处理中存在只获取TaskInfo不获取DAG的情况 所以若不替换 则需要在每个获取TaskInfo的地方同时获取DAG // 采用空间换时间的策略 此处将引用替换为实际内容后 存储DAG的大小会变大 但可以简化后续处理的复杂度 不用每次都获取DAG // mapping中引用替换为实际内容后 后续处理将不再使用commonMapping 为减少DAG大小 此处将commonMapping设置为null handleMappingReference(1, dag.getCommonMapping(), dag.getTasks()); handleMappingReference(dag.getCommonMapping(), dag.getCallbackConfig()); dag.setCommonMapping(null); Optional.ofNullable(dag.getResources()).ifPresent(resources -> handleResources(1, resources.stream().collect(Collectors.toMap(BaseResource::getName, it -> it)), dag.getTasks())); dag.setResources(null); DAGInvokeMsg dagInvokeMsg = buildInvokeMsg(executionId, settings, notifyInfo); DAGInfo dagInfoToUpdate = new DAGInfoMaker() .dag(dag) .executionId(executionId) .dagInvokeMsg(dagInvokeMsg) .dagStatus(DAGStatus.RUNNING) .make(); ret.setDagInfo(dagInfoToUpdate); Optional.ofNullable(dagInvokeMsg) .map(DAGInvokeMsg::getExecutionRoutes) .filter(CollectionUtils::isNotEmpty) .map(it -> it.get(0)) .map(ExecutionInfo::getExecutionId) .filter(StringUtils::isNotBlank) .ifPresent(rootExecutionId -> context.putIfAbsent("flow_root_execution_id", rootExecutionId)); dagContextStorage.updateContext(executionId, context); dagInfoStorage.saveDAGInfo(executionId, dagInfoToUpdate); }); return ret; } private void handleResources(int currentDepth, Map<String, BaseResource> resourceMap, List<BaseTask> tasks) { if (MapUtils.isEmpty(resourceMap) || CollectionUtils.isEmpty(tasks)) { return; } if (currentDepth > SystemConfig.getTaskMaxDepth()) { throw new DAGTraversalException(TraversalErrorCode.DAG_ILLEGAL_STATE.getCode(), "exceed max depth"); } tasks.stream() .peek(task -> handleResources(currentDepth + 1, resourceMap, task.subTasks())) .filter(task -> task instanceof FunctionTask) .map(task -> (FunctionTask) task) .filter(functionTask -> functionTask.getResource() == null) .filter(functionTask -> StringUtils.isNotBlank(functionTask.getResourceName())) .forEach(functionTask -> {
String[] values = functionTask.getResourceName().split(ReservedConstant.FUNCTION_TASK_RESOURCE_NAME_SCHEME_CONNECTOR);
1
2023-11-03 03:46:01+00:00
16k
aliyun/alibabacloud-compute-nest-saas-boost
boost.server/src/main/java/org/example/service/impl/OrderServiceImpl.java
[ { "identifier": "BaseResult", "path": "boost.common/src/main/java/org/example/common/BaseResult.java", "snippet": "@Data\npublic class BaseResult<T> implements Serializable {\n private static final long serialVersionUID = 5680133981298179266L;\n\n /**\n * Status code.\n */\n protected S...
import com.alicloud.openservices.tablestore.model.search.sort.FieldSort; import com.alicloud.openservices.tablestore.model.search.sort.Sort.Sorter; import com.alicloud.openservices.tablestore.model.search.sort.SortOrder; import com.alipay.api.AlipayApiException; import com.aliyun.computenestsupplier20210521.models.CreateServiceInstanceResponse; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.example.common.BaseResult; import org.example.common.ListResult; import org.example.common.constant.ComputeNestConstants; import org.example.common.constant.OrderOtsConstant; import org.example.common.constant.PayPeriodUnit; import org.example.common.constant.TradeStatus; import org.example.common.dataobject.OrderDO; import org.example.common.dto.OrderDTO; import org.example.common.errorinfo.ErrorInfo; import org.example.common.exception.BizException; import org.example.common.helper.BaseOtsHelper.OtsFilter; import org.example.common.helper.OrderOtsHelper; import org.example.common.helper.ServiceInstanceLifeStyleHelper; import org.example.common.helper.WalletHelper; import org.example.common.model.ServiceMetadataModel; import org.example.common.model.UserInfoModel; import org.example.common.param.CreateOrderParam; import org.example.common.param.GetOrderParam; import org.example.common.param.GetServiceCostParam; import org.example.common.param.GetServiceMetadataParam; import org.example.common.param.ListOrdersParam; import org.example.common.param.RefundOrderParam; import org.example.common.param.UpdateServiceInstanceAttributeParam; import org.example.common.utils.BeanUtil; import org.example.common.utils.DateUtil; import org.example.common.utils.JsonUtil; import org.example.common.utils.UuidUtil; import org.example.service.AlipayService; import org.example.service.OrderService; import org.example.service.ServiceInstanceLifecycleService; import org.example.service.ServiceManager; import org.springframework.beans.BeanUtils; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import static org.example.common.constant.ComputeNestConstants.PAY_PERIOD; import static org.example.common.constant.ComputeNestConstants.PAY_PERIOD_UNIT;
12,665
/* *Copyright (c) Alibaba Group; *Licensed under the Apache License, Version 2.0 (the "License"); *you may not use this file except in compliance with the License. *You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 *Unless required by applicable law or agreed to in writing, software *distributed under the License is distributed on an "AS IS" BASIS, *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *See the License for the specific language governing permissions and *limitations under the License. */ package org.example.service.impl; @Service @Slf4j public class OrderServiceImpl implements OrderService { @Resource private AlipayService alipayService; @Resource private OrderOtsHelper orderOtsHelper; @Resource private WalletHelper walletHelper; @Resource private ServiceInstanceLifecycleService serviceInstanceLifecycleService; @Resource private ServiceManager serviceManager; @Resource private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper; private static final Integer DEFAULT_RETENTION_DAYS = 15; @Override
/* *Copyright (c) Alibaba Group; *Licensed under the Apache License, Version 2.0 (the "License"); *you may not use this file except in compliance with the License. *You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 *Unless required by applicable law or agreed to in writing, software *distributed under the License is distributed on an "AS IS" BASIS, *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *See the License for the specific language governing permissions and *limitations under the License. */ package org.example.service.impl; @Service @Slf4j public class OrderServiceImpl implements OrderService { @Resource private AlipayService alipayService; @Resource private OrderOtsHelper orderOtsHelper; @Resource private WalletHelper walletHelper; @Resource private ServiceInstanceLifecycleService serviceInstanceLifecycleService; @Resource private ServiceManager serviceManager; @Resource private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper; private static final Integer DEFAULT_RETENTION_DAYS = 15; @Override
public BaseResult<String> createOrder(UserInfoModel userInfoModel, CreateOrderParam param) throws AlipayApiException {
16
2023-11-01 08:19:34+00:00
16k
daominh-studio/quick-mem
app/src/main/java/com/daominh/quickmem/ui/fragments/home/HomeFragment.java
[ { "identifier": "ClassAdapter", "path": "app/src/main/java/com/daominh/quickmem/adapter/group/ClassAdapter.java", "snippet": "public class ClassAdapter extends RecyclerView.Adapter<ClassAdapter.ClassViewHolder> {\n private final Context context;\n private final ArrayList<Group> classes;\n\n pub...
import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.daominh.quickmem.adapter.group.ClassAdapter; import com.daominh.quickmem.adapter.folder.FolderAdapter; import com.daominh.quickmem.adapter.flashcard.SetsAdapter; import com.daominh.quickmem.data.dao.FlashCardDAO; import com.daominh.quickmem.data.dao.FolderDAO; import com.daominh.quickmem.data.dao.GroupDAO; import com.daominh.quickmem.data.model.FlashCard; import com.daominh.quickmem.data.model.Folder; import com.daominh.quickmem.data.model.Group; import com.daominh.quickmem.databinding.FragmentHomeBinding; import com.daominh.quickmem.preferen.UserSharePreferences; import com.daominh.quickmem.ui.activities.create.CreateSetActivity; import com.daominh.quickmem.ui.activities.search.ViewSearchActivity; import org.jetbrains.annotations.NotNull; import java.util.ArrayList;
13,968
package com.daominh.quickmem.ui.fragments.home; public class HomeFragment extends Fragment { private FragmentHomeBinding binding;
package com.daominh.quickmem.ui.fragments.home; public class HomeFragment extends Fragment { private FragmentHomeBinding binding;
private UserSharePreferences userSharePreferences;
9
2023-11-07 16:56:39+00:00
16k
FRCTeam2910/2023CompetitionRobot-Public
src/main/java/org/frcteam2910/c2023/util/PathChooser.java
[ { "identifier": "RobotContainer", "path": "src/main/java/org/frcteam2910/c2023/RobotContainer.java", "snippet": "public class RobotContainer {\n private final PathChooser pathChooser;\n\n private final DrivetrainSubsystem drivetrainSubsystem;\n\n private final LEDSubsystem ledSubsystem;\n\n ...
import com.pathplanner.lib.PathPlannerTrajectory; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj2.command.*; import org.frcteam2910.c2023.RobotContainer; import org.frcteam2910.c2023.commands.*; import org.frcteam2910.c2023.subsystems.drivetrain.DrivetrainSubsystem; import org.frcteam2910.c2023.subsystems.intake.IntakeSubsystem; import org.frcteam2910.c2023.util.constants.ArmPoseConstants; import org.littletonrobotics.junction.Logger;
13,830
package org.frcteam2910.c2023.util; public class PathChooser { public static final double EJECTION_DISTANCE = 0.4; // Enum for auto modes private enum AutonomousMode { DRIVE_STRAIGHT, BLUE_NO_BUMP_THREE_CUBE, RED_NO_BUMP_THREE_CUBE, NO_BUMP_TWO_CUBE_BALANCE, BLUE_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE, RED_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE, BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE, RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE, BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION, RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION, RED_BUMP_THREE_CUBE, BLUE_BUMP_THREE_CUBE, RED_CHEZYBUMP_THREE_CUBE, BLUE_CHEZYBUMP_THREE_CUBE, RED_CHEZYBUMP_TWO_CUBE, BLUE_CHEZYBUMP_TWO_CUBE, BUMP_TWO_AND_A_HALF_CUBE, BLUE_BUMP_TWO_CUBE, RED_BUMP_TWO_CUBE, MIDDLE_BALANCE, MIDDLE_UP_CUBE_BALANCE, MIDDLE_DOWN_CUBE_BALANCE, NO_BUMP_EXIT_COMMUNITY, BUMP_EXIT_COMMUNITY, } // Trajectories object private final PathTrajectories trajectories; // Chooser for autonomous mode private static final SendableChooser<AutonomousMode> autonomousModeChooser = new SendableChooser<>(); // Add options to chooser public PathChooser(PathTrajectories trajectories) { this.trajectories = trajectories; // autonomousModeChooser.addOption("Drive Straight", AutonomousMode.DRIVE_STRAIGHT); autonomousModeChooser.setDefaultOption( "Blue Yoshi No Bump 3 Cube Balance", AutonomousMode.BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE); autonomousModeChooser.setDefaultOption( "Red Yoshi No Bump 3 Cube Balance", AutonomousMode.RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE); autonomousModeChooser.addOption( "Blue Yoshi No Bump 3 Cube Substation", AutonomousMode.BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION); autonomousModeChooser.addOption( "Red Yoshi No Bump 3 Cube Substation", AutonomousMode.RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION); autonomousModeChooser.addOption("Blue No Bump 3 Cube", AutonomousMode.BLUE_NO_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red No Bump 3 Cube", AutonomousMode.RED_NO_BUMP_THREE_CUBE); // autonomousModeChooser.addOption("No Bump 1 Cube Balance", AutonomousMode.NO_BUMP_ONE_CUBE_BALANCE);; autonomousModeChooser.addOption( "Blue No Bump 2.5 Cube Balance", AutonomousMode.BLUE_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE); autonomousModeChooser.addOption( "Red No Bump 2.5 Cube Balance", AutonomousMode.RED_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE); // autonomousModeChooser.addOption("Bump 1.5 Cube", AutonomousMode.BUMP_ONE_AND_A_HALF_CUBE); // autonomousModeChooser.addOption("Chezy Blue Bump 3 Cube", AutonomousMode.BLUE_CHEZYBUMP_THREE_CUBE); // autonomousModeChooser.addOption("Chezy Red Bump 3 Cube", AutonomousMode.RED_CHEZYBUMP_THREE_CUBE); // autonomousModeChooser.addOption("Chezy Blue Bump 2 Cube", AutonomousMode.BLUE_CHEZYBUMP_TWO_CUBE); // autonomousModeChooser.addOption("Chezy Red Bump 2 Cube", AutonomousMode.RED_CHEZYBUMP_TWO_CUBE); autonomousModeChooser.addOption("Blue Bump 3 Cube", AutonomousMode.BLUE_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red Bump 3 Cube", AutonomousMode.RED_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red Bump 2 Cube", AutonomousMode.RED_BUMP_TWO_CUBE); autonomousModeChooser.addOption("Blue Bump 2 Cube", AutonomousMode.BLUE_BUMP_TWO_CUBE); // autonomousModeChooser.addOption("Middle No Bump Cube Balance", AutonomousMode.MIDDLE_UP_CUBE_BALANCE); // autonomousModeChooser.addOption("Middle Bump Cube Balance", AutonomousMode.MIDDLE_DOWN_CUBE_BALANCE); autonomousModeChooser.addOption("Middle Balance", AutonomousMode.MIDDLE_BALANCE); autonomousModeChooser.addOption("No Bump Exit Community", AutonomousMode.NO_BUMP_EXIT_COMMUNITY); autonomousModeChooser.addOption("Bump Exit Community", AutonomousMode.BUMP_EXIT_COMMUNITY); }
package org.frcteam2910.c2023.util; public class PathChooser { public static final double EJECTION_DISTANCE = 0.4; // Enum for auto modes private enum AutonomousMode { DRIVE_STRAIGHT, BLUE_NO_BUMP_THREE_CUBE, RED_NO_BUMP_THREE_CUBE, NO_BUMP_TWO_CUBE_BALANCE, BLUE_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE, RED_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE, BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE, RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE, BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION, RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION, RED_BUMP_THREE_CUBE, BLUE_BUMP_THREE_CUBE, RED_CHEZYBUMP_THREE_CUBE, BLUE_CHEZYBUMP_THREE_CUBE, RED_CHEZYBUMP_TWO_CUBE, BLUE_CHEZYBUMP_TWO_CUBE, BUMP_TWO_AND_A_HALF_CUBE, BLUE_BUMP_TWO_CUBE, RED_BUMP_TWO_CUBE, MIDDLE_BALANCE, MIDDLE_UP_CUBE_BALANCE, MIDDLE_DOWN_CUBE_BALANCE, NO_BUMP_EXIT_COMMUNITY, BUMP_EXIT_COMMUNITY, } // Trajectories object private final PathTrajectories trajectories; // Chooser for autonomous mode private static final SendableChooser<AutonomousMode> autonomousModeChooser = new SendableChooser<>(); // Add options to chooser public PathChooser(PathTrajectories trajectories) { this.trajectories = trajectories; // autonomousModeChooser.addOption("Drive Straight", AutonomousMode.DRIVE_STRAIGHT); autonomousModeChooser.setDefaultOption( "Blue Yoshi No Bump 3 Cube Balance", AutonomousMode.BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE); autonomousModeChooser.setDefaultOption( "Red Yoshi No Bump 3 Cube Balance", AutonomousMode.RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_BALANCE); autonomousModeChooser.addOption( "Blue Yoshi No Bump 3 Cube Substation", AutonomousMode.BLUE_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION); autonomousModeChooser.addOption( "Red Yoshi No Bump 3 Cube Substation", AutonomousMode.RED_LONG_INTAKE_NO_BUMP_THREE_CUBE_SUBSTATION); autonomousModeChooser.addOption("Blue No Bump 3 Cube", AutonomousMode.BLUE_NO_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red No Bump 3 Cube", AutonomousMode.RED_NO_BUMP_THREE_CUBE); // autonomousModeChooser.addOption("No Bump 1 Cube Balance", AutonomousMode.NO_BUMP_ONE_CUBE_BALANCE);; autonomousModeChooser.addOption( "Blue No Bump 2.5 Cube Balance", AutonomousMode.BLUE_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE); autonomousModeChooser.addOption( "Red No Bump 2.5 Cube Balance", AutonomousMode.RED_NO_BUMP_TWO_AND_A_HALF_CUBE_BALANCE); // autonomousModeChooser.addOption("Bump 1.5 Cube", AutonomousMode.BUMP_ONE_AND_A_HALF_CUBE); // autonomousModeChooser.addOption("Chezy Blue Bump 3 Cube", AutonomousMode.BLUE_CHEZYBUMP_THREE_CUBE); // autonomousModeChooser.addOption("Chezy Red Bump 3 Cube", AutonomousMode.RED_CHEZYBUMP_THREE_CUBE); // autonomousModeChooser.addOption("Chezy Blue Bump 2 Cube", AutonomousMode.BLUE_CHEZYBUMP_TWO_CUBE); // autonomousModeChooser.addOption("Chezy Red Bump 2 Cube", AutonomousMode.RED_CHEZYBUMP_TWO_CUBE); autonomousModeChooser.addOption("Blue Bump 3 Cube", AutonomousMode.BLUE_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red Bump 3 Cube", AutonomousMode.RED_BUMP_THREE_CUBE); autonomousModeChooser.addOption("Red Bump 2 Cube", AutonomousMode.RED_BUMP_TWO_CUBE); autonomousModeChooser.addOption("Blue Bump 2 Cube", AutonomousMode.BLUE_BUMP_TWO_CUBE); // autonomousModeChooser.addOption("Middle No Bump Cube Balance", AutonomousMode.MIDDLE_UP_CUBE_BALANCE); // autonomousModeChooser.addOption("Middle Bump Cube Balance", AutonomousMode.MIDDLE_DOWN_CUBE_BALANCE); autonomousModeChooser.addOption("Middle Balance", AutonomousMode.MIDDLE_BALANCE); autonomousModeChooser.addOption("No Bump Exit Community", AutonomousMode.NO_BUMP_EXIT_COMMUNITY); autonomousModeChooser.addOption("Bump Exit Community", AutonomousMode.BUMP_EXIT_COMMUNITY); }
public Command getDriveStraight(RobotContainer container) {
0
2023-11-03 02:12:12+00:00
16k
YunaBraska/type-map
src/test/java/berlin/yuna/typemap/model/TypeMapTest.java
[ { "identifier": "TypeConversionRegister", "path": "src/main/java/berlin/yuna/typemap/config/TypeConversionRegister.java", "snippet": "public class TypeConversionRegister<S, T> {\n\n /**\n * A map where the key is the target type and the value is another map.\n * The nested map's key is the so...
import berlin.yuna.typemap.config.TypeConversionRegister; import berlin.yuna.typemap.logic.TypeConverter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.time.*; import java.util.*; import java.util.stream.Stream; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat;
14,371
@ParameterizedTest @MethodSource("typeMapProvider") void mapConvertTest(final String mapName, final TypeMapI<?> typeMap) { final Map<Integer, Date> input = new HashMap<>(); input.put(6, new Date(TEST_TIME)); typeMap.put("myKey", input); // TREE MAP assertThat(typeMap.getMap("myKey")).containsEntry(6, new Date(TEST_TIME)); assertThat(typeMap.getMap(Long.class, Instant.class, "myKey")).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap(() -> new HashMap<>(), Long.class, Instant.class, "myKey")).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap(() -> new HashMap<>(), Long.class, Instant.class, "myKey2")).isEmpty(); // KEY MAP assertThat(typeMap.getMap("myKey", () -> new HashMap<>(), Long.class, Instant.class)).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap("myKey", Long.class, Instant.class)).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap("myKey2", () -> new HashMap<>(), Long.class, Instant.class)).isEmpty(); } @ParameterizedTest @MethodSource("typeMapProvider") void jsonConvertTest(final String mapName, final TypeMapI<?> typeMap) { final Map<String, Object> input = new HashMap<>(); final Map<String, Object> innerMap = new HashMap<>(); innerMap.put("FF", asList("GG", 2, true)); input.put("AA", asList("BB", 1, true, null)); input.put("CC", new long[]{4L, 5L, 6L}); input.put("DD", innerMap); input.put("EE", "HH,II,\n"); typeMap.put("myKey", input); assertThat(typeMap.toJson("invalidKey")).isEqualTo("{}"); assertThat(typeMap.toJson("myKey")).isEqualTo("{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}"); assertThat(typeMap.toJson()).isEqualTo("{\"myKey\":{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}}"); // Encode & Decode assertThat(new TypeMap(typeMap.toJson("invalidKey")).toJson()).isEqualTo("{}"); assertThat(new ConcurrentTypeMap(typeMap.toJson("myKey")).toJson()).isEqualTo("{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}"); assertThat(new LinkedTypeMap(typeMap.toJson()).toJson()).isEqualTo("{\"myKey\":{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}}"); } @ParameterizedTest @MethodSource("typeMapProvider") void nestedKeysTest(final String mapName, final TypeMapI<?> typeMap) { final Map<String, Object> innerMap = new HashMap<>(); final UnknownClass anObject = new UnknownClass(); innerMap.put("BB", asList("11", "22")); innerMap.put("CC", new Object[]{"33", "44"}); innerMap.put("DD", anObject); innerMap.put("EE", singletonList(anObject)); innerMap.put("FF", new Object[]{anObject}); typeMap.put("AA", innerMap); assertThat(typeMap.gett(Object.class)).isEmpty(); assertThat(typeMap.gett(Object.class, (Object) null)).isEmpty(); assertThat(typeMap.gett(Object.class, new Object[]{null})).isEmpty(); assertThat(typeMap.gett(Object.class, "AA")).contains(innerMap); assertThat(typeMap.gett(Object.class, "AA", "BB")).contains(asList("11", "22")); assertThat(typeMap.gett(Object.class, "AA", "CC")).contains(new Object[]{"33", "44"}); assertThat(typeMap.gett(Object.class, "AA", "BB", 0)).contains("11"); assertThat(typeMap.gett(Object.class, "AA", "BB", 1)).contains("22"); assertThat(typeMap.gett(Object.class, "AA", "CC", 0)).contains("33"); assertThat(typeMap.gett(Object.class, "AA", "CC", 1)).contains("44"); assertThat(typeMap.gett(UnknownClass.class, "AA", "DD")).contains(anObject); assertThat(typeMap.gett(UnknownClass.class, "AA", "DD", anObject)).isEmpty(); } @Test void testDefaultMapMethods() { final String myTime = new Date(TEST_TIME).toString(); // Broken json assertThat(new TypeMap("{ broken json")).containsEntry("", "{ broken json"); assertThat(new LinkedTypeMap("{ broken json")).containsEntry("", "{ broken json"); assertThat(new ConcurrentTypeMap("{ broken json")).containsEntry("", "{ broken json"); final TypeMap map1 = new TypeMap().putt("myKey", myTime); final LinkedTypeMap map2 = new LinkedTypeMap().putt("myKey", myTime); final ConcurrentTypeMap map3 = new ConcurrentTypeMap().putt("myKey", myTime); // Get assertThat(map1.get("myKey")).isNotNull(); assertThat(map2.get("myKey")).isNotNull(); assertThat(map3.get("myKey")).isNotNull(); } @Test void argsTest() { final String[] cliArgs = {" myCommand1 myCommand2 --help -v2=\"true\" -v=\"true\" -v=\"true\" --verbose=\"true\" -DArgs=\"true\" -param 42 54 -DArgList=\"item 1\" --DArgList=\"item 2\" -v2=\"false\" --DArgList=\"-item 3\" "}; final TypeMap map1 = new TypeMap(cliArgs); final LinkedTypeMap map2 = new LinkedTypeMap(cliArgs); final ConcurrentTypeMap map3 = new ConcurrentTypeMap(cliArgs); for (final TypeMapI<?> map : new TypeMapI<?>[]{map1, map2, map3}) { assertThat(map.get("help", Boolean.class)).isTrue(); assertThat(map.get("v", Boolean.class)).isTrue(); assertThat(map.get("v2", Boolean.class)).isTrue(); assertThat(map.get("verbose", Boolean.class)).isTrue(); assertThat(map.get("DArgs", Boolean.class)).isTrue(); assertThat(map.getList("param", Integer.class)).containsExactly(42, 54); assertThat(map.getList("v2", Boolean.class)).containsExactly(true, false); assertThat(map.getList("DArgList")).containsExactly("item 1", "item 2", "-item 3"); assertThat(map.getList("DArgList", String.class)).containsExactly("item 1", "item 2", "-item 3"); } } @Test void showCaseTest() { // Converter final Date date = TypeConverter.convertObj("Sat Nov 11 16:12:29 CET 2023", Date.class); // TypeMap final TypeMap map = new TypeMap(); map.put("key", new Date(TEST_TIME)); final Optional<Calendar> calendar = map.gett("key", Calendar.class); final Optional<LocalDateTime> localDateTime = map.gett("key", LocalDateTime.class); final Optional<ZonedDateTime> zonedDateTime = map.gett("key", ZonedDateTime.class); // Register custom conversion
package berlin.yuna.typemap.model; class TypeMapTest { public static final long TEST_TIME = 1800000000000L; @BeforeEach void setUp() { System.getProperties().setProperty("user.timezone", "UTC"); TimeZone.setDefault(null); } static Stream<Arguments> typeMapProvider() { return Stream.of( Arguments.of(TypeMap.class.getSimpleName(), new TypeMap()), Arguments.of(LinkedTypeMap.class.getSimpleName(), new LinkedTypeMap()), Arguments.of(ConcurrentTypeMap.class.getSimpleName(), new ConcurrentTypeMap()) ); } @ParameterizedTest(name = "[{index}] [{0}]") @MethodSource("typeMapProvider") void simpleConvertTest(final String mapName, final TypeMapI<?> typeMap) { final String myTime = new Date(TEST_TIME).toString(); typeMap.addd("myKey", myTime); // VALIDATIONS assertThat(typeMap.typeList()).isEmpty(); assertThat(typeMap.typeMap()).isPresent(); // TREE MAP assertThat(typeMap.gett(Instant.class, "myKey")).contains(Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.gett(LocalTime.class, "myKey")).contains(LocalDateTime.ofInstant(Instant.ofEpochMilli(TEST_TIME), ZoneId.systemDefault()).toLocalTime()); assertThat(typeMap.get(OffsetDateTime.class, "myKey")).isEqualTo(OffsetDateTime.ofInstant(Instant.ofEpochMilli(TEST_TIME), ZoneId.systemDefault())); // KEY MAP assertThat(typeMap.gett("myKey", Instant.class)).contains(Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.gett("myKey", LocalTime.class)).contains(LocalDateTime.ofInstant(Instant.ofEpochMilli(TEST_TIME), ZoneId.systemDefault()).toLocalTime()); assertThat(typeMap.get("myKey", OffsetDateTime.class)).isEqualTo(OffsetDateTime.ofInstant(Instant.ofEpochMilli(TEST_TIME), ZoneId.systemDefault())); } @ParameterizedTest @MethodSource("typeMapProvider") void enumConvertTest(final String mapName, final TypeMapI<?> typeMap) { typeMap.put("myKey", "BB"); assertThat(typeMap.gett(TestEnum.class, "myKey")).contains(TestEnum.BB); } @ParameterizedTest @MethodSource("typeMapProvider") void collectionConvertTest(final String mapName, final TypeMapI<?> typeMap) { final String myTime = new Date(TEST_TIME).toString(); typeMap.putt("myKey1", myTime); typeMap.put("myKey2", new String[]{"1", "2", "3"}); // TREE MAP final List<Instant> instantList1 = typeMap.getList(ArrayList::new, Instant.class, "myKey1"); final List<Integer> integerList1 = typeMap.getList(ArrayList::new, Integer.class, "myKey2"); final List<Float> floatList1 = typeMap.getList(ArrayList::new, Float.class, "myKey2"); final Double[] doubleArray1 = typeMap.getArray(new Double[0], Double.class, "myKey2"); final Long[] longArray1 = typeMap.getArray(Long[]::new, Long.class, "myKey2"); assertThat(instantList1).isNotEmpty(); assertThat(integerList1).isNotEmpty().containsExactly(1, 2, 3); assertThat(floatList1).isNotEmpty().containsExactly(1f, 2f, 3f); assertThat(doubleArray1).isNotEmpty().containsExactly(1d, 2d, 3d); assertThat(longArray1).isNotEmpty().containsExactly(1L, 2L, 3L); assertThat(typeMap.getList("myKey2")).isNotEmpty().containsExactly("1", "2", "3"); assertThat(typeMap.getList(Integer.class, "myKey2")).isNotEmpty().containsExactly(1, 2, 3); // KEY MAP final List<Instant> instantList2 = typeMap.getList("myKey1", ArrayList::new, Instant.class); final List<Integer> integerList2 = typeMap.getList("myKey2", ArrayList::new, Integer.class); final List<Float> floatList2 = typeMap.getList("myKey2", ArrayList::new, Float.class); final Double[] doubleArray2 = typeMap.getArray("myKey2", new Double[0], Double.class); final Long[] longArray2 = typeMap.getArray("myKey2", Long[]::new, Long.class); assertThat(instantList2).isNotEmpty(); assertThat(integerList2).isNotEmpty().containsExactly(1, 2, 3); assertThat(floatList2).isNotEmpty().containsExactly(1f, 2f, 3f); assertThat(doubleArray2).isNotEmpty().containsExactly(1d, 2d, 3d); assertThat(longArray2).isNotEmpty().containsExactly(1L, 2L, 3L); assertThat(typeMap.getList("myKey2", Integer.class)).isNotEmpty().containsExactly(1, 2, 3); } @ParameterizedTest @MethodSource("typeMapProvider") void mapConvertTest(final String mapName, final TypeMapI<?> typeMap) { final Map<Integer, Date> input = new HashMap<>(); input.put(6, new Date(TEST_TIME)); typeMap.put("myKey", input); // TREE MAP assertThat(typeMap.getMap("myKey")).containsEntry(6, new Date(TEST_TIME)); assertThat(typeMap.getMap(Long.class, Instant.class, "myKey")).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap(() -> new HashMap<>(), Long.class, Instant.class, "myKey")).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap(() -> new HashMap<>(), Long.class, Instant.class, "myKey2")).isEmpty(); // KEY MAP assertThat(typeMap.getMap("myKey", () -> new HashMap<>(), Long.class, Instant.class)).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap("myKey", Long.class, Instant.class)).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap("myKey2", () -> new HashMap<>(), Long.class, Instant.class)).isEmpty(); } @ParameterizedTest @MethodSource("typeMapProvider") void jsonConvertTest(final String mapName, final TypeMapI<?> typeMap) { final Map<String, Object> input = new HashMap<>(); final Map<String, Object> innerMap = new HashMap<>(); innerMap.put("FF", asList("GG", 2, true)); input.put("AA", asList("BB", 1, true, null)); input.put("CC", new long[]{4L, 5L, 6L}); input.put("DD", innerMap); input.put("EE", "HH,II,\n"); typeMap.put("myKey", input); assertThat(typeMap.toJson("invalidKey")).isEqualTo("{}"); assertThat(typeMap.toJson("myKey")).isEqualTo("{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}"); assertThat(typeMap.toJson()).isEqualTo("{\"myKey\":{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}}"); // Encode & Decode assertThat(new TypeMap(typeMap.toJson("invalidKey")).toJson()).isEqualTo("{}"); assertThat(new ConcurrentTypeMap(typeMap.toJson("myKey")).toJson()).isEqualTo("{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}"); assertThat(new LinkedTypeMap(typeMap.toJson()).toJson()).isEqualTo("{\"myKey\":{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}}"); } @ParameterizedTest @MethodSource("typeMapProvider") void nestedKeysTest(final String mapName, final TypeMapI<?> typeMap) { final Map<String, Object> innerMap = new HashMap<>(); final UnknownClass anObject = new UnknownClass(); innerMap.put("BB", asList("11", "22")); innerMap.put("CC", new Object[]{"33", "44"}); innerMap.put("DD", anObject); innerMap.put("EE", singletonList(anObject)); innerMap.put("FF", new Object[]{anObject}); typeMap.put("AA", innerMap); assertThat(typeMap.gett(Object.class)).isEmpty(); assertThat(typeMap.gett(Object.class, (Object) null)).isEmpty(); assertThat(typeMap.gett(Object.class, new Object[]{null})).isEmpty(); assertThat(typeMap.gett(Object.class, "AA")).contains(innerMap); assertThat(typeMap.gett(Object.class, "AA", "BB")).contains(asList("11", "22")); assertThat(typeMap.gett(Object.class, "AA", "CC")).contains(new Object[]{"33", "44"}); assertThat(typeMap.gett(Object.class, "AA", "BB", 0)).contains("11"); assertThat(typeMap.gett(Object.class, "AA", "BB", 1)).contains("22"); assertThat(typeMap.gett(Object.class, "AA", "CC", 0)).contains("33"); assertThat(typeMap.gett(Object.class, "AA", "CC", 1)).contains("44"); assertThat(typeMap.gett(UnknownClass.class, "AA", "DD")).contains(anObject); assertThat(typeMap.gett(UnknownClass.class, "AA", "DD", anObject)).isEmpty(); } @Test void testDefaultMapMethods() { final String myTime = new Date(TEST_TIME).toString(); // Broken json assertThat(new TypeMap("{ broken json")).containsEntry("", "{ broken json"); assertThat(new LinkedTypeMap("{ broken json")).containsEntry("", "{ broken json"); assertThat(new ConcurrentTypeMap("{ broken json")).containsEntry("", "{ broken json"); final TypeMap map1 = new TypeMap().putt("myKey", myTime); final LinkedTypeMap map2 = new LinkedTypeMap().putt("myKey", myTime); final ConcurrentTypeMap map3 = new ConcurrentTypeMap().putt("myKey", myTime); // Get assertThat(map1.get("myKey")).isNotNull(); assertThat(map2.get("myKey")).isNotNull(); assertThat(map3.get("myKey")).isNotNull(); } @Test void argsTest() { final String[] cliArgs = {" myCommand1 myCommand2 --help -v2=\"true\" -v=\"true\" -v=\"true\" --verbose=\"true\" -DArgs=\"true\" -param 42 54 -DArgList=\"item 1\" --DArgList=\"item 2\" -v2=\"false\" --DArgList=\"-item 3\" "}; final TypeMap map1 = new TypeMap(cliArgs); final LinkedTypeMap map2 = new LinkedTypeMap(cliArgs); final ConcurrentTypeMap map3 = new ConcurrentTypeMap(cliArgs); for (final TypeMapI<?> map : new TypeMapI<?>[]{map1, map2, map3}) { assertThat(map.get("help", Boolean.class)).isTrue(); assertThat(map.get("v", Boolean.class)).isTrue(); assertThat(map.get("v2", Boolean.class)).isTrue(); assertThat(map.get("verbose", Boolean.class)).isTrue(); assertThat(map.get("DArgs", Boolean.class)).isTrue(); assertThat(map.getList("param", Integer.class)).containsExactly(42, 54); assertThat(map.getList("v2", Boolean.class)).containsExactly(true, false); assertThat(map.getList("DArgList")).containsExactly("item 1", "item 2", "-item 3"); assertThat(map.getList("DArgList", String.class)).containsExactly("item 1", "item 2", "-item 3"); } } @Test void showCaseTest() { // Converter final Date date = TypeConverter.convertObj("Sat Nov 11 16:12:29 CET 2023", Date.class); // TypeMap final TypeMap map = new TypeMap(); map.put("key", new Date(TEST_TIME)); final Optional<Calendar> calendar = map.gett("key", Calendar.class); final Optional<LocalDateTime> localDateTime = map.gett("key", LocalDateTime.class); final Optional<ZonedDateTime> zonedDateTime = map.gett("key", ZonedDateTime.class); // Register custom conversion
TypeConversionRegister.registerTypeConvert(UnknownClass.class, Double.class, source -> 99d);
0
2023-11-09 14:40:13+00:00
16k
estkme-group/InfiLPA
core/src/main/java/com/infineon/esim/lpa/core/worker/remote/HandleNotificationsWorker.java
[ { "identifier": "ListNotificationResponse", "path": "messages/src/main/java/com/gsma/sgp/messages/rspdefinitions/ListNotificationResponse.java", "snippet": "public class ListNotificationResponse implements BerType, Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic byte[] c...
import com.infineon.esim.lpa.core.es10.Es10Interface; import com.infineon.esim.lpa.core.es10.definitions.NotificationEvents; import com.infineon.esim.lpa.core.es9plus.Es9PlusInterface; import com.infineon.esim.util.Log; import java.util.List; import com.beanit.jasn1.ber.types.string.BerUTF8String; import com.gsma.sgp.messages.rspdefinitions.ListNotificationResponse; import com.gsma.sgp.messages.rspdefinitions.NotificationMetadata; import com.gsma.sgp.messages.rspdefinitions.NotificationSentResponse; import com.gsma.sgp.messages.rspdefinitions.PendingNotification; import com.gsma.sgp.messages.rspdefinitions.RetrieveNotificationsListResponse; import com.infineon.esim.lpa.core.dtos.result.local.NotificationSentResult;
13,855
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.worker.remote; public class HandleNotificationsWorker { private static final String TAG = HandleNotificationsWorker.class.getName(); private final Es10Interface es10Interface; private final Es9PlusInterface es9PlusInterface; public HandleNotificationsWorker(Es10Interface es10Interface, Es9PlusInterface es9PlusInterface) { this.es10Interface = es10Interface; this.es9PlusInterface = es9PlusInterface; } public boolean handleNotifications() throws Exception { Log.debug(TAG, "Handling notifications..."); // ES10: Get list of notifications from eUICC ListNotificationResponse listNotificationResponse = es10Interface.es10b_listNotification(NotificationEvents.ALL); if(listNotificationResponse.getNotificationMetadataList() == null || listNotificationResponse.getNotificationMetadataList().getNotificationMetadata() == null) { Log.error(TAG, "Error: NotificationMetadataList is null."); return false; }
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.worker.remote; public class HandleNotificationsWorker { private static final String TAG = HandleNotificationsWorker.class.getName(); private final Es10Interface es10Interface; private final Es9PlusInterface es9PlusInterface; public HandleNotificationsWorker(Es10Interface es10Interface, Es9PlusInterface es9PlusInterface) { this.es10Interface = es10Interface; this.es9PlusInterface = es9PlusInterface; } public boolean handleNotifications() throws Exception { Log.debug(TAG, "Handling notifications..."); // ES10: Get list of notifications from eUICC ListNotificationResponse listNotificationResponse = es10Interface.es10b_listNotification(NotificationEvents.ALL); if(listNotificationResponse.getNotificationMetadataList() == null || listNotificationResponse.getNotificationMetadataList().getNotificationMetadata() == null) { Log.error(TAG, "Error: NotificationMetadataList is null."); return false; }
List<NotificationMetadata> notificationMetadataList = listNotificationResponse.getNotificationMetadataList().getNotificationMetadata();
1
2023-11-06 02:41:13+00:00
16k
CxyJerry/pilipala
src/main/java/com/jerry/pilipala/domain/vod/service/impl/VodServiceImpl.java
[ { "identifier": "UserInfoBO", "path": "src/main/java/com/jerry/pilipala/application/bo/UserInfoBO.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class UserInfoBO {\n private String uid;\n private String roleId;\n private List<String> permissionIdList;\n}" }, { "identifier": ...
import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.lang.Snowflake; import cn.hutool.core.util.IdUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.jerry.pilipala.application.bo.UserInfoBO; import com.jerry.pilipala.application.dto.PreUploadDTO; import com.jerry.pilipala.application.dto.VideoPostDTO; import com.jerry.pilipala.application.vo.bvod.BVodVO; import com.jerry.pilipala.application.vo.bvod.PreviewBVodVO; import com.jerry.pilipala.application.vo.user.PreviewUserVO; import com.jerry.pilipala.application.vo.vod.*; import com.jerry.pilipala.domain.common.template.MessageTrigger; import com.jerry.pilipala.domain.message.service.MessageService; import com.jerry.pilipala.domain.user.entity.mongo.Permission; import com.jerry.pilipala.domain.user.entity.mongo.User; import com.jerry.pilipala.domain.user.entity.neo4j.UserEntity; import com.jerry.pilipala.domain.user.repository.UserEntityRepository; import com.jerry.pilipala.domain.vod.entity.mongo.distribute.Quality; import com.jerry.pilipala.domain.vod.entity.mongo.distribute.VodDistributeInfo; import com.jerry.pilipala.domain.vod.entity.mongo.event.VodHandleActionEvent; import com.jerry.pilipala.domain.vod.entity.mongo.event.VodHandleActionRecord; import com.jerry.pilipala.domain.vod.entity.mongo.statitics.VodStatistics; import com.jerry.pilipala.domain.vod.entity.mongo.thumbnails.Thumbnails; import com.jerry.pilipala.domain.vod.entity.mongo.thumbnails.VodThumbnails; import com.jerry.pilipala.domain.vod.entity.mongo.vod.BVod; import com.jerry.pilipala.domain.vod.entity.mongo.vod.Vod; import com.jerry.pilipala.domain.vod.entity.mongo.vod.VodInfo; import com.jerry.pilipala.domain.vod.entity.mongo.vod.VodProfiles; import com.jerry.pilipala.domain.vod.entity.neo4j.VodInfoEntity; import com.jerry.pilipala.domain.vod.repository.VodInfoRepository; import com.jerry.pilipala.domain.vod.service.FileService; import com.jerry.pilipala.domain.vod.service.VodService; import com.jerry.pilipala.domain.vod.service.media.UGCSchema; import com.jerry.pilipala.domain.vod.service.media.encoder.Encoder; import com.jerry.pilipala.domain.vod.service.media.profiles.Profile; import com.jerry.pilipala.infrastructure.common.errors.BusinessException; import com.jerry.pilipala.infrastructure.common.response.StandardResponse; import com.jerry.pilipala.infrastructure.enums.ActionStatusEnum; import com.jerry.pilipala.infrastructure.enums.Qn; import com.jerry.pilipala.infrastructure.enums.VodHandleActionEnum; import com.jerry.pilipala.infrastructure.enums.VodStatusEnum; import com.jerry.pilipala.infrastructure.enums.message.TemplateNameEnum; import com.jerry.pilipala.infrastructure.enums.redis.VodCacheKeyEnum; import com.jerry.pilipala.infrastructure.enums.video.Resolution; import com.jerry.pilipala.infrastructure.utils.JsonHelper; import com.jerry.pilipala.infrastructure.utils.Page; import com.jerry.pilipala.infrastructure.utils.SecurityTool; import lombok.extern.slf4j.Slf4j; import net.bramp.ffmpeg.FFmpeg; import net.bramp.ffmpeg.FFmpegExecutor; import net.bramp.ffmpeg.FFprobe; import net.bramp.ffmpeg.builder.FFmpegBuilder; import net.bramp.ffmpeg.builder.FFmpegOutputBuilder; import net.bramp.ffmpeg.probe.FFmpegFormat; import net.bramp.ffmpeg.probe.FFmpegProbeResult; import org.apache.commons.lang3.StringUtils; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationEventPublisher; import org.springframework.core.io.InputStreamResource; import org.springframework.core.task.TaskExecutor; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.time.Instant; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
12,215
package com.jerry.pilipala.domain.vod.service.impl; @Slf4j @Service public class VodServiceImpl implements VodService { private final FFprobe fFprobe; private final FFmpeg fFmpeg; private final MongoTemplate mongoTemplate; private final RedisTemplate<String, Object> redisTemplate; private final Snowflake snowflake = IdUtil.getSnowflake(); private final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); private final ApplicationEventPublisher applicationEventPublisher; private final UGCSchema ugcSchema; private final TaskExecutor taskExecutor; private final VodInfoRepository vodInfoRepository; private final UserEntityRepository userEntityRepository; private final JsonHelper jsonHelper; private final FileService fileService;
package com.jerry.pilipala.domain.vod.service.impl; @Slf4j @Service public class VodServiceImpl implements VodService { private final FFprobe fFprobe; private final FFmpeg fFmpeg; private final MongoTemplate mongoTemplate; private final RedisTemplate<String, Object> redisTemplate; private final Snowflake snowflake = IdUtil.getSnowflake(); private final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); private final ApplicationEventPublisher applicationEventPublisher; private final UGCSchema ugcSchema; private final TaskExecutor taskExecutor; private final VodInfoRepository vodInfoRepository; private final UserEntityRepository userEntityRepository; private final JsonHelper jsonHelper; private final FileService fileService;
private final MessageTrigger messageTrigger;
6
2023-11-03 10:05:02+00:00
16k
giteecode/oaSystemPublic
src/main/java/cn/gson/oasys/controller/inform/InformManageController.java
[ { "identifier": "BindingResultVOUtil", "path": "src/main/java/cn/gson/oasys/common/formValid/BindingResultVOUtil.java", "snippet": "public class BindingResultVOUtil {\n /**\n * 表单验证,返回形式ResultVO\n *\n * @param br\n * @return\n */\n public static ResultVO hasErrors(BindingResult...
import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttribute; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.gson.oasys.common.formValid.BindingResultVOUtil; import cn.gson.oasys.common.formValid.MapToList; import cn.gson.oasys.common.formValid.ResultEnum; import cn.gson.oasys.common.formValid.ResultVO; import cn.gson.oasys.mappers.NoticeMapper; import cn.gson.oasys.model.dao.informdao.InformDao; import cn.gson.oasys.model.dao.informdao.InformRelationDao; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.DeptDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.entity.notice.NoticeUserRelation; import cn.gson.oasys.model.entity.notice.NoticeVO; import cn.gson.oasys.model.entity.notice.NoticesList; import cn.gson.oasys.model.entity.system.SystemMenu; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User; import cn.gson.oasys.services.inform.InformRelationService; import cn.gson.oasys.services.inform.InformService;
13,974
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private StatusDao statusDao; @Autowired private TypeDao typeDao; @Autowired private InformDao informDao; @Autowired private InformService informService; @Autowired private UserDao uDao; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired private InformRelationService informrelationservice; @Autowired private NoticeMapper nm; /** * 通知管理面板 * * @return */ @RequestMapping("infrommanage") public String inform(@RequestParam(value = "page", defaultValue = "0") int page,@SessionAttribute("userId") Long userId,Model model) { Page<NoticesList> page2 = informService.pageThis(page,userId); List<NoticesList> noticeList=page2.getContent(); List<Map<String, Object>> list=informService.fengZhuang(noticeList); model.addAttribute("list", list); model.addAttribute("page", page2); //设置变量,需要load的url; model.addAttribute("url", "infrommanagepaging"); return "inform/informmanage"; } @RequestMapping("forwardother") public String forwardOther(@SessionAttribute("userId")Long userId,@RequestParam(value="noticeId")Long noticeId){ List<User> users=uDao.findByFatherId(userId); NoticesList nl=informDao.findOne(noticeId); List<NoticeUserRelation> nurs=new ArrayList<>(); for (User user : users) { nurs.add(new NoticeUserRelation(nl, user, false)); } informrelationservice.saves(nurs); return "redirect:/infromlist"; } // demo // @RequestMapping("cccc") // public @ResponseBody Page<NoticesList> ddd(@RequestParam(value = "page", defaultValue = "0") int page, // @RequestParam(value = "size", defaultValue = "10") int size, // @RequestParam(value = "baseKey", required = false) String baseKey, @SessionAttribute("userId") Long userId, // Model model) { // Page<NoticesList> page2 = informService.pageThis(page, size, userId,baseKey,null,null,null); // List<NoticesList> noticeList=page2.getContent(); // Long sum=page2.getTotalElements(); // int size2=page2.getSize(); // int pages=page2.getTotalPages(); // int number=page2.getNumber(); // model.addAttribute("list", noticeList); // model.addAttribute("page", page2); // return page2; // List<NoticesList> noticeList=informDao.findByUserId(userId); // List<NoticesList> // noticeList=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // true); // List<NoticesList> // noticeList2=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // false); // noticeList.addAll(noticeList2); // List<Map<String, Object>> list=informService.fengZhuang(noticeList); // model.addAttribute("list",list); // } /** * 通知管理删除 */ @RequestMapping("infromdelete") public String infromDelete(HttpSession session, HttpServletRequest req) { Long noticeId = Long.parseLong(req.getParameter("id")); Long userId = Long.parseLong(session.getAttribute("userId") + ""); NoticesList notice = informDao.findOne(noticeId); if (!Objects.equals(userId, notice.getUserId())) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } System.out.println(noticeId); informService.deleteOne(noticeId); return "redirect:/infrommanage"; } /** * 通知列表删除 */ @RequestMapping("informlistdelete") public String informListDelete(HttpServletRequest req, HttpSession session) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); Long noticeId = Long.parseLong(req.getParameter("id")); NoticeUserRelation relation = informrelationDao.findByUserIdAndNoticeId(uDao.findOne(userId), informDao.findOne(noticeId)); if (Objects.isNull(relation)) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } informrelationservice.deleteOne(relation); return "forward:/infromlist"; } /** * 通知列表 * * @return */ @RequestMapping("infromlist") public String infromList(HttpSession session, HttpServletRequest req, Model model, @RequestParam(value="pageNum",defaultValue="1") int page) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); PageHelper.startPage(page, 10); List<Map<String, Object>> list = nm.findMyNotice(userId); PageInfo<Map<String, Object>> pageinfo=new PageInfo<Map<String, Object>>(list); List<Map<String, Object>> list2=informrelationservice.setList(list); for (Map<String, Object> map : list2) { System.out.println(map); } model.addAttribute("url", "informlistpaging"); model.addAttribute("list", list2); model.addAttribute("page", pageinfo); System.out.println(pageinfo); return "inform/informlist"; } /** * 编辑通知界面 */ @RequestMapping("informedit") public String infromEdit(HttpServletRequest req, HttpSession session, Model model) { session.removeAttribute("noticeId");
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private StatusDao statusDao; @Autowired private TypeDao typeDao; @Autowired private InformDao informDao; @Autowired private InformService informService; @Autowired private UserDao uDao; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired private InformRelationService informrelationservice; @Autowired private NoticeMapper nm; /** * 通知管理面板 * * @return */ @RequestMapping("infrommanage") public String inform(@RequestParam(value = "page", defaultValue = "0") int page,@SessionAttribute("userId") Long userId,Model model) { Page<NoticesList> page2 = informService.pageThis(page,userId); List<NoticesList> noticeList=page2.getContent(); List<Map<String, Object>> list=informService.fengZhuang(noticeList); model.addAttribute("list", list); model.addAttribute("page", page2); //设置变量,需要load的url; model.addAttribute("url", "infrommanagepaging"); return "inform/informmanage"; } @RequestMapping("forwardother") public String forwardOther(@SessionAttribute("userId")Long userId,@RequestParam(value="noticeId")Long noticeId){ List<User> users=uDao.findByFatherId(userId); NoticesList nl=informDao.findOne(noticeId); List<NoticeUserRelation> nurs=new ArrayList<>(); for (User user : users) { nurs.add(new NoticeUserRelation(nl, user, false)); } informrelationservice.saves(nurs); return "redirect:/infromlist"; } // demo // @RequestMapping("cccc") // public @ResponseBody Page<NoticesList> ddd(@RequestParam(value = "page", defaultValue = "0") int page, // @RequestParam(value = "size", defaultValue = "10") int size, // @RequestParam(value = "baseKey", required = false) String baseKey, @SessionAttribute("userId") Long userId, // Model model) { // Page<NoticesList> page2 = informService.pageThis(page, size, userId,baseKey,null,null,null); // List<NoticesList> noticeList=page2.getContent(); // Long sum=page2.getTotalElements(); // int size2=page2.getSize(); // int pages=page2.getTotalPages(); // int number=page2.getNumber(); // model.addAttribute("list", noticeList); // model.addAttribute("page", page2); // return page2; // List<NoticesList> noticeList=informDao.findByUserId(userId); // List<NoticesList> // noticeList=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // true); // List<NoticesList> // noticeList2=informDao.findByUserIdAndTopOrderByModifyTimeDesc(userId, // false); // noticeList.addAll(noticeList2); // List<Map<String, Object>> list=informService.fengZhuang(noticeList); // model.addAttribute("list",list); // } /** * 通知管理删除 */ @RequestMapping("infromdelete") public String infromDelete(HttpSession session, HttpServletRequest req) { Long noticeId = Long.parseLong(req.getParameter("id")); Long userId = Long.parseLong(session.getAttribute("userId") + ""); NoticesList notice = informDao.findOne(noticeId); if (!Objects.equals(userId, notice.getUserId())) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } System.out.println(noticeId); informService.deleteOne(noticeId); return "redirect:/infrommanage"; } /** * 通知列表删除 */ @RequestMapping("informlistdelete") public String informListDelete(HttpServletRequest req, HttpSession session) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); Long noticeId = Long.parseLong(req.getParameter("id")); NoticeUserRelation relation = informrelationDao.findByUserIdAndNoticeId(uDao.findOne(userId), informDao.findOne(noticeId)); if (Objects.isNull(relation)) { System.out.println("权限不匹配,不能删除"); return "redirect:/notlimit"; } informrelationservice.deleteOne(relation); return "forward:/infromlist"; } /** * 通知列表 * * @return */ @RequestMapping("infromlist") public String infromList(HttpSession session, HttpServletRequest req, Model model, @RequestParam(value="pageNum",defaultValue="1") int page) { Long userId = Long.parseLong(session.getAttribute("userId") + ""); PageHelper.startPage(page, 10); List<Map<String, Object>> list = nm.findMyNotice(userId); PageInfo<Map<String, Object>> pageinfo=new PageInfo<Map<String, Object>>(list); List<Map<String, Object>> list2=informrelationservice.setList(list); for (Map<String, Object> map : list2) { System.out.println(map); } model.addAttribute("url", "informlistpaging"); model.addAttribute("list", list2); model.addAttribute("page", pageinfo); System.out.println(pageinfo); return "inform/informlist"; } /** * 编辑通知界面 */ @RequestMapping("informedit") public String infromEdit(HttpServletRequest req, HttpSession session, Model model) { session.removeAttribute("noticeId");
List<SystemTypeList> typeList = typeDao.findByTypeModel("inform");
16
2023-11-03 02:29:57+00:00
16k
ballerina-platform/module-ballerina-data-xmldata
native/src/main/java/io/ballerina/stdlib/data/xmldata/xml/XmlParser.java
[ { "identifier": "FromString", "path": "native/src/main/java/io/ballerina/stdlib/data/xmldata/FromString.java", "snippet": "public class FromString {\n\n public static Object fromStringWithType(BString string, BTypedesc typed) {\n Type expType = typed.getDescribingType();\n\n try {\n ...
import io.ballerina.runtime.api.PredefinedTypes; import io.ballerina.runtime.api.TypeTags; import io.ballerina.runtime.api.creators.TypeCreator; import io.ballerina.runtime.api.creators.ValueCreator; import io.ballerina.runtime.api.flags.SymbolFlags; import io.ballerina.runtime.api.types.ArrayType; import io.ballerina.runtime.api.types.Field; import io.ballerina.runtime.api.types.MapType; import io.ballerina.runtime.api.types.RecordType; import io.ballerina.runtime.api.types.Type; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.utils.TypeUtils; import io.ballerina.runtime.api.values.BArray; import io.ballerina.runtime.api.values.BError; import io.ballerina.runtime.api.values.BMap; import io.ballerina.runtime.api.values.BString; import io.ballerina.stdlib.data.xmldata.FromString; import io.ballerina.stdlib.data.xmldata.utils.Constants; import io.ballerina.stdlib.data.xmldata.utils.DataUtils; import io.ballerina.stdlib.data.xmldata.utils.DiagnosticErrorCode; import io.ballerina.stdlib.data.xmldata.utils.DiagnosticLog; import java.io.Reader; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.Stack; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import static javax.xml.stream.XMLStreamConstants.CDATA; import static javax.xml.stream.XMLStreamConstants.CHARACTERS; import static javax.xml.stream.XMLStreamConstants.COMMENT; import static javax.xml.stream.XMLStreamConstants.DTD; import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; import static javax.xml.stream.XMLStreamConstants.PROCESSING_INSTRUCTION; import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
11,036
private void handleXMLStreamException(Exception e) { String reason = e.getCause() == null ? e.getMessage() : e.getCause().getMessage(); if (reason == null) { throw DiagnosticLog.getXmlError(PARSE_ERROR); } throw DiagnosticLog.getXmlError(PARSE_ERROR_PREFIX + reason); } public Object parse(Type type, XmlParserData xmlParserData) { if (type.getTag() != TypeTags.RECORD_TYPE_TAG) { throw DiagnosticLog.error(DiagnosticErrorCode.INVALID_TYPE, Constants.RECORD, type.getName()); } xmlParserData.rootRecord = (RecordType) type; Object result = parse(xmlParserData); reset(xmlParserData); return result; } private void reset(XmlParserData xmlParserData) { xmlParserData.fieldHierarchy.clear(); xmlParserData.attributeHierarchy.clear(); xmlParserData.restTypes.clear(); xmlParserData.nodesStack.clear(); xmlParserData.parents.clear(); xmlParserData.siblings.clear(); xmlParserData.recordTypeStack.clear(); xmlParserData.restFieldsPoints.clear(); } public Object parse(XmlParserData xmlParserData) { try { parseRootElement(xmlStreamReader, xmlParserData); boolean readNext = false; int next; while (xmlStreamReader.hasNext()) { if (readNext) { next = xmlStreamReader.getEventType(); } else { next = xmlStreamReader.next(); } readNext = parseXmlElements(next, xmlParserData); } } catch (NumberFormatException e) { throw DiagnosticLog.getXmlError(PARSE_ERROR_PREFIX + e); } catch (BError e) { throw e; } catch (Exception e) { handleXMLStreamException(e); } return xmlParserData.currentNode; } private boolean parseXmlElements(int next, XmlParserData xmlParserData) throws XMLStreamException { switch (next) { case START_ELEMENT -> readElement(xmlStreamReader, xmlParserData); case END_ELEMENT -> endElement(xmlStreamReader, xmlParserData); case CDATA -> readText(xmlStreamReader, true, xmlParserData); case CHARACTERS -> { readText(xmlStreamReader, false, xmlParserData); return true; } case END_DOCUMENT -> buildDocument(xmlParserData); case PROCESSING_INSTRUCTION, COMMENT, DTD -> { } // Ignore default -> { assert false; } } return false; } public void parseRecordRest(String startElementName, XmlParserData xmlParserData) { try { boolean readNext = false; int next; while (xmlStreamReader.hasNext()) { if (readNext) { next = xmlStreamReader.getEventType(); } else { next = xmlStreamReader.next(); } // Terminate the record rest field parsing if the end element is reached. if (next == END_ELEMENT) { QName endElement = xmlStreamReader.getName(); if (endElement.getLocalPart().equals(startElementName)) { validateRequiredFields(xmlParserData); xmlParserData.fieldHierarchy.pop(); xmlParserData.restTypes.pop(); xmlParserData.attributeHierarchy.pop(); break; } } readNext = parseXmlElements(next, xmlParserData); } } catch (BError e) { throw e; } catch (Exception e) { handleXMLStreamException(e); } } private void parseRootElement(XMLStreamReader xmlStreamReader, XmlParserData xmlParserData) throws XMLStreamException { if (xmlStreamReader.hasNext()) { int next = xmlStreamReader.next(); if (next == COMMENT || next == PROCESSING_INSTRUCTION) { parseRootElement(xmlStreamReader, xmlParserData); return; } else if (next != START_ELEMENT) { throw DiagnosticLog.error(DiagnosticErrorCode.XML_ROOT_MISSING); } } RecordType rootRecord = xmlParserData.rootRecord; xmlParserData.currentNode = ValueCreator.createRecordValue(rootRecord); QualifiedName elementQName = getElementName(xmlStreamReader); xmlParserData.rootElement =
/* * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). * * WSO2 LLC. 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 io.ballerina.stdlib.data.xmldata.xml; /** * Convert Xml string to a ballerina record. * * @since 0.1.0 */ public class XmlParser { // XMLInputFactory2 private static final XMLInputFactory xmlInputFactory; static { xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); } private XMLStreamReader xmlStreamReader; public static final String PARSE_ERROR = "failed to parse xml"; public static final String PARSE_ERROR_PREFIX = PARSE_ERROR + ": "; public XmlParser(Reader stringReader) { try { xmlStreamReader = xmlInputFactory.createXMLStreamReader(stringReader); } catch (XMLStreamException e) { handleXMLStreamException(e); } } public static Object parse(Reader reader, Type type) { try { XmlParserData xmlParserData = new XmlParserData(); XmlParser xmlParser = new XmlParser(reader); return xmlParser.parse(type, xmlParserData); } catch (BError e) { return e; } catch (Throwable e) { return DiagnosticLog.error(DiagnosticErrorCode.XML_PARSE_ERROR, e.getMessage()); } } private void handleXMLStreamException(Exception e) { String reason = e.getCause() == null ? e.getMessage() : e.getCause().getMessage(); if (reason == null) { throw DiagnosticLog.getXmlError(PARSE_ERROR); } throw DiagnosticLog.getXmlError(PARSE_ERROR_PREFIX + reason); } public Object parse(Type type, XmlParserData xmlParserData) { if (type.getTag() != TypeTags.RECORD_TYPE_TAG) { throw DiagnosticLog.error(DiagnosticErrorCode.INVALID_TYPE, Constants.RECORD, type.getName()); } xmlParserData.rootRecord = (RecordType) type; Object result = parse(xmlParserData); reset(xmlParserData); return result; } private void reset(XmlParserData xmlParserData) { xmlParserData.fieldHierarchy.clear(); xmlParserData.attributeHierarchy.clear(); xmlParserData.restTypes.clear(); xmlParserData.nodesStack.clear(); xmlParserData.parents.clear(); xmlParserData.siblings.clear(); xmlParserData.recordTypeStack.clear(); xmlParserData.restFieldsPoints.clear(); } public Object parse(XmlParserData xmlParserData) { try { parseRootElement(xmlStreamReader, xmlParserData); boolean readNext = false; int next; while (xmlStreamReader.hasNext()) { if (readNext) { next = xmlStreamReader.getEventType(); } else { next = xmlStreamReader.next(); } readNext = parseXmlElements(next, xmlParserData); } } catch (NumberFormatException e) { throw DiagnosticLog.getXmlError(PARSE_ERROR_PREFIX + e); } catch (BError e) { throw e; } catch (Exception e) { handleXMLStreamException(e); } return xmlParserData.currentNode; } private boolean parseXmlElements(int next, XmlParserData xmlParserData) throws XMLStreamException { switch (next) { case START_ELEMENT -> readElement(xmlStreamReader, xmlParserData); case END_ELEMENT -> endElement(xmlStreamReader, xmlParserData); case CDATA -> readText(xmlStreamReader, true, xmlParserData); case CHARACTERS -> { readText(xmlStreamReader, false, xmlParserData); return true; } case END_DOCUMENT -> buildDocument(xmlParserData); case PROCESSING_INSTRUCTION, COMMENT, DTD -> { } // Ignore default -> { assert false; } } return false; } public void parseRecordRest(String startElementName, XmlParserData xmlParserData) { try { boolean readNext = false; int next; while (xmlStreamReader.hasNext()) { if (readNext) { next = xmlStreamReader.getEventType(); } else { next = xmlStreamReader.next(); } // Terminate the record rest field parsing if the end element is reached. if (next == END_ELEMENT) { QName endElement = xmlStreamReader.getName(); if (endElement.getLocalPart().equals(startElementName)) { validateRequiredFields(xmlParserData); xmlParserData.fieldHierarchy.pop(); xmlParserData.restTypes.pop(); xmlParserData.attributeHierarchy.pop(); break; } } readNext = parseXmlElements(next, xmlParserData); } } catch (BError e) { throw e; } catch (Exception e) { handleXMLStreamException(e); } } private void parseRootElement(XMLStreamReader xmlStreamReader, XmlParserData xmlParserData) throws XMLStreamException { if (xmlStreamReader.hasNext()) { int next = xmlStreamReader.next(); if (next == COMMENT || next == PROCESSING_INSTRUCTION) { parseRootElement(xmlStreamReader, xmlParserData); return; } else if (next != START_ELEMENT) { throw DiagnosticLog.error(DiagnosticErrorCode.XML_ROOT_MISSING); } } RecordType rootRecord = xmlParserData.rootRecord; xmlParserData.currentNode = ValueCreator.createRecordValue(rootRecord); QualifiedName elementQName = getElementName(xmlStreamReader); xmlParserData.rootElement =
DataUtils.validateAndGetXmlNameFromRecordAnnotation(rootRecord, rootRecord.getName(), elementQName);
2
2023-11-08 04:13:52+00:00
16k
Mau38/SparePartsFTC
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/ArmMecanumDrive.java
[ { "identifier": "MAX_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static double MAX_ACCEL = 30;" }, { "identifier": "MAX_ANG_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/d...
import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kV; import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.drive.MecanumDrive; import com.acmerobotics.roadrunner.followers.HolonomicPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.roadRunner.drive.StandardTrackingWheelLocalizer; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.roadRunner.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
12,660
package org.firstinspires.ftc.teamcode; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class ArmMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double LATERAL_MULTIPLIER = 1; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private IMU imu; private VoltageSensor batteryVoltageSensor; private List<Integer> lastEncPositions = new ArrayList<>(); private List<Integer> lastEncVels = new ArrayList<>(); public ArmMecanumDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // TODO: adjust the names of the following hardware devices to match your configuration imu = hardwareMap.get(IMU.class, "imu"); IMU.Parameters parameters = new IMU.Parameters(new RevHubOrientationOnRobot( RevHubOrientationOnRobot.LogoFacingDirection.UP, RevHubOrientationOnRobot.UsbFacingDirection.RIGHT)); imu.initialize(parameters); leftFront = hardwareMap.get(DcMotorEx.class, "frontLeft"); leftRear = hardwareMap.get(DcMotorEx.class, "backLeft"); rightRear = hardwareMap.get(DcMotorEx.class, "backRight"); rightFront = hardwareMap.get(DcMotorEx.class, "frontRight"); leftRear.setDirection(DcMotorSimple.Direction.REVERSE); leftFront.setDirection(DcMotorSimple.Direction.REVERSE); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); } if (RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (RUN_USING_ENCODER && MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, MOTOR_VELO_PID); } // TODO: reverse any motors using DcMotor.setDirection() List<Integer> lastTrackingEncPositions = new ArrayList<>(); List<Integer> lastTrackingEncVels = new ArrayList<>(); // TODO: if desired, use setLocalizer() to change the localization method setLocalizer(new StandardTrackingWheelLocalizer(hardwareMap, lastTrackingEncPositions, lastTrackingEncVels)); trajectorySequenceRunner = new TrajectorySequenceRunner( follower, HEADING_PID, batteryVoltageSensor, lastEncPositions, lastEncVels, lastTrackingEncPositions, lastTrackingEncVels ); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) { return new TrajectorySequenceBuilder( startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT,
package org.firstinspires.ftc.teamcode; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class ArmMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double LATERAL_MULTIPLIER = 1; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private IMU imu; private VoltageSensor batteryVoltageSensor; private List<Integer> lastEncPositions = new ArrayList<>(); private List<Integer> lastEncVels = new ArrayList<>(); public ArmMecanumDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // TODO: adjust the names of the following hardware devices to match your configuration imu = hardwareMap.get(IMU.class, "imu"); IMU.Parameters parameters = new IMU.Parameters(new RevHubOrientationOnRobot( RevHubOrientationOnRobot.LogoFacingDirection.UP, RevHubOrientationOnRobot.UsbFacingDirection.RIGHT)); imu.initialize(parameters); leftFront = hardwareMap.get(DcMotorEx.class, "frontLeft"); leftRear = hardwareMap.get(DcMotorEx.class, "backLeft"); rightRear = hardwareMap.get(DcMotorEx.class, "backRight"); rightFront = hardwareMap.get(DcMotorEx.class, "frontRight"); leftRear.setDirection(DcMotorSimple.Direction.REVERSE); leftFront.setDirection(DcMotorSimple.Direction.REVERSE); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); } if (RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (RUN_USING_ENCODER && MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, MOTOR_VELO_PID); } // TODO: reverse any motors using DcMotor.setDirection() List<Integer> lastTrackingEncPositions = new ArrayList<>(); List<Integer> lastTrackingEncVels = new ArrayList<>(); // TODO: if desired, use setLocalizer() to change the localization method setLocalizer(new StandardTrackingWheelLocalizer(hardwareMap, lastTrackingEncPositions, lastTrackingEncVels)); trajectorySequenceRunner = new TrajectorySequenceRunner( follower, HEADING_PID, batteryVoltageSensor, lastEncPositions, lastEncVels, lastTrackingEncPositions, lastTrackingEncVels ); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) { return new TrajectorySequenceBuilder( startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT,
MAX_ANG_VEL, MAX_ANG_ACCEL
1
2023-11-06 21:25:54+00:00
16k
celedev97/asa-server-manager
src/main/java/dev/cele/asa_sm/ui/components/server_tab_accordions/RulesAccordion.java
[ { "identifier": "SpringApplicationContext", "path": "src/main/java/dev/cele/asa_sm/config/SpringApplicationContext.java", "snippet": "@Configuration\npublic class SpringApplicationContext implements ApplicationContextAware {\n private static ApplicationContext context;\n\n @Override\n public vo...
import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import dev.cele.asa_sm.config.SpringApplicationContext; import dev.cele.asa_sm.dto.AsaServerConfigDto; import dev.cele.asa_sm.ui.components.AccordionTopBar; import dev.cele.asa_sm.ui.components.forms.SliderWithText; import dev.cele.asa_sm.ui.components.forms.TimeField; import org.springframework.core.env.Environment; import javax.swing.*; import javax.swing.border.TitledBorder; import java.awt.*; import java.util.Arrays;
13,753
label31.setText("Logout Interval"); panel7.add(label31, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText17 = new SliderWithText(); panel7.add(sliderWithText17, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label32 = new JLabel(); label32.setText("seconds"); panel7.add(label32, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label33 = new JLabel(); label33.setText("Connection Invincible Interval"); panel7.add(label33, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText18 = new SliderWithText(); panel7.add(sliderWithText18, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label34 = new JLabel(); label34.setText("seconds"); panel7.add(label34, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel8 = new JPanel(); panel8.setLayout(new GridLayoutManager(2, 5, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel8, new GridConstraints(18, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel8.setBorder(BorderFactory.createTitledBorder(null, "PvE Schedule", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); enablePvEScheduleCheckBox = new JCheckBox(); enablePvEScheduleCheckBox.setText("Enable PvE Schedule"); panel8.add(enablePvEScheduleCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); useServerTimeCheckBox = new JCheckBox(); useServerTimeCheckBox.setText("Use Server Time"); panel8.add(useServerTimeCheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label35 = new JLabel(); label35.setText("Start Time"); panel8.add(label35, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label36 = new JLabel(); label36.setText("Stop Time"); panel8.add(label36, new GridConstraints(1, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel9 = new JPanel(); panel9.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); panel8.add(panel9, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final TimeField timeField1 = new TimeField(); panel9.add(timeField1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final Spacer spacer3 = new Spacer(); panel9.add(spacer3, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JPanel panel10 = new JPanel(); panel10.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); panel8.add(panel10, new GridConstraints(1, 4, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final TimeField timeField2 = new TimeField(); panel10.add(timeField2, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final Spacer spacer4 = new Spacer(); panel10.add(spacer4, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JPanel panel11 = new JPanel(); panel11.setLayout(new GridLayoutManager(6, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel11, new GridConstraints(19, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label37 = new JLabel(); label37.setText("Max Players in Tribe:"); panel11.add(label37, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText19 = new SliderWithText(); panel11.add(sliderWithText19, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label38 = new JLabel(); label38.setText("players"); panel11.add(label38, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label39 = new JLabel(); label39.setText("Tribe Name Change Cooldown"); panel11.add(label39, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText20 = new SliderWithText(); panel11.add(sliderWithText20, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label40 = new JLabel(); label40.setText("minutes"); panel11.add(label40, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label41 = new JLabel(); label41.setText("Tribe Slot Reuse Cooldown"); panel11.add(label41, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText21 = new SliderWithText(); panel11.add(sliderWithText21, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label42 = new JLabel(); label42.setText("minutes"); panel11.add(label42, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); allowTribeAlliancesCheckBox = new JCheckBox(); allowTribeAlliancesCheckBox.setText("Allow Tribe Alliances"); panel11.add(allowTribeAlliancesCheckBox, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label43 = new JLabel(); label43.setText("Max Alliances Per Tribe"); panel11.add(label43, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText22 = new SliderWithText(); panel11.add(sliderWithText22, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label44 = new JLabel(); label44.setText("Max Tribes Per Alliance"); panel11.add(label44, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText23 = new SliderWithText(); panel11.add(sliderWithText23, new GridConstraints(5, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JPanel panel12 = new JPanel(); panel12.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel12, new GridConstraints(20, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel12.setBorder(BorderFactory.createTitledBorder(null, "PvE \"Tribe Warfare\" Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); allowTribeWarfareCheckBox = new JCheckBox(); allowTribeWarfareCheckBox.setText("Allow Tribe Warfare"); panel12.add(allowTribeWarfareCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); allowCancellingTribeWarfareCheckBox = new JCheckBox(); allowCancellingTribeWarfareCheckBox.setText("Allow Cancelling Tribe Warfare"); panel12.add(allowCancellingTribeWarfareCheckBox, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel13 = new JPanel(); panel13.setLayout(new GridLayoutManager(3, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel13, new GridConstraints(21, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel13.setBorder(BorderFactory.createTitledBorder(null, "Custom Recipes Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); allowCustomRecipesCheckBox = new JCheckBox(); allowCustomRecipesCheckBox.setText("Allow Custom Recipes"); panel13.add(allowCustomRecipesCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer5 = new Spacer(); panel13.add(spacer5, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JLabel label45 = new JLabel(); label45.setText("Effectiveness Multiplier"); panel13.add(label45, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText24 = new SliderWithText(); panel13.add(sliderWithText24, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label46 = new JLabel(); label46.setText("x"); panel13.add(label46, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label47 = new JLabel(); label47.setText("Skill Multiplier"); panel13.add(label47, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText25 = new SliderWithText(); panel13.add(sliderWithText25, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label48 = new JLabel(); label48.setText("x"); panel13.add(label48, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
package dev.cele.asa_sm.ui.components.server_tab_accordions; public class RulesAccordion { private JCheckBox enableHardcoreModeCheckBox; private JCheckBox enablePvPCheckBox; private JCheckBox enableCreativeModeCheckBox; public JPanel contentPane; private JCheckBox disablePvEFriendlyFireCheckBox; private JCheckBox disablePvPFriendlyFireCheckBox; private JCheckBox preventBuildingInResourceCheckBox; private JCheckBox enableSignlePlayerSettingsCheckBox; private JCheckBox enablePvPCaveBuildingCheckBox; private JCheckBox disableCustomTributeFoldersCheckBox; private JCheckBox disablePvPRailgunCheckBox; private JCheckBox enablePveCryoSicknessCheckBox; private JCheckBox disableSupllyCratesCheckBox; private JCheckBox allowCratesSpawnOnCheckBox; private JCheckBox randomSupplyCratesPointsCheckBox; private JCheckBox useCorpseLocatorCheckBox; private JCheckBox preventSpawnAnimationsCheckBox; private JCheckBox allowUnlimitedRespecsCheckBox; private JCheckBox allowPlatformSaddleMultiCheckBox; private JCheckBox enableDifficultyOverrideCheckBox; private JCheckBox enablePvECaveBuildingCheckBox; private JCheckBox enableTributeDownloadsCheckBox; private JCheckBox noSurvivorDownloadsCheckBox; private JCheckBox noItemDownloadsCheckBox; private JCheckBox noDinoDownloadsCheckBox; private JCheckBox allowForeignsDinoDownloadsCheckBox; private JCheckBox noSurvivorUploadsCheckBox; private JCheckBox noItemUploadsCheckBox; private JCheckBox noDinoUploadsCheckBox; private JCheckBox noTransferFromFilteringCheckBox; private JCheckBox increasePvPRespawnIntervalCheckBox; private JCheckBox preventOfflinePvPCheckBox; private JCheckBox enablePvEScheduleCheckBox; private JCheckBox useServerTimeCheckBox; private JCheckBox allowTribeAlliancesCheckBox; private JCheckBox allowTribeWarfareCheckBox; private JCheckBox allowCancellingTribeWarfareCheckBox; private JCheckBox allowCustomRecipesCheckBox; private AsaServerConfigDto configDto; public RulesAccordion(AsaServerConfigDto configDto) { this.configDto = configDto; SwingUtilities.invokeLater(this::afterInit); } Environment environment = SpringApplicationContext.autoWire(Environment.class); private void afterInit() { enableHardcoreModeCheckBox.setSelected(configDto.getGameUserSettingsINI().getServerSettings().getServerHardcore()); enableHardcoreModeCheckBox.addActionListener(e -> configDto.getGameUserSettingsINI().getServerSettings().setServerHardcore(enableHardcoreModeCheckBox.isSelected()) ); enablePvPCheckBox.setSelected(!configDto.getGameUserSettingsINI().getServerSettings().getServerPVE()); enablePvPCheckBox.addActionListener(e -> configDto.getGameUserSettingsINI().getServerSettings().setServerPVE(!enablePvPCheckBox.isSelected()) ); } { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { contentPane = new JPanel(); contentPane.setLayout(new BorderLayout(0, 0)); contentPane.setVisible(true); final JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayoutManager(25, 4, new Insets(0, 0, 0, 0), -1, -1)); contentPane.add(panel1, BorderLayout.CENTER); enableHardcoreModeCheckBox = new JCheckBox(); enableHardcoreModeCheckBox.setText("Enable Hardcore Mode"); panel1.add(enableHardcoreModeCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); disablePvEFriendlyFireCheckBox = new JCheckBox(); disablePvEFriendlyFireCheckBox.setText("Disable Pve Friendly Fire"); panel1.add(disablePvEFriendlyFireCheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); disablePvPFriendlyFireCheckBox = new JCheckBox(); disablePvPFriendlyFireCheckBox.setText("Disable PvP Friendly Fire"); panel1.add(disablePvPFriendlyFireCheckBox, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); preventBuildingInResourceCheckBox = new JCheckBox(); preventBuildingInResourceCheckBox.setText("Prevent Building in Resource Rich Areas"); panel1.add(preventBuildingInResourceCheckBox, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); disableCustomTributeFoldersCheckBox = new JCheckBox(); disableCustomTributeFoldersCheckBox.setText("Disable Custom Tribute Folders"); panel1.add(disableCustomTributeFoldersCheckBox, new GridConstraints(3, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); enablePvPCheckBox = new JCheckBox(); enablePvPCheckBox.setText("Enable PvP"); panel1.add(enablePvPCheckBox, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); enableCreativeModeCheckBox = new JCheckBox(); enableCreativeModeCheckBox.setText("Enable Creative Mode"); panel1.add(enableCreativeModeCheckBox, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); enablePvPCaveBuildingCheckBox = new JCheckBox(); enablePvPCaveBuildingCheckBox.setText("Enable PvP Cave Building"); panel1.add(enablePvPCaveBuildingCheckBox, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); enableSignlePlayerSettingsCheckBox = new JCheckBox(); enableSignlePlayerSettingsCheckBox.setText("Enable Signle Player Settings"); panel1.add(enableSignlePlayerSettingsCheckBox, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); disablePvPRailgunCheckBox = new JCheckBox(); disablePvPRailgunCheckBox.setText("Disable PvP Railgun"); panel1.add(disablePvPRailgunCheckBox, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); enablePveCryoSicknessCheckBox = new JCheckBox(); enablePveCryoSicknessCheckBox.setText("Enable Pve Cryo Sickness"); panel1.add(enablePveCryoSicknessCheckBox, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); disableSupllyCratesCheckBox = new JCheckBox(); disableSupllyCratesCheckBox.setText("Disable Suplly Crates"); panel1.add(disableSupllyCratesCheckBox, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); allowCratesSpawnOnCheckBox = new JCheckBox(); allowCratesSpawnOnCheckBox.setText("Allow Crates Spawn on top of Structures"); panel1.add(allowCratesSpawnOnCheckBox, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); randomSupplyCratesPointsCheckBox = new JCheckBox(); randomSupplyCratesPointsCheckBox.setText("Random Supply Crates Points"); panel1.add(randomSupplyCratesPointsCheckBox, new GridConstraints(4, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText1 = new SliderWithText(); panel1.add(sliderWithText1, new GridConstraints(5, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final SliderWithText sliderWithText2 = new SliderWithText(); panel1.add(sliderWithText2, new GridConstraints(6, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); useCorpseLocatorCheckBox = new JCheckBox(); useCorpseLocatorCheckBox.setText("Use Corpse Locator"); panel1.add(useCorpseLocatorCheckBox, new GridConstraints(7, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); preventSpawnAnimationsCheckBox = new JCheckBox(); preventSpawnAnimationsCheckBox.setText("Prevent Spawn Animations"); panel1.add(preventSpawnAnimationsCheckBox, new GridConstraints(7, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); allowUnlimitedRespecsCheckBox = new JCheckBox(); allowUnlimitedRespecsCheckBox.setText("Allow Unlimited Respecs"); panel1.add(allowUnlimitedRespecsCheckBox, new GridConstraints(7, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); allowPlatformSaddleMultiCheckBox = new JCheckBox(); allowPlatformSaddleMultiCheckBox.setText("Allow Platform Saddle Multi Floors"); panel1.add(allowPlatformSaddleMultiCheckBox, new GridConstraints(8, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText3 = new SliderWithText(); panel1.add(sliderWithText3, new GridConstraints(9, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final SliderWithText sliderWithText4 = new SliderWithText(); panel1.add(sliderWithText4, new GridConstraints(10, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final SliderWithText sliderWithText5 = new SliderWithText(); panel1.add(sliderWithText5, new GridConstraints(12, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label1 = new JLabel(); label1.setText("Fishing Loot Quality Multiplier"); panel1.add(label1, new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label2 = new JLabel(); label2.setText("Supply Crate Loot Quality Multiplier"); panel1.add(label2, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label3 = new JLabel(); label3.setText("Platform Saddle Build Area Bounds Multiplier"); panel1.add(label3, new GridConstraints(9, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label4 = new JLabel(); label4.setText("Max Gateways on Saddles"); panel1.add(label4, new GridConstraints(10, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label5 = new JLabel(); label5.setText("Destroy Tames Over Level:"); panel1.add(label5, new GridConstraints(12, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel2 = new JPanel(); panel2.setLayout(new GridLayoutManager(3, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel2, new GridConstraints(11, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel2.setBorder(BorderFactory.createTitledBorder(null, "Difficulty Ovveride", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); enableDifficultyOverrideCheckBox = new JCheckBox(); enableDifficultyOverrideCheckBox.setText("Enable Difficulty Override"); panel2.add(enableDifficultyOverrideCheckBox, new GridConstraints(0, 0, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label6 = new JLabel(); label6.setText("Max Dino Level:"); panel2.add(label6, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText6 = new SliderWithText(); panel2.add(sliderWithText6, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label7 = new JLabel(); label7.setText("levels"); panel2.add(label7, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label8 = new JLabel(); label8.setText("Difficulty Offset:"); panel2.add(label8, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText7 = new SliderWithText(); panel2.add(sliderWithText7, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label9 = new JLabel(); label9.setText("x"); panel1.add(label9, new GridConstraints(5, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label10 = new JLabel(); label10.setText("x"); panel1.add(label10, new GridConstraints(6, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label11 = new JLabel(); label11.setText("x"); panel1.add(label11, new GridConstraints(9, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label12 = new JLabel(); label12.setText("levels"); panel1.add(label12, new GridConstraints(12, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); enablePvECaveBuildingCheckBox = new JCheckBox(); enablePvECaveBuildingCheckBox.setText("Enable PvE Cave Building"); panel1.add(enablePvECaveBuildingCheckBox, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel3 = new JPanel(); panel3.setLayout(new GridLayoutManager(3, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel3, new GridConstraints(13, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel3.setBorder(BorderFactory.createTitledBorder(null, "Tribute Downloads Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); enableTributeDownloadsCheckBox = new JCheckBox(); enableTributeDownloadsCheckBox.setText("Enable Tribute Downloads"); panel3.add(enableTributeDownloadsCheckBox, new GridConstraints(0, 0, 1, 3, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); noSurvivorDownloadsCheckBox = new JCheckBox(); noSurvivorDownloadsCheckBox.setText("No Survivor Downloads"); panel3.add(noSurvivorDownloadsCheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); noItemDownloadsCheckBox = new JCheckBox(); noItemDownloadsCheckBox.setText("No Item Downloads"); panel3.add(noItemDownloadsCheckBox, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 1, false)); noDinoDownloadsCheckBox = new JCheckBox(); noDinoDownloadsCheckBox.setText("No Dino Downloads"); panel3.add(noDinoDownloadsCheckBox, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); allowForeignsDinoDownloadsCheckBox = new JCheckBox(); allowForeignsDinoDownloadsCheckBox.setText("Allow Foreigns Dino Downloads"); panel3.add(allowForeignsDinoDownloadsCheckBox, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel4 = new JPanel(); panel4.setLayout(new GridLayoutManager(3, 4, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel4, new GridConstraints(14, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel4.setBorder(BorderFactory.createTitledBorder(null, "Tribute Uploads Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); noSurvivorUploadsCheckBox = new JCheckBox(); noSurvivorUploadsCheckBox.setText("No Survivor Uploads"); panel4.add(noSurvivorUploadsCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); noItemUploadsCheckBox = new JCheckBox(); noItemUploadsCheckBox.setText("No Item Uploads"); panel4.add(noItemUploadsCheckBox, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); noDinoUploadsCheckBox = new JCheckBox(); noDinoUploadsCheckBox.setText("No Dino Uploads"); panel4.add(noDinoUploadsCheckBox, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label13 = new JLabel(); label13.setText("Max Tribute Dinos"); panel4.add(label13, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText8 = new SliderWithText(); panel4.add(sliderWithText8, new GridConstraints(1, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label14 = new JLabel(); label14.setText("Max Tribute Items"); panel4.add(label14, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText9 = new SliderWithText(); panel4.add(sliderWithText9, new GridConstraints(2, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label15 = new JLabel(); label15.setText("dinos"); panel4.add(label15, new GridConstraints(1, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label16 = new JLabel(); label16.setText("items"); panel4.add(label16, new GridConstraints(2, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel5 = new JPanel(); panel5.setLayout(new GridLayoutManager(5, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel5, new GridConstraints(15, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel5.setBorder(BorderFactory.createTitledBorder(null, "Cluster Tribute Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); noTransferFromFilteringCheckBox = new JCheckBox(); noTransferFromFilteringCheckBox.setText("No Transfer from Filtering"); panel5.add(noTransferFromFilteringCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer1 = new Spacer(); panel5.add(spacer1, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JLabel label17 = new JLabel(); label17.setText("Override Survivor Upload Expiration"); panel5.add(label17, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText10 = new SliderWithText(); panel5.add(sliderWithText10, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label18 = new JLabel(); label18.setText("minutes"); panel5.add(label18, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label19 = new JLabel(); label19.setText("Override Item Upload Expiration"); panel5.add(label19, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText11 = new SliderWithText(); panel5.add(sliderWithText11, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label20 = new JLabel(); label20.setText("minutes"); panel5.add(label20, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label21 = new JLabel(); label21.setText("Override Dino Upload Expiration"); panel5.add(label21, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText12 = new SliderWithText(); panel5.add(sliderWithText12, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label22 = new JLabel(); label22.setText("minutes"); panel5.add(label22, new GridConstraints(3, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label23 = new JLabel(); label23.setText("Override Minimum Dino Re-upload Interval"); panel5.add(label23, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText13 = new SliderWithText(); panel5.add(sliderWithText13, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label24 = new JLabel(); label24.setText("minutes"); panel5.add(label24, new GridConstraints(4, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel6 = new JPanel(); panel6.setLayout(new GridLayoutManager(4, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel6, new GridConstraints(16, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel6.setBorder(BorderFactory.createTitledBorder(null, "PvP Respawn Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); final JLabel label25 = new JLabel(); label25.setText("Interval Check Period"); panel6.add(label25, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText14 = new SliderWithText(); panel6.add(sliderWithText14, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label26 = new JLabel(); label26.setText("seconds"); panel6.add(label26, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label27 = new JLabel(); label27.setText("Interval Multiplier:"); panel6.add(label27, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText15 = new SliderWithText(); panel6.add(sliderWithText15, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label28 = new JLabel(); label28.setText("x"); panel6.add(label28, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label29 = new JLabel(); label29.setText("Interval Base Amount:"); panel6.add(label29, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText16 = new SliderWithText(); panel6.add(sliderWithText16, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label30 = new JLabel(); label30.setText("seconds"); panel6.add(label30, new GridConstraints(3, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); increasePvPRespawnIntervalCheckBox = new JCheckBox(); increasePvPRespawnIntervalCheckBox.setText("Increase PvP Respawn Interval"); panel6.add(increasePvPRespawnIntervalCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel7 = new JPanel(); panel7.setLayout(new GridLayoutManager(3, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel7, new GridConstraints(17, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel7.setBorder(BorderFactory.createTitledBorder(null, "PvP Offline Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); preventOfflinePvPCheckBox = new JCheckBox(); preventOfflinePvPCheckBox.setText("Prevent Offline PvP"); panel7.add(preventOfflinePvPCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer2 = new Spacer(); panel7.add(spacer2, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JLabel label31 = new JLabel(); label31.setText("Logout Interval"); panel7.add(label31, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText17 = new SliderWithText(); panel7.add(sliderWithText17, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label32 = new JLabel(); label32.setText("seconds"); panel7.add(label32, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label33 = new JLabel(); label33.setText("Connection Invincible Interval"); panel7.add(label33, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText18 = new SliderWithText(); panel7.add(sliderWithText18, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label34 = new JLabel(); label34.setText("seconds"); panel7.add(label34, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel8 = new JPanel(); panel8.setLayout(new GridLayoutManager(2, 5, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel8, new GridConstraints(18, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel8.setBorder(BorderFactory.createTitledBorder(null, "PvE Schedule", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); enablePvEScheduleCheckBox = new JCheckBox(); enablePvEScheduleCheckBox.setText("Enable PvE Schedule"); panel8.add(enablePvEScheduleCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); useServerTimeCheckBox = new JCheckBox(); useServerTimeCheckBox.setText("Use Server Time"); panel8.add(useServerTimeCheckBox, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label35 = new JLabel(); label35.setText("Start Time"); panel8.add(label35, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label36 = new JLabel(); label36.setText("Stop Time"); panel8.add(label36, new GridConstraints(1, 3, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel9 = new JPanel(); panel9.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); panel8.add(panel9, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final TimeField timeField1 = new TimeField(); panel9.add(timeField1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final Spacer spacer3 = new Spacer(); panel9.add(spacer3, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JPanel panel10 = new JPanel(); panel10.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); panel8.add(panel10, new GridConstraints(1, 4, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final TimeField timeField2 = new TimeField(); panel10.add(timeField2, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final Spacer spacer4 = new Spacer(); panel10.add(spacer4, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JPanel panel11 = new JPanel(); panel11.setLayout(new GridLayoutManager(6, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel11, new GridConstraints(19, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label37 = new JLabel(); label37.setText("Max Players in Tribe:"); panel11.add(label37, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText19 = new SliderWithText(); panel11.add(sliderWithText19, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label38 = new JLabel(); label38.setText("players"); panel11.add(label38, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label39 = new JLabel(); label39.setText("Tribe Name Change Cooldown"); panel11.add(label39, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText20 = new SliderWithText(); panel11.add(sliderWithText20, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label40 = new JLabel(); label40.setText("minutes"); panel11.add(label40, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label41 = new JLabel(); label41.setText("Tribe Slot Reuse Cooldown"); panel11.add(label41, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText21 = new SliderWithText(); panel11.add(sliderWithText21, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label42 = new JLabel(); label42.setText("minutes"); panel11.add(label42, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); allowTribeAlliancesCheckBox = new JCheckBox(); allowTribeAlliancesCheckBox.setText("Allow Tribe Alliances"); panel11.add(allowTribeAlliancesCheckBox, new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label43 = new JLabel(); label43.setText("Max Alliances Per Tribe"); panel11.add(label43, new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText22 = new SliderWithText(); panel11.add(sliderWithText22, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label44 = new JLabel(); label44.setText("Max Tribes Per Alliance"); panel11.add(label44, new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText23 = new SliderWithText(); panel11.add(sliderWithText23, new GridConstraints(5, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JPanel panel12 = new JPanel(); panel12.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel12, new GridConstraints(20, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel12.setBorder(BorderFactory.createTitledBorder(null, "PvE \"Tribe Warfare\" Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); allowTribeWarfareCheckBox = new JCheckBox(); allowTribeWarfareCheckBox.setText("Allow Tribe Warfare"); panel12.add(allowTribeWarfareCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); allowCancellingTribeWarfareCheckBox = new JCheckBox(); allowCancellingTribeWarfareCheckBox.setText("Allow Cancelling Tribe Warfare"); panel12.add(allowCancellingTribeWarfareCheckBox, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel13 = new JPanel(); panel13.setLayout(new GridLayoutManager(3, 3, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel13, new GridConstraints(21, 0, 1, 4, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel13.setBorder(BorderFactory.createTitledBorder(null, "Custom Recipes Options", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null)); allowCustomRecipesCheckBox = new JCheckBox(); allowCustomRecipesCheckBox.setText("Allow Custom Recipes"); panel13.add(allowCustomRecipesCheckBox, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final Spacer spacer5 = new Spacer(); panel13.add(spacer5, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)); final JLabel label45 = new JLabel(); label45.setText("Effectiveness Multiplier"); panel13.add(label45, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText24 = new SliderWithText(); panel13.add(sliderWithText24, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label46 = new JLabel(); label46.setText("x"); panel13.add(label46, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JLabel label47 = new JLabel(); label47.setText("Skill Multiplier"); panel13.add(label47, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final SliderWithText sliderWithText25 = new SliderWithText(); panel13.add(sliderWithText25, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); final JLabel label48 = new JLabel(); label48.setText("x"); panel13.add(label48, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final AccordionTopBar accordionTopBar1 = new AccordionTopBar();
2
2023-11-07 19:36:49+00:00
16k
By1337/BAuction
Core/src/main/java/org/by1337/bauction/menu/impl/UnsoldItemsMenu.java
[ { "identifier": "Main", "path": "Core/src/main/java/org/by1337/bauction/Main.java", "snippet": "public final class Main extends JavaPlugin {\n private static Message message;\n private static Plugin instance;\n private static Config cfg;\n private static FileDataBase storage;\n private Co...
import org.bukkit.entity.Player; import org.by1337.api.chat.Placeholderable; import org.by1337.api.command.Command; import org.by1337.api.command.CommandException; import org.by1337.api.command.argument.ArgumentSetList; import org.by1337.api.command.argument.ArgumentString; import org.by1337.bauction.Main; import org.by1337.bauction.action.TakeUnsoldItemProcess; import org.by1337.bauction.auc.UnsoldItem; import org.by1337.bauction.auc.User; import org.by1337.bauction.lang.Lang; import org.by1337.bauction.menu.CustomItemStack; import org.by1337.bauction.menu.Menu; import org.by1337.bauction.menu.command.DefaultMenuCommand; import org.by1337.bauction.util.CUniqueName; import org.by1337.api.util.Pair; import org.by1337.bauction.util.UniqueName; import javax.annotation.Nullable; import java.util.*;
12,806
package org.by1337.bauction.menu.impl; public class UnsoldItemsMenu extends Menu { private int currentPage = 0; private int maxPage = 0; private final List<Integer> slots; private final Command<Pair<Menu, Player>> command; private final User user; public UnsoldItemsMenu(Player player, User user) { this(player, user, null); } public UnsoldItemsMenu(Player player, User user, @Nullable Menu backMenu) { super(Main.getCfg().getMenuManger().getUnsoldItems(), player, backMenu, user); this.user = user; slots = Main.getCfg().getMenuManger().getUnsoldItemsSlots(); command = new Command<Pair<Menu, Player>>("test") .addSubCommand(new Command<Pair<Menu, Player>>("[NEXT_PAGE]") .executor(((sender, args) -> { if (currentPage < maxPage - 1) { currentPage++; generate0(); } })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[PREVIOUS_PAGE]") .executor(((sender, args) -> { if (currentPage > 0) { currentPage--; generate0(); } })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[UPDATE]") .executor(((sender, args) -> { unsoldItems = null; generate0(); })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[TAKE_ITEM]") .argument(new ArgumentString<>("uuid")) .argument(new ArgumentSetList<>("fast", List.of("fast"))) .executor(((sender, args) -> { boolean fast = args.getOrDefault("fast", "").equals("fast"); String uuidS = (String) args.getOrThrow("uuid"); // UUID uuid = UUID.fromString(uuidS);
package org.by1337.bauction.menu.impl; public class UnsoldItemsMenu extends Menu { private int currentPage = 0; private int maxPage = 0; private final List<Integer> slots; private final Command<Pair<Menu, Player>> command; private final User user; public UnsoldItemsMenu(Player player, User user) { this(player, user, null); } public UnsoldItemsMenu(Player player, User user, @Nullable Menu backMenu) { super(Main.getCfg().getMenuManger().getUnsoldItems(), player, backMenu, user); this.user = user; slots = Main.getCfg().getMenuManger().getUnsoldItemsSlots(); command = new Command<Pair<Menu, Player>>("test") .addSubCommand(new Command<Pair<Menu, Player>>("[NEXT_PAGE]") .executor(((sender, args) -> { if (currentPage < maxPage - 1) { currentPage++; generate0(); } })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[PREVIOUS_PAGE]") .executor(((sender, args) -> { if (currentPage > 0) { currentPage--; generate0(); } })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[UPDATE]") .executor(((sender, args) -> { unsoldItems = null; generate0(); })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[TAKE_ITEM]") .argument(new ArgumentString<>("uuid")) .argument(new ArgumentSetList<>("fast", List.of("fast"))) .executor(((sender, args) -> { boolean fast = args.getOrDefault("fast", "").equals("fast"); String uuidS = (String) args.getOrThrow("uuid"); // UUID uuid = UUID.fromString(uuidS);
UniqueName uuid = new CUniqueName(uuidS);
9
2023-11-08 18:25:18+00:00
16k
YufiriaMazenta/CrypticLib
nms/src/main/java/crypticlib/nms/item/ItemFactory.java
[ { "identifier": "CrypticLib", "path": "common/src/main/java/crypticlib/CrypticLib.java", "snippet": "public class CrypticLib {\n\n\n private static final CommandManager commandManager;\n private static final PermissionManager permissionManager;\n private static IPlatform platform;\n private ...
import crypticlib.CrypticLib; import crypticlib.function.TernaryFunction; import crypticlib.nms.item.v1_12_R1.V1_12_R1NbtItem; import crypticlib.nms.item.v1_13_R1.V1_13_R1NbtItem; import crypticlib.nms.item.v1_13_R2.V1_13_R2NbtItem; import crypticlib.nms.item.v1_14_R1.V1_14_R1NbtItem; import crypticlib.nms.item.v1_15_R1.V1_15_R1NbtItem; import crypticlib.nms.item.v1_16_R1.V1_16_R1NbtItem; import crypticlib.nms.item.v1_16_R2.V1_16_R2NbtItem; import crypticlib.nms.item.v1_16_R3.V1_16_R3NbtItem; import crypticlib.nms.item.v1_17_R1.V1_17_R1NbtItem; import crypticlib.nms.item.v1_18_R1.V1_18_R1NbtItem; import crypticlib.nms.item.v1_18_R2.V1_18_R2NbtItem; import crypticlib.nms.item.v1_19_R1.V1_19_R1NbtItem; import crypticlib.nms.item.v1_19_R2.V1_19_R2NbtItem; import crypticlib.nms.item.v1_19_R3.V1_19_R3NbtItem; import crypticlib.nms.item.v1_20_R1.V1_20_R1NbtItem; import crypticlib.nms.item.v1_20_R2.V1_20_R2NbtItem; import crypticlib.nms.item.v1_20_R3.V1_20_R3NbtItem; import crypticlib.nms.nbt.NbtFactory; import crypticlib.nms.nbt.NbtTagCompound; import crypticlib.util.MaterialUtil; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; import java.util.function.Function;
12,399
package crypticlib.nms.item; /** * CrypticLib的物品提供工厂 */ public class ItemFactory { private static final Map<String, Function<ItemStack, NbtItem>> nbtItemProviderMap1;
package crypticlib.nms.item; /** * CrypticLib的物品提供工厂 */ public class ItemFactory { private static final Map<String, Function<ItemStack, NbtItem>> nbtItemProviderMap1;
private static final Map<String, BiFunction<Material, NbtTagCompound, NbtItem>> nbtItemProviderMap2;
20
2023-11-07 12:39:20+00:00
16k
txline0420/nacos-dm
plugin/datasource/src/main/java/com/alibaba/nacos/plugin/datasource/impl/dm/ConfigTagsRelationMapperByDm.java
[ { "identifier": "StringUtils", "path": "common/src/main/java/com/alibaba/nacos/common/utils/StringUtils.java", "snippet": "public class StringUtils {\n\n private StringUtils() {\n }\n \n public static final String DOT = \".\";\n \n private static final int INDEX_NOT_FOUND = -1;\n \n...
import com.alibaba.nacos.common.utils.StringUtils; import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant; import com.alibaba.nacos.plugin.datasource.mapper.AbstractMapper; import com.alibaba.nacos.plugin.datasource.mapper.ConfigTagsRelationMapper; import java.util.Map;
11,097
/* * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.plugin.datasource.impl.dm; /** * The DM implementation of ConfigTagsRelationMapper. * * @author TXLINE **/ public class ConfigTagsRelationMapperByDm extends AbstractMapper implements ConfigTagsRelationMapper { @Override public String findConfigInfo4PageFetchRows(Map<String, String> params, int tagSize, int startRow, int pageSize) { final String appName = params.get("appName"); final String dataId = params.get("dataId"); final String group = params.get("group"); final String content = params.get("content"); StringBuilder where = new StringBuilder(" WHERE "); final String sql = "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a LEFT JOIN " + "config_tags_relation b ON a.id=b.id"; where.append(" a.tenant_id=? "); if (StringUtils.isNotBlank(dataId)) { where.append(" AND a.data_id=? "); } if (StringUtils.isNotBlank(group)) { where.append(" AND a.group_id=? "); } if (StringUtils.isNotBlank(appName)) { where.append(" AND a.app_name=? "); } if (!StringUtils.isBlank(content)) { where.append(" AND a.content LIKE ? "); } where.append(" AND b.tag_name IN ("); for (int i = 0; i < tagSize; i++) { if (i != 0) { where.append(", "); } where.append('?'); } where.append(") "); return sql + where + " LIMIT " + startRow + "," + pageSize; } @Override public String findConfigInfoLike4PageFetchRows(final Map<String, String> params, int tagSize, int startRow, int pageSize) { final String appName = params.get("appName"); final String content = params.get("content"); final String dataId = params.get("dataId"); final String group = params.get("group"); StringBuilder where = new StringBuilder(" WHERE "); final String sqlFetchRows = "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content " + "FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id "; where.append(" a.tenant_id LIKE ? "); if (!StringUtils.isBlank(dataId)) { where.append(" AND a.data_id LIKE ? "); } if (!StringUtils.isBlank(group)) { where.append(" AND a.group_id LIKE ? "); } if (!StringUtils.isBlank(appName)) { where.append(" AND a.app_name = ? "); } if (!StringUtils.isBlank(content)) { where.append(" AND a.content LIKE ? "); } where.append(" AND b.tag_name IN ("); for (int i = 0; i < tagSize; i++) { if (i != 0) { where.append(", "); } where.append('?'); } where.append(") "); return sqlFetchRows + where + " LIMIT " + startRow + "," + pageSize; } @Override public String getDataSource() {
/* * Copyright 1999-2022 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.plugin.datasource.impl.dm; /** * The DM implementation of ConfigTagsRelationMapper. * * @author TXLINE **/ public class ConfigTagsRelationMapperByDm extends AbstractMapper implements ConfigTagsRelationMapper { @Override public String findConfigInfo4PageFetchRows(Map<String, String> params, int tagSize, int startRow, int pageSize) { final String appName = params.get("appName"); final String dataId = params.get("dataId"); final String group = params.get("group"); final String content = params.get("content"); StringBuilder where = new StringBuilder(" WHERE "); final String sql = "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content FROM config_info a LEFT JOIN " + "config_tags_relation b ON a.id=b.id"; where.append(" a.tenant_id=? "); if (StringUtils.isNotBlank(dataId)) { where.append(" AND a.data_id=? "); } if (StringUtils.isNotBlank(group)) { where.append(" AND a.group_id=? "); } if (StringUtils.isNotBlank(appName)) { where.append(" AND a.app_name=? "); } if (!StringUtils.isBlank(content)) { where.append(" AND a.content LIKE ? "); } where.append(" AND b.tag_name IN ("); for (int i = 0; i < tagSize; i++) { if (i != 0) { where.append(", "); } where.append('?'); } where.append(") "); return sql + where + " LIMIT " + startRow + "," + pageSize; } @Override public String findConfigInfoLike4PageFetchRows(final Map<String, String> params, int tagSize, int startRow, int pageSize) { final String appName = params.get("appName"); final String content = params.get("content"); final String dataId = params.get("dataId"); final String group = params.get("group"); StringBuilder where = new StringBuilder(" WHERE "); final String sqlFetchRows = "SELECT a.id,a.data_id,a.group_id,a.tenant_id,a.app_name,a.content " + "FROM config_info a LEFT JOIN config_tags_relation b ON a.id=b.id "; where.append(" a.tenant_id LIKE ? "); if (!StringUtils.isBlank(dataId)) { where.append(" AND a.data_id LIKE ? "); } if (!StringUtils.isBlank(group)) { where.append(" AND a.group_id LIKE ? "); } if (!StringUtils.isBlank(appName)) { where.append(" AND a.app_name = ? "); } if (!StringUtils.isBlank(content)) { where.append(" AND a.content LIKE ? "); } where.append(" AND b.tag_name IN ("); for (int i = 0; i < tagSize; i++) { if (i != 0) { where.append(", "); } where.append('?'); } where.append(") "); return sqlFetchRows + where + " LIMIT " + startRow + "," + pageSize; } @Override public String getDataSource() {
return DataSourceConstant.DM;
1
2023-11-02 01:34:09+00:00
16k
ynwynw/oaSystemPublic
src/main/java/cn/gson/oasys/controller/inform/InformManageController.java
[ { "identifier": "BindingResultVOUtil", "path": "src/main/java/cn/gson/oasys/common/formValid/BindingResultVOUtil.java", "snippet": "public class BindingResultVOUtil {\n /**\n * 表单验证,返回形式ResultVO\n *\n * @param br\n * @return\n */\n public static ResultVO hasErrors(BindingResult...
import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttribute; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.gson.oasys.common.formValid.BindingResultVOUtil; import cn.gson.oasys.common.formValid.MapToList; import cn.gson.oasys.common.formValid.ResultEnum; import cn.gson.oasys.common.formValid.ResultVO; import cn.gson.oasys.mappers.NoticeMapper; import cn.gson.oasys.model.dao.informdao.InformDao; import cn.gson.oasys.model.dao.informdao.InformRelationDao; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.DeptDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.entity.notice.NoticeUserRelation; import cn.gson.oasys.model.entity.notice.NoticeVO; import cn.gson.oasys.model.entity.notice.NoticesList; import cn.gson.oasys.model.entity.system.SystemMenu; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User; import cn.gson.oasys.services.inform.InformRelationService; import cn.gson.oasys.services.inform.InformService;
12,839
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private StatusDao statusDao; @Autowired private TypeDao typeDao; @Autowired private InformDao informDao; @Autowired private InformService informService; @Autowired private UserDao uDao; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private StatusDao statusDao; @Autowired private TypeDao typeDao; @Autowired private InformDao informDao; @Autowired private InformService informService; @Autowired private UserDao uDao; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired
private InformRelationService informrelationservice;
18
2023-11-03 02:08:22+00:00
16k
firstdarkdev/modfusioner
src/main/java/com/hypherionmc/modfusioner/task/JarFuseTask.java
[ { "identifier": "Constants", "path": "src/main/java/com/hypherionmc/modfusioner/Constants.java", "snippet": "public class Constants {\n\n public static final String TASK_GROUP = \"modfusioner\";\n public static final String TASK_NAME = \"fusejars\";\n public static final String EXTENSION_NAME =...
import com.hypherionmc.modfusioner.Constants; import com.hypherionmc.modfusioner.actions.JarMergeAction; import com.hypherionmc.modfusioner.plugin.FusionerExtension; import com.hypherionmc.modfusioner.plugin.ModFusionerPlugin; import com.hypherionmc.modfusioner.utils.FileChecks; import com.hypherionmc.modfusioner.utils.FileTools; import org.apache.commons.io.FileUtils; import org.gradle.api.Project; import org.gradle.api.internal.file.copy.CopyAction; import org.gradle.api.tasks.WorkResults; import org.gradle.jvm.tasks.Jar; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.modFusionerExtension; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.rootProject;
13,678
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.task; /** * @author HypherionSA * The main task of the plugin */ public class JarFuseTask extends Jar { // Fixed values private final File mergedJar; private static final AtomicBoolean hasRun = new AtomicBoolean(false); public JarFuseTask() { // Set task default values from extension getArchiveBaseName().set(modFusionerExtension.getMergedJarName()); getArchiveVersion().set(modFusionerExtension.getJarVersion()); getDestinationDirectory().set(getProject().file(modFusionerExtension.getOutputDirectory())); // We don't allow custom input files, when the user defines their own task getInputs().files(); // Only allow the task to run once per cycle getOutputs().upToDateWhen(spec -> hasRun.get()); // Set output file mergedJar = new File(getDestinationDirectory().get().getAsFile(), getArchiveFileName().get()); getOutputs().file(mergedJar); } /** * Main task logic * @throws IOException - Thrown when an IO error occurs */ void fuseJars() throws IOException { long time = System.currentTimeMillis(); ModFusionerPlugin.logger.lifecycle("Start Fusing Jars"); // Get settings from extension FusionerExtension.ForgeConfiguration forgeConfiguration = modFusionerExtension.getForgeConfiguration(); FusionerExtension.FabricConfiguration fabricConfiguration = modFusionerExtension.getFabricConfiguration(); FusionerExtension.QuiltConfiguration quiltConfiguration = modFusionerExtension.getQuiltConfiguration(); List<FusionerExtension.CustomConfiguration> customConfigurations = modFusionerExtension.getCustomConfigurations(); // Try to resolve the projects specific in the extension config Project forgeProject = null; Project fabricProject = null; Project quiltProject = null; Map<Project, FusionerExtension.CustomConfiguration> customProjects = new HashMap<>(); List<Boolean> validation = new ArrayList<>(); if (forgeConfiguration != null) { try {
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.task; /** * @author HypherionSA * The main task of the plugin */ public class JarFuseTask extends Jar { // Fixed values private final File mergedJar; private static final AtomicBoolean hasRun = new AtomicBoolean(false); public JarFuseTask() { // Set task default values from extension getArchiveBaseName().set(modFusionerExtension.getMergedJarName()); getArchiveVersion().set(modFusionerExtension.getJarVersion()); getDestinationDirectory().set(getProject().file(modFusionerExtension.getOutputDirectory())); // We don't allow custom input files, when the user defines their own task getInputs().files(); // Only allow the task to run once per cycle getOutputs().upToDateWhen(spec -> hasRun.get()); // Set output file mergedJar = new File(getDestinationDirectory().get().getAsFile(), getArchiveFileName().get()); getOutputs().file(mergedJar); } /** * Main task logic * @throws IOException - Thrown when an IO error occurs */ void fuseJars() throws IOException { long time = System.currentTimeMillis(); ModFusionerPlugin.logger.lifecycle("Start Fusing Jars"); // Get settings from extension FusionerExtension.ForgeConfiguration forgeConfiguration = modFusionerExtension.getForgeConfiguration(); FusionerExtension.FabricConfiguration fabricConfiguration = modFusionerExtension.getFabricConfiguration(); FusionerExtension.QuiltConfiguration quiltConfiguration = modFusionerExtension.getQuiltConfiguration(); List<FusionerExtension.CustomConfiguration> customConfigurations = modFusionerExtension.getCustomConfigurations(); // Try to resolve the projects specific in the extension config Project forgeProject = null; Project fabricProject = null; Project quiltProject = null; Map<Project, FusionerExtension.CustomConfiguration> customProjects = new HashMap<>(); List<Boolean> validation = new ArrayList<>(); if (forgeConfiguration != null) { try {
forgeProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(forgeConfiguration.getProjectName())).findFirst().get();
7
2023-11-03 23:19:08+00:00
16k
data-harness-cloud/data_harness-be
application-webadmin/src/main/java/supie/webadmin/interceptor/ApiAuthenticationInterceptor.java
[ { "identifier": "ApplicationConstant", "path": "common/common-core/src/main/java/supie/common/core/constant/ApplicationConstant.java", "snippet": "public final class ApplicationConstant {\n\n /**\n * 适用于所有类型的字典格式数据。该常量为字典的键字段。\n */\n public static final String DICT_ID = \"id\";\n /**\n ...
import cn.hutool.core.text.StrFormatter; import cn.hutool.core.util.StrUtil; import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.Nullable; import org.redisson.api.RBucket; import org.redisson.api.RedissonClient; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import supie.common.core.constant.ApplicationConstant; import supie.common.core.constant.ErrorCodeEnum; import supie.common.core.object.ResponseResult; import supie.common.core.util.ApplicationContextHolder; import supie.common.core.util.MyCommonUtil; import supie.webadmin.app.dao.CustomizeRouteMapper; import supie.webadmin.app.dao.ExternalAppMapper; import supie.webadmin.app.model.CustomizeRoute; import supie.webadmin.app.model.ExternalApp; import supie.webadmin.config.ApplicationConfig; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import java.util.concurrent.TimeUnit;
14,064
package supie.webadmin.interceptor; /** * 描述: * * @author 王立宏 * @date 2023/11/16 16:50 * @path SDT-supie.webadmin.interceptor-ApiAuthenticationInterceptor */ @Slf4j public class ApiAuthenticationInterceptor implements HandlerInterceptor { private final ApplicationConfig appConfig =
package supie.webadmin.interceptor; /** * 描述: * * @author 王立宏 * @date 2023/11/16 16:50 * @path SDT-supie.webadmin.interceptor-ApiAuthenticationInterceptor */ @Slf4j public class ApiAuthenticationInterceptor implements HandlerInterceptor { private final ApplicationConfig appConfig =
ApplicationContextHolder.getBean("applicationConfig");
3
2023-11-04 12:36:44+00:00
16k
FTC-ORBIT/14872-2024-CenterStage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java
[ { "identifier": "TrajectorySequence", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequence.java", "snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<SequenceSegment> se...
import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.drive.MecanumDrive; import com.acmerobotics.roadrunner.followers.HolonomicPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV;
10,952
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(7, 0, 2); public static PIDCoefficients HEADING_PID = new PIDCoefficients(5, 0, 1); public static double LATERAL_MULTIPLIER = 1.7; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private IMU imu; private VoltageSensor batteryVoltageSensor; private List<Integer> lastEncPositions = new ArrayList<>(); private List<Integer> lastEncVels = new ArrayList<>(); public SampleMecanumDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5);
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(7, 0, 2); public static PIDCoefficients HEADING_PID = new PIDCoefficients(5, 0, 1); public static double LATERAL_MULTIPLIER = 1.7; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private IMU imu; private VoltageSensor batteryVoltageSensor; private List<Integer> lastEncPositions = new ArrayList<>(); private List<Integer> lastEncVels = new ArrayList<>(); public SampleMecanumDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5);
LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap);
3
2023-11-03 13:32:48+00:00
16k
beminder/BeautyMinder
java/src/main/java/app/beautyminder/service/RecommendService.java
[ { "identifier": "Cosmetic", "path": "java/src/main/java/app/beautyminder/domain/Cosmetic.java", "snippet": "@Document(collection = \"cosmetics\") // mongodb\n@AllArgsConstructor\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@Getter\n@Builder\npublic class Cosmetic {\n\n @Id\n private String...
import app.beautyminder.domain.Cosmetic; import app.beautyminder.domain.Review; import app.beautyminder.domain.User; import app.beautyminder.repository.CosmeticRepository; import app.beautyminder.service.auth.UserService; import app.beautyminder.service.cosmetic.CosmeticRankService; import app.beautyminder.service.review.ReviewService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.bson.types.ObjectId; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Caching; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.AggregationResults; import org.springframework.data.mongodb.core.aggregation.MatchOperation; import org.springframework.data.mongodb.core.aggregation.SampleOperation; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors;
12,388
package app.beautyminder.service; @Slf4j @RequiredArgsConstructor @Service public class RecommendService { private final CosmeticRankService cosmeticRankService; private final UserService userService; private final ReviewService reviewService; private final CosmeticRepository cosmeticRepository; private final MongoTemplate mongoTemplate; private final Integer MAX_MATCHING_KEYWORDS = 2; private static <T> T getByRandomClass(Set<T> set) { if (set == null || set.isEmpty()) { throw new IllegalArgumentException("The Set cannot be empty."); } int randomIndex = ThreadLocalRandom.current().nextInt(set.size()); return set.stream() .skip(randomIndex) .findFirst() .orElseThrow(() -> new IllegalStateException("Something went wrong while picking a random element.")); } @Caching( evict = {@CacheEvict(value = "productRecommendations", key = "#userHash", condition = "#forceRefresh", beforeInvocation = true)}, cacheable = {@Cacheable(value = "productRecommendations", key = "#userHash", condition = "!#forceRefresh", unless = "#result == null or #result.isEmpty()")}, put = {@CachePut(value = "productRecommendations", key = "#userHash", condition = "#forceRefresh")} ) public List<Cosmetic> recommendProducts(String userId, String userHash, boolean forceRefresh) {
package app.beautyminder.service; @Slf4j @RequiredArgsConstructor @Service public class RecommendService { private final CosmeticRankService cosmeticRankService; private final UserService userService; private final ReviewService reviewService; private final CosmeticRepository cosmeticRepository; private final MongoTemplate mongoTemplate; private final Integer MAX_MATCHING_KEYWORDS = 2; private static <T> T getByRandomClass(Set<T> set) { if (set == null || set.isEmpty()) { throw new IllegalArgumentException("The Set cannot be empty."); } int randomIndex = ThreadLocalRandom.current().nextInt(set.size()); return set.stream() .skip(randomIndex) .findFirst() .orElseThrow(() -> new IllegalStateException("Something went wrong while picking a random element.")); } @Caching( evict = {@CacheEvict(value = "productRecommendations", key = "#userHash", condition = "#forceRefresh", beforeInvocation = true)}, cacheable = {@Cacheable(value = "productRecommendations", key = "#userHash", condition = "!#forceRefresh", unless = "#result == null or #result.isEmpty()")}, put = {@CachePut(value = "productRecommendations", key = "#userHash", condition = "#forceRefresh")} ) public List<Cosmetic> recommendProducts(String userId, String userHash, boolean forceRefresh) {
User user = userService.findById(userId);
2
2023-11-01 12:37:16+00:00
16k
FallenDeity/GameEngine2DJava
src/main/java/engine/components/MouseControls.java
[ { "identifier": "PropertiesWindow", "path": "src/main/java/engine/editor/PropertiesWindow.java", "snippet": "public class PropertiesWindow {\n\tprivate final List<Vector4f> objectColors;\n\tprivate final List<GameObject> gameObjects;\n\tprivate final Picker picker;\n\n\tpublic PropertiesWindow(Picker pi...
import engine.editor.PropertiesWindow; import engine.renderer.DebugDraw; import engine.renderer.Picker; import engine.ruby.ImGuiLayer; import engine.ruby.KeyListener; import engine.ruby.MouseListener; import engine.ruby.Window; import engine.scenes.LevelEditorScene; import engine.util.CONSTANTS; import org.joml.Vector2f; import org.joml.Vector2i; import org.joml.Vector4f; import java.util.HashSet; import java.util.Set; import static org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE; import static org.lwjgl.glfw.GLFW.GLFW_MOUSE_BUTTON_LEFT;
13,028
package engine.components; public class MouseControls extends Component { private static boolean holding = false; private final Vector2f boxSelectStart = new Vector2f(), boxSelectEnd = new Vector2f(); private GameObject activeGameObject = null; private float debounce = 0.0f; private boolean boxSelect = false; public static boolean isHolding() { return holding; } public void setActiveGameObject(GameObject activeGameObject) { if (this.activeGameObject != null) { this.activeGameObject.destroy(); } this.activeGameObject = activeGameObject; this.activeGameObject.getComponent(SpriteRenderer.class).setColor(new Vector4f(0.8f, 0.8f, 0.8f, 0.5f)); this.activeGameObject.addComponent(new NonPickable());
package engine.components; public class MouseControls extends Component { private static boolean holding = false; private final Vector2f boxSelectStart = new Vector2f(), boxSelectEnd = new Vector2f(); private GameObject activeGameObject = null; private float debounce = 0.0f; private boolean boxSelect = false; public static boolean isHolding() { return holding; } public void setActiveGameObject(GameObject activeGameObject) { if (this.activeGameObject != null) { this.activeGameObject.destroy(); } this.activeGameObject = activeGameObject; this.activeGameObject.getComponent(SpriteRenderer.class).setColor(new Vector4f(0.8f, 0.8f, 0.8f, 0.5f)); this.activeGameObject.addComponent(new NonPickable());
Window.getScene().addGameObjectToScene(activeGameObject);
6
2023-11-04 13:19:21+00:00
16k
RezaGooner/University-food-ordering
Frames/Admin/Managment/DataBaseManagment.java
[ { "identifier": "FilesPath", "path": "Classes/Pathes/FilesPath.java", "snippet": "public class FilesPath {\r\n\r\n public static ImageIcon icon = new ImageIcon(\"Source/icon.png\");\r\n public static String iconPath = \"Source/icon.png\";\r\n\r\n public static String UserPassPath = \"userpass.t...
import javax.swing.*; import javax.swing.tree.*; import java.awt.event.*; import java.io.*; import java.nio.file.Files; import static Classes.Pathes.FilesPath.*; import static Classes.Theme.SoundEffect.errorSound; import static Frames.Admin.ProfileManagment.UserEditor.deletedFilePath; import static Frames.Order.UniversitySelfRestaurant.*;
14,050
} } else if (result == JOptionPane.NO_OPTION) { JFileChooser fileChooser = new JFileChooser(); int chooserResult = fileChooser.showOpenDialog(frame); if (chooserResult == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); File file = new File(BalancesPath); if (file.exists()) { file.delete(); } try { Files.copy(selectedFile.toPath(), file.toPath()); JOptionPane.showMessageDialog(frame, "فایل با موفقیت جابجا شد."); } catch (IOException ex) { try { errorSound(); } catch (Exception exc) { } JOptionPane.showMessageDialog(frame, "خطا در جایجایی فایل : " + ex.getMessage()); } } } } else if (selectedNode.equals(balances)) { Object[] options = {"مشاهده", "جایگزینی فایل", "لغو"}; int result = JOptionPane.showOptionDialog(frame, "آیا میخواهید فایل را مشاهده یا ویرایش کنید ؟", "موجودی ها", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); if (result == JOptionPane.YES_OPTION) { try { File file = new File(BalancesPath); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line).append("\n"); } reader.close(); JOptionPane.showMessageDialog(frame, content.toString()); } catch (IOException ex) { try { errorSound(); } catch (Exception exc) { } JOptionPane.showMessageDialog(frame, "خطا در خواندن فایل : " + ex.getMessage()); } } else if (result == JOptionPane.NO_OPTION) { JFileChooser fileChooser = new JFileChooser(); int chooserResult = fileChooser.showOpenDialog(frame); if (chooserResult == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); File file = new File(BalancesPath); if (file.exists()) { file.delete(); } try { Files.copy(selectedFile.toPath(), file.toPath()); JOptionPane.showMessageDialog(frame, "فایل با موفقیت جابجا شد."); } catch (IOException ex) { try { errorSound(); } catch (Exception exc) { } JOptionPane.showMessageDialog(frame, "خطا در جایجایی فایل : " + ex.getMessage()); } } } } else if (selectedNode.equals(chargeHistory)) { Object[] options = {"مشاهده", "جایگزینی فایل", "لغو"}; int result = JOptionPane.showOptionDialog(frame, "آیا میخواهید فایل را مشاهده یا ویرایش کنید ؟", "سوابق شارژ", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); if (result == JOptionPane.YES_OPTION) { try { File file = new File(ChargeHistoryPath); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line).append("\n"); } reader.close(); JOptionPane.showMessageDialog(frame, content.toString()); } catch (IOException ex) { try { errorSound(); } catch (Exception exc) { } JOptionPane.showMessageDialog(frame, "خطا در خواندن فایل : " + ex.getMessage()); } } else if (result == JOptionPane.NO_OPTION) { JFileChooser fileChooser = new JFileChooser(); int chooserResult = fileChooser.showOpenDialog(frame); if (chooserResult == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); File file = new File(ChargeHistoryPath); if (file.exists()) { file.delete(); } try { Files.copy(selectedFile.toPath(), file.toPath()); JOptionPane.showMessageDialog(frame, "فایل با موفقیت جابجا شد."); } catch (IOException ex) { try { errorSound(); } catch (Exception exc) { } JOptionPane.showMessageDialog(frame, "خطا در جایجایی فایل : " + ex.getMessage()); } } } } else if (selectedNode.equals(deletedUsers)) { Object[] options = {"مشاهده", "جایگزینی فایل", "لغو"}; int result = JOptionPane.showOptionDialog(frame, "آیا میخواهید فایل را مشاهده یا ویرایش کنید ؟", "کاربران حذف شده", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); if (result == JOptionPane.YES_OPTION) { try {
package Frames.Admin.Managment; /* این کد جاوا یک درخت JTree با سه گره اصلی "کاربران"، "مالی" و "سفارش" ایجاد می کند. هر گره اصلی دارای چندین گره فرزند است که می توان آنها را در JTree باز یا بسته کرد. وقتی یک گره کلیک می شود، کد بررسی می کند کدام گره کلیک شده است و بر اساس گره کلیک شده عملی خاصی انجام می دهد. و فایل مربوظ به همان مورد بررسی قرار میگیرد به عنوان مثال، اگر گره "ادمین ها" کلیک شود، یک جعبه گفتگو با سه گزینه "مشاهده"، "جایگزینی فایل" و "لغو" نمایش داده می شود. اگر کاربر گزینه "مشاهده" را انتخاب کند، کد محتوای فایل "AdminsPath" را می خواند و آن را در یک جعبه گفتگو نمایش می دهد. اگر کاربر گزینه "جایگزینی فایل" را انتخاب کند، یک جعبه انتخاب فایل نمایش داده می شود تا به کاربر اجازه دهد فایل جدیدی را انتخاب کند و جایگزین فایل موجود شود. */ public class DataBaseManagment { public DataBaseManagment () { JFrame frame = new JFrame("مدیریت پایگاه های داده"); DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root"); DefaultMutableTreeNode admins = new DefaultMutableTreeNode("ادمین ها"); DefaultMutableTreeNode balances = new DefaultMutableTreeNode("موجودی ها"); DefaultMutableTreeNode chargeHistory = new DefaultMutableTreeNode("سوابق شارژ"); DefaultMutableTreeNode deletedUsers = new DefaultMutableTreeNode("کاربران حذف شده"); DefaultMutableTreeNode dinners = new DefaultMutableTreeNode("شام"); DefaultMutableTreeNode lunches = new DefaultMutableTreeNode("ناهار"); DefaultMutableTreeNode discounts = new DefaultMutableTreeNode("تخفیفات"); DefaultMutableTreeNode log = new DefaultMutableTreeNode("سوابق ورود"); DefaultMutableTreeNode orders = new DefaultMutableTreeNode("سفارشات"); DefaultMutableTreeNode userpass = new DefaultMutableTreeNode("کاربران"); DefaultMutableTreeNode usersRoot = new DefaultMutableTreeNode("کاربران"); usersRoot.add(admins); usersRoot.add(userpass); usersRoot.add(log); usersRoot.add(deletedUsers); DefaultMutableTreeNode financialRoot = new DefaultMutableTreeNode("مالی"); financialRoot.add(balances); financialRoot.add(chargeHistory); financialRoot.add(discounts); DefaultMutableTreeNode ordersRoot = new DefaultMutableTreeNode("سفارش"); ordersRoot.add(orders); ordersRoot.add(lunches); ordersRoot.add(dinners); root.add(usersRoot); root.add(financialRoot); root.add(ordersRoot); JTree tree = new JTree(root); tree.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { int selectedRow = tree.getRowForLocation(e.getX(), e.getY()); TreePath selectedPath = tree.getPathForLocation(e.getX(), e.getY()); if (selectedRow != -1) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectedPath.getLastPathComponent(); if (selectedNode.equals(admins)) { Object[] options = {"مشاهده", "جایگزینی فایل", "لغو"}; int result = JOptionPane.showOptionDialog(frame, "آیا میخواهید فایل را مشاهده یا ویرایش کنید ؟", "ادمین ها", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); if (result == JOptionPane.YES_OPTION) { try { File file = new File(AdminsPath); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line).append("\n"); } reader.close(); JOptionPane.showMessageDialog(frame, content.toString()); } catch (IOException ex) { try { errorSound(); } catch (Exception exc) { } JOptionPane.showMessageDialog(frame, "خطا در خواندن فایل : " + ex.getMessage()); } } else if (result == JOptionPane.NO_OPTION) { JFileChooser fileChooser = new JFileChooser(); int chooserResult = fileChooser.showOpenDialog(frame); if (chooserResult == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); File file = new File(AdminsPath); if (file.exists()) { file.delete(); } try { Files.copy(selectedFile.toPath(), file.toPath()); JOptionPane.showMessageDialog(frame, "فایل با موفقیت جابجا شد."); } catch (IOException ex) { try { errorSound(); } catch (Exception exc) { } JOptionPane.showMessageDialog(frame, "خطا در جایجایی فایل : " + ex.getMessage()); } } } } else if (selectedNode.equals(balances)) { Object[] options = {"مشاهده", "جایگزینی فایل", "لغو"}; int result = JOptionPane.showOptionDialog(frame, "آیا میخواهید فایل را مشاهده یا ویرایش کنید ؟", "موجودی ها", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); if (result == JOptionPane.YES_OPTION) { try { File file = new File(BalancesPath); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line).append("\n"); } reader.close(); JOptionPane.showMessageDialog(frame, content.toString()); } catch (IOException ex) { try { errorSound(); } catch (Exception exc) { } JOptionPane.showMessageDialog(frame, "خطا در خواندن فایل : " + ex.getMessage()); } } else if (result == JOptionPane.NO_OPTION) { JFileChooser fileChooser = new JFileChooser(); int chooserResult = fileChooser.showOpenDialog(frame); if (chooserResult == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); File file = new File(BalancesPath); if (file.exists()) { file.delete(); } try { Files.copy(selectedFile.toPath(), file.toPath()); JOptionPane.showMessageDialog(frame, "فایل با موفقیت جابجا شد."); } catch (IOException ex) { try { errorSound(); } catch (Exception exc) { } JOptionPane.showMessageDialog(frame, "خطا در جایجایی فایل : " + ex.getMessage()); } } } } else if (selectedNode.equals(balances)) { Object[] options = {"مشاهده", "جایگزینی فایل", "لغو"}; int result = JOptionPane.showOptionDialog(frame, "آیا میخواهید فایل را مشاهده یا ویرایش کنید ؟", "موجودی ها", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); if (result == JOptionPane.YES_OPTION) { try { File file = new File(BalancesPath); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line).append("\n"); } reader.close(); JOptionPane.showMessageDialog(frame, content.toString()); } catch (IOException ex) { try { errorSound(); } catch (Exception exc) { } JOptionPane.showMessageDialog(frame, "خطا در خواندن فایل : " + ex.getMessage()); } } else if (result == JOptionPane.NO_OPTION) { JFileChooser fileChooser = new JFileChooser(); int chooserResult = fileChooser.showOpenDialog(frame); if (chooserResult == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); File file = new File(BalancesPath); if (file.exists()) { file.delete(); } try { Files.copy(selectedFile.toPath(), file.toPath()); JOptionPane.showMessageDialog(frame, "فایل با موفقیت جابجا شد."); } catch (IOException ex) { try { errorSound(); } catch (Exception exc) { } JOptionPane.showMessageDialog(frame, "خطا در جایجایی فایل : " + ex.getMessage()); } } } } else if (selectedNode.equals(chargeHistory)) { Object[] options = {"مشاهده", "جایگزینی فایل", "لغو"}; int result = JOptionPane.showOptionDialog(frame, "آیا میخواهید فایل را مشاهده یا ویرایش کنید ؟", "سوابق شارژ", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); if (result == JOptionPane.YES_OPTION) { try { File file = new File(ChargeHistoryPath); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line).append("\n"); } reader.close(); JOptionPane.showMessageDialog(frame, content.toString()); } catch (IOException ex) { try { errorSound(); } catch (Exception exc) { } JOptionPane.showMessageDialog(frame, "خطا در خواندن فایل : " + ex.getMessage()); } } else if (result == JOptionPane.NO_OPTION) { JFileChooser fileChooser = new JFileChooser(); int chooserResult = fileChooser.showOpenDialog(frame); if (chooserResult == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); File file = new File(ChargeHistoryPath); if (file.exists()) { file.delete(); } try { Files.copy(selectedFile.toPath(), file.toPath()); JOptionPane.showMessageDialog(frame, "فایل با موفقیت جابجا شد."); } catch (IOException ex) { try { errorSound(); } catch (Exception exc) { } JOptionPane.showMessageDialog(frame, "خطا در جایجایی فایل : " + ex.getMessage()); } } } } else if (selectedNode.equals(deletedUsers)) { Object[] options = {"مشاهده", "جایگزینی فایل", "لغو"}; int result = JOptionPane.showOptionDialog(frame, "آیا میخواهید فایل را مشاهده یا ویرایش کنید ؟", "کاربران حذف شده", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]); if (result == JOptionPane.YES_OPTION) { try {
File file = new File(deletedFilePath);
2
2023-11-03 08:35:22+00:00
16k
schadfield/shogi-explorer
src/main/java/com/chadfield/shogiexplorer/objects/GameAnalyser.java
[ { "identifier": "AnalysisManager", "path": "src/main/java/com/chadfield/shogiexplorer/main/AnalysisManager.java", "snippet": "public class AnalysisManager {\n\n private AnalysisManager() {\n throw new IllegalStateException(\"Utility class\");\n }\n\n public static void save(Analysis anal...
import com.chadfield.shogiexplorer.main.AnalysisManager; import com.chadfield.shogiexplorer.main.EngineManager; import com.chadfield.shogiexplorer.main.SFENParser; import com.chadfield.shogiexplorer.objects.Board.Turn; import com.chadfield.shogiexplorer.utils.NotationUtils; import com.chadfield.shogiexplorer.utils.ParserUtils; import static com.chadfield.shogiexplorer.utils.StringUtils.getFileExtension; import com.ibm.icu.text.Transliterator; import java.awt.Rectangle; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JList; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.DefaultIntervalXYDataset;
13,802
/* Copyright © 2021, 2022 Stephen R Chadfield. This file is part of Shogi Explorer. Shogi Explorer 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. Shogi Explorer 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 Shogi Explorer. If not, see <https://www.gnu.org/licenses/>. */ package com.chadfield.shogiexplorer.objects; public class GameAnalyser { private Process process; private OutputStream stdin; private BufferedReader bufferedReader; private String lastScore = ""; private String opinion = ""; private int analysisTimePerMove; private static final int ANALYSIS_MISTAKE_THRESHOLD = 250; private static final int ANALYSIS_BLUNDER_THRESHOLD = 500; private static final int ANALYSIS_IGNORE_THRESHOLD = 2000; double[] x1Start; double[] x1; double[] x1End; double[] y1Start; double[] y1; double[] y1End; double[][] data1; double[] x2Start; double[] x2; double[] x2End; double[] y2Start; double[] y2; double[] y2End; double[][] data2; XYPlot plot; int range; String scoreStr; List<Integer> scoreList; JRadioButtonMenuItem graphView1; JRadioButtonMenuItem graphView2; JRadioButtonMenuItem graphView3; JButton stopAnalysisToolbarButton; JMenuItem stopAnalysisMenuItem; JMenuItem analyseGameMenuItem; JButton analyseGameToolbarButton; JMenuItem analysePositionMenuItem; JButton analysePositionToolbarButton; JMenuItem resumeAnalysisMenuItem; JButton resumeAnalysisToolbarButton; Transliterator trans = Transliterator.getInstance("Halfwidth-Fullwidth");
/* Copyright © 2021, 2022 Stephen R Chadfield. This file is part of Shogi Explorer. Shogi Explorer 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. Shogi Explorer 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 Shogi Explorer. If not, see <https://www.gnu.org/licenses/>. */ package com.chadfield.shogiexplorer.objects; public class GameAnalyser { private Process process; private OutputStream stdin; private BufferedReader bufferedReader; private String lastScore = ""; private String opinion = ""; private int analysisTimePerMove; private static final int ANALYSIS_MISTAKE_THRESHOLD = 250; private static final int ANALYSIS_BLUNDER_THRESHOLD = 500; private static final int ANALYSIS_IGNORE_THRESHOLD = 2000; double[] x1Start; double[] x1; double[] x1End; double[] y1Start; double[] y1; double[] y1End; double[][] data1; double[] x2Start; double[] x2; double[] x2End; double[] y2Start; double[] y2; double[] y2End; double[][] data2; XYPlot plot; int range; String scoreStr; List<Integer> scoreList; JRadioButtonMenuItem graphView1; JRadioButtonMenuItem graphView2; JRadioButtonMenuItem graphView3; JButton stopAnalysisToolbarButton; JMenuItem stopAnalysisMenuItem; JMenuItem analyseGameMenuItem; JButton analyseGameToolbarButton; JMenuItem analysePositionMenuItem; JButton analysePositionToolbarButton; JMenuItem resumeAnalysisMenuItem; JButton resumeAnalysisToolbarButton; Transliterator trans = Transliterator.getInstance("Halfwidth-Fullwidth");
Turn turn;
3
2023-11-08 09:24:57+00:00
16k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/service/impl/FileServiceImpl.java
[ { "identifier": "FileAdapt", "path": "talktime-minio/src/main/java/com/qingmeng/adapt/FileAdapt.java", "snippet": "public class FileAdapt {\n\n\n /**\n * 构建 minio vo\n *\n * @param uploadUrl 上传网址\n * @param downloadUrl 下载网址\n * @return {@link MinioVO }\n * @author qingmeng\n...
import cn.hutool.core.util.RandomUtil; import cn.hutool.extra.qrcode.QrCodeUtil; import cn.hutool.extra.qrcode.QrConfig; import com.qingmeng.adapt.FileAdapt; import com.qingmeng.config.adapt.UserInfoAdapt; import com.qingmeng.config.cache.UserCache; import com.qingmeng.config.cache.UserFriendSettingCache; import com.qingmeng.constant.SystemConstant; import com.qingmeng.dao.SysUserDao; import com.qingmeng.dto.file.MinioDTO; import com.qingmeng.dto.file.ScanQrcodeDTO; import com.qingmeng.dto.file.UploadUrlDTO; import com.qingmeng.dto.login.CheckFriendDTO; import com.qingmeng.entity.SysUser; import com.qingmeng.entity.SysUserFriendSetting; import com.qingmeng.enums.system.ScanQrcodeEnum; import com.qingmeng.enums.system.UploadSceneEnum; import com.qingmeng.service.FileService; import com.qingmeng.service.MinioService; import com.qingmeng.service.SysUserFriendService; import com.qingmeng.utils.AssertUtils; import com.qingmeng.utils.CommonUtils; import com.qingmeng.vo.common.ScanQrcodeInfoVO; import com.qingmeng.vo.file.MinioVO; import com.qingmeng.vo.user.CheckFriendVO; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.io.File; import java.util.ArrayList; import java.util.Objects;
13,578
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年12月05日 21:51:00 */ @Service public class FileServiceImpl implements FileService { @Resource private MinioService minioSerivce; @Resource private UserCache userCache; @Resource private SysUserDao sysUserDao; @Resource private SysUserFriendService sysUserFriendService; @Resource private UserFriendSettingCache userFriendSettingCache; /** * 获取二维码网址 * * @param userId 用户 ID * @return {@link String } * @author qingmeng * @createTime: 2023/12/05 21:59:23 */ @Override public String getQrcodeUrl(Long userId) { QrConfig config = new QrConfig(); config.setHeight(SystemConstant.QRCODE_HEIGHT); config.setWidth(SystemConstant.QRCODE_WIDTH); config.setImg(CommonUtils.getLogoImage()); File file = QrCodeUtil.generate( userId.toString(), config, new File(RandomUtil.randomString(10))); return minioSerivce.uploadFileByStream(userId, UploadSceneEnum.QRCODE.getType(), file); } /** * 获取预签名对象 URL * * @param userId 用户 ID * @param uploadUrlDTO 上传 URL DTO * @return {@link MinioVO } * @author qingmeng * @createTime: 2023/12/05 23:01:29 */ @Override public MinioVO getPreSignedObjectUrl(Long userId, UploadUrlDTO uploadUrlDTO) { MinioDTO minioDTO = FileAdapt.buildMinioDTO(userId, uploadUrlDTO); return minioSerivce.getPreSignedObjectUrl(minioDTO); } /** * 更新二维码网址 * * @param userId 用户 ID * @author qingmeng * @createTime: 2023/12/05 23:08:15 */ @Override @Transactional(rollbackFor = Exception.class) public void updateQrcodeUrl(Long userId) { String qrcodeUrl = getQrcodeUrl(userId); sysUserDao.updateQrcode(userId, qrcodeUrl); userCache.delete(userId); } /** * 扫描二维码信息 * * @param userId 用户 ID * @param scanQrcodeDTO 扫描二维码 DTO * @return {@link ScanQrcodeInfoVO }<{@link ? }> * @author qingmeng * @createTime: 2023/12/06 11:19:13 */ @Override
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年12月05日 21:51:00 */ @Service public class FileServiceImpl implements FileService { @Resource private MinioService minioSerivce; @Resource private UserCache userCache; @Resource private SysUserDao sysUserDao; @Resource private SysUserFriendService sysUserFriendService; @Resource private UserFriendSettingCache userFriendSettingCache; /** * 获取二维码网址 * * @param userId 用户 ID * @return {@link String } * @author qingmeng * @createTime: 2023/12/05 21:59:23 */ @Override public String getQrcodeUrl(Long userId) { QrConfig config = new QrConfig(); config.setHeight(SystemConstant.QRCODE_HEIGHT); config.setWidth(SystemConstant.QRCODE_WIDTH); config.setImg(CommonUtils.getLogoImage()); File file = QrCodeUtil.generate( userId.toString(), config, new File(RandomUtil.randomString(10))); return minioSerivce.uploadFileByStream(userId, UploadSceneEnum.QRCODE.getType(), file); } /** * 获取预签名对象 URL * * @param userId 用户 ID * @param uploadUrlDTO 上传 URL DTO * @return {@link MinioVO } * @author qingmeng * @createTime: 2023/12/05 23:01:29 */ @Override public MinioVO getPreSignedObjectUrl(Long userId, UploadUrlDTO uploadUrlDTO) { MinioDTO minioDTO = FileAdapt.buildMinioDTO(userId, uploadUrlDTO); return minioSerivce.getPreSignedObjectUrl(minioDTO); } /** * 更新二维码网址 * * @param userId 用户 ID * @author qingmeng * @createTime: 2023/12/05 23:08:15 */ @Override @Transactional(rollbackFor = Exception.class) public void updateQrcodeUrl(Long userId) { String qrcodeUrl = getQrcodeUrl(userId); sysUserDao.updateQrcode(userId, qrcodeUrl); userCache.delete(userId); } /** * 扫描二维码信息 * * @param userId 用户 ID * @param scanQrcodeDTO 扫描二维码 DTO * @return {@link ScanQrcodeInfoVO }<{@link ? }> * @author qingmeng * @createTime: 2023/12/06 11:19:13 */ @Override
public ScanQrcodeInfoVO<?> scanQrcodeInfo(Long userId,ScanQrcodeDTO scanQrcodeDTO) {
19
2023-11-07 16:04:55+00:00
16k
dingodb/dingo-expr
runtime/src/main/java/io/dingodb/expr/runtime/op/special/CaseFun.java
[ { "identifier": "EvalContext", "path": "runtime/src/main/java/io/dingodb/expr/runtime/EvalContext.java", "snippet": "public interface EvalContext extends Serializable {\n /**\n * Get the value of a variable by its id.\n *\n * @param id the id of the variable\n * @return the value of t...
import java.util.ArrayList; import java.util.List; import io.dingodb.expr.runtime.EvalContext; import io.dingodb.expr.runtime.ExprConfig; import io.dingodb.expr.runtime.expr.Expr; import io.dingodb.expr.runtime.expr.Exprs; import io.dingodb.expr.runtime.expr.Val; import io.dingodb.expr.runtime.expr.VariadicOpExpr; import io.dingodb.expr.runtime.op.VariadicOp; import io.dingodb.expr.runtime.type.Type; import io.dingodb.expr.runtime.type.Types; import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.checkerframework.checker.nullness.qual.NonNull;
11,012
/* * Copyright 2021 DataCanvas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dingodb.expr.runtime.op.special; @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public class CaseFun extends VariadicOp { public static final CaseFun INSTANCE = new CaseFun(Types.ANY); public static final String NAME = "CASE"; private static final long serialVersionUID = -898834141136092315L; @Getter private final Type type; @Override public Object eval(@NonNull Expr @NonNull [] exprs, EvalContext context, ExprConfig config) { int size = exprs.length; for (int i = 0; i < size - 1; i += 2) { Expr expr = exprs[i]; Object v = expr.eval(context, config); if (v != null && (Boolean) v) { return exprs[i + 1].eval(context, config); } } // There will be a `null` if you missed `ELSE` in SQL. return exprs[size - 1].eval(context, config); } @Override public Object keyOf(@NonNull Type @NonNull ... types) { Type type = null; int len = types.length; if (len % 2 != 1) { return null; } for (int i = 0; i < types.length - 1; i += 2) { if (!Types.BOOL.matches(types[i])) { return null; } if (type != null) { if (!type.matches(types[i + 1])) { return null; } } else if (!types[i + 1].equals(Types.NULL)) { type = types[i + 1]; } } if (type != null) { if (!type.matches(types[len - 1])) { return null; } } else { type = types[len - 1]; } return type; } @Override public @NonNull Expr simplify(@NonNull VariadicOpExpr expr, ExprConfig config) { int size = expr.getOperands().length; List<Expr> nonConstExprs = new ArrayList<>(size); for (int i = 0; i < size - 1; i += 2) { Expr operand = expr.getOperands()[i]; Expr operand1 = expr.getOperands()[i + 1];
/* * Copyright 2021 DataCanvas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dingodb.expr.runtime.op.special; @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public class CaseFun extends VariadicOp { public static final CaseFun INSTANCE = new CaseFun(Types.ANY); public static final String NAME = "CASE"; private static final long serialVersionUID = -898834141136092315L; @Getter private final Type type; @Override public Object eval(@NonNull Expr @NonNull [] exprs, EvalContext context, ExprConfig config) { int size = exprs.length; for (int i = 0; i < size - 1; i += 2) { Expr expr = exprs[i]; Object v = expr.eval(context, config); if (v != null && (Boolean) v) { return exprs[i + 1].eval(context, config); } } // There will be a `null` if you missed `ELSE` in SQL. return exprs[size - 1].eval(context, config); } @Override public Object keyOf(@NonNull Type @NonNull ... types) { Type type = null; int len = types.length; if (len % 2 != 1) { return null; } for (int i = 0; i < types.length - 1; i += 2) { if (!Types.BOOL.matches(types[i])) { return null; } if (type != null) { if (!type.matches(types[i + 1])) { return null; } } else if (!types[i + 1].equals(Types.NULL)) { type = types[i + 1]; } } if (type != null) { if (!type.matches(types[len - 1])) { return null; } } else { type = types[len - 1]; } return type; } @Override public @NonNull Expr simplify(@NonNull VariadicOpExpr expr, ExprConfig config) { int size = expr.getOperands().length; List<Expr> nonConstExprs = new ArrayList<>(size); for (int i = 0; i < size - 1; i += 2) { Expr operand = expr.getOperands()[i]; Expr operand1 = expr.getOperands()[i + 1];
if (operand instanceof Val) {
4
2023-11-04 08:43:49+00:00
16k
Arborsm/ArborCore
src/main/java/org/arbor/gtnn/data/GTNNMachines.java
[ { "identifier": "GTNN", "path": "src/main/java/org/arbor/gtnn/GTNN.java", "snippet": "@Mod(GTNN.MODID)\npublic class GTNN {\n\n public static final String MODID = \"gtnn\";\n public static final Logger LOGGER = LogUtils.getLogger();\n\n public GTNN() {\n MinecraftForge.EVENT_BUS.register...
import com.gregtechceu.gtceu.GTCEu; import com.gregtechceu.gtceu.api.GTValues; import com.gregtechceu.gtceu.api.block.ICoilType; import com.gregtechceu.gtceu.api.data.RotationState; import com.gregtechceu.gtceu.api.data.chemical.ChemicalHelper; import com.gregtechceu.gtceu.api.data.tag.TagPrefix; import com.gregtechceu.gtceu.api.machine.IMachineBlockEntity; import com.gregtechceu.gtceu.api.machine.MachineDefinition; import com.gregtechceu.gtceu.api.machine.MetaMachine; import com.gregtechceu.gtceu.api.machine.MultiblockMachineDefinition; import com.gregtechceu.gtceu.api.machine.multiblock.PartAbility; import com.gregtechceu.gtceu.api.pattern.FactoryBlockPattern; import com.gregtechceu.gtceu.api.pattern.MultiblockShapeInfo; import com.gregtechceu.gtceu.api.pattern.Predicates; import com.gregtechceu.gtceu.api.registry.registrate.MachineBuilder; import com.gregtechceu.gtceu.common.data.GTBlocks; import com.gregtechceu.gtceu.common.data.GTMachines; import com.gregtechceu.gtceu.common.data.GTMaterials; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import org.arbor.gtnn.GTNN; import org.arbor.gtnn.api.machine.multiblock.APartAbility; import org.arbor.gtnn.api.machine.multiblock.ChemicalPlant; import org.arbor.gtnn.api.machine.multiblock.NeutronActivator; import org.arbor.gtnn.api.machine.multiblock.part.HighSpeedPipeBlock; import org.arbor.gtnn.api.machine.multiblock.part.NeutronAccelerator; import org.arbor.gtnn.api.pattern.APredicates; import org.arbor.gtnn.block.BlockTier; import org.arbor.gtnn.block.MachineCasingBlock; import org.arbor.gtnn.block.PipeBlock; import org.arbor.gtnn.block.PlantCasingBlock; import org.arbor.gtnn.client.renderer.machine.BlockMachineRenderer; import org.arbor.gtnn.client.renderer.machine.GTPPMachineRenderer; import java.util.*; import java.util.function.BiFunction; import static com.gregtechceu.gtceu.api.GTValues.V; import static com.gregtechceu.gtceu.api.GTValues.VNF; import static com.gregtechceu.gtceu.api.pattern.Predicates.abilities; import static com.gregtechceu.gtceu.api.pattern.Predicates.autoAbilities; import static com.gregtechceu.gtceu.api.pattern.util.RelativeDirection.*; import static org.arbor.gtnn.api.registry.GTNNRegistries.REGISTRATE;
10,874
package org.arbor.gtnn.data; @SuppressWarnings("unused") public class GTNNMachines { public static final int[] NA_TIERS = GTValues.tiersBetween(1, 8); static { REGISTRATE.creativeModeTab(() -> GTNNCreativeModeTabs.MAIN_TAB); } ////////////////////////////////////// //********** Part **********// ////////////////////////////////////// public static final MachineDefinition[] NEUTRON_ACCELERATOR = registerTieredMachines("neutron_accelerator", NeutronAccelerator::new, (tier, builder) ->builder .langValue(VNF[tier] + "Neutron Accelerator") .rotationState(RotationState.ALL) .abilities(APartAbility.NEUTRON_ACCELERATOR) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip1")) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip2", V[tier])) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip3", V[tier] * 8 / 10)) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip4")) .overlayTieredHullRenderer("neutron_accelerator") .compassNode("neutron_accelerator") .register(), NA_TIERS); public static final MachineDefinition HIGH_SPEED_PIPE_BLOCK = REGISTRATE.machine("high_speed_pipe_block", HighSpeedPipeBlock::new) .renderer(() -> new BlockMachineRenderer(GTNN.id("block/machine/part/high_speed_pipe_block"))) .rotationState(RotationState.Y_AXIS) .register(); // public static final MachineDefinition CATALYTIC_HATCH = GTRegistries.REGISTRATE.machine("catalytic_hatch", // (holder) -> new SteamItemBusPartMachine(holder, IO.IN)) // .rotationState(RotationState.ALL) // .abilities(PartAbility.IMPORT_ITEMS) // .overlaySteamHullRenderer("item_bus.import") // .langValue("Catalytic Hatch") // .compassSections(GTCompassSections.PARTS) // .compassNode("item_bus") // .register(); ////////////////////////////////////// //********** Machine **********// ////////////////////////////////////// public static final MultiblockMachineDefinition CHEMICAL_PLANT = REGISTRATE.multiblock("chemical_plant", ChemicalPlant::new) .rotationState(RotationState.NON_Y_AXIS) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip1")) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip2")) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip3")) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip4")) .recipeTypes(GTNNRecipesTypes.CHEMICAL_PLANT_RECIPES) .recipeModifier(ChemicalPlant::chemicalPlantRecipe) .appearanceBlock(GTBlocks.CASING_BRONZE_BRICKS) .pattern(definition -> FactoryBlockPattern.start() .aisle("VVVVVVV", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .aisle("VBBBBBV", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("VBBBBBV", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("VBBBBBV", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("VBBBBBV", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("VBBBBBV", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("AVVSVVA", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .where("S", Predicates.controller(Predicates.blocks(definition.get()))) .where("V", APredicates.plantCasings() .or(autoAbilities(definition.getRecipeTypes())) .or(autoAbilities(true, false, false)) .or(abilities(PartAbility.INPUT_ENERGY)) .or(abilities(PartAbility.IMPORT_ITEMS)) .or(abilities(PartAbility.EXPORT_ITEMS)) .or(abilities(PartAbility.IMPORT_FLUIDS)) .or(abilities(PartAbility.EXPORT_FLUIDS)) ) .where("A", APredicates.plantCasings()) .where("D", APredicates.pipeBlock()) .where("C", Predicates.heatingCoils()) .where("B", APredicates.machineCasing()) .where("#", Predicates.air()) .build()) .shapeInfos(definition -> { List<MultiblockShapeInfo> shapeInfo = new ArrayList<>(); var builder = MultiblockShapeInfo.builder() .aisle("AAOSJAA", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .aisle("MBBBBBN", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("KBBBBBL", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("ABBBBBA", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("ABBBBBA", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("ABBBBBA", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("AAAAAAA", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .where('S', definition, Direction.NORTH) .where('#', Blocks.AIR.defaultBlockState()) .where('J', GTMachines.MAINTENANCE_HATCH, Direction.NORTH); Map<Integer, BlockState> shapeBlock = new HashMap<>(); for (PlantCasingBlock.PlantCasing casing : PlantCasingBlock.PlantCasing.values()) { shapeBlock.put(casing.getTier() + 10, casing.getPlantCasing(casing.getTier()).getDefaultState()); } for (MachineCasingBlock.MachineCasing machineCasing : MachineCasingBlock.MachineCasing.values()) { shapeBlock.put(machineCasing.getTier() + 20, machineCasing.getMachineCasing(machineCasing.getTier()).getDefaultState()); } for (ICoilType coil : GTBlocks.ALL_COILS.keySet()) { shapeBlock.put(coil.getTier() + 30, GTBlocks.ALL_COILS.get(coil).get().defaultBlockState()); } for (PipeBlock.Pipe pipe : PipeBlock.Pipe.values()) { shapeBlock.put(pipe.getTier() + 40, pipe.getPipe(pipe.getTier()).getDefaultState()); } for (BlockTier tier : BlockTier.values()) { builder.where('A', shapeBlock.get(tier.tier() + 10)); builder.where('B', shapeBlock.get(tier.tier() + 20)); builder.where('C', shapeBlock.get(tier.tier() + 30)); builder.where('D', shapeBlock.get(tier.tier() + 40)); builder.where('K', GTMachines.ITEM_IMPORT_BUS[tier.tier()], Direction.NORTH); builder.where('L', GTMachines.ITEM_EXPORT_BUS[tier.tier()], Direction.NORTH); builder.where('M', GTMachines.FLUID_IMPORT_HATCH[tier.tier()], Direction.NORTH); builder.where('N', GTMachines.FLUID_EXPORT_HATCH[tier.tier()], Direction.NORTH); builder.where('O', GTMachines.ENERGY_INPUT_HATCH[tier.tier()], Direction.NORTH); shapeInfo.add(builder.shallowCopy().build()); } return shapeInfo; }) .renderer(() -> new GTPPMachineRenderer(GTCEu.id("block/casings/solid/machine_casing_bronze_plated_bricks"), GTNN.id("block/multiblock/chemical_plant"), false)) .additionalDisplay((controller, components) -> { if (controller instanceof ChemicalPlant chemicalPlant && controller.isFormed()) { components.add(Component.translatable("gtceu.multiblock.chemical_plant.heating_coil", chemicalPlant.getCoilTier() * 50)); components.add(Component.translatable("gtceu.multiblock.chemical_plant.parallel_level", chemicalPlant.getPipeTier() * 2)); components.add(Component.translatable("gtceu.multiblock.chemical_plant.tier", VNF[chemicalPlant.getPlantCasingTier()])); } }) .register();
package org.arbor.gtnn.data; @SuppressWarnings("unused") public class GTNNMachines { public static final int[] NA_TIERS = GTValues.tiersBetween(1, 8); static { REGISTRATE.creativeModeTab(() -> GTNNCreativeModeTabs.MAIN_TAB); } ////////////////////////////////////// //********** Part **********// ////////////////////////////////////// public static final MachineDefinition[] NEUTRON_ACCELERATOR = registerTieredMachines("neutron_accelerator", NeutronAccelerator::new, (tier, builder) ->builder .langValue(VNF[tier] + "Neutron Accelerator") .rotationState(RotationState.ALL) .abilities(APartAbility.NEUTRON_ACCELERATOR) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip1")) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip2", V[tier])) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip3", V[tier] * 8 / 10)) .tooltips(Component.translatable("gtceu.machine.neutron_accelerator.tooltip4")) .overlayTieredHullRenderer("neutron_accelerator") .compassNode("neutron_accelerator") .register(), NA_TIERS); public static final MachineDefinition HIGH_SPEED_PIPE_BLOCK = REGISTRATE.machine("high_speed_pipe_block", HighSpeedPipeBlock::new) .renderer(() -> new BlockMachineRenderer(GTNN.id("block/machine/part/high_speed_pipe_block"))) .rotationState(RotationState.Y_AXIS) .register(); // public static final MachineDefinition CATALYTIC_HATCH = GTRegistries.REGISTRATE.machine("catalytic_hatch", // (holder) -> new SteamItemBusPartMachine(holder, IO.IN)) // .rotationState(RotationState.ALL) // .abilities(PartAbility.IMPORT_ITEMS) // .overlaySteamHullRenderer("item_bus.import") // .langValue("Catalytic Hatch") // .compassSections(GTCompassSections.PARTS) // .compassNode("item_bus") // .register(); ////////////////////////////////////// //********** Machine **********// ////////////////////////////////////// public static final MultiblockMachineDefinition CHEMICAL_PLANT = REGISTRATE.multiblock("chemical_plant", ChemicalPlant::new) .rotationState(RotationState.NON_Y_AXIS) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip1")) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip2")) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip3")) .tooltips(Component.translatable("gtceu.multiblock.chemical_plant.tooltip4")) .recipeTypes(GTNNRecipesTypes.CHEMICAL_PLANT_RECIPES) .recipeModifier(ChemicalPlant::chemicalPlantRecipe) .appearanceBlock(GTBlocks.CASING_BRONZE_BRICKS) .pattern(definition -> FactoryBlockPattern.start() .aisle("VVVVVVV", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .aisle("VBBBBBV", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("VBBBBBV", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("VBBBBBV", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("VBBBBBV", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("VBBBBBV", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("AVVSVVA", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .where("S", Predicates.controller(Predicates.blocks(definition.get()))) .where("V", APredicates.plantCasings() .or(autoAbilities(definition.getRecipeTypes())) .or(autoAbilities(true, false, false)) .or(abilities(PartAbility.INPUT_ENERGY)) .or(abilities(PartAbility.IMPORT_ITEMS)) .or(abilities(PartAbility.EXPORT_ITEMS)) .or(abilities(PartAbility.IMPORT_FLUIDS)) .or(abilities(PartAbility.EXPORT_FLUIDS)) ) .where("A", APredicates.plantCasings()) .where("D", APredicates.pipeBlock()) .where("C", Predicates.heatingCoils()) .where("B", APredicates.machineCasing()) .where("#", Predicates.air()) .build()) .shapeInfos(definition -> { List<MultiblockShapeInfo> shapeInfo = new ArrayList<>(); var builder = MultiblockShapeInfo.builder() .aisle("AAOSJAA", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .aisle("MBBBBBN", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("KBBBBBL", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("ABBBBBA", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("ABBBBBA", "#BCCCB#", "##DDD##", "##CCC##", "##DDD##", "#BCCCB#", "AAAAAAA") .aisle("ABBBBBA", "#BBBBB#", "#######", "#######", "#######", "#BBBBB#", "AAAAAAA") .aisle("AAAAAAA", "A#####A", "A#####A", "A#####A", "A#####A", "A#####A", "AAAAAAA") .where('S', definition, Direction.NORTH) .where('#', Blocks.AIR.defaultBlockState()) .where('J', GTMachines.MAINTENANCE_HATCH, Direction.NORTH); Map<Integer, BlockState> shapeBlock = new HashMap<>(); for (PlantCasingBlock.PlantCasing casing : PlantCasingBlock.PlantCasing.values()) { shapeBlock.put(casing.getTier() + 10, casing.getPlantCasing(casing.getTier()).getDefaultState()); } for (MachineCasingBlock.MachineCasing machineCasing : MachineCasingBlock.MachineCasing.values()) { shapeBlock.put(machineCasing.getTier() + 20, machineCasing.getMachineCasing(machineCasing.getTier()).getDefaultState()); } for (ICoilType coil : GTBlocks.ALL_COILS.keySet()) { shapeBlock.put(coil.getTier() + 30, GTBlocks.ALL_COILS.get(coil).get().defaultBlockState()); } for (PipeBlock.Pipe pipe : PipeBlock.Pipe.values()) { shapeBlock.put(pipe.getTier() + 40, pipe.getPipe(pipe.getTier()).getDefaultState()); } for (BlockTier tier : BlockTier.values()) { builder.where('A', shapeBlock.get(tier.tier() + 10)); builder.where('B', shapeBlock.get(tier.tier() + 20)); builder.where('C', shapeBlock.get(tier.tier() + 30)); builder.where('D', shapeBlock.get(tier.tier() + 40)); builder.where('K', GTMachines.ITEM_IMPORT_BUS[tier.tier()], Direction.NORTH); builder.where('L', GTMachines.ITEM_EXPORT_BUS[tier.tier()], Direction.NORTH); builder.where('M', GTMachines.FLUID_IMPORT_HATCH[tier.tier()], Direction.NORTH); builder.where('N', GTMachines.FLUID_EXPORT_HATCH[tier.tier()], Direction.NORTH); builder.where('O', GTMachines.ENERGY_INPUT_HATCH[tier.tier()], Direction.NORTH); shapeInfo.add(builder.shallowCopy().build()); } return shapeInfo; }) .renderer(() -> new GTPPMachineRenderer(GTCEu.id("block/casings/solid/machine_casing_bronze_plated_bricks"), GTNN.id("block/multiblock/chemical_plant"), false)) .additionalDisplay((controller, components) -> { if (controller instanceof ChemicalPlant chemicalPlant && controller.isFormed()) { components.add(Component.translatable("gtceu.multiblock.chemical_plant.heating_coil", chemicalPlant.getCoilTier() * 50)); components.add(Component.translatable("gtceu.multiblock.chemical_plant.parallel_level", chemicalPlant.getPipeTier() * 2)); components.add(Component.translatable("gtceu.multiblock.chemical_plant.tier", VNF[chemicalPlant.getPlantCasingTier()])); } }) .register();
public static final MultiblockMachineDefinition NEUTRON_ACTIVATOR = REGISTRATE.multiblock("neutron_activator", NeutronActivator::new)
3
2023-11-04 07:59:02+00:00
16k
BaderTim/minecraft-measurement-mod
src/main/java/io/github/mmm/measurement/device/DeviceController.java
[ { "identifier": "MMM", "path": "src/main/java/io/github/mmm/MMM.java", "snippet": "@Mod(MMM.MODID)\npublic class MMM {\n // Define mod id in a common place for everything to reference\n public static final String MODID = \"mmm\";\n // Directly reference a slf4j logger\n public static final L...
import io.github.mmm.MMM; import io.github.mmm.measurement.device.objects.imu.IMU; import io.github.mmm.measurement.device.objects.imu.IMUController; import io.github.mmm.measurement.device.objects.lidar.LiDAR; import io.github.mmm.measurement.device.objects.lidar.LiDARController; import io.github.mmm.measurement.device.scans.ImuScan; import io.github.mmm.measurement.device.scans.LidarScan; import io.github.mmm.measurement.device.scans.LidarScan2D; import io.github.mmm.modconfig.Config; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.player.LocalPlayer; import net.minecraft.network.chat.Component; import java.awt.*; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import static io.github.mmm.MMM.DEVICE_CONTROLLER; import static io.github.mmm.MMM.MMM_ROOT_PATH; import static io.github.mmm.Utils.saveStringToFile;
13,339
package io.github.mmm.measurement.device; public class DeviceController { private Boolean currentlyMeasuring; private int saveInterval; private String savePath; private boolean tickTimeWarning = false; private int tickTimeWarningTolerance; private LiDARController lidarController; private LiDAR lidar1; private LiDAR lidar2; private LiDAR lidar3; private IMUController imuController; private IMU imu1; public DeviceController() { System.out.println("Measure constructor"); this.currentlyMeasuring = false; } public Boolean isCurrentlyMeasuring() { return this.currentlyMeasuring; } public void startMeasure() { this.saveInterval = Config.SAVE_INTERVAL.get(); this.tickTimeWarning = Config.TICK_TIME_WARNING.get(); this.tickTimeWarningTolerance = Config.TICK_TIME_WARNING_TOLERANCE.get(); this.lidarController = new LiDARController(new LiDAR[]{lidar1, lidar2, lidar3}); this.imuController = new IMUController(imu1); String startTime = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss").format(LocalDateTime.now()); this.savePath = "device_measurements/" + startTime; try { Files.createDirectories(Paths.get(MMM_ROOT_PATH + this.savePath)); } catch (Exception e) { System.out.println("Error creating directory: " + e.getMessage()); } if(Config.LIDAR1_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar1.csv"); if(Config.LIDAR2_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar2.csv"); if(Config.LIDAR3_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar3.csv"); if(Config.IMU1_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;accX;accY;accZ,gyroX;gyroY;gyroZ\n", this.savePath, "imu1.csv"); Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".measure.start"), false); this.currentlyMeasuring = true; } public void stopMeasure() { // save remaining scans
package io.github.mmm.measurement.device; public class DeviceController { private Boolean currentlyMeasuring; private int saveInterval; private String savePath; private boolean tickTimeWarning = false; private int tickTimeWarningTolerance; private LiDARController lidarController; private LiDAR lidar1; private LiDAR lidar2; private LiDAR lidar3; private IMUController imuController; private IMU imu1; public DeviceController() { System.out.println("Measure constructor"); this.currentlyMeasuring = false; } public Boolean isCurrentlyMeasuring() { return this.currentlyMeasuring; } public void startMeasure() { this.saveInterval = Config.SAVE_INTERVAL.get(); this.tickTimeWarning = Config.TICK_TIME_WARNING.get(); this.tickTimeWarningTolerance = Config.TICK_TIME_WARNING_TOLERANCE.get(); this.lidarController = new LiDARController(new LiDAR[]{lidar1, lidar2, lidar3}); this.imuController = new IMUController(imu1); String startTime = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss").format(LocalDateTime.now()); this.savePath = "device_measurements/" + startTime; try { Files.createDirectories(Paths.get(MMM_ROOT_PATH + this.savePath)); } catch (Exception e) { System.out.println("Error creating directory: " + e.getMessage()); } if(Config.LIDAR1_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar1.csv"); if(Config.LIDAR2_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar2.csv"); if(Config.LIDAR3_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar3.csv"); if(Config.IMU1_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;accX;accY;accZ,gyroX;gyroY;gyroZ\n", this.savePath, "imu1.csv"); Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".measure.start"), false); this.currentlyMeasuring = true; } public void stopMeasure() { // save remaining scans
ArrayList<LidarScan>[] scans = DEVICE_CONTROLLER.getLidarController().getScans();
9
2023-11-06 16:56:46+00:00
16k
KilianCollins/road-runner-quickstart-master
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleTankDrive.java
[ { "identifier": "MAX_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double MAX_ACCEL = 73.17330064499293;" }, { "identifier": "MAX_ANG_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/Dr...
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV; import static org.openftc.apriltag.ApriltagDetectionJNI.getPoseEstimate; import com.acmerobotics.roadrunner.drive.TankDrive; import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.followers.TankPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TankVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
10,897
package org.firstinspires.ftc.teamcode.drive; /* * Simple tank drive hardware implementation for REV hardware. */ @Config public class SampleTankDrive extends TankDrive { public static PIDCoefficients AXIAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients CROSS_TRACK_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double VX_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint accelConstraint = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private List<DcMotorEx> motors, leftMotors, rightMotors; private IMU imu; private VoltageSensor batteryVoltageSensor; public SampleTankDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH); follower = new TankPIDVAFollower(AXIAL_PID, CROSS_TRACK_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5);
package org.firstinspires.ftc.teamcode.drive; /* * Simple tank drive hardware implementation for REV hardware. */ @Config public class SampleTankDrive extends TankDrive { public static PIDCoefficients AXIAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients CROSS_TRACK_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double VX_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint accelConstraint = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private List<DcMotorEx> motors, leftMotors, rightMotors; private IMU imu; private VoltageSensor batteryVoltageSensor; public SampleTankDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH); follower = new TankPIDVAFollower(AXIAL_PID, CROSS_TRACK_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5);
LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap);
14
2023-11-04 04:11:26+00:00
16k
conductor-oss/conductor
es7-persistence/src/test/java/com/netflix/conductor/es7/dao/index/TestElasticSearchRestDAOV7.java
[ { "identifier": "EventExecution", "path": "common/src/main/java/com/netflix/conductor/common/metadata/events/EventExecution.java", "snippet": "@ProtoMessage\npublic class EventExecution {\n\n @ProtoEnum\n public enum Status {\n IN_PROGRESS,\n COMPLETED,\n FAILED,\n SKIP...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; import java.util.function.Supplier; import org.joda.time.DateTime; import org.junit.Test; import com.netflix.conductor.common.metadata.events.EventExecution; import com.netflix.conductor.common.metadata.events.EventHandler; import com.netflix.conductor.common.metadata.tasks.TaskExecLog; import com.netflix.conductor.common.run.TaskSummary; import com.netflix.conductor.common.run.Workflow.WorkflowStatus; import com.netflix.conductor.common.run.WorkflowSummary; import com.netflix.conductor.core.events.queue.Message; import com.netflix.conductor.es7.utils.TestUtils; import com.google.common.collect.ImmutableMap;
12,843
List<String> ids = indexDAO.searchRecentRunningWorkflows(2, 1); assertEquals(1, ids.size()); assertEquals(recentWorkflow.getWorkflowId(), ids.get(0)); } @Test public void shouldCountWorkflows() { int counts = 1100; for (int i = 0; i < counts; i++) { WorkflowSummary workflowSummary = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflowSummary); } // wait for workflow to be indexed long result = tryGetCount(() -> getWorkflowCount("template_workflow", "RUNNING"), counts); assertEquals(counts, result); } private long tryGetCount(Supplier<Long> countFunction, int resultsCount) { long result = 0; for (int i = 0; i < 20; i++) { result = countFunction.get(); if (result == resultsCount) { return result; } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } } return result; } // Get total workflow counts given the name and status private long getWorkflowCount(String workflowName, String status) { return indexDAO.getWorkflowCount( "status=\"" + status + "\" AND workflowType=\"" + workflowName + "\"", "*"); } private void assertWorkflowSummary(String workflowId, WorkflowSummary summary) { assertEquals(summary.getWorkflowType(), indexDAO.get(workflowId, "workflowType")); assertEquals(String.valueOf(summary.getVersion()), indexDAO.get(workflowId, "version")); assertEquals(summary.getWorkflowId(), indexDAO.get(workflowId, "workflowId")); assertEquals(summary.getCorrelationId(), indexDAO.get(workflowId, "correlationId")); assertEquals(summary.getStartTime(), indexDAO.get(workflowId, "startTime")); assertEquals(summary.getUpdateTime(), indexDAO.get(workflowId, "updateTime")); assertEquals(summary.getEndTime(), indexDAO.get(workflowId, "endTime")); assertEquals(summary.getStatus().name(), indexDAO.get(workflowId, "status")); assertEquals(summary.getInput(), indexDAO.get(workflowId, "input")); assertEquals(summary.getOutput(), indexDAO.get(workflowId, "output")); assertEquals( summary.getReasonForIncompletion(), indexDAO.get(workflowId, "reasonForIncompletion")); assertEquals( String.valueOf(summary.getExecutionTime()), indexDAO.get(workflowId, "executionTime")); assertEquals(summary.getEvent(), indexDAO.get(workflowId, "event")); assertEquals( summary.getFailedReferenceTaskNames(), indexDAO.get(workflowId, "failedReferenceTaskNames")); } private String getFormattedTime(Date time) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); return sdf.format(time); } private <T> List<T> tryFindResults(Supplier<List<T>> searchFunction) { return tryFindResults(searchFunction, 1); } private <T> List<T> tryFindResults(Supplier<List<T>> searchFunction, int resultsCount) { List<T> result = Collections.emptyList(); for (int i = 0; i < 20; i++) { result = searchFunction.get(); if (result.size() == resultsCount) { return result; } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } } return result; } private List<String> searchWorkflows(String workflowId) { return indexDAO.searchWorkflows( "", "workflowId:\"" + workflowId + "\"", 0, 100, Collections.emptyList()) .getResults(); } private List<String> searchTasks(TaskSummary taskSummary) { return indexDAO.searchTasks( "", "workflowId:\"" + taskSummary.getWorkflowId() + "\"", 0, 100, Collections.emptyList()) .getResults(); } private TaskExecLog createLog(String taskId, String log) { TaskExecLog taskExecLog = new TaskExecLog(log); taskExecLog.setTaskId(taskId); return taskExecLog; } private EventExecution createEventExecution(String event) { EventExecution execution = new EventExecution(uuid(), uuid()); execution.setName("name"); execution.setEvent(event); execution.setCreated(System.currentTimeMillis()); execution.setStatus(EventExecution.Status.COMPLETED);
/* * Copyright 2023 Conductor Authors. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.es7.dao.index; public class TestElasticSearchRestDAOV7 extends ElasticSearchRestDaoBaseTest { private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyyMMWW"); private static final String INDEX_PREFIX = "conductor"; private static final String WORKFLOW_DOC_TYPE = "workflow"; private static final String TASK_DOC_TYPE = "task"; private static final String MSG_DOC_TYPE = "message"; private static final String EVENT_DOC_TYPE = "event"; private static final String LOG_DOC_TYPE = "task_log"; private boolean indexExists(final String index) throws IOException { return indexDAO.doesResourceExist("/" + index); } private boolean doesMappingExist(final String index, final String mappingName) throws IOException { return indexDAO.doesResourceExist("/" + index + "/_mapping/" + mappingName); } @Test public void assertInitialSetup() throws IOException { SIMPLE_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT")); String workflowIndex = INDEX_PREFIX + "_" + WORKFLOW_DOC_TYPE; String taskIndex = INDEX_PREFIX + "_" + TASK_DOC_TYPE; String taskLogIndex = INDEX_PREFIX + "_" + LOG_DOC_TYPE + "_" + SIMPLE_DATE_FORMAT.format(new Date()); String messageIndex = INDEX_PREFIX + "_" + MSG_DOC_TYPE + "_" + SIMPLE_DATE_FORMAT.format(new Date()); String eventIndex = INDEX_PREFIX + "_" + EVENT_DOC_TYPE + "_" + SIMPLE_DATE_FORMAT.format(new Date()); assertTrue("Index 'conductor_workflow' should exist", indexExists(workflowIndex)); assertTrue("Index 'conductor_task' should exist", indexExists(taskIndex)); assertTrue("Index '" + taskLogIndex + "' should exist", indexExists(taskLogIndex)); assertTrue("Index '" + messageIndex + "' should exist", indexExists(messageIndex)); assertTrue("Index '" + eventIndex + "' should exist", indexExists(eventIndex)); assertTrue( "Index template for 'message' should exist", indexDAO.doesResourceExist("/_template/template_" + MSG_DOC_TYPE)); assertTrue( "Index template for 'event' should exist", indexDAO.doesResourceExist("/_template/template_" + EVENT_DOC_TYPE)); assertTrue( "Index template for 'task_log' should exist", indexDAO.doesResourceExist("/_template/template_" + LOG_DOC_TYPE)); } @Test public void shouldIndexWorkflow() { WorkflowSummary workflowSummary = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflowSummary); assertWorkflowSummary(workflowSummary.getWorkflowId(), workflowSummary); } @Test public void shouldIndexWorkflowAsync() throws Exception { WorkflowSummary workflowSummary = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.asyncIndexWorkflow(workflowSummary).get(); assertWorkflowSummary(workflowSummary.getWorkflowId(), workflowSummary); } @Test public void shouldRemoveWorkflow() { WorkflowSummary workflowSummary = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflowSummary); // wait for workflow to be indexed List<String> workflows = tryFindResults(() -> searchWorkflows(workflowSummary.getWorkflowId()), 1); assertEquals(1, workflows.size()); indexDAO.removeWorkflow(workflowSummary.getWorkflowId()); workflows = tryFindResults(() -> searchWorkflows(workflowSummary.getWorkflowId()), 0); assertTrue("Workflow was not removed.", workflows.isEmpty()); } @Test public void shouldAsyncRemoveWorkflow() throws Exception { WorkflowSummary workflowSummary = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflowSummary); // wait for workflow to be indexed List<String> workflows = tryFindResults(() -> searchWorkflows(workflowSummary.getWorkflowId()), 1); assertEquals(1, workflows.size()); indexDAO.asyncRemoveWorkflow(workflowSummary.getWorkflowId()).get(); workflows = tryFindResults(() -> searchWorkflows(workflowSummary.getWorkflowId()), 0); assertTrue("Workflow was not removed.", workflows.isEmpty()); } @Test public void shouldUpdateWorkflow() { WorkflowSummary workflowSummary = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflowSummary); indexDAO.updateWorkflow( workflowSummary.getWorkflowId(), new String[] {"status"}, new Object[] {WorkflowStatus.COMPLETED}); workflowSummary.setStatus(WorkflowStatus.COMPLETED); assertWorkflowSummary(workflowSummary.getWorkflowId(), workflowSummary); } @Test public void shouldAsyncUpdateWorkflow() throws Exception { WorkflowSummary workflowSummary = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflowSummary); indexDAO.asyncUpdateWorkflow( workflowSummary.getWorkflowId(), new String[] {"status"}, new Object[] {WorkflowStatus.FAILED}) .get(); workflowSummary.setStatus(WorkflowStatus.FAILED); assertWorkflowSummary(workflowSummary.getWorkflowId(), workflowSummary); } @Test public void shouldIndexTask() { TaskSummary taskSummary = TestUtils.loadTaskSnapshot(objectMapper, "task_summary"); indexDAO.indexTask(taskSummary); List<String> tasks = tryFindResults(() -> searchTasks(taskSummary)); assertEquals(taskSummary.getTaskId(), tasks.get(0)); } @Test public void shouldIndexTaskAsync() throws Exception { TaskSummary taskSummary = TestUtils.loadTaskSnapshot(objectMapper, "task_summary"); indexDAO.asyncIndexTask(taskSummary).get(); List<String> tasks = tryFindResults(() -> searchTasks(taskSummary)); assertEquals(taskSummary.getTaskId(), tasks.get(0)); } @Test public void shouldRemoveTask() { WorkflowSummary workflowSummary = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflowSummary); // wait for workflow to be indexed tryFindResults(() -> searchWorkflows(workflowSummary.getWorkflowId()), 1); TaskSummary taskSummary = TestUtils.loadTaskSnapshot( objectMapper, "task_summary", workflowSummary.getWorkflowId()); indexDAO.indexTask(taskSummary); // Wait for the task to be indexed List<String> tasks = tryFindResults(() -> searchTasks(taskSummary), 1); indexDAO.removeTask(workflowSummary.getWorkflowId(), taskSummary.getTaskId()); tasks = tryFindResults(() -> searchTasks(taskSummary), 0); assertTrue("Task was not removed.", tasks.isEmpty()); } @Test public void shouldAsyncRemoveTask() throws Exception { WorkflowSummary workflowSummary = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflowSummary); // wait for workflow to be indexed tryFindResults(() -> searchWorkflows(workflowSummary.getWorkflowId()), 1); TaskSummary taskSummary = TestUtils.loadTaskSnapshot( objectMapper, "task_summary", workflowSummary.getWorkflowId()); indexDAO.indexTask(taskSummary); // Wait for the task to be indexed List<String> tasks = tryFindResults(() -> searchTasks(taskSummary), 1); indexDAO.asyncRemoveTask(workflowSummary.getWorkflowId(), taskSummary.getTaskId()).get(); tasks = tryFindResults(() -> searchTasks(taskSummary), 0); assertTrue("Task was not removed.", tasks.isEmpty()); } @Test public void shouldNotRemoveTaskWhenNotAssociatedWithWorkflow() { TaskSummary taskSummary = TestUtils.loadTaskSnapshot(objectMapper, "task_summary"); indexDAO.indexTask(taskSummary); // Wait for the task to be indexed List<String> tasks = tryFindResults(() -> searchTasks(taskSummary), 1); indexDAO.removeTask("InvalidWorkflow", taskSummary.getTaskId()); tasks = tryFindResults(() -> searchTasks(taskSummary), 0); assertFalse("Task was removed.", tasks.isEmpty()); } @Test public void shouldNotAsyncRemoveTaskWhenNotAssociatedWithWorkflow() throws Exception { TaskSummary taskSummary = TestUtils.loadTaskSnapshot(objectMapper, "task_summary"); indexDAO.indexTask(taskSummary); // Wait for the task to be indexed List<String> tasks = tryFindResults(() -> searchTasks(taskSummary), 1); indexDAO.asyncRemoveTask("InvalidWorkflow", taskSummary.getTaskId()).get(); tasks = tryFindResults(() -> searchTasks(taskSummary), 0); assertFalse("Task was removed.", tasks.isEmpty()); } @Test public void shouldAddTaskExecutionLogs() { List<TaskExecLog> logs = new ArrayList<>(); String taskId = uuid(); logs.add(createLog(taskId, "log1")); logs.add(createLog(taskId, "log2")); logs.add(createLog(taskId, "log3")); indexDAO.addTaskExecutionLogs(logs); List<TaskExecLog> indexedLogs = tryFindResults(() -> indexDAO.getTaskExecutionLogs(taskId), 3); assertEquals(3, indexedLogs.size()); assertTrue("Not all logs was indexed", indexedLogs.containsAll(logs)); } @Test public void shouldAddTaskExecutionLogsAsync() throws Exception { List<TaskExecLog> logs = new ArrayList<>(); String taskId = uuid(); logs.add(createLog(taskId, "log1")); logs.add(createLog(taskId, "log2")); logs.add(createLog(taskId, "log3")); indexDAO.asyncAddTaskExecutionLogs(logs).get(); List<TaskExecLog> indexedLogs = tryFindResults(() -> indexDAO.getTaskExecutionLogs(taskId), 3); assertEquals(3, indexedLogs.size()); assertTrue("Not all logs was indexed", indexedLogs.containsAll(logs)); } @Test public void shouldAddMessage() { String queue = "queue"; Message message1 = new Message(uuid(), "payload1", null); Message message2 = new Message(uuid(), "payload2", null); indexDAO.addMessage(queue, message1); indexDAO.addMessage(queue, message2); List<Message> indexedMessages = tryFindResults(() -> indexDAO.getMessages(queue), 2); assertEquals(2, indexedMessages.size()); assertTrue( "Not all messages was indexed", indexedMessages.containsAll(Arrays.asList(message1, message2))); } @Test public void shouldAddEventExecution() { String event = "event"; EventExecution execution1 = createEventExecution(event); EventExecution execution2 = createEventExecution(event); indexDAO.addEventExecution(execution1); indexDAO.addEventExecution(execution2); List<EventExecution> indexedExecutions = tryFindResults(() -> indexDAO.getEventExecutions(event), 2); assertEquals(2, indexedExecutions.size()); assertTrue( "Not all event executions was indexed", indexedExecutions.containsAll(Arrays.asList(execution1, execution2))); } @Test public void shouldAsyncAddEventExecution() throws Exception { String event = "event2"; EventExecution execution1 = createEventExecution(event); EventExecution execution2 = createEventExecution(event); indexDAO.asyncAddEventExecution(execution1).get(); indexDAO.asyncAddEventExecution(execution2).get(); List<EventExecution> indexedExecutions = tryFindResults(() -> indexDAO.getEventExecutions(event), 2); assertEquals(2, indexedExecutions.size()); assertTrue( "Not all event executions was indexed", indexedExecutions.containsAll(Arrays.asList(execution1, execution2))); } @Test public void shouldAddIndexPrefixToIndexTemplate() throws Exception { String json = TestUtils.loadJsonResource("expected_template_task_log"); String content = indexDAO.loadTypeMappingSource("/template_task_log.json"); assertEquals(json, content); } @Test public void shouldSearchRecentRunningWorkflows() throws Exception { WorkflowSummary oldWorkflow = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); oldWorkflow.setStatus(WorkflowStatus.RUNNING); oldWorkflow.setUpdateTime(getFormattedTime(new DateTime().minusHours(2).toDate())); WorkflowSummary recentWorkflow = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); recentWorkflow.setStatus(WorkflowStatus.RUNNING); recentWorkflow.setUpdateTime(getFormattedTime(new DateTime().minusHours(1).toDate())); WorkflowSummary tooRecentWorkflow = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); tooRecentWorkflow.setStatus(WorkflowStatus.RUNNING); tooRecentWorkflow.setUpdateTime(getFormattedTime(new DateTime().toDate())); indexDAO.indexWorkflow(oldWorkflow); indexDAO.indexWorkflow(recentWorkflow); indexDAO.indexWorkflow(tooRecentWorkflow); Thread.sleep(1000); List<String> ids = indexDAO.searchRecentRunningWorkflows(2, 1); assertEquals(1, ids.size()); assertEquals(recentWorkflow.getWorkflowId(), ids.get(0)); } @Test public void shouldCountWorkflows() { int counts = 1100; for (int i = 0; i < counts; i++) { WorkflowSummary workflowSummary = TestUtils.loadWorkflowSnapshot(objectMapper, "workflow_summary"); indexDAO.indexWorkflow(workflowSummary); } // wait for workflow to be indexed long result = tryGetCount(() -> getWorkflowCount("template_workflow", "RUNNING"), counts); assertEquals(counts, result); } private long tryGetCount(Supplier<Long> countFunction, int resultsCount) { long result = 0; for (int i = 0; i < 20; i++) { result = countFunction.get(); if (result == resultsCount) { return result; } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } } return result; } // Get total workflow counts given the name and status private long getWorkflowCount(String workflowName, String status) { return indexDAO.getWorkflowCount( "status=\"" + status + "\" AND workflowType=\"" + workflowName + "\"", "*"); } private void assertWorkflowSummary(String workflowId, WorkflowSummary summary) { assertEquals(summary.getWorkflowType(), indexDAO.get(workflowId, "workflowType")); assertEquals(String.valueOf(summary.getVersion()), indexDAO.get(workflowId, "version")); assertEquals(summary.getWorkflowId(), indexDAO.get(workflowId, "workflowId")); assertEquals(summary.getCorrelationId(), indexDAO.get(workflowId, "correlationId")); assertEquals(summary.getStartTime(), indexDAO.get(workflowId, "startTime")); assertEquals(summary.getUpdateTime(), indexDAO.get(workflowId, "updateTime")); assertEquals(summary.getEndTime(), indexDAO.get(workflowId, "endTime")); assertEquals(summary.getStatus().name(), indexDAO.get(workflowId, "status")); assertEquals(summary.getInput(), indexDAO.get(workflowId, "input")); assertEquals(summary.getOutput(), indexDAO.get(workflowId, "output")); assertEquals( summary.getReasonForIncompletion(), indexDAO.get(workflowId, "reasonForIncompletion")); assertEquals( String.valueOf(summary.getExecutionTime()), indexDAO.get(workflowId, "executionTime")); assertEquals(summary.getEvent(), indexDAO.get(workflowId, "event")); assertEquals( summary.getFailedReferenceTaskNames(), indexDAO.get(workflowId, "failedReferenceTaskNames")); } private String getFormattedTime(Date time) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); return sdf.format(time); } private <T> List<T> tryFindResults(Supplier<List<T>> searchFunction) { return tryFindResults(searchFunction, 1); } private <T> List<T> tryFindResults(Supplier<List<T>> searchFunction, int resultsCount) { List<T> result = Collections.emptyList(); for (int i = 0; i < 20; i++) { result = searchFunction.get(); if (result.size() == resultsCount) { return result; } try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e.getMessage(), e); } } return result; } private List<String> searchWorkflows(String workflowId) { return indexDAO.searchWorkflows( "", "workflowId:\"" + workflowId + "\"", 0, 100, Collections.emptyList()) .getResults(); } private List<String> searchTasks(TaskSummary taskSummary) { return indexDAO.searchTasks( "", "workflowId:\"" + taskSummary.getWorkflowId() + "\"", 0, 100, Collections.emptyList()) .getResults(); } private TaskExecLog createLog(String taskId, String log) { TaskExecLog taskExecLog = new TaskExecLog(log); taskExecLog.setTaskId(taskId); return taskExecLog; } private EventExecution createEventExecution(String event) { EventExecution execution = new EventExecution(uuid(), uuid()); execution.setName("name"); execution.setEvent(event); execution.setCreated(System.currentTimeMillis()); execution.setStatus(EventExecution.Status.COMPLETED);
execution.setAction(EventHandler.Action.Type.start_workflow);
1
2023-12-08 06:06:09+00:00
16k
kaifangqian/open-sign
src/main/java/com/resrun/controller/OpenSignController.java
[ { "identifier": "SignTypeEnum", "path": "src/main/java/com/resrun/enums/SignTypeEnum.java", "snippet": "public enum SignTypeEnum {\n\n\n POSITION(1,\"位置签署\"),\n KEYWORD(2,\"关键字签署\"),\n\n ;\n\n private String msg;\n private Integer code;\n\n\n SignTypeEnum(Integer code,String msg){\n ...
import com.resrun.enums.SignTypeEnum; import com.resrun.service.pojo.CertificateProperty; import com.resrun.service.pojo.GenerateCertificateInfo; import com.resrun.service.pojo.RealPositionProperty; import com.resrun.service.pojo.SourcePositionProperty; import com.resrun.service.cert.CertService; import com.resrun.service.image.EntSealClipService; import com.resrun.service.image.EntSealGenerateService; import com.resrun.service.pdf.CalculatePositionService; import com.resrun.service.pdf.SignService; import com.resrun.service.verify.SignVerifyService; import com.resrun.utils.Base64; import com.resrun.controller.vo.base.Result; import com.resrun.controller.vo.request.*; import com.resrun.controller.vo.response.SealResponse; import com.resrun.controller.vo.response.SignResponse; import com.resrun.controller.vo.response.VerifyResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.pdfbox.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.*; import java.io.*; import java.util.ArrayList; import java.util.List;
13,884
package com.resrun.controller; /** * @Description: OpenSignController * @Package: com.resrun.controller * @ClassName: OpenSignController * @copyright 北京资源律动科技有限公司 */ @Api(tags = "开放签-演示demo") @RestController public class OpenSignController { @Autowired private SignVerifyService signVerifyService ; @Autowired private CalculatePositionService calculatePositionService ; @Autowired private SignService signService ; @Autowired private EntSealGenerateService entSealGenerateService ; @Autowired private EntSealClipService entSealClipService ; @Autowired private CertService certService ; @ApiOperation("生成企业签章-上传生成") @RequestMapping(value = "/clip/seal",method = RequestMethod.POST) public Result<SealResponse> generateUpload(@RequestBody ClipSealRequest request){ if(request.getImage() == null || request.getImage().length() == 0){ return Result.error("图片数据为空",null); } byte[] decode = Base64.decode(request.getImage()); if(decode == null || decode.length == 0){ return Result.error("签章制作失败",null); } byte[] entSealByte = entSealClipService.clip(decode, request.getColorRange()); if(entSealByte == null){ return Result.error("签章制作失败",null); } String encode = Base64.encode(entSealByte); SealResponse response = new SealResponse(); response.setEntSeal(encode); return Result.OK(response) ; } @ApiOperation("生成企业签章-参数生成") @RequestMapping(value = "/generate/seal",method = RequestMethod.POST) public Result<SealResponse> seal(@RequestBody GenerateSealRequest request){ if(request == null || request.getMiddleText() == null || request.getTopText() == null){ return Result.error("参数缺失",null) ; } byte[] entSealByte = entSealGenerateService.generateEntSeal(request.getTopText(), request.getMiddleText()); if(entSealByte == null){ return Result.error("签章制作失败",null); } String encode = Base64.encode(entSealByte); SealResponse response = new SealResponse(); response.setEntSeal(encode); return Result.OK(response) ; } @ApiOperation("签署") @RequestMapping(value = "/sign",method = RequestMethod.POST) public Result<SignResponse> sign(@RequestBody SignRequest request){ String fileName = "开源工具版说明.pdf" ; byte[] signFileBytes = null ; byte[] entSealBytes = null ; byte[] personalBytes = null ;
package com.resrun.controller; /** * @Description: OpenSignController * @Package: com.resrun.controller * @ClassName: OpenSignController * @copyright 北京资源律动科技有限公司 */ @Api(tags = "开放签-演示demo") @RestController public class OpenSignController { @Autowired private SignVerifyService signVerifyService ; @Autowired private CalculatePositionService calculatePositionService ; @Autowired private SignService signService ; @Autowired private EntSealGenerateService entSealGenerateService ; @Autowired private EntSealClipService entSealClipService ; @Autowired private CertService certService ; @ApiOperation("生成企业签章-上传生成") @RequestMapping(value = "/clip/seal",method = RequestMethod.POST) public Result<SealResponse> generateUpload(@RequestBody ClipSealRequest request){ if(request.getImage() == null || request.getImage().length() == 0){ return Result.error("图片数据为空",null); } byte[] decode = Base64.decode(request.getImage()); if(decode == null || decode.length == 0){ return Result.error("签章制作失败",null); } byte[] entSealByte = entSealClipService.clip(decode, request.getColorRange()); if(entSealByte == null){ return Result.error("签章制作失败",null); } String encode = Base64.encode(entSealByte); SealResponse response = new SealResponse(); response.setEntSeal(encode); return Result.OK(response) ; } @ApiOperation("生成企业签章-参数生成") @RequestMapping(value = "/generate/seal",method = RequestMethod.POST) public Result<SealResponse> seal(@RequestBody GenerateSealRequest request){ if(request == null || request.getMiddleText() == null || request.getTopText() == null){ return Result.error("参数缺失",null) ; } byte[] entSealByte = entSealGenerateService.generateEntSeal(request.getTopText(), request.getMiddleText()); if(entSealByte == null){ return Result.error("签章制作失败",null); } String encode = Base64.encode(entSealByte); SealResponse response = new SealResponse(); response.setEntSeal(encode); return Result.OK(response) ; } @ApiOperation("签署") @RequestMapping(value = "/sign",method = RequestMethod.POST) public Result<SignResponse> sign(@RequestBody SignRequest request){ String fileName = "开源工具版说明.pdf" ; byte[] signFileBytes = null ; byte[] entSealBytes = null ; byte[] personalBytes = null ;
CertificateProperty entCert = null ;
1
2023-12-14 06:53:32+00:00
16k
Mahmud0808/ColorBlendr
app/src/main/java/com/drdisagree/colorblendr/ui/fragments/ThemeFragment.java
[ { "identifier": "MONET_ACCENT_SATURATION", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public static final String MONET_ACCENT_SATURATION = \"monetAccentSaturationValue\";" }, { "identifier": "MONET_ACCURATE_SHADES", "path": "app/src/main/java/com/dr...
import static com.drdisagree.colorblendr.common.Const.MONET_ACCENT_SATURATION; import static com.drdisagree.colorblendr.common.Const.MONET_ACCURATE_SHADES; import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_LIGHTNESS; import static com.drdisagree.colorblendr.common.Const.MONET_BACKGROUND_SATURATION; import static com.drdisagree.colorblendr.common.Const.MONET_LAST_UPDATED; import static com.drdisagree.colorblendr.common.Const.MONET_PITCH_BLACK_THEME; import static com.drdisagree.colorblendr.common.Const.MONET_STYLE; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SeekBar; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.drdisagree.colorblendr.R; import com.drdisagree.colorblendr.config.RPrefs; import com.drdisagree.colorblendr.databinding.FragmentThemeBinding; import com.drdisagree.colorblendr.utils.ColorSchemeUtil; import com.drdisagree.colorblendr.utils.ColorUtil; import com.drdisagree.colorblendr.utils.MiscUtil; import com.drdisagree.colorblendr.utils.OverlayManager; import com.drdisagree.colorblendr.utils.SystemUtil; import java.util.ArrayList;
11,014
} }); // Long Click Reset binding.accentSaturation.setResetClickListener(v -> { monetAccentSaturation[0] = 100; updatePreviewColors(); RPrefs.clearPref(MONET_ACCENT_SATURATION); RPrefs.putLong(MONET_LAST_UPDATED, System.currentTimeMillis()); new Handler(Looper.getMainLooper()).postDelayed(() -> { try { OverlayManager.applyFabricatedColors(requireContext()); } catch (Exception ignored) { } }, 200); return true; }); // Monet background saturation binding.backgroundSaturation.setSeekbarProgress(RPrefs.getInt(MONET_BACKGROUND_SATURATION, 100)); binding.backgroundSaturation.setOnSeekbarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { binding.backgroundSaturation.setSelectedProgress(); monetBackgroundSaturation[0] = progress; updatePreviewColors(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(@NonNull SeekBar seekBar) { monetBackgroundSaturation[0] = seekBar.getProgress(); RPrefs.putInt(MONET_BACKGROUND_SATURATION, monetBackgroundSaturation[0]); RPrefs.putLong(MONET_LAST_UPDATED, System.currentTimeMillis()); new Handler(Looper.getMainLooper()).postDelayed(() -> { try { OverlayManager.applyFabricatedColors(requireContext()); } catch (Exception ignored) { } }, 200); } }); // Reset button binding.backgroundSaturation.setResetClickListener(v -> { monetBackgroundSaturation[0] = 100; updatePreviewColors(); RPrefs.clearPref(MONET_BACKGROUND_SATURATION); RPrefs.putLong(MONET_LAST_UPDATED, System.currentTimeMillis()); new Handler(Looper.getMainLooper()).postDelayed(() -> { try { OverlayManager.applyFabricatedColors(requireContext()); } catch (Exception ignored) { } }, 200); return true; }); // Monet background lightness binding.backgroundLightness.setSeekbarProgress(RPrefs.getInt(MONET_BACKGROUND_LIGHTNESS, 100)); binding.backgroundLightness.setOnSeekbarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(@NonNull SeekBar seekBar, int progress, boolean fromUser) { binding.backgroundLightness.setSelectedProgress(); monetBackgroundLightness[0] = progress; updatePreviewColors(); } @Override public void onStartTrackingTouch(@NonNull SeekBar seekBar) { } @Override public void onStopTrackingTouch(@NonNull SeekBar seekBar) { monetBackgroundLightness[0] = seekBar.getProgress(); RPrefs.putInt(MONET_BACKGROUND_LIGHTNESS, monetBackgroundLightness[0]); RPrefs.putLong(MONET_LAST_UPDATED, System.currentTimeMillis()); new Handler(Looper.getMainLooper()).postDelayed(() -> { try { OverlayManager.applyFabricatedColors(requireContext()); } catch (Exception ignored) { } }, 200); } }); // Long Click Reset binding.backgroundLightness.setResetClickListener(v -> { monetBackgroundLightness[0] = 100; updatePreviewColors(); RPrefs.clearPref(MONET_BACKGROUND_LIGHTNESS); RPrefs.putLong(MONET_LAST_UPDATED, System.currentTimeMillis()); new Handler(Looper.getMainLooper()).postDelayed(() -> { try { OverlayManager.applyFabricatedColors(requireContext()); } catch (Exception ignored) { } }, 200); return true; }); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); updatePreviewColors(); } private void updatePreviewColors() { ArrayList<ArrayList<Integer>> colorPalette = generateModifiedColors( monetAccentSaturation[0], monetBackgroundSaturation[0], monetBackgroundLightness[0], RPrefs.getBoolean(MONET_PITCH_BLACK_THEME, false),
package com.drdisagree.colorblendr.ui.fragments; public class ThemeFragment extends Fragment { private static final String TAG = ThemeFragment.class.getSimpleName(); private FragmentThemeBinding binding; private final int[] monetAccentSaturation = new int[]{RPrefs.getInt(MONET_ACCENT_SATURATION, 100)}; private final int[] monetBackgroundSaturation = new int[]{RPrefs.getInt(MONET_BACKGROUND_SATURATION, 100)}; private final int[] monetBackgroundLightness = new int[]{RPrefs.getInt(MONET_BACKGROUND_LIGHTNESS, 100)}; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentThemeBinding.inflate(inflater, container, false); MiscUtil.setToolbarTitle(requireContext(), R.string.theme, true, binding.header.toolbar); // Color preview titles binding.colorAccent1.title.setText(R.string.primary); binding.colorAccent2.title.setText(R.string.secondary); binding.colorAccent3.title.setText(R.string.tertiary); binding.colorNeutral1.title.setText(R.string.neutral_1); binding.colorNeutral2.title.setText(R.string.neutral_2); // Monet primary accent saturation binding.accentSaturation.setSeekbarProgress(RPrefs.getInt(MONET_ACCENT_SATURATION, 100)); binding.accentSaturation.setOnSeekbarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { binding.accentSaturation.setSelectedProgress(); monetAccentSaturation[0] = progress; updatePreviewColors(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { monetAccentSaturation[0] = seekBar.getProgress(); RPrefs.putInt(MONET_ACCENT_SATURATION, monetAccentSaturation[0]); RPrefs.putLong(MONET_LAST_UPDATED, System.currentTimeMillis()); new Handler(Looper.getMainLooper()).postDelayed(() -> { try { OverlayManager.applyFabricatedColors(requireContext()); } catch (Exception ignored) { } }, 200); } }); // Long Click Reset binding.accentSaturation.setResetClickListener(v -> { monetAccentSaturation[0] = 100; updatePreviewColors(); RPrefs.clearPref(MONET_ACCENT_SATURATION); RPrefs.putLong(MONET_LAST_UPDATED, System.currentTimeMillis()); new Handler(Looper.getMainLooper()).postDelayed(() -> { try { OverlayManager.applyFabricatedColors(requireContext()); } catch (Exception ignored) { } }, 200); return true; }); // Monet background saturation binding.backgroundSaturation.setSeekbarProgress(RPrefs.getInt(MONET_BACKGROUND_SATURATION, 100)); binding.backgroundSaturation.setOnSeekbarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { binding.backgroundSaturation.setSelectedProgress(); monetBackgroundSaturation[0] = progress; updatePreviewColors(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(@NonNull SeekBar seekBar) { monetBackgroundSaturation[0] = seekBar.getProgress(); RPrefs.putInt(MONET_BACKGROUND_SATURATION, monetBackgroundSaturation[0]); RPrefs.putLong(MONET_LAST_UPDATED, System.currentTimeMillis()); new Handler(Looper.getMainLooper()).postDelayed(() -> { try { OverlayManager.applyFabricatedColors(requireContext()); } catch (Exception ignored) { } }, 200); } }); // Reset button binding.backgroundSaturation.setResetClickListener(v -> { monetBackgroundSaturation[0] = 100; updatePreviewColors(); RPrefs.clearPref(MONET_BACKGROUND_SATURATION); RPrefs.putLong(MONET_LAST_UPDATED, System.currentTimeMillis()); new Handler(Looper.getMainLooper()).postDelayed(() -> { try { OverlayManager.applyFabricatedColors(requireContext()); } catch (Exception ignored) { } }, 200); return true; }); // Monet background lightness binding.backgroundLightness.setSeekbarProgress(RPrefs.getInt(MONET_BACKGROUND_LIGHTNESS, 100)); binding.backgroundLightness.setOnSeekbarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(@NonNull SeekBar seekBar, int progress, boolean fromUser) { binding.backgroundLightness.setSelectedProgress(); monetBackgroundLightness[0] = progress; updatePreviewColors(); } @Override public void onStartTrackingTouch(@NonNull SeekBar seekBar) { } @Override public void onStopTrackingTouch(@NonNull SeekBar seekBar) { monetBackgroundLightness[0] = seekBar.getProgress(); RPrefs.putInt(MONET_BACKGROUND_LIGHTNESS, monetBackgroundLightness[0]); RPrefs.putLong(MONET_LAST_UPDATED, System.currentTimeMillis()); new Handler(Looper.getMainLooper()).postDelayed(() -> { try { OverlayManager.applyFabricatedColors(requireContext()); } catch (Exception ignored) { } }, 200); } }); // Long Click Reset binding.backgroundLightness.setResetClickListener(v -> { monetBackgroundLightness[0] = 100; updatePreviewColors(); RPrefs.clearPref(MONET_BACKGROUND_LIGHTNESS); RPrefs.putLong(MONET_LAST_UPDATED, System.currentTimeMillis()); new Handler(Looper.getMainLooper()).postDelayed(() -> { try { OverlayManager.applyFabricatedColors(requireContext()); } catch (Exception ignored) { } }, 200); return true; }); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); updatePreviewColors(); } private void updatePreviewColors() { ArrayList<ArrayList<Integer>> colorPalette = generateModifiedColors( monetAccentSaturation[0], monetBackgroundSaturation[0], monetBackgroundLightness[0], RPrefs.getBoolean(MONET_PITCH_BLACK_THEME, false),
RPrefs.getBoolean(MONET_ACCURATE_SHADES, true)
1
2023-12-06 13:20:16+00:00
16k
HelpChat/DeluxeMenus
src/main/java/com/extendedclip/deluxemenus/action/ClickActionTask.java
[ { "identifier": "DeluxeMenus", "path": "src/main/java/com/extendedclip/deluxemenus/DeluxeMenus.java", "snippet": "public class DeluxeMenus extends JavaPlugin {\r\n\r\n public final static Map<String, Material> MATERIALS\r\n = Arrays.stream(Material.values()).collect(Collectors.toUnmodifiableMa...
import com.extendedclip.deluxemenus.DeluxeMenus; import com.extendedclip.deluxemenus.menu.Menu; import com.extendedclip.deluxemenus.menu.MenuHolder; import com.extendedclip.deluxemenus.utils.AdventureUtils; import com.extendedclip.deluxemenus.utils.DebugLevel; import com.extendedclip.deluxemenus.utils.ExpUtils; import com.extendedclip.deluxemenus.utils.StringUtils; import com.extendedclip.deluxemenus.utils.VersionHelper; import java.util.logging.Level; import me.clip.placeholderapi.PlaceholderAPI; import net.kyori.adventure.Adventure; import net.kyori.adventure.text.minimessage.MiniMessage; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.scheduler.BukkitRunnable; import org.jetbrains.annotations.NotNull;
12,290
package com.extendedclip.deluxemenus.action; public class ClickActionTask extends BukkitRunnable { private final DeluxeMenus plugin; private final String name; private final ActionType actionType; private final String exec; public ClickActionTask( @NotNull final DeluxeMenus plugin, @NotNull final String name, @NotNull final ActionType actionType, @NotNull final String exec ) { this.plugin = plugin; this.name = name; this.actionType = actionType; this.exec = exec; } @Override public void run() { final Player player = Bukkit.getServer().getPlayerExact(name); if (player == null) { return; } final String executable = PlaceholderAPI.setPlaceholders((OfflinePlayer) player, exec); final MenuHolder holder = Menu.getMenuHolder(player); switch (actionType) { case META: if (!VersionHelper.IS_PDC_VERSION || DeluxeMenus.getInstance().getPersistentMetaHandler() == null) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, "Meta action not supported on this server version."); break; } try { final boolean result = DeluxeMenus.getInstance().getPersistentMetaHandler().setMeta(player, executable); if (!result) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, "Invalid meta action! Make sure you have the right syntax."); break; } } catch (final NumberFormatException exception) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, "Invalid integer value for meta action!"); } break; case PLAYER: player.chat("/" + executable); break; case PLAYER_COMMAND_EVENT: Bukkit.getPluginManager().callEvent(new PlayerCommandPreprocessEvent(player, "/" + executable)); break; case PLACEHOLDER: PlaceholderAPI.setPlaceholders(player, executable); break; case CHAT: player.chat(executable); break; case CONSOLE: Bukkit.dispatchCommand(Bukkit.getConsoleSender(), executable); break; case MINI_MESSAGE: plugin.adventure().player(player).sendMessage(MiniMessage.miniMessage().deserialize(executable)); break; case MINI_BROADCAST: plugin.adventure().all().sendMessage(MiniMessage.miniMessage().deserialize(executable)); break; case MESSAGE:
package com.extendedclip.deluxemenus.action; public class ClickActionTask extends BukkitRunnable { private final DeluxeMenus plugin; private final String name; private final ActionType actionType; private final String exec; public ClickActionTask( @NotNull final DeluxeMenus plugin, @NotNull final String name, @NotNull final ActionType actionType, @NotNull final String exec ) { this.plugin = plugin; this.name = name; this.actionType = actionType; this.exec = exec; } @Override public void run() { final Player player = Bukkit.getServer().getPlayerExact(name); if (player == null) { return; } final String executable = PlaceholderAPI.setPlaceholders((OfflinePlayer) player, exec); final MenuHolder holder = Menu.getMenuHolder(player); switch (actionType) { case META: if (!VersionHelper.IS_PDC_VERSION || DeluxeMenus.getInstance().getPersistentMetaHandler() == null) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, "Meta action not supported on this server version."); break; } try { final boolean result = DeluxeMenus.getInstance().getPersistentMetaHandler().setMeta(player, executable); if (!result) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, "Invalid meta action! Make sure you have the right syntax."); break; } } catch (final NumberFormatException exception) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, "Invalid integer value for meta action!"); } break; case PLAYER: player.chat("/" + executable); break; case PLAYER_COMMAND_EVENT: Bukkit.getPluginManager().callEvent(new PlayerCommandPreprocessEvent(player, "/" + executable)); break; case PLACEHOLDER: PlaceholderAPI.setPlaceholders(player, executable); break; case CHAT: player.chat(executable); break; case CONSOLE: Bukkit.dispatchCommand(Bukkit.getConsoleSender(), executable); break; case MINI_MESSAGE: plugin.adventure().player(player).sendMessage(MiniMessage.miniMessage().deserialize(executable)); break; case MINI_BROADCAST: plugin.adventure().all().sendMessage(MiniMessage.miniMessage().deserialize(executable)); break; case MESSAGE:
player.sendMessage(StringUtils.color(executable));
6
2023-12-14 23:41:07+00:00
16k
lxs2601055687/contextAdminRuoYi
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysRoleServiceImpl.java
[ { "identifier": "UserConstants", "path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/UserConstants.java", "snippet": "public interface UserConstants {\n\n /**\n * 平台内系统用户的唯一标志\n */\n String SYS_USER = \"SYS_USER\";\n\n /**\n * 正常状态\n */\n String NORMAL = \"0\";\n\n ...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.PageQuery; import com.ruoyi.common.core.domain.entity.SysRole; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.helper.LoginHelper; import com.ruoyi.common.utils.StreamUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.domain.SysRoleDept; import com.ruoyi.system.domain.SysRoleMenu; import com.ruoyi.system.domain.SysUserRole; import com.ruoyi.system.mapper.SysRoleDeptMapper; import com.ruoyi.system.mapper.SysRoleMapper; import com.ruoyi.system.mapper.SysRoleMenuMapper; import com.ruoyi.system.mapper.SysUserRoleMapper; import com.ruoyi.system.service.ISysRoleService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*;
11,792
package com.ruoyi.system.service.impl; /** * 角色 业务层处理 * * @author Lion Li */ @RequiredArgsConstructor @Service public class SysRoleServiceImpl implements ISysRoleService { private final SysRoleMapper baseMapper; private final SysRoleMenuMapper roleMenuMapper; private final SysUserRoleMapper userRoleMapper; private final SysRoleDeptMapper roleDeptMapper; @Override
package com.ruoyi.system.service.impl; /** * 角色 业务层处理 * * @author Lion Li */ @RequiredArgsConstructor @Service public class SysRoleServiceImpl implements ISysRoleService { private final SysRoleMapper baseMapper; private final SysRoleMenuMapper roleMenuMapper; private final SysUserRoleMapper userRoleMapper; private final SysRoleDeptMapper roleDeptMapper; @Override
public TableDataInfo<SysRole> selectPageRoleList(SysRole role, PageQuery pageQuery) {
1
2023-12-07 12:06:21+00:00
16k