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 |
|---|---|---|---|---|---|---|---|---|---|---|
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; | 8,866 | package org.arbor.gtnn.data;
@SuppressWarnings("unused")
public class GTNNMachines {
public static final int[] NA_TIERS = GTValues.tiersBetween(1, 8);
static { | 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); | 13 | 2023-11-04 07:59:02+00:00 | 12k |
satisfyu/HerbalBrews | common/src/main/java/satisfyu/herbalbrews/compat/rei/HerbalBrewsReiClientPlugin.java | [
{
"identifier": "CauldronCategory",
"path": "common/src/main/java/satisfyu/herbalbrews/compat/rei/category/CauldronCategory.java",
"snippet": "public class CauldronCategory implements DisplayCategory<CauldronDisplay> {\n\n @Override\n public CategoryIdentifier<CauldronDisplay> getCategoryIdentifie... | import me.shedaniel.rei.api.client.registry.category.CategoryRegistry;
import me.shedaniel.rei.api.client.registry.display.DisplayRegistry;
import me.shedaniel.rei.api.common.util.EntryStacks;
import satisfyu.herbalbrews.compat.rei.category.CauldronCategory;
import satisfyu.herbalbrews.compat.rei.category.TeaKettleCategory;
import satisfyu.herbalbrews.compat.rei.display.CauldronDisplay;
import satisfyu.herbalbrews.compat.rei.display.TeaKettleDisplay;
import satisfyu.herbalbrews.recipe.CauldronRecipe;
import satisfyu.herbalbrews.recipe.TeaKettleRecipe;
import satisfyu.herbalbrews.registry.ObjectRegistry; | 7,631 | package satisfyu.herbalbrews.compat.rei;
public class HerbalBrewsReiClientPlugin {
public static void registerCategories(CategoryRegistry registry) {
registry.add(new TeaKettleCategory());
registry.add(new CauldronCategory());
registry.addWorkstations(TeaKettleCategory.COOKING_CAULDRON_DISPLAY, EntryStacks.of(ObjectRegistry.TEA_KETTLE.get()));
registry.addWorkstations(TeaKettleCategory.COOKING_CAULDRON_DISPLAY, EntryStacks.of(ObjectRegistry.COPPER_TEA_KETTLE.get()));
registry.addWorkstations(CauldronDisplay.CAULDRON_DISPLAY, EntryStacks.of(ObjectRegistry.CAULDRON.get()));
}
public static void registerDisplays(DisplayRegistry registry) { | package satisfyu.herbalbrews.compat.rei;
public class HerbalBrewsReiClientPlugin {
public static void registerCategories(CategoryRegistry registry) {
registry.add(new TeaKettleCategory());
registry.add(new CauldronCategory());
registry.addWorkstations(TeaKettleCategory.COOKING_CAULDRON_DISPLAY, EntryStacks.of(ObjectRegistry.TEA_KETTLE.get()));
registry.addWorkstations(TeaKettleCategory.COOKING_CAULDRON_DISPLAY, EntryStacks.of(ObjectRegistry.COPPER_TEA_KETTLE.get()));
registry.addWorkstations(CauldronDisplay.CAULDRON_DISPLAY, EntryStacks.of(ObjectRegistry.CAULDRON.get()));
}
public static void registerDisplays(DisplayRegistry registry) { | registry.registerFiller(TeaKettleRecipe.class, TeaKettleDisplay::new); | 3 | 2023-11-05 16:46:52+00:00 | 12k |
AnhyDev/AnhyLingo | src/main/java/ink/anh/lingo/command/LingoCommand.java | [
{
"identifier": "AnhyLingo",
"path": "src/main/java/ink/anh/lingo/AnhyLingo.java",
"snippet": "public class AnhyLingo extends JavaPlugin {\n\n private static AnhyLingo instance;\n \n private boolean isSpigot;\n private boolean isPaper;\n private boolean isFolia;\n private boolean hasPa... | import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import ink.anh.api.lingo.Translator;
import ink.anh.api.messages.MessageType;
import ink.anh.api.messages.Messenger;
import ink.anh.api.utils.LangUtils;
import ink.anh.lingo.AnhyLingo;
import ink.anh.lingo.GlobalManager;
import ink.anh.lingo.Permissions;
import ink.anh.lingo.file.DirectoryContents;
import ink.anh.lingo.file.FileProcessType;
import ink.anh.lingo.item.ItemLang;
import net.md_5.bungee.api.ChatColor;
import ink.anh.lingo.file.FileCommandProcessor; | 7,738 | package ink.anh.lingo.command;
/**
* Command executor for the 'lingo' command in the AnhyLingo plugin.
* This class processes and executes various subcommands related to language settings and file management.
*/
public class LingoCommand implements CommandExecutor {
private AnhyLingo lingoPlugin;
private GlobalManager globalManager;
/**
* Constructor for the LingoCommand class.
*
* @param lingoPlugin The instance of AnhyLingo plugin.
*/
public LingoCommand(AnhyLingo lingoPlugin) {
this.lingoPlugin = lingoPlugin;
this.globalManager = lingoPlugin.getGlobalManager();
}
/**
* Executes the given command, returning its success.
*
* @param sender Source of the command.
* @param cmd The command which was executed.
* @param label Alias of the command which was used.
* @param args Passed command arguments.
* @return true if a valid command, otherwise false.
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length > 0) {
switch (args[0].toLowerCase()) {
case "nbt":
return new NBTSubCommand(lingoPlugin).execNBT(sender, args);
case "items":
return itemLang(sender, args);
case "reload":
return reload(sender);
case "set":
return setLang(sender, args);
case "get":
return getLang(sender);
case "reset":
return resetLang(sender);
case "dir":
return directory(sender, args);
case "flingo":
case "fl": | package ink.anh.lingo.command;
/**
* Command executor for the 'lingo' command in the AnhyLingo plugin.
* This class processes and executes various subcommands related to language settings and file management.
*/
public class LingoCommand implements CommandExecutor {
private AnhyLingo lingoPlugin;
private GlobalManager globalManager;
/**
* Constructor for the LingoCommand class.
*
* @param lingoPlugin The instance of AnhyLingo plugin.
*/
public LingoCommand(AnhyLingo lingoPlugin) {
this.lingoPlugin = lingoPlugin;
this.globalManager = lingoPlugin.getGlobalManager();
}
/**
* Executes the given command, returning its success.
*
* @param sender Source of the command.
* @param cmd The command which was executed.
* @param label Alias of the command which was used.
* @param args Passed command arguments.
* @return true if a valid command, otherwise false.
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length > 0) {
switch (args[0].toLowerCase()) {
case "nbt":
return new NBTSubCommand(lingoPlugin).execNBT(sender, args);
case "items":
return itemLang(sender, args);
case "reload":
return reload(sender);
case "set":
return setLang(sender, args);
case "get":
return getLang(sender);
case "reset":
return resetLang(sender);
case "dir":
return directory(sender, args);
case "flingo":
case "fl": | return new FileCommandProcessor(lingoPlugin).processFile(sender, args, FileProcessType.YAML_LOADER); | 4 | 2023-11-10 00:35:39+00:00 | 12k |
BaderTim/minecraft-measurement-mod | src/main/java/io/github/mmm/keymappings/KeyEventHandler.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.modconfig.gui.DeviceConfigGUI;
import io.github.mmm.modconfig.gui.SurveyConfigGUI;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import static io.github.mmm.MMM.*;
import static io.github.mmm.keymappings.KeyDefinitions.*;
import static io.github.mmm.renderer.RenderEventHandler.DEVICE_RENDERER; | 10,560 | package io.github.mmm.keymappings;
@Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.FORGE, value = Dist.CLIENT)
public class KeyEventHandler {
// Listen to Key Bindings
@SubscribeEvent
public static void onClientTick(TickEvent.ClientTickEvent event) {
// Only call code once as the tick event is called twice every tick
if (event.phase == TickEvent.Phase.END) {
if (DEVICE_MEASURE_MAPPING.get().consumeClick()) {
LOGGER.info("MEASURE_START_STOP_MAPPING is pressed");
if (DEVICE_CONTROLLER.isCurrentlyMeasuring()) {
DEVICE_CONTROLLER.stopMeasure();
} else {
DEVICE_CONTROLLER.startMeasure();
}
} else if (SETTINGS_MAPPING.get().consumeClick()) {
LOGGER.info("SETTINGS_MAPPING is pressed");
if(DEVICE_CONTROLLER.isCurrentlyMeasuring()) {
Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".gui.open.warn"), false);
return;
}
if(latestConfigGUI == ConfigGUIType.DEVICE) { | package io.github.mmm.keymappings;
@Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.FORGE, value = Dist.CLIENT)
public class KeyEventHandler {
// Listen to Key Bindings
@SubscribeEvent
public static void onClientTick(TickEvent.ClientTickEvent event) {
// Only call code once as the tick event is called twice every tick
if (event.phase == TickEvent.Phase.END) {
if (DEVICE_MEASURE_MAPPING.get().consumeClick()) {
LOGGER.info("MEASURE_START_STOP_MAPPING is pressed");
if (DEVICE_CONTROLLER.isCurrentlyMeasuring()) {
DEVICE_CONTROLLER.stopMeasure();
} else {
DEVICE_CONTROLLER.startMeasure();
}
} else if (SETTINGS_MAPPING.get().consumeClick()) {
LOGGER.info("SETTINGS_MAPPING is pressed");
if(DEVICE_CONTROLLER.isCurrentlyMeasuring()) {
Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".gui.open.warn"), false);
return;
}
if(latestConfigGUI == ConfigGUIType.DEVICE) { | Minecraft.getInstance().setScreen(new DeviceConfigGUI()); | 1 | 2023-11-06 16:56:46+00:00 | 12k |
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,738 | 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;
| 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); | 2 | 2023-11-04 04:11:26+00:00 | 12k |
InfantinoAndrea00/polimi-software-engineering-project-2022 | src/main/java/it/polimi/ingsw/server/controller/ViewObserver.java | [
{
"identifier": "ActionPhase1Move",
"path": "src/main/java/it/polimi/ingsw/resources/ActionPhase1Move.java",
"snippet": "public class ActionPhase1Move implements Serializable {\n private Color student;\n private Destination destination;\n private int islandId;\n\n private ActionPhase1Move(Co... | import it.polimi.ingsw.resources.ActionPhase1Move;
import it.polimi.ingsw.resources.GameState;
import it.polimi.ingsw.resources.Message;
import it.polimi.ingsw.resources.enumerators.TowerColor;
import it.polimi.ingsw.server.ClientHandler;
import it.polimi.ingsw.server.Server;
import it.polimi.ingsw.server.controller.states.ChooseCloudTile;
import it.polimi.ingsw.server.controller.states.MoveMotherNature;
import it.polimi.ingsw.server.controller.states.NextRoundOrEndGame;
import it.polimi.ingsw.server.model.Cloud;
import it.polimi.ingsw.server.model.Player;
import it.polimi.ingsw.server.model.PlayerTurn;
import it.polimi.ingsw.server.model.Team;
import it.polimi.ingsw.server.model.expert.ExpertGame;
import it.polimi.ingsw.server.model.expert.ExpertPlayer;
import java.io.IOException;
import java.net.Socket;
import java.util.*;
import static it.polimi.ingsw.resources.enumerators.MessageCode.*; | 7,876 | package it.polimi.ingsw.server.controller;
/**
* class that observe the view
*/
public class ViewObserver {
private GameController gameController;
private int counter;
private boolean canAddPlayer;
private CharacterCardHandler characterCardHandler;
private Map<Integer, Socket> playersSockets;
private List<ClientHandler> clients;
public ViewObserver () {
clients = new ArrayList<>();
playersSockets = new HashMap<>();
gameController = new GameController();
counter = 0;
canAddPlayer = false;
}
/**
*
* @param expertMode true if the game is in expert mode, false otherwise
* @param playerNumber number of players in the game
* @return an acknowledgement message
*/ | package it.polimi.ingsw.server.controller;
/**
* class that observe the view
*/
public class ViewObserver {
private GameController gameController;
private int counter;
private boolean canAddPlayer;
private CharacterCardHandler characterCardHandler;
private Map<Integer, Socket> playersSockets;
private List<ClientHandler> clients;
public ViewObserver () {
clients = new ArrayList<>();
playersSockets = new HashMap<>();
gameController = new GameController();
counter = 0;
canAddPlayer = false;
}
/**
*
* @param expertMode true if the game is in expert mode, false otherwise
* @param playerNumber number of players in the game
* @return an acknowledgement message
*/ | public Message expertModeAndPlayerNumber(boolean expertMode, int playerNumber) { | 2 | 2023-11-06 00:50:18+00:00 | 12k |
conductor-oss/conductor | core/src/main/java/com/netflix/conductor/service/MetadataService.java | [
{
"identifier": "EventHandler",
"path": "common/src/main/java/com/netflix/conductor/common/metadata/events/EventHandler.java",
"snippet": "@ProtoMessage\npublic class EventHandler {\n\n @ProtoField(id = 1)\n @NotEmpty(message = \"Missing event handler name\")\n private String name;\n\n @Prot... | import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.validation.annotation.Validated;
import com.netflix.conductor.common.metadata.events.EventHandler;
import com.netflix.conductor.common.metadata.tasks.TaskDef;
import com.netflix.conductor.common.metadata.workflow.WorkflowDef;
import com.netflix.conductor.common.metadata.workflow.WorkflowDefSummary;
import com.netflix.conductor.common.model.BulkResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size; | 10,072 | /*
* Copyright 2022 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.service;
@Validated
public interface MetadataService {
/**
* @param taskDefinitions Task Definitions to register
*/
void registerTaskDef(
@NotNull(message = "TaskDefList cannot be empty or null")
@Size(min = 1, message = "TaskDefList is empty")
List<@Valid TaskDef> taskDefinitions);
/**
* @param taskDefinition Task Definition to be updated
*/
void updateTaskDef(@NotNull(message = "TaskDef cannot be null") @Valid TaskDef taskDefinition);
/**
* @param taskType Remove task definition
*/
void unregisterTaskDef(@NotEmpty(message = "TaskName cannot be null or empty") String taskType);
/**
* @return List of all the registered tasks
*/
List<TaskDef> getTaskDefs();
/**
* @param taskType Task to retrieve
* @return Task Definition
*/
TaskDef getTaskDef(@NotEmpty(message = "TaskType cannot be null or empty") String taskType);
/**
* @param def Workflow definition to be updated
*/
void updateWorkflowDef(@NotNull(message = "WorkflowDef cannot be null") @Valid WorkflowDef def);
/**
* @param workflowDefList Workflow definitions to be updated.
*/
BulkResponse updateWorkflowDef(
@NotNull(message = "WorkflowDef list name cannot be null or empty")
@Size(min = 1, message = "WorkflowDefList is empty")
List<@NotNull(message = "WorkflowDef cannot be null") @Valid WorkflowDef>
workflowDefList);
/**
* @param name Name of the workflow to retrieve
* @param version Optional. Version. If null, then retrieves the latest
* @return Workflow definition
*/
WorkflowDef getWorkflowDef(
@NotEmpty(message = "Workflow name cannot be null or empty") String name,
Integer version);
/**
* @param name Name of the workflow to retrieve
* @return Latest version of the workflow definition
*/
Optional<WorkflowDef> getLatestWorkflow(
@NotEmpty(message = "Workflow name cannot be null or empty") String name);
/**
* @return Returns all workflow defs (all versions)
*/
List<WorkflowDef> getWorkflowDefs();
/**
* @return Returns workflow names and versions only (no definition bodies)
*/ | /*
* Copyright 2022 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.service;
@Validated
public interface MetadataService {
/**
* @param taskDefinitions Task Definitions to register
*/
void registerTaskDef(
@NotNull(message = "TaskDefList cannot be empty or null")
@Size(min = 1, message = "TaskDefList is empty")
List<@Valid TaskDef> taskDefinitions);
/**
* @param taskDefinition Task Definition to be updated
*/
void updateTaskDef(@NotNull(message = "TaskDef cannot be null") @Valid TaskDef taskDefinition);
/**
* @param taskType Remove task definition
*/
void unregisterTaskDef(@NotEmpty(message = "TaskName cannot be null or empty") String taskType);
/**
* @return List of all the registered tasks
*/
List<TaskDef> getTaskDefs();
/**
* @param taskType Task to retrieve
* @return Task Definition
*/
TaskDef getTaskDef(@NotEmpty(message = "TaskType cannot be null or empty") String taskType);
/**
* @param def Workflow definition to be updated
*/
void updateWorkflowDef(@NotNull(message = "WorkflowDef cannot be null") @Valid WorkflowDef def);
/**
* @param workflowDefList Workflow definitions to be updated.
*/
BulkResponse updateWorkflowDef(
@NotNull(message = "WorkflowDef list name cannot be null or empty")
@Size(min = 1, message = "WorkflowDefList is empty")
List<@NotNull(message = "WorkflowDef cannot be null") @Valid WorkflowDef>
workflowDefList);
/**
* @param name Name of the workflow to retrieve
* @param version Optional. Version. If null, then retrieves the latest
* @return Workflow definition
*/
WorkflowDef getWorkflowDef(
@NotEmpty(message = "Workflow name cannot be null or empty") String name,
Integer version);
/**
* @param name Name of the workflow to retrieve
* @return Latest version of the workflow definition
*/
Optional<WorkflowDef> getLatestWorkflow(
@NotEmpty(message = "Workflow name cannot be null or empty") String name);
/**
* @return Returns all workflow defs (all versions)
*/
List<WorkflowDef> getWorkflowDefs();
/**
* @return Returns workflow names and versions only (no definition bodies)
*/ | Map<String, ? extends Iterable<WorkflowDefSummary>> getWorkflowNamesAndVersions(); | 3 | 2023-12-08 06:06:09+00:00 | 12k |
Mahmud0808/ColorBlendr | app/src/main/java/com/drdisagree/colorblendr/service/BroadcastListener.java | [
{
"identifier": "FABRICATED_OVERLAY_NAME_APPS",
"path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java",
"snippet": "public static final String FABRICATED_OVERLAY_NAME_APPS = BuildConfig.APPLICATION_ID + \".%s_dynamic_theme\";"
},
{
"identifier": "MONET_LAST_UPDATED",
"path"... | import static com.drdisagree.colorblendr.common.Const.FABRICATED_OVERLAY_NAME_APPS;
import static com.drdisagree.colorblendr.common.Const.MONET_LAST_UPDATED;
import static com.drdisagree.colorblendr.common.Const.MONET_SEED_COLOR;
import static com.drdisagree.colorblendr.common.Const.MONET_SEED_COLOR_ENABLED;
import static com.drdisagree.colorblendr.common.Const.WALLPAPER_COLOR_LIST;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.drdisagree.colorblendr.ColorBlendr;
import com.drdisagree.colorblendr.common.Const;
import com.drdisagree.colorblendr.config.RPrefs;
import com.drdisagree.colorblendr.extension.MethodInterface;
import com.drdisagree.colorblendr.provider.RootServiceProvider;
import com.drdisagree.colorblendr.utils.AppUtil;
import com.drdisagree.colorblendr.utils.OverlayManager;
import com.drdisagree.colorblendr.utils.SystemUtil;
import com.drdisagree.colorblendr.utils.WallpaperUtil;
import java.util.ArrayList;
import java.util.HashMap; | 7,953 | package com.drdisagree.colorblendr.service;
public class BroadcastListener extends BroadcastReceiver {
private static final String TAG = BroadcastListener.class.getSimpleName();
public static int lastOrientation = -1;
private static long cooldownTime = 5000;
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Received intent: " + intent.getAction());
if (lastOrientation == -1) { | package com.drdisagree.colorblendr.service;
public class BroadcastListener extends BroadcastReceiver {
private static final String TAG = BroadcastListener.class.getSimpleName();
public static int lastOrientation = -1;
private static long cooldownTime = 5000;
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Received intent: " + intent.getAction());
if (lastOrientation == -1) { | lastOrientation = SystemUtil.getScreenRotation(context); | 12 | 2023-12-06 13:20:16+00:00 | 12k |
HelpChat/DeluxeMenus | src/main/java/com/extendedclip/deluxemenus/dupe/MenuItemMarker.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.dupe.marker.ItemMarker;
import com.extendedclip.deluxemenus.dupe.marker.impl.NMSMenuItemMarker;
import com.extendedclip.deluxemenus.dupe.marker.impl.PDCMenuItemMarker;
import com.extendedclip.deluxemenus.dupe.marker.impl.UnavailableMenuItemMarker;
import com.extendedclip.deluxemenus.nbt.NbtProvider;
import com.extendedclip.deluxemenus.utils.DebugLevel;
import com.extendedclip.deluxemenus.utils.VersionHelper;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.util.logging.Level;
import java.util.regex.Pattern;
| 8,649 | package com.extendedclip.deluxemenus.dupe;
public class MenuItemMarker implements ItemMarker {
private final static String DEFAULT_MARK = "DM";
private final static Pattern MARK_PATTERN = Pattern.compile("^[a-zA-Z0-9]+$");
private final static boolean SUPPORTS_PDC = VersionHelper.IS_PDC_VERSION;
private final static boolean SUPPORTS_NMS = NbtProvider.isAvailable();
private final ItemMarker marker;
private final String mark;
public MenuItemMarker(@NotNull final DeluxeMenus plugin) {
this(plugin, DEFAULT_MARK);
}
public MenuItemMarker(@NotNull final DeluxeMenus plugin, @NotNull final String mark) {
this.mark = DEFAULT_MARK.equals(mark) || MARK_PATTERN.matcher(mark).matches() ? mark : DEFAULT_MARK;
if (SUPPORTS_PDC) {
marker = new PDCMenuItemMarker(plugin, this.mark);
} else if (SUPPORTS_NMS) {
marker = new NMSMenuItemMarker(this.mark);
} else {
| package com.extendedclip.deluxemenus.dupe;
public class MenuItemMarker implements ItemMarker {
private final static String DEFAULT_MARK = "DM";
private final static Pattern MARK_PATTERN = Pattern.compile("^[a-zA-Z0-9]+$");
private final static boolean SUPPORTS_PDC = VersionHelper.IS_PDC_VERSION;
private final static boolean SUPPORTS_NMS = NbtProvider.isAvailable();
private final ItemMarker marker;
private final String mark;
public MenuItemMarker(@NotNull final DeluxeMenus plugin) {
this(plugin, DEFAULT_MARK);
}
public MenuItemMarker(@NotNull final DeluxeMenus plugin, @NotNull final String mark) {
this.mark = DEFAULT_MARK.equals(mark) || MARK_PATTERN.matcher(mark).matches() ? mark : DEFAULT_MARK;
if (SUPPORTS_PDC) {
marker = new PDCMenuItemMarker(plugin, this.mark);
} else if (SUPPORTS_NMS) {
marker = new NMSMenuItemMarker(this.mark);
} else {
| marker = new UnavailableMenuItemMarker();
| 4 | 2023-12-14 23:41:07+00:00 | 12k |
lxs2601055687/contextAdminRuoYi | ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java | [
{
"identifier": "Constants",
"path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/Constants.java",
"snippet": "public interface Constants {\n\n /**\n * UTF-8 字符集\n */\n String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n String GBK = \"GBK\";\n\n /**\n * www主域... | import cn.dev33.satoken.annotation.SaIgnore;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.SmsLoginBody;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.system.domain.vo.RouterVo;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.SysLoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | 9,659 | package com.ruoyi.web.controller.system;
/**
* 登录验证
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
public class SysLoginController {
private final SysLoginService loginService;
private final ISysMenuService menuService; | package com.ruoyi.web.controller.system;
/**
* 登录验证
*
* @author Lion Li
*/
@Validated
@RequiredArgsConstructor
@RestController
public class SysLoginController {
private final SysLoginService loginService;
private final ISysMenuService menuService; | private final ISysUserService userService; | 10 | 2023-12-07 12:06:21+00:00 | 12k |
Earthcomputer/ModCompatChecker | root/src/main/java/net/earthcomputer/modcompatchecker/checker/indy/LambdaMetafactoryChecker.java | [
{
"identifier": "Errors",
"path": "root/src/main/java/net/earthcomputer/modcompatchecker/checker/Errors.java",
"snippet": "public enum Errors {\n CLASS_EXTENDS_REMOVED(\"Superclass %s is removed\"),\n CLASS_EXTENDS_FINAL(\"Superclass %s is final\"),\n CLASS_EXTENDS_INTERFACE(\"Superclass %s is ... | import net.earthcomputer.modcompatchecker.checker.Errors;
import net.earthcomputer.modcompatchecker.indexer.IResolvedClass;
import net.earthcomputer.modcompatchecker.util.AccessFlags;
import net.earthcomputer.modcompatchecker.util.AccessLevel;
import net.earthcomputer.modcompatchecker.util.AsmUtil;
import net.earthcomputer.modcompatchecker.util.ClassMember;
import net.earthcomputer.modcompatchecker.util.InheritanceUtil;
import net.earthcomputer.modcompatchecker.util.OwnedClassMember;
import net.earthcomputer.modcompatchecker.util.UnimplementedMethodChecker;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import java.lang.invoke.LambdaMetafactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; | 7,622 | package net.earthcomputer.modcompatchecker.checker.indy;
public enum LambdaMetafactoryChecker implements IndyChecker {
INSTANCE;
@Override
public void check(IndyContext context) {
List<String> interfaces = new ArrayList<>();
List<String> interfaceMethodDescs = new ArrayList<>();
Type interfaceType = Type.getReturnType(context.descriptor());
if (interfaceType.getSort() != Type.OBJECT) {
return;
}
interfaces.add(interfaceType.getInternalName());
String interfaceMethodName = context.name();
if (!(context.args()[0] instanceof Type interfaceMethodType)) {
return;
}
interfaceMethodDescs.add(interfaceMethodType.getDescriptor());
if ("altMetafactory".equals(context.bsm().getName())) {
if (!(context.args()[3] instanceof Integer flags)) {
return;
}
int argIndex = 4;
if ((flags & LambdaMetafactory.FLAG_MARKERS) != 0) {
if (!(context.args()[argIndex++] instanceof Integer markerCount)) {
return;
}
for (int i = 0; i < markerCount; i++) {
if (!(context.args()[argIndex++] instanceof Type itfType)) {
return;
}
if (itfType.getSort() != Type.OBJECT) {
return;
}
interfaces.add(itfType.getInternalName());
}
}
if ((flags & LambdaMetafactory.FLAG_BRIDGES) != 0) {
if (!(context.args()[argIndex++] instanceof Integer bridgeCount)) {
return;
}
for (int i = 0; i < bridgeCount; i++) {
if (!(context.args()[argIndex++] instanceof Type bridgeType)) {
return;
}
if (bridgeType.getSort() != Type.METHOD) {
return;
}
interfaceMethodDescs.add(bridgeType.getDescriptor());
}
}
}
for (String interfaceName : interfaces) {
IResolvedClass resolvedInterface = context.index().findClass(interfaceName);
if (resolvedInterface == null) {
context.addProblem(Errors.LAMBDA_INTERFACE_REMOVED, interfaceName);
continue;
}
if (!AsmUtil.isClassAccessible(context.className(), interfaceName, resolvedInterface.getAccess().accessLevel())) {
context.addProblem(Errors.LAMBDA_INTERFACE_INACCESSIBLE, interfaceName, resolvedInterface.getAccess().accessLevel().getLowerName());
}
if (!resolvedInterface.getAccess().isInterface()) {
context.addProblem(Errors.LAMBDA_INTERFACE_NOT_AN_INTERFACE, interfaceName);
}
}
| package net.earthcomputer.modcompatchecker.checker.indy;
public enum LambdaMetafactoryChecker implements IndyChecker {
INSTANCE;
@Override
public void check(IndyContext context) {
List<String> interfaces = new ArrayList<>();
List<String> interfaceMethodDescs = new ArrayList<>();
Type interfaceType = Type.getReturnType(context.descriptor());
if (interfaceType.getSort() != Type.OBJECT) {
return;
}
interfaces.add(interfaceType.getInternalName());
String interfaceMethodName = context.name();
if (!(context.args()[0] instanceof Type interfaceMethodType)) {
return;
}
interfaceMethodDescs.add(interfaceMethodType.getDescriptor());
if ("altMetafactory".equals(context.bsm().getName())) {
if (!(context.args()[3] instanceof Integer flags)) {
return;
}
int argIndex = 4;
if ((flags & LambdaMetafactory.FLAG_MARKERS) != 0) {
if (!(context.args()[argIndex++] instanceof Integer markerCount)) {
return;
}
for (int i = 0; i < markerCount; i++) {
if (!(context.args()[argIndex++] instanceof Type itfType)) {
return;
}
if (itfType.getSort() != Type.OBJECT) {
return;
}
interfaces.add(itfType.getInternalName());
}
}
if ((flags & LambdaMetafactory.FLAG_BRIDGES) != 0) {
if (!(context.args()[argIndex++] instanceof Integer bridgeCount)) {
return;
}
for (int i = 0; i < bridgeCount; i++) {
if (!(context.args()[argIndex++] instanceof Type bridgeType)) {
return;
}
if (bridgeType.getSort() != Type.METHOD) {
return;
}
interfaceMethodDescs.add(bridgeType.getDescriptor());
}
}
}
for (String interfaceName : interfaces) {
IResolvedClass resolvedInterface = context.index().findClass(interfaceName);
if (resolvedInterface == null) {
context.addProblem(Errors.LAMBDA_INTERFACE_REMOVED, interfaceName);
continue;
}
if (!AsmUtil.isClassAccessible(context.className(), interfaceName, resolvedInterface.getAccess().accessLevel())) {
context.addProblem(Errors.LAMBDA_INTERFACE_INACCESSIBLE, interfaceName, resolvedInterface.getAccess().accessLevel().getLowerName());
}
if (!resolvedInterface.getAccess().isInterface()) {
context.addProblem(Errors.LAMBDA_INTERFACE_NOT_AN_INTERFACE, interfaceName);
}
}
| UnimplementedMethodChecker checker = new UnimplementedMethodChecker(context.index(), AsmUtil.OBJECT, interfaces.toArray(String[]::new)) { | 6 | 2023-12-11 00:48:12+00:00 | 12k |
HzlGauss/bulls | src/main/java/com/bulls/qa/testcase/testerhome/Demo.java | [
{
"identifier": "SConfig",
"path": "src/main/java/com/bulls/qa/configuration/SConfig.java",
"snippet": "@Configuration\n@ConfigurationPropertiesScan(basePackages = {\"com.bulls.qa.*\"})\n@ComponentScan(basePackages = {\"com.bulls.qa.*\"})\n@PropertySource(value = {\"application.properties\", \"${spring.... | import com.bulls.qa.configuration.SConfig;
import com.bulls.qa.request.Request;
import com.bulls.qa.service.CustomListener;
import com.bulls.qa.util.ExcelUtils;
import io.restassured.http.Headers;
import io.restassured.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Reporter;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.io.File;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat; | 10,516 | package com.bulls.qa.testcase.testerhome;
/**
* @author hzl
* @date 2023/10/25
*/
@Slf4j
@ContextConfiguration(classes = SConfig.class)
//@Listeners(CustomListener.class)
public class Demo extends AbstractTestNGSpringContextTests {
@Test(enabled = true, description = "打开帖子详情页→点赞")
public void test() {
log.info("test start");
//请求实例1
Request request = Request.getInstance("topics");
//请求1发送
Response response = request.doRequest();
String html = response.asString();
Headers headers = response.getHeaders();
Map<String, String> cookies = response.getCookies();
Document document = Jsoup.parse(html);
Element metaElement = document.select("meta[name=csrf-token]").first();
String x_csrf_token = null;
if (metaElement != null) {
x_csrf_token = metaElement.attr("content");
}
request = Request.getInstance("likes");
//request.addHeaders(headers);
request.addCookies(cookies);
if (x_csrf_token != null) {
request.addHeader("x-csrf-token",x_csrf_token);
}
response = request.doRequest();
assertThat(response.getStatusCode()).isGreaterThanOrEqualTo(200).as("返回状态码校验");
}
//参数化实例1
@Test(enabled = true, description = "参数化demo,方法", dataProvider = "idList")
public void dataProviderTest(String id, int type) {
//请求实例1
Request request = Request.getInstance("testerhomeLogin");
request.setParameter("user[login]","");
request.setParameter("user[password]","");
//请求1发送
Response response = request.doRequest();
log.info("id:{},type:{}",id,type);
assertThat(1+1>2).isTrue().as("断言失败举例");
}
//参数化实例2
@Test(enabled = true, description = "参数化demo,excel", dataProvider = "ids")
public void dataProviderTest2(String id, String type) {
log.info("id:{},type:{}",id,type);
assertThat(1+1==2).isTrue().as("断言举例");
}
@DataProvider(name = "idList")
private Object[][] idList() {
return new Object[][]{
{"806a1d02410e1c4b6cbf05a85c383381", 1},
{"806a1d02410e1c4b6cbf05a85c383382", 1}
};
}
@DataProvider(name = "ids")
private Object[][] excel() {
File file = new File("data/types.xlsx"); | package com.bulls.qa.testcase.testerhome;
/**
* @author hzl
* @date 2023/10/25
*/
@Slf4j
@ContextConfiguration(classes = SConfig.class)
//@Listeners(CustomListener.class)
public class Demo extends AbstractTestNGSpringContextTests {
@Test(enabled = true, description = "打开帖子详情页→点赞")
public void test() {
log.info("test start");
//请求实例1
Request request = Request.getInstance("topics");
//请求1发送
Response response = request.doRequest();
String html = response.asString();
Headers headers = response.getHeaders();
Map<String, String> cookies = response.getCookies();
Document document = Jsoup.parse(html);
Element metaElement = document.select("meta[name=csrf-token]").first();
String x_csrf_token = null;
if (metaElement != null) {
x_csrf_token = metaElement.attr("content");
}
request = Request.getInstance("likes");
//request.addHeaders(headers);
request.addCookies(cookies);
if (x_csrf_token != null) {
request.addHeader("x-csrf-token",x_csrf_token);
}
response = request.doRequest();
assertThat(response.getStatusCode()).isGreaterThanOrEqualTo(200).as("返回状态码校验");
}
//参数化实例1
@Test(enabled = true, description = "参数化demo,方法", dataProvider = "idList")
public void dataProviderTest(String id, int type) {
//请求实例1
Request request = Request.getInstance("testerhomeLogin");
request.setParameter("user[login]","");
request.setParameter("user[password]","");
//请求1发送
Response response = request.doRequest();
log.info("id:{},type:{}",id,type);
assertThat(1+1>2).isTrue().as("断言失败举例");
}
//参数化实例2
@Test(enabled = true, description = "参数化demo,excel", dataProvider = "ids")
public void dataProviderTest2(String id, String type) {
log.info("id:{},type:{}",id,type);
assertThat(1+1==2).isTrue().as("断言举例");
}
@DataProvider(name = "idList")
private Object[][] idList() {
return new Object[][]{
{"806a1d02410e1c4b6cbf05a85c383381", 1},
{"806a1d02410e1c4b6cbf05a85c383382", 1}
};
}
@DataProvider(name = "ids")
private Object[][] excel() {
File file = new File("data/types.xlsx"); | List<Map<Integer, String>> maps = ExcelUtils.readExcel(file); | 3 | 2023-12-14 06:54:24+00:00 | 12k |
DantSu/studio | core/src/main/java/studio/core/v1/reader/binary/BinaryStoryPackReader.java | [
{
"identifier": "BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT",
"path": "core/src/main/java/studio/core/v1/Constants.java",
"snippet": "public static final int BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT = 16;"
},
{
"identifier": "BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT_PADDING",
... | import static studio.core.v1.Constants.BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT;
import static studio.core.v1.Constants.BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT_PADDING;
import static studio.core.v1.Constants.BINARY_ENRICHED_METADATA_DESCRIPTION_TRUNCATE;
import static studio.core.v1.Constants.BINARY_ENRICHED_METADATA_NODE_NAME_TRUNCATE;
import static studio.core.v1.Constants.BINARY_ENRICHED_METADATA_SECTOR_1_ALIGNMENT_PADDING;
import static studio.core.v1.Constants.BINARY_ENRICHED_METADATA_STAGE_NODE_ALIGNMENT_PADDING;
import static studio.core.v1.Constants.BINARY_ENRICHED_METADATA_TITLE_TRUNCATE;
import static studio.core.v1.Constants.SECTOR_SIZE;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.UUID;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import studio.core.v1.model.ActionNode;
import studio.core.v1.model.ControlSettings;
import studio.core.v1.model.StageNode;
import studio.core.v1.model.StoryPack;
import studio.core.v1.model.Transition;
import studio.core.v1.model.asset.AudioAsset;
import studio.core.v1.model.asset.AudioType;
import studio.core.v1.model.asset.ImageAsset;
import studio.core.v1.model.asset.ImageType;
import studio.core.v1.model.enriched.EnrichedNodeMetadata;
import studio.core.v1.model.enriched.EnrichedNodePosition;
import studio.core.v1.model.enriched.EnrichedNodeType;
import studio.core.v1.model.enriched.EnrichedPackMetadata;
import studio.core.v1.model.metadata.StoryPackMetadata;
import studio.core.v1.reader.StoryPackReader;
import studio.core.v1.reader.binary.AssetAddr.AssetType;
import studio.core.v1.utils.PackFormat; | 7,523 | });
Optional.ofNullable(audioAssetAddr).ifPresent(adr -> {
List<StageNode> swa = stagesWithAudio.getOrDefault(adr, new ArrayList<>());
swa.add(stageNode);
stagesWithAudio.put(adr, swa);
});
// Action nodes will be updated when they are read
Optional.ofNullable(okActionNodeAddr).ifPresent(adr -> {
List<Transition> twa = transitionsWithAction.getOrDefault(adr, new ArrayList<>());
twa.add(okTransition);
transitionsWithAction.put(adr, twa);
});
Optional.ofNullable(homeActionNodeAddr).ifPresent(adr -> {
List<Transition> twa = transitionsWithAction.getOrDefault(adr, new ArrayList<>());
twa.add(homeTransition);
transitionsWithAction.put(adr, twa);
});
// Skip to end of sector
dis.skipBytes(SECTOR_SIZE - 54
- BINARY_ENRICHED_METADATA_STAGE_NODE_ALIGNMENT_PADDING
- BINARY_ENRICHED_METADATA_NODE_NAME_TRUNCATE*2 - 16 - 1 - 4);
}
// Read action nodes
// We are positioned at the end of sector stages+1
int currentOffset = stages;
Iterator<SectorAddr> actionNodesIter = actionNodesToVisit.iterator();
while (actionNodesIter.hasNext()) {
// Sector to read
SectorAddr actionNodeAddr = actionNodesIter.next();
// Skip to the beginning of the sector, if needed
while (actionNodeAddr.getOffset() > currentOffset) {
dis.skipBytes(SECTOR_SIZE);
currentOffset++;
}
List<StageNode> options = new ArrayList<>();
short optionAddr = dis.readShort();
while (optionAddr != 0) {
options.add(stageNodes.get(new SectorAddr(optionAddr)));
optionAddr = dis.readShort();
}
// Read (optional) enriched node metadata
int alignmentOverflow = 2*(options.size()) % BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT;
int alignmentPadding = BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT_PADDING + (alignmentOverflow > 0 ? BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT - alignmentOverflow : 0);
dis.skipBytes(alignmentPadding - 2); // No need to skip the last 2 bytes that were read in the previous loop
EnrichedNodeMetadata enrichedNodeMetadata = readEnrichedNodeMetadata(dis);
// Update action on transitions referencing this sector
ActionNode actionNode = new ActionNode(enrichedNodeMetadata, options);
transitionsWithAction.get(actionNodeAddr).forEach(transition -> transition.setActionNode(actionNode));
// Skip to end of sector
dis.skipBytes(SECTOR_SIZE - (2*(options.size()+1))
- (alignmentPadding - 2)
- BINARY_ENRICHED_METADATA_NODE_NAME_TRUNCATE*2 - 16 - 1 - 4);
currentOffset++;
}
// Read assets
Iterator<AssetAddr> assetAddrsIter = assetAddrsToVisit.iterator();
while (assetAddrsIter.hasNext()) {
// First sector to read
AssetAddr assetAddr = assetAddrsIter.next();
// Skip to the beginning of the sector, if needed
while (assetAddr.getOffset() > currentOffset) {
dis.skipBytes(SECTOR_SIZE);
currentOffset++;
}
// Read all bytes
byte[] assetBytes = new byte[SECTOR_SIZE * assetAddr.getSize()];
dis.read(assetBytes, 0, assetBytes.length);
// Update asset on stage nodes referencing this sector
if(assetAddr.getType() == AssetType.AUDIO) {
AudioAsset audioAsset = new AudioAsset(AudioType.WAV, assetBytes);
stagesWithAudio.get(assetAddr).forEach(stageNode -> stageNode.setAudio(audioAsset));
}
if(assetAddr.getType() == AssetType.IMAGE) {
ImageAsset imageAsset = new ImageAsset(ImageType.BMP, assetBytes);
stagesWithImage.get(assetAddr).forEach(stageNode -> stageNode.setImage(imageAsset));
}
currentOffset += assetAddr.getSize();
}
// Create storypack
StoryPack sp = new StoryPack();
sp.setUuid(stageNodes.get(new SectorAddr(0)).getUuid());
sp.setFactoryDisabled(factoryDisabled);
sp.setVersion(version);
sp.setStageNodes(List.copyOf(stageNodes.values()));
sp.setEnriched(enrichedPack);
sp.setNightModeAvailable(false);
return sp;
}
}
/** Read UTF16 String from stream. */
private Optional<String> readString(InputStream dis, int maxChars) throws IOException {
byte[] bytes = dis.readNBytes(maxChars*2);
String str = new String(bytes, StandardCharsets.UTF_16);
int firstNullChar = str.indexOf("\u0000");
if(firstNullChar == 0) {
return Optional.empty();
}
if(firstNullChar == -1) {
return Optional.of(str);
}
return Optional.of(str.substring(0, firstNullChar));
}
private EnrichedNodeMetadata readEnrichedNodeMetadata(DataInputStream dis) throws IOException {
Optional<String> maybeName = readString(dis, BINARY_ENRICHED_METADATA_NODE_NAME_TRUNCATE);
Optional<String> maybeGroupId = Optional.empty();
long groupIdLowBytes = dis.readLong();
long groupIdHighBytes = dis.readLong();
if (groupIdLowBytes != 0 || groupIdHighBytes != 0) {
maybeGroupId = Optional.of((new UUID(groupIdLowBytes, groupIdHighBytes)).toString());
} | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package studio.core.v1.reader.binary;
public class BinaryStoryPackReader implements StoryPackReader {
private static final Logger LOGGER = LogManager.getLogger(BinaryStoryPackReader.class);
public StoryPackMetadata readMetadata(Path path) throws IOException {
try(DataInputStream dis = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))){
// Pack metadata model
StoryPackMetadata metadata = new StoryPackMetadata(PackFormat.RAW);
// Read sector 1
dis.skipBytes(3); // Skip to version
metadata.setVersion(dis.readShort());
// Read (optional) enriched pack metadata
dis.skipBytes(BINARY_ENRICHED_METADATA_SECTOR_1_ALIGNMENT_PADDING);
Optional<String> maybeTitle = readString(dis, BINARY_ENRICHED_METADATA_TITLE_TRUNCATE);
metadata.setTitle(maybeTitle.orElse(null));
Optional<String> maybeDescription = readString(dis, BINARY_ENRICHED_METADATA_DESCRIPTION_TRUNCATE);
metadata.setDescription(maybeDescription.orElse(null));
// TODO Thumbnail?
dis.skipBytes(SECTOR_SIZE - 5
- BINARY_ENRICHED_METADATA_SECTOR_1_ALIGNMENT_PADDING
- BINARY_ENRICHED_METADATA_TITLE_TRUNCATE*2
- BINARY_ENRICHED_METADATA_DESCRIPTION_TRUNCATE*2); // Skip to end of sector
// Read main stage node
long uuidLowBytes = dis.readLong();
long uuidHighBytes = dis.readLong();
String uuid = (new UUID(uuidLowBytes, uuidHighBytes)).toString();
metadata.setUuid(uuid);
return metadata;
}
}
public StoryPack read(Path path) throws IOException {
try(DataInputStream dis = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))) {
// Read sector 1
short stages = dis.readShort();
boolean factoryDisabled = dis.readByte() == 1;
short version = dis.readShort();
// Read (optional) enriched pack metadata
EnrichedPackMetadata enrichedPack = null;
dis.skipBytes(BINARY_ENRICHED_METADATA_SECTOR_1_ALIGNMENT_PADDING);
Optional<String> maybeTitle = readString(dis, BINARY_ENRICHED_METADATA_TITLE_TRUNCATE);
Optional<String> maybeDescription = readString(dis, BINARY_ENRICHED_METADATA_DESCRIPTION_TRUNCATE);
// TODO Thumbnail?
if (maybeTitle.or(() -> maybeDescription).isPresent() ) {
enrichedPack = new EnrichedPackMetadata(maybeTitle.orElse(null), maybeDescription.orElse(null));
}
dis.skipBytes(SECTOR_SIZE - 5
- BINARY_ENRICHED_METADATA_SECTOR_1_ALIGNMENT_PADDING
- BINARY_ENRICHED_METADATA_TITLE_TRUNCATE*2
- BINARY_ENRICHED_METADATA_DESCRIPTION_TRUNCATE*2); // Skip to end of sector
// Read stage nodes (`stages` sectors, starting from sector 2)
TreeMap<SectorAddr, StageNode> stageNodes = new TreeMap<>();
TreeMap<AssetAddr, List<StageNode>> stagesWithImage = new TreeMap<>(); // StageNodes must be updated with the actual ImageAsset
TreeMap<AssetAddr, List<StageNode>> stagesWithAudio = new TreeMap<>(); // StageNodes must be updated with the actual AudioAsset
TreeMap<SectorAddr, List<Transition>> transitionsWithAction = new TreeMap<>(); // Transitions must be updated with the actual ActionNode
Set<SectorAddr> actionNodesToVisit = new TreeSet<>(); // Stage nodes / transitions reference action nodes, which are read after all stage nodes
Set<AssetAddr> assetAddrsToVisit = new TreeSet<>(); // Stage nodes reference assets, which are read after all nodes
for (int i = 0; i < stages; i++) {
// Reading sector i+2
// UUID
long uuidLowBytes = dis.readLong();
long uuidHighBytes = dis.readLong();
String uuid = (new UUID(uuidLowBytes, uuidHighBytes)).toString();
// Image asset
int imageOffset = dis.readInt();
int imageSize = dis.readInt();
AssetAddr imageAssetAddr = null;
if (imageOffset != -1) {
// Asset must be visited
imageAssetAddr = new AssetAddr(AssetType.IMAGE, imageOffset, imageSize);
assetAddrsToVisit.add(imageAssetAddr);
}
// Audio asset
int audioOffset = dis.readInt();
int audioSize = dis.readInt();
AssetAddr audioAssetAddr = null;
if (audioOffset != -1) {
// Asset must be visited
audioAssetAddr = new AssetAddr(AssetType.AUDIO, audioOffset, audioSize);
assetAddrsToVisit.add(audioAssetAddr);
}
// Transitions
short okTransitionOffset = dis.readShort();
short okTransitionCount = dis.readShort();
short okTransitionIndex = dis.readShort();
SectorAddr okActionNodeAddr = null;
if (okTransitionOffset != -1) {
// Action node must be visited
okActionNodeAddr = new SectorAddr(okTransitionOffset);
actionNodesToVisit.add(okActionNodeAddr);
}
Transition okTransition = Optional.ofNullable(okActionNodeAddr)
.map(h -> new Transition(null, okTransitionIndex)).orElse(null);
short homeTransitionOffset = dis.readShort();
short homeTransitionCount = dis.readShort();
short homeTransitionIndex = dis.readShort();
SectorAddr homeActionNodeAddr = null;
if (homeTransitionOffset != -1) {
// Action node must be visited
homeActionNodeAddr = new SectorAddr(homeTransitionOffset);
actionNodesToVisit.add(homeActionNodeAddr);
}
Transition homeTransition = Optional.ofNullable(homeActionNodeAddr)
.map(h -> new Transition(null, homeTransitionIndex)).orElse(null);
LOGGER.trace("Transitions : {} ok, {} home", okTransitionCount, homeTransitionCount);
// Control settings
boolean wheelEnabled = dis.readShort() == 1;
boolean okEnabled = dis.readShort() == 1;
boolean homeEnabled = dis.readShort() == 1;
boolean pauseEnabled = dis.readShort() == 1;
boolean autoJumpEnabled = dis.readShort() == 1;
ControlSettings ctrl = new ControlSettings(wheelEnabled, okEnabled, homeEnabled, pauseEnabled, autoJumpEnabled);
// Read (optional) enriched node metadata
dis.skipBytes(BINARY_ENRICHED_METADATA_STAGE_NODE_ALIGNMENT_PADDING);
EnrichedNodeMetadata enrichedNode = readEnrichedNodeMetadata(dis);
// Build stage node
StageNode stageNode = new StageNode(uuid, null, null, okTransition, homeTransition, ctrl, enrichedNode);
stageNodes.put(new SectorAddr(i), stageNode);
// Assets will be updated when they are read
Optional.ofNullable(imageAssetAddr).ifPresent(adr -> {
List<StageNode> swi = stagesWithImage.getOrDefault(adr, new ArrayList<>());
swi.add(stageNode);
stagesWithImage.put(adr, swi);
});
Optional.ofNullable(audioAssetAddr).ifPresent(adr -> {
List<StageNode> swa = stagesWithAudio.getOrDefault(adr, new ArrayList<>());
swa.add(stageNode);
stagesWithAudio.put(adr, swa);
});
// Action nodes will be updated when they are read
Optional.ofNullable(okActionNodeAddr).ifPresent(adr -> {
List<Transition> twa = transitionsWithAction.getOrDefault(adr, new ArrayList<>());
twa.add(okTransition);
transitionsWithAction.put(adr, twa);
});
Optional.ofNullable(homeActionNodeAddr).ifPresent(adr -> {
List<Transition> twa = transitionsWithAction.getOrDefault(adr, new ArrayList<>());
twa.add(homeTransition);
transitionsWithAction.put(adr, twa);
});
// Skip to end of sector
dis.skipBytes(SECTOR_SIZE - 54
- BINARY_ENRICHED_METADATA_STAGE_NODE_ALIGNMENT_PADDING
- BINARY_ENRICHED_METADATA_NODE_NAME_TRUNCATE*2 - 16 - 1 - 4);
}
// Read action nodes
// We are positioned at the end of sector stages+1
int currentOffset = stages;
Iterator<SectorAddr> actionNodesIter = actionNodesToVisit.iterator();
while (actionNodesIter.hasNext()) {
// Sector to read
SectorAddr actionNodeAddr = actionNodesIter.next();
// Skip to the beginning of the sector, if needed
while (actionNodeAddr.getOffset() > currentOffset) {
dis.skipBytes(SECTOR_SIZE);
currentOffset++;
}
List<StageNode> options = new ArrayList<>();
short optionAddr = dis.readShort();
while (optionAddr != 0) {
options.add(stageNodes.get(new SectorAddr(optionAddr)));
optionAddr = dis.readShort();
}
// Read (optional) enriched node metadata
int alignmentOverflow = 2*(options.size()) % BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT;
int alignmentPadding = BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT_PADDING + (alignmentOverflow > 0 ? BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT - alignmentOverflow : 0);
dis.skipBytes(alignmentPadding - 2); // No need to skip the last 2 bytes that were read in the previous loop
EnrichedNodeMetadata enrichedNodeMetadata = readEnrichedNodeMetadata(dis);
// Update action on transitions referencing this sector
ActionNode actionNode = new ActionNode(enrichedNodeMetadata, options);
transitionsWithAction.get(actionNodeAddr).forEach(transition -> transition.setActionNode(actionNode));
// Skip to end of sector
dis.skipBytes(SECTOR_SIZE - (2*(options.size()+1))
- (alignmentPadding - 2)
- BINARY_ENRICHED_METADATA_NODE_NAME_TRUNCATE*2 - 16 - 1 - 4);
currentOffset++;
}
// Read assets
Iterator<AssetAddr> assetAddrsIter = assetAddrsToVisit.iterator();
while (assetAddrsIter.hasNext()) {
// First sector to read
AssetAddr assetAddr = assetAddrsIter.next();
// Skip to the beginning of the sector, if needed
while (assetAddr.getOffset() > currentOffset) {
dis.skipBytes(SECTOR_SIZE);
currentOffset++;
}
// Read all bytes
byte[] assetBytes = new byte[SECTOR_SIZE * assetAddr.getSize()];
dis.read(assetBytes, 0, assetBytes.length);
// Update asset on stage nodes referencing this sector
if(assetAddr.getType() == AssetType.AUDIO) {
AudioAsset audioAsset = new AudioAsset(AudioType.WAV, assetBytes);
stagesWithAudio.get(assetAddr).forEach(stageNode -> stageNode.setAudio(audioAsset));
}
if(assetAddr.getType() == AssetType.IMAGE) {
ImageAsset imageAsset = new ImageAsset(ImageType.BMP, assetBytes);
stagesWithImage.get(assetAddr).forEach(stageNode -> stageNode.setImage(imageAsset));
}
currentOffset += assetAddr.getSize();
}
// Create storypack
StoryPack sp = new StoryPack();
sp.setUuid(stageNodes.get(new SectorAddr(0)).getUuid());
sp.setFactoryDisabled(factoryDisabled);
sp.setVersion(version);
sp.setStageNodes(List.copyOf(stageNodes.values()));
sp.setEnriched(enrichedPack);
sp.setNightModeAvailable(false);
return sp;
}
}
/** Read UTF16 String from stream. */
private Optional<String> readString(InputStream dis, int maxChars) throws IOException {
byte[] bytes = dis.readNBytes(maxChars*2);
String str = new String(bytes, StandardCharsets.UTF_16);
int firstNullChar = str.indexOf("\u0000");
if(firstNullChar == 0) {
return Optional.empty();
}
if(firstNullChar == -1) {
return Optional.of(str);
}
return Optional.of(str.substring(0, firstNullChar));
}
private EnrichedNodeMetadata readEnrichedNodeMetadata(DataInputStream dis) throws IOException {
Optional<String> maybeName = readString(dis, BINARY_ENRICHED_METADATA_NODE_NAME_TRUNCATE);
Optional<String> maybeGroupId = Optional.empty();
long groupIdLowBytes = dis.readLong();
long groupIdHighBytes = dis.readLong();
if (groupIdLowBytes != 0 || groupIdHighBytes != 0) {
maybeGroupId = Optional.of((new UUID(groupIdLowBytes, groupIdHighBytes)).toString());
} | Optional<EnrichedNodeType> maybeType = Optional.empty(); | 19 | 2023-12-14 15:08:35+00:00 | 12k |
conductor-oss/conductor-community | persistence/postgres-persistence/src/test/java/com/netflix/conductor/postgres/dao/PostgresQueueDAOTest.java | [
{
"identifier": "TestObjectMapperConfiguration",
"path": "test-util/src/test/java/com/netflix/conductor/common/config/TestObjectMapperConfiguration.java",
"snippet": "@Configuration\npublic class TestObjectMapperConfiguration {\n\n @Bean\n public ObjectMapper testObjectMapper() {\n return n... | import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import com.netflix.conductor.common.config.TestObjectMapperConfiguration;
import com.netflix.conductor.core.events.queue.Message;
import com.netflix.conductor.postgres.config.PostgresConfiguration;
import com.netflix.conductor.postgres.util.Query;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; | 7,472 | /*
* <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.postgres.dao;
@ContextConfiguration(
classes = {
TestObjectMapperConfiguration.class,
PostgresConfiguration.class,
FlywayAutoConfiguration.class
})
@RunWith(SpringRunner.class)
@SpringBootTest
public class PostgresQueueDAOTest {
private static final Logger LOGGER = LoggerFactory.getLogger(PostgresQueueDAOTest.class);
@Autowired private PostgresQueueDAO queueDAO;
@Qualifier("dataSource")
@Autowired
private DataSource dataSource;
@Autowired private ObjectMapper objectMapper;
@Rule public TestName name = new TestName();
@Autowired Flyway flyway;
// clean the database between tests.
@Before
public void before() {
flyway.clean();
flyway.migrate();
}
@Test
public void complexQueueTest() {
String queueName = "TestQueue";
long offsetTimeInSecond = 0;
for (int i = 0; i < 10; i++) {
String messageId = "msg" + i;
queueDAO.push(queueName, messageId, offsetTimeInSecond);
}
int size = queueDAO.getSize(queueName);
assertEquals(10, size);
Map<String, Long> details = queueDAO.queuesDetail();
assertEquals(1, details.size());
assertEquals(10L, details.get(queueName).longValue());
for (int i = 0; i < 10; i++) {
String messageId = "msg" + i;
queueDAO.pushIfNotExists(queueName, messageId, offsetTimeInSecond);
}
List<String> popped = queueDAO.pop(queueName, 10, 100);
assertNotNull(popped);
assertEquals(10, popped.size());
Map<String, Map<String, Map<String, Long>>> verbose = queueDAO.queuesDetailVerbose();
assertEquals(1, verbose.size());
long shardSize = verbose.get(queueName).get("a").get("size");
long unackedSize = verbose.get(queueName).get("a").get("uacked");
assertEquals(0, shardSize);
assertEquals(10, unackedSize);
popped.forEach(messageId -> queueDAO.ack(queueName, messageId));
verbose = queueDAO.queuesDetailVerbose();
assertEquals(1, verbose.size());
shardSize = verbose.get(queueName).get("a").get("size");
unackedSize = verbose.get(queueName).get("a").get("uacked");
assertEquals(0, shardSize);
assertEquals(0, unackedSize);
popped = queueDAO.pop(queueName, 10, 100);
assertNotNull(popped);
assertEquals(0, popped.size());
for (int i = 0; i < 10; i++) {
String messageId = "msg" + i;
queueDAO.pushIfNotExists(queueName, messageId, offsetTimeInSecond);
}
size = queueDAO.getSize(queueName);
assertEquals(10, size);
for (int i = 0; i < 10; i++) {
String messageId = "msg" + i;
assertTrue(queueDAO.containsMessage(queueName, messageId));
queueDAO.remove(queueName, messageId);
}
size = queueDAO.getSize(queueName);
assertEquals(0, size);
for (int i = 0; i < 10; i++) {
String messageId = "msg" + i;
queueDAO.pushIfNotExists(queueName, messageId, offsetTimeInSecond);
}
queueDAO.flush(queueName);
size = queueDAO.getSize(queueName);
assertEquals(0, size);
}
/**
* Test fix for https://github.com/Netflix/conductor/issues/399
*
* @since 1.8.2-rc5
*/
@Test
public void pollMessagesTest() {
final List<Message> messages = new ArrayList<>();
final String queueName = "issue399_testQueue";
final int totalSize = 10;
for (int i = 0; i < totalSize; i++) {
String payload = "{\"id\": " + i + ", \"msg\":\"test " + i + "\"}";
Message m = new Message("testmsg-" + i, payload, "");
if (i % 2 == 0) {
// Set priority on message with pair id
m.setPriority(99 - i);
}
messages.add(m);
}
// Populate the queue with our test message batch
queueDAO.push(queueName, ImmutableList.copyOf(messages));
// Assert that all messages were persisted and no extras are in there
assertEquals("Queue size mismatch", totalSize, queueDAO.getSize(queueName));
List<Message> zeroPoll = queueDAO.pollMessages(queueName, 0, 10_000);
assertTrue("Zero poll should be empty", zeroPoll.isEmpty());
final int firstPollSize = 3;
List<Message> firstPoll = queueDAO.pollMessages(queueName, firstPollSize, 10_000);
assertNotNull("First poll was null", firstPoll);
assertFalse("First poll was empty", firstPoll.isEmpty());
assertEquals("First poll size mismatch", firstPollSize, firstPoll.size());
final int secondPollSize = 4;
List<Message> secondPoll = queueDAO.pollMessages(queueName, secondPollSize, 10_000);
assertNotNull("Second poll was null", secondPoll);
assertFalse("Second poll was empty", secondPoll.isEmpty());
assertEquals("Second poll size mismatch", secondPollSize, secondPoll.size());
// Assert that the total queue size hasn't changed
assertEquals(
"Total queue size should have remained the same",
totalSize,
queueDAO.getSize(queueName));
// Assert that our un-popped messages match our expected size
final long expectedSize = totalSize - firstPollSize - secondPollSize;
try (Connection c = dataSource.getConnection()) {
String UNPOPPED =
"SELECT COUNT(*) FROM queue_message WHERE queue_name = ? AND popped = false"; | /*
* <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.postgres.dao;
@ContextConfiguration(
classes = {
TestObjectMapperConfiguration.class,
PostgresConfiguration.class,
FlywayAutoConfiguration.class
})
@RunWith(SpringRunner.class)
@SpringBootTest
public class PostgresQueueDAOTest {
private static final Logger LOGGER = LoggerFactory.getLogger(PostgresQueueDAOTest.class);
@Autowired private PostgresQueueDAO queueDAO;
@Qualifier("dataSource")
@Autowired
private DataSource dataSource;
@Autowired private ObjectMapper objectMapper;
@Rule public TestName name = new TestName();
@Autowired Flyway flyway;
// clean the database between tests.
@Before
public void before() {
flyway.clean();
flyway.migrate();
}
@Test
public void complexQueueTest() {
String queueName = "TestQueue";
long offsetTimeInSecond = 0;
for (int i = 0; i < 10; i++) {
String messageId = "msg" + i;
queueDAO.push(queueName, messageId, offsetTimeInSecond);
}
int size = queueDAO.getSize(queueName);
assertEquals(10, size);
Map<String, Long> details = queueDAO.queuesDetail();
assertEquals(1, details.size());
assertEquals(10L, details.get(queueName).longValue());
for (int i = 0; i < 10; i++) {
String messageId = "msg" + i;
queueDAO.pushIfNotExists(queueName, messageId, offsetTimeInSecond);
}
List<String> popped = queueDAO.pop(queueName, 10, 100);
assertNotNull(popped);
assertEquals(10, popped.size());
Map<String, Map<String, Map<String, Long>>> verbose = queueDAO.queuesDetailVerbose();
assertEquals(1, verbose.size());
long shardSize = verbose.get(queueName).get("a").get("size");
long unackedSize = verbose.get(queueName).get("a").get("uacked");
assertEquals(0, shardSize);
assertEquals(10, unackedSize);
popped.forEach(messageId -> queueDAO.ack(queueName, messageId));
verbose = queueDAO.queuesDetailVerbose();
assertEquals(1, verbose.size());
shardSize = verbose.get(queueName).get("a").get("size");
unackedSize = verbose.get(queueName).get("a").get("uacked");
assertEquals(0, shardSize);
assertEquals(0, unackedSize);
popped = queueDAO.pop(queueName, 10, 100);
assertNotNull(popped);
assertEquals(0, popped.size());
for (int i = 0; i < 10; i++) {
String messageId = "msg" + i;
queueDAO.pushIfNotExists(queueName, messageId, offsetTimeInSecond);
}
size = queueDAO.getSize(queueName);
assertEquals(10, size);
for (int i = 0; i < 10; i++) {
String messageId = "msg" + i;
assertTrue(queueDAO.containsMessage(queueName, messageId));
queueDAO.remove(queueName, messageId);
}
size = queueDAO.getSize(queueName);
assertEquals(0, size);
for (int i = 0; i < 10; i++) {
String messageId = "msg" + i;
queueDAO.pushIfNotExists(queueName, messageId, offsetTimeInSecond);
}
queueDAO.flush(queueName);
size = queueDAO.getSize(queueName);
assertEquals(0, size);
}
/**
* Test fix for https://github.com/Netflix/conductor/issues/399
*
* @since 1.8.2-rc5
*/
@Test
public void pollMessagesTest() {
final List<Message> messages = new ArrayList<>();
final String queueName = "issue399_testQueue";
final int totalSize = 10;
for (int i = 0; i < totalSize; i++) {
String payload = "{\"id\": " + i + ", \"msg\":\"test " + i + "\"}";
Message m = new Message("testmsg-" + i, payload, "");
if (i % 2 == 0) {
// Set priority on message with pair id
m.setPriority(99 - i);
}
messages.add(m);
}
// Populate the queue with our test message batch
queueDAO.push(queueName, ImmutableList.copyOf(messages));
// Assert that all messages were persisted and no extras are in there
assertEquals("Queue size mismatch", totalSize, queueDAO.getSize(queueName));
List<Message> zeroPoll = queueDAO.pollMessages(queueName, 0, 10_000);
assertTrue("Zero poll should be empty", zeroPoll.isEmpty());
final int firstPollSize = 3;
List<Message> firstPoll = queueDAO.pollMessages(queueName, firstPollSize, 10_000);
assertNotNull("First poll was null", firstPoll);
assertFalse("First poll was empty", firstPoll.isEmpty());
assertEquals("First poll size mismatch", firstPollSize, firstPoll.size());
final int secondPollSize = 4;
List<Message> secondPoll = queueDAO.pollMessages(queueName, secondPollSize, 10_000);
assertNotNull("Second poll was null", secondPoll);
assertFalse("Second poll was empty", secondPoll.isEmpty());
assertEquals("Second poll size mismatch", secondPollSize, secondPoll.size());
// Assert that the total queue size hasn't changed
assertEquals(
"Total queue size should have remained the same",
totalSize,
queueDAO.getSize(queueName));
// Assert that our un-popped messages match our expected size
final long expectedSize = totalSize - firstPollSize - secondPollSize;
try (Connection c = dataSource.getConnection()) {
String UNPOPPED =
"SELECT COUNT(*) FROM queue_message WHERE queue_name = ? AND popped = false"; | try (Query q = new Query(objectMapper, c, UNPOPPED)) { | 2 | 2023-12-08 06:06:20+00:00 | 12k |
blueokanna/ReverseCoin | src/main/java/top/pulselink/java/reversecoin/ReverseCoin.java | [
{
"identifier": "PeerMessages",
"path": "src/main/java/BlockModel/PeerMessages.java",
"snippet": "public class PeerMessages implements Serializable, ReverseCoinBlockMessagesInterface {\n\n private static final long serialVersionUID = 1145141919810L;\n\n private CommandCode CommandCode;\n privat... | import BlockModel.PeerMessages;
import BlockModel.ReverseCoinBlock;
import ClientSeverMach.P2PClient;
import ClientSeverMach.P2PServer;
import ReverseCoinBlockChainGeneration.BlockChainConfig;
import ReverseCoinBlockChainGeneration.NewBlockCreation;
import ReverseCoinChainNetwork.P2PNetwork;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ConnectionAPI.NewReverseCoinBlockInterface;
import ConnectionAPI.ReverseCoinBlockEventListener;
import ConnectionAPI.ReverseCoinChainConfigInterface;
import ConnectionAPI.ReverseCoinBlockInterface; | 7,294 | package top.pulselink.java.reversecoin;
public class ReverseCoin {
private volatile BlockChainConfig blockConfig = new BlockChainConfig();
private volatile ReverseCoinBlock block = new ReverseCoinBlock();
private volatile NewBlockCreation newBlock = new NewBlockCreation();
private volatile PeerMessages message = new PeerMessages();
private volatile ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private volatile P2PNetwork network = new P2PNetwork();
private static final Logger logger = LoggerFactory.getLogger(ReverseCoin.class);
public ReverseCoin(String address, int port, int difficulty) {
blockConfig.setDifficulty(difficulty);
blockConfig.setPorts(port);
blockConfig.setAddressPort(address);
initializeConnections();
startInputReader(block, new BlockEventManager(), newBlock, blockConfig, address);
}
private synchronized void startInputReader(ReverseCoinBlockInterface block, ReverseCoinBlockEventListener listener, NewReverseCoinBlockInterface addnewblock, ReverseCoinChainConfigInterface configParams, String addressPort) {
if (!executor.isShutdown() && !executor.isTerminated()) {
CompletableFuture.runAsync(() -> {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
String str;
while ((str = reader.readLine()) != null) {
handleEvent(str, block, listener, addnewblock, configParams, addressPort);
}
} catch (IOException e) {
logger.error(e.getMessage());
}
}, executor);
}
}
private void initializeConnections() {
printNodeInfo(blockConfig);
CompletableFuture<Void> serverInitFuture = CompletableFuture.runAsync(() -> initP2PServer());
CompletableFuture<Void> clientConnectFuture = CompletableFuture.runAsync(() -> connectToPeer());
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
executor.shutdownNow();
try {
executor.awaitTermination(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error(e.getMessage());
}
}));
CompletableFuture<Void> allTasks = CompletableFuture.allOf(serverInitFuture, clientConnectFuture);
allTasks.join();
}
private void printNodeInfo(ReverseCoinChainConfigInterface configParams) {
int difficulty = configParams.getDifficulty();
int ports = configParams.getPorts();
String addressPort = configParams.getAddressPort();
System.out.println("------------------\nPetaBlock Difficulty: " + difficulty + "\n------------------");
System.out.println("------------------\nP2P Port: " + ports + "\n------------------");
System.out.println("------------------\nP2P Network IP with Port: " + addressPort + "\n------------------");
System.out.println();
}
private void initP2PServer() { | package top.pulselink.java.reversecoin;
public class ReverseCoin {
private volatile BlockChainConfig blockConfig = new BlockChainConfig();
private volatile ReverseCoinBlock block = new ReverseCoinBlock();
private volatile NewBlockCreation newBlock = new NewBlockCreation();
private volatile PeerMessages message = new PeerMessages();
private volatile ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private volatile P2PNetwork network = new P2PNetwork();
private static final Logger logger = LoggerFactory.getLogger(ReverseCoin.class);
public ReverseCoin(String address, int port, int difficulty) {
blockConfig.setDifficulty(difficulty);
blockConfig.setPorts(port);
blockConfig.setAddressPort(address);
initializeConnections();
startInputReader(block, new BlockEventManager(), newBlock, blockConfig, address);
}
private synchronized void startInputReader(ReverseCoinBlockInterface block, ReverseCoinBlockEventListener listener, NewReverseCoinBlockInterface addnewblock, ReverseCoinChainConfigInterface configParams, String addressPort) {
if (!executor.isShutdown() && !executor.isTerminated()) {
CompletableFuture.runAsync(() -> {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
String str;
while ((str = reader.readLine()) != null) {
handleEvent(str, block, listener, addnewblock, configParams, addressPort);
}
} catch (IOException e) {
logger.error(e.getMessage());
}
}, executor);
}
}
private void initializeConnections() {
printNodeInfo(blockConfig);
CompletableFuture<Void> serverInitFuture = CompletableFuture.runAsync(() -> initP2PServer());
CompletableFuture<Void> clientConnectFuture = CompletableFuture.runAsync(() -> connectToPeer());
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
executor.shutdownNow();
try {
executor.awaitTermination(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error(e.getMessage());
}
}));
CompletableFuture<Void> allTasks = CompletableFuture.allOf(serverInitFuture, clientConnectFuture);
allTasks.join();
}
private void printNodeInfo(ReverseCoinChainConfigInterface configParams) {
int difficulty = configParams.getDifficulty();
int ports = configParams.getPorts();
String addressPort = configParams.getAddressPort();
System.out.println("------------------\nPetaBlock Difficulty: " + difficulty + "\n------------------");
System.out.println("------------------\nP2P Port: " + ports + "\n------------------");
System.out.println("------------------\nP2P Network IP with Port: " + addressPort + "\n------------------");
System.out.println();
}
private void initP2PServer() { | P2PServer server = new P2PServer(); | 3 | 2023-12-11 05:18:04+00:00 | 12k |
i-moonlight/Movie_Manager | backend/src/main/java/ch/xxx/moviemanager/usecase/service/MovieService.java | [
{
"identifier": "MovieDbRestClient",
"path": "backend/src/main/java/ch/xxx/moviemanager/domain/client/MovieDbRestClient.java",
"snippet": "public interface MovieDbRestClient {\n\tMovieDto fetchMovie(String moviedbkey, long movieDbId);\n\t\n\tWrapperCastDto fetchCast(String moviedbkey, Long movieId);\n\t... | import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.google.crypto.tink.DeterministicAead;
import com.google.crypto.tink.InsecureSecretKeyAccess;
import com.google.crypto.tink.KeysetHandle;
import com.google.crypto.tink.TinkJsonProtoKeysetFormat;
import com.google.crypto.tink.daead.DeterministicAeadConfig;
import ch.xxx.moviemanager.domain.client.MovieDbRestClient;
import ch.xxx.moviemanager.domain.common.CommonUtils;
import ch.xxx.moviemanager.domain.model.dto.ActorDto;
import ch.xxx.moviemanager.domain.model.dto.CastDto;
import ch.xxx.moviemanager.domain.model.dto.GenereDto;
import ch.xxx.moviemanager.domain.model.dto.MovieDto;
import ch.xxx.moviemanager.domain.model.dto.MovieFilterCriteriaDto;
import ch.xxx.moviemanager.domain.model.dto.SearchTermDto;
import ch.xxx.moviemanager.domain.model.dto.WrapperCastDto;
import ch.xxx.moviemanager.domain.model.dto.WrapperGenereDto;
import ch.xxx.moviemanager.domain.model.dto.WrapperMovieDto;
import ch.xxx.moviemanager.domain.model.entity.Actor;
import ch.xxx.moviemanager.domain.model.entity.ActorRepository;
import ch.xxx.moviemanager.domain.model.entity.Cast;
import ch.xxx.moviemanager.domain.model.entity.CastRepository;
import ch.xxx.moviemanager.domain.model.entity.Genere;
import ch.xxx.moviemanager.domain.model.entity.GenereRepository;
import ch.xxx.moviemanager.domain.model.entity.Movie;
import ch.xxx.moviemanager.domain.model.entity.MovieRepository;
import ch.xxx.moviemanager.domain.model.entity.User;
import ch.xxx.moviemanager.usecase.mapper.DefaultMapper;
import jakarta.annotation.PostConstruct; | 8,589 | /**
* Copyright 2019 Sven Loesekann
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 ch.xxx.moviemanager.usecase.service;
@Transactional
@Service
public class MovieService {
private static final Logger LOG = LoggerFactory.getLogger(MovieService.class);
private final MovieRepository movieRep;
private final CastRepository castRep;
private final ActorRepository actorRep;
private final GenereRepository genereRep;
private final UserDetailService userDetailService;
private final DefaultMapper mapper; | /**
* Copyright 2019 Sven Loesekann
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 ch.xxx.moviemanager.usecase.service;
@Transactional
@Service
public class MovieService {
private static final Logger LOG = LoggerFactory.getLogger(MovieService.class);
private final MovieRepository movieRep;
private final CastRepository castRep;
private final ActorRepository actorRep;
private final GenereRepository genereRep;
private final UserDetailService userDetailService;
private final DefaultMapper mapper; | private final MovieDbRestClient movieDbRestClient; | 0 | 2023-12-11 13:53:51+00:00 | 12k |
i-moonlight/Suricate | src/main/java/com/michelin/suricate/configuration/web/WebConfig.java | [
{
"identifier": "ApplicationProperties",
"path": "src/main/java/com/michelin/suricate/properties/ApplicationProperties.java",
"snippet": "@Getter\n@Setter\n@Configuration\n@PropertySource(\"classpath:application.properties\")\n@ConfigurationProperties(prefix = \"application\", ignoreUnknownFields = fals... | import com.michelin.suricate.properties.ApplicationProperties;
import com.michelin.suricate.security.AuthenticationFailureEntryPoint;
import com.michelin.suricate.security.filter.JwtTokenFilter;
import com.michelin.suricate.security.filter.PersonalAccessTokenFilter;
import com.michelin.suricate.security.oauth2.HttpCookieOauth2AuthorizationRequestRepository;
import com.michelin.suricate.security.oauth2.Oauth2AuthenticationFailureHandler;
import com.michelin.suricate.security.oauth2.Oauth2AuthenticationSuccessHandler;
import com.michelin.suricate.security.oauth2.Oauth2UserService;
import com.michelin.suricate.security.oauth2.OpenIdcUserService;
import java.io.IOException;
import java.util.Locale;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.resource.PathResourceResolver; | 7,343 | /*
* Copyright 2012-2021 the original author or 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 com.michelin.suricate.configuration.web;
/**
* Web configuration.
*/
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class WebConfig implements WebMvcConfigurer {
@Autowired
private ApplicationProperties applicationProperties;
@Value("${spring.h2.console.enabled:false}")
private boolean h2Enabled;
/**
* The view resolver.
*
* @param registry Store the configurations
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/public/")
.resourceChain(true)
.addResolver(new PathResourceResolver() {
@Override
protected Resource getResource(@NotNull String resourcePath, @NotNull Resource location)
throws IOException {
Resource requestedResource = location.createRelative(resourcePath);
return requestedResource.exists() && requestedResource.isReadable() ? requestedResource :
new ClassPathResource("/public/index.html");
}
});
}
/**
* Define the security filter chain.
*
* @param http The http security
* @param authFailureEntryPoint The authentication failure entry point
* @param oauth2RequestRepository The auth request repository
* @param userService The user service
* @param openIdcUserService The oidc user service
* @param oauth2SuccessHandler The oauth2 authentication success handler
* @param oauth2FailureHandler The oauth2 authentication failure handler
* @return The security filter chain
* @throws Exception When an error occurred
*/
@Bean
public SecurityFilterChain filterChain(HttpSecurity http,
AuthenticationFailureEntryPoint authFailureEntryPoint,
HttpCookieOauth2AuthorizationRequestRepository oauth2RequestRepository, | /*
* Copyright 2012-2021 the original author or 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 com.michelin.suricate.configuration.web;
/**
* Web configuration.
*/
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class WebConfig implements WebMvcConfigurer {
@Autowired
private ApplicationProperties applicationProperties;
@Value("${spring.h2.console.enabled:false}")
private boolean h2Enabled;
/**
* The view resolver.
*
* @param registry Store the configurations
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/public/")
.resourceChain(true)
.addResolver(new PathResourceResolver() {
@Override
protected Resource getResource(@NotNull String resourcePath, @NotNull Resource location)
throws IOException {
Resource requestedResource = location.createRelative(resourcePath);
return requestedResource.exists() && requestedResource.isReadable() ? requestedResource :
new ClassPathResource("/public/index.html");
}
});
}
/**
* Define the security filter chain.
*
* @param http The http security
* @param authFailureEntryPoint The authentication failure entry point
* @param oauth2RequestRepository The auth request repository
* @param userService The user service
* @param openIdcUserService The oidc user service
* @param oauth2SuccessHandler The oauth2 authentication success handler
* @param oauth2FailureHandler The oauth2 authentication failure handler
* @return The security filter chain
* @throws Exception When an error occurred
*/
@Bean
public SecurityFilterChain filterChain(HttpSecurity http,
AuthenticationFailureEntryPoint authFailureEntryPoint,
HttpCookieOauth2AuthorizationRequestRepository oauth2RequestRepository, | Oauth2UserService userService, OpenIdcUserService openIdcUserService, | 8 | 2023-12-11 11:28:37+00:00 | 12k |
NaerQAQ/js4bukkit | src/main/java/org/js4bukkit/script/ScriptHandler.java | [
{
"identifier": "Js4Bukkit",
"path": "src/main/java/org/js4bukkit/Js4Bukkit.java",
"snippet": "public class Js4Bukkit extends JavaPlugin {\n /**\n * 实例。\n */\n @Getter\n @Setter\n private static Js4Bukkit instance;\n\n /**\n * 服务器版本。\n */\n @Getter\n @Setter\n pri... | import de.leonhard.storage.Yaml;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.js4bukkit.Js4Bukkit;
import org.js4bukkit.io.config.ConfigManager;
import org.js4bukkit.script.interop.command.CommandInterop;
import org.js4bukkit.script.interop.listener.EasyEventListenerInterop;
import org.js4bukkit.script.interop.listener.EventListenerInterop;
import org.js4bukkit.script.interop.placeholder.PlaceholderInterop;
import org.js4bukkit.script.objects.handler.CustomContextHandler;
import org.js4bukkit.script.objects.handler.ScriptExecutorHandler;
import org.js4bukkit.script.objects.objects.ScriptExecutor;
import org.js4bukkit.script.objects.objects.ScriptPlugin;
import org.js4bukkit.thread.Scheduler;
import org.js4bukkit.thread.enums.SchedulerExecutionMode;
import org.js4bukkit.thread.enums.SchedulerTypeEnum;
import org.js4bukkit.utils.common.text.QuickUtils;
import org.js4bukkit.utils.common.text.enums.ConsoleMessageTypeEnum;
import java.io.File;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.stream.Collectors; | 8,389 | package org.js4bukkit.script;
/**
* 脚本处理程序。
*
* @author NaerQAQ / 2000000
* @version 1.0
* @since 2023/10/12
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ScriptHandler {
/**
* 脚本所在文件夹。
*/
public static final String SCRIPT_PATH =
Js4Bukkit.getDataFolderAbsolutePath() + "/plugins/";
/**
* 获取上下文的函数名称。
*/
public static final String GET_CONTEXT_FUNCTION = "getContext";
/**
* 所有脚本插件对象。
*/
public static final Queue<ScriptPlugin> SCRIPT_PLUGINS =
new ConcurrentLinkedQueue<>();
/**
* 注册脚本插件对象。
*/
public static void registerScriptPlugins() {
Yaml plugins = ConfigManager.getPlugins();
SCRIPT_PLUGINS.addAll(
plugins.singleLayerKeySet()
.stream()
.map(folder -> new ScriptPlugin().init(plugins, folder))
.filter(Objects::nonNull)
.collect(Collectors.toList())
);
}
/**
* 获取所有脚本文件。
*
* @return 所有脚本文件
*/
public static Queue<File> getScriptFiles() {
return SCRIPT_PLUGINS.stream()
.flatMap(scriptPlugin -> scriptPlugin.getScriptFiles().stream())
.collect(Collectors.toCollection(ConcurrentLinkedQueue::new));
}
/**
* 注册所有脚本。
*/
@SneakyThrows
public static void registerScripts() {
registerScriptPlugins();
Queue<File> scriptFiles = getScriptFiles();
scriptFiles.forEach(scriptFile -> {
String scriptName = scriptFile.getName();
try {
ScriptExecutorHandler.addScriptExecutor( | package org.js4bukkit.script;
/**
* 脚本处理程序。
*
* @author NaerQAQ / 2000000
* @version 1.0
* @since 2023/10/12
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ScriptHandler {
/**
* 脚本所在文件夹。
*/
public static final String SCRIPT_PATH =
Js4Bukkit.getDataFolderAbsolutePath() + "/plugins/";
/**
* 获取上下文的函数名称。
*/
public static final String GET_CONTEXT_FUNCTION = "getContext";
/**
* 所有脚本插件对象。
*/
public static final Queue<ScriptPlugin> SCRIPT_PLUGINS =
new ConcurrentLinkedQueue<>();
/**
* 注册脚本插件对象。
*/
public static void registerScriptPlugins() {
Yaml plugins = ConfigManager.getPlugins();
SCRIPT_PLUGINS.addAll(
plugins.singleLayerKeySet()
.stream()
.map(folder -> new ScriptPlugin().init(plugins, folder))
.filter(Objects::nonNull)
.collect(Collectors.toList())
);
}
/**
* 获取所有脚本文件。
*
* @return 所有脚本文件
*/
public static Queue<File> getScriptFiles() {
return SCRIPT_PLUGINS.stream()
.flatMap(scriptPlugin -> scriptPlugin.getScriptFiles().stream())
.collect(Collectors.toCollection(ConcurrentLinkedQueue::new));
}
/**
* 注册所有脚本。
*/
@SneakyThrows
public static void registerScripts() {
registerScriptPlugins();
Queue<File> scriptFiles = getScriptFiles();
scriptFiles.forEach(scriptFile -> {
String scriptName = scriptFile.getName();
try {
ScriptExecutorHandler.addScriptExecutor( | new ScriptExecutor(scriptFile) | 8 | 2023-12-14 13:50:24+00:00 | 12k |
i-moonlight/Beluga | server/src/main/java/com/amnesica/belugaproject/services/aircraft/OpenskyService.java | [
{
"identifier": "Configuration",
"path": "server/src/main/java/com/amnesica/belugaproject/config/Configuration.java",
"snippet": "@Data\n@Slf4j\n@Validated\n@ConstructorBinding\n@org.springframework.context.annotation.Configuration\npublic class Configuration {\n\n @Autowired\n private Environment... | import com.amnesica.belugaproject.config.Configuration;
import com.amnesica.belugaproject.config.Feeder;
import com.amnesica.belugaproject.config.FeederMapping;
import com.amnesica.belugaproject.config.StaticValues;
import com.amnesica.belugaproject.entities.aircraft.OpenskyAircraft;
import com.amnesica.belugaproject.entities.data.AirportData;
import com.amnesica.belugaproject.repositories.aircraft.OpenskyAircraftRepository;
import com.amnesica.belugaproject.services.data.AircraftDataService;
import com.amnesica.belugaproject.services.data.AirportDataService;
import com.amnesica.belugaproject.services.helper.HelperService;
import com.amnesica.belugaproject.services.helper.NetworkHandlerService;
import com.amnesica.belugaproject.services.helper.Request;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; | 10,488 | for (int i = 0; i < jsonArray.length(); i++) {
JSONArray innerArray = jsonArray.getJSONArray(i);
if (innerArray != null) {
JSONObject innerObject = new JSONObject();
innerObject.put("hex", innerArray.get(0));
innerObject.put("flightId", innerArray.get(1));
innerObject.put("onGround", innerArray.get(8));
innerObject.put("squawk", innerArray.get(14));
innerObject.put("source", innerArray.get(16));
if (innerArray.get(5) instanceof BigDecimal) {
innerObject.put("lon", innerArray.getDouble(5));
} else {
innerObject.put("lon", innerArray.get(5));
}
if (innerArray.get(6) instanceof BigDecimal) {
innerObject.put("lat", innerArray.getDouble(6));
} else {
innerObject.put("lat", innerArray.get(6));
}
if (innerArray.get(10) instanceof BigDecimal) {
innerObject.put("track", innerArray.getDouble(10));
} else {
innerObject.put("track", innerArray.get(10));
}
// OpenSky liefert metrische Werte, deshalb Konvertierung in nautical erforderlich
if (innerArray.get(7) instanceof Integer) {
conversionValueDouble = HelperService.convertMeter2Foot(((int) innerArray.get(7)));
innerObject.put("elipsoidalAltitude", conversionValueDouble);
} else if (innerArray.get(7) instanceof Double || innerArray.get(7) instanceof BigDecimal) {
conversionValueDouble = HelperService.convertMeter2Foot(innerArray.getDouble(7));
innerObject.put("elipsoidalAltitude", conversionValueDouble);
} else {
innerObject.put("elipsoidalAltitude", innerArray.get(7));
}
if (innerArray.get(13) instanceof Integer) {
conversionValueDouble = HelperService.convertMeter2Foot(((int) innerArray.get(13)));
innerObject.put("altitude", conversionValueDouble);
} else if (innerArray.get(13) instanceof Double || innerArray.get(13) instanceof BigDecimal) {
conversionValueDouble = HelperService.convertMeter2Foot(innerArray.getDouble(13));
innerObject.put("altitude", conversionValueDouble);
} else {
innerObject.put("altitude", innerArray.get(13));
}
if (innerArray.get(9) instanceof Integer) {
conversionValueDouble = HelperService.convertMeterPerSec2KilometersPerHour(((int) innerArray.get(9)));
conversionValueDouble = HelperService.convertKilometer2Nmile(conversionValueDouble);
innerObject.put("speed", conversionValueDouble);
} else if (innerArray.get(9) instanceof Double || innerArray.get(9) instanceof BigDecimal) {
conversionValueDouble = HelperService.convertMeterPerSec2KilometersPerHour(innerArray.getDouble(9));
conversionValueDouble = HelperService.convertKilometer2Nmile(conversionValueDouble);
innerObject.put("speed", conversionValueDouble);
} else {
innerObject.put("speed", innerArray.get(9));
}
if (innerArray.get(11) instanceof Integer) {
conversionValueDouble = HelperService.convertMeterPerSec2FootPerMin(((int) innerArray.get(11)));
innerObject.put("verticalRate", conversionValueDouble);
} else if (innerArray.get(11) instanceof Double || innerArray.get(11) instanceof BigDecimal) {
conversionValueDouble = HelperService.convertMeterPerSec2FootPerMin(innerArray.getDouble(11));
innerObject.put("verticalRate", conversionValueDouble);
} else {
innerObject.put("verticalRate", innerArray.get(11));
}
// Füge innerObject zu arrayWithObjects hinzu
arrayWithObjects.put(innerObject);
}
}
return arrayWithObjects;
}
/**
* Erstellt einen Feeder für das Opensky-Network
*
* @return Feeder
*/
public Feeder createOpenskyFeeder() {
// Erstelle Feeder Opensky
Feeder feeder = new Feeder("Opensky", null, "Opensky", "yellow");
// Erstelle Mapping
FeederMapping mapping = new FeederMapping();
mapping.setHex("hex");
mapping.setLatitude("latitude");
mapping.setLongitude("longitude");
mapping.setAltitude("altitude");
mapping.setTrack("track");
mapping.setOnGround("onGround");
mapping.setSpeed("speed");
mapping.setSquawk("squawk");
mapping.setFlightId("flightId");
mapping.setVerticalRate("verticalRate");
mapping.setAutopilotEngaged("autopilotEngaged");
mapping.setElipsoidalAltitude("elipsoidalAltitude");
mapping.setFeeder("feeder");
mapping.setSource("source");
// Setze Mapping
feeder.setMapping(mapping);
return feeder;
}
/**
* Methode ruft Flugzeuge innerhalb des Extents in arrayOpenskyExtent vom
* Opensky-Network ab und speichert Flugzeuge in der Tabelle opensky_aircraft.
* Methode wird alle INTERVAL_UPDATE_OPENSKY Sekunden abgerufen. Abruf wird
* jedoch nur durchgeführt, wenn das arrayOpenskyExtent-Array mit Werten gefüllt
* ist (dieses wird nur bei einer Anfrage vom Frontend gefüllt). Hinweis: Das
* Abruf-Intervall ist auf 10 Sekunden gesetzt, da für nicht-registrierte Nutzer
* nur alle 10 Sekunden die Daten von Opensky aktualisiert werden können
*/ | package com.amnesica.belugaproject.services.aircraft;
@Slf4j
@EnableScheduling
@Service
public class OpenskyService {
@Autowired
private AircraftService aircraftService;
@Autowired
private NetworkHandlerService networkHandler;
@Autowired
private AircraftDataService aircraftDataService;
@Autowired
private AirportDataService airportDataService;
@Autowired
private OpenskyAircraftRepository openskyAircraftRepository;
@Autowired
private Configuration configuration;
// Feeder für das Opensky-Network
private Feeder openskyFeeder;
// Queue mit Anfragen an Opensky
private final BlockingQueue<Request> requestQueueOpensky = new LinkedBlockingQueue<>();
// Url zum Fetchen der Daten von Opensky
private static final String URL_OPENSKY_LIVE_API = "https://opensky-network.org/api/states/all?";
/**
* Ruft die Rohdaten als JSONArray vom Opensky-Network ab
*
* @param lomin lower bound for the longitude in decimal degrees
* @param lamin lower bound for the latitude in decimal degrees
* @param lomax upper bound for the longitude in decimal degrees
* @param lamax upper bound for the latitude in decimal degrees
* @return JSONArray
*/
public JSONArray getDataFromOpensky(double lomin, double lamin, double lomax, double lamax) {
// Array mit konvertierten Daten von Opensky
JSONArray jsonArray = null;
// Genriere URL mit Daten der Bounding-Box vom Frontend
final String url = URL_OPENSKY_LIVE_API + "lamin=" + lamin + "&lomin=" + lomin + "&lamax=" + lamax + "&lomax="
+ lomax;
// Anfrage an Opensky mit url und Credentials
String jsonStr = networkHandler.makeOpenskyServiceCall(url, configuration.getOpenskyUsername(), configuration.getOpenskyPassword());
try {
if (jsonStr != null) {
JSONObject jsonObject = new JSONObject(jsonStr);
// Hinweis: jsonArray ist ein Array aus Arrays
// und muss daher für weitere Bearbeitung konvertiert werden
JSONArray jsonArrayStates = jsonObject.getJSONArray("states");
if (jsonArrayStates != null) {
jsonArray = convertJsonArrayToArrayOfObjects(jsonArrayStates);
} else {
throw new Exception();
}
}
} catch (Exception e) {
log.error(
"Server: Data from Opensky-Network could not get fetched or there are no planes in this area. Url: "
+ url);
}
return jsonArray;
}
/**
* Konvertiert ein JSONArray aus Arrays in ein JSONArray aus JSONObjects
*
* @param jsonArray JSONArray
* @return JSONArray
*/
private JSONArray convertJsonArrayToArrayOfObjects(JSONArray jsonArray) {
JSONArray arrayWithObjects = new JSONArray();
Double conversionValueDouble;
if (jsonArray == null) {
return null;
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray innerArray = jsonArray.getJSONArray(i);
if (innerArray != null) {
JSONObject innerObject = new JSONObject();
innerObject.put("hex", innerArray.get(0));
innerObject.put("flightId", innerArray.get(1));
innerObject.put("onGround", innerArray.get(8));
innerObject.put("squawk", innerArray.get(14));
innerObject.put("source", innerArray.get(16));
if (innerArray.get(5) instanceof BigDecimal) {
innerObject.put("lon", innerArray.getDouble(5));
} else {
innerObject.put("lon", innerArray.get(5));
}
if (innerArray.get(6) instanceof BigDecimal) {
innerObject.put("lat", innerArray.getDouble(6));
} else {
innerObject.put("lat", innerArray.get(6));
}
if (innerArray.get(10) instanceof BigDecimal) {
innerObject.put("track", innerArray.getDouble(10));
} else {
innerObject.put("track", innerArray.get(10));
}
// OpenSky liefert metrische Werte, deshalb Konvertierung in nautical erforderlich
if (innerArray.get(7) instanceof Integer) {
conversionValueDouble = HelperService.convertMeter2Foot(((int) innerArray.get(7)));
innerObject.put("elipsoidalAltitude", conversionValueDouble);
} else if (innerArray.get(7) instanceof Double || innerArray.get(7) instanceof BigDecimal) {
conversionValueDouble = HelperService.convertMeter2Foot(innerArray.getDouble(7));
innerObject.put("elipsoidalAltitude", conversionValueDouble);
} else {
innerObject.put("elipsoidalAltitude", innerArray.get(7));
}
if (innerArray.get(13) instanceof Integer) {
conversionValueDouble = HelperService.convertMeter2Foot(((int) innerArray.get(13)));
innerObject.put("altitude", conversionValueDouble);
} else if (innerArray.get(13) instanceof Double || innerArray.get(13) instanceof BigDecimal) {
conversionValueDouble = HelperService.convertMeter2Foot(innerArray.getDouble(13));
innerObject.put("altitude", conversionValueDouble);
} else {
innerObject.put("altitude", innerArray.get(13));
}
if (innerArray.get(9) instanceof Integer) {
conversionValueDouble = HelperService.convertMeterPerSec2KilometersPerHour(((int) innerArray.get(9)));
conversionValueDouble = HelperService.convertKilometer2Nmile(conversionValueDouble);
innerObject.put("speed", conversionValueDouble);
} else if (innerArray.get(9) instanceof Double || innerArray.get(9) instanceof BigDecimal) {
conversionValueDouble = HelperService.convertMeterPerSec2KilometersPerHour(innerArray.getDouble(9));
conversionValueDouble = HelperService.convertKilometer2Nmile(conversionValueDouble);
innerObject.put("speed", conversionValueDouble);
} else {
innerObject.put("speed", innerArray.get(9));
}
if (innerArray.get(11) instanceof Integer) {
conversionValueDouble = HelperService.convertMeterPerSec2FootPerMin(((int) innerArray.get(11)));
innerObject.put("verticalRate", conversionValueDouble);
} else if (innerArray.get(11) instanceof Double || innerArray.get(11) instanceof BigDecimal) {
conversionValueDouble = HelperService.convertMeterPerSec2FootPerMin(innerArray.getDouble(11));
innerObject.put("verticalRate", conversionValueDouble);
} else {
innerObject.put("verticalRate", innerArray.get(11));
}
// Füge innerObject zu arrayWithObjects hinzu
arrayWithObjects.put(innerObject);
}
}
return arrayWithObjects;
}
/**
* Erstellt einen Feeder für das Opensky-Network
*
* @return Feeder
*/
public Feeder createOpenskyFeeder() {
// Erstelle Feeder Opensky
Feeder feeder = new Feeder("Opensky", null, "Opensky", "yellow");
// Erstelle Mapping
FeederMapping mapping = new FeederMapping();
mapping.setHex("hex");
mapping.setLatitude("latitude");
mapping.setLongitude("longitude");
mapping.setAltitude("altitude");
mapping.setTrack("track");
mapping.setOnGround("onGround");
mapping.setSpeed("speed");
mapping.setSquawk("squawk");
mapping.setFlightId("flightId");
mapping.setVerticalRate("verticalRate");
mapping.setAutopilotEngaged("autopilotEngaged");
mapping.setElipsoidalAltitude("elipsoidalAltitude");
mapping.setFeeder("feeder");
mapping.setSource("source");
// Setze Mapping
feeder.setMapping(mapping);
return feeder;
}
/**
* Methode ruft Flugzeuge innerhalb des Extents in arrayOpenskyExtent vom
* Opensky-Network ab und speichert Flugzeuge in der Tabelle opensky_aircraft.
* Methode wird alle INTERVAL_UPDATE_OPENSKY Sekunden abgerufen. Abruf wird
* jedoch nur durchgeführt, wenn das arrayOpenskyExtent-Array mit Werten gefüllt
* ist (dieses wird nur bei einer Anfrage vom Frontend gefüllt). Hinweis: Das
* Abruf-Intervall ist auf 10 Sekunden gesetzt, da für nicht-registrierte Nutzer
* nur alle 10 Sekunden die Daten von Opensky aktualisiert werden können
*/ | @Scheduled(fixedRate = StaticValues.INTERVAL_UPDATE_OPENSKY) | 3 | 2023-12-11 11:37:46+00:00 | 12k |
fiber-net-gateway/fiber-net-gateway | fiber-gateway-example/src/main/java/io/fiber/net/example/Main.java | [
{
"identifier": "Engine",
"path": "fiber-gateway-common/src/main/java/io/fiber/net/common/Engine.java",
"snippet": "public class Engine implements Destroyable {\n private static final Logger log = LoggerFactory.getLogger(Engine.class);\n\n\n private static class InterceptorNode implements Intercep... | import io.fiber.net.common.Engine;
import io.fiber.net.common.ioc.Binder;
import io.fiber.net.common.utils.ArrayUtils;
import io.fiber.net.common.utils.StringUtils;
import io.fiber.net.dubbo.nacos.DubboModule;
import io.fiber.net.proxy.ConfigWatcher;
import io.fiber.net.proxy.LibProxyMainModule;
import io.fiber.net.server.HttpServer;
import io.fiber.net.server.ServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; | 7,580 | package io.fiber.net.example;
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) throws Exception {
if (ArrayUtils.isEmpty(args) || StringUtils.isEmpty(args[0])) {
throw new IllegalArgumentException("onInit path is required");
}
File file = new File(args[0]);
if (!file.exists() || !file.isDirectory()) {
throw new IllegalArgumentException("onInit path must be directory");
}
Engine engine = LibProxyMainModule.createEngine(
new DubboModule(),
binder -> install(binder, file));
try {
HttpServer server = engine.getInjector().getInstance(HttpServer.class);
server.start(new ServerConfig(), engine);
} catch (Throwable e) {
log.error("error start http server", e);
engine.getInjector().destroy();
throw e;
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
engine.getInjector().destroy();
}));
}
| package io.fiber.net.example;
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) throws Exception {
if (ArrayUtils.isEmpty(args) || StringUtils.isEmpty(args[0])) {
throw new IllegalArgumentException("onInit path is required");
}
File file = new File(args[0]);
if (!file.exists() || !file.isDirectory()) {
throw new IllegalArgumentException("onInit path must be directory");
}
Engine engine = LibProxyMainModule.createEngine(
new DubboModule(),
binder -> install(binder, file));
try {
HttpServer server = engine.getInjector().getInstance(HttpServer.class);
server.start(new ServerConfig(), engine);
} catch (Throwable e) {
log.error("error start http server", e);
engine.getInjector().destroy();
throw e;
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
engine.getInjector().destroy();
}));
}
| private static void install(Binder binder, File file) { | 1 | 2023-12-08 15:18:05+00:00 | 12k |
sigbla/sigbla-pds | src/main/java/sigbla/app/pds/collection/internal/base/AbstractTraversable.java | [
{
"identifier": "Builder",
"path": "src/main/java/sigbla/app/pds/collection/Builder.java",
"snippet": "public interface Builder<E, R> {\n @NotNull\n Builder<E, R> add(E element);\n\n @NotNull\n Builder<E, R> addAll(@NotNull Traversable<E> elements);\n\n @NotNull\n Builder<E, R> addAll(... | import sigbla.app.pds.collection.Vector;
import org.jetbrains.annotations.NotNull;
import java.util.Comparator;
import sigbla.app.pds.collection.Builder;
import sigbla.app.pds.collection.Function;
import sigbla.app.pds.collection.HashSet;
import sigbla.app.pds.collection.IndexedList;
import sigbla.app.pds.collection.Set;
import sigbla.app.pds.collection.SortedSet;
import sigbla.app.pds.collection.Traversable;
import sigbla.app.pds.collection.TreeSet; | 9,325 | /*
* Copyright (c) 2014 Andrew O'Malley
*
* 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 sigbla.app.pds.collection.internal.base;
public abstract class AbstractTraversable<E> implements Traversable<E> {
@Override
public int size() {
final int[] result = {0};
forEach(new Function<E, Object>() {
@Override
public Object invoke(E parameter) {
return result[0]++;
}
});
return result[0];
}
@NotNull
public String makeString(@NotNull String separator) {
return makeString(separator, "", "", -1, "");
}
@NotNull
public String makeString(@NotNull final String separator, @NotNull String prefix, @NotNull String postfix, final int limit, @NotNull String truncated) {
final StringBuilder buffer = new StringBuilder(prefix);
final int[] count = {0};
try {
forEach(new Function<E, Object>() {
@Override
public Object invoke(E element) {
int current = count[0] + 1;
count[0] = current;
if (current > 1) buffer.append(separator);
if (limit < 0 || current <= limit) {
buffer.append(element == null ? "null" : element.toString());
} else throw Break.instance;
return null;
}
});
} catch (Break e) {
// Fall through
}
if (limit >= 0 && count[0] > limit) buffer.append(truncated);
buffer.append(postfix);
return buffer.toString();
}
@Override
public String toString() {
return makeString(", ", getClass().getSimpleName() + "(", ")", 100, "...");
}
@NotNull
@Override
public <R extends Traversable<E>> R to(@NotNull Builder<E, R> builder) {
return builder.addAll(this).build();
}
@NotNull
@Override
public Set<E> toSet() { | /*
* Copyright (c) 2014 Andrew O'Malley
*
* 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 sigbla.app.pds.collection.internal.base;
public abstract class AbstractTraversable<E> implements Traversable<E> {
@Override
public int size() {
final int[] result = {0};
forEach(new Function<E, Object>() {
@Override
public Object invoke(E parameter) {
return result[0]++;
}
});
return result[0];
}
@NotNull
public String makeString(@NotNull String separator) {
return makeString(separator, "", "", -1, "");
}
@NotNull
public String makeString(@NotNull final String separator, @NotNull String prefix, @NotNull String postfix, final int limit, @NotNull String truncated) {
final StringBuilder buffer = new StringBuilder(prefix);
final int[] count = {0};
try {
forEach(new Function<E, Object>() {
@Override
public Object invoke(E element) {
int current = count[0] + 1;
count[0] = current;
if (current > 1) buffer.append(separator);
if (limit < 0 || current <= limit) {
buffer.append(element == null ? "null" : element.toString());
} else throw Break.instance;
return null;
}
});
} catch (Break e) {
// Fall through
}
if (limit >= 0 && count[0] > limit) buffer.append(truncated);
buffer.append(postfix);
return buffer.toString();
}
@Override
public String toString() {
return makeString(", ", getClass().getSimpleName() + "(", ")", 100, "...");
}
@NotNull
@Override
public <R extends Traversable<E>> R to(@NotNull Builder<E, R> builder) {
return builder.addAll(this).build();
}
@NotNull
@Override
public Set<E> toSet() { | return to(HashSet.<E>factory().newBuilder()); | 2 | 2023-12-10 15:10:13+00:00 | 12k |
netty/netty-incubator-codec-ohttp | codec-ohttp/src/test/java/io/netty/incubator/codec/ohttp/OHttpCryptoTest.java | [
{
"identifier": "AsymmetricCipherKeyPair",
"path": "codec-ohttp-hpke/src/main/java/io/netty/incubator/codec/hpke/AsymmetricCipherKeyPair.java",
"snippet": "public interface AsymmetricCipherKeyPair {\n\n /**\n * Returns the public key parameters.\n *\n * @return the public key parameters.\... | import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.incubator.codec.hpke.AsymmetricCipherKeyPair;
import io.netty.incubator.codec.hpke.AsymmetricKeyParameter;
import io.netty.incubator.codec.hpke.OHttpCryptoProvider;
import io.netty.incubator.codec.hpke.boringssl.BoringSSLHPKE;
import io.netty.incubator.codec.hpke.boringssl.BoringSSLOHttpCryptoProvider;
import io.netty.incubator.codec.hpke.bouncycastle.BouncyCastleOHttpCryptoProvider;
import io.netty.incubator.codec.hpke.CryptoException;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.DecoderException;
import org.bouncycastle.crypto.params.X25519PrivateKeyParameters;
import org.bouncycastle.crypto.params.X25519PublicKeyParameters;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
import org.junit.jupiter.params.provider.ArgumentsSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import io.netty.incubator.codec.hpke.AEAD;
import io.netty.incubator.codec.hpke.KDF;
import io.netty.incubator.codec.hpke.KEM;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; | 8,940 | /*
* Copyright 2023 The Netty Project
*
* The Netty Project 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:
*
* https://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.netty.incubator.codec.ohttp;
public class OHttpCryptoTest {
private static final class OHttpCryptoProviderArgumentsProvider implements ArgumentsProvider {
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
List<Arguments> arguments = new ArrayList<>();
arguments.add(Arguments.of(BouncyCastleOHttpCryptoProvider.INSTANCE,
BouncyCastleOHttpCryptoProvider.INSTANCE));
if (BoringSSLHPKE.isAvailable()) {
arguments.add(Arguments.of(BoringSSLOHttpCryptoProvider.INSTANCE,
BoringSSLOHttpCryptoProvider.INSTANCE));
arguments.add(Arguments.of(BouncyCastleOHttpCryptoProvider.INSTANCE,
BoringSSLOHttpCryptoProvider.INSTANCE));
arguments.add(Arguments.of(BoringSSLOHttpCryptoProvider.INSTANCE,
BouncyCastleOHttpCryptoProvider.INSTANCE));
}
return arguments.stream();
}
}
static AsymmetricCipherKeyPair createX25519KeyPair(OHttpCryptoProvider cryptoProvider, String privateKeyHexBytes) {
X25519PrivateKeyParameters privateKey = new X25519PrivateKeyParameters(
ByteBufUtil.decodeHexDump(privateKeyHexBytes));
X25519PublicKeyParameters publicKey = privateKey.generatePublicKey();
return cryptoProvider.deserializePrivateKey(
KEM.X25519_SHA256, privateKey.getEncoded(), publicKey.getEncoded());
}
/*
* Use values from
* https://ietf-wg-ohai.github.io/oblivious-http/draft-ietf-ohai-ohttp.html#name-complete-example-of-a-reque
*/
@ParameterizedTest
@ArgumentsSource(value = OHttpCryptoProviderArgumentsProvider.class)
public void testCryptoVectors(OHttpCryptoProvider senderProvider, OHttpCryptoProvider receiverProvider)
throws DecoderException, CryptoException {
byte keyId = 1;
AsymmetricCipherKeyPair kpR = createX25519KeyPair(
receiverProvider, "3c168975674b2fa8e465970b79c8dcf09f1c741626480bd4c6162fc5b6a98e1a");
AsymmetricCipherKeyPair kpE = createX25519KeyPair(
senderProvider, "bc51d5e930bda26589890ac7032f70ad12e4ecb37abb1b65b1256c9c48999c73");
byte[] request = ByteBufUtil.decodeHexDump("00034745540568747470730b6578616d706c652e636f6d012f");
byte[] response = ByteBufUtil.decodeHexDump("0140c8");
OHttpServerKeys serverKeys = new OHttpServerKeys(
OHttpKey.newPrivateKey(
keyId,
KEM.X25519_SHA256,
Arrays.asList( | /*
* Copyright 2023 The Netty Project
*
* The Netty Project 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:
*
* https://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.netty.incubator.codec.ohttp;
public class OHttpCryptoTest {
private static final class OHttpCryptoProviderArgumentsProvider implements ArgumentsProvider {
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
List<Arguments> arguments = new ArrayList<>();
arguments.add(Arguments.of(BouncyCastleOHttpCryptoProvider.INSTANCE,
BouncyCastleOHttpCryptoProvider.INSTANCE));
if (BoringSSLHPKE.isAvailable()) {
arguments.add(Arguments.of(BoringSSLOHttpCryptoProvider.INSTANCE,
BoringSSLOHttpCryptoProvider.INSTANCE));
arguments.add(Arguments.of(BouncyCastleOHttpCryptoProvider.INSTANCE,
BoringSSLOHttpCryptoProvider.INSTANCE));
arguments.add(Arguments.of(BoringSSLOHttpCryptoProvider.INSTANCE,
BouncyCastleOHttpCryptoProvider.INSTANCE));
}
return arguments.stream();
}
}
static AsymmetricCipherKeyPair createX25519KeyPair(OHttpCryptoProvider cryptoProvider, String privateKeyHexBytes) {
X25519PrivateKeyParameters privateKey = new X25519PrivateKeyParameters(
ByteBufUtil.decodeHexDump(privateKeyHexBytes));
X25519PublicKeyParameters publicKey = privateKey.generatePublicKey();
return cryptoProvider.deserializePrivateKey(
KEM.X25519_SHA256, privateKey.getEncoded(), publicKey.getEncoded());
}
/*
* Use values from
* https://ietf-wg-ohai.github.io/oblivious-http/draft-ietf-ohai-ohttp.html#name-complete-example-of-a-reque
*/
@ParameterizedTest
@ArgumentsSource(value = OHttpCryptoProviderArgumentsProvider.class)
public void testCryptoVectors(OHttpCryptoProvider senderProvider, OHttpCryptoProvider receiverProvider)
throws DecoderException, CryptoException {
byte keyId = 1;
AsymmetricCipherKeyPair kpR = createX25519KeyPair(
receiverProvider, "3c168975674b2fa8e465970b79c8dcf09f1c741626480bd4c6162fc5b6a98e1a");
AsymmetricCipherKeyPair kpE = createX25519KeyPair(
senderProvider, "bc51d5e930bda26589890ac7032f70ad12e4ecb37abb1b65b1256c9c48999c73");
byte[] request = ByteBufUtil.decodeHexDump("00034745540568747470730b6578616d706c652e636f6d012f");
byte[] response = ByteBufUtil.decodeHexDump("0140c8");
OHttpServerKeys serverKeys = new OHttpServerKeys(
OHttpKey.newPrivateKey(
keyId,
KEM.X25519_SHA256,
Arrays.asList( | OHttpKey.newCipher(KDF.HKDF_SHA256, AEAD.AES_GCM128), | 8 | 2023-12-06 09:14:09+00:00 | 12k |
lyswhut/react-native-local-media-metadata | android/src/main/java/org/jaudiotagger/audio/mp4/atom/Mp4BoxHeader.java | [
{
"identifier": "StandardCharsets",
"path": "android/src/main/java/org/jaudiotagger/StandardCharsets.java",
"snippet": "public final class StandardCharsets {\n\n private StandardCharsets() {\n throw new AssertionError(\"No org.jaudiotagger.StandardCharsets instances for you!\");\n }\n /*... | import java.util.logging.Logger;
import org.jaudiotagger.StandardCharsets;
import org.jaudiotagger.audio.exceptions.InvalidBoxHeaderException;
import org.jaudiotagger.audio.exceptions.NullBoxIdException;
import org.jaudiotagger.audio.generic.Utils;
import org.jaudiotagger.logging.ErrorMessage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset; | 9,034 | /*
* Entagged Audio Tag library
* Copyright (c) 2003-2005 Raphaël Slinckx <raphael@slinckx.net>
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jaudiotagger.audio.mp4.atom;
/**
* Everything in MP4s are held in boxes (formally known as atoms), they are held as a hierachial tree within the MP4.
*
* We are most interested in boxes that are used to hold metadata, but we have to know about some other boxes
* as well in order to find them.
*
* All boxes consist of a 4 byte box length (big Endian), and then a 4 byte identifier, this is the header
* which is model in this class.
*
* The length includes the length of the box including the identifier and the length itself.
* Then they may contain data and/or sub boxes, if they contain subboxes they are known as a parent box. Parent boxes
* shouldn't really contain data, but sometimes they do.
*
* Parent boxes length includes the length of their immediate sub boxes
*
* This class is normally used by instantiating with the empty constructor, then use the update method
* to pass the header data which is used to read the identifier and the the size of the box
*/
public class Mp4BoxHeader
{
// Logger Object
public static Logger logger = Logger.getLogger("org.jaudiotagger.audio.mp4.atom");
public static final int OFFSET_POS = 0;
public static final int IDENTIFIER_POS = 4;
public static final int OFFSET_LENGTH = 4;
public static final int IDENTIFIER_LENGTH = 4;
public static final int HEADER_LENGTH = OFFSET_LENGTH + IDENTIFIER_LENGTH;
//Box identifier
private String id;
//Box length
protected int length;
//If reading from file , this can be used to hold the headers position in the file
private long filePos;
//Raw Header data
protected ByteBuffer dataBuffer;
//Mp4 uses UTF-8 for all text
public static final String CHARSET_UTF_8 = "UTF-8";
/**
* Construct empty header
*
* Can be populated later with update method
*/
public Mp4BoxHeader()
{
}
/**
* Construct header to allow manual creation of header for writing to file
*
* @param id
*/
public Mp4BoxHeader(String id)
{
if(id.length()!=IDENTIFIER_LENGTH)
{
throw new RuntimeException("Invalid length:atom idenifier should always be 4 characters long");
}
dataBuffer = ByteBuffer.allocate(HEADER_LENGTH);
try
{
this.id = id;
dataBuffer.put(4, id.getBytes("ISO-8859-1")[0]);
dataBuffer.put(5, id.getBytes("ISO-8859-1")[1]);
dataBuffer.put(6, id.getBytes("ISO-8859-1")[2]);
dataBuffer.put(7, id.getBytes("ISO-8859-1")[3]);
}
catch(UnsupportedEncodingException uee)
{
//Should never happen
throw new RuntimeException(uee);
}
}
/**
* Construct header
*
* Create header using headerdata, expected to find header at headerdata current position
*
* Note after processing adjusts position to immediately after header
*
* @param headerData
*/
public Mp4BoxHeader(ByteBuffer headerData)
{
update(headerData);
}
/**
* Create header using headerdata, expected to find header at headerdata current position
*
* Note after processing adjusts position to immediately after header
*
* @param headerData
*/
public void update(ByteBuffer headerData)
{
//Read header data into byte array
byte[] b = new byte[HEADER_LENGTH];
headerData.get(b);
//Keep reference to copy of RawData
dataBuffer = ByteBuffer.wrap(b);
dataBuffer.order(ByteOrder.BIG_ENDIAN);
//Calculate box size and id
this.length = dataBuffer.getInt();
this.id = Utils.readFourBytesAsChars(dataBuffer);
logger.finest("Mp4BoxHeader id:"+id+":length:"+length);
if (id.equals("\0\0\0\0"))
{
throw new NullBoxIdException(ErrorMessage.MP4_UNABLE_TO_FIND_NEXT_ATOM_BECAUSE_IDENTIFIER_IS_INVALID.getMsg(id));
}
if(length<HEADER_LENGTH)
{ | /*
* Entagged Audio Tag library
* Copyright (c) 2003-2005 Raphaël Slinckx <raphael@slinckx.net>
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.jaudiotagger.audio.mp4.atom;
/**
* Everything in MP4s are held in boxes (formally known as atoms), they are held as a hierachial tree within the MP4.
*
* We are most interested in boxes that are used to hold metadata, but we have to know about some other boxes
* as well in order to find them.
*
* All boxes consist of a 4 byte box length (big Endian), and then a 4 byte identifier, this is the header
* which is model in this class.
*
* The length includes the length of the box including the identifier and the length itself.
* Then they may contain data and/or sub boxes, if they contain subboxes they are known as a parent box. Parent boxes
* shouldn't really contain data, but sometimes they do.
*
* Parent boxes length includes the length of their immediate sub boxes
*
* This class is normally used by instantiating with the empty constructor, then use the update method
* to pass the header data which is used to read the identifier and the the size of the box
*/
public class Mp4BoxHeader
{
// Logger Object
public static Logger logger = Logger.getLogger("org.jaudiotagger.audio.mp4.atom");
public static final int OFFSET_POS = 0;
public static final int IDENTIFIER_POS = 4;
public static final int OFFSET_LENGTH = 4;
public static final int IDENTIFIER_LENGTH = 4;
public static final int HEADER_LENGTH = OFFSET_LENGTH + IDENTIFIER_LENGTH;
//Box identifier
private String id;
//Box length
protected int length;
//If reading from file , this can be used to hold the headers position in the file
private long filePos;
//Raw Header data
protected ByteBuffer dataBuffer;
//Mp4 uses UTF-8 for all text
public static final String CHARSET_UTF_8 = "UTF-8";
/**
* Construct empty header
*
* Can be populated later with update method
*/
public Mp4BoxHeader()
{
}
/**
* Construct header to allow manual creation of header for writing to file
*
* @param id
*/
public Mp4BoxHeader(String id)
{
if(id.length()!=IDENTIFIER_LENGTH)
{
throw new RuntimeException("Invalid length:atom idenifier should always be 4 characters long");
}
dataBuffer = ByteBuffer.allocate(HEADER_LENGTH);
try
{
this.id = id;
dataBuffer.put(4, id.getBytes("ISO-8859-1")[0]);
dataBuffer.put(5, id.getBytes("ISO-8859-1")[1]);
dataBuffer.put(6, id.getBytes("ISO-8859-1")[2]);
dataBuffer.put(7, id.getBytes("ISO-8859-1")[3]);
}
catch(UnsupportedEncodingException uee)
{
//Should never happen
throw new RuntimeException(uee);
}
}
/**
* Construct header
*
* Create header using headerdata, expected to find header at headerdata current position
*
* Note after processing adjusts position to immediately after header
*
* @param headerData
*/
public Mp4BoxHeader(ByteBuffer headerData)
{
update(headerData);
}
/**
* Create header using headerdata, expected to find header at headerdata current position
*
* Note after processing adjusts position to immediately after header
*
* @param headerData
*/
public void update(ByteBuffer headerData)
{
//Read header data into byte array
byte[] b = new byte[HEADER_LENGTH];
headerData.get(b);
//Keep reference to copy of RawData
dataBuffer = ByteBuffer.wrap(b);
dataBuffer.order(ByteOrder.BIG_ENDIAN);
//Calculate box size and id
this.length = dataBuffer.getInt();
this.id = Utils.readFourBytesAsChars(dataBuffer);
logger.finest("Mp4BoxHeader id:"+id+":length:"+length);
if (id.equals("\0\0\0\0"))
{
throw new NullBoxIdException(ErrorMessage.MP4_UNABLE_TO_FIND_NEXT_ATOM_BECAUSE_IDENTIFIER_IS_INVALID.getMsg(id));
}
if(length<HEADER_LENGTH)
{ | throw new InvalidBoxHeaderException(ErrorMessage.MP4_UNABLE_TO_FIND_NEXT_ATOM_BECAUSE_IDENTIFIER_IS_INVALID.getMsg(id,length)); | 1 | 2023-12-11 05:58:19+00:00 | 12k |
Ender-Cube/Endercube | Parkour/src/main/java/net/endercube/Parkour/ParkourMinigame.java | [
{
"identifier": "EndercubeMinigame",
"path": "Common/src/main/java/net/endercube/Common/EndercubeMinigame.java",
"snippet": "public abstract class EndercubeMinigame {\n\n public static final Logger logger;\n private HoconConfigurationLoader configLoader;\n public CommentedConfigurationNode conf... | import net.endercube.Common.EndercubeMinigame;
import net.endercube.Common.EndercubeServer;
import net.endercube.Common.dimensions.FullbrightDimension;
import net.endercube.Common.players.EndercubePlayer;
import net.endercube.Parkour.commands.LeaderboardCommand;
import net.endercube.Parkour.database.ParkourDatabase;
import net.endercube.Parkour.listeners.InventoryPreClick;
import net.endercube.Parkour.listeners.MinigamePlayerJoin;
import net.endercube.Parkour.listeners.MinigamePlayerLeave;
import net.endercube.Parkour.listeners.PlayerMove;
import net.endercube.Parkour.listeners.PlayerUseItem;
import net.hollowcube.polar.PolarLoader;
import net.minestom.server.MinecraftServer;
import net.minestom.server.command.builder.Command;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.event.player.PlayerSwapItemEvent;
import net.minestom.server.instance.Instance;
import net.minestom.server.instance.InstanceContainer;
import net.minestom.server.network.packet.server.play.TeamsPacket;
import net.minestom.server.scoreboard.Team;
import net.minestom.server.tag.Tag;
import org.spongepowered.configurate.ConfigurationNode;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList; | 8,585 | package net.endercube.Parkour;
/**
* This is the entrypoint for Parkour
*/
public class ParkourMinigame extends EndercubeMinigame {
public static ParkourMinigame parkourMinigame; | package net.endercube.Parkour;
/**
* This is the entrypoint for Parkour
*/
public class ParkourMinigame extends EndercubeMinigame {
public static ParkourMinigame parkourMinigame; | public static ParkourDatabase database; | 5 | 2023-12-10 12:08:18+00:00 | 12k |
lukebemishprojects/Tempest | forge/src/main/java/dev/lukebemish/tempest/impl/forge/ModPlatform.java | [
{
"identifier": "Constants",
"path": "common/src/main/java/dev/lukebemish/tempest/impl/Constants.java",
"snippet": "public final class Constants {\n public static final String MOD_ID = \"tempest\";\n\n private static final ResourceLocation BASE = new ResourceLocation(MOD_ID, MOD_ID);\n public s... | import com.google.auto.service.AutoService;
import com.mojang.datafixers.util.Pair;
import dev.lukebemish.tempest.impl.Constants;
import dev.lukebemish.tempest.impl.FastChunkLookup;
import dev.lukebemish.tempest.impl.Services;
import dev.lukebemish.tempest.impl.data.world.WeatherChunkData;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityToken;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.registries.DeferredRegister;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier; | 8,571 | package dev.lukebemish.tempest.impl.forge;
@AutoService(Services.Platform.class)
public final class ModPlatform implements Services.Platform {
public static final Capability<WeatherChunkData> WEATHER_CHUNK_DATA = CapabilityManager.get(new CapabilityToken<>(){}); | package dev.lukebemish.tempest.impl.forge;
@AutoService(Services.Platform.class)
public final class ModPlatform implements Services.Platform {
public static final Capability<WeatherChunkData> WEATHER_CHUNK_DATA = CapabilityManager.get(new CapabilityToken<>(){}); | public static final ResourceLocation WEATHER_CHUNK_DATA_LOCATION = Constants.id("weather_status"); | 0 | 2023-12-06 23:23:31+00:00 | 12k |
xhtcode/xht-cloud-parent | xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/area/service/impl/SysAreaInfoServiceImpl.java | [
{
"identifier": "PageResponse",
"path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/api/response/PageResponse.java",
"snippet": "@Data\n@Schema(description = \"分页信息响应实体\")\npublic class PageResponse<T> extends Response {\n\n /**\n * 当前页\n */\n @... | import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xht.cloud.framework.core.api.response.PageResponse;
import com.xht.cloud.framework.core.constant.CommonConstants;
import com.xht.cloud.framework.core.support.StringUtils;
import com.xht.cloud.framework.core.treenode.INode;
import com.xht.cloud.framework.core.treenode.TreeNode;
import com.xht.cloud.framework.core.treenode.TreeUtils;
import com.xht.cloud.framework.exception.Assert;
import com.xht.cloud.framework.exception.business.BizException;
import com.xht.cloud.system.module.area.controller.request.SysAreaInfoAddRequest;
import com.xht.cloud.system.module.area.controller.request.SysAreaInfoQueryRequest;
import com.xht.cloud.system.module.area.controller.request.SysAreaInfoUpdateRequest;
import com.xht.cloud.system.module.area.controller.response.SysAreaInfoResponse;
import com.xht.cloud.system.module.area.convert.SysAreaInfoConvert;
import com.xht.cloud.system.module.area.dao.dataobject.SysAreaInfoDO;
import com.xht.cloud.system.module.area.dao.mapper.SysAreaInfoMapper;
import com.xht.cloud.system.module.area.dao.wrapper.SysAreaInfoWrapper;
import com.xht.cloud.system.module.area.service.ISysAreaInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects; | 8,433 | package com.xht.cloud.system.module.area.service.impl;
/**
* 描述 :地区信息
*
* @author : xht
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class SysAreaInfoServiceImpl implements ISysAreaInfoService {
private final SysAreaInfoMapper sysAreaInfoMapper;
private final SysAreaInfoConvert sysAreaInfoConvert;
/**
* 创建
*
* @param addRequest {@link SysAreaInfoAddRequest}
* @return {@link String} 主键
*/
@Override
@Transactional(rollbackFor = Exception.class)
public String create(SysAreaInfoAddRequest addRequest) {
SysAreaInfoDO entity = sysAreaInfoConvert.toDO(addRequest);
sysAreaInfoMapper.insert(entity);
return entity.getId();
}
/**
* 根据id修改
*
* @param updateRequest SysAreaInfoUpdateRequest
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void update(SysAreaInfoUpdateRequest updateRequest) {
if (Objects.isNull(findById(updateRequest.getId()))) {
throw new BizException("修改的对象不存在!");
}
sysAreaInfoMapper.updateById(sysAreaInfoConvert.toDO(updateRequest));
}
/**
* 删除
*
* @param ids {@link List<String>} id集合
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void remove(List<String> ids) {
List<SysAreaInfoDO> sysAreaInfoDOS = sysAreaInfoMapper.selectList(SysAreaInfoWrapper.getInstance().lambdaQuery().in(SysAreaInfoDO::getParentId, ids));
if (!CollectionUtils.isEmpty(sysAreaInfoDOS)) {
Assert.fail("删除数据中含有下级城市数据,禁止删除!");
}
sysAreaInfoMapper.deleteBatchIds(ids);
}
/**
* 根据id查询详细
*
* @param id {@link String} 数据库主键
* @return {@link SysAreaInfoResponse}
*/
@Override | package com.xht.cloud.system.module.area.service.impl;
/**
* 描述 :地区信息
*
* @author : xht
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class SysAreaInfoServiceImpl implements ISysAreaInfoService {
private final SysAreaInfoMapper sysAreaInfoMapper;
private final SysAreaInfoConvert sysAreaInfoConvert;
/**
* 创建
*
* @param addRequest {@link SysAreaInfoAddRequest}
* @return {@link String} 主键
*/
@Override
@Transactional(rollbackFor = Exception.class)
public String create(SysAreaInfoAddRequest addRequest) {
SysAreaInfoDO entity = sysAreaInfoConvert.toDO(addRequest);
sysAreaInfoMapper.insert(entity);
return entity.getId();
}
/**
* 根据id修改
*
* @param updateRequest SysAreaInfoUpdateRequest
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void update(SysAreaInfoUpdateRequest updateRequest) {
if (Objects.isNull(findById(updateRequest.getId()))) {
throw new BizException("修改的对象不存在!");
}
sysAreaInfoMapper.updateById(sysAreaInfoConvert.toDO(updateRequest));
}
/**
* 删除
*
* @param ids {@link List<String>} id集合
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void remove(List<String> ids) {
List<SysAreaInfoDO> sysAreaInfoDOS = sysAreaInfoMapper.selectList(SysAreaInfoWrapper.getInstance().lambdaQuery().in(SysAreaInfoDO::getParentId, ids));
if (!CollectionUtils.isEmpty(sysAreaInfoDOS)) {
Assert.fail("删除数据中含有下级城市数据,禁止删除!");
}
sysAreaInfoMapper.deleteBatchIds(ids);
}
/**
* 根据id查询详细
*
* @param id {@link String} 数据库主键
* @return {@link SysAreaInfoResponse}
*/
@Override | public SysAreaInfoResponse findById(String id) { | 11 | 2023-12-12 08:16:30+00:00 | 12k |
serendipitk/LunarCore | src/main/java/emu/lunarcore/command/commands/MailCommand.java | [
{
"identifier": "CommandArgs",
"path": "src/main/java/emu/lunarcore/command/CommandArgs.java",
"snippet": "@Getter\npublic class CommandArgs {\n private String raw;\n private List<String> list;\n private Player sender;\n private Player target;\n \n private int targetUid;\n private i... | import java.util.ArrayList;
import java.util.List;
import emu.lunarcore.command.Command;
import emu.lunarcore.command.CommandArgs;
import emu.lunarcore.command.CommandHandler;
import emu.lunarcore.data.GameData;
import emu.lunarcore.data.excel.ItemExcel;
import emu.lunarcore.game.inventory.GameItem;
import emu.lunarcore.game.mail.Mail; | 9,104 | package emu.lunarcore.command.commands;
@Command(label = "mail", aliases = {"m"}, permission = "player.mail", requireTarget = true, desc = "/mail [邮件内容]. 发送邮件给目标玩家.")
public class MailCommand implements CommandHandler {
@Override | package emu.lunarcore.command.commands;
@Command(label = "mail", aliases = {"m"}, permission = "player.mail", requireTarget = true, desc = "/mail [邮件内容]. 发送邮件给目标玩家.")
public class MailCommand implements CommandHandler {
@Override | public void execute(CommandArgs args) { | 0 | 2023-12-08 14:13:04+00:00 | 12k |
zhaw-iwi/promise | src/test/java/ch/zhaw/statefulconversation/paper/MultiStateInteraction.java | [
{
"identifier": "Agent",
"path": "src/main/java/ch/zhaw/statefulconversation/model/Agent.java",
"snippet": "@Entity\npublic class Agent {\n\n // @TODO: maybe have an attribute or getter method is active?\n\n @Id\n @GeneratedValue\n private UUID id;\n\n public UUID getId() {\n retur... | import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.google.gson.Gson;
import ch.zhaw.statefulconversation.model.Agent;
import ch.zhaw.statefulconversation.model.Final;
import ch.zhaw.statefulconversation.model.OuterState;
import ch.zhaw.statefulconversation.model.State;
import ch.zhaw.statefulconversation.model.Storage;
import ch.zhaw.statefulconversation.model.Transition;
import ch.zhaw.statefulconversation.model.commons.actions.StaticExtractionAction;
import ch.zhaw.statefulconversation.model.commons.decisions.StaticDecision;
import ch.zhaw.statefulconversation.model.commons.states.DynamicSingleChoiceState;
import ch.zhaw.statefulconversation.model.commons.states.EN_DynamicCauseAssessmentState;
import ch.zhaw.statefulconversation.repositories.AgentRepository; | 7,606 | package ch.zhaw.statefulconversation.paper;
@SpringBootTest
class MultiStateInteraction {
private static final String PROMPT_THERAPYCOACH = """
As a digital therapy coach, your role is to support and enhance patient adherence to their therapy plans.
Always respond with very brief, succinct answers, keeping them to a maximum of one or two sentences.
""";
private static final String PROMPT_THERAPYCOACH_TRIGGER = """
Review the patient's latest messages in the following conversation.
Decide if there are any statements or cues suggesting they wish to pause or stop the conversation, such as explicit requests for a break, indications of needing time, or other phrases implying a desire to end the chat.
""";
private static final String PROMPT_THERAPYCOACH_GUARD = """
Examine the following conversation and confirm that the patient has not reported any issues like physical or mental discomfort that need addressing.
""";
private static final String PROMPT_THERAPYCOACH_ACTION = """
Summarize the coach-patient conversation, highlighting adherence to the therapy plan, issues reported, and suggestions for improvements accepted for the physician's review.
""";
@Autowired
private AgentRepository repository;
@Test
void setUp() {
String storageKeyFromActivityMissed = "ActivityMissed";
String storageKeyToReasonProvided = "ReasonProvided";
String storageKeyFromSuggestionsOffered = "SuggestionsOffered";
String storageKeyToSuggestionChosen = "SuggestionChosen";
Gson gson = new Gson();
Storage storage = new Storage();
storage.put(storageKeyFromActivityMissed,
gson.toJsonTree(List.of("Patient missed 30 minutes of swimming yesterday evening.")));
storage.put(storageKeyFromSuggestionsOffered,
gson.toJsonTree(List.of(
"Less Crowded Swim Sessions: Recommend that the patient look for less busy times to swim at the public pool.",
"Alternative Water Exercises: Propose looking into water aerobics classes which often attract people of all body types, promoting a more inclusive and less self-conscious atmosphere.")));
State patientChoosesSuggestion = new DynamicSingleChoiceState("PatientChoosesSuggestion", new Final(),
storage,
storageKeyFromSuggestionsOffered, storageKeyToSuggestionChosen);
State patientProvidesReason = new EN_DynamicCauseAssessmentState("PatientProvidesReason",
patientChoosesSuggestion,
storage,
storageKeyFromActivityMissed, storageKeyToReasonProvided);
| package ch.zhaw.statefulconversation.paper;
@SpringBootTest
class MultiStateInteraction {
private static final String PROMPT_THERAPYCOACH = """
As a digital therapy coach, your role is to support and enhance patient adherence to their therapy plans.
Always respond with very brief, succinct answers, keeping them to a maximum of one or two sentences.
""";
private static final String PROMPT_THERAPYCOACH_TRIGGER = """
Review the patient's latest messages in the following conversation.
Decide if there are any statements or cues suggesting they wish to pause or stop the conversation, such as explicit requests for a break, indications of needing time, or other phrases implying a desire to end the chat.
""";
private static final String PROMPT_THERAPYCOACH_GUARD = """
Examine the following conversation and confirm that the patient has not reported any issues like physical or mental discomfort that need addressing.
""";
private static final String PROMPT_THERAPYCOACH_ACTION = """
Summarize the coach-patient conversation, highlighting adherence to the therapy plan, issues reported, and suggestions for improvements accepted for the physician's review.
""";
@Autowired
private AgentRepository repository;
@Test
void setUp() {
String storageKeyFromActivityMissed = "ActivityMissed";
String storageKeyToReasonProvided = "ReasonProvided";
String storageKeyFromSuggestionsOffered = "SuggestionsOffered";
String storageKeyToSuggestionChosen = "SuggestionChosen";
Gson gson = new Gson();
Storage storage = new Storage();
storage.put(storageKeyFromActivityMissed,
gson.toJsonTree(List.of("Patient missed 30 minutes of swimming yesterday evening.")));
storage.put(storageKeyFromSuggestionsOffered,
gson.toJsonTree(List.of(
"Less Crowded Swim Sessions: Recommend that the patient look for less busy times to swim at the public pool.",
"Alternative Water Exercises: Propose looking into water aerobics classes which often attract people of all body types, promoting a more inclusive and less self-conscious atmosphere.")));
State patientChoosesSuggestion = new DynamicSingleChoiceState("PatientChoosesSuggestion", new Final(),
storage,
storageKeyFromSuggestionsOffered, storageKeyToSuggestionChosen);
State patientProvidesReason = new EN_DynamicCauseAssessmentState("PatientProvidesReason",
patientChoosesSuggestion,
storage,
storageKeyFromActivityMissed, storageKeyToReasonProvided);
| Transition therapyCoachTransition = new Transition( | 5 | 2023-12-06 09:36:58+00:00 | 12k |
quentin452/Garden-Stuff-Continuation | src/main/java/com/jaquadro/minecraft/gardentrees/item/ItemThinLog.java | [
{
"identifier": "BlockThinLog",
"path": "src/main/java/com/jaquadro/minecraft/gardentrees/block/BlockThinLog.java",
"snippet": "public class BlockThinLog extends BlockContainer implements IChainSingleAttachable {\n\n public static final String[] subNames = new String[] { \"oak\", \"spruce\", \"birch\... | import com.jaquadro.minecraft.gardentrees.block.BlockThinLog;
import com.jaquadro.minecraft.gardentrees.block.tile.TileEntityWoodProxy;
import com.jaquadro.minecraft.gardentrees.core.ModBlocks;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World; | 7,531 | package com.jaquadro.minecraft.gardentrees.item;
public class ItemThinLog extends ItemBlock {
public ItemThinLog(Block block) {
super(block);
this.setMaxDamage(0);
this.setHasSubtypes(true);
}
public int getMetadata(int meta) {
return meta;
}
public String getUnlocalizedName(ItemStack itemStack) {
int meta = itemStack.getItemDamage();
return meta >= 0 && meta < BlockThinLog.subNames.length
? super.getUnlocalizedName() + "." + BlockThinLog.subNames[meta]
: super.getUnlocalizedName();
}
public String getItemStackDisplayName(ItemStack itemStack) {
int meta = itemStack.getItemDamage();
if (meta < 16) {
return super.getItemStackDisplayName(itemStack);
} else {
Block block = TileEntityWoodProxy.getBlockFromComposedMetadata(meta);
Item item = Item.getItemFromBlock(block);
if (item == null) {
return super.getItemStackDisplayName(itemStack);
} else {
String unlocName = item
.getUnlocalizedName(new ItemStack(item, 1, TileEntityWoodProxy.getMetaFromComposedMetadata(meta)));
return ("" + StatCollector.translateToLocal(unlocName + ".name")
+ " "
+ StatCollector.translateToLocal(this.getUnlocalizedName() + ".name")).trim();
}
}
}
public IIcon getIconFromDamage(int meta) { | package com.jaquadro.minecraft.gardentrees.item;
public class ItemThinLog extends ItemBlock {
public ItemThinLog(Block block) {
super(block);
this.setMaxDamage(0);
this.setHasSubtypes(true);
}
public int getMetadata(int meta) {
return meta;
}
public String getUnlocalizedName(ItemStack itemStack) {
int meta = itemStack.getItemDamage();
return meta >= 0 && meta < BlockThinLog.subNames.length
? super.getUnlocalizedName() + "." + BlockThinLog.subNames[meta]
: super.getUnlocalizedName();
}
public String getItemStackDisplayName(ItemStack itemStack) {
int meta = itemStack.getItemDamage();
if (meta < 16) {
return super.getItemStackDisplayName(itemStack);
} else {
Block block = TileEntityWoodProxy.getBlockFromComposedMetadata(meta);
Item item = Item.getItemFromBlock(block);
if (item == null) {
return super.getItemStackDisplayName(itemStack);
} else {
String unlocName = item
.getUnlocalizedName(new ItemStack(item, 1, TileEntityWoodProxy.getMetaFromComposedMetadata(meta)));
return ("" + StatCollector.translateToLocal(unlocName + ".name")
+ " "
+ StatCollector.translateToLocal(this.getUnlocalizedName() + ".name")).trim();
}
}
}
public IIcon getIconFromDamage(int meta) { | return ModBlocks.thinLog.getIcon(0, meta); | 2 | 2023-12-12 08:13:16+00:00 | 12k |
Zergatul/java-scripting-language | src/main/java/com/zergatul/scripting/compiler/ScriptingLanguageCompiler.java | [
{
"identifier": "BinaryOperation",
"path": "src/main/java/com/zergatul/scripting/compiler/operations/BinaryOperation.java",
"snippet": "public abstract class BinaryOperation {\r\n\r\n public abstract SType getType();\r\n public abstract void apply(CompilerMethodVisitor left, BufferVisitor right) t... | import com.zergatul.scripting.compiler.operations.BinaryOperation;
import com.zergatul.scripting.compiler.operations.ImplicitCast;
import com.zergatul.scripting.compiler.operations.UnaryOperation;
import com.zergatul.scripting.compiler.types.*;
import com.zergatul.scripting.compiler.variables.FunctionEntry;
import com.zergatul.scripting.compiler.variables.StaticVariableEntry;
import com.zergatul.scripting.compiler.variables.VariableContextStack;
import com.zergatul.scripting.compiler.variables.VariableEntry;
import com.zergatul.scripting.generated.*;
import org.objectweb.asm.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.objectweb.asm.Opcodes.*;
| 8,137 | consumer.apply(writer, constructorVisitorWrapper, runVisitorWrapper);
constructorVisitor.visitInsn(RETURN);
constructorVisitor.visitMaxs(0, 0);
constructorVisitor.visitEnd();
runVisitor.visitInsn(RETURN);
runVisitor.visitMaxs(0, 0);
runVisitor.visitEnd();
for (StaticVariableEntry entry : runVisitorWrapper.getContextStack().getStaticVariables()) {
if (entry.getClassName().equals(name)) {
FieldVisitor fieldVisitor = writer.visitField(
ACC_PUBLIC | ACC_STATIC,
entry.getIdentifier(),
Type.getDescriptor(entry.getType().getJavaClass()),
null, null);
fieldVisitor.visitEnd();
}
}
writer.visitEnd();
byte[] code = writer.toByteArray();
return (Class<Runnable>) classLoader.defineClass(name.replace('/', '.'), code);
}
private void compile(
ASTInput input,
ClassWriter classWriter,
CompilerMethodVisitor constructorVisitor,
CompilerMethodVisitor runVisitor
) throws ScriptCompileException {
if (input.jjtGetNumChildren() < 2) {
throw new ScriptCompileException("ASTInput: num children < 2.");
}
if (!(input.jjtGetChild(0) instanceof ASTStaticVariablesList variablesList)) {
throw new ScriptCompileException("ASTInput: static vars list expected.");
}
if (!(input.jjtGetChild(1) instanceof ASTFunctionsList functionsList)) {
throw new ScriptCompileException("ASTInput: functions list expected.");
}
compile(variablesList, constructorVisitor);
compile(functionsList, classWriter, constructorVisitor);
for (int i = 2; i < input.jjtGetNumChildren(); i++) {
if (!(input.jjtGetChild(i) instanceof ASTStatement statement)) {
throw new ScriptCompileException("ASTInput statement expected.");
}
compile(statement, runVisitor);
}
}
private void compile(ASTStaticVariablesList list, CompilerMethodVisitor visitor) throws ScriptCompileException {
for (int i = 0; i < list.jjtGetNumChildren(); i++) {
if (!(list.jjtGetChild(i) instanceof ASTStaticVariableDeclaration variableDeclaration)) {
throw new ScriptCompileException("ASTStaticVariablesList declaration expected.");
}
compile(variableDeclaration, visitor);
}
}
private void compile(
ASTFunctionsList list,
ClassWriter classWriter,
CompilerMethodVisitor visitor
) throws ScriptCompileException {
for (int i = 0; i < list.jjtGetNumChildren(); i++) {
if (!(list.jjtGetChild(i) instanceof ASTFunctionDeclaration functionDeclaration)) {
throw new ScriptCompileException("ASTFunctionsList: declaration expected.");
}
SType type = getFunctionReturnType(functionDeclaration);
ASTIdentifier identifier = getFunctionIdentifier(functionDeclaration);
List<FunctionParameter> parameters = getFunctionParameters(functionDeclaration);
String name = (String) identifier.jjtGetValue();
visitor.getContextStack().addFunction(
name,
type,
parameters.stream().map(p -> p.type).toArray(SType[]::new),
visitor.getClassName());
}
for (int i = 0; i < list.jjtGetNumChildren(); i++) {
compile(
(ASTFunctionDeclaration) list.jjtGetChild(i),
classWriter,
visitor.getContextStack().newWithStaticVariables(0));
}
}
private void compile(ASTStaticVariableDeclaration declaration, CompilerMethodVisitor visitor) throws ScriptCompileException {
if (declaration.jjtGetNumChildren() != 1) {
throw new ScriptCompileException("Invalid static var decl structure.");
}
Node node = declaration.jjtGetChild(0);
if (!(node instanceof ASTLocalVariableDeclaration localVariableDeclaration)) {
throw new ScriptCompileException("ASTLocalVariableDeclaration expected.");
}
ASTType astType = (ASTType) localVariableDeclaration.jjtGetChild(0);
ASTVariableDeclarator variableDeclarator = (ASTVariableDeclarator) localVariableDeclaration.jjtGetChild(1);
ASTVariableDeclaratorId variableDeclaratorId = (ASTVariableDeclaratorId) variableDeclarator.jjtGetChild(0);
ASTIdentifier identifier = (ASTIdentifier) variableDeclaratorId.jjtGetChild(0);
ASTVariableInitializer initializer = null;
if (variableDeclarator.jjtGetNumChildren() > 1) {
initializer = (ASTVariableInitializer) variableDeclarator.jjtGetChild(1);
}
SType type = parseType(astType);
if (initializer != null) {
SType returnType = compile((ASTExpression) initializer.jjtGetChild(0), visitor);
if (!returnType.equals(type)) {
| package com.zergatul.scripting.compiler;
public class ScriptingLanguageCompiler {
private static AtomicInteger counter = new AtomicInteger(0);
private static ScriptingClassLoader classLoader = new ScriptingClassLoader();
private final Class<?> root;
private final MethodVisibilityChecker visibilityChecker;
public ScriptingLanguageCompiler(Class<?> root) {
this(root, new MethodVisibilityChecker());
}
public ScriptingLanguageCompiler(Class<?> root, MethodVisibilityChecker visibilityChecker) {
this.root = root;
this.visibilityChecker = visibilityChecker;
}
public Runnable compile(String program) throws ParseException, ScriptCompileException {
program += "\r\n"; // temp fix for error if last token is comment
InputStream stream = new ByteArrayInputStream(program.getBytes(StandardCharsets.UTF_8));
ScriptingLanguage parser = new ScriptingLanguage(stream);
ASTInput input = parser.Input();
Class<Runnable> dynamic = compileRunnable((cw, v1, v2) -> {
compile(input, cw, v1, v2);
});
Constructor<Runnable> constructor;
try {
constructor = dynamic.getConstructor();
} catch (NoSuchMethodException e) {
throw new ScriptCompileException("Cannot find constructor for dynamic class.");
}
Runnable instance;
try {
instance = constructor.newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new ScriptCompileException("Cannot instantiate dynamic class.");
}
return instance;
}
private Class<Runnable> compileRunnable(CompileConsumer consumer) throws ScriptCompileException {
// since this is instance method, local vars start from 1
// 0 = this
return compileRunnable(consumer, new VariableContextStack(1));
}
@SuppressWarnings("unchecked")
private Class<Runnable> compileRunnable(CompileConsumer consumer, VariableContextStack context) throws ScriptCompileException {
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
String name = "com/zergatul/scripting/dynamic/DynamicClass_" + counter.incrementAndGet();
writer.visit(V1_5, ACC_PUBLIC, name, null, Type.getInternalName(Object.class), new String[] { Type.getInternalName(Runnable.class) });
MethodVisitor constructorVisitor = writer.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
constructorVisitor.visitCode();
constructorVisitor.visitVarInsn(ALOAD, 0);
constructorVisitor.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V", false);
MethodVisitor runVisitor = writer.visitMethod(ACC_PUBLIC, "run", "()V", null, null);
runVisitor.visitCode();
MethodVisitorWrapper constructorVisitorWrapper = new MethodVisitorWrapper(constructorVisitor, name, context);
MethodVisitorWrapper runVisitorWrapper = new MethodVisitorWrapper(runVisitor, name, context);
runVisitorWrapper.getLoops().push(
v -> {
throw new ScriptCompileException("Continue statement without loop.");
},
v -> {
throw new ScriptCompileException("Break statement without loop.");
});
consumer.apply(writer, constructorVisitorWrapper, runVisitorWrapper);
constructorVisitor.visitInsn(RETURN);
constructorVisitor.visitMaxs(0, 0);
constructorVisitor.visitEnd();
runVisitor.visitInsn(RETURN);
runVisitor.visitMaxs(0, 0);
runVisitor.visitEnd();
for (StaticVariableEntry entry : runVisitorWrapper.getContextStack().getStaticVariables()) {
if (entry.getClassName().equals(name)) {
FieldVisitor fieldVisitor = writer.visitField(
ACC_PUBLIC | ACC_STATIC,
entry.getIdentifier(),
Type.getDescriptor(entry.getType().getJavaClass()),
null, null);
fieldVisitor.visitEnd();
}
}
writer.visitEnd();
byte[] code = writer.toByteArray();
return (Class<Runnable>) classLoader.defineClass(name.replace('/', '.'), code);
}
private void compile(
ASTInput input,
ClassWriter classWriter,
CompilerMethodVisitor constructorVisitor,
CompilerMethodVisitor runVisitor
) throws ScriptCompileException {
if (input.jjtGetNumChildren() < 2) {
throw new ScriptCompileException("ASTInput: num children < 2.");
}
if (!(input.jjtGetChild(0) instanceof ASTStaticVariablesList variablesList)) {
throw new ScriptCompileException("ASTInput: static vars list expected.");
}
if (!(input.jjtGetChild(1) instanceof ASTFunctionsList functionsList)) {
throw new ScriptCompileException("ASTInput: functions list expected.");
}
compile(variablesList, constructorVisitor);
compile(functionsList, classWriter, constructorVisitor);
for (int i = 2; i < input.jjtGetNumChildren(); i++) {
if (!(input.jjtGetChild(i) instanceof ASTStatement statement)) {
throw new ScriptCompileException("ASTInput statement expected.");
}
compile(statement, runVisitor);
}
}
private void compile(ASTStaticVariablesList list, CompilerMethodVisitor visitor) throws ScriptCompileException {
for (int i = 0; i < list.jjtGetNumChildren(); i++) {
if (!(list.jjtGetChild(i) instanceof ASTStaticVariableDeclaration variableDeclaration)) {
throw new ScriptCompileException("ASTStaticVariablesList declaration expected.");
}
compile(variableDeclaration, visitor);
}
}
private void compile(
ASTFunctionsList list,
ClassWriter classWriter,
CompilerMethodVisitor visitor
) throws ScriptCompileException {
for (int i = 0; i < list.jjtGetNumChildren(); i++) {
if (!(list.jjtGetChild(i) instanceof ASTFunctionDeclaration functionDeclaration)) {
throw new ScriptCompileException("ASTFunctionsList: declaration expected.");
}
SType type = getFunctionReturnType(functionDeclaration);
ASTIdentifier identifier = getFunctionIdentifier(functionDeclaration);
List<FunctionParameter> parameters = getFunctionParameters(functionDeclaration);
String name = (String) identifier.jjtGetValue();
visitor.getContextStack().addFunction(
name,
type,
parameters.stream().map(p -> p.type).toArray(SType[]::new),
visitor.getClassName());
}
for (int i = 0; i < list.jjtGetNumChildren(); i++) {
compile(
(ASTFunctionDeclaration) list.jjtGetChild(i),
classWriter,
visitor.getContextStack().newWithStaticVariables(0));
}
}
private void compile(ASTStaticVariableDeclaration declaration, CompilerMethodVisitor visitor) throws ScriptCompileException {
if (declaration.jjtGetNumChildren() != 1) {
throw new ScriptCompileException("Invalid static var decl structure.");
}
Node node = declaration.jjtGetChild(0);
if (!(node instanceof ASTLocalVariableDeclaration localVariableDeclaration)) {
throw new ScriptCompileException("ASTLocalVariableDeclaration expected.");
}
ASTType astType = (ASTType) localVariableDeclaration.jjtGetChild(0);
ASTVariableDeclarator variableDeclarator = (ASTVariableDeclarator) localVariableDeclaration.jjtGetChild(1);
ASTVariableDeclaratorId variableDeclaratorId = (ASTVariableDeclaratorId) variableDeclarator.jjtGetChild(0);
ASTIdentifier identifier = (ASTIdentifier) variableDeclaratorId.jjtGetChild(0);
ASTVariableInitializer initializer = null;
if (variableDeclarator.jjtGetNumChildren() > 1) {
initializer = (ASTVariableInitializer) variableDeclarator.jjtGetChild(1);
}
SType type = parseType(astType);
if (initializer != null) {
SType returnType = compile((ASTExpression) initializer.jjtGetChild(0), visitor);
if (!returnType.equals(type)) {
| UnaryOperation operation = ImplicitCast.get(returnType, type);
| 2 | 2023-12-10 00:37:27+00:00 | 12k |
Lampadina17/MorpheusLauncher | src/team/morpheus/launcher/instance/Morpheus.java | [
{
"identifier": "Launcher",
"path": "src/team/morpheus/launcher/Launcher.java",
"snippet": "public class Launcher {\r\n\r\n private static final MyLogger log = new MyLogger(Launcher.class);\r\n public JSONParser jsonParser = new JSONParser();\r\n private File gameFolder, assetsFolder;\r\n\r\n ... | import com.google.gson.Gson;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import team.morpheus.launcher.Launcher;
import team.morpheus.launcher.Main;
import team.morpheus.launcher.logging.MyLogger;
import team.morpheus.launcher.model.MorpheusSession;
import team.morpheus.launcher.model.MorpheusUser;
import team.morpheus.launcher.model.products.MorpheusProduct;
import team.morpheus.launcher.utils.Utils;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
| 9,909 | package team.morpheus.launcher.instance;
public class Morpheus {
private static final MyLogger log = new MyLogger(Morpheus.class);
public MorpheusSession session;
public JSONParser jsonParser = new JSONParser();
public MorpheusUser user;
public Morpheus(MorpheusSession session) {
this.session = session;
}
public void prepareLaunch() throws Exception {
/* Ask server user json */
HashMap<String, String> map = new HashMap<>();
map.put("accessToken", session.getSessionToken());
| package team.morpheus.launcher.instance;
public class Morpheus {
private static final MyLogger log = new MyLogger(Morpheus.class);
public MorpheusSession session;
public JSONParser jsonParser = new JSONParser();
public MorpheusUser user;
public Morpheus(MorpheusSession session) {
this.session = session;
}
public void prepareLaunch() throws Exception {
/* Ask server user json */
HashMap<String, String> map = new HashMap<>();
map.put("accessToken", session.getSessionToken());
| HttpURLConnection userInfo = Utils.makePostRequest(new URL(String.format("%s/api/userinfo", Main.getMorpheusAPI())), map);
| 6 | 2023-12-07 14:34:54+00:00 | 12k |
Serilum/Collective | Common/src/main/java/com/natamus/collective/events/CollectiveEvents.java | [
{
"identifier": "RegisterMod",
"path": "Common/src/main/java/com/natamus/collective/check/RegisterMod.java",
"snippet": "public class RegisterMod {\n\tprivate static final CopyOnWriteArrayList<String> jarlist = new CopyOnWriteArrayList<String>();\n\tprivate static final HashMap<String, String> jartoname... | import com.mojang.datafixers.util.Pair;
import com.natamus.collective.check.RegisterMod;
import com.natamus.collective.config.CollectiveConfigHandler;
import com.natamus.collective.data.GlobalVariables;
import com.natamus.collective.functions.BlockPosFunctions;
import com.natamus.collective.functions.EntityFunctions;
import com.natamus.collective.functions.SpawnEntityFunctions;
import com.natamus.collective.objects.SAMObject;
import com.natamus.collective.util.CollectiveReference;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.TickTask;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.AgeableMob;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.Entity.RemovalReason;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.animal.horse.AbstractHorse;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.CopyOnWriteArrayList; | 10,216 | package com.natamus.collective.events;
public class CollectiveEvents {
public static WeakHashMap<ServerLevel, List<Entity>> entitiesToSpawn = new WeakHashMap<ServerLevel, List<Entity>>();
public static WeakHashMap<ServerLevel, WeakHashMap<Entity, Entity>> entitiesToRide = new WeakHashMap<ServerLevel, WeakHashMap<Entity, Entity>>();
public static CopyOnWriteArrayList<Pair<Integer, Runnable>> scheduledRunnables = new CopyOnWriteArrayList<Pair<Integer, Runnable>>();
public static void onWorldTick(ServerLevel serverLevel) {
if (entitiesToSpawn.computeIfAbsent(serverLevel, k -> new ArrayList<Entity>()).size() > 0) {
Entity tospawn = entitiesToSpawn.get(serverLevel).get(0);
serverLevel.addFreshEntityWithPassengers(tospawn);
if (entitiesToRide.computeIfAbsent(serverLevel, k -> new WeakHashMap<Entity, Entity>()).containsKey(tospawn)) {
Entity rider = entitiesToRide.get(serverLevel).get(tospawn);
rider.startRiding(tospawn);
entitiesToRide.get(serverLevel).remove(tospawn);
}
entitiesToSpawn.get(serverLevel).remove(0);
}
}
public static void onServerTick(MinecraftServer minecraftServer) {
int serverTickCount = minecraftServer.getTickCount();
for (Pair<Integer, Runnable> pair : scheduledRunnables) {
if (pair.getFirst() <= serverTickCount) {
minecraftServer.tell(new TickTask(minecraftServer.getTickCount(), pair.getSecond()));
scheduledRunnables.remove(pair);
}
}
}
public static boolean onEntityJoinLevel(Level level, Entity entity) {
if (!(entity instanceof LivingEntity)) {
return true;
}
if (RegisterMod.shouldDoCheck) {
if (entity instanceof Player) {
RegisterMod.joinWorldProcess(level, (Player)entity);
}
}
if (entity.isRemoved()) {
return true;
}
if (GlobalVariables.globalSAMs.isEmpty()) {
return true;
}
Set<String> tags = entity.getTags();
if (tags.contains(CollectiveReference.MOD_ID + ".checked")) {
return true;
}
entity.addTag(CollectiveReference.MOD_ID + ".checked");
EntityType<?> entityType = entity.getType();
if (!GlobalVariables.activeSAMEntityTypes.contains(entityType)) {
return true;
}
boolean isFromSpawner = tags.contains(CollectiveReference.MOD_ID + ".fromspawner");
List<SAMObject> possibles = new ArrayList<SAMObject>();
for (SAMObject sam : GlobalVariables.globalSAMs) {
if (sam == null) {
continue;
}
if (sam.fromEntityType == null) {
continue;
}
if (sam.fromEntityType.equals(entityType)) {
if ((sam.onlyFromSpawner && !isFromSpawner) || (!sam.onlyFromSpawner && isFromSpawner)) {
continue;
}
possibles.add(sam);
}
}
int size = possibles.size();
if (size == 0) {
return true;
}
Vec3 eVec = entity.position();
boolean ageable = entity instanceof AgeableMob;
boolean isOnSurface = BlockPosFunctions.isOnSurface(level, eVec);
for (SAMObject sam : possibles) {
double num = GlobalVariables.random.nextDouble();
if (num > sam.changeChance) {
continue;
}
if (sam.onlyOnSurface) {
if (!isOnSurface) {
continue;
}
}
else if (sam.onlyBelowSurface) {
if (isOnSurface) {
continue;
}
}
if (sam.onlyBelowSpecificY) {
if (eVec.y >= sam.specificY) {
continue;
}
}
Entity to = sam.toEntityType.create(level);
if (to == null) {
return true;
}
to.setPos(eVec.x, eVec.y, eVec.z);
if (ageable && to instanceof AgeableMob) {
AgeableMob am = (AgeableMob)to;
am.setAge(((AgeableMob)entity).getAge());
to = am;
}
boolean ignoreMainhand = false;
if (sam.itemToHold != null) {
if (to instanceof LivingEntity) {
LivingEntity le = (LivingEntity)to;
if (!le.getMainHandItem().getItem().equals(sam.itemToHold)) {
le.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(sam.itemToHold, 1));
ignoreMainhand = true;
}
}
}
boolean ride = false;
if (EntityFunctions.isHorse(to) && sam.rideNotReplace) {
AbstractHorse ah = (AbstractHorse)to;
ah.setTamed(true);
ride = true;
}
else { | package com.natamus.collective.events;
public class CollectiveEvents {
public static WeakHashMap<ServerLevel, List<Entity>> entitiesToSpawn = new WeakHashMap<ServerLevel, List<Entity>>();
public static WeakHashMap<ServerLevel, WeakHashMap<Entity, Entity>> entitiesToRide = new WeakHashMap<ServerLevel, WeakHashMap<Entity, Entity>>();
public static CopyOnWriteArrayList<Pair<Integer, Runnable>> scheduledRunnables = new CopyOnWriteArrayList<Pair<Integer, Runnable>>();
public static void onWorldTick(ServerLevel serverLevel) {
if (entitiesToSpawn.computeIfAbsent(serverLevel, k -> new ArrayList<Entity>()).size() > 0) {
Entity tospawn = entitiesToSpawn.get(serverLevel).get(0);
serverLevel.addFreshEntityWithPassengers(tospawn);
if (entitiesToRide.computeIfAbsent(serverLevel, k -> new WeakHashMap<Entity, Entity>()).containsKey(tospawn)) {
Entity rider = entitiesToRide.get(serverLevel).get(tospawn);
rider.startRiding(tospawn);
entitiesToRide.get(serverLevel).remove(tospawn);
}
entitiesToSpawn.get(serverLevel).remove(0);
}
}
public static void onServerTick(MinecraftServer minecraftServer) {
int serverTickCount = minecraftServer.getTickCount();
for (Pair<Integer, Runnable> pair : scheduledRunnables) {
if (pair.getFirst() <= serverTickCount) {
minecraftServer.tell(new TickTask(minecraftServer.getTickCount(), pair.getSecond()));
scheduledRunnables.remove(pair);
}
}
}
public static boolean onEntityJoinLevel(Level level, Entity entity) {
if (!(entity instanceof LivingEntity)) {
return true;
}
if (RegisterMod.shouldDoCheck) {
if (entity instanceof Player) {
RegisterMod.joinWorldProcess(level, (Player)entity);
}
}
if (entity.isRemoved()) {
return true;
}
if (GlobalVariables.globalSAMs.isEmpty()) {
return true;
}
Set<String> tags = entity.getTags();
if (tags.contains(CollectiveReference.MOD_ID + ".checked")) {
return true;
}
entity.addTag(CollectiveReference.MOD_ID + ".checked");
EntityType<?> entityType = entity.getType();
if (!GlobalVariables.activeSAMEntityTypes.contains(entityType)) {
return true;
}
boolean isFromSpawner = tags.contains(CollectiveReference.MOD_ID + ".fromspawner");
List<SAMObject> possibles = new ArrayList<SAMObject>();
for (SAMObject sam : GlobalVariables.globalSAMs) {
if (sam == null) {
continue;
}
if (sam.fromEntityType == null) {
continue;
}
if (sam.fromEntityType.equals(entityType)) {
if ((sam.onlyFromSpawner && !isFromSpawner) || (!sam.onlyFromSpawner && isFromSpawner)) {
continue;
}
possibles.add(sam);
}
}
int size = possibles.size();
if (size == 0) {
return true;
}
Vec3 eVec = entity.position();
boolean ageable = entity instanceof AgeableMob;
boolean isOnSurface = BlockPosFunctions.isOnSurface(level, eVec);
for (SAMObject sam : possibles) {
double num = GlobalVariables.random.nextDouble();
if (num > sam.changeChance) {
continue;
}
if (sam.onlyOnSurface) {
if (!isOnSurface) {
continue;
}
}
else if (sam.onlyBelowSurface) {
if (isOnSurface) {
continue;
}
}
if (sam.onlyBelowSpecificY) {
if (eVec.y >= sam.specificY) {
continue;
}
}
Entity to = sam.toEntityType.create(level);
if (to == null) {
return true;
}
to.setPos(eVec.x, eVec.y, eVec.z);
if (ageable && to instanceof AgeableMob) {
AgeableMob am = (AgeableMob)to;
am.setAge(((AgeableMob)entity).getAge());
to = am;
}
boolean ignoreMainhand = false;
if (sam.itemToHold != null) {
if (to instanceof LivingEntity) {
LivingEntity le = (LivingEntity)to;
if (!le.getMainHandItem().getItem().equals(sam.itemToHold)) {
le.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(sam.itemToHold, 1));
ignoreMainhand = true;
}
}
}
boolean ride = false;
if (EntityFunctions.isHorse(to) && sam.rideNotReplace) {
AbstractHorse ah = (AbstractHorse)to;
ah.setTamed(true);
ride = true;
}
else { | if (CollectiveConfigHandler.transferItemsBetweenReplacedEntities) { | 1 | 2023-12-11 22:37:15+00:00 | 12k |
muchfish/ruoyi-vue-pro-sample | yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/permission/MenuServiceImpl.java | [
{
"identifier": "MenuCreateReqVO",
"path": "yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/permission/vo/menu/MenuCreateReqVO.java",
"snippet": "@Schema(description = \"管理后台 - 菜单创建 Request VO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\npubl... | import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuListReqVO;
import cn.iocoder.yudao.module.system.controller.admin.permission.vo.menu.MenuUpdateReqVO;
import cn.iocoder.yudao.module.system.convert.permission.MenuConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO;
import cn.iocoder.yudao.module.system.dal.mysql.permission.MenuMapper;
import cn.iocoder.yudao.module.system.dal.redis.RedisKeyConstants;
import cn.iocoder.yudao.module.system.enums.permission.MenuTypeEnum;
import cn.iocoder.yudao.module.system.service.tenant.TenantService;
import com.google.common.annotations.VisibleForTesting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO.ID_ROOT;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; | 7,902 | package cn.iocoder.yudao.module.system.service.permission;
/**
* 菜单 Service 实现
*
* @author 芋道源码
*/
@Service
@Slf4j
public class MenuServiceImpl implements MenuService {
@Resource
private MenuMapper menuMapper;
@Resource
private PermissionService permissionService;
@Resource
@Lazy // 延迟,避免循环依赖报错 | package cn.iocoder.yudao.module.system.service.permission;
/**
* 菜单 Service 实现
*
* @author 芋道源码
*/
@Service
@Slf4j
public class MenuServiceImpl implements MenuService {
@Resource
private MenuMapper menuMapper;
@Resource
private PermissionService permissionService;
@Resource
@Lazy // 延迟,避免循环依赖报错 | private TenantService tenantService; | 8 | 2023-12-08 02:48:42+00:00 | 12k |
mklemmingen/senet-boom | core/src/com/senetboom/game/SenetBoom.java | [
{
"identifier": "ExtraTurnActor",
"path": "core/src/com/senetboom/game/frontend/actors/ExtraTurnActor.java",
"snippet": "public class ExtraTurnActor extends Actor {\n /*\n class to hold an actor that gets displayed on screen for 2 seconds if the player got an extra Turn\n */\n\n // px coord... | import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.ScreenUtils;
import com.senetboom.game.backend.*;
import com.senetboom.game.frontend.actors.ExtraTurnActor;
import com.senetboom.game.frontend.sound.MusicPlaylist;
import com.senetboom.game.frontend.stages.GameStage;
import com.senetboom.game.frontend.stages.MainMenu;
import com.senetboom.game.frontend.text.Typewriter;
import com.badlogic.gdx.scenes.scene2d.ui.Stack;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import java.util.ArrayList; | 9,083 | stack.setPosition(X, Y);
stack.draw(batch, parentAlpha);
}
}
@Override
public void dispose () {
batch.dispose();
background.dispose();
// dispose of all textures
blackpiece.dispose();
whitepiece.dispose();
happy.dispose();
water.dispose();
safe.dispose();
rebirth.dispose();
rebirthProtection.dispose();
logo.dispose();
tileTexture.dispose();
emptyTexture.dispose();
extraTurnTexture.dispose();
blackStick.dispose();
whiteStick.dispose();
number0.dispose();
number1.dispose();
number2.dispose();
number3.dispose();
number4.dispose();
number6.dispose();
whiteStarts.dispose();
blackStarts.dispose();
}
public static Coordinate calculatePXbyTile(int x) {
// the screen is 1536 to 896. The board is 3x10 tiles and each tile is 80x80px.
// the board is centered on the screen
int screenWidth = 1536;
int screenHeight = 896;
int boardWidth = (int) (tileSize * 10);
int boardHeight = (int) (tileSize * 3);
// Calculate starting position (upper left corner) of the board
int boardStartX = (screenWidth - boardWidth) / 2;
int boardStartY = (screenHeight - boardHeight) / 2;
int yCoord;
int xCoord;
// Calculate the tile's position
if(x <= 9){
yCoord = boardStartY + 80;
xCoord = boardStartX + (x * 80);
} else if (x <= 19){
yCoord = boardStartY;
xCoord = boardStartX + (10*80) - ((x-9)*80);
} else {
yCoord = boardStartY - (80);
xCoord = boardStartY * ((x-19) * 80);
}
return new Coordinate(xCoord, yCoord);
}
public static int calculateTilebyPx(int x, int y) {
int screenWidth = 1536;
int screenHeight = 896;
int inFuncTileSize = (int) tileSize;
int boardWidth = (inFuncTileSize * 10);
int boardHeight = (inFuncTileSize * 3);
// Calculate starting position (upper left corner) of the board
int boardStartX = (screenWidth - boardWidth) / 2;
int boardStartY = (screenHeight - boardHeight) / 2;
// Adjust the y-coordinate to reflect libGDX's bottom-left origin
int adjustedY = screenHeight - y;
// Calculate which tile
int tileX = (int) ((x - boardStartX) / inFuncTileSize);
int tileY = (int) ((adjustedY - boardStartY) / inFuncTileSize);
int tile;
if (tileY == 0) { // Top row
tile = tileX; // Tiles 0 to 9
} else if (tileY == 1) { // Middle row (reversed)
tile = 19 - tileX; // Tiles 19 to 10, in reverse
} else if (tileY == 2) { // Bottom row
tile = 20 + tileX; // Tiles 20 to 29
} else {
// Handle the case where the coordinates are outside the board
tile = -1;
}
return tile;
}
public static void createHelpStage() {
// load texture help
Image help = new Image(helpTexture);
help.setPosition(tileSize*13.1f, tileSize*2.7f);
help.setSize(tileSize*7, tileSize*9);
// add it to help stage
helpOverlayStage.addActor(help);
}
public static void createOptionsStage() {
}
public static Skin getSkin() {
return skin;
}
public static void renderBoard() {
stickValueStage.clear();
stickValueStage = SenetBoom.drawStickValue(currentStickValue);
mapStage.clear(); | package com.senetboom.game;
public class SenetBoom extends ApplicationAdapter {
// for the stage the bot moves a piece on
public static Group botMovingStage;
// for the empty tile texture
public static Texture emptyTexture;
// for the empty variables (the tiles that are currently moved by a bot)
public static int emptyVariable;
// for the possible moves that the bot uses for decision-making
// Array of int values
public static ArrayList<Integer> possibleMoves;
public static int possibleMove;
// for the batch
SpriteBatch batch;
// for the background
Texture background;
// for the currentStage
static Stage currentStage;
// stage options
public static boolean showOptions;
Stage OptionsStage;
// stage credit
boolean showCredits;
Stage CreditsStage;
// stick stage
public static Stage stickStage;
// typeWriterStage
public static Stage typeWriterStage;
// hitStage
Stage hitStage;
Animation<TextureRegion> hitAnimation;
// helpOverlayStage
static Stage helpOverlayStage;
Texture help;
public static boolean displayHelp;
Texture hand;
// for the pieces textures unselected
public static Texture blackpiece;
public static Texture whitepiece;
// for the turn constant
static Turn gameState;
// for the game boolean value of it having just started
public static boolean gameStarted;
// for the tileSize relative to screenSize from RelativeResizer
public static float tileSize;
// textures for special state
public static Texture happy;
public static Texture water;
public static Texture safe;
public static Texture rebirth;
// boolean determining if the game is in progress
public static boolean inGame;
// typewriter
public static Typewriter typeWriter;
// for knowing when to skip the Turn
public static boolean skipTurn;
public static Texture logo;
// for the textbutton skin
public static Skin skin;
// if the Sticks are Tumbling
public static boolean sticksTumbling;
// current Stick value
public static int currentStickValue;
// Sticks
public static Stick gameSticks;
//Game End Stage
public static Stage gameEndStage;
// legitMove boolean
public static boolean legitMove;
// rebirth protection
public static Texture rebirthProtection;
// for the music volume
public static float volume;
// texture for the tile
public static Texture tileTexture;
// map stage
public static Stage mapStage;
// boolean for an extra turn
public static boolean extraTurn;
// texture
public static Texture extraTurnTexture;
//stage for extra turn
public static Stage extraTurnStage;
// stick value Stage
private static Stage stickValueStage;
// textures for the sticks
public static Texture blackStick;
public static Texture whiteStick;
// number textures
public static Texture number0;
public static Texture number1;
public static Texture number2;
public static Texture number3;
public static Texture number4;
public static Texture number6;
// for the game start
public static boolean startUndecided;
public static Stage deciderStage;
// textures of starter
public static Texture whiteStarts;
public static Texture blackStarts;
// boolean for the decider
public static boolean deciderStarted;
// for when a turn has not been checked yet
public static boolean gameUnchecked;
// hint stage
public static Stage hintStage;
// for displaying the current Turn
public static Stage currentTurnStage;
// turn play textures
public static Texture whitePlays;
public static Texture blackPlays;
// texture for the help
public static Texture helpTexture;
// no moves texture
public static Texture noMovesTexture;
public static boolean displayHint = false;
public static Texture possibleMoveTexture;
public static boolean needRender;
// for the arms
public static Image armFromBelow;
public static Image armFromAbove;
// for the advanced arm stages and their respective boolean
public static Stage armFromBelowStage;
public static Stage armFromAboveStage;
public static boolean showArmFromBelowStage;
public static boolean showArmFromAboveStage;
public static MusicPlaylist musicPlaylist;
// enum of turn
private enum Turn {
PLAYERWHITE,
PLAYERBLACK,
}
@Override
public void create () {
batch = new SpriteBatch();
background = new Texture("textures/background.png");
// from scene2dUi
currentStage = new Stage();
showOptions = false;
OptionsStage = new Stage();
showCredits = false;
CreditsStage = new Stage();
inGame = false;
gameStarted = false;
gameEndStage = new Stage();
stickStage = new Stage();
typeWriterStage = new Stage();
hitStage = new Stage();
helpOverlayStage = new Stage();
mapStage = new Stage();
extraTurnStage = new Stage();
stickValueStage = new Stage();
deciderStage = new Stage();
hintStage = new Stage();
currentTurnStage = new Stage();
// for the arms
armFromBelowStage = new Stage();
armFromAboveStage = new Stage();
showArmFromBelowStage = false;
showArmFromAboveStage = false;
// possible Moves is a ArrayList of int values
possibleMoves = new ArrayList<Integer>();
displayHelp = false;
skipTurn = false;
sticksTumbling = false;
legitMove = false;
// loading the skin
skin = new Skin(Gdx.files.internal("menu.commodore64/uiskin.json"));
// loading all textures
blackpiece = new Texture("textures/blackpiece.png");
whitepiece = new Texture("textures/whitepiece.png");
happy = new Texture("textures/happy.png");
water = new Texture("textures/water.png");
safe = new Texture("textures/safe.png");
rebirth = new Texture("textures/rebirth.png");
rebirthProtection = new Texture("textures/rebirthprotection.png");
logo = new Texture("logoSenet.png");
tileTexture = new Texture("textures/tile.png");
emptyTexture = new Texture("textures/empty.png");
extraTurnTexture = new Texture("textures/extraTurn.png");
whiteStarts = new Texture("textures/whiteStart.png");
blackStarts = new Texture("textures/blackStarts.png");
// arms
armFromAboveStage = new Stage();
armFromBelowStage = new Stage();
armFromAbove = new Image(new Texture("textures/armabovein.png"));
armFromBelow = new Image(new Texture("textures/armbelowin.png"));
armFromAboveStage.addActor(armFromAbove);
armFromBelowStage.addActor(armFromBelow);
// for the sticks
blackStick = new Texture("textures/blackStick.png");
whiteStick = new Texture("textures/whiteStick.png");
// for the numbers
number0 = new Texture("textures/0.png");
number1 = new Texture("textures/1.png");
number2 = new Texture("textures/2.png");
number3 = new Texture("textures/3.png");
number4 = new Texture("textures/4.png");
number6 = new Texture("textures/6.png");
// possible Move Texture
possibleMoveTexture = new Texture("textures/possibleMove.png");
// no moves texture
noMovesTexture = new Texture("textures/noMovesTexture.png");
// help texture
helpTexture = new Texture("textures/rules.png");
// for the turn plays textures
whitePlays = new Texture("textures/whitePlays.png");
blackPlays = new Texture("textures/blackPlays.png");
// for the empty tile texture
emptyTexture = new Texture("textures/empty.png");
// music Playlist
volume = 0.5f;
musicPlaylist = new MusicPlaylist();
// from youtube: https://www.youtube.com/watch?v=nBmWXmn11YE
musicPlaylist.addSong("music/egyptreconstruct.mp3");
// from youtube: https://www.youtube.com/watch?v=mECTRQ0VEyU
musicPlaylist.addSong("music/egyptianmusic.mp3");
// from youtube: https://www.youtube.com/watch?v=d7jKP_JngC8
musicPlaylist.addSong("music/egyptianmusic2.mp3");
musicPlaylist.play();
// for the empty variable (the tile that is currently moved by a bot)
emptyVariable = -1;
// for the tileSize relative to screenSize from RelativeResizer
tileSize = 80;
gameState = Turn.PLAYERWHITE;
resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.input.setInputProcessor(currentStage);
createHelpStage(); // for the help overlay that can be activated
createMenu();
}
@Override
public void render () {
ScreenUtils.clear(1, 0, 0, 1);
batch.begin();
batch.draw(background, 0, 0);
batch.end();
if(needRender){
renderBoard();
needRender = false;
}
if(inGame){
mapStage.act();
mapStage.draw();
}
// from scene2dUi
currentStage.act();
currentStage.draw();
if(displayHelp){
helpOverlayStage.act();
helpOverlayStage.draw();
}
if (showOptions) {
OptionsStage.act();
OptionsStage.draw();
}
if (showCredits) {
CreditsStage.act();
CreditsStage.draw();
}
if(inGame){
// all stages affiliated with the game ongoing
if(gameStarted){
// decide who starts!
if(startUndecided){
if(!(deciderStarted)) {
// randomly decides the first turn state + displays this deciding on the screen
decideStarter();
}
// gets called till the timer in deciderStarter is up, then it sets startUndecided to false
deciderStage.act();
deciderStage.draw();
return;
}
updateLogoStage();
// first act of a new game:
// throw the sticks!
gameSticks = new Stick();
currentStickValue = gameSticks.getValue();
sticksTumbling = true;
// add the stickValueStage
stickValueStage = SenetBoom.drawStickValue(currentStickValue);
gameStarted = false;
}
// stick animation
stickStage.act();
stickStage.draw();
// for the explicit typewriter
typeWriterStage.act();
typeWriterStage.draw();
// for the switch animation (kinda like hit)
hitStage.act();
hitStage.draw();
// for the hints if displayHint turned on
if(displayHint) {
hintStage.act();
hintStage.draw();
}
// for the extra turn symbol
extraTurnStage.act();
extraTurnStage.draw();
// current turn stage
currentTurnStage.act();
currentTurnStage.draw();
if(!(sticksTumbling)) {
// display the current stick value if the sticks are not tumbling
stickValueStage.act();
stickValueStage.draw();
} else{
// waiting for the sticks to end tumbling ( its animation )
Stick.update(Gdx.graphics.getDeltaTime());
return;
}
// for the arms
if(showArmFromBelowStage) {
armFromBelowStage.act();
armFromBelowStage.draw();
}
if(showArmFromAboveStage) {
armFromAboveStage.act();
armFromAboveStage.draw();
}
// for the display of the game having ended
gameEndStage.act();
gameEndStage.draw();
// only if the sticks have stopped tumbling, and if the turn hasn't skipped,
// we can let a turn be processed
if (skipTurn) { // skip turn gets set to true if player pushed the skipTurn button
// add a typewriter of ANGER or CONFUSED or SAD
/* TODO
if (gameState == Turn.PLAYERWHITE)
typeWriter.makeSpeech(Typewriter.Emotion.ANGRY, Typewriter.Character.WHITE);
else
typeWriter.makeSpeech(Typewriter.Emotion.ANGRY, Typewriter.Character.BLACK);
*/
// other players turn
switchTurn();
skipTurn = false;
}
processTurn();
}
}
public void processTurn() {
// ----------------- legit Move part
// wait for a legitMove from a player of gameState
if(legitMove) {
// resets the legitMove check
legitMove = false;
// if not legitMove, waits for a legitMove switch around
// if legitMove, moves the piece in its respective dragStop Listener
// check if the game is over
checkForGameEnd();
// switch turn after completing the move
switchTurn();
}
}
private void switchTurn() {
// switch the turn
if(extraTurn){ // if extraTurn is true, do not switch turn
// player has an extra turn
extraTurn = false;
}
else { // switch turn
if (gameState == Turn.PLAYERWHITE) {
gameState = Turn.PLAYERBLACK;
} else {
gameState = Turn.PLAYERWHITE;
}
}
possibleMoves = new ArrayList<Integer>();
gameSticks = new Stick();
currentStickValue = gameSticks.getValue();
// ----------------- help part
// after thrown, check if any moves are even possible with the stick(dice) number
// if the next player has no moves possible, a slight hint gets added to the screen
// we run calculateMove on any piece of the player and if it returns null,
// the next player has no moves possible
if (gameState == Turn.PLAYERWHITE) {
// check if any moves are possible for the white player
// if not, add a hint to the screen
checkForNoMoves(Turn.PLAYERWHITE);
// if yes, remove the hint from the screen
} else {
// check if any moves are possible for the black player
// if not, add a hint to the screen
// if yes, remove the hint from the screen
checkForNoMoves(Turn.PLAYERBLACK);
}
// ----------------- end of help part
renderBoard();
// update move logo
updateLogoStage();
renderBoard();
Gdx.input.setInputProcessor(currentStage);
}
private static void checkForNoMoves(Turn turn) {
hintStage.clear();
// this method checks if the player has any moves possible
// if not, it adds a "No moves possible" Actor to the hint screen
boolean noMoves = true;
Tile[] gameBoard = Board.getBoard();
Piece.Color currentTurn = turn == Turn.PLAYERWHITE ? Piece.Color.WHITE : Piece.Color.BLACK;
for(Tile tiles: gameBoard){
if(tiles.hasPiece()){
if(tiles.getPiece().getColour() == currentTurn){
// if the piece is of the current turn
// check if it has any moves possible
if(tiles.isMoveValid(tiles.getPosition(), currentStickValue)){
// if yes, set noMoves to false
noMoves = false;
possibleMoves.add(tiles.getPosition()+currentStickValue);
}
}
}
}
if(noMoves){
// if noMoves is true, add a hint to the screen
Image noMove = new Image(noMovesTexture);
// add at Position middle low
noMove.setPosition((float) Gdx.graphics.getWidth() /2, tileSize*2);
hintStage.addActor(noMove);
// add a typewriter of ANGER or CONFUSED or SAD
// TODO
// render the board so that the possible Moves can be displayed on the screen
renderBoard();
}
}
// resize override
@Override
public void resize(int width, int height) {
// from scene2dUi
currentStage.getViewport().update(width, height, true);
if (showOptions) {
OptionsStage.getViewport().update(width, height, true);
}
if (showCredits) {
CreditsStage.getViewport().update(width, height, true);
}
if(inGame){
mapStage.getViewport().update(width, height, true);
stickStage.getViewport().update(width, height, true);
typeWriterStage.getViewport().update(width, height, true);
hitStage.getViewport().update(width, height, true);
helpOverlayStage.getViewport().update(width, height, true);
gameEndStage.getViewport().update(width, height, true);
extraTurnStage.getViewport().update(width, height, true);
stickValueStage.getViewport().update(width, height, true);
deciderStage.getViewport().update(width, height, true);
hintStage.getViewport().update(width, height, true);
currentTurnStage.getViewport().update(width, height, true);
armFromAboveStage.getViewport().update(width, height, true);
armFromBelowStage.getViewport().update(width, height, true);
}
}
private void updateLogoStage() {
// updates the logo according to the turn constant
// remove the old logo
currentTurnStage.clear();
Image currentTurner;
// add the new logo
if(gameState == Turn.PLAYERWHITE){
currentTurner = new Image(whitePlays);
} else {
currentTurner = new Image(blackPlays);
}
// upper left corner
currentTurner.setSize(tileSize*3, tileSize*2);
currentTurner.setPosition(tileSize*2, tileSize * 8);
currentTurnStage.addActor(currentTurner);
}
private void decideStarter() {
deciderStarted = true;
// random decide if turn White or black
int random = (int) (Math.random() * 2);
if(random == 0){
gameState = Turn.PLAYERWHITE;
} else {
gameState = Turn.PLAYERBLACK;
}
// adds the Decider to the stage
Decider decider = new Decider(gameState);
deciderStage.addActor(decider);
}
private class Decider extends Actor{
// after 2 seconds, it will set startDecided to true
float X;
float Y;
// elapsed time since addition to stage
float elapsed = 0;
// this is the maximum duration that the bubble will be on the screen
final float MAX_DURATION = 2f;
// this is the stack of the bubble
Stack stack;
public Decider(Turn turn){
this.stack = new Stack();
stack.setSize(tileSize*4, tileSize*2);
if(turn == Turn.PLAYERWHITE){
stack.addActor(new Image(whiteStarts));
} else {
stack.addActor(new Image(blackStarts));
}
this.X = tileSize*8;
this.Y = tileSize*8;
}
@Override
public void act(float delta) {
/*
* this method is called every frame to update the Actor
*/
super.act(delta);
elapsed += delta;
if (elapsed > MAX_DURATION) {
startUndecided = false;
remove(); // This will remove the actor from the stage
}
}
// Override the draw method to add the stack at the correct position
@Override
public void draw(Batch batch, float parentAlpha) {
/*
This method is called every frame to draw the starter indicator
*/
super.draw(batch, parentAlpha);
stack.setPosition(X, Y);
stack.draw(batch, parentAlpha);
}
}
@Override
public void dispose () {
batch.dispose();
background.dispose();
// dispose of all textures
blackpiece.dispose();
whitepiece.dispose();
happy.dispose();
water.dispose();
safe.dispose();
rebirth.dispose();
rebirthProtection.dispose();
logo.dispose();
tileTexture.dispose();
emptyTexture.dispose();
extraTurnTexture.dispose();
blackStick.dispose();
whiteStick.dispose();
number0.dispose();
number1.dispose();
number2.dispose();
number3.dispose();
number4.dispose();
number6.dispose();
whiteStarts.dispose();
blackStarts.dispose();
}
public static Coordinate calculatePXbyTile(int x) {
// the screen is 1536 to 896. The board is 3x10 tiles and each tile is 80x80px.
// the board is centered on the screen
int screenWidth = 1536;
int screenHeight = 896;
int boardWidth = (int) (tileSize * 10);
int boardHeight = (int) (tileSize * 3);
// Calculate starting position (upper left corner) of the board
int boardStartX = (screenWidth - boardWidth) / 2;
int boardStartY = (screenHeight - boardHeight) / 2;
int yCoord;
int xCoord;
// Calculate the tile's position
if(x <= 9){
yCoord = boardStartY + 80;
xCoord = boardStartX + (x * 80);
} else if (x <= 19){
yCoord = boardStartY;
xCoord = boardStartX + (10*80) - ((x-9)*80);
} else {
yCoord = boardStartY - (80);
xCoord = boardStartY * ((x-19) * 80);
}
return new Coordinate(xCoord, yCoord);
}
public static int calculateTilebyPx(int x, int y) {
int screenWidth = 1536;
int screenHeight = 896;
int inFuncTileSize = (int) tileSize;
int boardWidth = (inFuncTileSize * 10);
int boardHeight = (inFuncTileSize * 3);
// Calculate starting position (upper left corner) of the board
int boardStartX = (screenWidth - boardWidth) / 2;
int boardStartY = (screenHeight - boardHeight) / 2;
// Adjust the y-coordinate to reflect libGDX's bottom-left origin
int adjustedY = screenHeight - y;
// Calculate which tile
int tileX = (int) ((x - boardStartX) / inFuncTileSize);
int tileY = (int) ((adjustedY - boardStartY) / inFuncTileSize);
int tile;
if (tileY == 0) { // Top row
tile = tileX; // Tiles 0 to 9
} else if (tileY == 1) { // Middle row (reversed)
tile = 19 - tileX; // Tiles 19 to 10, in reverse
} else if (tileY == 2) { // Bottom row
tile = 20 + tileX; // Tiles 20 to 29
} else {
// Handle the case where the coordinates are outside the board
tile = -1;
}
return tile;
}
public static void createHelpStage() {
// load texture help
Image help = new Image(helpTexture);
help.setPosition(tileSize*13.1f, tileSize*2.7f);
help.setSize(tileSize*7, tileSize*9);
// add it to help stage
helpOverlayStage.addActor(help);
}
public static void createOptionsStage() {
}
public static Skin getSkin() {
return skin;
}
public static void renderBoard() {
stickValueStage.clear();
stickValueStage = SenetBoom.drawStickValue(currentStickValue);
mapStage.clear(); | mapStage = GameStage.drawMap(); | 2 | 2023-12-05 22:19:00+00:00 | 12k |
ItzOverS/CoReScreen | src/main/java/me/overlight/corescreen/Commands.java | [
{
"identifier": "AnalyzeModule",
"path": "src/main/java/me/overlight/corescreen/Analyzer/AnalyzeModule.java",
"snippet": "public class AnalyzeModule {\n public String getName() {\n return name;\n }\n\n private final String name;\n\n public AnalyzeModule(String name) {\n this.na... | import me.overlight.corescreen.Analyzer.AnalyzeModule;
import me.overlight.corescreen.Analyzer.AnalyzerManager;
import me.overlight.corescreen.ClientSettings.CSManager;
import me.overlight.corescreen.ClientSettings.CSModule;
import me.overlight.corescreen.Freeze.Cache.CacheManager;
import me.overlight.corescreen.Freeze.FreezeManager;
import me.overlight.corescreen.Freeze.Warps.WarpManager;
import me.overlight.corescreen.Profiler.ProfilerManager;
import me.overlight.corescreen.Profiler.Profiles.NmsHandler;
import me.overlight.corescreen.Profiler.ProfilingSystem;
import me.overlight.corescreen.Test.TestCheck;
import me.overlight.corescreen.Test.TestManager;
import me.overlight.corescreen.Vanish.VanishManager;
import me.overlight.corescreen.api.Freeze.PlayerFreezeEvent;
import me.overlight.corescreen.api.Freeze.PlayerUnfreezeEvent;
import me.overlight.powerlib.Chat.Text.impl.PlayerChatMessage;
import me.overlight.powerlib.Chat.Text.impl.ext.ClickableCommand;
import net.md_5.bungee.api.chat.BaseComponent;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors; | 9,024 | return false;
}
new BukkitRunnable(){
@Override
public void run() {
if(CoReScreen.getPlayer(commandSender.getName()) == null) {
cancel();
return;
}
if(CoReScreen.getPlayer(who.getName()) == null) {
cancel();
commandSender.sendMessage(CoReScreen.translate("messages.analyzer.analyzer-cancelled"));
return;
}
if(t >= delay * 10){
commandSender.sendMessage(prefix);
commandSender.sendMessage("§9Analyzer Result §9§l-------------");
module.result((Player) commandSender, who);
commandSender.sendMessage("§9§l--------------------------");
cancel();
return;
}
t++;
}
private int t = 0;
}.runTaskTimerAsynchronously(CoReScreen.getInstance(), 0, 2);
}
return false;
}
public static class TabComplete implements TabCompleter {
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String alias, String[] args) {
if (args.length == 1) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList());
if (args.length == 2) return AnalyzerManager.analyzers.stream().map(r -> r.getName().toLowerCase()).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList());
return null;
}
}
}
public static class ClientSettings implements CommandExecutor {
@Override
public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) {
if (args.length == 1) {
if (!commandSender.hasPermission("corescreen.clientsettings")) {
commandSender.sendMessage(CoReScreen.translate("messages.no-permission"));
return false;
}
if (!(commandSender instanceof Player)) {
commandSender.sendMessage(CoReScreen.translate("messages.only-players"));
return false;
}
Player who = CoReScreen.getPlayer(args[0]);
if (who == null) {
commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0]));
return false;
}
AtomicInteger i = new AtomicInteger(0);
CSManager.modules.forEach(module -> {
if (!commandSender.hasPermission("corescreen.clientsettings." + module.getPermission().toLowerCase())) {
commandSender.sendMessage(CoReScreen.translate("messages.client-settings.no-permission-to-setting").replace("%cs%", module.getName()));
return;
}
commandSender.sendMessage(CoReScreen.translate("messages.client-settings.chat-message-format").replace("%key%", module.getName()).replace("%value%", module.getValue(who)));
i.set(i.get() + 1);
});
if(i.get() == 0){
commandSender.sendMessage(CoReScreen.translate("messages.client-settings.no-permission-to-view-all"));
}
} else if (args.length == 2) {
if (!commandSender.hasPermission("corescreen.clientsettings")) {
commandSender.sendMessage(CoReScreen.translate("messages.no-permission"));
return false;
}
if (!(commandSender instanceof Player)) {
commandSender.sendMessage(CoReScreen.translate("messages.only-players"));
return false;
}
Player who = CoReScreen.getPlayer(args[0]);
if (who == null) {
commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0]));
return false;
}
Optional<CSModule> module = CSManager.modules.stream().filter(r -> r.getName().equalsIgnoreCase(args[1])).findFirst();
if(!module.isPresent()){
commandSender.sendMessage(CoReScreen.translate("messages.client-settings.invalid-client-setting"));
return false;
}
if(!commandSender.hasPermission("corescreen.clientsettings." + module.get().getPermission().toLowerCase())){
commandSender.sendMessage(CoReScreen.translate("messages.client-settings.no-permission-to-setting").replace("%cs%", module.get().getName()));
return false;
}
commandSender.sendMessage(CoReScreen.translate("messages.client-settings.chat-message-format").replace("%key%", module.get().getName()).replace("%value%", module.get().getValue(who)));
}
return false;
}
public static class TabComplete implements TabCompleter {
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String alias, String[] args) {
if (args.length == 1) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList());
if (args.length == 2) return CSManager.modules.stream().filter(r -> commandSender.hasPermission("corescreen.clientsettings." + r.getPermission())).map(r -> r.getName().toLowerCase()).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList());
return null;
}
}
}
public static class Freeze implements CommandExecutor {
@Override
public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) {
if (args.length == 1) {
if (!commandSender.hasPermission("corescreen.freeze")) {
commandSender.sendMessage(CoReScreen.translate("messages.no-permission"));
return false;
}
Player who = CoReScreen.getPlayer(args[0]);
if (who == null) {
commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0]));
return false;
} | package me.overlight.corescreen;
public class Commands {
public static String prefix;
public static class Vanish implements CommandExecutor {
private final HashMap<String, Long> cooldown_vanish = new HashMap<>();
private final HashMap<String, Long> cooldown_unvanish = new HashMap<>();
private final int vanishCooldown = CoReScreen.getInstance().getConfig().getInt("settings.vanish.command-cooldown.vanish"),
unvanishCooldown = CoReScreen.getInstance().getConfig().getInt("settings.vanish.command-cooldown.unvanish");
@Override
public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) {
if (args.length == 0) {
if (!commandSender.hasPermission("corescreen.vanish.self")) {
commandSender.sendMessage(CoReScreen.translate("messages.no-permission"));
return false;
}
if (!(commandSender instanceof Player)) {
commandSender.sendMessage(CoReScreen.translate("messages.only-players"));
return false;
}
if ((!VanishManager.isVanish((Player) commandSender) && System.currentTimeMillis() - cooldown_vanish.getOrDefault(commandSender.getName(), 0L) > vanishCooldown) ||
(VanishManager.isVanish((Player) commandSender) && System.currentTimeMillis() - cooldown_unvanish.getOrDefault(commandSender.getName(), 0L) > unvanishCooldown)) {
if(VanishManager.isVanish((Player) commandSender)) cooldown_unvanish.put(commandSender.getName(), System.currentTimeMillis());
else cooldown_vanish.put(commandSender.getName(), System.currentTimeMillis());
VanishManager.toggleVanish((Player) commandSender);
if (VanishManager.isVanish((Player) commandSender)) {
commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.you-are-vanish"));
DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-vanish")).setContent("**" + commandSender.getName() + "** has vanished they self!").execute();
} else {
commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.you-are-unvanish"));
DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-unvanish")).setContent("**" + commandSender.getName() + "** has un-vanished they self!").execute();
}
} else {
commandSender.sendMessage(CoReScreen.translate("settings.vanish.command-cooldown.message"));
}
} else if (args.length == 1) {
if (!commandSender.hasPermission("corescreen.vanish.other")) {
commandSender.sendMessage(CoReScreen.translate("messages.no-permission"));
return false;
}
List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList());
if (LWho.isEmpty()) {
commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0]));
return false;
}
Player who = LWho.get(0);
VanishManager.toggleVanish(who);
if (VanishManager.isVanish(who)) {
commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-vanish").replace("%who%", who.getName()));
DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-vanish")).setContent("**" + who.getName() + "** has vanished by **" + commandSender.getName() + "**!").execute();
} else {
commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-unvanish").replace("%who%", who.getName()));
DiscordWebhook.createDef(CoReScreen.getInstance().getConfig().getString("discord.webhooks.on-unvanish")).setContent("**" + who.getName() + "** has un-vanished by **" + commandSender.getName() + "**!").execute();
}
} else if (args.length == 2) {
if (!commandSender.hasPermission("corescreen.vanish.other")) {
commandSender.sendMessage(CoReScreen.translate("messages.no-permission"));
return false;
}
boolean forceEnabled = args[1].equalsIgnoreCase("on");
List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList());
if (LWho.isEmpty()) {
commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0]));
return false;
}
Player who = LWho.get(0);
if (forceEnabled) VanishManager.vanishPlayer(who);
else VanishManager.unVanishPlayer(who);
if (VanishManager.isVanish(who)) commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-vanish").replace("%who%", who.getName()));
else commandSender.sendMessage(CoReScreen.translate("messages.vanish.command.other-are-unvanish").replace("%who%", who.getName()));
}
return false;
}
public static class TabComplete implements TabCompleter {
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) {
if(args.length == 1 && commandSender.hasPermission("corescreen.vanish.other")) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList());
return null;
}
}
}
public static class Profiler implements CommandExecutor {
@Override
public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) {
if (args.length == 1 && args[0].equalsIgnoreCase("remove")) {
if (!commandSender.hasPermission("corescreen.profiler.remove")) {
commandSender.sendMessage(CoReScreen.translate("messages.no-permission"));
return false;
}
if (!(commandSender instanceof Player)) {
commandSender.sendMessage(CoReScreen.translate("messages.only-players"));
return false;
}
ProfilerManager.removeProfiler((Player) commandSender);
} else if (args.length == 2) {
if (!commandSender.hasPermission("corescreen.profiler.append")) {
commandSender.sendMessage(CoReScreen.translate("messages.no-permission"));
return false;
}
if (!(commandSender instanceof Player)) {
commandSender.sendMessage(CoReScreen.translate("messages.only-players"));
return false;
}
List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList());
if (LWho.isEmpty()) {
commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0]));
return false;
}
Player who = LWho.get(0);
try {
ProfilingSystem profiler = ProfilerManager.profilingSystems.stream().filter(r -> r.getName().equalsIgnoreCase(args[1])).collect(Collectors.toList()).get(0);
ProfilerManager.addProfiler((Player) commandSender, who, profiler.getMode());
commandSender.sendMessage(CoReScreen.translate("messages.profiler.profiler-success-add").replace("%who%", who.getName()).replace("%profiler%", args[1]));
} catch (Exception ex) {
if(NmsHandler.handlers.stream().anyMatch(r -> r.getName().equalsIgnoreCase(args[1]))){
ProfilerManager.addProfiler((Player) commandSender, who, NmsHandler.handlers.stream().filter(r -> r.getName().equalsIgnoreCase(args[1])).findFirst().get());
} else {
commandSender.sendMessage(CoReScreen.translate("messages.profiler.invalid-profiler-name").replace("%name%", args[1]));
}
}
}
return false;
}
public static class TabComplete implements TabCompleter {
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String alias, String[] args) {
if (args.length == 1) {
List<String> out = new ArrayList<>();
if(commandSender.hasPermission("corescreen.profiler.append")) out.addAll(Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()));
if(commandSender.hasPermission("corescreen.profiler.remove")) out.add("remove");
return out;
};
if (args.length == 2 && commandSender.hasPermission("corescreen.profiler.append")) {
List<String> out = new ArrayList<>(ProfilerManager.profilingSystems.stream().map(r -> r.getName().toLowerCase()).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList()));
out.addAll(NmsHandler.handlers.stream().map(NmsHandler.NmsWrapper::getName).collect(Collectors.toList()));
return out;
};
return null;
}
}
}
public static class Test implements CommandExecutor {
@Override
public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) {
if (args.length == 2) {
if (!commandSender.hasPermission("corescreen.test")) {
commandSender.sendMessage(CoReScreen.translate("messages.no-permission"));
return false;
}
if (!(commandSender instanceof Player)) {
commandSender.sendMessage(CoReScreen.translate("messages.only-players"));
return false;
}
List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList());
if (LWho.isEmpty()) {
commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0]));
return false;
}
Player who = LWho.get(0);
TestCheck test = null;
try {
test = TestManager.tests.stream().filter(r -> Arrays.asList(r.getAlias()).contains(args[1])).collect(Collectors.toList()).get(0);
} catch (Exception ex) {
}
if (test == null) {
commandSender.sendMessage(CoReScreen.translate("messages.test.test-not-found").replace("%test%", args[1]));
return false;
}
if (!commandSender.hasPermission("corescreen.test." + test.getName().toLowerCase())) {
commandSender.sendMessage(CoReScreen.translate("messages.no-permission"));
return false;
}
test.handle(who, (Player) commandSender);
}
return false;
}
public static class TabComplete implements TabCompleter {
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String alias, String[] args) {
if (args.length == 1) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList());
if (args.length == 2) return TestManager.tests.stream().map(r -> r.getAlias()[0].toLowerCase()).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList());
return null;
}
}
}
public static class Analyzer implements CommandExecutor {
@Override
public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) {
if (args.length == 2 || args.length == 3) {
if (!commandSender.hasPermission("corescreen.analyzer")) {
commandSender.sendMessage(CoReScreen.translate("messages.no-permission"));
return false;
}
if (!(commandSender instanceof Player)) {
commandSender.sendMessage(CoReScreen.translate("messages.only-players"));
return false;
}
List<Player> LWho = Bukkit.getOnlinePlayers().stream().filter(r -> r.getName().equals(args[0])).collect(Collectors.toList());
if (LWho.isEmpty()) {
commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0]));
return false;
}
Player who = LWho.get(0);
AnalyzeModule module = AnalyzerManager.analyzers.stream().filter(r -> r.getName().equalsIgnoreCase(args[1])).findFirst().orElse(null);
if (module == null) {
commandSender.sendMessage(CoReScreen.translate("messages.test.test-not-found").replace("%test%", args[1]));
return false;
}
if (!commandSender.hasPermission("corescreen.analyzer." + module.getName().toLowerCase())) {
commandSender.sendMessage(CoReScreen.translate("messages.analyzer.no-permission"));
return false;
}
module.activate(who);
commandSender.sendMessage(CoReScreen.translate("messages.analyzer.analyzing-started").replace("%player%", who.getName()));
int delay;
try {
delay = args.length == 2 ? 5 : Integer.parseInt(args[2]);
} catch(Exception ex) {
commandSender.sendMessage(CoReScreen.translate("messages.analyzer.illegal-number"));
return false;
}
if(!(delay >= 3 && delay <= 25)) {
commandSender.sendMessage(CoReScreen.translate("messages.analyzer.illegal-number"));
return false;
}
new BukkitRunnable(){
@Override
public void run() {
if(CoReScreen.getPlayer(commandSender.getName()) == null) {
cancel();
return;
}
if(CoReScreen.getPlayer(who.getName()) == null) {
cancel();
commandSender.sendMessage(CoReScreen.translate("messages.analyzer.analyzer-cancelled"));
return;
}
if(t >= delay * 10){
commandSender.sendMessage(prefix);
commandSender.sendMessage("§9Analyzer Result §9§l-------------");
module.result((Player) commandSender, who);
commandSender.sendMessage("§9§l--------------------------");
cancel();
return;
}
t++;
}
private int t = 0;
}.runTaskTimerAsynchronously(CoReScreen.getInstance(), 0, 2);
}
return false;
}
public static class TabComplete implements TabCompleter {
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String alias, String[] args) {
if (args.length == 1) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList());
if (args.length == 2) return AnalyzerManager.analyzers.stream().map(r -> r.getName().toLowerCase()).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList());
return null;
}
}
}
public static class ClientSettings implements CommandExecutor {
@Override
public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) {
if (args.length == 1) {
if (!commandSender.hasPermission("corescreen.clientsettings")) {
commandSender.sendMessage(CoReScreen.translate("messages.no-permission"));
return false;
}
if (!(commandSender instanceof Player)) {
commandSender.sendMessage(CoReScreen.translate("messages.only-players"));
return false;
}
Player who = CoReScreen.getPlayer(args[0]);
if (who == null) {
commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0]));
return false;
}
AtomicInteger i = new AtomicInteger(0);
CSManager.modules.forEach(module -> {
if (!commandSender.hasPermission("corescreen.clientsettings." + module.getPermission().toLowerCase())) {
commandSender.sendMessage(CoReScreen.translate("messages.client-settings.no-permission-to-setting").replace("%cs%", module.getName()));
return;
}
commandSender.sendMessage(CoReScreen.translate("messages.client-settings.chat-message-format").replace("%key%", module.getName()).replace("%value%", module.getValue(who)));
i.set(i.get() + 1);
});
if(i.get() == 0){
commandSender.sendMessage(CoReScreen.translate("messages.client-settings.no-permission-to-view-all"));
}
} else if (args.length == 2) {
if (!commandSender.hasPermission("corescreen.clientsettings")) {
commandSender.sendMessage(CoReScreen.translate("messages.no-permission"));
return false;
}
if (!(commandSender instanceof Player)) {
commandSender.sendMessage(CoReScreen.translate("messages.only-players"));
return false;
}
Player who = CoReScreen.getPlayer(args[0]);
if (who == null) {
commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0]));
return false;
}
Optional<CSModule> module = CSManager.modules.stream().filter(r -> r.getName().equalsIgnoreCase(args[1])).findFirst();
if(!module.isPresent()){
commandSender.sendMessage(CoReScreen.translate("messages.client-settings.invalid-client-setting"));
return false;
}
if(!commandSender.hasPermission("corescreen.clientsettings." + module.get().getPermission().toLowerCase())){
commandSender.sendMessage(CoReScreen.translate("messages.client-settings.no-permission-to-setting").replace("%cs%", module.get().getName()));
return false;
}
commandSender.sendMessage(CoReScreen.translate("messages.client-settings.chat-message-format").replace("%key%", module.get().getName()).replace("%value%", module.get().getValue(who)));
}
return false;
}
public static class TabComplete implements TabCompleter {
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String alias, String[] args) {
if (args.length == 1) return Bukkit.getOnlinePlayers().stream().map(Player::getName).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList());
if (args.length == 2) return CSManager.modules.stream().filter(r -> commandSender.hasPermission("corescreen.clientsettings." + r.getPermission())).map(r -> r.getName().toLowerCase()).filter(r -> r.startsWith(args[args.length - 1])).collect(Collectors.toList());
return null;
}
}
}
public static class Freeze implements CommandExecutor {
@Override
public boolean onCommand(CommandSender commandSender, org.bukkit.command.Command command, String alias, String[] args) {
if (args.length == 1) {
if (!commandSender.hasPermission("corescreen.freeze")) {
commandSender.sendMessage(CoReScreen.translate("messages.no-permission"));
return false;
}
Player who = CoReScreen.getPlayer(args[0]);
if (who == null) {
commandSender.sendMessage(CoReScreen.translate("messages.player-offline").replace("%who%", args[0]));
return false;
} | if (who.getName().equals(commandSender.getName()) && (commandSender instanceof Player && !FreezeManager.isFrozen((Player) commandSender))) { | 5 | 2023-12-07 16:34:39+00:00 | 12k |
fabriciofx/cactoos-pdf | src/test/java/com/github/fabriciofx/cactoos/pdf/pages/MarginsTest.java | [
{
"identifier": "Document",
"path": "src/main/java/com/github/fabriciofx/cactoos/pdf/Document.java",
"snippet": "public final class Document implements Bytes {\n /**\n * PDF Version.\n */\n private static final String VERSION = \"1.3\";\n\n /**\n * PDF binary file signature.\n *... | import com.github.fabriciofx.cactoos.pdf.Document;
import com.github.fabriciofx.cactoos.pdf.Font;
import com.github.fabriciofx.cactoos.pdf.Id;
import com.github.fabriciofx.cactoos.pdf.content.Contents;
import com.github.fabriciofx.cactoos.pdf.content.Text;
import com.github.fabriciofx.cactoos.pdf.id.Serial;
import com.github.fabriciofx.cactoos.pdf.object.Catalog;
import com.github.fabriciofx.cactoos.pdf.object.Information;
import com.github.fabriciofx.cactoos.pdf.page.DefaultPage;
import com.github.fabriciofx.cactoos.pdf.page.Format;
import com.github.fabriciofx.cactoos.pdf.resource.Resources;
import com.github.fabriciofx.cactoos.pdf.resource.font.TimesRoman;
import java.io.File;
import java.nio.file.Files;
import org.cactoos.bytes.BytesOf;
import org.cactoos.io.ResourceOf;
import org.cactoos.text.Joined;
import org.hamcrest.core.IsEqual;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.llorllale.cactoos.matchers.Assertion; | 9,003 | /*
* The MIT License (MIT)
*
* Copyright (C) 2023-2024 Fabrício Barros Cabral
*
* 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 NON-INFRINGEMENT. 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.github.fabriciofx.cactoos.pdf.pages;
/**
* Test case for {@link Margins}.
*
* @since 0.0.1
*/
final class MarginsTest {
@Test
void margins() throws Exception {
final Id id = new Serial(); | /*
* The MIT License (MIT)
*
* Copyright (C) 2023-2024 Fabrício Barros Cabral
*
* 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 NON-INFRINGEMENT. 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.github.fabriciofx.cactoos.pdf.pages;
/**
* Test case for {@link Margins}.
*
* @since 0.0.1
*/
final class MarginsTest {
@Test
void margins() throws Exception {
final Id id = new Serial(); | final org.cactoos.Text content = new Joined( | 4 | 2023-12-05 00:07:24+00:00 | 12k |
BeansGalaxy/Beans-Backpacks-2 | forge/src/main/java/com/beansgalaxy/backpacks/platform/ForgeNetworkHelper.java | [
{
"identifier": "BackpackInventory",
"path": "common/src/main/java/com/beansgalaxy/backpacks/core/BackpackInventory.java",
"snippet": "public interface BackpackInventory extends Container {\n\n Viewable getViewable();\n\n Entity getOwner();\n\n\n LocalData getLocalData();\n\n class V... | import com.beansgalaxy.backpacks.core.BackpackInventory;
import com.beansgalaxy.backpacks.entity.Backpack;
import com.beansgalaxy.backpacks.network.NetworkPackages;
import com.beansgalaxy.backpacks.network.client.SyncBackInventory2C;
import com.beansgalaxy.backpacks.network.client.SyncBackSlot2C;
import com.beansgalaxy.backpacks.network.client.SyncViewersPacket2C;
import com.beansgalaxy.backpacks.network.packages.SprintKeyPacket2S;
import com.beansgalaxy.backpacks.platform.services.NetworkHelper;
import com.beansgalaxy.backpacks.screen.BackSlot;
import com.beansgalaxy.backpacks.screen.BackpackMenu;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import org.jetbrains.annotations.Nullable; | 9,755 | package com.beansgalaxy.backpacks.platform;
public class ForgeNetworkHelper implements NetworkHelper {
@Override
public void SprintKey(boolean sprintKeyPressed) { | package com.beansgalaxy.backpacks.platform;
public class ForgeNetworkHelper implements NetworkHelper {
@Override
public void SprintKey(boolean sprintKeyPressed) { | NetworkPackages.C2S(new SprintKeyPacket2S(sprintKeyPressed)); | 2 | 2023-12-14 21:55:00+00:00 | 12k |
sinbad-navigator/erp-crm | common/src/main/java/com/ec/common/core/controller/BaseController.java | [
{
"identifier": "HttpStatus",
"path": "common/src/main/java/com/ec/common/constant/HttpStatus.java",
"snippet": "public class HttpStatus {\n /**\n * 操作成功\n */\n public static final int SUCCESS = 200;\n\n /**\n * 对象创建成功\n */\n public static final int CREATED = 201;\n\n /**\... | import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ec.common.constant.HttpStatus;
import com.ec.common.core.domain.AjaxResult;
import com.ec.common.core.domain.model.LoginUser;
import com.ec.common.core.page.PageDomain;
import com.ec.common.core.page.TableDataInfo;
import com.ec.common.core.page.TableSupport;
import com.ec.common.utils.DateUtils;
import com.ec.common.utils.PageUtils;
import com.ec.common.utils.SecurityUtils;
import com.ec.common.utils.StringUtils;
import com.ec.common.utils.sql.SqlUtil; | 10,192 | package com.ec.common.core.controller;
/**
* web层通用数据处理
*
* @author ec
*/
public class BaseController {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@InitBinder //@InitBinder 标注的方法名为 initBinder,它被用于将 WebDataBinder 对象进行初始化,用于将字符串类型的日期转换成 java.util.Date 类型。
public void initBinder(WebDataBinder binder) {
// Date 类型转换
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(DateUtils.parseDate(text));
}
});
}
/**
* 设置请求分页数据
*/
protected void startPage() { | package com.ec.common.core.controller;
/**
* web层通用数据处理
*
* @author ec
*/
public class BaseController {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@InitBinder //@InitBinder 标注的方法名为 initBinder,它被用于将 WebDataBinder 对象进行初始化,用于将字符串类型的日期转换成 java.util.Date 类型。
public void initBinder(WebDataBinder binder) {
// Date 类型转换
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(DateUtils.parseDate(text));
}
});
}
/**
* 设置请求分页数据
*/
protected void startPage() { | PageUtils.startPage(); | 7 | 2023-12-07 14:23:12+00:00 | 12k |
ganeshbabugb/NASC-CMS | src/main/java/com/nasc/application/views/marks/table/MarksView.java | [
{
"identifier": "AcademicYearEntity",
"path": "src/main/java/com/nasc/application/data/core/AcademicYearEntity.java",
"snippet": "@Data\n@Entity\n@Table(name = \"t_academic_year\")\npublic class AcademicYearEntity implements BaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY... | import com.flowingcode.vaadin.addons.fontawesome.FontAwesome;
import com.nasc.application.data.core.AcademicYearEntity;
import com.nasc.application.data.core.DepartmentEntity;
import com.nasc.application.data.core.SubjectEntity;
import com.nasc.application.data.core.User;
import com.nasc.application.data.core.dto.StudentMarksDTO;
import com.nasc.application.data.core.dto.StudentSubjectInfo;
import com.nasc.application.data.core.enums.ExamType;
import com.nasc.application.data.core.enums.Role;
import com.nasc.application.data.core.enums.Semester;
import com.nasc.application.data.core.enums.StudentSection;
import com.nasc.application.services.*;
import com.nasc.application.utils.NotificationUtils;
import com.nasc.application.utils.UIUtils;
import com.nasc.application.views.MainLayout;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.Html;
import com.vaadin.flow.component.Text;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.charts.Chart;
import com.vaadin.flow.component.charts.export.SVGGenerator;
import com.vaadin.flow.component.charts.model.*;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.combobox.ComboBoxVariant;
import com.vaadin.flow.component.contextmenu.ContextMenu;
import com.vaadin.flow.component.contextmenu.MenuItem;
import com.vaadin.flow.component.dependency.CssImport;
import com.vaadin.flow.component.dialog.Dialog;
import com.vaadin.flow.component.grid.ColumnTextAlign;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.GridVariant;
import com.vaadin.flow.component.grid.HeaderRow;
import com.vaadin.flow.component.grid.dataview.GridListDataView;
import com.vaadin.flow.component.gridpro.GridPro;
import com.vaadin.flow.component.gridpro.GridProVariant;
import com.vaadin.flow.component.html.H3;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.NumberField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.component.textfield.TextFieldVariant;
import com.vaadin.flow.data.provider.Query;
import com.vaadin.flow.data.renderer.TextRenderer;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.StreamResource;
import jakarta.annotation.security.RolesAllowed;
import lombok.extern.slf4j.Slf4j;
import org.vaadin.olli.FileDownloadWrapper;
import software.xdev.vaadin.grid_exporter.GridExporter;
import software.xdev.vaadin.grid_exporter.column.ColumnConfigurationBuilder;
import software.xdev.vaadin.grid_exporter.jasper.format.HtmlFormat;
import software.xdev.vaadin.grid_exporter.jasper.format.PdfFormat;
import software.xdev.vaadin.grid_exporter.jasper.format.XlsxFormat;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.function.Consumer; | 8,627 |
private boolean isFilterInValid() {
return examTypeComboBox.getValue() == null ||
semesterComboBox.getValue() == null ||
departmentComboBox.getValue() == null ||
academicYearComboBox.getValue() == null ||
studentSectionComboBox.getValue() == null;
}
private static Component createFilterHeader(Consumer<String> filterChangeConsumer) {
TextField textField = new TextField();
textField.setValueChangeMode(ValueChangeMode.EAGER);
textField.setClearButtonVisible(true);
textField.addThemeVariants(TextFieldVariant.LUMO_SMALL);
textField.setWidthFull();
// CASE IN SENSITIVE
textField.addValueChangeListener(e -> filterChangeConsumer.accept(e.getValue().toLowerCase()));
return textField;
}
private void configureComboBoxes() {
List<AcademicYearEntity> academicYears = academicYearService.findAll();
List<DepartmentEntity> departments = departmentService.findAll();
Semester[] semesters = Semester.values();
ExamType[] examTypes = ExamType.values();
StudentSection[] studentSections = StudentSection.values();
semesterComboBox.setItems(semesters);
semesterComboBox.setItemLabelGenerator(Semester::getDisplayName);
semesterComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);
semesterComboBox.setRequiredIndicatorVisible(true);
examTypeComboBox.setItems(examTypes);
examTypeComboBox.setItemLabelGenerator(ExamType::getDisplayName);
examTypeComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);
examTypeComboBox.setRequiredIndicatorVisible(true);
academicYearComboBox.setItems(academicYears);
academicYearComboBox.setItemLabelGenerator(item -> item.getStartYear() + " - " + item.getEndYear());
academicYearComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);
academicYearComboBox.setRequiredIndicatorVisible(true);
departmentComboBox.setItems(departments);
departmentComboBox.setItemLabelGenerator(item -> item.getName() + " - " + item.getShortName());
departmentComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);
departmentComboBox.setRequiredIndicatorVisible(true);
studentSectionComboBox.setItems(studentSections);
studentSectionComboBox.setItemLabelGenerator(StudentSection::getDisplayName);
studentSectionComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);
studentSectionComboBox.setRequiredIndicatorVisible(true);
}
private void updateTotalPassFailCounts(List<StudentMarksDTO> allStudentMarks, PassFailCounts counts) {
counts.totalPass = 0;
counts.totalFail = 0;
counts.totalPresent = 0;
counts.totalAbsent = 0;
counts.subjectPassCounts.clear();
counts.subjectFailCounts.clear();
counts.subjectPresentCounts.clear();
counts.subjectAbsentCounts.clear();
for (StudentMarksDTO studentMarksDTO : allStudentMarks) {
updateTotalPassFailCounts(studentMarksDTO, counts);
}
}
private void updateTotalPassFailCounts(StudentMarksDTO studentMarksDTO, PassFailCounts counts) {
for (Map.Entry<SubjectEntity, StudentSubjectInfo> entry : studentMarksDTO.getSubjectInfoMap().entrySet()) {
SubjectEntity subject = entry.getKey();
StudentSubjectInfo subjectInfo = entry.getValue();
if (subjectInfo.getMarks() != null && subjectInfo.getPassMarks() != null) {
boolean passed = subjectInfo.getMarks() >= subjectInfo.getPassMarks();
if (passed) {
counts.totalPass++;
counts.subjectPassCounts.put(subject, counts.subjectPassCounts.getOrDefault(subject, 0) + 1);
} else {
counts.totalFail++;
counts.subjectFailCounts.put(subject, counts.subjectFailCounts.getOrDefault(subject, 0) + 1);
}
}
// PRE & ABS
if (subjectInfo.getAbsent() != null) {
if (subjectInfo.getAbsent()) {
counts.totalAbsent++;
counts.subjectAbsentCounts.put(subject, counts.subjectAbsentCounts.getOrDefault(subject, 0) + 1);
} else {
counts.totalPresent++;
counts.subjectPresentCounts.put(subject, counts.subjectPresentCounts.getOrDefault(subject, 0) + 1);
}
}
}
}
private void updateGridData() {
// Clearing all the list that where in previous one!
contextMenu.removeAll();
ExamType selectedExamType = examTypeComboBox.getValue();
Semester selectedSemester = semesterComboBox.getValue();
DepartmentEntity selectedDepartment = departmentComboBox.getValue();
AcademicYearEntity selectedAcademicYear = academicYearComboBox.getValue();
StudentSection studentSection = studentSectionComboBox.getValue();
if (isAllFiltersNotNull(
selectedExamType,
selectedSemester,
selectedDepartment,
selectedAcademicYear,
studentSection
)) {
NotificationUtils.showErrorNotification("Please select values for all the filters!");
return;
}
// Set up grid data for all students | package com.nasc.application.views.marks.table;
@Route(value = "marks", layout = MainLayout.class)
@RolesAllowed({"HOD", "ADMIN", "PROFESSOR"})
@PageTitle("Marks")
@CssImport(
themeFor = "vaadin-grid",
value = "./recipe/gridcell/grid-cell.css"
)
@Slf4j
public class MarksView extends VerticalLayout {
// Service
private final MarksService marksService;
private final DepartmentService departmentService;
private final AcademicYearService academicYearService;
private final Button menuButton = new Button("Show/Hide Columns");
private final SubjectService subjectService;
private final UserService userService;
// Grid
private final GridPro<StudentMarksDTO> marksGrid = new GridPro<>(StudentMarksDTO.class);
private GridListDataView<StudentMarksDTO> dataProvider;
// Combobox
private final ComboBox<ExamType> examTypeComboBox = new ComboBox<>("Select Exam Type");
private final ComboBox<Semester> semesterComboBox = new ComboBox<>("Select Semester");
private final ComboBox<DepartmentEntity> departmentComboBox = new ComboBox<>("Select Department");
private final ComboBox<AcademicYearEntity> academicYearComboBox = new ComboBox<>("Select Academic Year");
private final ComboBox<StudentSection> studentSectionComboBox = new ComboBox<>("Select Student Section");
// UTILS
private final ColumnToggleContextMenu contextMenu = new ColumnToggleContextMenu(menuButton);
private final HeaderRow headerRow;
private GridExporter<StudentMarksDTO> gridExporter;
public MarksView(MarksService marksService,
DepartmentService departmentService,
AcademicYearService academicYearService,
SubjectService subjectService,
UserService userService
) {
this.marksService = marksService;
this.departmentService = departmentService;
this.academicYearService = academicYearService;
this.subjectService = subjectService;
this.userService = userService;
configureComboBoxes();
marksGrid.removeAllColumns();
marksGrid.setSizeFull();
marksGrid.setEditOnClick(true);
marksGrid.setSingleCellEdit(true);
marksGrid.setMultiSort(true);
marksGrid.addThemeVariants(GridVariant.LUMO_WRAP_CELL_CONTENT, GridVariant.LUMO_COLUMN_BORDERS);
marksGrid.addThemeVariants(GridProVariant.LUMO_ROW_STRIPES);
// marksGrid.setAllRowsVisible(true); // TO AVOID SCROLLER DISPLAY ALL THE ROWS
headerRow = marksGrid.appendHeaderRow();
// Button
Button searchButton = new Button("Search/Refresh");
searchButton.addClickListener(e -> updateGridData());
searchButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_SMALL);
menuButton.addThemeVariants(ButtonVariant.LUMO_TERTIARY, ButtonVariant.LUMO_SMALL);
HorizontalLayout filterLayout = new HorizontalLayout();
filterLayout.setAlignItems(Alignment.BASELINE);
filterLayout.add(
departmentComboBox,
academicYearComboBox,
semesterComboBox,
examTypeComboBox,
studentSectionComboBox,
searchButton
);
Button exportButton = new Button("Export",
FontAwesome.Solid.FILE_EXPORT.create(),
e -> {
ExamType selectedExamType = examTypeComboBox.getValue();
Semester selectedSemester = semesterComboBox.getValue();
DepartmentEntity selectedDepartment = departmentComboBox.getValue();
AcademicYearEntity selectedAcademicYear = academicYearComboBox.getValue();
StudentSection studentSection = studentSectionComboBox.getValue();
// Check Grid and Filter Before Export
int size = marksGrid.getDataProvider().size(new Query<>());
if (!isFilterInValid() && size > 0) {
String fileName = selectedDepartment.getShortName()
+ "_"
+ selectedAcademicYear.getStartYear() + "-" + selectedAcademicYear.getEndYear()
+ "_"
+ studentSection.getDisplayName()
+ "_"
+ selectedSemester.getDisplayName()
+ "_"
+ selectedExamType.getDisplayName() + "_Marks";
XlsxFormat xlsxFormat = new XlsxFormat();
PdfFormat pdfFormat = new PdfFormat();
HtmlFormat htmlFormat = new HtmlFormat();
gridExporter = GridExporter
.newWithDefaults(marksGrid)
.withFileName(fileName)
// Ignoring chart column
.withColumnFilter(studentMarksDTOColumn ->
studentMarksDTOColumn.isVisible() &&
!studentMarksDTOColumn.getKey().equals("Chart"))
.withAvailableFormats(xlsxFormat, pdfFormat, htmlFormat)
.withPreSelectedFormat(xlsxFormat)
.withColumnConfigurationBuilder(new ColumnConfigurationBuilder());
gridExporter.open();
}
}
);
exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL);
HorizontalLayout horizontalLayout = new HorizontalLayout(menuButton, exportButton);
horizontalLayout.setWidthFull();
horizontalLayout.setJustifyContentMode(JustifyContentMode.END);
horizontalLayout.setAlignItems(Alignment.CENTER);
add(new H3("Marks View"), filterLayout, horizontalLayout, marksGrid);
setSizeFull();
}
private boolean isFilterInValid() {
return examTypeComboBox.getValue() == null ||
semesterComboBox.getValue() == null ||
departmentComboBox.getValue() == null ||
academicYearComboBox.getValue() == null ||
studentSectionComboBox.getValue() == null;
}
private static Component createFilterHeader(Consumer<String> filterChangeConsumer) {
TextField textField = new TextField();
textField.setValueChangeMode(ValueChangeMode.EAGER);
textField.setClearButtonVisible(true);
textField.addThemeVariants(TextFieldVariant.LUMO_SMALL);
textField.setWidthFull();
// CASE IN SENSITIVE
textField.addValueChangeListener(e -> filterChangeConsumer.accept(e.getValue().toLowerCase()));
return textField;
}
private void configureComboBoxes() {
List<AcademicYearEntity> academicYears = academicYearService.findAll();
List<DepartmentEntity> departments = departmentService.findAll();
Semester[] semesters = Semester.values();
ExamType[] examTypes = ExamType.values();
StudentSection[] studentSections = StudentSection.values();
semesterComboBox.setItems(semesters);
semesterComboBox.setItemLabelGenerator(Semester::getDisplayName);
semesterComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);
semesterComboBox.setRequiredIndicatorVisible(true);
examTypeComboBox.setItems(examTypes);
examTypeComboBox.setItemLabelGenerator(ExamType::getDisplayName);
examTypeComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);
examTypeComboBox.setRequiredIndicatorVisible(true);
academicYearComboBox.setItems(academicYears);
academicYearComboBox.setItemLabelGenerator(item -> item.getStartYear() + " - " + item.getEndYear());
academicYearComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);
academicYearComboBox.setRequiredIndicatorVisible(true);
departmentComboBox.setItems(departments);
departmentComboBox.setItemLabelGenerator(item -> item.getName() + " - " + item.getShortName());
departmentComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);
departmentComboBox.setRequiredIndicatorVisible(true);
studentSectionComboBox.setItems(studentSections);
studentSectionComboBox.setItemLabelGenerator(StudentSection::getDisplayName);
studentSectionComboBox.addThemeVariants(ComboBoxVariant.LUMO_SMALL);
studentSectionComboBox.setRequiredIndicatorVisible(true);
}
private void updateTotalPassFailCounts(List<StudentMarksDTO> allStudentMarks, PassFailCounts counts) {
counts.totalPass = 0;
counts.totalFail = 0;
counts.totalPresent = 0;
counts.totalAbsent = 0;
counts.subjectPassCounts.clear();
counts.subjectFailCounts.clear();
counts.subjectPresentCounts.clear();
counts.subjectAbsentCounts.clear();
for (StudentMarksDTO studentMarksDTO : allStudentMarks) {
updateTotalPassFailCounts(studentMarksDTO, counts);
}
}
private void updateTotalPassFailCounts(StudentMarksDTO studentMarksDTO, PassFailCounts counts) {
for (Map.Entry<SubjectEntity, StudentSubjectInfo> entry : studentMarksDTO.getSubjectInfoMap().entrySet()) {
SubjectEntity subject = entry.getKey();
StudentSubjectInfo subjectInfo = entry.getValue();
if (subjectInfo.getMarks() != null && subjectInfo.getPassMarks() != null) {
boolean passed = subjectInfo.getMarks() >= subjectInfo.getPassMarks();
if (passed) {
counts.totalPass++;
counts.subjectPassCounts.put(subject, counts.subjectPassCounts.getOrDefault(subject, 0) + 1);
} else {
counts.totalFail++;
counts.subjectFailCounts.put(subject, counts.subjectFailCounts.getOrDefault(subject, 0) + 1);
}
}
// PRE & ABS
if (subjectInfo.getAbsent() != null) {
if (subjectInfo.getAbsent()) {
counts.totalAbsent++;
counts.subjectAbsentCounts.put(subject, counts.subjectAbsentCounts.getOrDefault(subject, 0) + 1);
} else {
counts.totalPresent++;
counts.subjectPresentCounts.put(subject, counts.subjectPresentCounts.getOrDefault(subject, 0) + 1);
}
}
}
}
private void updateGridData() {
// Clearing all the list that where in previous one!
contextMenu.removeAll();
ExamType selectedExamType = examTypeComboBox.getValue();
Semester selectedSemester = semesterComboBox.getValue();
DepartmentEntity selectedDepartment = departmentComboBox.getValue();
AcademicYearEntity selectedAcademicYear = academicYearComboBox.getValue();
StudentSection studentSection = studentSectionComboBox.getValue();
if (isAllFiltersNotNull(
selectedExamType,
selectedSemester,
selectedDepartment,
selectedAcademicYear,
studentSection
)) {
NotificationUtils.showErrorNotification("Please select values for all the filters!");
return;
}
// Set up grid data for all students | List<User> allStudents = userService.findStudentsByDepartmentAndRoleAndAcademicYearAndSection( | 3 | 2023-12-10 18:07:28+00:00 | 12k |
Viola-Siemens/StellarForge | src/main/java/com/hexagram2021/stellarforge/StellarForge.java | [
{
"identifier": "ClientProxy",
"path": "src/main/java/com/hexagram2021/stellarforge/client/ClientProxy.java",
"snippet": "@Mod.EventBusSubscriber(value = Dist.CLIENT, modid = MODID, bus = Mod.EventBusSubscriber.Bus.MOD)\npublic class ClientProxy {\n\tpublic static void modConstruction() {\n\t}\n\n\t@Sub... | import com.hexagram2021.stellarforge.client.ClientProxy;
import com.hexagram2021.stellarforge.common.SFContent;
import com.hexagram2021.stellarforge.common.config.SFCommonConfig;
import com.hexagram2021.stellarforge.common.util.RegistryChecker;
import com.hexagram2021.stellarforge.common.util.SFLogger;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.server.ServerAboutToStartEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.loading.FMLLoader;
import org.apache.logging.log4j.LogManager;
import java.util.function.Supplier; | 7,412 | package com.hexagram2021.stellarforge;
@Mod(StellarForge.MODID)
public class StellarForge {
public static final String MODID = "stellarforge";
public static final String MODNAME = "StellarForge";
public static final String VERSION = ModList.get().getModFileById(MODID).versionString();
public static <T>
Supplier<T> bootstrapErrorToXCPInDev(Supplier<T> in) {
if(FMLLoader.isProduction()) {
return in;
}
return () -> {
try {
return in.get();
} catch(BootstrapMethodError e) {
throw new RuntimeException(e);
}
};
}
public StellarForge() {
SFLogger.logger = LogManager.getLogger(MODID);
IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
SFContent.modConstruction(bus);
DistExecutor.safeRunWhenOn(Dist.CLIENT, bootstrapErrorToXCPInDev(() -> ClientProxy::modConstruction));
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, SFCommonConfig.getConfig());
bus.addListener(SFContent::onNewRegistry);
MinecraftForge.EVENT_BUS.addListener(SFContent::registerCommands);
MinecraftForge.EVENT_BUS.addListener(this::onServerAboutToStart);
MinecraftForge.EVENT_BUS.register(this);
}
private void onServerAboutToStart(ServerAboutToStartEvent event) {
if(SFCommonConfig.ENABLE_REGISTRY_CHECK.get()) { | package com.hexagram2021.stellarforge;
@Mod(StellarForge.MODID)
public class StellarForge {
public static final String MODID = "stellarforge";
public static final String MODNAME = "StellarForge";
public static final String VERSION = ModList.get().getModFileById(MODID).versionString();
public static <T>
Supplier<T> bootstrapErrorToXCPInDev(Supplier<T> in) {
if(FMLLoader.isProduction()) {
return in;
}
return () -> {
try {
return in.get();
} catch(BootstrapMethodError e) {
throw new RuntimeException(e);
}
};
}
public StellarForge() {
SFLogger.logger = LogManager.getLogger(MODID);
IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
SFContent.modConstruction(bus);
DistExecutor.safeRunWhenOn(Dist.CLIENT, bootstrapErrorToXCPInDev(() -> ClientProxy::modConstruction));
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, SFCommonConfig.getConfig());
bus.addListener(SFContent::onNewRegistry);
MinecraftForge.EVENT_BUS.addListener(SFContent::registerCommands);
MinecraftForge.EVENT_BUS.addListener(this::onServerAboutToStart);
MinecraftForge.EVENT_BUS.register(this);
}
private void onServerAboutToStart(ServerAboutToStartEvent event) {
if(SFCommonConfig.ENABLE_REGISTRY_CHECK.get()) { | RegistryChecker.registryCheck(event.getServer().getLootData()); | 3 | 2023-12-10 07:20:43+00:00 | 12k |
gaetanBloch/jhlite-gateway | src/main/java/com/mycompany/myapp/shared/pagination/domain/JhipsterSampleApplicationPage.java | [
{
"identifier": "JhipsterSampleApplicationCollections",
"path": "src/main/java/com/mycompany/myapp/shared/collection/domain/JhipsterSampleApplicationCollections.java",
"snippet": "public final class JhipsterSampleApplicationCollections {\n\n private JhipsterSampleApplicationCollections() {}\n\n /**\n ... | import java.util.List;
import java.util.function.Function;
import com.mycompany.myapp.shared.collection.domain.JhipsterSampleApplicationCollections;
import com.mycompany.myapp.shared.error.domain.Assert; | 10,398 | package com.mycompany.myapp.shared.pagination.domain;
public class JhipsterSampleApplicationPage<T> {
private static final int MINIMAL_PAGE_COUNT = 1;
private final List<T> content;
private final int currentPage;
private final int pageSize;
private final long totalElementsCount;
private JhipsterSampleApplicationPage(JhipsterSampleApplicationPageBuilder<T> builder) { | package com.mycompany.myapp.shared.pagination.domain;
public class JhipsterSampleApplicationPage<T> {
private static final int MINIMAL_PAGE_COUNT = 1;
private final List<T> content;
private final int currentPage;
private final int pageSize;
private final long totalElementsCount;
private JhipsterSampleApplicationPage(JhipsterSampleApplicationPageBuilder<T> builder) { | content = JhipsterSampleApplicationCollections.immutable(builder.content); | 0 | 2023-12-10 06:39:18+00:00 | 12k |
zerodevstuff/ExploitFixerv2 | src/main/java/dev/_2lstudios/exploitfixer/managers/ModuleManager.java | [
{
"identifier": "NotificationsModule",
"path": "src/main/java/dev/_2lstudios/exploitfixer/modules/NotificationsModule.java",
"snippet": "public class NotificationsModule extends Module {\n private Server server;\n private Logger logger;\n private Map<String, Integer> packetDebug = new HashMap<>... | import java.io.File;
import java.util.logging.Logger;
import org.bukkit.Server;
import org.bukkit.plugin.Plugin;
import dev._2lstudios.exploitfixer.modules.NotificationsModule;
import dev._2lstudios.exploitfixer.modules.ItemAnalysisModule;
import dev._2lstudios.exploitfixer.modules.PatcherModule;
import dev._2lstudios.exploitfixer.utils.ConfigUtil;
import dev._2lstudios.exploitfixer.modules.CreativeItemsFixModule;
import dev._2lstudios.exploitfixer.configuration.IConfiguration;
import dev._2lstudios.exploitfixer.modules.CommandsModule;
import dev._2lstudios.exploitfixer.modules.ConnectionModule;
import dev._2lstudios.exploitfixer.modules.MessagesModule;
import dev._2lstudios.exploitfixer.modules.PacketsModule; | 7,333 | package dev._2lstudios.exploitfixer.managers;
public class ModuleManager {
private Plugin plugin; | package dev._2lstudios.exploitfixer.managers;
public class ModuleManager {
private Plugin plugin; | private CommandsModule commandsModule; | 6 | 2023-12-13 21:49:27+00:00 | 12k |
xuexu2/Crasher | src/main/java/cn/sn0wo/crasher/utils/Utils.java | [
{
"identifier": "Crasher",
"path": "src/main/java/cn/sn0wo/crasher/Crasher.java",
"snippet": "public final class Crasher extends JavaPlugin {\n\n public Crasher() {\n Utils.utils = new Utils(this);\n }\n\n @Override\n public void onLoad() {\n getLogger().info(\"Loaded \" + getD... | import cn.sn0wo.crasher.Crasher;
import cn.sn0wo.crasher.bstats.Metrics;
import cn.sn0wo.crasher.commands.Crash;
import cn.sn0wo.crasher.datas.DataManager;
import cn.sn0wo.crasher.listener.PlayerListener;
import cn.sn0wo.crasher.tasks.CheckUpdate;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.scheduler.BukkitRunnable;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
| 8,600 | package cn.sn0wo.crasher.utils;
public final class Utils {
public static Utils utils;
public final Map<UUID, Queue<Object>> packetQueues = new HashMap<>();
public final Map<UUID, Queue<Object>> packetReviveQueues = new HashMap<>();
public final Set<UUID> crashSet = new HashSet<>();
public final Set<UUID> frozenSet = new HashSet<>();
public Crasher instance;
public Metrics metrics;
public DataManager dataManager;
private String serverVersion;
public Utils(final Crasher instance) {
this.instance = instance;
instance.saveResource("eula.txt", false);
final FileConfiguration eulaConfig = YamlConfiguration.loadConfiguration(new File(instance.getDataFolder(), "eula.txt"));
if (!eulaConfig.getBoolean("eula")) {
instance.getLogger().info("您同意eula.txt, 若您同意需要将eula: false改为eula: true");
Bukkit.shutdown();
System.exit(0);
return;
}
instance.getLogger().info("Your server version: " + getServerVersion());
if (!getServerVersion().equals("v1_8_R3")) {
instance.getLogger().severe("Your server version is not support! [?Plugin has unknown bug?]");
instance.getLogger().warning("If you are using 1.20+ server version will not support!");
}
if (instance.getConfig().getBoolean("Debug.bStats")) {
metrics = new Metrics(instance, 20432);
}
}
public void setupPlugin() {
instance.saveDefaultConfig();
if (!instance.getDescription().getVersion().equals(instance.getConfig().getString("Debug.CfgVer"))) {
instance.getLogger().severe("Your config version is not support! Config Version: " + instance.getConfig().getString("Debug.CfgVer"));
}
dataManager = new DataManager();
Bukkit.getPluginManager().registerEvents(new PlayerListener(), instance);
| package cn.sn0wo.crasher.utils;
public final class Utils {
public static Utils utils;
public final Map<UUID, Queue<Object>> packetQueues = new HashMap<>();
public final Map<UUID, Queue<Object>> packetReviveQueues = new HashMap<>();
public final Set<UUID> crashSet = new HashSet<>();
public final Set<UUID> frozenSet = new HashSet<>();
public Crasher instance;
public Metrics metrics;
public DataManager dataManager;
private String serverVersion;
public Utils(final Crasher instance) {
this.instance = instance;
instance.saveResource("eula.txt", false);
final FileConfiguration eulaConfig = YamlConfiguration.loadConfiguration(new File(instance.getDataFolder(), "eula.txt"));
if (!eulaConfig.getBoolean("eula")) {
instance.getLogger().info("您同意eula.txt, 若您同意需要将eula: false改为eula: true");
Bukkit.shutdown();
System.exit(0);
return;
}
instance.getLogger().info("Your server version: " + getServerVersion());
if (!getServerVersion().equals("v1_8_R3")) {
instance.getLogger().severe("Your server version is not support! [?Plugin has unknown bug?]");
instance.getLogger().warning("If you are using 1.20+ server version will not support!");
}
if (instance.getConfig().getBoolean("Debug.bStats")) {
metrics = new Metrics(instance, 20432);
}
}
public void setupPlugin() {
instance.saveDefaultConfig();
if (!instance.getDescription().getVersion().equals(instance.getConfig().getString("Debug.CfgVer"))) {
instance.getLogger().severe("Your config version is not support! Config Version: " + instance.getConfig().getString("Debug.CfgVer"));
}
dataManager = new DataManager();
Bukkit.getPluginManager().registerEvents(new PlayerListener(), instance);
| instance.getCommand("Crash").setExecutor(new Crash());
| 2 | 2023-12-05 15:08:54+00:00 | 12k |
Crydsch/the-one | src/report/RadiusOfGyrationReport.java | [
{
"identifier": "Coord",
"path": "src/core/Coord.java",
"snippet": "public class Coord implements Cloneable, Comparable<Coord> {\n\tprivate double x;\n\tprivate double y;\n\n\t/**\n\t * Constructor.\n\t * @param x Initial X-coordinate\n\t * @param y Initial Y-coordinate\n\t */\n\tpublic Coord(double x, ... | import core.Coord;
import core.DTNHost;
import core.SimScenario;
import java.util.List; | 9,059 | package report;
/**
* <p>Calculates the radius of gyration for all the nodes in the simulation. The
* radius of gyration is calculated by sampling the simulation at fixed
* intervals (defined by the '{@link SamplingReport#SAMPLE_INTERVAL_SETTING}'
* setting) to record the position of all the nodes. For each node, the
* center of the mass of the trajectory is calculated from the samples. The
* radius of gyration is the standard deviation of the distance of the
* samples from the center of the mass of the trajectory.
* </p>
*
* <p>In other words, for each node:
* r_g = sqrt( 1/n * sum_i( distance( r_i, r_cm )^2 ) ),
* where r_g is the radius of gyration, n is the number of samples, r_i is the
* coordinate of the sample i of the trajectory, r_cm is the coordinate of
* the center of mass of the samples:
* r_cm = 1/n * sum_i( r_i ).</p>
*
* <p>The output line format is: "node_id node_name r_cm_x r_cm_y r_g"</p>
*
* @author teemuk
*/
public final class RadiusOfGyrationReport
extends SamplingReport {
//========================================================================//
// Instance vars
//========================================================================//
private final double[][][] samples;
private final int[] sampleCounts;
private final String[] nodeNames;
//========================================================================//
//========================================================================//
// Report implementation
//========================================================================//
public RadiusOfGyrationReport() {
super();
final SimScenario simScenario = SimScenario.getInstance();
final int nodeCount = simScenario.getHosts().size();
final double simDuration = simScenario.getEndTime();
final int numSamples = (int) Math.ceil(simDuration / super.interval);
this.samples = new double[nodeCount][numSamples][2];
this.sampleCounts = new int[nodeCount];
this.nodeNames = new String[nodeCount];
int i = 0; | package report;
/**
* <p>Calculates the radius of gyration for all the nodes in the simulation. The
* radius of gyration is calculated by sampling the simulation at fixed
* intervals (defined by the '{@link SamplingReport#SAMPLE_INTERVAL_SETTING}'
* setting) to record the position of all the nodes. For each node, the
* center of the mass of the trajectory is calculated from the samples. The
* radius of gyration is the standard deviation of the distance of the
* samples from the center of the mass of the trajectory.
* </p>
*
* <p>In other words, for each node:
* r_g = sqrt( 1/n * sum_i( distance( r_i, r_cm )^2 ) ),
* where r_g is the radius of gyration, n is the number of samples, r_i is the
* coordinate of the sample i of the trajectory, r_cm is the coordinate of
* the center of mass of the samples:
* r_cm = 1/n * sum_i( r_i ).</p>
*
* <p>The output line format is: "node_id node_name r_cm_x r_cm_y r_g"</p>
*
* @author teemuk
*/
public final class RadiusOfGyrationReport
extends SamplingReport {
//========================================================================//
// Instance vars
//========================================================================//
private final double[][][] samples;
private final int[] sampleCounts;
private final String[] nodeNames;
//========================================================================//
//========================================================================//
// Report implementation
//========================================================================//
public RadiusOfGyrationReport() {
super();
final SimScenario simScenario = SimScenario.getInstance();
final int nodeCount = simScenario.getHosts().size();
final double simDuration = simScenario.getEndTime();
final int numSamples = (int) Math.ceil(simDuration / super.interval);
this.samples = new double[nodeCount][numSamples][2];
this.sampleCounts = new int[nodeCount];
this.nodeNames = new String[nodeCount];
int i = 0; | for (final DTNHost host : simScenario.getHosts()) { | 1 | 2023-12-10 15:51:41+00:00 | 12k |
seleuco/MAME4droid-2024 | android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/helpers/SAFHelper.java | [
{
"identifier": "Emulator",
"path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/Emulator.java",
"snippet": "public class Emulator {\n\n\t//gets\n\tfinal static public int IN_MENU = 1;\n\tfinal static public int IN_GAME = 2;\n\tfinal static public int NUMBTNS = 3;\n\tfinal static public ... | import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.provider.DocumentsContract;
import android.util.Log;
import com.seleuco.mame4droid.Emulator;
import com.seleuco.mame4droid.MAME4droid;
import com.seleuco.mame4droid.progress.ProgressWidget;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List; | 9,553 | /*
* This file is part of MAME4droid.
*
* Copyright (C) 2023 David Valdeita (Seleuco)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>.
*
* Linking MAME4droid statically or dynamically with other modules is
* making a combined work based on MAME4droid. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* In addition, as a special exception, the copyright holders of MAME4droid
* give you permission to combine MAME4droid with free software programs
* or libraries that are released under the GNU LGPL and with code included
* in the standard release of MAME under the MAME License (or modified
* versions of such code, with unchanged license). You may copy and
* distribute such a system following the terms of the GNU GPL for MAME4droid
* and the licenses of the other code concerned, provided that you include
* the source code of that other code when and as the GNU GPL requires
* distribution of source code.
*
* Note that people who make modified versions of MAME4idroid are not
* obligated to grant this special exception for their modified versions; it
* is their choice whether to do so. The GNU General Public License
* gives permission to release a modified version without this exception;
* this exception also makes it possible to release a modified version
* which carries forward this exception.
*
* MAME4droid is dual-licensed: Alternatively, you can license MAME4droid
* under a MAME license, as set out in http://mamedev.org/
*/
package com.seleuco.mame4droid.helpers;
class DirEnt{
private static int lastId = 1;
DirEnt(){this.id = lastId++;}
int id = 0;
int fileNameIdx = 0;
ArrayList fileNames = null;
}
public class SAFHelper {
static protected MAME4droid mm = null;
static Uri uri = null;
static protected Hashtable<String, String> fileIDs = null; //hago estatico para evitar reloads si la actividad se recrea
static protected Hashtable<String,ArrayList<String>> dirFiles = null;
protected Hashtable<Integer,DirEnt> openDirs = new Hashtable<Integer, DirEnt>();
| /*
* This file is part of MAME4droid.
*
* Copyright (C) 2023 David Valdeita (Seleuco)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>.
*
* Linking MAME4droid statically or dynamically with other modules is
* making a combined work based on MAME4droid. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* In addition, as a special exception, the copyright holders of MAME4droid
* give you permission to combine MAME4droid with free software programs
* or libraries that are released under the GNU LGPL and with code included
* in the standard release of MAME under the MAME License (or modified
* versions of such code, with unchanged license). You may copy and
* distribute such a system following the terms of the GNU GPL for MAME4droid
* and the licenses of the other code concerned, provided that you include
* the source code of that other code when and as the GNU GPL requires
* distribution of source code.
*
* Note that people who make modified versions of MAME4idroid are not
* obligated to grant this special exception for their modified versions; it
* is their choice whether to do so. The GNU General Public License
* gives permission to release a modified version without this exception;
* this exception also makes it possible to release a modified version
* which carries forward this exception.
*
* MAME4droid is dual-licensed: Alternatively, you can license MAME4droid
* under a MAME license, as set out in http://mamedev.org/
*/
package com.seleuco.mame4droid.helpers;
class DirEnt{
private static int lastId = 1;
DirEnt(){this.id = lastId++;}
int id = 0;
int fileNameIdx = 0;
ArrayList fileNames = null;
}
public class SAFHelper {
static protected MAME4droid mm = null;
static Uri uri = null;
static protected Hashtable<String, String> fileIDs = null; //hago estatico para evitar reloads si la actividad se recrea
static protected Hashtable<String,ArrayList<String>> dirFiles = null;
protected Hashtable<Integer,DirEnt> openDirs = new Hashtable<Integer, DirEnt>();
| protected ProgressWidget pw = null; | 2 | 2023-12-18 11:16:18+00:00 | 12k |
John200410/rusherhack-spotify | src/main/java/me/john200410/spotify/ui/SpotifyHudElement.java | [
{
"identifier": "SpotifyPlugin",
"path": "src/main/java/me/john200410/spotify/SpotifyPlugin.java",
"snippet": "public class SpotifyPlugin extends Plugin {\n\t\n\tpublic static final File CONFIG_FILE = RusherHackAPI.getConfigPath().resolve(\"spotify.json\").toFile();\n\tpublic static final Gson GSON = ne... | import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import joptsimple.internal.Strings;
import me.john200410.spotify.SpotifyPlugin;
import me.john200410.spotify.http.SpotifyAPI;
import me.john200410.spotify.http.responses.PlaybackState;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.ChatScreen;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.resources.ResourceLocation;
import org.lwjgl.glfw.GLFW;
import org.rusherhack.client.api.bind.key.GLFWKey;
import org.rusherhack.client.api.events.client.input.EventMouse;
import org.rusherhack.client.api.feature.hud.ResizeableHudElement;
import org.rusherhack.client.api.render.IRenderer2D;
import org.rusherhack.client.api.render.RenderContext;
import org.rusherhack.client.api.render.font.IFontRenderer;
import org.rusherhack.client.api.render.graphic.VectorGraphic;
import org.rusherhack.client.api.setting.BindSetting;
import org.rusherhack.client.api.setting.ColorSetting;
import org.rusherhack.client.api.ui.ScaledElementBase;
import org.rusherhack.client.api.utils.InputUtils;
import org.rusherhack.core.bind.key.NullKey;
import org.rusherhack.core.event.stage.Stage;
import org.rusherhack.core.event.subscribe.Subscribe;
import org.rusherhack.core.interfaces.IClickable;
import org.rusherhack.core.setting.BooleanSetting;
import org.rusherhack.core.setting.NumberSetting;
import org.rusherhack.core.utils.ColorUtils;
import org.rusherhack.core.utils.MathUtils;
import org.rusherhack.core.utils.Timer;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse; | 7,792 | package me.john200410.spotify.ui;
/**
* @author John200410
*/
public class SpotifyHudElement extends ResizeableHudElement {
public static final int BACKGROUND_COLOR = ColorUtils.transparency(Color.BLACK.getRGB(), 0.5f);
private static final PlaybackState.Item AI_DJ_SONG = new PlaybackState.Item(); //item that is displayed when the DJ is talking
static {
AI_DJ_SONG.album = new PlaybackState.Item.Album();
AI_DJ_SONG.artists = new PlaybackState.Item.Artist[1];
AI_DJ_SONG.album.images = new PlaybackState.Item.Album.Image[1];
AI_DJ_SONG.artists[0] = new PlaybackState.Item.Artist();
AI_DJ_SONG.album.images[0] = new PlaybackState.Item.Album.Image();
AI_DJ_SONG.artists[0].name = "Spotify";
AI_DJ_SONG.album.name = "Songs Made For You";
AI_DJ_SONG.name = AI_DJ_SONG.id = "DJ";
AI_DJ_SONG.duration_ms = 30000;
AI_DJ_SONG.album.images[0].url = "https://i.imgur.com/29vr8jz.png";
AI_DJ_SONG.album.images[0].width = 640;
AI_DJ_SONG.album.images[0].height = 640;
AI_DJ_SONG.uri = "";
}
/**
* Settings
*/
private final BooleanSetting authenticateButton = new BooleanSetting("Authenticate", true)
.setVisibility(() -> !this.isConnected());
private final BooleanSetting background = new BooleanSetting("Background", true);
private final ColorSetting backgroundColor = new ColorSetting("Color", new Color(BACKGROUND_COLOR, true));
private final NumberSetting<Double> updateDelay = new NumberSetting<>("UpdateDelay", 0.5d, 0.25d, 2d);
private final BooleanSetting binds = new BooleanSetting("Binds", false);
private final BindSetting playPauseBind = new BindSetting("Play/Pause", NullKey.INSTANCE);
private final BindSetting backBind = new BindSetting("Back", NullKey.INSTANCE);
private final BindSetting nextBind = new BindSetting("Next", NullKey.INSTANCE);
private final BindSetting back5Bind = new BindSetting("Back 5", NullKey.INSTANCE);
private final BindSetting next5Bind = new BindSetting("Next 5", NullKey.INSTANCE);
/**
* Media Controller
*/
private final SongInfoHandler songInfo;
private final DurationHandler duration;
private final MediaControllerHandler mediaController;
/**
* Variables
*/
private final VectorGraphic spotifyLogo;
private final ResourceLocation trackThumbnailResourceLocation;
private final DynamicTexture trackThumbnailTexture;
private final SpotifyPlugin plugin;
private PlaybackState.Item song = null;
private boolean consumedButtonClick = false;
private Boolean ai = false;
public SpotifyHudElement(SpotifyPlugin plugin) throws IOException {
super("Spotify");
this.plugin = plugin;
this.mediaController = new MediaControllerHandler();
this.duration = new DurationHandler();
this.songInfo = new SongInfoHandler();
this.spotifyLogo = new VectorGraphic("spotify/graphics/spotify_logo.svg", 32, 32);
this.trackThumbnailTexture = new DynamicTexture(640, 640, false);
this.trackThumbnailTexture.setFilter(true, true);
this.trackThumbnailResourceLocation = mc.getTextureManager().register("rusherhack-spotify-track-thumbnail/", this.trackThumbnailTexture);
//dummy setting whos only purpose is to be clicked to open the web browser
this.authenticateButton.onChange((b) -> {
if(!b) {
try {
Desktop.getDesktop().browse(new URI("http://localhost:4000/"));
} catch(IOException | URISyntaxException e) {
this.plugin.getLogger().error(e.getMessage());
e.printStackTrace();
}
this.authenticateButton.setValue(true);
}
});
this.background.addSubSettings(backgroundColor);
this.binds.addSubSettings(playPauseBind, backBind, nextBind, back5Bind, next5Bind);
this.registerSettings(authenticateButton, background, updateDelay, binds);
//dont ask
//this.setupDummyModuleBecauseImFuckingStupidAndForgotToRegisterHudElementsIntoTheEventBus();
}
@Override
public void tick() {
if(!this.isConnected()) {
return;
}
| package me.john200410.spotify.ui;
/**
* @author John200410
*/
public class SpotifyHudElement extends ResizeableHudElement {
public static final int BACKGROUND_COLOR = ColorUtils.transparency(Color.BLACK.getRGB(), 0.5f);
private static final PlaybackState.Item AI_DJ_SONG = new PlaybackState.Item(); //item that is displayed when the DJ is talking
static {
AI_DJ_SONG.album = new PlaybackState.Item.Album();
AI_DJ_SONG.artists = new PlaybackState.Item.Artist[1];
AI_DJ_SONG.album.images = new PlaybackState.Item.Album.Image[1];
AI_DJ_SONG.artists[0] = new PlaybackState.Item.Artist();
AI_DJ_SONG.album.images[0] = new PlaybackState.Item.Album.Image();
AI_DJ_SONG.artists[0].name = "Spotify";
AI_DJ_SONG.album.name = "Songs Made For You";
AI_DJ_SONG.name = AI_DJ_SONG.id = "DJ";
AI_DJ_SONG.duration_ms = 30000;
AI_DJ_SONG.album.images[0].url = "https://i.imgur.com/29vr8jz.png";
AI_DJ_SONG.album.images[0].width = 640;
AI_DJ_SONG.album.images[0].height = 640;
AI_DJ_SONG.uri = "";
}
/**
* Settings
*/
private final BooleanSetting authenticateButton = new BooleanSetting("Authenticate", true)
.setVisibility(() -> !this.isConnected());
private final BooleanSetting background = new BooleanSetting("Background", true);
private final ColorSetting backgroundColor = new ColorSetting("Color", new Color(BACKGROUND_COLOR, true));
private final NumberSetting<Double> updateDelay = new NumberSetting<>("UpdateDelay", 0.5d, 0.25d, 2d);
private final BooleanSetting binds = new BooleanSetting("Binds", false);
private final BindSetting playPauseBind = new BindSetting("Play/Pause", NullKey.INSTANCE);
private final BindSetting backBind = new BindSetting("Back", NullKey.INSTANCE);
private final BindSetting nextBind = new BindSetting("Next", NullKey.INSTANCE);
private final BindSetting back5Bind = new BindSetting("Back 5", NullKey.INSTANCE);
private final BindSetting next5Bind = new BindSetting("Next 5", NullKey.INSTANCE);
/**
* Media Controller
*/
private final SongInfoHandler songInfo;
private final DurationHandler duration;
private final MediaControllerHandler mediaController;
/**
* Variables
*/
private final VectorGraphic spotifyLogo;
private final ResourceLocation trackThumbnailResourceLocation;
private final DynamicTexture trackThumbnailTexture;
private final SpotifyPlugin plugin;
private PlaybackState.Item song = null;
private boolean consumedButtonClick = false;
private Boolean ai = false;
public SpotifyHudElement(SpotifyPlugin plugin) throws IOException {
super("Spotify");
this.plugin = plugin;
this.mediaController = new MediaControllerHandler();
this.duration = new DurationHandler();
this.songInfo = new SongInfoHandler();
this.spotifyLogo = new VectorGraphic("spotify/graphics/spotify_logo.svg", 32, 32);
this.trackThumbnailTexture = new DynamicTexture(640, 640, false);
this.trackThumbnailTexture.setFilter(true, true);
this.trackThumbnailResourceLocation = mc.getTextureManager().register("rusherhack-spotify-track-thumbnail/", this.trackThumbnailTexture);
//dummy setting whos only purpose is to be clicked to open the web browser
this.authenticateButton.onChange((b) -> {
if(!b) {
try {
Desktop.getDesktop().browse(new URI("http://localhost:4000/"));
} catch(IOException | URISyntaxException e) {
this.plugin.getLogger().error(e.getMessage());
e.printStackTrace();
}
this.authenticateButton.setValue(true);
}
});
this.background.addSubSettings(backgroundColor);
this.binds.addSubSettings(playPauseBind, backBind, nextBind, back5Bind, next5Bind);
this.registerSettings(authenticateButton, background, updateDelay, binds);
//dont ask
//this.setupDummyModuleBecauseImFuckingStupidAndForgotToRegisterHudElementsIntoTheEventBus();
}
@Override
public void tick() {
if(!this.isConnected()) {
return;
}
| final SpotifyAPI api = this.plugin.getAPI(); | 1 | 2023-12-19 17:59:37+00:00 | 12k |
Swofty-Developments/HypixelSkyBlock | generic/src/main/java/net/swofty/types/generic/event/actions/player/ActionPlayerChat.java | [
{
"identifier": "DataHandler",
"path": "generic/src/main/java/net/swofty/types/generic/data/DataHandler.java",
"snippet": "public class DataHandler {\n public static Map<UUID, DataHandler> userCache = new HashMap<>();\n @Getter\n private UUID uuid;\n private final Map<String, Datapoint> data... | import net.minestom.server.MinecraftServer;
import net.minestom.server.event.Event;
import net.minestom.server.event.player.PlayerChatEvent;
import net.swofty.types.generic.data.DataHandler;
import net.swofty.types.generic.data.datapoints.DatapointRank;
import net.swofty.types.generic.user.SkyBlockPlayer;
import net.swofty.types.generic.user.categories.Rank;
import net.swofty.types.generic.event.EventNodes;
import net.swofty.types.generic.event.EventParameters;
import net.swofty.types.generic.event.SkyBlockEvent; | 8,349 | package net.swofty.types.generic.event.actions.player;
@EventParameters(description = "Handles chat stuff",
node = EventNodes.PLAYER,
requireDataLoaded = false)
public class ActionPlayerChat extends SkyBlockEvent {
@Override
public Class<? extends Event> getEvent() {
return PlayerChatEvent.class;
}
@Override
public void run(Event event) {
PlayerChatEvent playerChatEvent = (PlayerChatEvent) event;
| package net.swofty.types.generic.event.actions.player;
@EventParameters(description = "Handles chat stuff",
node = EventNodes.PLAYER,
requireDataLoaded = false)
public class ActionPlayerChat extends SkyBlockEvent {
@Override
public Class<? extends Event> getEvent() {
return PlayerChatEvent.class;
}
@Override
public void run(Event event) {
PlayerChatEvent playerChatEvent = (PlayerChatEvent) event;
| final SkyBlockPlayer player = (SkyBlockPlayer) playerChatEvent.getPlayer(); | 2 | 2023-12-14 09:51:15+00:00 | 12k |
Tianscar/uxgl | base/src/main/java/unrefined/util/event/EventBus.java | [
{
"identifier": "Environment",
"path": "base/src/main/java/unrefined/context/Environment.java",
"snippet": "public class Environment implements Map<Object, Object> {\n\n private static final Environment system = new Environment(() -> new ConcurrentHashMap<>(System.getenv()), \"SYSTEM ENVIRONMENT VARI... | import unrefined.context.Environment;
import unrefined.util.function.Slot;
import unrefined.util.signal.Connection;
import unrefined.util.signal.Dispatcher;
import unrefined.util.signal.Signal;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static unrefined.util.signal.Connection.Type.AUTO; | 8,481 | package unrefined.util.event;
public abstract class EventBus {
private static volatile EventBus DEFAULT_INSTANCE;
private static final Object DEFAULT_INSTANCE_LOCK = new Object();
public static EventBus defaultInstance() {
if (DEFAULT_INSTANCE == null) synchronized (DEFAULT_INSTANCE_LOCK) { | package unrefined.util.event;
public abstract class EventBus {
private static volatile EventBus DEFAULT_INSTANCE;
private static final Object DEFAULT_INSTANCE_LOCK = new Object();
public static EventBus defaultInstance() {
if (DEFAULT_INSTANCE == null) synchronized (DEFAULT_INSTANCE_LOCK) { | if (DEFAULT_INSTANCE == null) DEFAULT_INSTANCE = Environment.global().get("unrefined.runtime.eventBus", EventBus.class); | 0 | 2023-12-15 19:03:31+00:00 | 12k |
Valerde/vadb | va-collection/src/main/java/com/sovava/vacollection/vaset/VaHashSet.java | [
{
"identifier": "VaCollection",
"path": "va-collection/src/main/java/com/sovava/vacollection/api/VaCollection.java",
"snippet": "public interface VaCollection<E> extends Iterable<E> {\n\n int size();\n\n boolean isEmpty();\n\n boolean contains(Object o);\n\n VaIterator<E> vaIterator();\n\n ... | import com.sovava.vacollection.api.VaCollection;
import com.sovava.vacollection.api.VaIterator;
import com.sovava.vacollection.api.VaSet;
import com.sovava.vacollection.vamap.VaHashMap;
import java.io.Serializable; | 9,009 | package com.sovava.vacollection.vaset;
/**
* Description: 基于hashmap的hashset
*
* @author: ykn
* @date: 2023年12月27日 3:06 PM
**/
public class VaHashSet<E> extends VaAbstractSet<E> implements VaSet<E>, Cloneable, Serializable {
private static final long serialVersionUID = 5120875045620310227L;
private VaHashMap<E, Object> map;
private final Object DEFAULT_VALUE = new Object();
public VaHashSet() {
map = new VaHashMap<>();
}
public VaHashSet(VaCollection<? extends E> c) {
map = new VaHashMap<>(Math.max((int) (c.size() / 0.75f), 16));
addAll(c);
}
public VaHashSet(int initCap) {
map = new VaHashMap<>(initCap);
}
public VaHashSet(int initCap, float loadFactor) {
map = new VaHashMap<>(initCap, loadFactor);
}
@Override
public boolean add(E e) {
return map.put(e, DEFAULT_VALUE) == null;
}
@Override | package com.sovava.vacollection.vaset;
/**
* Description: 基于hashmap的hashset
*
* @author: ykn
* @date: 2023年12月27日 3:06 PM
**/
public class VaHashSet<E> extends VaAbstractSet<E> implements VaSet<E>, Cloneable, Serializable {
private static final long serialVersionUID = 5120875045620310227L;
private VaHashMap<E, Object> map;
private final Object DEFAULT_VALUE = new Object();
public VaHashSet() {
map = new VaHashMap<>();
}
public VaHashSet(VaCollection<? extends E> c) {
map = new VaHashMap<>(Math.max((int) (c.size() / 0.75f), 16));
addAll(c);
}
public VaHashSet(int initCap) {
map = new VaHashMap<>(initCap);
}
public VaHashSet(int initCap, float loadFactor) {
map = new VaHashMap<>(initCap, loadFactor);
}
@Override
public boolean add(E e) {
return map.put(e, DEFAULT_VALUE) == null;
}
@Override | public VaIterator<E> vaIterator() { | 1 | 2023-12-17 13:29:10+00:00 | 12k |
litongjava/next-jfinal | src/main/java/com/jfinal/template/ext/spring/JFinalViewResolver.java | [
{
"identifier": "StrKit",
"path": "src/main/java/com/jfinal/kit/StrKit.java",
"snippet": "public class StrKit {\n\t\n\t/**\n\t * 首字母变小写\n\t */\n\tpublic static String firstCharToLowerCase(String str) {\n\t\tchar firstChar = str.charAt(0);\n\t\tif (firstChar >= 'A' && firstChar <= 'Z') {\n\t\t\tchar[] ar... | import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.AbstractTemplateViewResolver;
import com.jfinal.kit.StrKit;
import com.jfinal.servlet.ServletContext;
import com.jfinal.template.Directive;
import com.jfinal.template.Engine;
import com.jfinal.template.source.ClassPathSourceFactory;
import com.jfinal.template.source.ISourceFactory; | 9,428 | /**
* Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com).
*
* 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.jfinal.template.ext.spring;
/**
* JFinalViewResolver
*
* <pre>
* 关键配置:
* 1:setDevMode(true) 设置支持热加载模板文件
*
* 2:addSharedFunction(file) 添加共享函数文件
*
* 3:setSourceFactory(new ClassPathSourceFactory()),从 class path 与 jar 包中加载模板文件
* 一般用于 sprint boot
*
* 4:setSessionInView(true) 设置在模板中可通过 #(session.value) 访问 session 中的数据
*
* 5:setCreateSession(boolean) 用来设置 request.getSession(boolean) 调时的参数
*
* 6:setBaseTemplatePath(path) 设置模板文件所在的基础路径,通常用于 spring mvc
* 默认值为 web 根路径,一般不需要设置
* </pre>
*/
public class JFinalViewResolver /*extends AbstractTemplateViewResolver*/ {
public static final Engine engine = new Engine();
static List<String> sharedFunctionFiles = new ArrayList<String>();
static boolean sessionInView = false;
static boolean createSession = true;
private static JFinalViewResolver me = null;
/**
* me 会保存在第一次被创建对象
*/
public static JFinalViewResolver me() {
return me;
}
public Engine getEngine() {
return engine;
}
/**
* 设置开发模式,值为 true 时支持模板文件热加载
*/
public void setDevMode(boolean devMode) {
engine.setDevMode(devMode);
}
/**
* 设置 shared function 文件,多个文件用逗号分隔
*
* 主要用于 Spring MVC 的 xml 配置方式
*
* Spring Boot 的代码配置方式可使用 addSharedFunction(...) 进行配置
*/
public void setSharedFunction(String sharedFunctionFiles) { | /**
* Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com).
*
* 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.jfinal.template.ext.spring;
/**
* JFinalViewResolver
*
* <pre>
* 关键配置:
* 1:setDevMode(true) 设置支持热加载模板文件
*
* 2:addSharedFunction(file) 添加共享函数文件
*
* 3:setSourceFactory(new ClassPathSourceFactory()),从 class path 与 jar 包中加载模板文件
* 一般用于 sprint boot
*
* 4:setSessionInView(true) 设置在模板中可通过 #(session.value) 访问 session 中的数据
*
* 5:setCreateSession(boolean) 用来设置 request.getSession(boolean) 调时的参数
*
* 6:setBaseTemplatePath(path) 设置模板文件所在的基础路径,通常用于 spring mvc
* 默认值为 web 根路径,一般不需要设置
* </pre>
*/
public class JFinalViewResolver /*extends AbstractTemplateViewResolver*/ {
public static final Engine engine = new Engine();
static List<String> sharedFunctionFiles = new ArrayList<String>();
static boolean sessionInView = false;
static boolean createSession = true;
private static JFinalViewResolver me = null;
/**
* me 会保存在第一次被创建对象
*/
public static JFinalViewResolver me() {
return me;
}
public Engine getEngine() {
return engine;
}
/**
* 设置开发模式,值为 true 时支持模板文件热加载
*/
public void setDevMode(boolean devMode) {
engine.setDevMode(devMode);
}
/**
* 设置 shared function 文件,多个文件用逗号分隔
*
* 主要用于 Spring MVC 的 xml 配置方式
*
* Spring Boot 的代码配置方式可使用 addSharedFunction(...) 进行配置
*/
public void setSharedFunction(String sharedFunctionFiles) { | if (StrKit.isBlank(sharedFunctionFiles)) { | 0 | 2023-12-19 10:58:33+00:00 | 12k |
HypixelSkyblockmod/ChromaHud | src/java/xyz/apfelmus/cheeto/client/modules/player/CommMacro.java | [
{
"identifier": "CF4M",
"path": "src/java/xyz/apfelmus/cf4m/CF4M.java",
"snippet": "public enum CF4M {\n INSTANCE;\n\n public String packName;\n public String dir;\n public IConfiguration configuration;\n public ClassManager classManager;\n public EventManager eventManager;\n public... | import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityOtherPlayerMP;
import net.minecraft.client.gui.inventory.GuiChest;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityArmorStand;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.BlockPos;
import net.minecraft.util.StringUtils;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import xyz.apfelmus.cf4m.CF4M;
import xyz.apfelmus.cf4m.annotation.Event;
import xyz.apfelmus.cf4m.annotation.Setting;
import xyz.apfelmus.cf4m.annotation.module.Disable;
import xyz.apfelmus.cf4m.annotation.module.Enable;
import xyz.apfelmus.cf4m.annotation.module.Module;
import xyz.apfelmus.cf4m.module.Category;
import xyz.apfelmus.cheeto.client.events.ClientChatReceivedEvent;
import xyz.apfelmus.cheeto.client.events.ClientTickEvent;
import xyz.apfelmus.cheeto.client.events.Render3DEvent;
import xyz.apfelmus.cheeto.client.events.WorldUnloadEvent;
import xyz.apfelmus.cheeto.client.settings.BooleanSetting;
import xyz.apfelmus.cheeto.client.settings.IntegerSetting;
import xyz.apfelmus.cheeto.client.utils.client.ChadUtils;
import xyz.apfelmus.cheeto.client.utils.client.ChatUtils;
import xyz.apfelmus.cheeto.client.utils.client.JsonUtils;
import xyz.apfelmus.cheeto.client.utils.client.RotationUtils;
import xyz.apfelmus.cheeto.client.utils.math.RandomUtil;
import xyz.apfelmus.cheeto.client.utils.math.TimeHelper;
import xyz.apfelmus.cheeto.client.utils.mining.Location;
import xyz.apfelmus.cheeto.client.utils.mining.MiningJson;
import xyz.apfelmus.cheeto.client.utils.mining.PathPoint;
import xyz.apfelmus.cheeto.client.utils.skyblock.InventoryUtils;
import xyz.apfelmus.cheeto.client.utils.skyblock.SkyblockUtils; | 10,094 | /*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* net.minecraft.block.Block
* net.minecraft.client.Minecraft
* net.minecraft.client.entity.EntityOtherPlayerMP
* net.minecraft.client.gui.inventory.GuiChest
* net.minecraft.client.settings.KeyBinding
* net.minecraft.entity.Entity
* net.minecraft.entity.item.EntityArmorStand
* net.minecraft.entity.player.EntityPlayer
* net.minecraft.init.Blocks
* net.minecraft.init.Items
* net.minecraft.item.Item
* net.minecraft.item.ItemStack
* net.minecraft.nbt.NBTTagCompound
* net.minecraft.nbt.NBTTagList
* net.minecraft.util.BlockPos
* net.minecraft.util.StringUtils
* net.minecraft.util.Vec3
* net.minecraft.world.World
* org.apache.commons.lang3.StringUtils
*/
package xyz.apfelmus.cheeto.client.modules.player;
@Module(name="CommMacro", category=Category.PLAYER)
public class CommMacro {
@Setting(name="LookTime", description="Set higher if low mana or bad ping")
private IntegerSetting lookTime = new IntegerSetting(500, 0, 2500);
@Setting(name="WarpTime", description="Set higher if low mana or bad ping")
private IntegerSetting warpTime = new IntegerSetting(250, 0, 1000);
@Setting(name="MaxPlayerRange")
private IntegerSetting maxPlayerRange = new IntegerSetting(5, 0, 10);
@Setting(name="PickSlot")
private IntegerSetting pickSlot = new IntegerSetting(0, 0, 8);
@Setting(name="AotvSlot")
private IntegerSetting aotvSlot = new IntegerSetting(0, 0, 8);
@Setting(name="PigeonSlot")
private IntegerSetting pigeonSlot = new IntegerSetting(0, 0, 8);
@Setting(name="Ungrab", description="Automatically tabs out")
private BooleanSetting ungrab = new BooleanSetting(true);
private static Minecraft mc = Minecraft.func_71410_x();
public static MiningJson miningJson = JsonUtils.getMiningJson();
private static Quest currentQuest = null;
private static Location currentLocation = null;
private static List<PathPoint> path = null; | /*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* net.minecraft.block.Block
* net.minecraft.client.Minecraft
* net.minecraft.client.entity.EntityOtherPlayerMP
* net.minecraft.client.gui.inventory.GuiChest
* net.minecraft.client.settings.KeyBinding
* net.minecraft.entity.Entity
* net.minecraft.entity.item.EntityArmorStand
* net.minecraft.entity.player.EntityPlayer
* net.minecraft.init.Blocks
* net.minecraft.init.Items
* net.minecraft.item.Item
* net.minecraft.item.ItemStack
* net.minecraft.nbt.NBTTagCompound
* net.minecraft.nbt.NBTTagList
* net.minecraft.util.BlockPos
* net.minecraft.util.StringUtils
* net.minecraft.util.Vec3
* net.minecraft.world.World
* org.apache.commons.lang3.StringUtils
*/
package xyz.apfelmus.cheeto.client.modules.player;
@Module(name="CommMacro", category=Category.PLAYER)
public class CommMacro {
@Setting(name="LookTime", description="Set higher if low mana or bad ping")
private IntegerSetting lookTime = new IntegerSetting(500, 0, 2500);
@Setting(name="WarpTime", description="Set higher if low mana or bad ping")
private IntegerSetting warpTime = new IntegerSetting(250, 0, 1000);
@Setting(name="MaxPlayerRange")
private IntegerSetting maxPlayerRange = new IntegerSetting(5, 0, 10);
@Setting(name="PickSlot")
private IntegerSetting pickSlot = new IntegerSetting(0, 0, 8);
@Setting(name="AotvSlot")
private IntegerSetting aotvSlot = new IntegerSetting(0, 0, 8);
@Setting(name="PigeonSlot")
private IntegerSetting pigeonSlot = new IntegerSetting(0, 0, 8);
@Setting(name="Ungrab", description="Automatically tabs out")
private BooleanSetting ungrab = new BooleanSetting(true);
private static Minecraft mc = Minecraft.func_71410_x();
public static MiningJson miningJson = JsonUtils.getMiningJson();
private static Quest currentQuest = null;
private static Location currentLocation = null;
private static List<PathPoint> path = null; | private static TimeHelper pigeonTimer = new TimeHelper(); | 13 | 2023-12-21 16:22:25+00:00 | 12k |
ciallo-dev/JWSystemLib | src/main/java/moe/snowflake/jwSystem/JWSystem.java | [
{
"identifier": "CourseSelectManager",
"path": "src/main/java/moe/snowflake/jwSystem/manager/CourseSelectManager.java",
"snippet": "public class CourseSelectManager {\n private final JWSystem system;\n\n\n public CourseSelectManager(JWSystem system) {\n this.system = system;\n }\n\n /... | import moe.snowflake.jwSystem.manager.CourseSelectManager;
import moe.snowflake.jwSystem.manager.CourseReviewManager;
import moe.snowflake.jwSystem.manager.URLManager;
import moe.snowflake.jwSystem.utils.HttpUtil;
import moe.snowflake.jwSystem.utils.PasswordUtil;
import org.jsoup.Connection;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.*; | 7,558 | package moe.snowflake.jwSystem;
public class JWSystem {
public Connection.Response jwLoggedResponse;
public Connection.Response courseSelectSystemResponse;
public Map<String, String> headers = new HashMap<>();
private final boolean loginCourseSelectWeb;
private final CourseSelectManager courseSelectManager;
private final CourseReviewManager courseReviewManager;
public JWSystem() {
this(true);
}
public JWSystem(boolean loginCourseSelectWeb) {
this.loginCourseSelectWeb = loginCourseSelectWeb;
this.courseSelectManager = new CourseSelectManager(this);
this.courseReviewManager = new CourseReviewManager(this);
}
/**
* 判断教务是否登录成功
*
* @return 是否登录成功
*/
public boolean isJWLogged() {
try {
if (this.jwLoggedResponse != null) {
// 只要有这个元素即登录失败
Element element = this.jwLoggedResponse.parse().getElementById("showMsg");
if (element != null) return false;
}
} catch (Exception e) {
return false;
}
return true;
}
/**
* 判断选课系统是否登录成功
*
* @return 选课系统是否登录
*/
public boolean isCourseLogged() {
try {
return this.isJWLogged() &&
this.courseSelectSystemResponse != null && !this.courseSelectSystemResponse.parse().title().contains("登录");
} catch (IOException e) {
return false;
}
}
/**
* 设置全局的 headers,包含cookie
* jsoup设置的cookie无法识别
*
* @param cookie cookie
*/
private void setHeaders(String cookie) {
headers.put("Cookie", "JSESSIONID=" + cookie);
}
/**
* 直接导向目标API的登录
*
* @param username 用户名
* @param password 密码
*/
public JWSystem login(String username, String password) {
Map<String, String> formData = new HashMap<>();
formData.put("userAccount", username);
formData.put("userPassword", "");
// 很明显的两个base64加密
formData.put("encoded", new String(Base64.getEncoder().encode(username.getBytes())) + "%%%" + new String(Base64.getEncoder().encode(password.getBytes())));
// 登录成功的 响应 | package moe.snowflake.jwSystem;
public class JWSystem {
public Connection.Response jwLoggedResponse;
public Connection.Response courseSelectSystemResponse;
public Map<String, String> headers = new HashMap<>();
private final boolean loginCourseSelectWeb;
private final CourseSelectManager courseSelectManager;
private final CourseReviewManager courseReviewManager;
public JWSystem() {
this(true);
}
public JWSystem(boolean loginCourseSelectWeb) {
this.loginCourseSelectWeb = loginCourseSelectWeb;
this.courseSelectManager = new CourseSelectManager(this);
this.courseReviewManager = new CourseReviewManager(this);
}
/**
* 判断教务是否登录成功
*
* @return 是否登录成功
*/
public boolean isJWLogged() {
try {
if (this.jwLoggedResponse != null) {
// 只要有这个元素即登录失败
Element element = this.jwLoggedResponse.parse().getElementById("showMsg");
if (element != null) return false;
}
} catch (Exception e) {
return false;
}
return true;
}
/**
* 判断选课系统是否登录成功
*
* @return 选课系统是否登录
*/
public boolean isCourseLogged() {
try {
return this.isJWLogged() &&
this.courseSelectSystemResponse != null && !this.courseSelectSystemResponse.parse().title().contains("登录");
} catch (IOException e) {
return false;
}
}
/**
* 设置全局的 headers,包含cookie
* jsoup设置的cookie无法识别
*
* @param cookie cookie
*/
private void setHeaders(String cookie) {
headers.put("Cookie", "JSESSIONID=" + cookie);
}
/**
* 直接导向目标API的登录
*
* @param username 用户名
* @param password 密码
*/
public JWSystem login(String username, String password) {
Map<String, String> formData = new HashMap<>();
formData.put("userAccount", username);
formData.put("userPassword", "");
// 很明显的两个base64加密
formData.put("encoded", new String(Base64.getEncoder().encode(username.getBytes())) + "%%%" + new String(Base64.getEncoder().encode(password.getBytes())));
// 登录成功的 响应 | Connection.Response response = HttpUtil.sendPost(URLManager.LOGIN, formData); | 3 | 2023-12-21 10:58:12+00:00 | 12k |
emtee40/ApkSignatureKill-pc | app/src/main/java/org/jf/dexlib2/immutable/value/ImmutableEncodedValueFactory.java | [
{
"identifier": "ValueType",
"path": "app/src/main/java/org/jf/dexlib2/ValueType.java",
"snippet": "public final class ValueType {\n public static final int BYTE = 0x00;\n public static final int SHORT = 0x02;\n public static final int CHAR = 0x03;\n public static final int INT = 0x04;\n ... | import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import org.jf.dexlib2.ValueType;
import org.jf.dexlib2.iface.value.AnnotationEncodedValue;
import org.jf.dexlib2.iface.value.ArrayEncodedValue;
import org.jf.dexlib2.iface.value.BooleanEncodedValue;
import org.jf.dexlib2.iface.value.ByteEncodedValue;
import org.jf.dexlib2.iface.value.CharEncodedValue;
import org.jf.dexlib2.iface.value.DoubleEncodedValue;
import org.jf.dexlib2.iface.value.EncodedValue;
import org.jf.dexlib2.iface.value.EnumEncodedValue;
import org.jf.dexlib2.iface.value.FieldEncodedValue;
import org.jf.dexlib2.iface.value.FloatEncodedValue;
import org.jf.dexlib2.iface.value.IntEncodedValue;
import org.jf.dexlib2.iface.value.LongEncodedValue;
import org.jf.dexlib2.iface.value.MethodEncodedValue;
import org.jf.dexlib2.iface.value.ShortEncodedValue;
import org.jf.dexlib2.iface.value.StringEncodedValue;
import org.jf.dexlib2.iface.value.TypeEncodedValue;
import org.jf.util.ExceptionWithContext;
import org.jf.util.ImmutableConverter; | 9,224 | package org.jf.dexlib2.immutable.value;
public class ImmutableEncodedValueFactory {
private static final ImmutableConverter<ImmutableEncodedValue, EncodedValue> CONVERTER =
new ImmutableConverter<ImmutableEncodedValue, EncodedValue>() {
@Override
protected boolean isImmutable(@NonNull EncodedValue item) {
return item instanceof ImmutableEncodedValue;
}
@NonNull
@Override
protected ImmutableEncodedValue makeImmutable(@NonNull EncodedValue item) {
return of(item);
}
};
@NonNull
public static ImmutableEncodedValue of(@NonNull EncodedValue encodedValue) {
switch (encodedValue.getValueType()) {
case ValueType.BYTE:
return ImmutableByteEncodedValue.of((ByteEncodedValue) encodedValue);
case ValueType.SHORT:
return ImmutableShortEncodedValue.of((ShortEncodedValue) encodedValue);
case ValueType.CHAR: | package org.jf.dexlib2.immutable.value;
public class ImmutableEncodedValueFactory {
private static final ImmutableConverter<ImmutableEncodedValue, EncodedValue> CONVERTER =
new ImmutableConverter<ImmutableEncodedValue, EncodedValue>() {
@Override
protected boolean isImmutable(@NonNull EncodedValue item) {
return item instanceof ImmutableEncodedValue;
}
@NonNull
@Override
protected ImmutableEncodedValue makeImmutable(@NonNull EncodedValue item) {
return of(item);
}
};
@NonNull
public static ImmutableEncodedValue of(@NonNull EncodedValue encodedValue) {
switch (encodedValue.getValueType()) {
case ValueType.BYTE:
return ImmutableByteEncodedValue.of((ByteEncodedValue) encodedValue);
case ValueType.SHORT:
return ImmutableShortEncodedValue.of((ShortEncodedValue) encodedValue);
case ValueType.CHAR: | return ImmutableCharEncodedValue.of((CharEncodedValue) encodedValue); | 5 | 2023-12-16 11:11:16+00:00 | 12k |
IzanagiCraft/IzanagiWorldGuard | worldguard-plugin-bukkit/src/main/java/com/izanagicraft/guard/events/listener/InventoryItemChangeListener.java | [
{
"identifier": "GuardConstants",
"path": "worldguard-api/src/main/java/com/izanagicraft/guard/GuardConstants.java",
"snippet": "public class GuardConstants {\n\n /**\n * The main prefix used for plugin-related messages.\n */\n public static final String PREFIX = \"&#CB2D3EG&#D4343Du&#DD3A... | import org.bukkit.event.player.PlayerAttemptPickupItemEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import com.izanagicraft.guard.GuardConstants;
import com.izanagicraft.guard.IzanagiWorldGuardPlugin;
import com.izanagicraft.guard.commands.BuildModeCommand;
import com.izanagicraft.guard.events.GuardListener;
import com.izanagicraft.guard.flags.GuardFlag;
import com.izanagicraft.guard.permissions.GuardPermission;
import com.izanagicraft.guard.utils.MessageUtils;
import io.papermc.paper.event.player.PlayerPickItemEvent;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.inventory.InventoryPickupItemEvent; | 7,206 | /*
* ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄
* ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██
* ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪
* ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌·
* ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <sanguine6660@gmail.com>
* Copyright (c) 2023 - present | izanagicraft.com <contact@izanagicraft.com>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.izanagicraft.guard.events.listener;
/**
* IzanagiWorldGuard; com.izanagicraft.guard.events.listener:InventoryItemChangeListener
* <p>
* Handles inventory-related events for IzanagiWorldGuard.
* This listener checks and enforces item drop and pickup permissions within protected regions.
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 18.12.2023
*/
public class InventoryItemChangeListener extends GuardListener {
/**
* Constructs a new GuardListener with the specified IzanagiWorldGuardPlugin.
*
* @param plugin The IzanagiWorldGuardPlugin instance.
*/
public InventoryItemChangeListener(IzanagiWorldGuardPlugin plugin) {
super(plugin);
}
/**
* Handles the PlayerDropItemEvent to enforce item drop permissions within protected regions.
*
* @param event The PlayerDropItemEvent.
*/
@EventHandler
public void onItemDrop(PlayerDropItemEvent event) {
Player player = event.getPlayer();
Item item = event.getItemDrop();
if (player == null || item == null) {
event.setCancelled(true);
return;
}
if (event.isCancelled()) return;
if (player.hasPermission(GuardPermission.GROUPS_ADMIN.getName())
|| player.hasPermission(GuardPermission.PLAYER_ITEM_DROP.getName())) {
return;
}
if (BuildModeCommand.isBuildMode(player)) return;
Location target = item.getLocation();
YamlConfiguration worldConfig = getPlugin().getWorldConfigs().get(target.getWorld().getName());
if (worldConfig == null) return;
boolean allowItem = true;
String allow = worldConfig.getString("flags." + GuardFlag.ITEM_DROP.getFlagName(), "false");
// System.out.println("Drop Allow: '" + allow + "'");
if (allow.isEmpty() || allow.equalsIgnoreCase("empty")
|| allow.equalsIgnoreCase("false") || allow.equalsIgnoreCase("deny")) {
allowItem = false;
}
// TODO: region based checks.
// System.out.println("Final Drop Allow: '" + allowItem + "'");
if (!allowItem) {
event.setCancelled(true);
// TODO: translations by player locale || fire event cancelled item drop instead | /*
* ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄
* ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██
* ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪
* ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌·
* ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <sanguine6660@gmail.com>
* Copyright (c) 2023 - present | izanagicraft.com <contact@izanagicraft.com>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.izanagicraft.guard.events.listener;
/**
* IzanagiWorldGuard; com.izanagicraft.guard.events.listener:InventoryItemChangeListener
* <p>
* Handles inventory-related events for IzanagiWorldGuard.
* This listener checks and enforces item drop and pickup permissions within protected regions.
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 18.12.2023
*/
public class InventoryItemChangeListener extends GuardListener {
/**
* Constructs a new GuardListener with the specified IzanagiWorldGuardPlugin.
*
* @param plugin The IzanagiWorldGuardPlugin instance.
*/
public InventoryItemChangeListener(IzanagiWorldGuardPlugin plugin) {
super(plugin);
}
/**
* Handles the PlayerDropItemEvent to enforce item drop permissions within protected regions.
*
* @param event The PlayerDropItemEvent.
*/
@EventHandler
public void onItemDrop(PlayerDropItemEvent event) {
Player player = event.getPlayer();
Item item = event.getItemDrop();
if (player == null || item == null) {
event.setCancelled(true);
return;
}
if (event.isCancelled()) return;
if (player.hasPermission(GuardPermission.GROUPS_ADMIN.getName())
|| player.hasPermission(GuardPermission.PLAYER_ITEM_DROP.getName())) {
return;
}
if (BuildModeCommand.isBuildMode(player)) return;
Location target = item.getLocation();
YamlConfiguration worldConfig = getPlugin().getWorldConfigs().get(target.getWorld().getName());
if (worldConfig == null) return;
boolean allowItem = true;
String allow = worldConfig.getString("flags." + GuardFlag.ITEM_DROP.getFlagName(), "false");
// System.out.println("Drop Allow: '" + allow + "'");
if (allow.isEmpty() || allow.equalsIgnoreCase("empty")
|| allow.equalsIgnoreCase("false") || allow.equalsIgnoreCase("deny")) {
allowItem = false;
}
// TODO: region based checks.
// System.out.println("Final Drop Allow: '" + allowItem + "'");
if (!allowItem) {
event.setCancelled(true);
// TODO: translations by player locale || fire event cancelled item drop instead | player.sendActionBar(MessageUtils.getComponentSerializer().deserialize( | 6 | 2023-12-17 14:18:31+00:00 | 12k |
123yyh123/xiaofanshu | xfs-modules-server/xfs-user-server/src/main/java/com/yyh/xfs/user/service/impl/UserRelationServiceImpl.java | [
{
"identifier": "Result",
"path": "xfs-common/common-base/src/main/java/com/yyh/xfs/common/domain/Result.java",
"snippet": "@Setter\n@Getter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Result<T> implements Serializable {\n private Integer code;\n private String msg;\n priv... | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yyh.xfs.common.domain.Result;
import com.yyh.xfs.common.myEnum.ExceptionMsgEnum;
import com.yyh.xfs.common.redis.constant.RedisConstant;
import com.yyh.xfs.common.redis.utils.RedisCache;
import com.yyh.xfs.common.redis.utils.RedisKey;
import com.yyh.xfs.common.utils.ResultUtil;
import com.yyh.xfs.common.web.exception.BusinessException;
import com.yyh.xfs.user.domain.UserAttentionDO;
import com.yyh.xfs.user.domain.UserFansDO;
import com.yyh.xfs.user.mapper.UserAttentionMapper;
import com.yyh.xfs.user.mapper.UserBlackMapper;
import com.yyh.xfs.user.mapper.UserFansMapper;
import com.yyh.xfs.user.service.UserRelationService;
import com.yyh.xfs.user.vo.UserRelationVO;
import com.yyh.xfs.user.vo.ViewUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Objects; | 8,098 | package com.yyh.xfs.user.service.impl;
/**
* @author yyh
* @date 2024-01-15
*/
@Service
public class UserRelationServiceImpl implements UserRelationService {
private final UserAttentionMapper userAttentionMapper;
private final UserBlackMapper userBlackMapper;
private final UserFansMapper userFansMapper;
private final RedisCache redisCache;
public UserRelationServiceImpl(UserAttentionMapper userAttentionMapper, UserBlackMapper userBlackMapper, UserFansMapper userFansMapper, RedisCache redisCache) {
this.userAttentionMapper = userAttentionMapper;
this.userBlackMapper = userBlackMapper;
this.userFansMapper = userFansMapper;
this.redisCache = redisCache;
}
@Override
public Result<Boolean> selectOneByUserIdAndBlackIdIsExist(Long toId, Long fromId) {
return ResultUtil.successGet(userBlackMapper.selectOneByUserIdAndBlackIdIsExist(toId, fromId));
}
@Override
public Result<Boolean> selectOneByUserIdAndAttentionIdIsExist(Long toId, Long fromId) {
return ResultUtil.successGet(userAttentionMapper.selectOneByUserIdAndAttentionIdIsExist(toId, fromId));
}
@Override | package com.yyh.xfs.user.service.impl;
/**
* @author yyh
* @date 2024-01-15
*/
@Service
public class UserRelationServiceImpl implements UserRelationService {
private final UserAttentionMapper userAttentionMapper;
private final UserBlackMapper userBlackMapper;
private final UserFansMapper userFansMapper;
private final RedisCache redisCache;
public UserRelationServiceImpl(UserAttentionMapper userAttentionMapper, UserBlackMapper userBlackMapper, UserFansMapper userFansMapper, RedisCache redisCache) {
this.userAttentionMapper = userAttentionMapper;
this.userBlackMapper = userBlackMapper;
this.userFansMapper = userFansMapper;
this.redisCache = redisCache;
}
@Override
public Result<Boolean> selectOneByUserIdAndBlackIdIsExist(Long toId, Long fromId) {
return ResultUtil.successGet(userBlackMapper.selectOneByUserIdAndBlackIdIsExist(toId, fromId));
}
@Override
public Result<Boolean> selectOneByUserIdAndAttentionIdIsExist(Long toId, Long fromId) {
return ResultUtil.successGet(userAttentionMapper.selectOneByUserIdAndAttentionIdIsExist(toId, fromId));
}
@Override | public Result<List<UserRelationVO>> selectAttentionList(Long userId, Integer pageNum, Integer pageSize) { | 13 | 2023-12-15 08:13:42+00:00 | 12k |
egisac/ethicalvoting | src/main/java/net/egis/ethicalvoting/EthicalVoting.java | [
{
"identifier": "EthicalVotingCommand",
"path": "src/main/java/net/egis/ethicalvoting/commands/EthicalVotingCommand.java",
"snippet": "public class EthicalVotingCommand implements CommandExecutor, TabCompleter {\n @Override\n public boolean onCommand(CommandSender sender, Command command, String l... | import lombok.Getter;
import mc.obliviate.inventory.InventoryAPI;
import net.egis.ethicalvoting.commands.EthicalVotingCommand;
import net.egis.ethicalvoting.commands.VoteCommand;
import net.egis.ethicalvoting.data.ProfileManager;
import net.egis.ethicalvoting.data.StorageInterface;
import net.egis.ethicalvoting.data.interfaces.MySQLInterface;
import net.egis.ethicalvoting.data.interfaces.YamlInterface;
import net.egis.ethicalvoting.https.UpdateChecker;
import net.egis.ethicalvoting.integrations.EthicalPAPI;
import net.egis.ethicalvoting.listeners.FireworkDamageListener;
import net.egis.ethicalvoting.listeners.PlayerConnectionListener;
import net.egis.ethicalvoting.listeners.VotifierVoteListener;
import net.egis.ethicalvoting.rewards.VoteRewardHandler;
import net.egis.ethicalvoting.utils.Translate;
import net.egis.ethicalvoting.voteparty.VotePartyHandler;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin; | 7,718 | package net.egis.ethicalvoting;
@Getter
public final class EthicalVoting extends JavaPlugin {
@Getter
private static EthicalVoting self;
private StorageInterface storage;
private ProfileManager profiles;
private PlayerConnectionListener connectionListener;
private VotifierVoteListener voteListener;
private FireworkDamageListener fireworkDamageListener;
private VotePartyHandler votePartyHandler;
private VoteRewardHandler voteRewardHandler;
@Override
public void onEnable() {
self = this;
new InventoryAPI(this).init();
saveDefaultConfig();
pickStorageType();
loadPluginData();
loadFeatures();
registerEventListeners();
registerCommands();
registerIntegrations();
getLogger().info("Storage Type: " + storage.getAdapterType());
checkUpdates();
getLogger().info("EthicalVoting has been successfully enabled.");
}
@Override
public void onDisable() {
profiles.shutdown();
voteRewardHandler.getVoteQueue().shutdown();
getLogger().info("EthicalVoting has been successfully disabled.");
}
public void registerIntegrations() {
if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) {
new EthicalPAPI().register();
getLogger().info("PlaceholderAPI integration has been successfully enabled.");
} else {
getLogger().warning("PlaceholderAPI integration has failed to load.");
}
}
/*
Defines which database type will be used to store user data.
Current options:
- MySQL
- YAML (Bukkit internal)
*/
public void pickStorageType() {
String storageInterface = getConfig().getString("database.type");
if (storageInterface == null) {
getLogger().severe("Storage Interface is null. Report this to plugin developer.");
getServer().shutdown();
return;
}
if (storageInterface.equalsIgnoreCase("mysql")) {
storage = new MySQLInterface();
String host = getConfig().getString("database.host");
int port = getConfig().getInt("database.port");
String database = getConfig().getString("database.database");
String username = getConfig().getString("database.username");
String password = getConfig().getString("database.password");
if (host == null || database == null || username == null || password == null) {
getLogger().severe("MySQL credentials are null. Report this to plugin developer.");
getServer().shutdown();
return;
}
if (!storage.jdbcInit("jdbc:mysql://" + host + ":" + port + "/" + database, username, password)) {
getLogger().severe("Failed to connect to MySQL database. Report this to plugin developer.");
getServer().shutdown();
return;
}
} else {
storage = new YamlInterface(this);
}
}
public void registerCommands() {
EthicalVotingCommand ethicalVotingCommand = new EthicalVotingCommand();
getCommand("ethicalvoting").setExecutor(ethicalVotingCommand);
getCommand("ethicalvoting").setTabCompleter(ethicalVotingCommand);
VoteCommand voteCommand = new VoteCommand();
getCommand("vote").setExecutor(voteCommand);
getCommand("vote").setTabCompleter(voteCommand);
}
public void loadPluginData() {
this.profiles = new ProfileManager(storage);
}
public void registerEventListeners() {
this.connectionListener = new PlayerConnectionListener(this);
this.voteListener = new VotifierVoteListener(this);
this.fireworkDamageListener = new FireworkDamageListener();
getServer().getPluginManager().registerEvents(connectionListener, this);
getServer().getPluginManager().registerEvents(voteListener, this);
getServer().getPluginManager().registerEvents(fireworkDamageListener, this);
}
public void loadFeatures() {
votePartyHandler = new VotePartyHandler(this);
voteRewardHandler = new VoteRewardHandler(this);
}
public void checkUpdates() {
new UpdateChecker(this, 12345).getVersion(version -> {
if (!this.getDescription().getVersion().equals(version)) {
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.isOp()) {
String prefix = getConfig().getString("messages.prefix"); | package net.egis.ethicalvoting;
@Getter
public final class EthicalVoting extends JavaPlugin {
@Getter
private static EthicalVoting self;
private StorageInterface storage;
private ProfileManager profiles;
private PlayerConnectionListener connectionListener;
private VotifierVoteListener voteListener;
private FireworkDamageListener fireworkDamageListener;
private VotePartyHandler votePartyHandler;
private VoteRewardHandler voteRewardHandler;
@Override
public void onEnable() {
self = this;
new InventoryAPI(this).init();
saveDefaultConfig();
pickStorageType();
loadPluginData();
loadFeatures();
registerEventListeners();
registerCommands();
registerIntegrations();
getLogger().info("Storage Type: " + storage.getAdapterType());
checkUpdates();
getLogger().info("EthicalVoting has been successfully enabled.");
}
@Override
public void onDisable() {
profiles.shutdown();
voteRewardHandler.getVoteQueue().shutdown();
getLogger().info("EthicalVoting has been successfully disabled.");
}
public void registerIntegrations() {
if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) {
new EthicalPAPI().register();
getLogger().info("PlaceholderAPI integration has been successfully enabled.");
} else {
getLogger().warning("PlaceholderAPI integration has failed to load.");
}
}
/*
Defines which database type will be used to store user data.
Current options:
- MySQL
- YAML (Bukkit internal)
*/
public void pickStorageType() {
String storageInterface = getConfig().getString("database.type");
if (storageInterface == null) {
getLogger().severe("Storage Interface is null. Report this to plugin developer.");
getServer().shutdown();
return;
}
if (storageInterface.equalsIgnoreCase("mysql")) {
storage = new MySQLInterface();
String host = getConfig().getString("database.host");
int port = getConfig().getInt("database.port");
String database = getConfig().getString("database.database");
String username = getConfig().getString("database.username");
String password = getConfig().getString("database.password");
if (host == null || database == null || username == null || password == null) {
getLogger().severe("MySQL credentials are null. Report this to plugin developer.");
getServer().shutdown();
return;
}
if (!storage.jdbcInit("jdbc:mysql://" + host + ":" + port + "/" + database, username, password)) {
getLogger().severe("Failed to connect to MySQL database. Report this to plugin developer.");
getServer().shutdown();
return;
}
} else {
storage = new YamlInterface(this);
}
}
public void registerCommands() {
EthicalVotingCommand ethicalVotingCommand = new EthicalVotingCommand();
getCommand("ethicalvoting").setExecutor(ethicalVotingCommand);
getCommand("ethicalvoting").setTabCompleter(ethicalVotingCommand);
VoteCommand voteCommand = new VoteCommand();
getCommand("vote").setExecutor(voteCommand);
getCommand("vote").setTabCompleter(voteCommand);
}
public void loadPluginData() {
this.profiles = new ProfileManager(storage);
}
public void registerEventListeners() {
this.connectionListener = new PlayerConnectionListener(this);
this.voteListener = new VotifierVoteListener(this);
this.fireworkDamageListener = new FireworkDamageListener();
getServer().getPluginManager().registerEvents(connectionListener, this);
getServer().getPluginManager().registerEvents(voteListener, this);
getServer().getPluginManager().registerEvents(fireworkDamageListener, this);
}
public void loadFeatures() {
votePartyHandler = new VotePartyHandler(this);
voteRewardHandler = new VoteRewardHandler(this);
}
public void checkUpdates() {
new UpdateChecker(this, 12345).getVersion(version -> {
if (!this.getDescription().getVersion().equals(version)) {
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.isOp()) {
String prefix = getConfig().getString("messages.prefix"); | player.sendMessage(Translate.translate(prefix + "&7There is a new &aupdate &7available &fhttps://www.spigot.org/")); | 12 | 2023-12-15 16:48:38+00:00 | 12k |
Blawuken/MicroG-Extended | play-services-core/src/main/java/org/microg/gms/gcm/McsService.java | [
{
"identifier": "ForegroundServiceContext",
"path": "play-services-base/core/src/main/java/org/microg/gms/common/ForegroundServiceContext.java",
"snippet": "public class ForegroundServiceContext extends ContextWrapper {\n private static final String TAG = \"ForegroundService\";\n public static fin... | import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PermissionInfo;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Messenger;
import android.os.Parcelable;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.UserHandle;
import android.util.Base64;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.legacy.content.WakefulBroadcastReceiver;
import com.squareup.wire.Message;
import org.microg.gms.checkin.LastCheckinInfo;
import org.microg.gms.common.ForegroundServiceContext;
import org.microg.gms.common.ForegroundServiceInfo;
import org.microg.gms.common.PackageUtils;
import org.microg.gms.gcm.mcs.AppData;
import org.microg.gms.gcm.mcs.Close;
import org.microg.gms.gcm.mcs.DataMessageStanza;
import org.microg.gms.gcm.mcs.Extension;
import org.microg.gms.gcm.mcs.HeartbeatAck;
import org.microg.gms.gcm.mcs.HeartbeatPing;
import org.microg.gms.gcm.mcs.IqStanza;
import org.microg.gms.gcm.mcs.LoginRequest;
import org.microg.gms.gcm.mcs.LoginResponse;
import org.microg.gms.gcm.mcs.Setting;
import java.io.Closeable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.SSLContext;
import okio.ByteString;
import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
import static android.os.Build.VERSION.SDK_INT;
import static org.microg.gms.common.PackageUtils.warnIfNotPersistentProcess;
import static org.microg.gms.gcm.GcmConstants.*;
import static org.microg.gms.gcm.McsConstants.*; | 8,612 |
private static HandlerThread handlerThread;
private static Handler rootHandler;
private GcmDatabase database;
private AlarmManager alarmManager;
private PowerManager powerManager;
private static PowerManager.WakeLock wakeLock;
private static long currentDelay = 0;
private Intent connectIntent;
private static int maxTtl = 24 * 60 * 60;
@Nullable
private Method getUserIdMethod;
@Nullable
private Object deviceIdleController;
@Nullable
private Method addPowerSaveTempWhitelistAppMethod;
@Nullable
@RequiresApi(31)
private Object powerExemptionManager;
@Nullable
@RequiresApi(31)
private Method addToTemporaryAllowListMethod;
private class HandlerThread extends Thread {
public HandlerThread() {
setName("McsHandler");
}
@Override
public void run() {
Looper.prepare();
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "mcs");
wakeLock.setReferenceCounted(false);
synchronized (McsService.class) {
rootHandler = new Handler(Looper.myLooper(), McsService.this);
if (connectIntent != null) {
rootHandler.sendMessage(rootHandler.obtainMessage(MSG_CONNECT, connectIntent));
WakefulBroadcastReceiver.completeWakefulIntent(connectIntent);
}
}
Looper.loop();
}
}
private static void logd(Context context, String msg) {
if (context == null || GcmPrefs.get(context).isGcmLogEnabled()) Log.d(TAG, msg);
}
@Override
@SuppressLint("PrivateApi")
public void onCreate() {
super.onCreate();
TriggerReceiver.register(this);
database = new GcmDatabase(this);
heartbeatIntent = PendingIntent.getService(this, 0, new Intent(ACTION_HEARTBEAT, null, this, McsService.class), PendingIntent.FLAG_IMMUTABLE);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
powerManager = (PowerManager) getSystemService(POWER_SERVICE);
if (SDK_INT >= 23 && checkSelfPermission("android.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST") == PackageManager.PERMISSION_GRANTED) {
try {
if (SDK_INT >= 31) {
Class<?> powerExemptionManagerClass = Class.forName("android.os.PowerExemptionManager");
powerExemptionManager = getSystemService(powerExemptionManagerClass);
addToTemporaryAllowListMethod =
powerExemptionManagerClass.getMethod("addToTemporaryAllowList", String.class, int.class, String.class, long.class);
} else {
String deviceIdleControllerName = "deviceidle";
try {
Field field = Context.class.getField("DEVICE_IDLE_CONTROLLER");
deviceIdleControllerName = (String) field.get(null);
} catch (Exception ignored) {
}
IBinder binder = (IBinder) Class.forName("android.os.ServiceManager")
.getMethod("getService", String.class).invoke(null, deviceIdleControllerName);
if (binder != null) {
deviceIdleController = Class.forName("android.os.IDeviceIdleController$Stub")
.getMethod("asInterface", IBinder.class).invoke(null, binder);
getUserIdMethod = UserHandle.class.getMethod("getUserId", int.class);
addPowerSaveTempWhitelistAppMethod = deviceIdleController.getClass()
.getMethod("addPowerSaveTempWhitelistApp", String.class, long.class, int.class, String.class);
}
}
} catch (Exception e) {
Log.w(TAG, e);
}
}
synchronized (McsService.class) {
if (handlerThread == null) {
handlerThread = new HandlerThread();
handlerThread.start();
}
}
}
public static void stop(Context context) {
context.stopService(new Intent(context, McsService.class));
closeAll();
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
alarmManager.cancel(heartbeatIntent);
closeAll();
database.close();
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public synchronized static boolean isConnected(Context context) { | /*
* Copyright (C) 2013-2017 microG Project Team
*
* 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.microg.gms.gcm;
@ForegroundServiceInfo(value = "Cloud messaging", resName = "service_name_mcs", resPackage = "com.google.android.gms")
public class McsService extends Service implements Handler.Callback {
private static final String TAG = "GmsGcmMcsSvc";
public static final String SELF_CATEGORY = "com.google.android.gsf.gtalkservice";
public static final String IDLE_NOTIFICATION = "IdleNotification";
public static final String FROM_FIELD = "gcm@android.com";
public static final String SERVICE_HOST = "mtalk.google.com";
// A few ports are available: 443, 5228-5230 but also 5222-5223
// See https://github.com/microg/GmsCore/issues/408
// Likely if the main port 5228 is blocked by a firewall, the other 52xx are blocked as well
public static final int[] SERVICE_PORTS = {5228, 443};
private static final int WAKELOCK_TIMEOUT = 5000;
// On bad mobile network a ping can take >60s, so we wait for an ACK for 90s
private static final int HEARTBEAT_ACK_AFTER_PING_TIMEOUT_MS = 90000;
private static long lastHeartbeatPingElapsedRealtime = -1;
private static long lastHeartbeatAckElapsedRealtime = -1;
private static long lastIncomingNetworkRealtime = 0;
private static long startTimestamp = 0;
public static String activeNetworkPref = null;
private boolean wasTornDown = false;
private AtomicInteger nextMessageId = new AtomicInteger(0x1000000);
private static Socket sslSocket;
private static McsInputStream inputStream;
private static McsOutputStream outputStream;
private PendingIntent heartbeatIntent;
private static HandlerThread handlerThread;
private static Handler rootHandler;
private GcmDatabase database;
private AlarmManager alarmManager;
private PowerManager powerManager;
private static PowerManager.WakeLock wakeLock;
private static long currentDelay = 0;
private Intent connectIntent;
private static int maxTtl = 24 * 60 * 60;
@Nullable
private Method getUserIdMethod;
@Nullable
private Object deviceIdleController;
@Nullable
private Method addPowerSaveTempWhitelistAppMethod;
@Nullable
@RequiresApi(31)
private Object powerExemptionManager;
@Nullable
@RequiresApi(31)
private Method addToTemporaryAllowListMethod;
private class HandlerThread extends Thread {
public HandlerThread() {
setName("McsHandler");
}
@Override
public void run() {
Looper.prepare();
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "mcs");
wakeLock.setReferenceCounted(false);
synchronized (McsService.class) {
rootHandler = new Handler(Looper.myLooper(), McsService.this);
if (connectIntent != null) {
rootHandler.sendMessage(rootHandler.obtainMessage(MSG_CONNECT, connectIntent));
WakefulBroadcastReceiver.completeWakefulIntent(connectIntent);
}
}
Looper.loop();
}
}
private static void logd(Context context, String msg) {
if (context == null || GcmPrefs.get(context).isGcmLogEnabled()) Log.d(TAG, msg);
}
@Override
@SuppressLint("PrivateApi")
public void onCreate() {
super.onCreate();
TriggerReceiver.register(this);
database = new GcmDatabase(this);
heartbeatIntent = PendingIntent.getService(this, 0, new Intent(ACTION_HEARTBEAT, null, this, McsService.class), PendingIntent.FLAG_IMMUTABLE);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
powerManager = (PowerManager) getSystemService(POWER_SERVICE);
if (SDK_INT >= 23 && checkSelfPermission("android.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST") == PackageManager.PERMISSION_GRANTED) {
try {
if (SDK_INT >= 31) {
Class<?> powerExemptionManagerClass = Class.forName("android.os.PowerExemptionManager");
powerExemptionManager = getSystemService(powerExemptionManagerClass);
addToTemporaryAllowListMethod =
powerExemptionManagerClass.getMethod("addToTemporaryAllowList", String.class, int.class, String.class, long.class);
} else {
String deviceIdleControllerName = "deviceidle";
try {
Field field = Context.class.getField("DEVICE_IDLE_CONTROLLER");
deviceIdleControllerName = (String) field.get(null);
} catch (Exception ignored) {
}
IBinder binder = (IBinder) Class.forName("android.os.ServiceManager")
.getMethod("getService", String.class).invoke(null, deviceIdleControllerName);
if (binder != null) {
deviceIdleController = Class.forName("android.os.IDeviceIdleController$Stub")
.getMethod("asInterface", IBinder.class).invoke(null, binder);
getUserIdMethod = UserHandle.class.getMethod("getUserId", int.class);
addPowerSaveTempWhitelistAppMethod = deviceIdleController.getClass()
.getMethod("addPowerSaveTempWhitelistApp", String.class, long.class, int.class, String.class);
}
}
} catch (Exception e) {
Log.w(TAG, e);
}
}
synchronized (McsService.class) {
if (handlerThread == null) {
handlerThread = new HandlerThread();
handlerThread.start();
}
}
}
public static void stop(Context context) {
context.stopService(new Intent(context, McsService.class));
closeAll();
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
alarmManager.cancel(heartbeatIntent);
closeAll();
database.close();
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public synchronized static boolean isConnected(Context context) { | warnIfNotPersistentProcess(McsService.class); | 2 | 2023-12-17 16:14:53+00:00 | 12k |
Yolka5/FTC-Imu3 | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/opmode/OnlyParkingRight.java | [
{
"identifier": "SampleMecanumDrive",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java",
"snippet": "@Config\npublic class SampleMecanumDrive extends MecanumDrive {\n public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(2, 0, 0);\n publi... | import com.acmerobotics.roadrunner.geometry.Pose2d;
import com.acmerobotics.roadrunner.geometry.Vector2d;
import com.acmerobotics.roadrunner.trajectory.Trajectory;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.ColorSensor;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorEx;
import com.qualcomm.robotcore.hardware.DistanceSensor;
import com.qualcomm.robotcore.hardware.OpticalDistanceSensor;
import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit;
import org.firstinspires.ftc.teamcode.drive.SampleMecanumDrive;
import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence;
import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName;
import org.openftc.apriltag.AprilTagDetection;
import org.openftc.easyopencv.OpenCvCamera;
import org.openftc.easyopencv.OpenCvCameraFactory;
import org.openftc.easyopencv.OpenCvCameraRotation;
import org.openftc.easyopencv.OpenCvInternalCamera;
import java.util.ArrayList; | 9,951 | package org.firstinspires.ftc.teamcode.drive.opmode;
@Autonomous(group = "drive")
public class OnlyParkingRight extends LinearOpMode {
public static double SPEED = 0.15;
OpticalDistanceSensor lightSensor;
ColorSensor colorSensor;
DistanceSensor distanceSensor;
Boolean RedFirstTime = false;
public double correction;
public static double FirstDistance = -25;
boolean Starting = false;
boolean SawRed = false;
boolean SawCancer = false;
boolean SawCancer1 = false;
int ConusIndex = 0;
double value;
OpenCvCamera camera;
AprilTagDetectionPipeline aprilTagDetectionPipeline;
static final double FEET_PER_METER = 3.28084;
// Lens intrinsics
// UNITS ARE PIXELS
// NOTE: this calibration is for the C920 webcam at 800x448.
// You will need to do your own calibration for other configurations!
double fx = 578.272;
double fy = 578.272;
double cx = 402.145;
double cy = 221.506;
// UNITS ARE METERS
double tagsize = 0.166;
// Tag ID 1,2,3 from the 36h11 family
/*EDIT IF NEEDED!!!*/
int LEFT = 1;
int MIDDLE = 2;
int RIGHT = 3;
boolean Parking = false;
int wantedId;
AprilTagDetection tagOfInterest = null;
@Override
public void runOpMode() throws InterruptedException {
int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName());
camera = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName.class, "Webcam 1"), cameraMonitorViewId);
aprilTagDetectionPipeline = new AprilTagDetectionPipeline(tagsize, fx, fy, cx, cy);
camera.setPipeline(aprilTagDetectionPipeline);
camera.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener()
{
@Override
public void onOpened()
{
camera.startStreaming(800,448, OpenCvCameraRotation.UPRIGHT);
}
@Override
public void onError(int errorCode)
{
}
});
telemetry.setMsTransmissionInterval(50);
/*
* The INIT-loop:
* This REPLACES waitForStart!
*/
while (!isStarted() && !isStopRequested())
{
ArrayList<AprilTagDetection> currentDetections = aprilTagDetectionPipeline.getLatestDetections();
if(currentDetections.size() != 0)
{
boolean tagFound = false;
for(AprilTagDetection tag : currentDetections)
{
if(tag.id == LEFT || tag.id == MIDDLE || tag.id == RIGHT)
{
tagOfInterest = tag;
tagFound = true;
break;
}
}
if(tagFound)
{
telemetry.addLine("Tag of interest is in sight!\n\nLocation data:");
tagToTelemetry(tagOfInterest);
wantedId = tagOfInterest.id;
}
else
{
telemetry.addLine("Don't see tag of interest :(");
if(tagOfInterest == null)
{
telemetry.addLine("(The tag has never been seen)");
}
else
{
telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:");
tagToTelemetry(tagOfInterest);
}
}
}
else
{
telemetry.addLine("Don't see tag of interest :(");
if(tagOfInterest == null)
{
telemetry.addLine("(The tag has never been seen)");
}
else
{
telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:");
tagToTelemetry(tagOfInterest);
}
}
telemetry.update();
sleep(20);
}
SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap);
colorSensor = hardwareMap.get(ColorSensor.class, "sensor_color");
distanceSensor = hardwareMap.get(DistanceSensor.class, "DistanceSensor");
waitForStart();
if (isStopRequested()) return;
//--------------------------------------------------------------------------------------
Trajectory trajectoryForwardFirst = drive.trajectoryBuilder(new Pose2d())
.forward(FirstDistance)
.build();
| package org.firstinspires.ftc.teamcode.drive.opmode;
@Autonomous(group = "drive")
public class OnlyParkingRight extends LinearOpMode {
public static double SPEED = 0.15;
OpticalDistanceSensor lightSensor;
ColorSensor colorSensor;
DistanceSensor distanceSensor;
Boolean RedFirstTime = false;
public double correction;
public static double FirstDistance = -25;
boolean Starting = false;
boolean SawRed = false;
boolean SawCancer = false;
boolean SawCancer1 = false;
int ConusIndex = 0;
double value;
OpenCvCamera camera;
AprilTagDetectionPipeline aprilTagDetectionPipeline;
static final double FEET_PER_METER = 3.28084;
// Lens intrinsics
// UNITS ARE PIXELS
// NOTE: this calibration is for the C920 webcam at 800x448.
// You will need to do your own calibration for other configurations!
double fx = 578.272;
double fy = 578.272;
double cx = 402.145;
double cy = 221.506;
// UNITS ARE METERS
double tagsize = 0.166;
// Tag ID 1,2,3 from the 36h11 family
/*EDIT IF NEEDED!!!*/
int LEFT = 1;
int MIDDLE = 2;
int RIGHT = 3;
boolean Parking = false;
int wantedId;
AprilTagDetection tagOfInterest = null;
@Override
public void runOpMode() throws InterruptedException {
int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName());
camera = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName.class, "Webcam 1"), cameraMonitorViewId);
aprilTagDetectionPipeline = new AprilTagDetectionPipeline(tagsize, fx, fy, cx, cy);
camera.setPipeline(aprilTagDetectionPipeline);
camera.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener()
{
@Override
public void onOpened()
{
camera.startStreaming(800,448, OpenCvCameraRotation.UPRIGHT);
}
@Override
public void onError(int errorCode)
{
}
});
telemetry.setMsTransmissionInterval(50);
/*
* The INIT-loop:
* This REPLACES waitForStart!
*/
while (!isStarted() && !isStopRequested())
{
ArrayList<AprilTagDetection> currentDetections = aprilTagDetectionPipeline.getLatestDetections();
if(currentDetections.size() != 0)
{
boolean tagFound = false;
for(AprilTagDetection tag : currentDetections)
{
if(tag.id == LEFT || tag.id == MIDDLE || tag.id == RIGHT)
{
tagOfInterest = tag;
tagFound = true;
break;
}
}
if(tagFound)
{
telemetry.addLine("Tag of interest is in sight!\n\nLocation data:");
tagToTelemetry(tagOfInterest);
wantedId = tagOfInterest.id;
}
else
{
telemetry.addLine("Don't see tag of interest :(");
if(tagOfInterest == null)
{
telemetry.addLine("(The tag has never been seen)");
}
else
{
telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:");
tagToTelemetry(tagOfInterest);
}
}
}
else
{
telemetry.addLine("Don't see tag of interest :(");
if(tagOfInterest == null)
{
telemetry.addLine("(The tag has never been seen)");
}
else
{
telemetry.addLine("\nBut we HAVE seen the tag before; last seen at:");
tagToTelemetry(tagOfInterest);
}
}
telemetry.update();
sleep(20);
}
SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap);
colorSensor = hardwareMap.get(ColorSensor.class, "sensor_color");
distanceSensor = hardwareMap.get(DistanceSensor.class, "DistanceSensor");
waitForStart();
if (isStopRequested()) return;
//--------------------------------------------------------------------------------------
Trajectory trajectoryForwardFirst = drive.trajectoryBuilder(new Pose2d())
.forward(FirstDistance)
.build();
| TrajectorySequence trajectorySignalOne = drive.trajectorySequenceBuilder(new Pose2d()) | 1 | 2023-12-15 16:57:19+00:00 | 12k |
PeytonPlayz595/0.30-WebGL-Server | src/com/mojang/minecraft/server/MinecraftServer.java | [
{
"identifier": "LevelIO",
"path": "src/com/mojang/minecraft/level/LevelIO.java",
"snippet": "public final class LevelIO {\r\n\r\n private MinecraftServer server;\r\n\r\n\r\n public LevelIO(MinecraftServer var1) {\r\n this.server = var1;\r\n }\r\n\r\n public final Level load(InputStream var... | import com.mojang.minecraft.level.LevelIO;
import com.mojang.minecraft.level.generator.LevelGenerator;
import com.mojang.minecraft.net.PacketType;
import com.mojang.net.BindTo;
import com.mojang.net.NetworkHandler;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
| 9,658 | package com.mojang.minecraft.server;
public class MinecraftServer implements Runnable {
static Logger logger = Logger.getLogger("MinecraftServer");
static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
private BindTo bindTo;
private Map m = new HashMap();
private List n = new ArrayList();
private List o = new ArrayList();
private Properties properties = new Properties();
public com.mojang.minecraft.level.Level mainLevel;
public String serverName;
public String MOTD;
public boolean adminSlot;
private NetworkManager[] networkManager;
public PlayerManager playerManager1 = new PlayerManager("Admins", new File("admins.txt"));
public PlayerManager playerManager2 = new PlayerManager("Banned", new File("banned.txt"));
private PlayerManager playerManager3 = new PlayerManager("Banned (IP)", new File("banned-ip.txt"));
public PlayerManager playerManager4 = new PlayerManager("Players", new File("players.txt"));
private List v = new ArrayList();
private String salt = "" + (new Random()).nextLong();
private String x = "";
private boolean growTrees;
public MinecraftServer() {
this.growTrees = false;
try {
this.properties.load(new FileReader("server.properties"));
} catch (Exception var4) {
logger.warning("Failed to load server.properties!");
}
try {
this.serverName = this.properties.getProperty("server-name", "Minecraft Server");
this.MOTD = this.properties.getProperty("motd", "Welcome to my Minecraft Server!");
this.growTrees = Boolean.parseBoolean(this.properties.getProperty("grow-trees", "false"));
this.adminSlot = Boolean.parseBoolean(this.properties.getProperty("admin-slot", "false"));
this.properties.setProperty("server-name", this.serverName);
this.properties.setProperty("motd", this.MOTD);
this.properties.setProperty("max-connections", "3");
this.properties.setProperty("grow-trees", "" + this.growTrees);
this.properties.setProperty("admin-slot", "" + this.adminSlot);
} catch (Exception var3) {
var3.printStackTrace();
logger.warning("server.properties is broken! Delete it or fix it!");
System.exit(0);
}
try {
this.properties.store(new FileWriter("server.properties"), "Minecraft server properties");
} catch (Exception var2) {
logger.warning("Failed to save server.properties!");
}
this.networkManager = new NetworkManager[32];
this.bindTo = new BindTo(this);
(new ConsoleInput(this)).start();
}
| package com.mojang.minecraft.server;
public class MinecraftServer implements Runnable {
static Logger logger = Logger.getLogger("MinecraftServer");
static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
private BindTo bindTo;
private Map m = new HashMap();
private List n = new ArrayList();
private List o = new ArrayList();
private Properties properties = new Properties();
public com.mojang.minecraft.level.Level mainLevel;
public String serverName;
public String MOTD;
public boolean adminSlot;
private NetworkManager[] networkManager;
public PlayerManager playerManager1 = new PlayerManager("Admins", new File("admins.txt"));
public PlayerManager playerManager2 = new PlayerManager("Banned", new File("banned.txt"));
private PlayerManager playerManager3 = new PlayerManager("Banned (IP)", new File("banned-ip.txt"));
public PlayerManager playerManager4 = new PlayerManager("Players", new File("players.txt"));
private List v = new ArrayList();
private String salt = "" + (new Random()).nextLong();
private String x = "";
private boolean growTrees;
public MinecraftServer() {
this.growTrees = false;
try {
this.properties.load(new FileReader("server.properties"));
} catch (Exception var4) {
logger.warning("Failed to load server.properties!");
}
try {
this.serverName = this.properties.getProperty("server-name", "Minecraft Server");
this.MOTD = this.properties.getProperty("motd", "Welcome to my Minecraft Server!");
this.growTrees = Boolean.parseBoolean(this.properties.getProperty("grow-trees", "false"));
this.adminSlot = Boolean.parseBoolean(this.properties.getProperty("admin-slot", "false"));
this.properties.setProperty("server-name", this.serverName);
this.properties.setProperty("motd", this.MOTD);
this.properties.setProperty("max-connections", "3");
this.properties.setProperty("grow-trees", "" + this.growTrees);
this.properties.setProperty("admin-slot", "" + this.adminSlot);
} catch (Exception var3) {
var3.printStackTrace();
logger.warning("server.properties is broken! Delete it or fix it!");
System.exit(0);
}
try {
this.properties.store(new FileWriter("server.properties"), "Minecraft server properties");
} catch (Exception var2) {
logger.warning("Failed to save server.properties!");
}
this.networkManager = new NetworkManager[32];
this.bindTo = new BindTo(this);
(new ConsoleInput(this)).start();
}
| public final void a(NetworkHandler var1) {
| 4 | 2023-12-18 15:38:59+00:00 | 12k |
Frig00/Progetto-Ing-Software | src/main/java/it/unipv/po/aioobe/trenissimo/view/AcquistoVoucherView.java | [
{
"identifier": "AccountSettingsController",
"path": "src/main/java/it/unipv/po/aioobe/trenissimo/controller/AccountSettingsController.java",
"snippet": "public class AccountSettingsController implements Initializable {\n\n\n @FXML\n private Button btnModifica;\n @FXML\n private Button btnAn... | import it.unipv.po.aioobe.trenissimo.controller.AccountSettingsController;
import it.unipv.po.aioobe.trenissimo.controller.AcquistoVoucherController;
import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.enumeration.ValoreVoucher;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
import org.jetbrains.annotations.NotNull;
import java.io.IOException; | 8,164 | package it.unipv.po.aioobe.trenissimo.view;
/**
* Main class che gestisce il render del file acquistoVoucher.fxml
*
* @author ArrayIndexOutOfBoundsException
* @see Application
* @see it.unipv.po.aioobe.trenissimo.view.acquistoVoucher
*/
public class AcquistoVoucherView extends Application {
/**
* Lancia il render della parte grafica
*
* @param args argomenti da linea di comando
* @see #launch(String...)
*/
public static void main(String[] args) {
launch();
}
/**
* Risponde alle chiamate esterne di altri componenti
*
* @param owner finestra che contiene l'elemento che ha chiamato il metodo
* @see Login
* @see AccountSettingsController
*/
public static void openWindow(Window owner) {
FXMLLoader fxmlLoader = new FXMLLoader(HomePage.class.getResource("acquistoVoucher/acquistoVoucher.fxml"));
Stage stage = new Stage();
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(owner);
Scene scene = null;
try {
scene = new Scene(fxmlLoader.load(), 800, 600);
} catch (IOException e) {
e.printStackTrace();
}
stage.setTitle("AcquistoVoucher");
stage.setScene(scene);
stage.show();
}
/**
* Risponde alle chiamate esterne di altri componenti
*
* @param owner finestra che contiene l'elemento che ha chiamato il metodo
* @param importo lista di viaggi da visualizzare
* @see ValoreVoucher
* @see HomePage
* @see AcquistoVoucherController
*/ | package it.unipv.po.aioobe.trenissimo.view;
/**
* Main class che gestisce il render del file acquistoVoucher.fxml
*
* @author ArrayIndexOutOfBoundsException
* @see Application
* @see it.unipv.po.aioobe.trenissimo.view.acquistoVoucher
*/
public class AcquistoVoucherView extends Application {
/**
* Lancia il render della parte grafica
*
* @param args argomenti da linea di comando
* @see #launch(String...)
*/
public static void main(String[] args) {
launch();
}
/**
* Risponde alle chiamate esterne di altri componenti
*
* @param owner finestra che contiene l'elemento che ha chiamato il metodo
* @see Login
* @see AccountSettingsController
*/
public static void openWindow(Window owner) {
FXMLLoader fxmlLoader = new FXMLLoader(HomePage.class.getResource("acquistoVoucher/acquistoVoucher.fxml"));
Stage stage = new Stage();
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(owner);
Scene scene = null;
try {
scene = new Scene(fxmlLoader.load(), 800, 600);
} catch (IOException e) {
e.printStackTrace();
}
stage.setTitle("AcquistoVoucher");
stage.setScene(scene);
stage.show();
}
/**
* Risponde alle chiamate esterne di altri componenti
*
* @param owner finestra che contiene l'elemento che ha chiamato il metodo
* @param importo lista di viaggi da visualizzare
* @see ValoreVoucher
* @see HomePage
* @see AcquistoVoucherController
*/ | public static void openScene(Window owner, ValoreVoucher importo) { | 2 | 2023-12-21 10:41:11+00:00 | 12k |
chulakasam/layered | src/main/java/com/example/layeredarchitecture/controller/PlaceOrderFormController.java | [
{
"identifier": "BOFactory",
"path": "src/main/java/com/example/layeredarchitecture/bo/BOFactory.java",
"snippet": "public class BOFactory {\n private static BOFactory boFactory;\n private BOFactory(){\n\n }\n public static BOFactory getBOFactory(){\n return (boFactory==null) ? boFact... | import com.example.layeredarchitecture.bo.BOFactory;
import com.example.layeredarchitecture.bo.PlaceOrderBO;
import com.example.layeredarchitecture.bo.PlaceOrderBOImpl;
import com.example.layeredarchitecture.dao.custom.CustomerDAO;
import com.example.layeredarchitecture.dao.custom.Impl.CustomerDAOImpl;
import com.example.layeredarchitecture.dao.custom.Impl.ItemDAO;
import com.example.layeredarchitecture.dao.custom.Impl.OrderDAO;
import com.example.layeredarchitecture.dao.custom.Impl.OrderDetailDAOImpl;
import com.example.layeredarchitecture.dao.custom.ItemDao;
import com.example.layeredarchitecture.dao.custom.OrderDao;
import com.example.layeredarchitecture.dao.custom.OrderDetailDAO;
import com.example.layeredarchitecture.db.DBConnection;
import com.example.layeredarchitecture.model.CustomerDTO;
import com.example.layeredarchitecture.model.ItemDTO;
import com.example.layeredarchitecture.model.OrderDetailDTO;
import com.example.layeredarchitecture.view.tdm.OrderDetailTM;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; | 7,612 | package com.example.layeredarchitecture.controller;
public class PlaceOrderFormController {
public AnchorPane root;
public JFXButton btnPlaceOrder;
public TextField txtCustomerName;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnSave;
public TableView<OrderDetailTM> tblOrderDetails;
public TextField txtUnitPrice;
public JFXComboBox<String> cmbCustomerId;
public JFXComboBox<String> cmbItemCode;
public TextField txtQty;
public Label lblId;
public Label lblDate;
public Label lblTotal;
private String orderId;
PlaceOrderBO placeOrderBO = (PlaceOrderBO) BOFactory.getBOFactory().getBOFactory(BOFactory.BOTypes.PLACE_ORDER);
public void initialize() throws SQLException, ClassNotFoundException {
tblOrderDetails.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code"));
tblOrderDetails.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description"));
tblOrderDetails.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qty"));
tblOrderDetails.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice"));
tblOrderDetails.getColumns().get(4).setCellValueFactory(new PropertyValueFactory<>("total"));
TableColumn<OrderDetailTM, Button> lastCol = (TableColumn<OrderDetailTM, Button>) tblOrderDetails.getColumns().get(5);
lastCol.setCellValueFactory(param -> {
Button btnDelete = new Button("Delete");
btnDelete.setOnAction(event -> {
tblOrderDetails.getItems().remove(param.getValue());
tblOrderDetails.getSelectionModel().clearSelection();
calculateTotal();
enableOrDisablePlaceOrderButton();
});
return new ReadOnlyObjectWrapper<>(btnDelete);
});
orderId = generateNewOrderId();
lblId.setText("Order ID: " + orderId);
lblDate.setText(LocalDate.now().toString());
btnPlaceOrder.setDisable(true);
txtCustomerName.setFocusTraversable(false);
txtCustomerName.setEditable(false);
txtDescription.setFocusTraversable(false);
txtDescription.setEditable(false);
txtUnitPrice.setFocusTraversable(false);
txtUnitPrice.setEditable(false);
txtQtyOnHand.setFocusTraversable(false);
txtQtyOnHand.setEditable(false);
txtQty.setOnAction(event -> btnSave.fire());
txtQty.setEditable(false);
btnSave.setDisable(true);
cmbCustomerId.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
enableOrDisablePlaceOrderButton();
if (newValue != null) {
try {
/*Search Customer*/
Connection connection = DBConnection.getDbConnection().getConnection();
try {
//CustomerDAOImpl customerDAO = new CustomerDAOImpl();
if (!placeOrderBO.existCustomer(newValue + "")) {
// "There is no such customer associated with the id " + id
new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show();
}
PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Customer WHERE id=?");
pstm.setString(1, newValue + "");
ResultSet rst = pstm.executeQuery();
rst.next(); | package com.example.layeredarchitecture.controller;
public class PlaceOrderFormController {
public AnchorPane root;
public JFXButton btnPlaceOrder;
public TextField txtCustomerName;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnSave;
public TableView<OrderDetailTM> tblOrderDetails;
public TextField txtUnitPrice;
public JFXComboBox<String> cmbCustomerId;
public JFXComboBox<String> cmbItemCode;
public TextField txtQty;
public Label lblId;
public Label lblDate;
public Label lblTotal;
private String orderId;
PlaceOrderBO placeOrderBO = (PlaceOrderBO) BOFactory.getBOFactory().getBOFactory(BOFactory.BOTypes.PLACE_ORDER);
public void initialize() throws SQLException, ClassNotFoundException {
tblOrderDetails.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code"));
tblOrderDetails.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description"));
tblOrderDetails.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qty"));
tblOrderDetails.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice"));
tblOrderDetails.getColumns().get(4).setCellValueFactory(new PropertyValueFactory<>("total"));
TableColumn<OrderDetailTM, Button> lastCol = (TableColumn<OrderDetailTM, Button>) tblOrderDetails.getColumns().get(5);
lastCol.setCellValueFactory(param -> {
Button btnDelete = new Button("Delete");
btnDelete.setOnAction(event -> {
tblOrderDetails.getItems().remove(param.getValue());
tblOrderDetails.getSelectionModel().clearSelection();
calculateTotal();
enableOrDisablePlaceOrderButton();
});
return new ReadOnlyObjectWrapper<>(btnDelete);
});
orderId = generateNewOrderId();
lblId.setText("Order ID: " + orderId);
lblDate.setText(LocalDate.now().toString());
btnPlaceOrder.setDisable(true);
txtCustomerName.setFocusTraversable(false);
txtCustomerName.setEditable(false);
txtDescription.setFocusTraversable(false);
txtDescription.setEditable(false);
txtUnitPrice.setFocusTraversable(false);
txtUnitPrice.setEditable(false);
txtQtyOnHand.setFocusTraversable(false);
txtQtyOnHand.setEditable(false);
txtQty.setOnAction(event -> btnSave.fire());
txtQty.setEditable(false);
btnSave.setDisable(true);
cmbCustomerId.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
enableOrDisablePlaceOrderButton();
if (newValue != null) {
try {
/*Search Customer*/
Connection connection = DBConnection.getDbConnection().getConnection();
try {
//CustomerDAOImpl customerDAO = new CustomerDAOImpl();
if (!placeOrderBO.existCustomer(newValue + "")) {
// "There is no such customer associated with the id " + id
new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show();
}
PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Customer WHERE id=?");
pstm.setString(1, newValue + "");
ResultSet rst = pstm.executeQuery();
rst.next(); | CustomerDTO customerDTO = new CustomerDTO(newValue + "", rst.getString("name"), rst.getString("address")); | 12 | 2023-12-15 04:45:10+00:00 | 12k |
pan2013e/ppt4j | framework/src/main/java/ppt4j/factory/ExtractorFactory.java | [
{
"identifier": "CrossMatcher",
"path": "framework/src/main/java/ppt4j/analysis/patch/CrossMatcher.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic interface CrossMatcher {\n\n SourceType getKeyType();\n\n SourceType getValueType();\n\n boolean isMatched(int index);\n\n double getSco... | import ppt4j.analysis.patch.CrossMatcher;
import ppt4j.database.DatabaseType;
import ppt4j.database.Vulnerability;
import ppt4j.feature.bytecode.BytecodeExtractor;
import ppt4j.feature.java.JavaExtractor;
import ppt4j.util.FileUtils;
import ppt4j.util.ResourceUtils;
import ppt4j.util.StringUtils;
import ppt4j.util.VMUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
import spoon.Launcher;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtImport;
import spoon.reflect.reference.CtTypeReference;
import spoon.reflect.visitor.ImportScannerImpl;
import spoon.support.compiler.jdt.CompilationUnitFilter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile; | 8,502 | package ppt4j.factory;
@Log4j
public final class ExtractorFactory {
String prepatchPath, postpatchPath;
String[] thirdPartySrcPath;
@Getter
String classPath;
boolean isJar = false;
private JarFile jarFile = null;
@Setter
Vulnerability vuln = null;
final Map<String, JavaExtractor> cachedPreExtractors = new HashMap<>();
final Map<String, JavaExtractor> cachedPostExtractors = new HashMap<>();
final Map<String, BytecodeExtractor> cachedBytecodeExtractors = new HashMap<>();
final Map<String, CrossMatcher> cachedPre2Class = new HashMap<>();
final Map<String, CrossMatcher> cachedPost2Class = new HashMap<>();
public static ExtractorFactory get(String prepatchPath,
String postpatchPath,
String classPath,
String... thirdPartySrcPath) {
return new ExtractorFactory(prepatchPath, postpatchPath,
classPath, thirdPartySrcPath);
}
public static ExtractorFactory get(Vulnerability vuln,
DatabaseType type) {
String prepatchPath = StringUtils.getDatabasePrepatchSrcPath(vuln);
String postpatchPath = StringUtils.getDatabasePostpatchSrcPath(vuln);
String classPath = Path.of(
type.getPath(vuln.getDatabaseId()),
vuln.getClassesTopLevelDir()
).toString(); | package ppt4j.factory;
@Log4j
public final class ExtractorFactory {
String prepatchPath, postpatchPath;
String[] thirdPartySrcPath;
@Getter
String classPath;
boolean isJar = false;
private JarFile jarFile = null;
@Setter
Vulnerability vuln = null;
final Map<String, JavaExtractor> cachedPreExtractors = new HashMap<>();
final Map<String, JavaExtractor> cachedPostExtractors = new HashMap<>();
final Map<String, BytecodeExtractor> cachedBytecodeExtractors = new HashMap<>();
final Map<String, CrossMatcher> cachedPre2Class = new HashMap<>();
final Map<String, CrossMatcher> cachedPost2Class = new HashMap<>();
public static ExtractorFactory get(String prepatchPath,
String postpatchPath,
String classPath,
String... thirdPartySrcPath) {
return new ExtractorFactory(prepatchPath, postpatchPath,
classPath, thirdPartySrcPath);
}
public static ExtractorFactory get(Vulnerability vuln,
DatabaseType type) {
String prepatchPath = StringUtils.getDatabasePrepatchSrcPath(vuln);
String postpatchPath = StringUtils.getDatabasePostpatchSrcPath(vuln);
String classPath = Path.of(
type.getPath(vuln.getDatabaseId()),
vuln.getClassesTopLevelDir()
).toString(); | VMUtils.checkVMClassPathPresent(classPath); | 8 | 2023-12-14 15:33:50+00:00 | 12k |
f1den/MrCrayfishGunMod | src/main/java/com/mrcrayfish/guns/common/ProjectileManager.java | [
{
"identifier": "ProjectileEntity",
"path": "src/main/java/com/mrcrayfish/guns/entity/ProjectileEntity.java",
"snippet": "public class ProjectileEntity extends Entity implements IEntityAdditionalSpawnData\n{\n private static final Predicate<Entity> PROJECTILE_TARGETS = input -> input != null && input... | import com.mrcrayfish.guns.entity.ProjectileEntity;
import com.mrcrayfish.guns.init.ModEntities;
import com.mrcrayfish.guns.interfaces.IProjectileFactory;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraftforge.registries.ForgeRegistries;
import java.util.HashMap;
import java.util.Map; | 8,575 | package com.mrcrayfish.guns.common;
/**
* A class to manage custom projectile factories
*
* Author: MrCrayfish
*/
public class ProjectileManager
{
private static ProjectileManager instance = null;
public static ProjectileManager getInstance()
{
if(instance == null)
{
instance = new ProjectileManager();
}
return instance;
}
| package com.mrcrayfish.guns.common;
/**
* A class to manage custom projectile factories
*
* Author: MrCrayfish
*/
public class ProjectileManager
{
private static ProjectileManager instance = null;
public static ProjectileManager getInstance()
{
if(instance == null)
{
instance = new ProjectileManager();
}
return instance;
}
| private final IProjectileFactory DEFAULT_FACTORY = (worldIn, entity, weapon, item, modifiedGun) -> new ProjectileEntity(ModEntities.PROJECTILE.get(), worldIn, entity, weapon, item, modifiedGun); | 1 | 2023-12-18 15:04:35+00:00 | 12k |
Team319/SwerveTemplate_with_AK | src/main/java/frc/robot/RobotContainer.java | [
{
"identifier": "DriveCommands",
"path": "src/main/java/frc/robot/commands/DriveCommands.java",
"snippet": "public class DriveCommands {\n private static final double DEADBAND = 0.2;\n private static final double JOYSTICK_GOVERNOR = 0.3; // this value must not exceed 1.0\n private static final double... | import com.pathplanner.lib.auto.AutoBuilder;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.wpilibj.GenericHID;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.Commands;
import edu.wpi.first.wpilibj2.command.button.CommandXboxController;
import frc.robot.commands.DriveCommands;
import frc.robot.commands.FeedForwardCharacterization;
import frc.robot.subsystems.drive.Drive;
import frc.robot.subsystems.drive.GyroIO;
import frc.robot.subsystems.drive.GyroIOPigeon2;
import frc.robot.subsystems.drive.ModuleIO;
import frc.robot.subsystems.drive.ModuleIOSim;
import frc.robot.subsystems.drive.ModuleIOTalonFX;
import org.littletonrobotics.junction.networktables.LoggedDashboardChooser; | 7,295 | // Copyright 2021-2023 FRC 6328
// http://github.com/Mechanical-Advantage
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// version 3 as published by the Free Software Foundation or
// available in the root directory of this project.
//
// 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.
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 button mappings) should be declared here.
*/
public class RobotContainer {
// Subsystems
private final Drive drive;
// private final Flywheel flywheel;
// Controller
private final CommandXboxController controller = new CommandXboxController(0);
// Dashboard inputs
private final LoggedDashboardChooser<Command> autoChooser;
// private final LoggedDashboardNumber flywheelSpeedInput =
// new LoggedDashboardNumber("Flywheel Speed", 1500.0);
/** The container for the robot. Contains subsystems, OI devices, and commands. */
public RobotContainer() {
switch (Constants.currentMode) {
case REAL:
// Real robot, instantiate hardware IO implementations
// drive =
// new Drive(
// new GyroIOPigeon2(),
// new ModuleIOSparkMax(0),
// new ModuleIOSparkMax(1),
// new ModuleIOSparkMax(2),
// new ModuleIOSparkMax(3));
// flywheel = new Flywheel(new FlywheelIOSparkMax());
drive =
new Drive(
new GyroIOPigeon2(),
new ModuleIOTalonFX(0),
new ModuleIOTalonFX(1),
new ModuleIOTalonFX(2),
new ModuleIOTalonFX(3));
// flywheel = new Flywheel(new FlywheelIOTalonFX());
break;
case SIM:
// Sim robot, instantiate physics sim IO implementations
drive =
new Drive(
new GyroIO() {},
new ModuleIOSim(),
new ModuleIOSim(),
new ModuleIOSim(),
new ModuleIOSim());
// flywheel = new Flywheel(new FlywheelIOSim());
break;
default:
// Replayed robot, disable IO implementations
drive =
new Drive(
new GyroIO() {},
new ModuleIO() {},
new ModuleIO() {},
new ModuleIO() {},
new ModuleIO() {});
// flywheel = new Flywheel(new FlywheelIO() {});
break;
}
// Set up named commands for PathPlanner
// NamedCommands.registerCommand(
// "Run Flywheel",
// Commands.startEnd(
// () -> flywheel.runVelocity(flywheelSpeedInput.get()), flywheel::stop, flywheel));
// Set up auto routines
autoChooser = new LoggedDashboardChooser<>("Auto Choices", AutoBuilder.buildAutoChooser());
// Set up FF characterization routines
autoChooser.addOption(
"Drive FF Characterization", | // Copyright 2021-2023 FRC 6328
// http://github.com/Mechanical-Advantage
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// version 3 as published by the Free Software Foundation or
// available in the root directory of this project.
//
// 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.
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 button mappings) should be declared here.
*/
public class RobotContainer {
// Subsystems
private final Drive drive;
// private final Flywheel flywheel;
// Controller
private final CommandXboxController controller = new CommandXboxController(0);
// Dashboard inputs
private final LoggedDashboardChooser<Command> autoChooser;
// private final LoggedDashboardNumber flywheelSpeedInput =
// new LoggedDashboardNumber("Flywheel Speed", 1500.0);
/** The container for the robot. Contains subsystems, OI devices, and commands. */
public RobotContainer() {
switch (Constants.currentMode) {
case REAL:
// Real robot, instantiate hardware IO implementations
// drive =
// new Drive(
// new GyroIOPigeon2(),
// new ModuleIOSparkMax(0),
// new ModuleIOSparkMax(1),
// new ModuleIOSparkMax(2),
// new ModuleIOSparkMax(3));
// flywheel = new Flywheel(new FlywheelIOSparkMax());
drive =
new Drive(
new GyroIOPigeon2(),
new ModuleIOTalonFX(0),
new ModuleIOTalonFX(1),
new ModuleIOTalonFX(2),
new ModuleIOTalonFX(3));
// flywheel = new Flywheel(new FlywheelIOTalonFX());
break;
case SIM:
// Sim robot, instantiate physics sim IO implementations
drive =
new Drive(
new GyroIO() {},
new ModuleIOSim(),
new ModuleIOSim(),
new ModuleIOSim(),
new ModuleIOSim());
// flywheel = new Flywheel(new FlywheelIOSim());
break;
default:
// Replayed robot, disable IO implementations
drive =
new Drive(
new GyroIO() {},
new ModuleIO() {},
new ModuleIO() {},
new ModuleIO() {},
new ModuleIO() {});
// flywheel = new Flywheel(new FlywheelIO() {});
break;
}
// Set up named commands for PathPlanner
// NamedCommands.registerCommand(
// "Run Flywheel",
// Commands.startEnd(
// () -> flywheel.runVelocity(flywheelSpeedInput.get()), flywheel::stop, flywheel));
// Set up auto routines
autoChooser = new LoggedDashboardChooser<>("Auto Choices", AutoBuilder.buildAutoChooser());
// Set up FF characterization routines
autoChooser.addOption(
"Drive FF Characterization", | new FeedForwardCharacterization( | 1 | 2023-12-16 14:59:04+00:00 | 12k |
ReChronoRain/HyperCeiler | app/src/main/java/com/sevtinge/hyperceiler/ui/fragment/settings/development/DevelopmentKillFragment.java | [
{
"identifier": "AppData",
"path": "app/src/main/java/com/sevtinge/hyperceiler/data/AppData.java",
"snippet": "public class AppData {\n public int user = 0;\n public Bitmap icon;\n public String label;\n public String packageName;\n public String activityName;\n public String versionNa... | import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import com.sevtinge.hyperceiler.R;
import com.sevtinge.hyperceiler.data.AppData;
import com.sevtinge.hyperceiler.ui.fragment.base.SettingsPreferenceFragment;
import com.sevtinge.hyperceiler.utils.ContextUtils;
import com.sevtinge.hyperceiler.utils.PackageManagerUtils;
import com.sevtinge.hyperceiler.utils.ShellUtils;
import com.sevtinge.hyperceiler.utils.ToastHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import moralnorm.appcompat.app.AlertDialog;
import moralnorm.preference.Preference; | 7,624 | package com.sevtinge.hyperceiler.ui.fragment.settings.development;
public class DevelopmentKillFragment extends SettingsPreferenceFragment {
public List<AppData> appData = new ArrayList<>();
Preference mKillPackage;
Preference mName;
Preference mCheck;
ExecutorService executorService;
Handler handler;
public interface EditDialogCallback {
void onInputReceived(String userInput);
}
public interface KillCallback {
void onKillCallback(String kill, String rest);
}
public interface GetCallback {
void onCallback(Boolean boo, String rest);
}
@Override
public int getContentResId() {
return R.xml.prefs_development_kill;
}
@Override
public void initPrefs() {
mKillPackage = findPreference("prefs_key_development_kill_package");
mName = findPreference("prefs_key_development_kill_name");
mCheck = findPreference("prefs_key_development_kill_check");
ToastHelper.makeText(ContextUtils.getContext(ContextUtils.FLAG_CURRENT_APP), "加载数据,请稍后");
executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
handler = new Handler();
initApp(executorService);
mCheck.setOnPreferenceClickListener(
preference -> {
showInDialog(
userInput -> {
String pkg = "";
for (AppData appData1 : appData) {
if (appData1.label.equals(userInput)) {
pkg = appData1.packageName;
}
}
if (!(pkg == null || pkg.equals(""))) {
showOutDialog(getPackage(pkg, true, null));
return;
}
showOutDialog(getPackage(userInput, true, null));
}
);
return true;
}
);
mName.setOnPreferenceClickListener(
preference -> {
showInDialog(
userInput -> {
if (!userInput.equals("")) {
String pkg = "";
for (AppData appData1 : appData) {
if (appData1.label.equals(userInput)) {
pkg = appData1.packageName;
}
}
if (!(pkg == null || pkg.equals(""))) {
String finalPkg = pkg;
getAndKill(pkg, (boo, rest) -> {
if (boo) {
showOutDialog("kill success: " + rest);
} else {
showOutDialog("kill error: " + userInput + "\npkg: " + finalPkg);
}
});
} else showOutDialog("kill error maybe not present: " + userInput);
}
}
);
return true;
}
);
mKillPackage.setOnPreferenceClickListener(
preference -> {
showInDialog(
userInput -> {
if (!userInput.equals("")) {
getAndKill(userInput, (boo, rest) -> {
if (boo) {
showOutDialog("kill success: " + rest);
} else showOutDialog("kill error: " + userInput);
});
}
}
);
return true;
}
);
}
private void getAndKill(String pkg, GetCallback getCallback) {
getPackage(pkg, false, (kill, rest) -> {
getCallback.onCallback(killPackage(kill), rest);
}
);
}
private boolean killPackage(String kill) { | package com.sevtinge.hyperceiler.ui.fragment.settings.development;
public class DevelopmentKillFragment extends SettingsPreferenceFragment {
public List<AppData> appData = new ArrayList<>();
Preference mKillPackage;
Preference mName;
Preference mCheck;
ExecutorService executorService;
Handler handler;
public interface EditDialogCallback {
void onInputReceived(String userInput);
}
public interface KillCallback {
void onKillCallback(String kill, String rest);
}
public interface GetCallback {
void onCallback(Boolean boo, String rest);
}
@Override
public int getContentResId() {
return R.xml.prefs_development_kill;
}
@Override
public void initPrefs() {
mKillPackage = findPreference("prefs_key_development_kill_package");
mName = findPreference("prefs_key_development_kill_name");
mCheck = findPreference("prefs_key_development_kill_check");
ToastHelper.makeText(ContextUtils.getContext(ContextUtils.FLAG_CURRENT_APP), "加载数据,请稍后");
executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
handler = new Handler();
initApp(executorService);
mCheck.setOnPreferenceClickListener(
preference -> {
showInDialog(
userInput -> {
String pkg = "";
for (AppData appData1 : appData) {
if (appData1.label.equals(userInput)) {
pkg = appData1.packageName;
}
}
if (!(pkg == null || pkg.equals(""))) {
showOutDialog(getPackage(pkg, true, null));
return;
}
showOutDialog(getPackage(userInput, true, null));
}
);
return true;
}
);
mName.setOnPreferenceClickListener(
preference -> {
showInDialog(
userInput -> {
if (!userInput.equals("")) {
String pkg = "";
for (AppData appData1 : appData) {
if (appData1.label.equals(userInput)) {
pkg = appData1.packageName;
}
}
if (!(pkg == null || pkg.equals(""))) {
String finalPkg = pkg;
getAndKill(pkg, (boo, rest) -> {
if (boo) {
showOutDialog("kill success: " + rest);
} else {
showOutDialog("kill error: " + userInput + "\npkg: " + finalPkg);
}
});
} else showOutDialog("kill error maybe not present: " + userInput);
}
}
);
return true;
}
);
mKillPackage.setOnPreferenceClickListener(
preference -> {
showInDialog(
userInput -> {
if (!userInput.equals("")) {
getAndKill(userInput, (boo, rest) -> {
if (boo) {
showOutDialog("kill success: " + rest);
} else showOutDialog("kill error: " + userInput);
});
}
}
);
return true;
}
);
}
private void getAndKill(String pkg, GetCallback getCallback) {
getPackage(pkg, false, (kill, rest) -> {
getCallback.onCallback(killPackage(kill), rest);
}
);
}
private boolean killPackage(String kill) { | ShellUtils.CommandResult commandResult = | 4 | 2023-10-27 17:17:42+00:00 | 12k |
thebatmanfuture/fofa_search | src/main/java/org/fofaviewer/controls/MyTableView.java | [
{
"identifier": "TableBean",
"path": "src/main/java/org/fofaviewer/bean/TableBean.java",
"snippet": "public class TableBean extends BaseBean{\n public SimpleIntegerProperty num = new SimpleIntegerProperty();\n public SimpleStringProperty host = new SimpleStringProperty();\n public SimpleStringP... | import javafx.beans.binding.Bindings;
import javafx.collections.ObservableList;
import javafx.scene.control.*;
import javafx.scene.control.MenuItem;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import org.fofaviewer.bean.TableBean;
import org.fofaviewer.callback.MainControllerCallback;
import org.fofaviewer.utils.DataUtil;
import org.fofaviewer.utils.RequestUtil;
import org.fofaviewer.utils.ResourceBundleUtil;
import org.tinylog.Logger;
import java.awt.*;
import java.io.IOException;
import java.net.URI;
import java.util.*; | 8,590 | package org.fofaviewer.controls;
/**
* TableView装饰类
*/
public class MyTableView {
private final ResourceBundle resourceBundle = ResourceBundleUtil.getResource();
private final RequestUtil helper = RequestUtil.getInstance();
public MyTableView(TableView<TableBean> view, MainControllerCallback mainControllerCallback) {
TableColumn<TableBean, Integer> num = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_NO"));
TableColumn<TableBean, String> host = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_HOST"));
TableColumn<TableBean, String> title = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_TITLE"));
TableColumn<TableBean, String> ip = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_IP"));
TableColumn<TableBean, Integer> port = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_PORT"));
TableColumn<TableBean, String> domain = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_DOMAIN"));
TableColumn<TableBean, String> protocol = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_PROCOTOL"));
TableColumn<TableBean, String> server = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_SERVER"));
TableColumn<TableBean, String> fid = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_FID"));
TableColumn<TableBean, String> cert = new TableColumn<>();
TableColumn<TableBean, String> certCN = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_CERTCN"));
num.setCellValueFactory(param -> param.getValue().getNum().asObject());
host.setCellValueFactory(param -> param.getValue().getHost());
title.setCellValueFactory(param -> param.getValue().getTitle());
ip.setCellValueFactory(param -> param.getValue().getIp());
port.setCellValueFactory(param -> param.getValue().getPort().asObject());
domain.setCellValueFactory(param -> param.getValue().getDomain());
protocol.setCellValueFactory(param -> param.getValue().getProtocol());
server.setCellValueFactory(param -> param.getValue().getServer());
fid.setCellValueFactory(param -> param.getValue().getFid());
cert.setCellValueFactory(param -> param.getValue().getCert());
cert.setVisible(false); // 证书序列号太长默认不显示
certCN.setCellValueFactory(param -> param.getValue().getCertCN());
if(!mainControllerCallback.getFidStatus()){ // 未勾选fid时默认不显示
fid.setVisible(false);
}
// 修改ip的排序规则 | package org.fofaviewer.controls;
/**
* TableView装饰类
*/
public class MyTableView {
private final ResourceBundle resourceBundle = ResourceBundleUtil.getResource();
private final RequestUtil helper = RequestUtil.getInstance();
public MyTableView(TableView<TableBean> view, MainControllerCallback mainControllerCallback) {
TableColumn<TableBean, Integer> num = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_NO"));
TableColumn<TableBean, String> host = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_HOST"));
TableColumn<TableBean, String> title = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_TITLE"));
TableColumn<TableBean, String> ip = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_IP"));
TableColumn<TableBean, Integer> port = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_PORT"));
TableColumn<TableBean, String> domain = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_DOMAIN"));
TableColumn<TableBean, String> protocol = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_PROCOTOL"));
TableColumn<TableBean, String> server = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_SERVER"));
TableColumn<TableBean, String> fid = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_FID"));
TableColumn<TableBean, String> cert = new TableColumn<>();
TableColumn<TableBean, String> certCN = new TableColumn<>(resourceBundle.getString("TABLE_HEADER_CERTCN"));
num.setCellValueFactory(param -> param.getValue().getNum().asObject());
host.setCellValueFactory(param -> param.getValue().getHost());
title.setCellValueFactory(param -> param.getValue().getTitle());
ip.setCellValueFactory(param -> param.getValue().getIp());
port.setCellValueFactory(param -> param.getValue().getPort().asObject());
domain.setCellValueFactory(param -> param.getValue().getDomain());
protocol.setCellValueFactory(param -> param.getValue().getProtocol());
server.setCellValueFactory(param -> param.getValue().getServer());
fid.setCellValueFactory(param -> param.getValue().getFid());
cert.setCellValueFactory(param -> param.getValue().getCert());
cert.setVisible(false); // 证书序列号太长默认不显示
certCN.setCellValueFactory(param -> param.getValue().getCertCN());
if(!mainControllerCallback.getFidStatus()){ // 未勾选fid时默认不显示
fid.setVisible(false);
}
// 修改ip的排序规则 | ip.setComparator(Comparator.comparing(DataUtil::getValueFromIP)); | 2 | 2023-10-25 11:13:47+00:00 | 12k |
amithkoujalgi/ollama4j | src/test/java/io/github/amithkoujalgi/ollama4j/unittests/TestMockedAPIs.java | [
{
"identifier": "OllamaAPI",
"path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/OllamaAPI.java",
"snippet": "@SuppressWarnings(\"DuplicatedCode\")\npublic class OllamaAPI {\n\n private static final Logger logger = LoggerFactory.getLogger(OllamaAPI.class);\n private final String host;\n priv... | import static org.mockito.Mockito.*;
import io.github.amithkoujalgi.ollama4j.core.OllamaAPI;
import io.github.amithkoujalgi.ollama4j.core.exceptions.OllamaBaseException;
import io.github.amithkoujalgi.ollama4j.core.models.ModelDetail;
import io.github.amithkoujalgi.ollama4j.core.models.OllamaAsyncResultCallback;
import io.github.amithkoujalgi.ollama4j.core.models.OllamaResult;
import io.github.amithkoujalgi.ollama4j.core.types.OllamaModelType;
import io.github.amithkoujalgi.ollama4j.core.utils.OptionsBuilder;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito; | 10,286 | package io.github.amithkoujalgi.ollama4j.unittests;
class TestMockedAPIs {
@Test
void testPullModel() {
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
String model = OllamaModelType.LLAMA2;
try {
doNothing().when(ollamaAPI).pullModel(model);
ollamaAPI.pullModel(model);
verify(ollamaAPI, times(1)).pullModel(model);
} catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
@Test
void testListModels() {
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
try {
when(ollamaAPI.listModels()).thenReturn(new ArrayList<>());
ollamaAPI.listModels();
verify(ollamaAPI, times(1)).listModels();
} catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
@Test
void testCreateModel() {
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
String model = OllamaModelType.LLAMA2;
String modelFilePath = "FROM llama2\nSYSTEM You are mario from Super Mario Bros.";
try {
doNothing().when(ollamaAPI).createModelWithModelFileContents(model, modelFilePath);
ollamaAPI.createModelWithModelFileContents(model, modelFilePath);
verify(ollamaAPI, times(1)).createModelWithModelFileContents(model, modelFilePath);
} catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
@Test
void testDeleteModel() {
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
String model = OllamaModelType.LLAMA2;
try {
doNothing().when(ollamaAPI).deleteModel(model, true);
ollamaAPI.deleteModel(model, true);
verify(ollamaAPI, times(1)).deleteModel(model, true);
} catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
@Test
void testGetModelDetails() {
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
String model = OllamaModelType.LLAMA2;
try {
when(ollamaAPI.getModelDetails(model)).thenReturn(new ModelDetail());
ollamaAPI.getModelDetails(model);
verify(ollamaAPI, times(1)).getModelDetails(model);
} catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
@Test
void testGenerateEmbeddings() {
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
String model = OllamaModelType.LLAMA2;
String prompt = "some prompt text";
try {
when(ollamaAPI.generateEmbeddings(model, prompt)).thenReturn(new ArrayList<>());
ollamaAPI.generateEmbeddings(model, prompt);
verify(ollamaAPI, times(1)).generateEmbeddings(model, prompt);
} catch (IOException | OllamaBaseException | InterruptedException e) {
throw new RuntimeException(e);
}
}
@Test
void testAsk() {
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
String model = OllamaModelType.LLAMA2;
String prompt = "some prompt text";
OptionsBuilder optionsBuilder = new OptionsBuilder();
try {
when(ollamaAPI.ask(model, prompt, optionsBuilder.build())) | package io.github.amithkoujalgi.ollama4j.unittests;
class TestMockedAPIs {
@Test
void testPullModel() {
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
String model = OllamaModelType.LLAMA2;
try {
doNothing().when(ollamaAPI).pullModel(model);
ollamaAPI.pullModel(model);
verify(ollamaAPI, times(1)).pullModel(model);
} catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
@Test
void testListModels() {
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
try {
when(ollamaAPI.listModels()).thenReturn(new ArrayList<>());
ollamaAPI.listModels();
verify(ollamaAPI, times(1)).listModels();
} catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
@Test
void testCreateModel() {
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
String model = OllamaModelType.LLAMA2;
String modelFilePath = "FROM llama2\nSYSTEM You are mario from Super Mario Bros.";
try {
doNothing().when(ollamaAPI).createModelWithModelFileContents(model, modelFilePath);
ollamaAPI.createModelWithModelFileContents(model, modelFilePath);
verify(ollamaAPI, times(1)).createModelWithModelFileContents(model, modelFilePath);
} catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
@Test
void testDeleteModel() {
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
String model = OllamaModelType.LLAMA2;
try {
doNothing().when(ollamaAPI).deleteModel(model, true);
ollamaAPI.deleteModel(model, true);
verify(ollamaAPI, times(1)).deleteModel(model, true);
} catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
@Test
void testGetModelDetails() {
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
String model = OllamaModelType.LLAMA2;
try {
when(ollamaAPI.getModelDetails(model)).thenReturn(new ModelDetail());
ollamaAPI.getModelDetails(model);
verify(ollamaAPI, times(1)).getModelDetails(model);
} catch (IOException | OllamaBaseException | InterruptedException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
@Test
void testGenerateEmbeddings() {
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
String model = OllamaModelType.LLAMA2;
String prompt = "some prompt text";
try {
when(ollamaAPI.generateEmbeddings(model, prompt)).thenReturn(new ArrayList<>());
ollamaAPI.generateEmbeddings(model, prompt);
verify(ollamaAPI, times(1)).generateEmbeddings(model, prompt);
} catch (IOException | OllamaBaseException | InterruptedException e) {
throw new RuntimeException(e);
}
}
@Test
void testAsk() {
OllamaAPI ollamaAPI = Mockito.mock(OllamaAPI.class);
String model = OllamaModelType.LLAMA2;
String prompt = "some prompt text";
OptionsBuilder optionsBuilder = new OptionsBuilder();
try {
when(ollamaAPI.ask(model, prompt, optionsBuilder.build())) | .thenReturn(new OllamaResult("", 0, 200)); | 4 | 2023-10-26 19:12:14+00:00 | 12k |
Changbaiqi/yatori | yatori-console/src/main/java/com/cbq/yatori/console/run/Launch.java | [
{
"identifier": "LoginResponseRequest",
"path": "yatori-core/src/main/java/com/cbq/yatori/core/action/canghui/entity/loginresponse/LoginResponseRequest.java",
"snippet": "@lombok.Data\npublic class LoginResponseRequest {\n @JsonProperty(\"code\")\n private long code;\n @JsonProperty(\"data\")\n... | import com.cbq.yatori.core.action.canghui.entity.loginresponse.LoginResponseRequest;
import com.cbq.yatori.core.action.canghui.entity.mycourselistresponse.MyCourse;
import com.cbq.yatori.core.action.canghui.entity.mycourselistresponse.MyCourseData;
import com.cbq.yatori.core.action.enaea.entity.LoginAblesky;
import com.cbq.yatori.core.action.enaea.entity.underwayproject.ResultList;
import com.cbq.yatori.core.action.enaea.entity.underwayproject.UnderwayProjectRquest;
import com.cbq.yatori.core.action.yinghua.CourseAction;
import com.cbq.yatori.core.action.yinghua.CourseStudyAction;
import com.cbq.yatori.core.action.yinghua.LoginAction;
import com.cbq.yatori.core.action.yinghua.entity.allcourse.CourseInform;
import com.cbq.yatori.core.action.yinghua.entity.allcourse.CourseRequest;
import com.cbq.yatori.core.entity.*;
import com.cbq.yatori.core.utils.ConfigUtils;
import com.cbq.yatori.core.utils.FileUtils;
import com.cbq.yatori.core.utils.VerificationCodeUtil;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask; | 9,965 | package com.cbq.yatori.console.run;
/**
* @author 长白崎
* @version 1.0
* @description: 加载启动程序
* @date 2023/10/31 8:45
*/
@Slf4j
public class Launch {
private Config config;
static {
System.out.println("""
___ \s
,---, ,--.'|_ ,--, \s
/_ ./| | | :,' ,---. __ ,-.,--.'| \s
,---, | ' : : : ' : ' ,'\\ ,' ,'/ /|| |, \s
/___/ \\. : | ,--.--. .;__,' / / / |' | |' |`--'_ \s
. \\ \\ ,' ' / \\ | | | . ; ,. :| | ,',' ,'| \s
\\ ; ` ,' .--. .-. |:__,'| : ' | |: :' : / ' | | \s
\\ \\ ' \\__\\/: . . ' : |__' | .; :| | ' | | : \s
' \\ | ," .--.; | | | '.'| : |; : | ' : |__ \s
\\ ; ; / / ,. | ; : ;\\ \\ / | , ; | | '.'|\s
: \\ \\; : .' \\ | , / `----' ---' ; : ;\s
\\ ' ;| , .-./ ---`-' | , / \s
`--` `--`---' ---`-' \s
Yatori v2.0.0-Beta.2
仅用于学习交流,请勿用于违法和商业用途!!!
GitHub开源地址:https://github.com/Changbaiqi/brushlessons
""");
}
/**
* 初始化数据
*/
public void init() {
//加载配置文件
config = ConfigUtils.loadingConfig();
}
public void toRun() {
//获取账号列表-----------------------------
List<User> users = config.getUsers();
//先进行登录----------------------------------------------
for (User user : users) {
switch (user.getAccountType()) {
//英华,创能
case YINGHUA -> {
AccountCacheYingHua accountCacheYingHua = new AccountCacheYingHua();
user.setCache(accountCacheYingHua);
//refresh_code:1代表密码错误,
Map<String, Object> result = null;
do {
//获取SESSION
String session = null;
while ((session = LoginAction.getSESSION(user)) == null) ;
accountCacheYingHua.setSession(session);
//获取验证码
File code = null;
while ((code = LoginAction.getCode(user)) == null) ;
accountCacheYingHua.setCode(VerificationCodeUtil.aiDiscern(code));
FileUtils.deleteFile(code);//删除验证码文件
//进行登录操作
while ((result = LoginAction.toLogin(user)) == null) ;
} while (!(Boolean) result.get("status") && ((String) result.get("msg")).contains("验证码有误"));
//对结果进行判定
if ((Boolean) result.get("status")) {
accountCacheYingHua.setStatus(1);
log.info("{}登录成功!", user.getAccount());
} else {
log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), ((String) result.get("msg")));
return;
}
//为账号维持登录状态-----------------------------------
new Thread(() -> {
while (true) {
Map online;
//避免超时
while ((online = LoginAction.online(user)) == null) {
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//如果含有登录超时字样
if (((String) online.get("msg")).contains("更新成功")) {
accountCacheYingHua.setStatus(1);
} else if (((String) online.get("msg")).contains("登录超时")) {
accountCacheYingHua.setStatus(2);//设定登录状态为超时
log.info("{}登录超时,正在重新登录...", user.getAccount());
//进行登录
Map<String, Object> map;
do {
//获取验证码
File code = LoginAction.getCode(user);
((AccountCacheYingHua) user.getCache()).setCode(VerificationCodeUtil.aiDiscern(code));
FileUtils.deleteFile(code);//删除验证码文件
//进行登录操作
map = LoginAction.toLogin(user);
} while (!(Boolean) map.get("status") && ((String) map.get("msg")).contains("验证码有误"));
//对结果进行判定
if ((Boolean) map.get("status")) {
accountCacheYingHua.setStatus(1);
log.info("{}登录成功!", user.getAccount());
} else {
log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), ((String) map.get("msg")));
}
}
try {
Thread.sleep(1000 * 60);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}).start();
}
//仓辉
case CANGHUI -> {
AccountCacheCangHui accountCacheCangHui = new AccountCacheCangHui();
user.setCache(accountCacheCangHui);
//refresh_code:1代表密码错误, | package com.cbq.yatori.console.run;
/**
* @author 长白崎
* @version 1.0
* @description: 加载启动程序
* @date 2023/10/31 8:45
*/
@Slf4j
public class Launch {
private Config config;
static {
System.out.println("""
___ \s
,---, ,--.'|_ ,--, \s
/_ ./| | | :,' ,---. __ ,-.,--.'| \s
,---, | ' : : : ' : ' ,'\\ ,' ,'/ /|| |, \s
/___/ \\. : | ,--.--. .;__,' / / / |' | |' |`--'_ \s
. \\ \\ ,' ' / \\ | | | . ; ,. :| | ,',' ,'| \s
\\ ; ` ,' .--. .-. |:__,'| : ' | |: :' : / ' | | \s
\\ \\ ' \\__\\/: . . ' : |__' | .; :| | ' | | : \s
' \\ | ," .--.; | | | '.'| : |; : | ' : |__ \s
\\ ; ; / / ,. | ; : ;\\ \\ / | , ; | | '.'|\s
: \\ \\; : .' \\ | , / `----' ---' ; : ;\s
\\ ' ;| , .-./ ---`-' | , / \s
`--` `--`---' ---`-' \s
Yatori v2.0.0-Beta.2
仅用于学习交流,请勿用于违法和商业用途!!!
GitHub开源地址:https://github.com/Changbaiqi/brushlessons
""");
}
/**
* 初始化数据
*/
public void init() {
//加载配置文件
config = ConfigUtils.loadingConfig();
}
public void toRun() {
//获取账号列表-----------------------------
List<User> users = config.getUsers();
//先进行登录----------------------------------------------
for (User user : users) {
switch (user.getAccountType()) {
//英华,创能
case YINGHUA -> {
AccountCacheYingHua accountCacheYingHua = new AccountCacheYingHua();
user.setCache(accountCacheYingHua);
//refresh_code:1代表密码错误,
Map<String, Object> result = null;
do {
//获取SESSION
String session = null;
while ((session = LoginAction.getSESSION(user)) == null) ;
accountCacheYingHua.setSession(session);
//获取验证码
File code = null;
while ((code = LoginAction.getCode(user)) == null) ;
accountCacheYingHua.setCode(VerificationCodeUtil.aiDiscern(code));
FileUtils.deleteFile(code);//删除验证码文件
//进行登录操作
while ((result = LoginAction.toLogin(user)) == null) ;
} while (!(Boolean) result.get("status") && ((String) result.get("msg")).contains("验证码有误"));
//对结果进行判定
if ((Boolean) result.get("status")) {
accountCacheYingHua.setStatus(1);
log.info("{}登录成功!", user.getAccount());
} else {
log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), ((String) result.get("msg")));
return;
}
//为账号维持登录状态-----------------------------------
new Thread(() -> {
while (true) {
Map online;
//避免超时
while ((online = LoginAction.online(user)) == null) {
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//如果含有登录超时字样
if (((String) online.get("msg")).contains("更新成功")) {
accountCacheYingHua.setStatus(1);
} else if (((String) online.get("msg")).contains("登录超时")) {
accountCacheYingHua.setStatus(2);//设定登录状态为超时
log.info("{}登录超时,正在重新登录...", user.getAccount());
//进行登录
Map<String, Object> map;
do {
//获取验证码
File code = LoginAction.getCode(user);
((AccountCacheYingHua) user.getCache()).setCode(VerificationCodeUtil.aiDiscern(code));
FileUtils.deleteFile(code);//删除验证码文件
//进行登录操作
map = LoginAction.toLogin(user);
} while (!(Boolean) map.get("status") && ((String) map.get("msg")).contains("验证码有误"));
//对结果进行判定
if ((Boolean) map.get("status")) {
accountCacheYingHua.setStatus(1);
log.info("{}登录成功!", user.getAccount());
} else {
log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), ((String) map.get("msg")));
}
}
try {
Thread.sleep(1000 * 60);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}).start();
}
//仓辉
case CANGHUI -> {
AccountCacheCangHui accountCacheCangHui = new AccountCacheCangHui();
user.setCache(accountCacheCangHui);
//refresh_code:1代表密码错误, | LoginResponseRequest result=null; | 0 | 2023-10-30 04:15:41+00:00 | 12k |
sgware/sabre | src/edu/uky/cs/nil/sabre/logic/Disjunction.java | [
{
"identifier": "Settings",
"path": "src/edu/uky/cs/nil/sabre/Settings.java",
"snippet": "public class Settings {\n\n\t/** The full name of this software library */\n\tpublic static final String TITLE = \"The Sabre Narrative Planner\";\n\t\n\t/** The list of primary authors */\n\tpublic static final Str... | import java.util.Collection;
import java.util.Iterator;
import java.util.TreeSet;
import java.util.function.Consumer;
import java.util.function.Function;
import edu.uky.cs.nil.sabre.Settings;
import edu.uky.cs.nil.sabre.State;
import edu.uky.cs.nil.sabre.Utilities;
import edu.uky.cs.nil.sabre.util.Countable;
import edu.uky.cs.nil.sabre.util.ImmutableArray; | 7,593 | package edu.uky.cs.nil.sabre.logic;
/**
* A disjunction is a {@link Proposition proposition} made up of zero to many
* arguments (or disjuncts) which are {@link Expression expressions} of type
* {@code boolean} such that at least one of them must {@link
* Expression#evaluate(State) evaluate} to {@link True true} for the
* disjunction to be true.
*
* @param <E> the type of the disjunction's arguments
* @author Stephen G. Ware
*/
public class Disjunction<E extends Expression> implements Iterable<E>, Countable, Proposition {
/** Serial version ID */
private static final long serialVersionUID = Settings.VERSION_UID;
/**
* The disjuncts which must contain at least one true expression for this
* disjunction to be true
*/
public final ImmutableArray<E> arguments;
/**
* Constructs a new disjunction from an {@link ImmutableArray immutable
* array} of disjuncts. This constructor does not check the arguments to
* ensure they are of type {@code boolean}.
*
* @param arguments the disjuncts
*/
protected Disjunction(ImmutableArray<E> arguments) {
this.arguments = arguments;
}
/**
* Constructs a new disjunction from an array of disjuncts.
*
* @param arguments the disjuncts
* @throws edu.uky.cs.nil.sabre.FormatException if any disjunct is not of
* type {@code boolean}
*/
@SafeVarargs
public Disjunction(E...arguments) {
this(new ImmutableArray<>(arguments));
checkFormatting(this);
}
/**
* Constructs a new disjunction from an {@link Iterable iterable} of
* disjuncts.
*
* @param arguments the disjuncts
* @throws edu.uky.cs.nil.sabre.FormatException if any disjunct is not of
* type {@code boolean}
*/
public Disjunction(Iterable<E> arguments) {
this(new ImmutableArray<>(arguments));
checkFormatting(this);
}
private static final void checkFormatting(Disjunction<?> disjunction) {
for(int i=0; i<disjunction.size(); i++)
disjunction.get(i).mustBeBoolean();
}
@Override
public boolean equals(Object other) {
if(getClass().equals(other.getClass()))
return arguments.equals(((Disjunction<?>) other).arguments);
return false;
}
@Override
public int hashCode() { | package edu.uky.cs.nil.sabre.logic;
/**
* A disjunction is a {@link Proposition proposition} made up of zero to many
* arguments (or disjuncts) which are {@link Expression expressions} of type
* {@code boolean} such that at least one of them must {@link
* Expression#evaluate(State) evaluate} to {@link True true} for the
* disjunction to be true.
*
* @param <E> the type of the disjunction's arguments
* @author Stephen G. Ware
*/
public class Disjunction<E extends Expression> implements Iterable<E>, Countable, Proposition {
/** Serial version ID */
private static final long serialVersionUID = Settings.VERSION_UID;
/**
* The disjuncts which must contain at least one true expression for this
* disjunction to be true
*/
public final ImmutableArray<E> arguments;
/**
* Constructs a new disjunction from an {@link ImmutableArray immutable
* array} of disjuncts. This constructor does not check the arguments to
* ensure they are of type {@code boolean}.
*
* @param arguments the disjuncts
*/
protected Disjunction(ImmutableArray<E> arguments) {
this.arguments = arguments;
}
/**
* Constructs a new disjunction from an array of disjuncts.
*
* @param arguments the disjuncts
* @throws edu.uky.cs.nil.sabre.FormatException if any disjunct is not of
* type {@code boolean}
*/
@SafeVarargs
public Disjunction(E...arguments) {
this(new ImmutableArray<>(arguments));
checkFormatting(this);
}
/**
* Constructs a new disjunction from an {@link Iterable iterable} of
* disjuncts.
*
* @param arguments the disjuncts
* @throws edu.uky.cs.nil.sabre.FormatException if any disjunct is not of
* type {@code boolean}
*/
public Disjunction(Iterable<E> arguments) {
this(new ImmutableArray<>(arguments));
checkFormatting(this);
}
private static final void checkFormatting(Disjunction<?> disjunction) {
for(int i=0; i<disjunction.size(); i++)
disjunction.get(i).mustBeBoolean();
}
@Override
public boolean equals(Object other) {
if(getClass().equals(other.getClass()))
return arguments.equals(((Disjunction<?>) other).arguments);
return false;
}
@Override
public int hashCode() { | return Utilities.hashCode(getClass(), arguments); | 2 | 2023-10-26 18:14:19+00:00 | 12k |
sngular/pact-annotation-processor | src/main/java/com/sngular/annotation/processor/PactDslProcessor.java | [
{
"identifier": "PactProcessorException",
"path": "src/main/java/com/sngular/annotation/processor/exception/PactProcessorException.java",
"snippet": "public class PactProcessorException extends RuntimeException {\n\n private static final String ERROR_MESSAGE = \"Error processing element %s\";\n\n publ... | import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableMap;
import com.sngular.annotation.pact.DslExclude;
import com.sngular.annotation.pact.Example;
import com.sngular.annotation.pact.PactDslBodyBuilder;
import com.sngular.annotation.processor.exception.PactProcessorException;
import com.sngular.annotation.processor.exception.TemplateFactoryException;
import com.sngular.annotation.processor.exception.TemplateGenerationException;
import com.sngular.annotation.processor.mapping.BigDecimalMapping;
import com.sngular.annotation.processor.mapping.BigIntegerMapping;
import com.sngular.annotation.processor.mapping.BooleanMapping;
import com.sngular.annotation.processor.mapping.ByteMapping;
import com.sngular.annotation.processor.mapping.CharMapping;
import com.sngular.annotation.processor.mapping.DateMapping;
import com.sngular.annotation.processor.mapping.DoubleMapping;
import com.sngular.annotation.processor.mapping.FloatMapping;
import com.sngular.annotation.processor.mapping.IntegerMapping;
import com.sngular.annotation.processor.mapping.LongMapping;
import com.sngular.annotation.processor.mapping.ShortMapping;
import com.sngular.annotation.processor.mapping.StringMapping;
import com.sngular.annotation.processor.mapping.TypeMapping;
import com.sngular.annotation.processor.mapping.ZonedDateTimeMapping;
import com.sngular.annotation.processor.model.ClassBuilderTemplate;
import com.sngular.annotation.processor.model.DslComplexField;
import com.sngular.annotation.processor.model.DslComplexTypeEnum;
import com.sngular.annotation.processor.model.DslField;
import com.sngular.annotation.processor.model.DslSimpleField;
import com.sngular.annotation.processor.model.FieldValidations;
import com.sngular.annotation.processor.template.ClasspathTemplateLoader;
import com.sngular.annotation.processor.template.TemplateFactory;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.collections4.IteratorUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.rng.RestorableUniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
import org.jetbrains.annotations.NotNull; | 7,883 | return valueAsTypeList;
}
private AnnotationValue getAnnotationValue(final AnnotationMirror annotationMirror, final String key) {
AnnotationValue annotationValue = null;
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) {
if (entry.getKey().getSimpleName().toString().equals(key)) {
annotationValue = entry.getValue();
}
}
return annotationValue;
}
private DslField composeDslField(final Element fieldElement, final boolean insideCollection) {
final DslField result;
final Optional<TypeMapping<?>> mappingOp = extractMappingByType(fieldElement);
if (mappingOp.isEmpty()) {
if (checkIfOwn(fieldElement)) {
result = composeDslComplexField(fieldElement);
} else {
final String type = extractType(fieldElement);
if (type.endsWith("List") || type.endsWith("Map") || type.endsWith("Set") || type.endsWith("Collection")) {
result = composeCollection(fieldElement);
} else {
result = composeDslComplexField(fieldElement);
}
}
} else {
result = composeDslSimpleField(fieldElement, mappingOp.get(), insideCollection);
}
return result;
}
private DslComplexField composeDslComplexField(final Element element) {
return DslComplexField.builder()
.name(element.getSimpleName().toString())
.fieldType(element.asType().toString())
.needBuilder(checkIfOwn(element))
.complexType(DslComplexTypeEnum.OBJECT)
.fieldValidations(extractValidations(element))
.empty(Objects.nonNull(element.getAnnotation(DslExclude.class)))
.build();
}
private DslComplexField composeCollection(final Element element) {
final var typeStr = cleanType(element);
return DslComplexField.builder()
.name(element.getSimpleName().toString())
.fieldType(typeStr)
.fields(extractTypes(element))
.fieldValidations(extractValidations(element))
.complexType(DslComplexTypeEnum.COLLECTION)
.empty(Objects.nonNull(element.getAnnotation(DslExclude.class)))
.build();
}
private boolean checkIfOwn(final Element element) {
final var typePackage = elementUtils.getPackageOf(typeUtils.asElement(element.asType())).toString();
final var parentType = elementUtils.getPackageOf(typeUtils.asElement(element.getEnclosingElement().asType())).toString();
return parentType.equalsIgnoreCase(typePackage);
}
private String extractType(final Element element) {
return ((TypeElement) typeUtils.asElement(element.asType())).getQualifiedName().toString();
}
private String cleanType(final Element element) {
var finalType = element.asType().toString();
for (var annotation : element.asType().getAnnotationMirrors()) {
finalType = finalType.replace(annotation.toString(), "");
}
return finalType.replace(", ", "");
}
private FieldValidations extractValidations(final Element element) {
final var validationBuilder = FieldValidations.builder();
int minValue = 0;
int maxValue = 0;
final var type = element.asType();
if (CollectionUtils.isNotEmpty(type.getAnnotationMirrors())) {
for (var annotation : type.getAnnotationMirrors()) {
if (annotation.getAnnotationType().toString().toUpperCase().endsWith("MAX")) {
maxValue = ((Long) Objects.requireNonNull(getAnnotationValue(annotation, "value")).getValue()).intValue();
validationBuilder.max(maxValue);
} else {
minValue = ((Long) Objects.requireNonNull(getAnnotationValue(annotation, "value")).getValue()).intValue();
validationBuilder.min(minValue);
}
}
//For random size calculation: defaults to +10 elements max if not defined.
maxValue = (maxValue == 0) ? (minValue + 10) : maxValue;
validationBuilder.randomSize(new Random().nextInt(maxValue - minValue + 1) + minValue);
}
return validationBuilder.build();
}
@NotNull
private List<DslField> extractTypes(final Element element) {
final List<DslField> listOfFields;
final var listOfCustomMods = new ArrayList<>(CollectionUtils.collect(((DeclaredType) element.asType()).getTypeArguments(), typeUtils::asElement));
if (listOfCustomMods.size() > 1) {
listOfFields = new ArrayList<>(CollectionUtils.collect(listOfCustomMods, e -> composeDslField(e, true)));
} else {
listOfFields = List.of(
composeDslSimpleField(listOfCustomMods.get(0),
extractMappingByType(listOfCustomMods.get(0))
.orElseThrow(() -> new PactProcessorException(listOfCustomMods.get(0).getSimpleName().toString())),
true));
}
return listOfFields;
}
private List<String> extractCustomModifiers(final Element element) {
final List<String> customModList = new ArrayList<>();
final var listOfCustomMods = CollectionUtils.collect(element.getAnnotationMirrors(), a -> getAnnotationValueAsType(a, CUSTOM_MODIFIERS));
CollectionUtils.collect(listOfCustomMods, customModList::addAll);
return customModList;
}
| /*
* This Source Code Form is subject to the terms of the Mozilla Public
* * License, v. 2.0. If a copy of the MPL was not distributed with this
* * file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package com.sngular.annotation.processor;
@Slf4j
@AutoService(Processor.class)
@SupportedAnnotationTypes("com.sngular.annotation.pact.PactDslBodyBuilder")
public class PactDslProcessor extends AbstractProcessor {
static final Map<String, TypeMapping<?>> TYPE_MAPPING = ImmutableMap.<String, TypeMapping<?>>builder()
.put("int", new IntegerMapping())
.put("Integer", new IntegerMapping())
.put("BigInteger", new BigIntegerMapping())
.put("short", new ShortMapping())
.put("Short", new ShortMapping())
.put("byte", new ByteMapping())
.put("Byte", new ByteMapping())
.put("long", new LongMapping())
.put("Long", new LongMapping())
.put("char", new CharMapping())
.put("Character", new CharMapping())
.put("String", new StringMapping())
.put("float", new FloatMapping())
.put("Float", new FloatMapping())
.put("double", new DoubleMapping())
.put("Double", new DoubleMapping())
.put("BigDecimal", new BigDecimalMapping())
.put("boolean", new BooleanMapping())
.put("Boolean", new BooleanMapping())
.put("date", new DateMapping())
.put("java.time.ZonedDateTime", new ZonedDateTimeMapping())
.put("ZonedDateTime", new ZonedDateTimeMapping())
.put("java.util.Date", new DateMapping())
.put("Date", new DateMapping())
.build();
private static final String CUSTOM_MODIFIERS = "customModifiers";
private Elements elementUtils;
private Types typeUtils;
private RestorableUniformRandomProvider randomSource = RandomSource.XO_RO_SHI_RO_128_PP.create();
public PactDslProcessor() {
}
public PactDslProcessor(final RestorableUniformRandomProvider randomSource) {
this.randomSource = randomSource;
}
@NotNull
private static List<? extends Element> getFieldElements(final Element element) {
return IterableUtils.toList(IterableUtils.filteredIterable(element.getEnclosedElements(), elt -> elt.getKind().isField()));
}
private static String getFormat(final Element fieldElement, final String defaultFormat) {
final String value = fieldElement.getAnnotation(Example.class).format();
return StringUtils.defaultIfEmpty(value, defaultFormat);
}
@Override
public final SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public final boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
final TemplateFactory templateFactory;
try {
templateFactory = new TemplateFactory();
} catch (final TemplateException e) {
throw new TemplateFactoryException(e);
}
elementUtils = processingEnv.getElementUtils();
typeUtils = processingEnv.getTypeUtils();
final Set<? extends Element> elementsAnnotatedWith = roundEnv.getElementsAnnotatedWith(PactDslBodyBuilder.class);
IteratorUtils
.transformedIterator(elementsAnnotatedWith.iterator(), this::composeBuilderTemplate).forEachRemaining(builderTemplate -> {
try {
final var builderFile = processingEnv.getFiler().createSourceFile(builderTemplate.completePath());
templateFactory.writeTemplateToFile(ClasspathTemplateLoader.TEMPLATE_DSL_BUILDER, builderTemplate, builderFile.openWriter());
} catch (IOException | TemplateException e) {
throw new TemplateGenerationException("PactDslBodyBuilder", e);
}
});
return true;
}
private ClassBuilderTemplate composeBuilderTemplate(final Element element) {
final List<? extends Element> fieldElements = getFieldElements(element);
final var qualifiedName = ((TypeElement) element).getQualifiedName().toString();
String packageName = null;
final int lastDot = qualifiedName.lastIndexOf('.');
if (lastDot > 0) {
packageName = qualifiedName.substring(0, lastDot);
}
final var builderSimpleClassName = qualifiedName.substring(lastDot + 1);
final var builderClassName = builderSimpleClassName + "Builder";
return ClassBuilderTemplate.builder()
.fileName(builderClassName)
.className(builderSimpleClassName)
.modelPackage(packageName)
.fieldList(getFields(fieldElements))
.customModifiers(extractCustomModifiers(element))
.build();
}
@NotNull
private List<DslField> getFields(final List<? extends Element> fieldElements) {
return IterableUtils.toList(IterableUtils.transformedIterable(fieldElements, fieldElement -> composeDslField(fieldElement, false)));
}
private List<String> getAnnotationValueAsType(final AnnotationMirror annotationMirror, final String key) {
final var valueAsTypeList = new ArrayList<String>();
final var annotationValue = getAnnotationValue(annotationMirror, key);
if (annotationValue != null) {
valueAsTypeList.addAll(List.of(annotationValue.toString()
.replace(" ", "").replace("{", "")
.replace("}", "").replace("\"", "")
.split(",")));
}
return valueAsTypeList;
}
private AnnotationValue getAnnotationValue(final AnnotationMirror annotationMirror, final String key) {
AnnotationValue annotationValue = null;
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet()) {
if (entry.getKey().getSimpleName().toString().equals(key)) {
annotationValue = entry.getValue();
}
}
return annotationValue;
}
private DslField composeDslField(final Element fieldElement, final boolean insideCollection) {
final DslField result;
final Optional<TypeMapping<?>> mappingOp = extractMappingByType(fieldElement);
if (mappingOp.isEmpty()) {
if (checkIfOwn(fieldElement)) {
result = composeDslComplexField(fieldElement);
} else {
final String type = extractType(fieldElement);
if (type.endsWith("List") || type.endsWith("Map") || type.endsWith("Set") || type.endsWith("Collection")) {
result = composeCollection(fieldElement);
} else {
result = composeDslComplexField(fieldElement);
}
}
} else {
result = composeDslSimpleField(fieldElement, mappingOp.get(), insideCollection);
}
return result;
}
private DslComplexField composeDslComplexField(final Element element) {
return DslComplexField.builder()
.name(element.getSimpleName().toString())
.fieldType(element.asType().toString())
.needBuilder(checkIfOwn(element))
.complexType(DslComplexTypeEnum.OBJECT)
.fieldValidations(extractValidations(element))
.empty(Objects.nonNull(element.getAnnotation(DslExclude.class)))
.build();
}
private DslComplexField composeCollection(final Element element) {
final var typeStr = cleanType(element);
return DslComplexField.builder()
.name(element.getSimpleName().toString())
.fieldType(typeStr)
.fields(extractTypes(element))
.fieldValidations(extractValidations(element))
.complexType(DslComplexTypeEnum.COLLECTION)
.empty(Objects.nonNull(element.getAnnotation(DslExclude.class)))
.build();
}
private boolean checkIfOwn(final Element element) {
final var typePackage = elementUtils.getPackageOf(typeUtils.asElement(element.asType())).toString();
final var parentType = elementUtils.getPackageOf(typeUtils.asElement(element.getEnclosingElement().asType())).toString();
return parentType.equalsIgnoreCase(typePackage);
}
private String extractType(final Element element) {
return ((TypeElement) typeUtils.asElement(element.asType())).getQualifiedName().toString();
}
private String cleanType(final Element element) {
var finalType = element.asType().toString();
for (var annotation : element.asType().getAnnotationMirrors()) {
finalType = finalType.replace(annotation.toString(), "");
}
return finalType.replace(", ", "");
}
private FieldValidations extractValidations(final Element element) {
final var validationBuilder = FieldValidations.builder();
int minValue = 0;
int maxValue = 0;
final var type = element.asType();
if (CollectionUtils.isNotEmpty(type.getAnnotationMirrors())) {
for (var annotation : type.getAnnotationMirrors()) {
if (annotation.getAnnotationType().toString().toUpperCase().endsWith("MAX")) {
maxValue = ((Long) Objects.requireNonNull(getAnnotationValue(annotation, "value")).getValue()).intValue();
validationBuilder.max(maxValue);
} else {
minValue = ((Long) Objects.requireNonNull(getAnnotationValue(annotation, "value")).getValue()).intValue();
validationBuilder.min(minValue);
}
}
//For random size calculation: defaults to +10 elements max if not defined.
maxValue = (maxValue == 0) ? (minValue + 10) : maxValue;
validationBuilder.randomSize(new Random().nextInt(maxValue - minValue + 1) + minValue);
}
return validationBuilder.build();
}
@NotNull
private List<DslField> extractTypes(final Element element) {
final List<DslField> listOfFields;
final var listOfCustomMods = new ArrayList<>(CollectionUtils.collect(((DeclaredType) element.asType()).getTypeArguments(), typeUtils::asElement));
if (listOfCustomMods.size() > 1) {
listOfFields = new ArrayList<>(CollectionUtils.collect(listOfCustomMods, e -> composeDslField(e, true)));
} else {
listOfFields = List.of(
composeDslSimpleField(listOfCustomMods.get(0),
extractMappingByType(listOfCustomMods.get(0))
.orElseThrow(() -> new PactProcessorException(listOfCustomMods.get(0).getSimpleName().toString())),
true));
}
return listOfFields;
}
private List<String> extractCustomModifiers(final Element element) {
final List<String> customModList = new ArrayList<>();
final var listOfCustomMods = CollectionUtils.collect(element.getAnnotationMirrors(), a -> getAnnotationValueAsType(a, CUSTOM_MODIFIERS));
CollectionUtils.collect(listOfCustomMods, customModList::addAll);
return customModList;
}
| private DslSimpleField composeDslSimpleField(final Element fieldElement, final TypeMapping<?> mapping, final boolean insideCollection) { | 21 | 2023-10-25 14:36:38+00:00 | 12k |
granny/Pl3xMap | core/src/main/java/net/pl3x/map/core/util/Colors.java | [
{
"identifier": "Pl3xMap",
"path": "core/src/main/java/net/pl3x/map/core/Pl3xMap.java",
"snippet": "public abstract class Pl3xMap {\n public static @NotNull Pl3xMap api() {\n return Provider.api();\n }\n\n private final boolean isBukkit;\n\n private final Attributes manifestAttributes... | import net.pl3x.map.core.world.BlockState;
import net.pl3x.map.core.world.Chunk;
import net.pl3x.map.core.world.Region;
import org.jetbrains.annotations.NotNull;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Path;
import javax.imageio.ImageIO;
import net.pl3x.map.core.Pl3xMap;
import net.pl3x.map.core.world.Biome; | 9,259 | return rgb(
(int) Mathf.lerp(red(color0), red(color1), delta),
(int) Mathf.lerp(green(color0), green(color1), delta),
(int) Mathf.lerp(blue(color0), blue(color1), delta)
);
}
public static int lerpARGB(int color0, int color1, float delta) {
if (color0 == color1) return color0;
if (delta >= 1F) return color1;
if (delta <= 0F) return color0;
return argb(
(int) Mathf.lerp(alpha(color0), alpha(color1), delta),
(int) Mathf.lerp(red(color0), red(color1), delta),
(int) Mathf.lerp(green(color0), green(color1), delta),
(int) Mathf.lerp(blue(color0), blue(color1), delta)
);
}
public static int lerpHSB(int color0, int color1, float delta) {
return lerpHSB(color0, color1, delta, true);
}
public static int lerpHSB(int color0, int color1, float delta, boolean useShortestAngle) {
float[] hsb0 = Color.RGBtoHSB(red(color0), green(color0), blue(color0), null);
float[] hsb1 = Color.RGBtoHSB(red(color1), green(color1), blue(color1), null);
return setAlpha(
(int) Mathf.lerp(alpha(color0), alpha(color1), delta),
Color.HSBtoRGB(
useShortestAngle ?
lerpShortestAngle(hsb0[0], hsb1[0], delta) :
Mathf.lerp(hsb0[0], hsb1[0], delta),
Mathf.lerp(hsb0[1], hsb1[1], delta),
Mathf.lerp(hsb0[2], hsb1[2], delta)
)
);
}
public static int inverseLerpRGB(int color0, int color1, float delta) {
if (color0 == color1) return color0;
if (delta >= 1F) return color1;
if (delta <= 0F) return color0;
return rgb(
(int) Mathf.inverseLerp(red(color0), red(color1), delta),
(int) Mathf.inverseLerp(green(color0), green(color1), delta),
(int) Mathf.inverseLerp(blue(color0), blue(color1), delta)
);
}
public static int inverseLerpARGB(int color0, int color1, float delta) {
if (color0 == color1) return color0;
if (delta >= 1F) return color1;
if (delta <= 0F) return color0;
return argb(
(int) Mathf.inverseLerp(alpha(color0), alpha(color1), delta),
(int) Mathf.inverseLerp(red(color0), red(color1), delta),
(int) Mathf.inverseLerp(green(color0), green(color1), delta),
(int) Mathf.inverseLerp(blue(color0), blue(color1), delta)
);
}
public static int inverseLerpHSB(int color0, int color1, float delta) {
return inverseLerpHSB(color0, color1, delta, true);
}
public static int inverseLerpHSB(int color0, int color1, float delta, boolean useShortestAngle) {
float[] hsb0 = Color.RGBtoHSB(red(color0), green(color0), blue(color0), null);
float[] hsb1 = Color.RGBtoHSB(red(color1), green(color1), blue(color1), null);
return setAlpha(
(int) Mathf.inverseLerp(alpha(color0), alpha(color1), delta),
Color.HSBtoRGB(
useShortestAngle ?
lerpShortestAngle(hsb0[0], hsb1[0], delta) :
Mathf.inverseLerp(hsb0[0], hsb1[0], delta),
Mathf.inverseLerp(hsb0[1], hsb1[1], delta),
Mathf.inverseLerp(hsb0[2], hsb1[2], delta)
)
);
}
public static float lerpShortestAngle(float start, float end, float delta) {
float distCW = (end >= start ? end - start : 1F - (start - end));
float distCCW = (start >= end ? start - end : 1F - (end - start));
float direction = (distCW <= distCCW ? distCW : -1F * distCCW);
return (start + (direction * delta));
}
/**
* Blends one color over another.
*
* @param color0 color to blend over with
* @param color1 color to be blended over
* @return resulting blended color
* @see <a href="https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending">Alpha Blending</a>
*/
public static int blend(int color0, int color1) {
double a0 = (double) alpha(color0) / 0xFF;
double a1 = (double) alpha(color1) / 0xFF;
double a = a0 + a1 * (1 - a0);
double r = (red(color0) * a0 + red(color1) * a1 * (1 - a0)) / a;
double g = (green(color0) * a0 + green(color1) * a1 * (1 - a0)) / a;
double b = (blue(color0) * a0 + blue(color1) * a1 * (1 - a0)) / a;
return argb((int) a * 0xFF, (int) r, (int) g, (int) b);
}
public static int mix(int color0, int color1) {
int r = red(color0) + red(color1);
int g = green(color0) + green(color1);
int b = blue(color0) + blue(color1);
return rgb(r >> 1, g >> 1, b >> 1);
}
public static int shade(int color, int shade) {
float ratio = shade / 255F;
int r = (int) ((color >> 16 & 0xFF) * ratio);
int g = (int) ((color >> 8 & 0xFF) * ratio);
int b = (int) ((color & 0xFF) * ratio);
return (0xFF << 24) | (r << 16) | (g << 8) | b;
}
| /*
* MIT License
*
* Copyright (c) 2020-2023 William Blake Galbreath
*
* 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 net.pl3x.map.core.util;
@SuppressWarnings("unused")
public class Colors {
private static final int[] mapGrass;
private static final int[] mapFoliage;
static {
int[] grass, foliage;
try {
Path imagesDir = FileUtil.getWebDir().resolve("images");
BufferedImage imgGrass, imgFoliage;
try {
imgGrass = ImageIO.read(imagesDir.resolve("grass.png").toFile());
imgFoliage = ImageIO.read(imagesDir.resolve("foliage.png").toFile());
} catch (IOException e) {
throw new IllegalStateException("Failed to read color images", e);
}
grass = getColorsFromImage(imgGrass);
foliage = getColorsFromImage(imgFoliage);
} catch (Throwable ignore) {
grass = new int[0];
foliage = new int[0];
}
mapGrass = grass;
mapFoliage = foliage;
}
private static int[] getColorsFromImage(@NotNull BufferedImage image) {
int[] map = new int[256 * 256];
for (int x = 0; x < 256; ++x) {
for (int y = 0; y < 256; ++y) {
int rgb = image.getRGB(x, y);
map[x + y * 256] = (red(rgb) << 16) | (green(rgb) << 8) | blue(rgb);
}
}
return map;
}
public static int getDefaultGrassColor(double temperature, double humidity) {
return getDefaultColor(temperature, humidity, mapGrass);
}
public static int getDefaultFoliageColor(double temperature, double humidity) {
return getDefaultColor(temperature, humidity, mapFoliage);
}
private static int getDefaultColor(double temperature, double humidity, int[] map) {
int i = (int) ((1.0 - temperature) * 255.0);
int j = (int) ((1.0 - (humidity * temperature)) * 255.0);
int k = j << 8 | i;
return k > map.length ? 0 : map[k];
}
public static int rgb2bgr(int color) {
// Minecraft flips red and blue for some reason
// lets flip them back
int a = color >> 24 & 0xFF;
int r = color >> 16 & 0xFF;
int g = color >> 8 & 0xFF;
int b = color & 0xFF;
return (a << 24) | (b << 16) | (g << 8) | r;
}
public static int lerpRGB(int color0, int color1, float delta) {
if (color0 == color1) return color0;
if (delta >= 1F) return color1;
if (delta <= 0F) return color0;
return rgb(
(int) Mathf.lerp(red(color0), red(color1), delta),
(int) Mathf.lerp(green(color0), green(color1), delta),
(int) Mathf.lerp(blue(color0), blue(color1), delta)
);
}
public static int lerpARGB(int color0, int color1, float delta) {
if (color0 == color1) return color0;
if (delta >= 1F) return color1;
if (delta <= 0F) return color0;
return argb(
(int) Mathf.lerp(alpha(color0), alpha(color1), delta),
(int) Mathf.lerp(red(color0), red(color1), delta),
(int) Mathf.lerp(green(color0), green(color1), delta),
(int) Mathf.lerp(blue(color0), blue(color1), delta)
);
}
public static int lerpHSB(int color0, int color1, float delta) {
return lerpHSB(color0, color1, delta, true);
}
public static int lerpHSB(int color0, int color1, float delta, boolean useShortestAngle) {
float[] hsb0 = Color.RGBtoHSB(red(color0), green(color0), blue(color0), null);
float[] hsb1 = Color.RGBtoHSB(red(color1), green(color1), blue(color1), null);
return setAlpha(
(int) Mathf.lerp(alpha(color0), alpha(color1), delta),
Color.HSBtoRGB(
useShortestAngle ?
lerpShortestAngle(hsb0[0], hsb1[0], delta) :
Mathf.lerp(hsb0[0], hsb1[0], delta),
Mathf.lerp(hsb0[1], hsb1[1], delta),
Mathf.lerp(hsb0[2], hsb1[2], delta)
)
);
}
public static int inverseLerpRGB(int color0, int color1, float delta) {
if (color0 == color1) return color0;
if (delta >= 1F) return color1;
if (delta <= 0F) return color0;
return rgb(
(int) Mathf.inverseLerp(red(color0), red(color1), delta),
(int) Mathf.inverseLerp(green(color0), green(color1), delta),
(int) Mathf.inverseLerp(blue(color0), blue(color1), delta)
);
}
public static int inverseLerpARGB(int color0, int color1, float delta) {
if (color0 == color1) return color0;
if (delta >= 1F) return color1;
if (delta <= 0F) return color0;
return argb(
(int) Mathf.inverseLerp(alpha(color0), alpha(color1), delta),
(int) Mathf.inverseLerp(red(color0), red(color1), delta),
(int) Mathf.inverseLerp(green(color0), green(color1), delta),
(int) Mathf.inverseLerp(blue(color0), blue(color1), delta)
);
}
public static int inverseLerpHSB(int color0, int color1, float delta) {
return inverseLerpHSB(color0, color1, delta, true);
}
public static int inverseLerpHSB(int color0, int color1, float delta, boolean useShortestAngle) {
float[] hsb0 = Color.RGBtoHSB(red(color0), green(color0), blue(color0), null);
float[] hsb1 = Color.RGBtoHSB(red(color1), green(color1), blue(color1), null);
return setAlpha(
(int) Mathf.inverseLerp(alpha(color0), alpha(color1), delta),
Color.HSBtoRGB(
useShortestAngle ?
lerpShortestAngle(hsb0[0], hsb1[0], delta) :
Mathf.inverseLerp(hsb0[0], hsb1[0], delta),
Mathf.inverseLerp(hsb0[1], hsb1[1], delta),
Mathf.inverseLerp(hsb0[2], hsb1[2], delta)
)
);
}
public static float lerpShortestAngle(float start, float end, float delta) {
float distCW = (end >= start ? end - start : 1F - (start - end));
float distCCW = (start >= end ? start - end : 1F - (end - start));
float direction = (distCW <= distCCW ? distCW : -1F * distCCW);
return (start + (direction * delta));
}
/**
* Blends one color over another.
*
* @param color0 color to blend over with
* @param color1 color to be blended over
* @return resulting blended color
* @see <a href="https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending">Alpha Blending</a>
*/
public static int blend(int color0, int color1) {
double a0 = (double) alpha(color0) / 0xFF;
double a1 = (double) alpha(color1) / 0xFF;
double a = a0 + a1 * (1 - a0);
double r = (red(color0) * a0 + red(color1) * a1 * (1 - a0)) / a;
double g = (green(color0) * a0 + green(color1) * a1 * (1 - a0)) / a;
double b = (blue(color0) * a0 + blue(color1) * a1 * (1 - a0)) / a;
return argb((int) a * 0xFF, (int) r, (int) g, (int) b);
}
public static int mix(int color0, int color1) {
int r = red(color0) + red(color1);
int g = green(color0) + green(color1);
int b = blue(color0) + blue(color1);
return rgb(r >> 1, g >> 1, b >> 1);
}
public static int shade(int color, int shade) {
float ratio = shade / 255F;
int r = (int) ((color >> 16 & 0xFF) * ratio);
int g = (int) ((color >> 8 & 0xFF) * ratio);
int b = (int) ((color & 0xFF) * ratio);
return (0xFF << 24) | (r << 16) | (g << 8) | b;
}
| public static int getFoliageColor(@NotNull Region region, @NotNull Biome biome, int color, int x, int z) { | 4 | 2023-10-26 01:14:31+00:00 | 12k |
jd-opensource/sql-analysis | sql-analysis/src/main/java/com/jd/sql/analysis/core/SqlAnalysisAspect.java | [
{
"identifier": "SqlAnalysis",
"path": "sql-analysis/src/main/java/com/jd/sql/analysis/analysis/SqlAnalysis.java",
"snippet": "public class SqlAnalysis {\n\n private static Logger logger = LoggerFactory.getLogger(SqlAnalysis.class);\n\n /**\n * mysql 版本标识\n */\n private static String my... | import com.jd.sql.analysis.analysis.SqlAnalysis;
import com.jd.sql.analysis.analysis.SqlAnalysisResultList;
import com.jd.sql.analysis.config.JmqConfig;
import com.jd.sql.analysis.config.SqlAnalysisConfig;
import com.jd.sql.analysis.extract.SqlExtract;
import com.jd.sql.analysis.extract.SqlExtractResult;
import com.jd.sql.analysis.out.OutModelEnum;
import com.jd.sql.analysis.out.SqlScoreResultOutMq;
import com.jd.sql.analysis.out.SqlScoreResultOutService;
import com.jd.sql.analysis.out.SqlScoreResultOutServiceDefault;
import com.jd.sql.analysis.replace.SqlReplace;
import com.jd.sql.analysis.replace.SqlReplaceConfig;
import com.jd.sql.analysis.rule.SqlScoreRuleLoader;
import com.jd.sql.analysis.rule.SqlScoreRuleLoaderRulesEngine;
import com.jd.sql.analysis.score.SqlScoreResult;
import com.jd.sql.analysis.score.SqlScoreService;
import com.jd.sql.analysis.score.SqlScoreServiceRulesEngine;
import com.jd.sql.analysis.util.GsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.util.Properties; | 9,607 | package com.jd.sql.analysis.core;
/**
* @Author huhaitao21
* @Description sql分析切面类
* @Date 22:47 2022/10/25
**/
@Intercepts({@Signature(
type = StatementHandler.class,
method = "prepare",
args = {Connection.class, Integer.class}
), @Signature(
type = Executor.class,
method = "update",
args = {MappedStatement.class, Object.class}
),@Signature(
type = Executor.class,
method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
)})
public class SqlAnalysisAspect implements Interceptor {
Logger logger = LoggerFactory.getLogger(SqlAnalysisAspect.class);
/**
* 评分规则服务
*/
private static SqlScoreService sqlScoreService = new SqlScoreServiceRulesEngine();
/**
* 评分结果输出服务
*/
private static SqlScoreResultOutService sqlScoreResultOut = new SqlScoreResultOutServiceDefault();
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
Object firstArg = invocation.getArgs()[0];
if(SqlAnalysisConfig.getSqlReplaceModelSwitch()!=null && SqlAnalysisConfig.getSqlReplaceModelSwitch() && firstArg instanceof MappedStatement){
//sql替换模块
MappedStatement mappedStatement = (MappedStatement)firstArg;
String replaceSql = SqlReplaceConfig.getReplaceSqlBySqlId(mappedStatement.getId());
if(StringUtils.isNotBlank(replaceSql)){
SqlReplace.replace(invocation,replaceSql);
}
}else if(SqlAnalysisConfig.getAnalysisSwitch() && firstArg instanceof Connection){
//sql 分析模块
//获取入参statement
StatementHandler statementHandler = (StatementHandler)invocation.getTarget();
//提取待执行的完整sql语句
SqlExtractResult sqlExtractResult = SqlExtract.extract(statementHandler);
if(sqlExtractResult!=null){
//对sql进行分析
Connection connection = (Connection)invocation.getArgs()[0]; | package com.jd.sql.analysis.core;
/**
* @Author huhaitao21
* @Description sql分析切面类
* @Date 22:47 2022/10/25
**/
@Intercepts({@Signature(
type = StatementHandler.class,
method = "prepare",
args = {Connection.class, Integer.class}
), @Signature(
type = Executor.class,
method = "update",
args = {MappedStatement.class, Object.class}
),@Signature(
type = Executor.class,
method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
)})
public class SqlAnalysisAspect implements Interceptor {
Logger logger = LoggerFactory.getLogger(SqlAnalysisAspect.class);
/**
* 评分规则服务
*/
private static SqlScoreService sqlScoreService = new SqlScoreServiceRulesEngine();
/**
* 评分结果输出服务
*/
private static SqlScoreResultOutService sqlScoreResultOut = new SqlScoreResultOutServiceDefault();
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
Object firstArg = invocation.getArgs()[0];
if(SqlAnalysisConfig.getSqlReplaceModelSwitch()!=null && SqlAnalysisConfig.getSqlReplaceModelSwitch() && firstArg instanceof MappedStatement){
//sql替换模块
MappedStatement mappedStatement = (MappedStatement)firstArg;
String replaceSql = SqlReplaceConfig.getReplaceSqlBySqlId(mappedStatement.getId());
if(StringUtils.isNotBlank(replaceSql)){
SqlReplace.replace(invocation,replaceSql);
}
}else if(SqlAnalysisConfig.getAnalysisSwitch() && firstArg instanceof Connection){
//sql 分析模块
//获取入参statement
StatementHandler statementHandler = (StatementHandler)invocation.getTarget();
//提取待执行的完整sql语句
SqlExtractResult sqlExtractResult = SqlExtract.extract(statementHandler);
if(sqlExtractResult!=null){
//对sql进行分析
Connection connection = (Connection)invocation.getArgs()[0]; | SqlAnalysisResultList resultList = SqlAnalysis.analysis(sqlExtractResult,connection); | 0 | 2023-10-25 08:59:26+00:00 | 12k |
d0ge/sessionless | src/main/java/one/d4d/sessionless/presenter/KeyPresenter.java | [
{
"identifier": "BurpKeysModelPersistence",
"path": "src/main/java/burp/config/BurpKeysModelPersistence.java",
"snippet": "public class BurpKeysModelPersistence {\n static final String BURP_SETTINGS_NAME = \"one.d4d.sessionless.keys\";\n private final Preferences preferences;\n\n public BurpKey... | import burp.config.BurpKeysModelPersistence;
import burp.config.KeysModel;
import burp.config.KeysModelListener;
import one.d4d.sessionless.forms.WordlistView;
import one.d4d.sessionless.forms.dialog.KeyDialog;
import one.d4d.sessionless.forms.dialog.NewKeyDialog;
import one.d4d.sessionless.keys.SecretKey;
import one.d4d.sessionless.utils.Utils;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.List;
import static one.d4d.sessionless.utils.Utils.prettyPrintJSON; | 9,154 | package one.d4d.sessionless.presenter;
public class KeyPresenter extends Presenter {
private final KeysModel model;
private final PresenterStore presenters;
private final WordlistView view;
private final DefaultListModel<String> modelSecrets;
private final DefaultListModel<String> modelSalts;
private final BurpKeysModelPersistence keysModelPersistence;
public KeyPresenter(WordlistView view, PresenterStore presenters, KeysModel model, BurpKeysModelPersistence keysModelPersistence, DefaultListModel<String> modelSecrets, DefaultListModel<String> modelSalts) {
this.view = view;
this.presenters = presenters;
this.model = model;
this.keysModelPersistence = keysModelPersistence;
this.modelSecrets = modelSecrets;
this.modelSalts = modelSalts;
model.addKeyModelListener(new KeysModelListener() {
@Override
public void notifyKeyInserted(SecretKey key) {
view.addKey(key);
keysModelPersistence.save(model);
}
@Override
public void notifyKeyDeleted(int rowIndex) {
view.deleteKey(rowIndex);
keysModelPersistence.save(model);
}
});
presenters.register(this);
}
public void onButtonLoadSecretsClick(ActionEvent e) {
readSecretsFromFile(e);
}
public void onButtonRemoveSecretsClick(ActionEvent e) {
JList listSecrets = view.getSecretsList();
ListSelectionModel selmodel = listSecrets.getSelectionModel();
int index = selmodel.getMinSelectionIndex();
if (index >= 0) {
String s = modelSecrets.get(index);
modelSecrets.remove(index);
model.removeSecret(s);
}
}
public void onButtonCleanSecretsClick(ActionEvent e) {
modelSecrets.clear();
model.clearSecrets();
view.getSecretsTextArea().setText("");
}
public void onButtonLoadSaltsClick(ActionEvent e) {
readSaltsFromFile(e);
}
public void onButtonRemoveSaltsClick(ActionEvent e) {
JList listSalts = view.getSaltsList();
ListSelectionModel selmodel = listSalts.getSelectionModel();
int index = selmodel.getMinSelectionIndex();
if (index >= 0) {
String s = modelSalts.get(index);
modelSalts.remove(index);
model.removeSalt(s);
}
}
public void onButtonCleanSaltsClick(ActionEvent e) {
modelSalts.clear();
model.clearSalts();
view.getSaltsTextArea().setText("");
}
public void onButtonNewSecretKeyClick() {
KeyDialog d = new NewKeyDialog(view.getParent(), presenters);
d.display();
// If the dialog returned a key, add it to the model
if (d.getKey() != null) {
model.addKey((SecretKey) d.getKey());
}
}
public void onTableKeysDoubleClick() {
SecretKey key = model.getKey(view.getSelectedRow());
KeyDialog d;
// Get the dialog type based on the key type
if (key != null) {
d = new NewKeyDialog(view.getParent(), presenters, key);
} else {
return;
}
d.display();
// If dialog returned a key, replace the key in the store with the new key
SecretKey newKey = (SecretKey) d.getKey();
if (newKey != null) {
model.deleteKey(key);
model.addKey(newKey);
}
}
public void onPopupDelete(int[] rows) {
String messageResourceId = rows.length > 1 ? "keys_confirm_delete_multiple" : "keys_confirm_delete_single";
int option = JOptionPane.showConfirmDialog(
view.getParent(), | package one.d4d.sessionless.presenter;
public class KeyPresenter extends Presenter {
private final KeysModel model;
private final PresenterStore presenters;
private final WordlistView view;
private final DefaultListModel<String> modelSecrets;
private final DefaultListModel<String> modelSalts;
private final BurpKeysModelPersistence keysModelPersistence;
public KeyPresenter(WordlistView view, PresenterStore presenters, KeysModel model, BurpKeysModelPersistence keysModelPersistence, DefaultListModel<String> modelSecrets, DefaultListModel<String> modelSalts) {
this.view = view;
this.presenters = presenters;
this.model = model;
this.keysModelPersistence = keysModelPersistence;
this.modelSecrets = modelSecrets;
this.modelSalts = modelSalts;
model.addKeyModelListener(new KeysModelListener() {
@Override
public void notifyKeyInserted(SecretKey key) {
view.addKey(key);
keysModelPersistence.save(model);
}
@Override
public void notifyKeyDeleted(int rowIndex) {
view.deleteKey(rowIndex);
keysModelPersistence.save(model);
}
});
presenters.register(this);
}
public void onButtonLoadSecretsClick(ActionEvent e) {
readSecretsFromFile(e);
}
public void onButtonRemoveSecretsClick(ActionEvent e) {
JList listSecrets = view.getSecretsList();
ListSelectionModel selmodel = listSecrets.getSelectionModel();
int index = selmodel.getMinSelectionIndex();
if (index >= 0) {
String s = modelSecrets.get(index);
modelSecrets.remove(index);
model.removeSecret(s);
}
}
public void onButtonCleanSecretsClick(ActionEvent e) {
modelSecrets.clear();
model.clearSecrets();
view.getSecretsTextArea().setText("");
}
public void onButtonLoadSaltsClick(ActionEvent e) {
readSaltsFromFile(e);
}
public void onButtonRemoveSaltsClick(ActionEvent e) {
JList listSalts = view.getSaltsList();
ListSelectionModel selmodel = listSalts.getSelectionModel();
int index = selmodel.getMinSelectionIndex();
if (index >= 0) {
String s = modelSalts.get(index);
modelSalts.remove(index);
model.removeSalt(s);
}
}
public void onButtonCleanSaltsClick(ActionEvent e) {
modelSalts.clear();
model.clearSalts();
view.getSaltsTextArea().setText("");
}
public void onButtonNewSecretKeyClick() {
KeyDialog d = new NewKeyDialog(view.getParent(), presenters);
d.display();
// If the dialog returned a key, add it to the model
if (d.getKey() != null) {
model.addKey((SecretKey) d.getKey());
}
}
public void onTableKeysDoubleClick() {
SecretKey key = model.getKey(view.getSelectedRow());
KeyDialog d;
// Get the dialog type based on the key type
if (key != null) {
d = new NewKeyDialog(view.getParent(), presenters, key);
} else {
return;
}
d.display();
// If dialog returned a key, replace the key in the store with the new key
SecretKey newKey = (SecretKey) d.getKey();
if (newKey != null) {
model.deleteKey(key);
model.addKey(newKey);
}
}
public void onPopupDelete(int[] rows) {
String messageResourceId = rows.length > 1 ? "keys_confirm_delete_multiple" : "keys_confirm_delete_single";
int option = JOptionPane.showConfirmDialog(
view.getParent(), | Utils.getResourceString(messageResourceId), | 7 | 2023-10-30 09:12:06+00:00 | 12k |
LEAWIND/Third-Person | common/src/main/java/net/leawind/mc/thirdperson/core/CameraAgent.java | [
{
"identifier": "ThirdPerson",
"path": "common/src/main/java/net/leawind/mc/thirdperson/ThirdPerson.java",
"snippet": "public class ThirdPerson {\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(ModConstants.MOD_ID);\n\tprivate static final ConfigManager CONFIG_MA... | import net.leawind.mc.thirdperson.ThirdPerson;
import net.leawind.mc.thirdperson.api.ModConstants;
import net.leawind.mc.thirdperson.api.cameraoffset.CameraOffsetMode;
import net.leawind.mc.thirdperson.impl.config.Config;
import net.leawind.mc.thirdperson.mixin.CameraInvoker;
import net.leawind.mc.thirdperson.mixin.LocalPlayerInvoker;
import net.leawind.mc.util.api.math.vector.Vector2d;
import net.leawind.mc.util.api.math.vector.Vector3d;
import net.leawind.mc.util.math.LMath;
import net.leawind.mc.util.math.smoothvalue.ExpSmoothDouble;
import net.leawind.mc.util.math.smoothvalue.ExpSmoothVector2d;
import net.leawind.mc.util.math.smoothvalue.ExpSmoothVector3d;
import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.projectile.ProjectileUtil;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.phys.*;
import org.apache.logging.log4j.util.PerformanceSensitive;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | 9,673 | package net.leawind.mc.thirdperson.core;
public final class CameraAgent {
public static final @NotNull Camera fakeCamera = new Camera();
public static final @NotNull Vector2d relativeRotation = Vector2d.of(0);
/**
* 相机偏移量
*/
public static final @NotNull ExpSmoothVector2d smoothOffsetRatio;
/**
* 眼睛的平滑位置
*/
public static final @NotNull ExpSmoothVector3d smoothEyePosition;
/**
* 虚相机到平滑眼睛的距离
*/
public static final @NotNull ExpSmoothDouble smoothDistanceToEye;
public static @Nullable BlockGetter level;
public static @Nullable Camera camera;
/**
* renderTick 中更新
*/
public static boolean wasCameraCloseToEntity = false;
/**
* 上次玩家操控转动视角的时间
*/
public static double lastCameraTurnTimeStamp = 0;
static {
smoothOffsetRatio = new ExpSmoothVector2d();
smoothOffsetRatio.setSmoothFactorWeight(ModConstants.OFFSET_RATIO_SMOOTH_WEIGHT);
smoothEyePosition = new ExpSmoothVector3d();
smoothEyePosition.setSmoothFactorWeight(ModConstants.EYE_POSITIOIN_SMOOTH_WEIGHT);
smoothDistanceToEye = new ExpSmoothDouble();
smoothDistanceToEye.setSmoothFactorWeight(ModConstants.DISTANCE_TO_EYE_SMOOTH_WEIGHT);
}
/**
* 判断:模组功能已启用,且相机和玩家都已经初始化
*/
public static boolean isAvailable () {
Minecraft mc = Minecraft.getInstance();
if (!ThirdPerson.getConfig().is_mod_enable) {
return false;
} else if (!mc.gameRenderer.getMainCamera().isInitialized()) {
return false;
} else {
return mc.player != null;
}
}
/**
* 当前是否在控制玩家
* <p>
* 如果当前玩家处于旁观者模式,附着在其他实体上,则返回false
*/
public static boolean isControlledCamera () {
Minecraft mc = Minecraft.getInstance();
return (mc.player != null) && ((LocalPlayerInvoker)mc.player).invokeIsControlledCamera();
}
/**
* 重置玩家对象,重置相机的位置、角度等参数
*/
public static void reset () {
Minecraft mc = Minecraft.getInstance();
camera = mc.gameRenderer.getMainCamera();
ThirdPerson.lastPartialTick = mc.getFrameTime();
smoothOffsetRatio.setValue(0, 0);
smoothDistanceToEye.set(ThirdPerson.getConfig().distanceMonoList.get(0));
if (mc.cameraEntity != null) {
relativeRotation.set(-mc.cameraEntity.getViewXRot(ThirdPerson.lastPartialTick), mc.cameraEntity.getViewYRot(ThirdPerson.lastPartialTick) - 180);
}
}
/**
* 计算并更新相机的朝向和坐标
*
* @param period 维度
*/
@PerformanceSensitive
public static void onCameraSetup (double period) {
Minecraft mc = Minecraft.getInstance();
if (!mc.isPaused()) {
// 平滑更新距离
updateSmoothVirtualDistance(period);
// 平滑更新相机偏移量
updateSmoothOffsetRatio(period);
}
// 设置相机朝向和位置
updateFakeCameraRotationPosition();
preventThroughWall();
updateFakeCameraRotationPosition();
applyCamera();
wasCameraCloseToEntity = ModReferee.wasCameraCloseToEntity();
// if (wasCameraCloseToEntity) {
// // 假的第一人称,强制将相机放在玩家眼睛处
// Vec3 eyePosition = attachedEntity.getEyePosition(partialTick);
// ((CameraInvoker)fakeCamera).invokeSetPosition(eyePosition);
// applyCamera();
// }
}
public static void updateSmoothVirtualDistance (double period) {
Config config = ThirdPerson.getConfig();
boolean isAdjusting = ModReferee.isAdjustingCameraDistance();
CameraOffsetMode mode = config.cameraOffsetScheme.getMode();
smoothDistanceToEye.setSmoothFactor(isAdjusting ? config.adjusting_distance_smooth_factor: mode.getDistanceSmoothFactor());
smoothDistanceToEye.setTarget(mode.getMaxDistance());
smoothDistanceToEye.update(period);
// 如果是非瞄准模式下,且距离过远则强行放回去
if (!config.cameraOffsetScheme.isAiming() && !isAdjusting) {
smoothDistanceToEye.set(Math.min(mode.getMaxDistance(), smoothDistanceToEye.get()));
}
}
public static void updateSmoothOffsetRatio (double period) {
Config config = ThirdPerson.getConfig();
CameraOffsetMode mode = config.cameraOffsetScheme.getMode();
if (ModReferee.isAdjustingCameraOffset()) {
smoothOffsetRatio.setSmoothFactor(config.adjusting_camera_offset_smooth_factor);
} else {
mode.getOffsetSmoothFactor(smoothOffsetRatio.smoothFactor);
}
if (config.center_offset_when_flying && ModReferee.isAttachedEntityFallFlying()) {
smoothOffsetRatio.setTarget(0, 0);
} else {
mode.getOffsetRatio(smoothOffsetRatio.target);
}
smoothOffsetRatio.update(period);
}
/**
* 根据角度、距离、偏移量计算假相机实际朝向和位置
*/
private static void updateFakeCameraRotationPosition () {
Minecraft mc = Minecraft.getInstance();
// 宽高比
double aspectRatio = (double)mc.getWindow().getWidth() / mc.getWindow().getHeight();
// 垂直视野角度一半(弧度制)
double verticalRadianHalf = Math.toRadians(mc.options.fov().get()) / 2;
// 成像平面宽高
double heightHalf = Math.tan(verticalRadianHalf) * ModConstants.NEAR_PLANE_DISTANCE;
double widthHalf = aspectRatio * heightHalf;
// // 水平视野角度一半(弧度制)
// double horizonalRadianHalf = Math.atan(widthHalf / NEAR_PLANE_DISTANCE);
// 平滑值
Vector2d smoothOffsetRatioValue = smoothOffsetRatio.get();
double smoothVirtualDistanceValue = smoothDistanceToEye.get();
// 偏移量
double upOffset = smoothOffsetRatioValue.y() * smoothVirtualDistanceValue * Math.tan(verticalRadianHalf);
double leftOffset = smoothOffsetRatioValue.x() * smoothVirtualDistanceValue * widthHalf / ModConstants.NEAR_PLANE_DISTANCE;
// 没有偏移的情况下相机位置 | package net.leawind.mc.thirdperson.core;
public final class CameraAgent {
public static final @NotNull Camera fakeCamera = new Camera();
public static final @NotNull Vector2d relativeRotation = Vector2d.of(0);
/**
* 相机偏移量
*/
public static final @NotNull ExpSmoothVector2d smoothOffsetRatio;
/**
* 眼睛的平滑位置
*/
public static final @NotNull ExpSmoothVector3d smoothEyePosition;
/**
* 虚相机到平滑眼睛的距离
*/
public static final @NotNull ExpSmoothDouble smoothDistanceToEye;
public static @Nullable BlockGetter level;
public static @Nullable Camera camera;
/**
* renderTick 中更新
*/
public static boolean wasCameraCloseToEntity = false;
/**
* 上次玩家操控转动视角的时间
*/
public static double lastCameraTurnTimeStamp = 0;
static {
smoothOffsetRatio = new ExpSmoothVector2d();
smoothOffsetRatio.setSmoothFactorWeight(ModConstants.OFFSET_RATIO_SMOOTH_WEIGHT);
smoothEyePosition = new ExpSmoothVector3d();
smoothEyePosition.setSmoothFactorWeight(ModConstants.EYE_POSITIOIN_SMOOTH_WEIGHT);
smoothDistanceToEye = new ExpSmoothDouble();
smoothDistanceToEye.setSmoothFactorWeight(ModConstants.DISTANCE_TO_EYE_SMOOTH_WEIGHT);
}
/**
* 判断:模组功能已启用,且相机和玩家都已经初始化
*/
public static boolean isAvailable () {
Minecraft mc = Minecraft.getInstance();
if (!ThirdPerson.getConfig().is_mod_enable) {
return false;
} else if (!mc.gameRenderer.getMainCamera().isInitialized()) {
return false;
} else {
return mc.player != null;
}
}
/**
* 当前是否在控制玩家
* <p>
* 如果当前玩家处于旁观者模式,附着在其他实体上,则返回false
*/
public static boolean isControlledCamera () {
Minecraft mc = Minecraft.getInstance();
return (mc.player != null) && ((LocalPlayerInvoker)mc.player).invokeIsControlledCamera();
}
/**
* 重置玩家对象,重置相机的位置、角度等参数
*/
public static void reset () {
Minecraft mc = Minecraft.getInstance();
camera = mc.gameRenderer.getMainCamera();
ThirdPerson.lastPartialTick = mc.getFrameTime();
smoothOffsetRatio.setValue(0, 0);
smoothDistanceToEye.set(ThirdPerson.getConfig().distanceMonoList.get(0));
if (mc.cameraEntity != null) {
relativeRotation.set(-mc.cameraEntity.getViewXRot(ThirdPerson.lastPartialTick), mc.cameraEntity.getViewYRot(ThirdPerson.lastPartialTick) - 180);
}
}
/**
* 计算并更新相机的朝向和坐标
*
* @param period 维度
*/
@PerformanceSensitive
public static void onCameraSetup (double period) {
Minecraft mc = Minecraft.getInstance();
if (!mc.isPaused()) {
// 平滑更新距离
updateSmoothVirtualDistance(period);
// 平滑更新相机偏移量
updateSmoothOffsetRatio(period);
}
// 设置相机朝向和位置
updateFakeCameraRotationPosition();
preventThroughWall();
updateFakeCameraRotationPosition();
applyCamera();
wasCameraCloseToEntity = ModReferee.wasCameraCloseToEntity();
// if (wasCameraCloseToEntity) {
// // 假的第一人称,强制将相机放在玩家眼睛处
// Vec3 eyePosition = attachedEntity.getEyePosition(partialTick);
// ((CameraInvoker)fakeCamera).invokeSetPosition(eyePosition);
// applyCamera();
// }
}
public static void updateSmoothVirtualDistance (double period) {
Config config = ThirdPerson.getConfig();
boolean isAdjusting = ModReferee.isAdjustingCameraDistance();
CameraOffsetMode mode = config.cameraOffsetScheme.getMode();
smoothDistanceToEye.setSmoothFactor(isAdjusting ? config.adjusting_distance_smooth_factor: mode.getDistanceSmoothFactor());
smoothDistanceToEye.setTarget(mode.getMaxDistance());
smoothDistanceToEye.update(period);
// 如果是非瞄准模式下,且距离过远则强行放回去
if (!config.cameraOffsetScheme.isAiming() && !isAdjusting) {
smoothDistanceToEye.set(Math.min(mode.getMaxDistance(), smoothDistanceToEye.get()));
}
}
public static void updateSmoothOffsetRatio (double period) {
Config config = ThirdPerson.getConfig();
CameraOffsetMode mode = config.cameraOffsetScheme.getMode();
if (ModReferee.isAdjustingCameraOffset()) {
smoothOffsetRatio.setSmoothFactor(config.adjusting_camera_offset_smooth_factor);
} else {
mode.getOffsetSmoothFactor(smoothOffsetRatio.smoothFactor);
}
if (config.center_offset_when_flying && ModReferee.isAttachedEntityFallFlying()) {
smoothOffsetRatio.setTarget(0, 0);
} else {
mode.getOffsetRatio(smoothOffsetRatio.target);
}
smoothOffsetRatio.update(period);
}
/**
* 根据角度、距离、偏移量计算假相机实际朝向和位置
*/
private static void updateFakeCameraRotationPosition () {
Minecraft mc = Minecraft.getInstance();
// 宽高比
double aspectRatio = (double)mc.getWindow().getWidth() / mc.getWindow().getHeight();
// 垂直视野角度一半(弧度制)
double verticalRadianHalf = Math.toRadians(mc.options.fov().get()) / 2;
// 成像平面宽高
double heightHalf = Math.tan(verticalRadianHalf) * ModConstants.NEAR_PLANE_DISTANCE;
double widthHalf = aspectRatio * heightHalf;
// // 水平视野角度一半(弧度制)
// double horizonalRadianHalf = Math.atan(widthHalf / NEAR_PLANE_DISTANCE);
// 平滑值
Vector2d smoothOffsetRatioValue = smoothOffsetRatio.get();
double smoothVirtualDistanceValue = smoothDistanceToEye.get();
// 偏移量
double upOffset = smoothOffsetRatioValue.y() * smoothVirtualDistanceValue * Math.tan(verticalRadianHalf);
double leftOffset = smoothOffsetRatioValue.x() * smoothVirtualDistanceValue * widthHalf / ModConstants.NEAR_PLANE_DISTANCE;
// 没有偏移的情况下相机位置 | Vector3d positionWithoutOffset = calculatePositionWithoutOffset(); | 7 | 2023-10-31 05:52:36+00:00 | 12k |
kandybaby/S3mediaArchival | backend/src/main/java/com/example/mediaarchival/consumers/MediaObjectTransferListener.java | [
{
"identifier": "MediaController",
"path": "backend/src/main/java/com/example/mediaarchival/controllers/MediaController.java",
"snippet": "@RestController\n@RequestMapping(\"/api/media-objects\")\npublic class MediaController {\n private final MediaRepository mediaRepository;\n\n private final JmsTemp... | import com.example.mediaarchival.controllers.MediaController;
import com.example.mediaarchival.enums.ArchivedStatus;
import com.example.mediaarchival.models.MediaModel;
import com.example.mediaarchival.repositories.MediaRepository;
import com.example.mediaarchival.utils.TarUtils;
import java.io.File;
import java.io.IOException;
import java.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.transfer.s3.model.FileDownload;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.progress.TransferListener; | 7,520 | package com.example.mediaarchival.consumers;
public class MediaObjectTransferListener implements TransferListener {
private final MediaRepository mediaRepository; | package com.example.mediaarchival.consumers;
public class MediaObjectTransferListener implements TransferListener {
private final MediaRepository mediaRepository; | private final MediaController mediaController; | 0 | 2023-10-27 01:54:57+00:00 | 12k |
siam1026/siam-cloud | siam-mall/mall-provider/src/main/java/com/siam/package_mall/controller/admin/AdminPointsMallGoodsSpecificationOptionController.java | [
{
"identifier": "PointsMallGoodsSpecificationOptionService",
"path": "siam-mall/mall-provider/src/main/java/com/siam/package_mall/service/PointsMallGoodsSpecificationOptionService.java",
"snippet": "public interface PointsMallGoodsSpecificationOptionService {\n int countByExample(PointsMallGoodsSpeci... | import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siam.package_common.annoation.AdminPermission;
import com.siam.package_mall.service.PointsMallGoodsSpecificationOptionService;
import com.siam.package_mall.service.PointsMallGoodsSpecificationService;
import com.siam.package_common.entity.BasicData;
import com.siam.package_common.entity.BasicResult;
import com.siam.package_common.constant.BasicResultCode;
import com.siam.package_mall.model.dto.PointsMallGoodsSpecificationOptionDto;
import com.siam.package_mall.entity.PointsMallGoodsSpecification;
import com.siam.package_mall.entity.PointsMallGoodsSpecificationOption;
import com.siam.package_mall.model.example.PointsMallGoodsSpecificationOptionExample;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.Map; | 8,643 | package com.siam.package_mall.controller.admin;
@RestController
@RequestMapping(value = "/rest/admin/pointsMall/goodsSpecificationOption")
@Transactional(rollbackFor = Exception.class)
@Api(tags = "后台商品规格选项模块相关接口", description = "AdminPointsMallGoodsSpecificationOptionController")
public class AdminPointsMallGoodsSpecificationOptionController {
@Autowired
private PointsMallGoodsSpecificationOptionService goodsSpecificationOptionService;
@Autowired
private PointsMallGoodsSpecificationService goodsSpecificationService;
@ApiOperation(value = "商品规格选项列表")
@PostMapping(value = "/list")
public BasicResult list(@RequestBody @Validated(value = {}) PointsMallGoodsSpecificationOptionDto goodsSpecificationOptionDto){ | package com.siam.package_mall.controller.admin;
@RestController
@RequestMapping(value = "/rest/admin/pointsMall/goodsSpecificationOption")
@Transactional(rollbackFor = Exception.class)
@Api(tags = "后台商品规格选项模块相关接口", description = "AdminPointsMallGoodsSpecificationOptionController")
public class AdminPointsMallGoodsSpecificationOptionController {
@Autowired
private PointsMallGoodsSpecificationOptionService goodsSpecificationOptionService;
@Autowired
private PointsMallGoodsSpecificationService goodsSpecificationService;
@ApiOperation(value = "商品规格选项列表")
@PostMapping(value = "/list")
public BasicResult list(@RequestBody @Validated(value = {}) PointsMallGoodsSpecificationOptionDto goodsSpecificationOptionDto){ | BasicData basicResult = new BasicData(); | 2 | 2023-10-26 10:45:10+00:00 | 12k |
elizagamedev/android-libre-japanese-input | app/src/main/java/sh/eliza/japaneseinput/KeyEventButtonTouchListener.java | [
{
"identifier": "DrawableType",
"path": "app/src/main/java/sh/eliza/japaneseinput/keyboard/BackgroundDrawableFactory.java",
"snippet": "public enum DrawableType {\n // Key background for twelvekeys layout.\n TWELVEKEYS_REGULAR_KEY_BACKGROUND,\n TWELVEKEYS_FUNCTION_KEY_BACKGROUND,\n TWELVEKEYS_FUNCTI... | import android.view.View;
import android.view.View.OnTouchListener;
import com.google.common.base.Optional;
import java.util.Collections;
import org.mozc.android.inputmethod.japanese.protobuf.ProtoCommands.Input.TouchAction;
import sh.eliza.japaneseinput.keyboard.BackgroundDrawableFactory.DrawableType;
import sh.eliza.japaneseinput.keyboard.Flick;
import sh.eliza.japaneseinput.keyboard.Flick.Direction;
import sh.eliza.japaneseinput.keyboard.Key;
import sh.eliza.japaneseinput.keyboard.Key.Stick;
import sh.eliza.japaneseinput.keyboard.KeyEntity;
import sh.eliza.japaneseinput.keyboard.KeyEventContext;
import sh.eliza.japaneseinput.keyboard.KeyEventHandler;
import sh.eliza.japaneseinput.keyboard.KeyState;
import android.view.MotionEvent; | 9,139 | // Copyright 2010-2018, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package sh.eliza.japaneseinput;
/**
* This class is an event listener for a view which sends a key to MozcServer.
*
* <p>Note that currently, we assume all key are repeatable based on our requirements. We can easily
* support non repeatable key if necessary.
*/
public class KeyEventButtonTouchListener implements OnTouchListener {
private final int sourceId;
private final int keyCode; | // Copyright 2010-2018, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package sh.eliza.japaneseinput;
/**
* This class is an event listener for a view which sends a key to MozcServer.
*
* <p>Note that currently, we assume all key are repeatable based on our requirements. We can easily
* support non repeatable key if necessary.
*/
public class KeyEventButtonTouchListener implements OnTouchListener {
private final int sourceId;
private final int keyCode; | private KeyEventHandler keyEventHandler = null; | 7 | 2023-10-25 07:33:25+00:00 | 12k |
PhilipPanda/Temple-Client | src/main/java/xyz/templecheats/templeclient/impl/modules/world/Scaffold.java | [
{
"identifier": "TempleClient",
"path": "src/main/java/xyz/templecheats/templeclient/TempleClient.java",
"snippet": "@Mod(modid = TempleClient.MODID, name = TempleClient.NAME, version = TempleClient.VERSION)\npublic class TempleClient {\n public static String name = \"Temple Client 1.8.2\";\n\n pu... | import net.minecraft.block.BlockLiquid;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemBlock;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import org.lwjgl.input.Keyboard;
import team.stiff.pomelo.impl.annotated.handler.annotation.Listener;
import xyz.templecheats.templeclient.TempleClient;
import xyz.templecheats.templeclient.api.event.events.player.MotionEvent;
import xyz.templecheats.templeclient.api.util.time.TimerUtil;
import xyz.templecheats.templeclient.impl.gui.clickgui.setting.Setting;
import xyz.templecheats.templeclient.impl.modules.Module;
import xyz.templecheats.templeclient.impl.modules.combat.AutoCrystal; | 7,401 | package xyz.templecheats.templeclient.impl.modules.world;
public class Scaffold extends Module {
private final Setting tower = new Setting("Tower", this, true);
private final TimerUtil timer = new TimerUtil();
private BlockPos placePos;
private EnumFacing placeFace;
public Scaffold() {
super("Scaffold", Keyboard.KEY_NONE, Category.WORLD);
TempleClient.settingsManager.rSetting(tower);
}
@Listener | package xyz.templecheats.templeclient.impl.modules.world;
public class Scaffold extends Module {
private final Setting tower = new Setting("Tower", this, true);
private final TimerUtil timer = new TimerUtil();
private BlockPos placePos;
private EnumFacing placeFace;
public Scaffold() {
super("Scaffold", Keyboard.KEY_NONE, Category.WORLD);
TempleClient.settingsManager.rSetting(tower);
}
@Listener | public void onMotion(MotionEvent event) { | 1 | 2023-10-28 12:03:50+00:00 | 12k |
PlayReissLP/Continuity | src/main/java/me/pepperbell/continuity/client/processor/ProcessingDataKeys.java | [
{
"identifier": "ProcessingDataKey",
"path": "src/main/java/me/pepperbell/continuity/api/client/ProcessingDataKey.java",
"snippet": "public interface ProcessingDataKey<T> {\n\tIdentifier getId();\n\n\tint getRawId();\n\n\tSupplier<T> getValueSupplier();\n\n\t@Nullable\n\tConsumer<T> getValueResetAction(... | import java.util.function.Consumer;
import java.util.function.Supplier;
import me.pepperbell.continuity.api.client.ProcessingDataKey;
import me.pepperbell.continuity.api.client.ProcessingDataKeyRegistry;
import me.pepperbell.continuity.client.ContinuityClient;
import me.pepperbell.continuity.client.processor.overlay.SimpleOverlayQuadProcessor;
import me.pepperbell.continuity.client.processor.overlay.StandardOverlayQuadProcessor;
import net.fabricmc.fabric.api.renderer.v1.RendererAccess;
import net.fabricmc.fabric.api.renderer.v1.mesh.MeshBuilder;
import net.minecraft.util.math.BlockPos; | 7,597 | package me.pepperbell.continuity.client.processor;
public final class ProcessingDataKeys {
public static final ProcessingDataKey<BlockPos.Mutable> MUTABLE_POS_KEY = create("mutable_pos", BlockPos.Mutable::new);
public static final ProcessingDataKey<MeshBuilder> MESH_BUILDER_KEY = create("mesh_builder", () -> RendererAccess.INSTANCE.getRenderer().meshBuilder());
public static final ProcessingDataKey<BaseProcessingPredicate.BiomeCache> BIOME_CACHE_KEY = create("biome_cache", BaseProcessingPredicate.BiomeCache::new, BaseProcessingPredicate.BiomeCache::reset);
public static final ProcessingDataKey<BaseProcessingPredicate.BlockEntityNameCache> BLOCK_ENTITY_NAME_CACHE_KEY = create("block_entity_name_cache", BaseProcessingPredicate.BlockEntityNameCache::new, BaseProcessingPredicate.BlockEntityNameCache::reset);
public static final ProcessingDataKey<CompactCTMQuadProcessor.VertexContainer> VERTEX_CONTAINER_KEY = create("vertex_container", CompactCTMQuadProcessor.VertexContainer::new);
public static final ProcessingDataKey<StandardOverlayQuadProcessor.BlockStateAndBoolean> BLOCK_STATE_AND_BOOLEAN_KEY = create("block_state_and_boolean", StandardOverlayQuadProcessor.BlockStateAndBoolean::new);
public static final ProcessingDataKey<StandardOverlayQuadProcessor.OverlayRendererPool> STANDARD_OVERLAY_RENDERER_POOL_KEY = create("standard_overlay_renderer_pool", StandardOverlayQuadProcessor.OverlayRendererPool::new, StandardOverlayQuadProcessor.OverlayRendererPool::reset);
public static final ProcessingDataKey<SimpleOverlayQuadProcessor.OverlayRendererPool> SIMPLE_OVERLAY_RENDERER_POOL_KEY = create("simple_overlay_renderer_pool", SimpleOverlayQuadProcessor.OverlayRendererPool::new, SimpleOverlayQuadProcessor.OverlayRendererPool::reset);
private static <T> ProcessingDataKey<T> create(String id, Supplier<T> valueSupplier) { | package me.pepperbell.continuity.client.processor;
public final class ProcessingDataKeys {
public static final ProcessingDataKey<BlockPos.Mutable> MUTABLE_POS_KEY = create("mutable_pos", BlockPos.Mutable::new);
public static final ProcessingDataKey<MeshBuilder> MESH_BUILDER_KEY = create("mesh_builder", () -> RendererAccess.INSTANCE.getRenderer().meshBuilder());
public static final ProcessingDataKey<BaseProcessingPredicate.BiomeCache> BIOME_CACHE_KEY = create("biome_cache", BaseProcessingPredicate.BiomeCache::new, BaseProcessingPredicate.BiomeCache::reset);
public static final ProcessingDataKey<BaseProcessingPredicate.BlockEntityNameCache> BLOCK_ENTITY_NAME_CACHE_KEY = create("block_entity_name_cache", BaseProcessingPredicate.BlockEntityNameCache::new, BaseProcessingPredicate.BlockEntityNameCache::reset);
public static final ProcessingDataKey<CompactCTMQuadProcessor.VertexContainer> VERTEX_CONTAINER_KEY = create("vertex_container", CompactCTMQuadProcessor.VertexContainer::new);
public static final ProcessingDataKey<StandardOverlayQuadProcessor.BlockStateAndBoolean> BLOCK_STATE_AND_BOOLEAN_KEY = create("block_state_and_boolean", StandardOverlayQuadProcessor.BlockStateAndBoolean::new);
public static final ProcessingDataKey<StandardOverlayQuadProcessor.OverlayRendererPool> STANDARD_OVERLAY_RENDERER_POOL_KEY = create("standard_overlay_renderer_pool", StandardOverlayQuadProcessor.OverlayRendererPool::new, StandardOverlayQuadProcessor.OverlayRendererPool::reset);
public static final ProcessingDataKey<SimpleOverlayQuadProcessor.OverlayRendererPool> SIMPLE_OVERLAY_RENDERER_POOL_KEY = create("simple_overlay_renderer_pool", SimpleOverlayQuadProcessor.OverlayRendererPool::new, SimpleOverlayQuadProcessor.OverlayRendererPool::reset);
private static <T> ProcessingDataKey<T> create(String id, Supplier<T> valueSupplier) { | return ProcessingDataKeyRegistry.INSTANCE.registerKey(ContinuityClient.asId(id), valueSupplier); | 1 | 2023-10-29 00:08:50+00:00 | 12k |
oghenevovwerho/yaa | src/main/java/yaa/semantic/handlers/MEqualOp.java | [
{
"identifier": "MEqual",
"path": "src/main/java/yaa/ast/MEqual.java",
"snippet": "public class MEqual extends BinaryStmt {\r\n public MEqual(Stmt e1, YaaToken op, Stmt e2) {\r\n super(e1, op, e2);\r\n }\r\n\r\n @Override\r\n public YaaInfo visit(FileState fs) {\r\n return fs.$mEqual(this);\r\... | import yaa.ast.MEqual;
import yaa.pojos.GlobalData;
import yaa.semantic.passes.fs6.results.CallResult;
import yaa.pojos.YaaFun;
import yaa.pojos.YaaInfo;
import static yaa.pojos.GlobalData.fs;
import static yaa.pojos.GlobalData.results;
| 7,739 | package yaa.semantic.handlers;
public class MEqualOp {
public static YaaInfo mEqual(MEqual $mequal) {
| package yaa.semantic.handlers;
public class MEqualOp {
public static YaaInfo mEqual(MEqual $mequal) {
| var equal$mtd = new YaaFun("equals", $mequal.e1.visit(GlobalData.fs).name);
| 3 | 2023-10-26 17:41:13+00:00 | 12k |
echcz/web-service | src/main/jooq/cn/echcz/webservice/adapter/repository/Keys.java | [
{
"identifier": "ActionLogTable",
"path": "src/main/jooq/cn/echcz/webservice/adapter/repository/tables/ActionLogTable.java",
"snippet": "@SuppressWarnings({ \"all\", \"unchecked\", \"rawtypes\" })\npublic class ActionLogTable extends TableImpl<ActionLogRecord> {\n\n private static final long serialVe... | import cn.echcz.webservice.adapter.repository.tables.ActionLogTable;
import cn.echcz.webservice.adapter.repository.tables.DocumentTable;
import cn.echcz.webservice.adapter.repository.tables.records.ActionLogRecord;
import cn.echcz.webservice.adapter.repository.tables.records.DocumentRecord;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.DSL;
import org.jooq.impl.Internal; | 7,410 | /*
* This file is generated by jOOQ.
*/
package cn.echcz.webservice.adapter.repository;
/**
* A class modelling foreign key relationships and constraints of tables in
* the default schema.
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Keys {
// -------------------------------------------------------------------------
// UNIQUE and PRIMARY KEY definitions
// -------------------------------------------------------------------------
public static final UniqueKey<ActionLogRecord> KEY_ACTION_LOG_PRIMARY = Internal.createUniqueKey(ActionLogTable.ACTION_LOG, DSL.name("KEY_action_log_PRIMARY"), new TableField[] { ActionLogTable.ACTION_LOG.ID }, true); | /*
* This file is generated by jOOQ.
*/
package cn.echcz.webservice.adapter.repository;
/**
* A class modelling foreign key relationships and constraints of tables in
* the default schema.
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Keys {
// -------------------------------------------------------------------------
// UNIQUE and PRIMARY KEY definitions
// -------------------------------------------------------------------------
public static final UniqueKey<ActionLogRecord> KEY_ACTION_LOG_PRIMARY = Internal.createUniqueKey(ActionLogTable.ACTION_LOG, DSL.name("KEY_action_log_PRIMARY"), new TableField[] { ActionLogTable.ACTION_LOG.ID }, true); | public static final UniqueKey<DocumentRecord> KEY_DOCUMENT_PRIMARY = Internal.createUniqueKey(DocumentTable.DOCUMENT, DSL.name("KEY_document_PRIMARY"), new TableField[] { DocumentTable.DOCUMENT.ID }, true); | 1 | 2023-10-30 18:55:49+00:00 | 12k |
tom5454/Toms-Peripherals | Forge/src/platform-shared/java/com/tom/peripherals/Content.java | [
{
"identifier": "GPUBlock",
"path": "Forge/src/platform-shared/java/com/tom/peripherals/block/GPUBlock.java",
"snippet": "public class GPUBlock extends Block implements EntityBlock {\n\n\tpublic GPUBlock() {\n\t\tsuper(Block.Properties.of().mapColor(DyeColor.WHITE).sound(SoundType.METAL).strength(5));\n... | import java.util.function.Function;
import java.util.function.Supplier;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import com.tom.peripherals.block.GPUBlock;
import com.tom.peripherals.block.MonitorBlock;
import com.tom.peripherals.block.RedstonePortBlock;
import com.tom.peripherals.block.WatchDogTimerBlock;
import com.tom.peripherals.block.entity.GPUBlockEntity;
import com.tom.peripherals.block.entity.MonitorBlockEntity;
import com.tom.peripherals.block.entity.RedstonePortBlockEntity;
import com.tom.peripherals.block.entity.WatchDogTimerBlockEntity;
import com.tom.peripherals.platform.GameObject;
import com.tom.peripherals.platform.GameObject.GameObjectBlockEntity;
import com.tom.peripherals.platform.GameObject.GameRegistryBE.BlockEntityFactory;
import com.tom.peripherals.platform.Platform; | 10,689 | package com.tom.peripherals;
public class Content {
public static final GameObject<GPUBlock> gpu = blockWithItem("gpu", GPUBlock::new);
public static final GameObject<MonitorBlock> monitor = blockWithItem("monitor", MonitorBlock::new);
public static final GameObject<WatchDogTimerBlock> wdt = blockWithItem("wdt", WatchDogTimerBlock::new);
public static final GameObject<RedstonePortBlock> redstonePort = blockWithItem("redstone_port", RedstonePortBlock::new);
public static final GameObject<Item> gpuChip = item("gpu_chip", () -> new Item(new Item.Properties()));
public static final GameObject<Item> gpuChipRaw = item("gpu_chip_raw", () -> new Item(new Item.Properties()));
| package com.tom.peripherals;
public class Content {
public static final GameObject<GPUBlock> gpu = blockWithItem("gpu", GPUBlock::new);
public static final GameObject<MonitorBlock> monitor = blockWithItem("monitor", MonitorBlock::new);
public static final GameObject<WatchDogTimerBlock> wdt = blockWithItem("wdt", WatchDogTimerBlock::new);
public static final GameObject<RedstonePortBlock> redstonePort = blockWithItem("redstone_port", RedstonePortBlock::new);
public static final GameObject<Item> gpuChip = item("gpu_chip", () -> new Item(new Item.Properties()));
public static final GameObject<Item> gpuChipRaw = item("gpu_chip_raw", () -> new Item(new Item.Properties()));
| public static final GameObjectBlockEntity<GPUBlockEntity> gpuBE = blockEntity("gpu", GPUBlockEntity::new, gpu); | 4 | 2023-10-30 17:05:11+00:00 | 12k |
unloggedio/intellij-java-plugin | src/main/java/com/insidious/plugin/client/VideobugLocalClient.java | [
{
"identifier": "SessionNotSelectedException",
"path": "src/main/java/com/insidious/plugin/client/exception/SessionNotSelectedException.java",
"snippet": "public class SessionNotSelectedException extends Throwable {\n}"
},
{
"identifier": "DataResponse",
"path": "src/main/java/com/insidious/... | import com.insidious.common.FilteredDataEventsRequest;
import com.insidious.common.weaver.TypeInfo;
import com.insidious.plugin.callbacks.*;
import com.insidious.plugin.client.exception.SessionNotSelectedException;
import com.insidious.plugin.client.pojo.DataResponse;
import com.insidious.plugin.client.pojo.ExecutionSession;
import com.insidious.plugin.client.pojo.SigninRequest;
import com.insidious.plugin.extension.model.ReplayData;
import com.insidious.plugin.factory.ActiveSessionManager;
import com.insidious.plugin.pojo.SearchQuery;
import com.insidious.plugin.pojo.TracePoint;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.project.Project;
import java.io.File;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; | 9,631 | package com.insidious.plugin.client;
public class VideobugLocalClient implements VideobugClientInterface {
private static final Logger logger = Logger.getInstance(VideobugLocalClient.class.getName());
private final String pathToSessions;
private final VideobugNetworkClient networkClient;
private final ScheduledExecutorService threadPoolExecutor5Seconds = Executors.newScheduledThreadPool(1);
private final Project project;
private final ActiveSessionManager sessionManager;
private SessionInstance sessionInstance;
private ProjectItem currentProject;
public VideobugLocalClient(String pathToSessions, Project project, ActiveSessionManager sessionManager) {
this.project = project;
this.sessionManager = sessionManager;
if (!pathToSessions.endsWith("/")) {
pathToSessions = pathToSessions + "/";
}
this.pathToSessions = pathToSessions;
this.networkClient = new VideobugNetworkClient("https://cloud.bug.video");
}
@Override
public ExecutionSession getCurrentSession() {
if (this.sessionInstance == null) {
return null;
}
return this.sessionInstance.getExecutionSession();
}
@Override
public void signup(String serverUrl, String username, String password, SignUpCallback callback) {
callback.success();
}
@Override
public void signin(SigninRequest signinRequest, SignInCallback signInCallback) {
signInCallback.success("localhost-token");
}
@Override
public void getProjectByName(String projectName, GetProjectCallback getProjectCallback) {
getProjectCallback.success(projectName);
}
@Override
public ProjectItem fetchProjectByName(String projectName) {
ProjectItem projectItem = new ProjectItem();
projectItem.setName(projectName);
projectItem.setId("1");
projectItem.setCreatedAt(new Date().toString());
return projectItem;
}
@Override
public void createProject(String projectName, NewProjectCallback newProjectCallback) {
newProjectCallback.success("1");
}
@Override
public void getProjectToken(ProjectTokenCallback projectTokenCallback) {
projectTokenCallback.success("localhost-token");
}
@Override
public void getProjectSessions(GetProjectSessionsCallback getProjectSessionsCallback) {
getProjectSessionsCallback.success(getLocalSessions());
}
private List<ExecutionSession> getLocalSessions() {
List<ExecutionSession> list = new ArrayList<>();
logger.debug(String.format("looking for sessions in [%s]", pathToSessions));
File currentDir = new File(pathToSessions);
if (!currentDir.exists()) {
currentDir.mkdirs();
return Collections.emptyList();
}
File[] sessionDirectories = currentDir.listFiles();
if (sessionDirectories == null) {
return Collections.emptyList();
}
for (File file : sessionDirectories) {
if (file.isDirectory() && file.getName().contains("selogger")) {
ExecutionSession executionSession = new ExecutionSession();
executionSession.setSessionId(file.getName());
executionSession.setCreatedAt(new Date(file.lastModified()));
executionSession.setHostname("localhost");
executionSession.setLastUpdateAt(file.lastModified());
executionSession.setPath(file.getAbsolutePath());
list.add(executionSession);
}
}
logger.debug("Session list: " + list);
if (list.size() > 1) {
list.sort(Comparator.comparing(ExecutionSession::getSessionId));
logger.debug("Session list after sort by session id: " + list);
Collections.reverse(list);
logger.debug("Session list after reverse: " + list);
int i = -1;
if (list.size() > 0) {
for (ExecutionSession executionSession : list) {
i++;
if (i == 0) {
continue;
}
logger.warn("Deleting session: " + executionSession.getSessionId() + " => " + project.getName());
sessionManager.cleanUpSessionDirectory(executionSession);
}
}
}
return list;
}
@Override
public DataResponse<ExecutionSession> fetchProjectSessions() {
List<ExecutionSession> localSessions = getLocalSessions();
return new DataResponse<>(localSessions, localSessions.size(), 1);
}
@Override
public void queryTracePointsByValue(
SearchQuery searchQuery,
String sessionId, | package com.insidious.plugin.client;
public class VideobugLocalClient implements VideobugClientInterface {
private static final Logger logger = Logger.getInstance(VideobugLocalClient.class.getName());
private final String pathToSessions;
private final VideobugNetworkClient networkClient;
private final ScheduledExecutorService threadPoolExecutor5Seconds = Executors.newScheduledThreadPool(1);
private final Project project;
private final ActiveSessionManager sessionManager;
private SessionInstance sessionInstance;
private ProjectItem currentProject;
public VideobugLocalClient(String pathToSessions, Project project, ActiveSessionManager sessionManager) {
this.project = project;
this.sessionManager = sessionManager;
if (!pathToSessions.endsWith("/")) {
pathToSessions = pathToSessions + "/";
}
this.pathToSessions = pathToSessions;
this.networkClient = new VideobugNetworkClient("https://cloud.bug.video");
}
@Override
public ExecutionSession getCurrentSession() {
if (this.sessionInstance == null) {
return null;
}
return this.sessionInstance.getExecutionSession();
}
@Override
public void signup(String serverUrl, String username, String password, SignUpCallback callback) {
callback.success();
}
@Override
public void signin(SigninRequest signinRequest, SignInCallback signInCallback) {
signInCallback.success("localhost-token");
}
@Override
public void getProjectByName(String projectName, GetProjectCallback getProjectCallback) {
getProjectCallback.success(projectName);
}
@Override
public ProjectItem fetchProjectByName(String projectName) {
ProjectItem projectItem = new ProjectItem();
projectItem.setName(projectName);
projectItem.setId("1");
projectItem.setCreatedAt(new Date().toString());
return projectItem;
}
@Override
public void createProject(String projectName, NewProjectCallback newProjectCallback) {
newProjectCallback.success("1");
}
@Override
public void getProjectToken(ProjectTokenCallback projectTokenCallback) {
projectTokenCallback.success("localhost-token");
}
@Override
public void getProjectSessions(GetProjectSessionsCallback getProjectSessionsCallback) {
getProjectSessionsCallback.success(getLocalSessions());
}
private List<ExecutionSession> getLocalSessions() {
List<ExecutionSession> list = new ArrayList<>();
logger.debug(String.format("looking for sessions in [%s]", pathToSessions));
File currentDir = new File(pathToSessions);
if (!currentDir.exists()) {
currentDir.mkdirs();
return Collections.emptyList();
}
File[] sessionDirectories = currentDir.listFiles();
if (sessionDirectories == null) {
return Collections.emptyList();
}
for (File file : sessionDirectories) {
if (file.isDirectory() && file.getName().contains("selogger")) {
ExecutionSession executionSession = new ExecutionSession();
executionSession.setSessionId(file.getName());
executionSession.setCreatedAt(new Date(file.lastModified()));
executionSession.setHostname("localhost");
executionSession.setLastUpdateAt(file.lastModified());
executionSession.setPath(file.getAbsolutePath());
list.add(executionSession);
}
}
logger.debug("Session list: " + list);
if (list.size() > 1) {
list.sort(Comparator.comparing(ExecutionSession::getSessionId));
logger.debug("Session list after sort by session id: " + list);
Collections.reverse(list);
logger.debug("Session list after reverse: " + list);
int i = -1;
if (list.size() > 0) {
for (ExecutionSession executionSession : list) {
i++;
if (i == 0) {
continue;
}
logger.warn("Deleting session: " + executionSession.getSessionId() + " => " + project.getName());
sessionManager.cleanUpSessionDirectory(executionSession);
}
}
}
return list;
}
@Override
public DataResponse<ExecutionSession> fetchProjectSessions() {
List<ExecutionSession> localSessions = getLocalSessions();
return new DataResponse<>(localSessions, localSessions.size(), 1);
}
@Override
public void queryTracePointsByValue(
SearchQuery searchQuery,
String sessionId, | ClientCallBack<TracePoint> getProjectSessionErrorsCallback) { | 7 | 2023-10-31 09:07:46+00:00 | 12k |
quentin452/DangerRPG-Continuation | src/main/java/mixac1/dangerrpg/api/entity/EntityAttribute.java | [
{
"identifier": "DangerRPG",
"path": "src/main/java/mixac1/dangerrpg/DangerRPG.java",
"snippet": "@Mod(\n modid = DangerRPG.MODID,\n name = DangerRPG.MODNAME,\n version = DangerRPG.VERSION,\n acceptedMinecraftVersions = DangerRPG.ACCEPTED_VERSION,\n dependencies = \"required-after:Forge\"... | import mixac1.dangerrpg.DangerRPG;
import mixac1.dangerrpg.capability.data.RPGEntityProperties;
import mixac1.dangerrpg.init.RPGCapability;
import mixac1.dangerrpg.init.RPGNetwork;
import mixac1.dangerrpg.network.MsgSyncEA;
import mixac1.dangerrpg.util.ITypeProvider;
import mixac1.dangerrpg.util.Tuple.Stub;
import mixac1.dangerrpg.util.Utils;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import java.util.UUID; | 7,743 | package mixac1.dangerrpg.api.entity;
/**
* Default entity attribute. It supports any Type, but you must create {@link ITypeProvider} for this Type. <br>
* {@link LvlEAProvider} allows making this attribute levelable.
*/
public class EntityAttribute<Type> {
public final String name;
public final int hash;
public final ITypeProvider<Type> typeProvider;
public EntityAttribute(ITypeProvider<Type> typeProvider, String name) {
this.name = "ea.".concat(name);
this.hash = name.hashCode();
this.typeProvider = typeProvider;
RPGCapability.mapIntToEntityAttribute.put(hash, this);
}
public void init(EntityLivingBase entity) {
RPGEntityProperties properties = getEntityData(entity); | package mixac1.dangerrpg.api.entity;
/**
* Default entity attribute. It supports any Type, but you must create {@link ITypeProvider} for this Type. <br>
* {@link LvlEAProvider} allows making this attribute levelable.
*/
public class EntityAttribute<Type> {
public final String name;
public final int hash;
public final ITypeProvider<Type> typeProvider;
public EntityAttribute(ITypeProvider<Type> typeProvider, String name) {
this.name = "ea.".concat(name);
this.hash = name.hashCode();
this.typeProvider = typeProvider;
RPGCapability.mapIntToEntityAttribute.put(hash, this);
}
public void init(EntityLivingBase entity) {
RPGEntityProperties properties = getEntityData(entity); | properties.attributeMap.put(hash, new Stub<Type>(typeProvider.getEmpty())); | 6 | 2023-10-31 21:00:14+00:00 | 12k |
thinhunan/wonder8-promotion-rule | java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/Strategy.java | [
{
"identifier": "Item",
"path": "java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/model/Item.java",
"snippet": "public class Item {\n String category;\n String SPU;\n String SKU;\n String seat;\n\n /// 单位:分 (by cent)\n int price;\n\n public Item(){}\n\n /*\n * @... | import com.github.thinhunan.wonder8.promotion.rule.model.Item;
import com.github.thinhunan.wonder8.promotion.rule.model.P;
import com.github.thinhunan.wonder8.promotion.rule.model.Rule;
import com.github.thinhunan.wonder8.promotion.rule.model.SimplexRule;
import com.github.thinhunan.wonder8.promotion.rule.model.strategy.BestMatch;
import com.github.thinhunan.wonder8.promotion.rule.model.strategy.Calculator;
import com.github.thinhunan.wonder8.promotion.rule.model.strategy.MatchGroup;
import com.github.thinhunan.wonder8.promotion.rule.model.strategy.MatchType;
import com.github.thinhunan.wonder8.promotion.rule.model.validate.RuleValidateResult;
import java.util.*; | 8,014 | package com.github.thinhunan.wonder8.promotion.rule;
public class Strategy {
/**
* 找出一组商品和和一堆规则的最佳组合匹配,即多个规则合作下优惠力度最大的匹配结果
* @param rules {Rule[]}
* @param items {Item[]}
* @param type {MatchType}
* MatchType.OneTime = 匹配一次
* MatchType.OneRule = 匹配一个规则,但这个规则可以匹配多次
* MatchType.MultiRule = 可以匹配多个规则,每个规则可以匹配多次
* @param groupSetting {MatchGroup}
* MatchGroup.CrossedMatch = 分组计算,不同组的优惠可叠加,所有规则放在一起求最大优惠
* MatchGroup.SequentialMatch = 分组计算,不同组的优惠可叠加,不同组的优惠按组计算后求最大叠加优惠
* @return {BestMatch}
*/
public static BestMatch bestChoice(List<Rule> rules, List<Item> items, MatchType type, MatchGroup groupSetting) {
BestMatch bestMatch = Calculator.calculate(rules, items,type, groupSetting);
bindSuggestion(bestMatch);
return bestMatch;
}
/**
* 找出一组商品和和一堆规则的最佳组合匹配,即多个规则合作下优惠力度最大的匹配结果
* @param rules {Rule[]}
* @param items {Item[]}
* @param type {MatchType}
* MatchType.OneTime = 匹配一次
* MatchType.OneRule = 匹配一个规则,但这个规则可以匹配多次
* MatchType.MultiRule = 可以匹配多个规则,每个规则可以匹配多次
* @return {BestMatch}
*/
public static BestMatch bestChoice(List<Rule> rules, List<Item> items, MatchType type) {
return bestChoice(rules, items,type,MatchGroup.CrossedMatch);
}
/**
* 找出一组商品和和一堆规则的最佳匹配,但只应用一条规则
* @param {Rule[]} rules
* @param {Item[]} tickets
* @return {MatchResult}
*/
@Deprecated
public static BestMatch bestMatch(List<Rule> rules, List<Item> items) {
return bestChoice(rules, items,MatchType.OneRule);
}
/**
* 找出一组商品和和一堆规则的最佳匹配,即优惠力度最大的匹配结果
* 与bestMatch()的区别在于,不管当前选的商品可以拆成匹配多少次,都只按一次匹配来算优惠
* 匹配的张数是规则的最低要求,价值取最高价格
* @param {Rule[]} rules
* @param {Item[]} tickets
* @return {MatchResult}
*/
@Deprecated
public static BestMatch bestOfOnlyOnceDiscount(List<Rule> rules, List<Item> items) {
return bestChoice(rules, items,MatchType.OneTime);
}
private static void bindSuggestion(BestMatch best) {
if (best != null) {
List<RuleValidateResult> ss = suggestions(best.getRules(), best.left());
if (ss != null && ss.size() > 0) {
best.setSuggestion(ss.get(0));
}
}
}
/**
* 获取所有未匹配但是比当前匹配更好的优惠组合建议
* 最好不直接调用,而通过调用bestMatch()再调用返回结果的suggestion属性来获取拼单建议,
* 因为会过滤当前商品集合已满足的优惠条件,可能造成没有更多的规则可供建议,而bestMatch的是匹配完后基于剩下的商品来建议
*/
public static List<RuleValidateResult> suggestions(List<Rule> rules, List<Item> items) {
//remember discount is negative number
int minDiscount = 1;
List<Rule> dontMatchedRules = new ArrayList<>();
for (Rule r : rules) {
if (r.check(items)) {
int discountValue = r.discount(items);
if (discountValue < minDiscount) {
minDiscount = discountValue;
}
} else {
dontMatchedRules.add(r);
}
}
List<RuleValidateResult> results = new ArrayList<>();
int finalMinDiscount = minDiscount;
//要小于已匹配的打折,才是更好的打折
dontMatchedRules.stream().filter(r -> r.discount(items) < finalMinDiscount)
.forEach(r -> results.add(r.validate(items)));
return results;
}
/**
* 获取当前未匹配,但是最接近的优惠组合拼单建议
* 最好不直接调用,而通过调用bestMatch()再调用返回结果的suggestion属性来获取拼单建议,
* 因为会过滤当前商品集合已满足的优惠条件,可能造成没有更多的规则可供建议,而bestMatch的是匹配完后基于剩下的商品来建议
*/
public static RuleValidateResult suggestion(List<Rule> rules, List<Item> items) {
List<RuleValidateResult> results = Strategy.suggestions(rules, items);
//缺张数优先级高还是差总价优先级高,咱讲道理,按每个商品的平均价来
int averagePrice = items.stream().map(Item::getPrice).reduce(0, Integer::sum) / items.size();
RuleValidateResult best = null;
int moreCount = 10000, moreSum = 100000000;
for (RuleValidateResult r :results) {
int[] needs = validateNeeds(r);
if(moreCount * averagePrice + moreSum > needs[0]*averagePrice + needs[1]){
moreCount = needs[0];
moreSum = needs[1];
best = r;
}
}
return best;
}
/*
* @Returns int[0] = count,int[1] = sum;
*/
private static int[] validateNeeds(RuleValidateResult result) {
int[] values = new int[2];
List<RuleValidateResult> clauses = result.getClauseResults();
if(clauses == null || clauses.size() == 0){
if(result.getRule() instanceof SimplexRule){
SimplexRule simplex = (SimplexRule) result.getRule(); | package com.github.thinhunan.wonder8.promotion.rule;
public class Strategy {
/**
* 找出一组商品和和一堆规则的最佳组合匹配,即多个规则合作下优惠力度最大的匹配结果
* @param rules {Rule[]}
* @param items {Item[]}
* @param type {MatchType}
* MatchType.OneTime = 匹配一次
* MatchType.OneRule = 匹配一个规则,但这个规则可以匹配多次
* MatchType.MultiRule = 可以匹配多个规则,每个规则可以匹配多次
* @param groupSetting {MatchGroup}
* MatchGroup.CrossedMatch = 分组计算,不同组的优惠可叠加,所有规则放在一起求最大优惠
* MatchGroup.SequentialMatch = 分组计算,不同组的优惠可叠加,不同组的优惠按组计算后求最大叠加优惠
* @return {BestMatch}
*/
public static BestMatch bestChoice(List<Rule> rules, List<Item> items, MatchType type, MatchGroup groupSetting) {
BestMatch bestMatch = Calculator.calculate(rules, items,type, groupSetting);
bindSuggestion(bestMatch);
return bestMatch;
}
/**
* 找出一组商品和和一堆规则的最佳组合匹配,即多个规则合作下优惠力度最大的匹配结果
* @param rules {Rule[]}
* @param items {Item[]}
* @param type {MatchType}
* MatchType.OneTime = 匹配一次
* MatchType.OneRule = 匹配一个规则,但这个规则可以匹配多次
* MatchType.MultiRule = 可以匹配多个规则,每个规则可以匹配多次
* @return {BestMatch}
*/
public static BestMatch bestChoice(List<Rule> rules, List<Item> items, MatchType type) {
return bestChoice(rules, items,type,MatchGroup.CrossedMatch);
}
/**
* 找出一组商品和和一堆规则的最佳匹配,但只应用一条规则
* @param {Rule[]} rules
* @param {Item[]} tickets
* @return {MatchResult}
*/
@Deprecated
public static BestMatch bestMatch(List<Rule> rules, List<Item> items) {
return bestChoice(rules, items,MatchType.OneRule);
}
/**
* 找出一组商品和和一堆规则的最佳匹配,即优惠力度最大的匹配结果
* 与bestMatch()的区别在于,不管当前选的商品可以拆成匹配多少次,都只按一次匹配来算优惠
* 匹配的张数是规则的最低要求,价值取最高价格
* @param {Rule[]} rules
* @param {Item[]} tickets
* @return {MatchResult}
*/
@Deprecated
public static BestMatch bestOfOnlyOnceDiscount(List<Rule> rules, List<Item> items) {
return bestChoice(rules, items,MatchType.OneTime);
}
private static void bindSuggestion(BestMatch best) {
if (best != null) {
List<RuleValidateResult> ss = suggestions(best.getRules(), best.left());
if (ss != null && ss.size() > 0) {
best.setSuggestion(ss.get(0));
}
}
}
/**
* 获取所有未匹配但是比当前匹配更好的优惠组合建议
* 最好不直接调用,而通过调用bestMatch()再调用返回结果的suggestion属性来获取拼单建议,
* 因为会过滤当前商品集合已满足的优惠条件,可能造成没有更多的规则可供建议,而bestMatch的是匹配完后基于剩下的商品来建议
*/
public static List<RuleValidateResult> suggestions(List<Rule> rules, List<Item> items) {
//remember discount is negative number
int minDiscount = 1;
List<Rule> dontMatchedRules = new ArrayList<>();
for (Rule r : rules) {
if (r.check(items)) {
int discountValue = r.discount(items);
if (discountValue < minDiscount) {
minDiscount = discountValue;
}
} else {
dontMatchedRules.add(r);
}
}
List<RuleValidateResult> results = new ArrayList<>();
int finalMinDiscount = minDiscount;
//要小于已匹配的打折,才是更好的打折
dontMatchedRules.stream().filter(r -> r.discount(items) < finalMinDiscount)
.forEach(r -> results.add(r.validate(items)));
return results;
}
/**
* 获取当前未匹配,但是最接近的优惠组合拼单建议
* 最好不直接调用,而通过调用bestMatch()再调用返回结果的suggestion属性来获取拼单建议,
* 因为会过滤当前商品集合已满足的优惠条件,可能造成没有更多的规则可供建议,而bestMatch的是匹配完后基于剩下的商品来建议
*/
public static RuleValidateResult suggestion(List<Rule> rules, List<Item> items) {
List<RuleValidateResult> results = Strategy.suggestions(rules, items);
//缺张数优先级高还是差总价优先级高,咱讲道理,按每个商品的平均价来
int averagePrice = items.stream().map(Item::getPrice).reduce(0, Integer::sum) / items.size();
RuleValidateResult best = null;
int moreCount = 10000, moreSum = 100000000;
for (RuleValidateResult r :results) {
int[] needs = validateNeeds(r);
if(moreCount * averagePrice + moreSum > needs[0]*averagePrice + needs[1]){
moreCount = needs[0];
moreSum = needs[1];
best = r;
}
}
return best;
}
/*
* @Returns int[0] = count,int[1] = sum;
*/
private static int[] validateNeeds(RuleValidateResult result) {
int[] values = new int[2];
List<RuleValidateResult> clauses = result.getClauseResults();
if(clauses == null || clauses.size() == 0){
if(result.getRule() instanceof SimplexRule){
SimplexRule simplex = (SimplexRule) result.getRule(); | if(simplex.getPredict() == P.SUM){ | 1 | 2023-10-28 09:03:45+00:00 | 12k |
llllllxy/tiny-jdbc-boot-starter | src/main/java/org/tinycloud/jdbc/support/IObjectSupport.java | [
{
"identifier": "Criteria",
"path": "src/main/java/org/tinycloud/jdbc/criteria/Criteria.java",
"snippet": "public class Criteria extends AbstractCriteria {\n\n public <R> Criteria lt(String field, R value) {\n String condition = \" AND \" + field + \" < \" + \"?\";\n conditions.add(cond... | import org.springframework.util.CollectionUtils;
import org.tinycloud.jdbc.criteria.Criteria;
import org.tinycloud.jdbc.criteria.LambdaCriteria;
import org.tinycloud.jdbc.page.Page;
import java.util.Collection;
import java.util.List; | 7,929 | package org.tinycloud.jdbc.support;
/**
* <p>
* 对象操作接口,传入要执行的实例,操纵数据库,执行增、删、改、查操作,
* 前提是传入的实例中用@Table指定了数据库表,用@Column指定了表字段
* 对象操作只支持对单表的增、删、改、查。多表查询和存储过程等请使用sql操作接口或JdbcTemplate原生接口
* </p>
*
* @author liuxingyu01
* @since 2023-07-28-16:49
**/
public interface IObjectSupport<T, ID> {
/**
* 持久化插入给定的实例(默认忽略null值)
*
* @param entity 实例
* @return int 受影响的行数
*/
int insert(T entity);
/**
* 持久化插入给定的实例
*
* @param entity 实例
* @param ignoreNulls 是否忽略null值,true忽略,false不忽略
* @return int 受影响的行数
*/
int insert(T entity, boolean ignoreNulls);
/**
* 持久化插入给定的实例,并且返回自增主键
*
* @param entity 实例
* @return Integer 返回主键
*/
Long insertReturnAutoIncrement(T entity);
/**
* 持久化更新给定的实例(默认忽略null值),根据主键值更新
*
* @param entity 实例
* @return int 受影响的行数
*/
int updateById(T entity);
/**
* 持久化更新给定的实例,根据主键值更新
*
* @param entity 实例
* @param ignoreNulls 是否忽略null值,true忽略,false不忽略
* @return int 受影响的行数
*/
int updateById(T entity, boolean ignoreNulls);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param criteria 条件构造器
* @return int 受影响的行数
*/
int update(T entity, boolean ignoreNulls, Criteria criteria);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param lambdaCriteria 条件构造器(lambda版)
* @return int 受影响的行数
*/
int update(T entity, boolean ignoreNulls, LambdaCriteria lambdaCriteria);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param criteria 条件构造器
* @return int 受影响的行数
*/
int update(T entity, Criteria criteria);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param lambdaCriteria 条件构造器(lambda版)
* @return int 受影响的行数
*/
int update(T entity, LambdaCriteria lambdaCriteria);
/**
* 持久化删除给定的实例
*
* @param entity 实例
* @return int 受影响的行数
*/
int delete(T entity);
/**
* 持久化删除给定的实例
*
* @param criteria 条件构造器
* @return int 受影响的行数
*/
int delete(Criteria criteria);
/**
* 持久化删除给定的实例
*
* @param criteria 条件构造器(lambda版)
* @return int 受影响的行数
*/
int delete(LambdaCriteria criteria);
/**
* 根据ID进行删除
*
* @param id 主键id
* @return T 对象
*/
int deleteById(ID id);
/**
* 根据ID列表进行批量删除
*
* @param ids 主键id列表
* @return T 对象
*/
int deleteByIds(List<ID> ids);
/**
* 批量持久化更新给定的实例
*
* @param collection 实例集合
* @return 一个数组,其中包含受批处理中每个更新影响的行数
*/
int[] batchUpdate(Collection<T> collection);
/**
* 批量持久化插入给定的实例
*
* @param collection 实例集合
* @return 一个数组,其中包含受批处理中每个更新影响的行数
*/
int[] batchInsert(Collection<T> collection);
/**
* 批量持久化删除给定的实例
*
* @param collection 实例集合
* @return 一个数组,其中包含受批处理中每个更新影响的行数
*/
int[] batchDelete(Collection<T> collection);
/**
* 查询给定的id,返回一个实例
*
* @param id 主键id
* @return T 对象
*/
T selectById(ID id);
/**
* 根据ID列表进行批量查询
*
* @param ids 主键id列表
* @return List<T> 实例列表
*/
List<T> selectByIds(List<ID> ids);
/**
* 查询给定的实例,返回实例列表
*
* @param entity 实例
* @return List<T> 实例列表
*/
List<T> select(T entity);
/**
* 查询给定的实例,返回实例列表
*
* @param criteria 条件构造器
* @return List<T> 实例列表
*/
List<T> select(Criteria criteria);
/**
* 查询给定的实例,返回实例列表
*
* @param lambdaCriteria 条件构造器(lambda版)
* @return List<T> 实例列表
*/
List<T> select(LambdaCriteria lambdaCriteria);
/**
* 分页查询给定的实例,返回实例列表
*
* @param entity 实例
* @param page 分页参数
* @return List<T> 实例列表
*/ | package org.tinycloud.jdbc.support;
/**
* <p>
* 对象操作接口,传入要执行的实例,操纵数据库,执行增、删、改、查操作,
* 前提是传入的实例中用@Table指定了数据库表,用@Column指定了表字段
* 对象操作只支持对单表的增、删、改、查。多表查询和存储过程等请使用sql操作接口或JdbcTemplate原生接口
* </p>
*
* @author liuxingyu01
* @since 2023-07-28-16:49
**/
public interface IObjectSupport<T, ID> {
/**
* 持久化插入给定的实例(默认忽略null值)
*
* @param entity 实例
* @return int 受影响的行数
*/
int insert(T entity);
/**
* 持久化插入给定的实例
*
* @param entity 实例
* @param ignoreNulls 是否忽略null值,true忽略,false不忽略
* @return int 受影响的行数
*/
int insert(T entity, boolean ignoreNulls);
/**
* 持久化插入给定的实例,并且返回自增主键
*
* @param entity 实例
* @return Integer 返回主键
*/
Long insertReturnAutoIncrement(T entity);
/**
* 持久化更新给定的实例(默认忽略null值),根据主键值更新
*
* @param entity 实例
* @return int 受影响的行数
*/
int updateById(T entity);
/**
* 持久化更新给定的实例,根据主键值更新
*
* @param entity 实例
* @param ignoreNulls 是否忽略null值,true忽略,false不忽略
* @return int 受影响的行数
*/
int updateById(T entity, boolean ignoreNulls);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param criteria 条件构造器
* @return int 受影响的行数
*/
int update(T entity, boolean ignoreNulls, Criteria criteria);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param lambdaCriteria 条件构造器(lambda版)
* @return int 受影响的行数
*/
int update(T entity, boolean ignoreNulls, LambdaCriteria lambdaCriteria);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param criteria 条件构造器
* @return int 受影响的行数
*/
int update(T entity, Criteria criteria);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param lambdaCriteria 条件构造器(lambda版)
* @return int 受影响的行数
*/
int update(T entity, LambdaCriteria lambdaCriteria);
/**
* 持久化删除给定的实例
*
* @param entity 实例
* @return int 受影响的行数
*/
int delete(T entity);
/**
* 持久化删除给定的实例
*
* @param criteria 条件构造器
* @return int 受影响的行数
*/
int delete(Criteria criteria);
/**
* 持久化删除给定的实例
*
* @param criteria 条件构造器(lambda版)
* @return int 受影响的行数
*/
int delete(LambdaCriteria criteria);
/**
* 根据ID进行删除
*
* @param id 主键id
* @return T 对象
*/
int deleteById(ID id);
/**
* 根据ID列表进行批量删除
*
* @param ids 主键id列表
* @return T 对象
*/
int deleteByIds(List<ID> ids);
/**
* 批量持久化更新给定的实例
*
* @param collection 实例集合
* @return 一个数组,其中包含受批处理中每个更新影响的行数
*/
int[] batchUpdate(Collection<T> collection);
/**
* 批量持久化插入给定的实例
*
* @param collection 实例集合
* @return 一个数组,其中包含受批处理中每个更新影响的行数
*/
int[] batchInsert(Collection<T> collection);
/**
* 批量持久化删除给定的实例
*
* @param collection 实例集合
* @return 一个数组,其中包含受批处理中每个更新影响的行数
*/
int[] batchDelete(Collection<T> collection);
/**
* 查询给定的id,返回一个实例
*
* @param id 主键id
* @return T 对象
*/
T selectById(ID id);
/**
* 根据ID列表进行批量查询
*
* @param ids 主键id列表
* @return List<T> 实例列表
*/
List<T> selectByIds(List<ID> ids);
/**
* 查询给定的实例,返回实例列表
*
* @param entity 实例
* @return List<T> 实例列表
*/
List<T> select(T entity);
/**
* 查询给定的实例,返回实例列表
*
* @param criteria 条件构造器
* @return List<T> 实例列表
*/
List<T> select(Criteria criteria);
/**
* 查询给定的实例,返回实例列表
*
* @param lambdaCriteria 条件构造器(lambda版)
* @return List<T> 实例列表
*/
List<T> select(LambdaCriteria lambdaCriteria);
/**
* 分页查询给定的实例,返回实例列表
*
* @param entity 实例
* @param page 分页参数
* @return List<T> 实例列表
*/ | Page<T> paginate(T entity, Page<T> page); | 2 | 2023-10-25 14:44:59+00:00 | 12k |
ansforge/SAMU-Hub-Modeles | src/main/java/com/hubsante/model/health/Location.java | [
{
"identifier": "Access",
"path": "src/main/java/com/hubsante/model/health/Access.java",
"snippet": "@JsonPropertyOrder(\n {Access.JSON_PROPERTY_FLOOR, Access.JSON_PROPERTY_ROOM_NUMBER,\n Access.JSON_PROPERTY_INTERPHONE, Access.JSON_PROPERTY_ACCESS_CODE,\n Access.JSON_PROPERTY_ELEVATOR, Acces... | import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.dataformat.xml.annotation.*;
import com.hubsante.model.health.Access;
import com.hubsante.model.health.City;
import com.hubsante.model.health.DetailedAddress;
import com.hubsante.model.health.ExternalInfo;
import com.hubsante.model.health.Geometry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; | 7,840 | /**
* Copyright © 2023-2024 Agence du Numerique en Sante (ANS)
*
* 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.
*/
/*
*
*
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator
* (https://openapi-generator.tech). https://openapi-generator.tech Do not edit
* the class manually.
*/
package com.hubsante.model.health;
/**
* Location
*/
@JsonPropertyOrder(
{Location.JSON_PROPERTY_LOC_I_D, Location.JSON_PROPERTY_LOC_LABEL,
Location.JSON_PROPERTY_NAME, Location.JSON_PROPERTY_DETAILED_ADDRESS,
Location.JSON_PROPERTY_CITY, Location.JSON_PROPERTY_ACCESS,
Location.JSON_PROPERTY_GEOMETRY, Location.JSON_PROPERTY_EXTERNAL_INFO,
Location.JSON_PROPERTY_COUNTRY, Location.JSON_PROPERTY_FREETEXT})
@JsonTypeName("location")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Location {
public static final String JSON_PROPERTY_LOC_I_D = "locID";
private String locID;
public static final String JSON_PROPERTY_LOC_LABEL = "locLabel";
private String locLabel;
public static final String JSON_PROPERTY_NAME = "name";
private String name;
public static final String JSON_PROPERTY_DETAILED_ADDRESS = "detailedAddress";
private DetailedAddress detailedAddress;
public static final String JSON_PROPERTY_CITY = "city";
private City city;
public static final String JSON_PROPERTY_ACCESS = "access";
private Access access;
public static final String JSON_PROPERTY_GEOMETRY = "geometry";
private Geometry geometry;
public static final String JSON_PROPERTY_EXTERNAL_INFO = "externalInfo"; | /**
* Copyright © 2023-2024 Agence du Numerique en Sante (ANS)
*
* 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.
*/
/*
*
*
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator
* (https://openapi-generator.tech). https://openapi-generator.tech Do not edit
* the class manually.
*/
package com.hubsante.model.health;
/**
* Location
*/
@JsonPropertyOrder(
{Location.JSON_PROPERTY_LOC_I_D, Location.JSON_PROPERTY_LOC_LABEL,
Location.JSON_PROPERTY_NAME, Location.JSON_PROPERTY_DETAILED_ADDRESS,
Location.JSON_PROPERTY_CITY, Location.JSON_PROPERTY_ACCESS,
Location.JSON_PROPERTY_GEOMETRY, Location.JSON_PROPERTY_EXTERNAL_INFO,
Location.JSON_PROPERTY_COUNTRY, Location.JSON_PROPERTY_FREETEXT})
@JsonTypeName("location")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Location {
public static final String JSON_PROPERTY_LOC_I_D = "locID";
private String locID;
public static final String JSON_PROPERTY_LOC_LABEL = "locLabel";
private String locLabel;
public static final String JSON_PROPERTY_NAME = "name";
private String name;
public static final String JSON_PROPERTY_DETAILED_ADDRESS = "detailedAddress";
private DetailedAddress detailedAddress;
public static final String JSON_PROPERTY_CITY = "city";
private City city;
public static final String JSON_PROPERTY_ACCESS = "access";
private Access access;
public static final String JSON_PROPERTY_GEOMETRY = "geometry";
private Geometry geometry;
public static final String JSON_PROPERTY_EXTERNAL_INFO = "externalInfo"; | private List<ExternalInfo> externalInfo; | 3 | 2023-10-25 14:24:31+00:00 | 12k |
yaroslav318/shop-telegram-bot | telegram-bot/src/main/java/ua/ivanzaitsev/bot/handlers/commands/CartCommandHandler.java | [
{
"identifier": "CommandHandler",
"path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/handlers/CommandHandler.java",
"snippet": "public interface CommandHandler extends Handler {\n\n void executeCommand(AbsSender absSender, Update update, Long chatId) throws TelegramApiException;\n\n}"
},
{
... | import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import ua.ivanzaitsev.bot.handlers.CommandHandler;
import ua.ivanzaitsev.bot.handlers.UpdateHandler;
import ua.ivanzaitsev.bot.handlers.commands.registries.CommandHandlerRegistry;
import ua.ivanzaitsev.bot.models.domain.Button;
import ua.ivanzaitsev.bot.models.domain.CartItem;
import ua.ivanzaitsev.bot.models.domain.ClientOrder;
import ua.ivanzaitsev.bot.models.domain.Command;
import ua.ivanzaitsev.bot.models.domain.MessagePlaceholder;
import ua.ivanzaitsev.bot.models.entities.Client;
import ua.ivanzaitsev.bot.models.entities.Message;
import ua.ivanzaitsev.bot.models.entities.Product;
import ua.ivanzaitsev.bot.repositories.CartRepository;
import ua.ivanzaitsev.bot.repositories.ClientCommandStateRepository;
import ua.ivanzaitsev.bot.repositories.ClientOrderStateRepository;
import ua.ivanzaitsev.bot.repositories.ClientRepository;
import ua.ivanzaitsev.bot.services.MessageService; | 7,218 | if (cartItem == null || cartItem.getQuantity() >= MAX_QUANTITY_PER_PRODUCT) {
return;
}
cartItem.setQuantity(cartItem.getQuantity() + 1);
cartRepository.updateCartItem(chatId, cartItem);
editCartMessage(absSender, chatId, messageId, cartItems, currentCartPage);
}
private void doPreviousProduct(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException {
List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId);
int currentCartPage = cartRepository.findPageNumberByChatId(chatId);
if (cartItems.isEmpty()) {
editEmptyCartMessage(absSender, chatId, messageId);
return;
}
if (cartItems.size() == 1) {
return;
}
if (currentCartPage <= 0) {
currentCartPage = cartItems.size() - 1;
} else {
currentCartPage -= 1;
}
cartRepository.updatePageNumberByChatId(chatId, currentCartPage);
editCartMessage(absSender, chatId, messageId, cartItems, currentCartPage);
}
private void doNextProduct(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException {
List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId);
int currentCartPage = cartRepository.findPageNumberByChatId(chatId);
if (cartItems.isEmpty()) {
editEmptyCartMessage(absSender, chatId, messageId);
return;
}
if (cartItems.size() == 1) {
return;
}
if (currentCartPage >= cartItems.size() - 1) {
currentCartPage = 0;
} else {
currentCartPage += 1;
}
cartRepository.updatePageNumberByChatId(chatId, currentCartPage);
editCartMessage(absSender, chatId, messageId, cartItems, currentCartPage);
}
private void sendEmptyCartMessage(AbsSender absSender, Long chatId) throws TelegramApiException {
SendMessage message = SendMessage.builder()
.chatId(chatId)
.text("Cart is empty.")
.build();
absSender.execute(message);
}
private void editEmptyCartMessage(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException {
EditMessageText message = EditMessageText.builder()
.chatId(chatId)
.messageId(messageId)
.text("Cart is empty.")
.build();
absSender.execute(message);
}
private void editClearedCartMessage(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException {
EditMessageText message = EditMessageText.builder()
.chatId(chatId)
.messageId(messageId)
.text("Cart cleared.")
.build();
absSender.execute(message);
}
private void sendCartMessage(AbsSender absSender, Long chatId, List<CartItem> cartItems, int currentCartPage)
throws TelegramApiException {
SendMessage message = SendMessage.builder()
.chatId(chatId)
.text(createProductText(cartItems.get(currentCartPage)))
.replyMarkup(createCartKeyboard(cartItems, currentCartPage))
.parseMode("HTML")
.build();
absSender.execute(message);
}
private void editCartMessage(AbsSender absSender, Long chatId, Integer messageId, List<CartItem> cartItems,
int currentCartPage) throws TelegramApiException {
EditMessageText message = EditMessageText.builder()
.chatId(chatId)
.messageId(messageId)
.text(createProductText(cartItems.get(currentCartPage)))
.replyMarkup(createCartKeyboard(cartItems, currentCartPage))
.parseMode("HTML")
.build();
absSender.execute(message);
}
private String createProductText(CartItem cartItem) {
Message message = messageService.findByName("CART_MESSAGE");
if (cartItem != null) {
Product product = cartItem.getProduct();
message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_NAME%", product.getName()));
message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_DESCRIPTION%", product.getDescription()));
message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_PRICE%", product.getPrice()));
message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_QUANTITY%", cartItem.getQuantity()));
message.applyPlaceholder(
MessagePlaceholder.of("%PRODUCT_TOTAL_PRICE%", product.getPrice() * cartItem.getQuantity()));
}
return message.buildText();
}
private InlineKeyboardMarkup createCartKeyboard(List<CartItem> cartItems, int currentCartPage) { | package ua.ivanzaitsev.bot.handlers.commands;
public class CartCommandHandler implements CommandHandler, UpdateHandler {
private static final int MAX_QUANTITY_PER_PRODUCT = 50;
private static final String PRODUCT_QUANTITY_CALLBACK = "cart=product-quantity";
private static final String CURRENT_PAGE_CALLBACK = "cart=current-page";
private static final String DELETE_PRODUCT_CALLBACK = "cart=delete-product";
private static final String MINUS_PRODUCT_CALLBACK = "cart=minus-product";
private static final String PLUS_PRODUCT_CALLBACK = "cart=plus-product";
private static final String PREVIOUS_PRODUCT_CALLBACK = "cart=previous-product";
private static final String NEXT_PRODUCT_CALLBACK = "cart=next-product";
private static final String PROCESS_ORDER_CALLBACK = "cart=process-order";
private static final Set<String> CALLBACKS = Set.of(DELETE_PRODUCT_CALLBACK, MINUS_PRODUCT_CALLBACK,
PLUS_PRODUCT_CALLBACK, PREVIOUS_PRODUCT_CALLBACK, NEXT_PRODUCT_CALLBACK, PROCESS_ORDER_CALLBACK);
private final CommandHandlerRegistry commandHandlerRegistry;
private final ClientCommandStateRepository clientCommandStateRepository;
private final ClientOrderStateRepository clientOrderStateRepository;
private final CartRepository cartRepository;
private final ClientRepository clientRepository;
private final MessageService messageService;
public CartCommandHandler(
CommandHandlerRegistry commandHandlerRegistry,
ClientCommandStateRepository clientCommandStateRepository,
ClientOrderStateRepository clientOrderStateRepository,
CartRepository cartRepository,
ClientRepository clientRepository,
MessageService messageService) {
this.commandHandlerRegistry = commandHandlerRegistry;
this.clientCommandStateRepository = clientCommandStateRepository;
this.clientOrderStateRepository = clientOrderStateRepository;
this.cartRepository = cartRepository;
this.clientRepository = clientRepository;
this.messageService = messageService;
}
@Override
public Command getCommand() {
return Command.CART;
}
@Override
public void executeCommand(AbsSender absSender, Update update, Long chatId) throws TelegramApiException {
handleCartMessageUpdate(absSender, chatId);
}
@Override
public boolean canHandleUpdate(Update update) {
return isCartMessageUpdate(update) || isCallbackQueryUpdate(update);
}
@Override
public void handleUpdate(AbsSender absSender, Update update) throws TelegramApiException {
if (isCartMessageUpdate(update)) {
handleCartMessageUpdate(absSender, update.getMessage().getChatId());
}
if (isCallbackQueryUpdate(update)) {
handleCallbackQueryUpdate(absSender, update);
}
}
private boolean isCartMessageUpdate(Update update) {
return update.hasMessage() &&
update.getMessage().hasText() &&
update.getMessage().getText().equals(Button.CART.getAlias());
}
private boolean isCallbackQueryUpdate(Update update) {
return update.hasCallbackQuery() && CALLBACKS.contains(update.getCallbackQuery().getData());
}
private void handleCartMessageUpdate(AbsSender absSender, Long chatId) throws TelegramApiException {
List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId);
cartRepository.updatePageNumberByChatId(chatId, 0);
if (cartItems.isEmpty()) {
sendEmptyCartMessage(absSender, chatId);
return;
}
sendCartMessage(absSender, chatId, cartItems, 0);
}
private void handleCallbackQueryUpdate(AbsSender absSender, Update update) throws TelegramApiException {
CallbackQuery callbackQuery = update.getCallbackQuery();
Long chatId = callbackQuery.getMessage().getChatId();
Integer messageId = callbackQuery.getMessage().getMessageId();
String data = callbackQuery.getData();
if (DELETE_PRODUCT_CALLBACK.equals(data)) {
doDeleteProduct(absSender, chatId, messageId);
}
if (MINUS_PRODUCT_CALLBACK.equals(data)) {
doMinusProduct(absSender, chatId, messageId);
}
if (PLUS_PRODUCT_CALLBACK.equals(data)) {
doPlusProduct(absSender, chatId, messageId);
}
if (PREVIOUS_PRODUCT_CALLBACK.equals(data)) {
doPreviousProduct(absSender, chatId, messageId);
}
if (NEXT_PRODUCT_CALLBACK.equals(data)) {
doNextProduct(absSender, chatId, messageId);
}
if (PROCESS_ORDER_CALLBACK.equals(data)) {
doProcessOrder(absSender, update, chatId, messageId);
}
}
private void doDeleteProduct(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException {
List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId);
int currentCartPage = cartRepository.findPageNumberByChatId(chatId);
if (!cartItems.isEmpty()) {
CartItem cartItem = cartItems.get(currentCartPage);
if (cartItem != null) {
cartItems.remove(cartItem);
cartRepository.deleteCartItem(chatId, cartItem.getId());
}
}
if (cartItems.isEmpty()) {
editClearedCartMessage(absSender, chatId, messageId);
return;
}
if (cartItems.size() == currentCartPage) {
currentCartPage -= 1;
cartRepository.updatePageNumberByChatId(chatId, currentCartPage);
}
editCartMessage(absSender, chatId, messageId, cartItems, currentCartPage);
}
private void doMinusProduct(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException {
List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId);
int currentCartPage = cartRepository.findPageNumberByChatId(chatId);
if (cartItems.isEmpty()) {
editEmptyCartMessage(absSender, chatId, messageId);
return;
}
CartItem cartItem = cartItems.get(currentCartPage);
if (cartItem == null || cartItem.getQuantity() <= 1) {
return;
}
cartItem.setQuantity(cartItem.getQuantity() - 1);
cartRepository.updateCartItem(chatId, cartItem);
editCartMessage(absSender, chatId, messageId, cartItems, currentCartPage);
}
private void doPlusProduct(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException {
List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId);
int currentCartPage = cartRepository.findPageNumberByChatId(chatId);
if (cartItems.isEmpty()) {
editEmptyCartMessage(absSender, chatId, messageId);
return;
}
CartItem cartItem = cartItems.get(currentCartPage);
if (cartItem == null || cartItem.getQuantity() >= MAX_QUANTITY_PER_PRODUCT) {
return;
}
cartItem.setQuantity(cartItem.getQuantity() + 1);
cartRepository.updateCartItem(chatId, cartItem);
editCartMessage(absSender, chatId, messageId, cartItems, currentCartPage);
}
private void doPreviousProduct(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException {
List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId);
int currentCartPage = cartRepository.findPageNumberByChatId(chatId);
if (cartItems.isEmpty()) {
editEmptyCartMessage(absSender, chatId, messageId);
return;
}
if (cartItems.size() == 1) {
return;
}
if (currentCartPage <= 0) {
currentCartPage = cartItems.size() - 1;
} else {
currentCartPage -= 1;
}
cartRepository.updatePageNumberByChatId(chatId, currentCartPage);
editCartMessage(absSender, chatId, messageId, cartItems, currentCartPage);
}
private void doNextProduct(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException {
List<CartItem> cartItems = cartRepository.findAllCartItemsByChatId(chatId);
int currentCartPage = cartRepository.findPageNumberByChatId(chatId);
if (cartItems.isEmpty()) {
editEmptyCartMessage(absSender, chatId, messageId);
return;
}
if (cartItems.size() == 1) {
return;
}
if (currentCartPage >= cartItems.size() - 1) {
currentCartPage = 0;
} else {
currentCartPage += 1;
}
cartRepository.updatePageNumberByChatId(chatId, currentCartPage);
editCartMessage(absSender, chatId, messageId, cartItems, currentCartPage);
}
private void sendEmptyCartMessage(AbsSender absSender, Long chatId) throws TelegramApiException {
SendMessage message = SendMessage.builder()
.chatId(chatId)
.text("Cart is empty.")
.build();
absSender.execute(message);
}
private void editEmptyCartMessage(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException {
EditMessageText message = EditMessageText.builder()
.chatId(chatId)
.messageId(messageId)
.text("Cart is empty.")
.build();
absSender.execute(message);
}
private void editClearedCartMessage(AbsSender absSender, Long chatId, Integer messageId) throws TelegramApiException {
EditMessageText message = EditMessageText.builder()
.chatId(chatId)
.messageId(messageId)
.text("Cart cleared.")
.build();
absSender.execute(message);
}
private void sendCartMessage(AbsSender absSender, Long chatId, List<CartItem> cartItems, int currentCartPage)
throws TelegramApiException {
SendMessage message = SendMessage.builder()
.chatId(chatId)
.text(createProductText(cartItems.get(currentCartPage)))
.replyMarkup(createCartKeyboard(cartItems, currentCartPage))
.parseMode("HTML")
.build();
absSender.execute(message);
}
private void editCartMessage(AbsSender absSender, Long chatId, Integer messageId, List<CartItem> cartItems,
int currentCartPage) throws TelegramApiException {
EditMessageText message = EditMessageText.builder()
.chatId(chatId)
.messageId(messageId)
.text(createProductText(cartItems.get(currentCartPage)))
.replyMarkup(createCartKeyboard(cartItems, currentCartPage))
.parseMode("HTML")
.build();
absSender.execute(message);
}
private String createProductText(CartItem cartItem) {
Message message = messageService.findByName("CART_MESSAGE");
if (cartItem != null) {
Product product = cartItem.getProduct();
message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_NAME%", product.getName()));
message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_DESCRIPTION%", product.getDescription()));
message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_PRICE%", product.getPrice()));
message.applyPlaceholder(MessagePlaceholder.of("%PRODUCT_QUANTITY%", cartItem.getQuantity()));
message.applyPlaceholder(
MessagePlaceholder.of("%PRODUCT_TOTAL_PRICE%", product.getPrice() * cartItem.getQuantity()));
}
return message.buildText();
}
private InlineKeyboardMarkup createCartKeyboard(List<CartItem> cartItems, int currentCartPage) { | ClientOrder clientOrder = new ClientOrder(); | 5 | 2023-10-29 15:49:41+00:00 | 12k |
MikiP98/HumilityAFM | src/main/java/io/github/mikip98/HumilityAFM.java | [
{
"identifier": "ConfigJSON",
"path": "src/main/java/io/github/mikip98/config/ConfigJSON.java",
"snippet": "public class ConfigJSON {\n\n // Save the configuration to a JSON file in the Minecraft configuration folder\n public static void saveConfigToFile() {\n Gson gson = new GsonBuilder().... | import io.github.mikip98.config.ConfigJSON;
import io.github.mikip98.config.ModConfig;
import io.github.mikip98.content.blockentities.LEDBlockEntity;
import io.github.mikip98.content.blockentities.cabinetBlock.IlluminatedCabinetBlockEntity;
import io.github.mikip98.content.blocks.JustHorizontalFacingBlock;
import io.github.mikip98.content.blocks.leds.LEDBlock;
import io.github.mikip98.content.blocks.stairs.InnerStairs;
import io.github.mikip98.content.blocks.stairs.OuterStairs;
import io.github.mikip98.content.blocks.cabinet.CabinetBlock;
import io.github.mikip98.content.blocks.cabinet.IlluminatedCabinetBlock;
import io.github.mikip98.helpers.*;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.item.v1.FabricItemSettings;
import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.block.Block;
import net.minecraft.block.entity.BlockEntityType;
import net.minecraft.item.*;
import net.minecraft.registry.Registries;
import net.minecraft.registry.Registry;
import net.minecraft.sound.BlockSoundGroup;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.github.mikip98.content.blockentities.cabinetBlock.CabinetBlockEntity;
import java.io.File;
import java.nio.file.Path;
import static net.fabricmc.loader.api.FabricLoader.getInstance; | 9,289 | package io.github.mikip98;
public class HumilityAFM implements ModInitializer {
// This logger is used to write text to the console and the log file.
// It is considered best practice to use your mod id as the logger's name.
// That way, it's clear which mod wrote info, warnings, and errors.
public static final String MOD_ID = "humility-afm";
public static final String MOD_NAME = "Humility AFM";
public static final String MOD_CAMEL = "HumilityAFM";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_CAMEL);
//Cabinet block
private static final float CabinetBlockStrength = 2.0f;
private static final FabricBlockSettings CabinetBlockSettings = FabricBlockSettings.create().strength(CabinetBlockStrength).requiresTool().nonOpaque();
public static final CabinetBlock CABINET_BLOCK = new CabinetBlock(CabinetBlockSettings);
public static final Item CABINET_BLOCK_ITEM = new BlockItem(CABINET_BLOCK, new FabricItemSettings());
private static final FabricBlockSettings IlluminatedCabinetBlockSettings = CabinetBlockSettings.luminance(2);
public static final IlluminatedCabinetBlock ILLUMINATED_CABINET_BLOCK = new IlluminatedCabinetBlock(IlluminatedCabinetBlockSettings);
//Cabinet block entity
public static BlockEntityType<CabinetBlockEntity> CABINET_BLOCK_ENTITY;
public static BlockEntityType<IlluminatedCabinetBlockEntity> ILLUMINATED_CABINET_BLOCK_ENTITY;
// LED block entity | package io.github.mikip98;
public class HumilityAFM implements ModInitializer {
// This logger is used to write text to the console and the log file.
// It is considered best practice to use your mod id as the logger's name.
// That way, it's clear which mod wrote info, warnings, and errors.
public static final String MOD_ID = "humility-afm";
public static final String MOD_NAME = "Humility AFM";
public static final String MOD_CAMEL = "HumilityAFM";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_CAMEL);
//Cabinet block
private static final float CabinetBlockStrength = 2.0f;
private static final FabricBlockSettings CabinetBlockSettings = FabricBlockSettings.create().strength(CabinetBlockStrength).requiresTool().nonOpaque();
public static final CabinetBlock CABINET_BLOCK = new CabinetBlock(CabinetBlockSettings);
public static final Item CABINET_BLOCK_ITEM = new BlockItem(CABINET_BLOCK, new FabricItemSettings());
private static final FabricBlockSettings IlluminatedCabinetBlockSettings = CabinetBlockSettings.luminance(2);
public static final IlluminatedCabinetBlock ILLUMINATED_CABINET_BLOCK = new IlluminatedCabinetBlock(IlluminatedCabinetBlockSettings);
//Cabinet block entity
public static BlockEntityType<CabinetBlockEntity> CABINET_BLOCK_ENTITY;
public static BlockEntityType<IlluminatedCabinetBlockEntity> ILLUMINATED_CABINET_BLOCK_ENTITY;
// LED block entity | public static BlockEntityType<LEDBlockEntity> LED_BLOCK_ENTITY; | 2 | 2023-10-30 12:11:22+00:00 | 12k |
HeitorLouzeiro/gerenciador-disciplinas-java | core/src/main/java/com/project/Menu/MenuItens/Cadastrar.java | [
{
"identifier": "Aluno",
"path": "core/src/main/java/com/project/Classes/Aluno.java",
"snippet": "public class Aluno extends Usuario {\n /**\n * Construtor padrão da classe Aluno.\n \n */\n public Aluno() {\n \n }\n\n // A classe Aluno herda os atributos e métodos da class... | import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Scanner;
import com.project.Classes.Aluno;
import com.project.Classes.Data;
import com.project.Classes.Disciplinas;
import com.project.Classes.Frequencia;
import com.project.Classes.Notas;
import com.project.Dao.DisciplinasDAO;
import com.project.Dao.FrequenciaDAO;
import com.project.Dao.NotasDAO;
import com.project.Dao.SecretarioDAO;
import com.project.Menu.MenuItens.Listar.Space; | 9,179 | package com.project.Menu.MenuItens;
/**
* Classe que representa o menu de cadastro do sistema.
*
* @Author @HeitorLouzeiro
*
*/
public class Cadastrar {
/**
* Realiza o cadastro de alunos no sistema.
*
* @throws IOException Se ocorrer um erro de I/O durante a execução.
*/
public void cadastrarAluno() throws IOException {
SecretarioDAO secretarioDAO = new SecretarioDAO();
Aluno aluno = new Aluno();
Data dataNascimento = new Data();
Data dataEntrada = new Data();
Scanner scanner = new Scanner(System.in);
int opcao = -1;
do {
try {
// Implemente a lógica para verificar algo
System.out.println("Cadastro de Aluno...");
System.out.print("Digite o nome do aluno: ");
aluno.setNome(scanner.nextLine());
System.out.print("Digite o CPF do aluno: ");
aluno.setCpf(scanner.nextLine());
System.out.print("Coloque as datas no formato dd-mm-aaaa\n");
System.out.print("Digite a data de nascimento do aluno: ");
dataNascimento.setData(scanner.nextLine());
aluno.setDataNascimento(dataNascimento);
System.out.print("Digite a data de entrada do aluno: ");
dataEntrada.setData(scanner.nextLine());
aluno.setDataEntrada(dataEntrada);
aluno.setSenha(aluno.getCpf());
secretarioDAO.InsertAluno(aluno);
System.out.println(Space.space);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
System.out.println("Deseja cadastrar outro aluno? 1 - Sim | 0 - Não");
opcao = scanner.nextInt();
scanner.nextLine();
} while (opcao != 0);
}
/**
* Realiza o cadastro de frequência para uma disciplina específica.
*
* @param codDisciplina O código da disciplina para a qual a frequência será cadastrada.
* @throws IOException Se ocorrer um erro de I/O durante a execução.
*/
public void cadastrarFrequencia(int codDisciplina) throws IOException {
Frequencia frequencia = new Frequencia();
FrequenciaDAO frequenciaDAO = new FrequenciaDAO();
Listar listar = new Listar();
Data data = new Data();
Scanner scanner = new Scanner(System.in);
System.out.println("Cadastro de frequencia do aluno...");
System.out.print("Para continuar o cadastro da frequencia selecione a data da frequencia.\n");
System.out.print("Deseja colocar a data de hoje? 1 - Sim | 0 - Não: ");
int opcao = scanner.nextInt();
if (opcao == 1) {
frequencia.setData(data.getDataAtual());
} else {
System.out.print("Coloque as datas no formato dd-mm-aaaa\n");
System.out.print("Digite a data da aula: ");
frequencia.setData(scanner.next());
}
List<Integer> codigosAlunos = listar.listarAlunosDisciplina(codDisciplina);
try {
// Mostra as disciplinas do professor
frequencia.setCodDisciplina(codDisciplina);
for (Integer codigo : codigosAlunos) {
System.out.println("Código do aluno: " + codigo);
frequencia.setCodUsuario(codigo);
System.out.print("Digite a presença do aluno: 1 - Presente | 0 - Ausente: ");
frequencia.setPresenca(scanner.nextInt());
frequenciaDAO.inserirFrequenciaAluno(frequencia);
}
System.out.println(Space.space);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Realiza o cadastro de notas para uma disciplina específica.
*
* @param codDisciplina O código da disciplina para a qual as notas serão cadastradas.
* @throws IOException Se ocorrer um erro de I/O durante a execução.
*/
public void cadastrarNotas(int codDisciplina) throws IOException {
Notas notas = new Notas(); | package com.project.Menu.MenuItens;
/**
* Classe que representa o menu de cadastro do sistema.
*
* @Author @HeitorLouzeiro
*
*/
public class Cadastrar {
/**
* Realiza o cadastro de alunos no sistema.
*
* @throws IOException Se ocorrer um erro de I/O durante a execução.
*/
public void cadastrarAluno() throws IOException {
SecretarioDAO secretarioDAO = new SecretarioDAO();
Aluno aluno = new Aluno();
Data dataNascimento = new Data();
Data dataEntrada = new Data();
Scanner scanner = new Scanner(System.in);
int opcao = -1;
do {
try {
// Implemente a lógica para verificar algo
System.out.println("Cadastro de Aluno...");
System.out.print("Digite o nome do aluno: ");
aluno.setNome(scanner.nextLine());
System.out.print("Digite o CPF do aluno: ");
aluno.setCpf(scanner.nextLine());
System.out.print("Coloque as datas no formato dd-mm-aaaa\n");
System.out.print("Digite a data de nascimento do aluno: ");
dataNascimento.setData(scanner.nextLine());
aluno.setDataNascimento(dataNascimento);
System.out.print("Digite a data de entrada do aluno: ");
dataEntrada.setData(scanner.nextLine());
aluno.setDataEntrada(dataEntrada);
aluno.setSenha(aluno.getCpf());
secretarioDAO.InsertAluno(aluno);
System.out.println(Space.space);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
System.out.println("Deseja cadastrar outro aluno? 1 - Sim | 0 - Não");
opcao = scanner.nextInt();
scanner.nextLine();
} while (opcao != 0);
}
/**
* Realiza o cadastro de frequência para uma disciplina específica.
*
* @param codDisciplina O código da disciplina para a qual a frequência será cadastrada.
* @throws IOException Se ocorrer um erro de I/O durante a execução.
*/
public void cadastrarFrequencia(int codDisciplina) throws IOException {
Frequencia frequencia = new Frequencia();
FrequenciaDAO frequenciaDAO = new FrequenciaDAO();
Listar listar = new Listar();
Data data = new Data();
Scanner scanner = new Scanner(System.in);
System.out.println("Cadastro de frequencia do aluno...");
System.out.print("Para continuar o cadastro da frequencia selecione a data da frequencia.\n");
System.out.print("Deseja colocar a data de hoje? 1 - Sim | 0 - Não: ");
int opcao = scanner.nextInt();
if (opcao == 1) {
frequencia.setData(data.getDataAtual());
} else {
System.out.print("Coloque as datas no formato dd-mm-aaaa\n");
System.out.print("Digite a data da aula: ");
frequencia.setData(scanner.next());
}
List<Integer> codigosAlunos = listar.listarAlunosDisciplina(codDisciplina);
try {
// Mostra as disciplinas do professor
frequencia.setCodDisciplina(codDisciplina);
for (Integer codigo : codigosAlunos) {
System.out.println("Código do aluno: " + codigo);
frequencia.setCodUsuario(codigo);
System.out.print("Digite a presença do aluno: 1 - Presente | 0 - Ausente: ");
frequencia.setPresenca(scanner.nextInt());
frequenciaDAO.inserirFrequenciaAluno(frequencia);
}
System.out.println(Space.space);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Realiza o cadastro de notas para uma disciplina específica.
*
* @param codDisciplina O código da disciplina para a qual as notas serão cadastradas.
* @throws IOException Se ocorrer um erro de I/O durante a execução.
*/
public void cadastrarNotas(int codDisciplina) throws IOException {
Notas notas = new Notas(); | NotasDAO notasDAO = new NotasDAO(); | 7 | 2023-10-30 18:29:39+00:00 | 12k |
llllllxy/tiny-security-boot-starter | src/main/java/org/tinycloud/security/AuthAutoConfiguration.java | [
{
"identifier": "AuthenticeInterceptor",
"path": "src/main/java/org/tinycloud/security/interceptor/AuthenticeInterceptor.java",
"snippet": "public class AuthenticeInterceptor extends HandlerInterceptorAdapter {\n\n /**\n * 存储会话的接口\n */\n private AuthProvider authProvider;\n\n public Aut... | import org.tinycloud.security.interceptor.AuthenticeInterceptor;
import org.tinycloud.security.interceptor.PermissionInterceptor;
import org.tinycloud.security.interfaces.PermissionInfoInterface;
import org.tinycloud.security.provider.AuthProvider;
import org.tinycloud.security.provider.JdbcAuthProvider;
import org.tinycloud.security.provider.RedisAuthProvider;
import org.tinycloud.security.provider.SingleAuthProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate; | 9,038 | package org.tinycloud.security;
/**
* <p>
* tiny-security 自动配置类
* </p>
*
* @author liuxingyu01
* @since 2022-12-13 11:45
**/
@Configuration
@EnableConfigurationProperties(AuthProperties.class)
public class AuthAutoConfiguration {
final static Logger logger = LoggerFactory.getLogger(AuthAutoConfiguration.class);
@Autowired
private AuthProperties authProperties;
/**
* 注入redisAuthProvider
*/
@ConditionalOnMissingBean(AuthProvider.class)
@ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "redis")
@Bean
public AuthProvider redisAuthProvider(StringRedisTemplate stringRedisTemplate) {
if (stringRedisTemplate == null) {
logger.error("AuthAutoConfiguration: Bean StringRedisTemplate is null!");
return null;
}
logger.info("RedisAuthProvider is running!");
return new RedisAuthProvider(stringRedisTemplate, authProperties);
}
/**
* 注入jdbcAuthProvider
*/
@ConditionalOnMissingBean(AuthProvider.class)
@ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "jdbc")
@Bean
public AuthProvider jdbcAuthProvider(JdbcTemplate jdbcTemplate) {
if (jdbcTemplate == null) {
logger.error("AuthAutoConfiguration: Bean JdbcTemplate is null!");
return null;
}
logger.info("JdbcAuthProvider is running!");
return new JdbcAuthProvider(jdbcTemplate, authProperties);
}
/**
* 注入singleAuthProvider
*/
@ConditionalOnMissingBean(AuthProvider.class)
@ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "single", matchIfMissing = true)
@Bean
public AuthProvider singleAuthProvider() {
logger.info("SingleAuthProvider is running!"); | package org.tinycloud.security;
/**
* <p>
* tiny-security 自动配置类
* </p>
*
* @author liuxingyu01
* @since 2022-12-13 11:45
**/
@Configuration
@EnableConfigurationProperties(AuthProperties.class)
public class AuthAutoConfiguration {
final static Logger logger = LoggerFactory.getLogger(AuthAutoConfiguration.class);
@Autowired
private AuthProperties authProperties;
/**
* 注入redisAuthProvider
*/
@ConditionalOnMissingBean(AuthProvider.class)
@ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "redis")
@Bean
public AuthProvider redisAuthProvider(StringRedisTemplate stringRedisTemplate) {
if (stringRedisTemplate == null) {
logger.error("AuthAutoConfiguration: Bean StringRedisTemplate is null!");
return null;
}
logger.info("RedisAuthProvider is running!");
return new RedisAuthProvider(stringRedisTemplate, authProperties);
}
/**
* 注入jdbcAuthProvider
*/
@ConditionalOnMissingBean(AuthProvider.class)
@ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "jdbc")
@Bean
public AuthProvider jdbcAuthProvider(JdbcTemplate jdbcTemplate) {
if (jdbcTemplate == null) {
logger.error("AuthAutoConfiguration: Bean JdbcTemplate is null!");
return null;
}
logger.info("JdbcAuthProvider is running!");
return new JdbcAuthProvider(jdbcTemplate, authProperties);
}
/**
* 注入singleAuthProvider
*/
@ConditionalOnMissingBean(AuthProvider.class)
@ConditionalOnProperty(name = "tiny-security.store-type", havingValue = "single", matchIfMissing = true)
@Bean
public AuthProvider singleAuthProvider() {
logger.info("SingleAuthProvider is running!"); | return new SingleAuthProvider(authProperties); | 6 | 2023-10-26 08:13:08+00:00 | 12k |
0-Gixty-0/Grupp-11-OOPP | sailinggame/src/test/java/modeltest/modelinitialization/AICommanderTest.java | [
{
"identifier": "EntityDirector",
"path": "sailinggame/src/main/java/com/group11/model/builders/EntityDirector.java",
"snippet": "public class EntityDirector {\n private IEntityBuilder builder;\n\n public EntityDirector(IEntityBuilder builder) {\n this.builder = builder;\n }\n\n /**\n... | import com.group11.model.builders.EntityDirector;
import com.group11.model.builders.ShipBuilder;
import com.group11.model.gameentites.AEntity;
import com.group11.model.gameentites.CommandableEntity;
import com.group11.model.gameworld.ATile;
import com.group11.model.gameworld.LandTile;
import com.group11.model.gameworld.SeaTile;
import com.group11.model.modelinitialization.AICommander;
import com.group11.model.utility.UMovement;
import com.group11.model.utility.UViewTileMatrixDecoder;
import com.group11.model.utility.UEntityMatrixGenerator;
import org.junit.Before;
import org.junit.Test;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static junit.framework.TestCase.assertEquals; | 7,471 | package modeltest.modelinitialization;
public class AICommanderTest {
private List<List<Integer>> grid = new ArrayList<>();
private List<List<ATile>> terrainMatrix = new ArrayList<>();
private EntityDirector director = new EntityDirector(new ShipBuilder());
private List<AEntity> entities = new ArrayList<>();
private List<List<AEntity>> entityMatrix = UEntityMatrixGenerator.createEntityMatrix(5,5, entities);
private class TestAICommander extends AICommander {
public TestAICommander(List<List<AEntity>> entityMatrix, List<List<ATile>> terrainMatrix) {
super(entityMatrix);
super.innerRadius = 1;
}
}
@Before
public void beforePreconditions() {
this.grid.add(Arrays.asList(1,1,0,1,1));
this.grid.add(Arrays.asList(1,0,1,0,1));
this.grid.add(Arrays.asList(1,1,1,1,1));
this.grid.add(Arrays.asList(1,0,1,0,1));
this.grid.add(Arrays.asList(1,1,0,1,1));
ArrayList<ATile> tileRow = new ArrayList<>();
tileRow.add(new SeaTile(new Point(0,0)));
tileRow.add(new SeaTile(new Point(0,1)));
tileRow.add(new LandTile(new Point(0,2)));
tileRow.add(new SeaTile(new Point(0,3)));
tileRow.add(new SeaTile(new Point(0,4)));
this.terrainMatrix.add(tileRow);
tileRow = new ArrayList<>();
tileRow.add(new SeaTile(new Point(1,0)));
tileRow.add(new LandTile(new Point(1,1)));
tileRow.add(new SeaTile(new Point(1,2)));
tileRow.add(new LandTile(new Point(1,3)));
tileRow.add(new SeaTile(new Point(1,4)));
this.terrainMatrix.add(tileRow);
tileRow = new ArrayList<>();
tileRow.add(new SeaTile(new Point(2,0)));
tileRow.add(new SeaTile(new Point(2,1)));
tileRow.add(new SeaTile(new Point(2,2)));
tileRow.add(new SeaTile(new Point(2,3)));
tileRow.add(new SeaTile(new Point(2,4)));
this.terrainMatrix.add(tileRow);
tileRow = new ArrayList<>();
tileRow.add(new SeaTile(new Point(3,0)));
tileRow.add(new LandTile(new Point(3,1)));
tileRow.add(new SeaTile(new Point(3,2)));
tileRow.add(new LandTile(new Point(3,3)));
tileRow.add(new SeaTile(new Point(3,4)));
this.terrainMatrix.add(tileRow);
tileRow = new ArrayList<>();
tileRow.add(new SeaTile(new Point(0,0)));
tileRow.add(new SeaTile(new Point(0,1)));
tileRow.add(new LandTile(new Point(0,2)));
tileRow.add(new SeaTile(new Point(0,3)));
tileRow.add(new SeaTile(new Point(0,4)));
this.terrainMatrix.add(tileRow);
| package modeltest.modelinitialization;
public class AICommanderTest {
private List<List<Integer>> grid = new ArrayList<>();
private List<List<ATile>> terrainMatrix = new ArrayList<>();
private EntityDirector director = new EntityDirector(new ShipBuilder());
private List<AEntity> entities = new ArrayList<>();
private List<List<AEntity>> entityMatrix = UEntityMatrixGenerator.createEntityMatrix(5,5, entities);
private class TestAICommander extends AICommander {
public TestAICommander(List<List<AEntity>> entityMatrix, List<List<ATile>> terrainMatrix) {
super(entityMatrix);
super.innerRadius = 1;
}
}
@Before
public void beforePreconditions() {
this.grid.add(Arrays.asList(1,1,0,1,1));
this.grid.add(Arrays.asList(1,0,1,0,1));
this.grid.add(Arrays.asList(1,1,1,1,1));
this.grid.add(Arrays.asList(1,0,1,0,1));
this.grid.add(Arrays.asList(1,1,0,1,1));
ArrayList<ATile> tileRow = new ArrayList<>();
tileRow.add(new SeaTile(new Point(0,0)));
tileRow.add(new SeaTile(new Point(0,1)));
tileRow.add(new LandTile(new Point(0,2)));
tileRow.add(new SeaTile(new Point(0,3)));
tileRow.add(new SeaTile(new Point(0,4)));
this.terrainMatrix.add(tileRow);
tileRow = new ArrayList<>();
tileRow.add(new SeaTile(new Point(1,0)));
tileRow.add(new LandTile(new Point(1,1)));
tileRow.add(new SeaTile(new Point(1,2)));
tileRow.add(new LandTile(new Point(1,3)));
tileRow.add(new SeaTile(new Point(1,4)));
this.terrainMatrix.add(tileRow);
tileRow = new ArrayList<>();
tileRow.add(new SeaTile(new Point(2,0)));
tileRow.add(new SeaTile(new Point(2,1)));
tileRow.add(new SeaTile(new Point(2,2)));
tileRow.add(new SeaTile(new Point(2,3)));
tileRow.add(new SeaTile(new Point(2,4)));
this.terrainMatrix.add(tileRow);
tileRow = new ArrayList<>();
tileRow.add(new SeaTile(new Point(3,0)));
tileRow.add(new LandTile(new Point(3,1)));
tileRow.add(new SeaTile(new Point(3,2)));
tileRow.add(new LandTile(new Point(3,3)));
tileRow.add(new SeaTile(new Point(3,4)));
this.terrainMatrix.add(tileRow);
tileRow = new ArrayList<>();
tileRow.add(new SeaTile(new Point(0,0)));
tileRow.add(new SeaTile(new Point(0,1)));
tileRow.add(new LandTile(new Point(0,2)));
tileRow.add(new SeaTile(new Point(0,3)));
tileRow.add(new SeaTile(new Point(0,4)));
this.terrainMatrix.add(tileRow);
| UMovement.setTileMatrix(this.terrainMatrix); | 8 | 2023-10-31 11:40:56+00:00 | 12k |
nailuj1992/OracionesCatolicas | app/src/main/java/com/prayers/app/activity/rosary/RosaryHomeActivity.java | [
{
"identifier": "AbstractClosableActivity",
"path": "app/src/main/java/com/prayers/app/activity/AbstractClosableActivity.java",
"snippet": "public abstract class AbstractClosableActivity extends AbstractActivity {\n\n private Button btnHome;\n\n /**\n * Prepare all view fields.\n */\n p... | import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import com.prayers.app.activity.AbstractClosableActivity;
import com.prayers.app.activity.R;
import com.prayers.app.activity.SpecialPrayersActivity;
import com.prayers.app.constants.GeneralConstants;
import com.prayers.app.constants.RedirectionConstants;
import com.prayers.app.mapper.RosaryMapper;
import com.prayers.app.model.rosary.Mysteries;
import com.prayers.app.utils.FieldsUtils;
import com.prayers.app.utils.GeneralUtils;
import com.prayers.app.utils.RedirectionUtils;
import java.util.Calendar; | 7,373 | package com.prayers.app.activity.rosary;
public class RosaryHomeActivity extends AbstractClosableActivity {
private Mysteries[] mysteries;
private Mysteries selectedMysteries;
private RadioGroup radioMysteries;
private Button btnPrev;
private Button btnBegin;
@Override
public int getActivity() {
return R.layout.rosary_home_activity;
}
@Override
public void prepareOthersActivity() {
radioMysteries = (RadioGroup) findViewById(R.id.radio_mysteries);
btnPrev = (Button) findViewById(R.id.btn_prev);
btnPrev.setOnClickListener(v -> backAction());
btnBegin = (Button) findViewById(R.id.btn_begin);
btnBegin.setOnClickListener(v -> nextAction());
}
@Override
public void updateViewState() {
mysteries = new Mysteries[GeneralConstants.MAX_GROUP_MYSTERIES];
try {
final String reflection = getString(R.string.txt_rosary_reflection);
final String pause = getString(R.string.txt_rosary_pause);
| package com.prayers.app.activity.rosary;
public class RosaryHomeActivity extends AbstractClosableActivity {
private Mysteries[] mysteries;
private Mysteries selectedMysteries;
private RadioGroup radioMysteries;
private Button btnPrev;
private Button btnBegin;
@Override
public int getActivity() {
return R.layout.rosary_home_activity;
}
@Override
public void prepareOthersActivity() {
radioMysteries = (RadioGroup) findViewById(R.id.radio_mysteries);
btnPrev = (Button) findViewById(R.id.btn_prev);
btnPrev.setOnClickListener(v -> backAction());
btnBegin = (Button) findViewById(R.id.btn_begin);
btnBegin.setOnClickListener(v -> nextAction());
}
@Override
public void updateViewState() {
mysteries = new Mysteries[GeneralConstants.MAX_GROUP_MYSTERIES];
try {
final String reflection = getString(R.string.txt_rosary_reflection);
final String pause = getString(R.string.txt_rosary_pause);
| mysteries[GeneralConstants.JOYFUL_MYSTERIES] = RosaryMapper.prepopulateJoyfulMysteries(this, reflection, pause); | 4 | 2023-10-25 17:17:47+00:00 | 12k |
LeoK99/swtw45WS21_reupload | src/main/java/com/buschmais/frontend/components/ADRExplorerComponent.java | [
{
"identifier": "ADR",
"path": "backup/java/com/buschmais/adr/ADR.java",
"snippet": "@Document\n@Data\npublic final class ADR {\n\n\t@Getter(AccessLevel.PRIVATE)\n\t@Setter(AccessLevel.PRIVATE)\n\t@EqualsExclude\n\t@Id\n\tprivate String id;\n\n\t@Setter(AccessLevel.PRIVATE)\n\t@DBRef\n\tprivate ADRConta... | import com.buschmais.backend.adr.ADR;
import com.buschmais.backend.adr.ADRTag;
import com.buschmais.backend.adr.dataAccess.ADRDao;
import com.buschmais.backend.adr.status.ADRStatusType;
import com.buschmais.backend.image.Image;
import com.buschmais.backend.image.ImageDao;
import com.buschmais.backend.users.User;
import com.buschmais.backend.users.dataAccess.UserDao;
import com.buschmais.frontend.vars.OtherConstantsFrontend;
import com.buschmais.frontend.vars.StringConstantsFrontend;
import com.vaadin.flow.component.avatar.Avatar;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.HeaderRow;
import com.vaadin.flow.component.grid.dataview.GridListDataView;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.component.textfield.TextFieldVariant;
import com.vaadin.flow.data.renderer.ComponentRenderer;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.function.SerializableBiConsumer;
import com.vaadin.flow.server.StreamResource;
import com.vaadin.flow.spring.annotation.UIScope;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors; | 9,211 | package com.buschmais.frontend.components;
@UIScope
@Component
public class ADRExplorerComponent extends Grid<ADR> {
private final ADRDao adrDao;
private final UserDao usrDao;
private final ImageDao imgDao;
Set<ADRTag> TagFilters;
List<ADR> ToShowList = new LinkedList();
GridListDataView<ADR> dataView;
private Column<ADR> titleColumn, statusColumn, tagColumn, authorColumn;
private Filter filter;
public ADRExplorerComponent(@Autowired ADRDao adrDao, @Autowired UserDao usrDao, @Autowired ImageDao imgDao){
this.adrDao = adrDao;
this.usrDao = usrDao;
this.imgDao = imgDao;
ToShowList = adrDao.findAll();
addAttachListener(event -> {getDataProvider().refreshAll();});
//Column<ADR> nameColumn = addColumn(ADR::getName).setHeader(StringConstantsFrontend.ADRCREATE_NAME).setSortable(true).setAutoWidth(true);
titleColumn = addColumn(ADR::getTitle).setHeader(StringConstantsFrontend.ADRCREATE_TITLE).setAutoWidth(true).setSortable(true);
authorColumn = addColumn(new ComponentRenderer<>(adr -> {
User usr = adr.getAuthor().get();
Avatar av = new Avatar(usr.getUserName());
| package com.buschmais.frontend.components;
@UIScope
@Component
public class ADRExplorerComponent extends Grid<ADR> {
private final ADRDao adrDao;
private final UserDao usrDao;
private final ImageDao imgDao;
Set<ADRTag> TagFilters;
List<ADR> ToShowList = new LinkedList();
GridListDataView<ADR> dataView;
private Column<ADR> titleColumn, statusColumn, tagColumn, authorColumn;
private Filter filter;
public ADRExplorerComponent(@Autowired ADRDao adrDao, @Autowired UserDao usrDao, @Autowired ImageDao imgDao){
this.adrDao = adrDao;
this.usrDao = usrDao;
this.imgDao = imgDao;
ToShowList = adrDao.findAll();
addAttachListener(event -> {getDataProvider().refreshAll();});
//Column<ADR> nameColumn = addColumn(ADR::getName).setHeader(StringConstantsFrontend.ADRCREATE_NAME).setSortable(true).setAutoWidth(true);
titleColumn = addColumn(ADR::getTitle).setHeader(StringConstantsFrontend.ADRCREATE_TITLE).setAutoWidth(true).setSortable(true);
authorColumn = addColumn(new ComponentRenderer<>(adr -> {
User usr = adr.getAuthor().get();
Avatar av = new Avatar(usr.getUserName());
| Image tempImg = usr.getProfilePicture(); | 4 | 2023-10-25 15:18:06+00:00 | 12k |
rudraparmar76/Student-Portal | Student-Portal/Home_Frame.java | [
{
"identifier": "Home_Bhagubhai",
"path": "Student-Portal/Colleges/Bhagubhai_College/Home_Bhagubhai.java",
"snippet": "public class Home_Bhagubhai extends javax.swing.JFrame {\n\n /**\n * Creates new form Home_Bhagubhai\n */\n public Home_Bhagubhai() {\n initComponents();\n }\n\n... | import Colleges.Bhagubhai_College.Home_Bhagubhai;
import Colleges.NM.Home_NM;
import javax.swing.JFrame; | 7,302 | jPanel2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel1.setBackground(java.awt.SystemColor.window);
jLabel1.setFont(new java.awt.Font("SansSerif", 1, 18)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("*** Please Select Your College ***");
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 255, 255));
jLabel9.setText("1.Shri Bhagubhai Mafatlal Polytechnic");
jLabel9.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel9MouseClicked(evt);
}
});
jLabel10.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 255, 255));
jLabel10.setText("3.Mithibai College");
jLabel11.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel11.setForeground(new java.awt.Color(255, 255, 255));
jLabel11.setText("4.NMIMS");
jLabel12.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel12.setForeground(new java.awt.Color(255, 255, 255));
jLabel12.setText("2.Narsee Monjee College");
jLabel12.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel12MouseClicked(evt);
}
});
jLabel13.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel13.setForeground(new java.awt.Color(255, 255, 255));
jLabel13.setText("5.D.J Sanghavi College of Engineering");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(145, 145, 145)
.addComponent(jLabel1))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(jLabel9)
.addComponent(jLabel11)
.addComponent(jLabel12)
.addComponent(jLabel13))))
.addContainerGap(163, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jLabel1)
.addGap(51, 51, 51)
.addComponent(jLabel9)
.addGap(18, 18, 18)
.addComponent(jLabel12)
.addGap(18, 18, 18)
.addComponent(jLabel10)
.addGap(18, 18, 18)
.addComponent(jLabel11)
.addGap(18, 18, 18)
.addComponent(jLabel13)
.addContainerGap(45, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(322, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 55, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jLabelCloseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelCloseMouseClicked
System.exit(0);
}//GEN-LAST:event_jLabelCloseMouseClicked
private void jLabelMinMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelMinMouseClicked
this.setState(Home_Frame.ICONIFIED);
}//GEN-LAST:event_jLabelMinMouseClicked
private void jLabel9MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel9MouseClicked
// TODO add your handling code here:
Home_Bhagubhai hb = new Home_Bhagubhai();
hb.setVisible(true);
hb.pack();
hb.setLocationRelativeTo(null);
// hb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.dispose();
}//GEN-LAST:event_jLabel9MouseClicked
private void jLabel12MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel12MouseClicked
// TODO add your handling code here: |
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
/**
*
* @author rudra
*/
public class Home_Frame extends javax.swing.JFrame {
/**
* Creates new form Home_Frame
*/
public Home_Frame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabelClose = new javax.swing.JLabel();
jLabelMin = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
jPanel1.setBackground(new java.awt.Color(37, 204, 247));
jLabelClose.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabelClose.setForeground(new java.awt.Color(255, 255, 255));
jLabelClose.setText("X");
jLabelClose.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabelClose.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelCloseMouseClicked(evt);
}
});
jLabelMin.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabelMin.setForeground(new java.awt.Color(255, 255, 255));
jLabelMin.setText("-");
jLabelMin.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabelMin.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabelMinMouseClicked(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("Home Page");
jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/download (2).jpeg"))); // NOI18N
jLabel8.setText("jLabel8");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 324, Short.MAX_VALUE)
.addComponent(jLabelMin)
.addGap(18, 18, 18)
.addComponent(jLabelClose)
.addGap(21, 21, 21))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelMin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelClose)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel2.setBackground(new java.awt.Color(27, 156, 252));
jPanel2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jLabel1.setBackground(java.awt.SystemColor.window);
jLabel1.setFont(new java.awt.Font("SansSerif", 1, 18)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("*** Please Select Your College ***");
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 255, 255));
jLabel9.setText("1.Shri Bhagubhai Mafatlal Polytechnic");
jLabel9.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel9MouseClicked(evt);
}
});
jLabel10.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 255, 255));
jLabel10.setText("3.Mithibai College");
jLabel11.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel11.setForeground(new java.awt.Color(255, 255, 255));
jLabel11.setText("4.NMIMS");
jLabel12.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel12.setForeground(new java.awt.Color(255, 255, 255));
jLabel12.setText("2.Narsee Monjee College");
jLabel12.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel12MouseClicked(evt);
}
});
jLabel13.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel13.setForeground(new java.awt.Color(255, 255, 255));
jLabel13.setText("5.D.J Sanghavi College of Engineering");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(145, 145, 145)
.addComponent(jLabel1))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(jLabel9)
.addComponent(jLabel11)
.addComponent(jLabel12)
.addComponent(jLabel13))))
.addContainerGap(163, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jLabel1)
.addGap(51, 51, 51)
.addComponent(jLabel9)
.addGap(18, 18, 18)
.addComponent(jLabel12)
.addGap(18, 18, 18)
.addComponent(jLabel10)
.addGap(18, 18, 18)
.addComponent(jLabel11)
.addGap(18, 18, 18)
.addComponent(jLabel13)
.addContainerGap(45, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(322, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 55, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jLabelCloseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelCloseMouseClicked
System.exit(0);
}//GEN-LAST:event_jLabelCloseMouseClicked
private void jLabelMinMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelMinMouseClicked
this.setState(Home_Frame.ICONIFIED);
}//GEN-LAST:event_jLabelMinMouseClicked
private void jLabel9MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel9MouseClicked
// TODO add your handling code here:
Home_Bhagubhai hb = new Home_Bhagubhai();
hb.setVisible(true);
hb.pack();
hb.setLocationRelativeTo(null);
// hb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.dispose();
}//GEN-LAST:event_jLabel9MouseClicked
private void jLabel12MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel12MouseClicked
// TODO add your handling code here: | Home_NM HNM = new Home_NM(); | 1 | 2023-10-27 17:08:02+00:00 | 12k |
Java-Game-Engine-Merger/Libgdx-Processing | framework/src/main/java/pama1234/gdx/util/element/MoveableCross.java | [
{
"identifier": "Tools",
"path": "server-framework/src/main/java/pama1234/Tools.java",
"snippet": "public class Tools extends ColorTools{\n // Android特供修正\n public static boolean isEmpty(CharSequence in) {\n return in.length()==0;\n }\n // Android特供修正,因为目前安卓中的String没有indent方法\n public static Str... | import com.badlogic.gdx.graphics.Color;
import pama1234.Tools;
import pama1234.gdx.util.UITools;
import pama1234.gdx.util.app.UtilScreen;
import pama1234.gdx.util.info.ScreenCamInfo;
import pama1234.math.geometry.RectD;
import pama1234.math.geometry.RectF;
import pama1234.math.geometry.RectI;
import pama1234.math.vec.Vec2f;
import pama1234.util.Annotations.DesktopOnly;
import pama1234.util.function.GetFloat; | 7,316 | package pama1234.gdx.util.element;
public class MoveableCross{
public Vec2f pos,offset; | package pama1234.gdx.util.element;
public class MoveableCross{
public Vec2f pos,offset; | public RectI size; | 6 | 2023-10-27 05:47:39+00:00 | 12k |
llllllxy/tinycloud | tinycloud-user/src/main/java/org/tinycloud/user/controller/TestController.java | [
{
"identifier": "RedisClient",
"path": "tinycloud-common/src/main/java/org/tinycloud/common/config/redis/RedisClient.java",
"snippet": "public class RedisClient {\n final static Logger log = LoggerFactory.getLogger(RedisClient.class);\n\n private RedisTemplate<String, Object> redisTemplate;\n\n ... | import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.tinycloud.common.config.redis.RedisClient;
import org.tinycloud.common.model.ApiResult;
import org.tinycloud.user.config.TinyCloudUserConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map; | 9,076 | package org.tinycloud.user.controller;
@Api(tags = "用户中心-测试", value = "用户中心-测试")
@RestController
@RequestMapping("/test")
public class TestController {
private static final Logger log = LoggerFactory.getLogger(TestController.class);
@Autowired | package org.tinycloud.user.controller;
@Api(tags = "用户中心-测试", value = "用户中心-测试")
@RestController
@RequestMapping("/test")
public class TestController {
private static final Logger log = LoggerFactory.getLogger(TestController.class);
@Autowired | private TinyCloudUserConfig tinyCloudUserConfig; | 2 | 2023-10-28 02:05:15+00:00 | 12k |
llllllxy/bluewind-base | src/main/java/com/bluewind/base/common/config/auth/session/AuthClientSessionDao.java | [
{
"identifier": "AuthConstant",
"path": "src/main/java/com/bluewind/base/common/config/auth/constant/AuthConstant.java",
"snippet": "public class AuthConstant {\n\n // 登录用户token-key\n public static final String BLUEWIND_TOKEN_KEY = \"token\";\n\n\n // 用户会话redis的key\n public final static Stri... | import com.bluewind.base.common.config.auth.constant.AuthConstant;
import com.bluewind.base.common.config.auth.util.SerializableUtil;
import com.bluewind.base.common.util.redis.RedisUtils;
import com.bluewind.base.common.util.spring.SpringContextUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set; | 8,656 | package com.bluewind.base.common.config.auth.session;
/**
* @author liuxingyu01
* @date 2022-08-26 12:43
* @description 基于redis的sessionDao,缓存共享session
**/
public class AuthClientSessionDao extends CachingSessionDAO {
private static final Logger logger = LoggerFactory.getLogger(AuthClientSessionDao.class);
private static Map<String, Session> sessionCacheMap = new HashMap<>();
private static RedisUtils redisUtils;
private static RedisUtils getRedisUtils() {
if (redisUtils == null) {
Object bean = SpringContextUtil.getBean("redisUtils");
if (bean == null) {
logger.error("redisUtils bean is null!");
}
redisUtils = (RedisUtils) bean;
}
return redisUtils;
}
@Override
protected Serializable doCreate(Session session) {
Serializable sessionId = generateSessionId(session);
assignSessionId(session, sessionId); | package com.bluewind.base.common.config.auth.session;
/**
* @author liuxingyu01
* @date 2022-08-26 12:43
* @description 基于redis的sessionDao,缓存共享session
**/
public class AuthClientSessionDao extends CachingSessionDAO {
private static final Logger logger = LoggerFactory.getLogger(AuthClientSessionDao.class);
private static Map<String, Session> sessionCacheMap = new HashMap<>();
private static RedisUtils redisUtils;
private static RedisUtils getRedisUtils() {
if (redisUtils == null) {
Object bean = SpringContextUtil.getBean("redisUtils");
if (bean == null) {
logger.error("redisUtils bean is null!");
}
redisUtils = (RedisUtils) bean;
}
return redisUtils;
}
@Override
protected Serializable doCreate(Session session) {
Serializable sessionId = generateSessionId(session);
assignSessionId(session, sessionId); | getRedisUtils().set(AuthConstant.BLUEWIND_SSO_SHIRO_SESSION_ID + ":" + sessionId, SerializableUtil.serialize(session), (int) session.getTimeout() / 1000); | 1 | 2023-10-26 10:02:07+00:00 | 12k |
danielbatres/orthodontic-dentistry-clinical-management | src/com/view/readPct/Delete.java | [
{
"identifier": "ApplicationContext",
"path": "src/com/context/ApplicationContext.java",
"snippet": "public class ApplicationContext {\r\n public static SesionUsuario sesionUsuario;\r\n public static LoadingApp loading = new LoadingApp();\r\n public static LoadingApplication loadingApplication ... | import com.context.ApplicationContext;
import com.context.ChoosedPalette;
import com.context.StateColors;
import com.helper.RadiografiaHelper;
import javax.swing.border.LineBorder; | 8,385 | package com.view.readPct;
/**
*
* @author Daniel Batres
* @version 1.0.0
* @since 3/10/22
*/
public class Delete extends javax.swing.JFrame {
private int id;
private String caseInOut;
/**
* Creates new form EstasSeguroEdicion
*/
public Delete() {
initComponents();
setLocationRelativeTo(null);
container2.setkFillBackground(true);
}
public void colorComponent(String preferred) {
switch (preferred) {
case "light":
colorBasics();
light();
break;
case "dark":
colorBasics();
dark();
break;
default:
System.out.println("Invalido");
}
}
public void colorBasics() {
content.setBackground(ChoosedPalette.getPrimaryBackground());
content.setBorder(new LineBorder(ChoosedPalette.getGray()));
title.setForeground(ChoosedPalette.getDarkColor());
text1.setForeground(ChoosedPalette.getTextColor());
nombreRadiografia.setForeground(ChoosedPalette.getTextColor());
}
public void light() {
container1.setkStartColor(StateColors.getLightDanger());
container1.setkEndColor(StateColors.getLightDanger());
container2.setkStartColor(StateColors.getLightDanger());
container2.setkEndColor(StateColors.getLightDanger());
guardar.setForeground(StateColors.getDanger());
cancelar.setForeground(StateColors.getLightDanger());
}
public void dark() {
container1.setkStartColor(StateColors.getDanger());
container1.setkEndColor(StateColors.getDanger());
container2.setkStartColor(StateColors.getDanger());
container2.setkEndColor(StateColors.getDanger());
guardar.setForeground(ChoosedPalette.getWhite());
cancelar.setForeground(StateColors.getDanger());
}
public void setIdRadiografia(int idRadiografia, String nombre, String caseIn) {
id = idRadiografia;
nombreRadiografia.setText(nombre);
caseInOut = caseIn;
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
content = new javax.swing.JPanel();
title = new javax.swing.JLabel();
text1 = new javax.swing.JLabel();
nombreRadiografia = new javax.swing.JLabel();
container1 = new com.k33ptoo.components.KGradientPanel();
cancelar = new javax.swing.JLabel();
container2 = new com.k33ptoo.components.KGradientPanel();
guardar = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("¿Estas seguro de que quieres eliminar?");
setMinimumSize(new java.awt.Dimension(450, 350));
setUndecorated(true);
setResizable(false);
content.setBackground(new java.awt.Color(255, 255, 255));
content.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
title.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 18)); // NOI18N
title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
title.setText("Eliminar radiografía");
content.add(title, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 80, 450, -1));
text1.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N
text1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
text1.setText("¿Estás seguro de que quieres eliminar esta radiografía?");
content.add(text1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 140, 450, -1));
nombreRadiografia.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N
nombreRadiografia.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
nombreRadiografia.setText("Se cerrará la sesión actual para iniciar de nuevo.");
content.add(nombreRadiografia, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 160, 450, -1));
container1.setkEndColor(new java.awt.Color(204, 204, 204));
container1.setkFillBackground(false);
container1.setkStartColor(new java.awt.Color(204, 204, 204));
container1.setOpaque(false);
container1.setLayout(new java.awt.BorderLayout());
cancelar.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N
cancelar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
cancelar.setText("Cancelar");
cancelar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
cancelar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
cancelarMouseClicked(evt);
}
});
container1.add(cancelar, java.awt.BorderLayout.CENTER);
content.add(container1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 220, 160, 50));
container2.setkEndColor(new java.awt.Color(204, 204, 204));
container2.setkFillBackground(false);
container2.setkStartColor(new java.awt.Color(204, 204, 204));
container2.setOpaque(false);
container2.setLayout(new java.awt.BorderLayout());
guardar.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N
guardar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
guardar.setText("Eliminar");
guardar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
guardar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
guardarMouseClicked(evt);
}
});
container2.add(guardar, java.awt.BorderLayout.CENTER);
content.add(container2, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 220, 160, 50));
getContentPane().add(content, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
private void cancelarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelarMouseClicked
dispose();
}//GEN-LAST:event_cancelarMouseClicked
private void guardarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_guardarMouseClicked | package com.view.readPct;
/**
*
* @author Daniel Batres
* @version 1.0.0
* @since 3/10/22
*/
public class Delete extends javax.swing.JFrame {
private int id;
private String caseInOut;
/**
* Creates new form EstasSeguroEdicion
*/
public Delete() {
initComponents();
setLocationRelativeTo(null);
container2.setkFillBackground(true);
}
public void colorComponent(String preferred) {
switch (preferred) {
case "light":
colorBasics();
light();
break;
case "dark":
colorBasics();
dark();
break;
default:
System.out.println("Invalido");
}
}
public void colorBasics() {
content.setBackground(ChoosedPalette.getPrimaryBackground());
content.setBorder(new LineBorder(ChoosedPalette.getGray()));
title.setForeground(ChoosedPalette.getDarkColor());
text1.setForeground(ChoosedPalette.getTextColor());
nombreRadiografia.setForeground(ChoosedPalette.getTextColor());
}
public void light() {
container1.setkStartColor(StateColors.getLightDanger());
container1.setkEndColor(StateColors.getLightDanger());
container2.setkStartColor(StateColors.getLightDanger());
container2.setkEndColor(StateColors.getLightDanger());
guardar.setForeground(StateColors.getDanger());
cancelar.setForeground(StateColors.getLightDanger());
}
public void dark() {
container1.setkStartColor(StateColors.getDanger());
container1.setkEndColor(StateColors.getDanger());
container2.setkStartColor(StateColors.getDanger());
container2.setkEndColor(StateColors.getDanger());
guardar.setForeground(ChoosedPalette.getWhite());
cancelar.setForeground(StateColors.getDanger());
}
public void setIdRadiografia(int idRadiografia, String nombre, String caseIn) {
id = idRadiografia;
nombreRadiografia.setText(nombre);
caseInOut = caseIn;
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
content = new javax.swing.JPanel();
title = new javax.swing.JLabel();
text1 = new javax.swing.JLabel();
nombreRadiografia = new javax.swing.JLabel();
container1 = new com.k33ptoo.components.KGradientPanel();
cancelar = new javax.swing.JLabel();
container2 = new com.k33ptoo.components.KGradientPanel();
guardar = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("¿Estas seguro de que quieres eliminar?");
setMinimumSize(new java.awt.Dimension(450, 350));
setUndecorated(true);
setResizable(false);
content.setBackground(new java.awt.Color(255, 255, 255));
content.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
title.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 18)); // NOI18N
title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
title.setText("Eliminar radiografía");
content.add(title, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 80, 450, -1));
text1.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N
text1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
text1.setText("¿Estás seguro de que quieres eliminar esta radiografía?");
content.add(text1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 140, 450, -1));
nombreRadiografia.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N
nombreRadiografia.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
nombreRadiografia.setText("Se cerrará la sesión actual para iniciar de nuevo.");
content.add(nombreRadiografia, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 160, 450, -1));
container1.setkEndColor(new java.awt.Color(204, 204, 204));
container1.setkFillBackground(false);
container1.setkStartColor(new java.awt.Color(204, 204, 204));
container1.setOpaque(false);
container1.setLayout(new java.awt.BorderLayout());
cancelar.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N
cancelar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
cancelar.setText("Cancelar");
cancelar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
cancelar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
cancelarMouseClicked(evt);
}
});
container1.add(cancelar, java.awt.BorderLayout.CENTER);
content.add(container1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 220, 160, 50));
container2.setkEndColor(new java.awt.Color(204, 204, 204));
container2.setkFillBackground(false);
container2.setkStartColor(new java.awt.Color(204, 204, 204));
container2.setOpaque(false);
container2.setLayout(new java.awt.BorderLayout());
guardar.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N
guardar.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
guardar.setText("Eliminar");
guardar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
guardar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
guardarMouseClicked(evt);
}
});
container2.add(guardar, java.awt.BorderLayout.CENTER);
content.add(container2, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 220, 160, 50));
getContentPane().add(content, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
private void cancelarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelarMouseClicked
dispose();
}//GEN-LAST:event_cancelarMouseClicked
private void guardarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_guardarMouseClicked | RadiografiaHelper.deleteRadiografia(ApplicationContext.selectedTreatment, id); | 3 | 2023-10-26 19:35:40+00:00 | 12k |
kdetard/koki | app/src/main/java/io/github/kdetard/koki/feature/main/MainController.java | [
{
"identifier": "AssetsController",
"path": "app/src/main/java/io/github/kdetard/koki/feature/assets/AssetsController.java",
"snippet": "public class AssetsController extends MapController {\n @EntryPoint\n @InstallIn(SingletonComponent.class)\n interface AssetsEntryPoint {\n OpenRemoteS... | import android.view.View;
import androidx.annotation.NonNull;
import com.bluelinelabs.conductor.Router;
import com.bluelinelabs.conductor.RouterTransaction;
import com.bluelinelabs.conductor.changehandler.FadeChangeHandler;
import com.bluelinelabs.conductor.viewpager2.RouterStateAdapter;
import java.util.Map;
import java.util.Objects;
import io.github.kdetard.koki.R;
import io.github.kdetard.koki.databinding.ControllerMainBinding;
import io.github.kdetard.koki.feature.assets.AssetsController;
import io.github.kdetard.koki.feature.base.BaseController;
import io.github.kdetard.koki.feature.home.HomeController;
import io.github.kdetard.koki.feature.monitoring.MonitoringController;
import io.github.kdetard.koki.feature.settings.SettingsMainController; | 8,347 | package io.github.kdetard.koki.feature.main;
public class MainController extends BaseController {
ControllerMainBinding binding;
RouterStateAdapter pagerAdapter;
private static final Map<Integer, Integer> navBarMap = Map.of(
R.id.nav_home, 0,
R.id.nav_assets, 1,
R.id.nav_monitoring, 2,
R.id.nav_settings, 3
);
private int currentNavItemId = R.id.nav_home;
public MainController() {
super(R.layout.controller_main);
pagerAdapter = new RouterStateAdapter(this) {
@Override
public void configureRouter(@NonNull Router router, int i) {
if (!router.hasRootController()) {
var page = switch (i) {
case 0 -> new HomeController(); | package io.github.kdetard.koki.feature.main;
public class MainController extends BaseController {
ControllerMainBinding binding;
RouterStateAdapter pagerAdapter;
private static final Map<Integer, Integer> navBarMap = Map.of(
R.id.nav_home, 0,
R.id.nav_assets, 1,
R.id.nav_monitoring, 2,
R.id.nav_settings, 3
);
private int currentNavItemId = R.id.nav_home;
public MainController() {
super(R.layout.controller_main);
pagerAdapter = new RouterStateAdapter(this) {
@Override
public void configureRouter(@NonNull Router router, int i) {
if (!router.hasRootController()) {
var page = switch (i) {
case 0 -> new HomeController(); | case 1 -> new AssetsController(); | 0 | 2023-10-30 00:44:59+00:00 | 12k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.