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
MrXiaoM/plugin-template
src/main/java/top/mrxiaom/example/func/AbstractPluginHolder.java
[ { "identifier": "ColorHelper", "path": "src/main/java/top/mrxiaom/example/utils/ColorHelper.java", "snippet": "public class ColorHelper {\n private static final Pattern startWithColor = Pattern.compile(\"^(&[LMNKOlmnko])+\");\n private static final Pattern gradientPattern = Pattern.compile(\"\\\\{...
import org.bukkit.Bukkit; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.command.TabCompleter; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.event.Listener; import org.jetbrains.annotations.Nullable; import top.mrxiaom.example.utils.ColorHelper; import top.mrxiaom.example.ExamplePlugin; import top.mrxiaom.example.utils.Util; import java.util.HashMap; import java.util.Map; import java.util.Optional;
3,669
package top.mrxiaom.example.func; @SuppressWarnings({"unused"}) public abstract class AbstractPluginHolder { private static final Map<Class<?>, AbstractPluginHolder> registeredHolders = new HashMap<>(); public final ExamplePlugin plugin; public AbstractPluginHolder(ExamplePlugin plugin) { this.plugin = plugin; } public void reloadConfig(MemoryConfiguration config) { } public void onDisable() { } protected void registerEvents(Listener listener) { try { Bukkit.getPluginManager().registerEvents(listener, plugin); } catch (Throwable t) { warn("在注册事件监听器 " + this.getClass().getSimpleName() + " 时出现一个异常", t); } } protected void registerCommand(String label, Object inst) { PluginCommand command = plugin.getCommand(label); if (command != null) { if (inst instanceof CommandExecutor){ command.setExecutor((CommandExecutor) inst); } else{ warn(inst.getClass().getSimpleName() + " 不是一个命令执行器"); } if (inst instanceof TabCompleter) command.setTabCompleter((TabCompleter) inst); } else { info("无法注册命令 /" + label); } } protected void register() { registeredHolders.put(getClass(), this); } protected void unregister() { registeredHolders.remove(getClass()); } protected boolean isRegistered() { return registeredHolders.containsKey(getClass()); } public void info(String... lines) { for (String line : lines) { plugin.getLogger().info(line); } } public void warn(String... lines) { for (String line : lines) { plugin.getLogger().warning(line); } } public void warn(String s, Throwable t) { plugin.getLogger().warning(s); plugin.getLogger().warning(Util.stackTraceToString(t)); } @Nullable @SuppressWarnings({"unchecked"}) public static <T extends AbstractPluginHolder> T getOrNull(Class<T> clazz) { return (T) registeredHolders.get(clazz); } @SuppressWarnings({"unchecked"}) public static <T extends AbstractPluginHolder> Optional<T> get(Class<T> clazz) { T inst = (T) registeredHolders.get(clazz); if (inst == null) return Optional.empty(); return Optional.of(inst); } public static void reloadAllConfig(MemoryConfiguration config) { for (AbstractPluginHolder inst : registeredHolders.values()) { inst.reloadConfig(config); } } public static void disableAllModule() { for (AbstractPluginHolder inst : registeredHolders.values()) { inst.onDisable(); } registeredHolders.clear(); } public static boolean t(CommandSender sender, String... msg) {
package top.mrxiaom.example.func; @SuppressWarnings({"unused"}) public abstract class AbstractPluginHolder { private static final Map<Class<?>, AbstractPluginHolder> registeredHolders = new HashMap<>(); public final ExamplePlugin plugin; public AbstractPluginHolder(ExamplePlugin plugin) { this.plugin = plugin; } public void reloadConfig(MemoryConfiguration config) { } public void onDisable() { } protected void registerEvents(Listener listener) { try { Bukkit.getPluginManager().registerEvents(listener, plugin); } catch (Throwable t) { warn("在注册事件监听器 " + this.getClass().getSimpleName() + " 时出现一个异常", t); } } protected void registerCommand(String label, Object inst) { PluginCommand command = plugin.getCommand(label); if (command != null) { if (inst instanceof CommandExecutor){ command.setExecutor((CommandExecutor) inst); } else{ warn(inst.getClass().getSimpleName() + " 不是一个命令执行器"); } if (inst instanceof TabCompleter) command.setTabCompleter((TabCompleter) inst); } else { info("无法注册命令 /" + label); } } protected void register() { registeredHolders.put(getClass(), this); } protected void unregister() { registeredHolders.remove(getClass()); } protected boolean isRegistered() { return registeredHolders.containsKey(getClass()); } public void info(String... lines) { for (String line : lines) { plugin.getLogger().info(line); } } public void warn(String... lines) { for (String line : lines) { plugin.getLogger().warning(line); } } public void warn(String s, Throwable t) { plugin.getLogger().warning(s); plugin.getLogger().warning(Util.stackTraceToString(t)); } @Nullable @SuppressWarnings({"unchecked"}) public static <T extends AbstractPluginHolder> T getOrNull(Class<T> clazz) { return (T) registeredHolders.get(clazz); } @SuppressWarnings({"unchecked"}) public static <T extends AbstractPluginHolder> Optional<T> get(Class<T> clazz) { T inst = (T) registeredHolders.get(clazz); if (inst == null) return Optional.empty(); return Optional.of(inst); } public static void reloadAllConfig(MemoryConfiguration config) { for (AbstractPluginHolder inst : registeredHolders.values()) { inst.reloadConfig(config); } } public static void disableAllModule() { for (AbstractPluginHolder inst : registeredHolders.values()) { inst.onDisable(); } registeredHolders.clear(); } public static boolean t(CommandSender sender, String... msg) {
sender.sendMessage(ColorHelper.parseColor(String.join("\n&r", msg)));
0
2023-12-08 15:50:57+00:00
8k
ExcaliburFRC/2024RobotTamplate
src/main/java/frc/robot/subsystems/swerve/Swerve.java
[ { "identifier": "Limelight", "path": "src/main/java/frc/lib/Limelight.java", "snippet": "public class Limelight {\n PhotonCamera camera;// = new PhotonCamera(\"bob\");\n AprilTagFieldLayout fieldLayout;\n\n private PhotonPoseEstimator photonPoseEstimator;\n\n private final Transform3d robotT...
import com.kauailabs.navx.frc.AHRS; import com.pathplanner.lib.auto.AutoBuilder; import com.pathplanner.lib.path.GoalEndState; import com.pathplanner.lib.path.PathPlannerPath; import com.pathplanner.lib.util.HolonomicPathFollowerConfig; import com.pathplanner.lib.util.PIDConstants; import com.pathplanner.lib.util.ReplanningConfig; import edu.wpi.first.math.controller.PIDController; import edu.wpi.first.math.controller.ProfiledPIDController; import edu.wpi.first.math.estimator.SwerveDrivePoseEstimator; import edu.wpi.first.math.filter.SlewRateLimiter; import edu.wpi.first.math.geometry.*; import edu.wpi.first.math.interpolation.InterpolatingTreeMap; import edu.wpi.first.math.interpolation.Interpolator; import edu.wpi.first.math.interpolation.InverseInterpolator; import edu.wpi.first.math.kinematics.ChassisSpeeds; import edu.wpi.first.math.kinematics.SwerveDriveKinematics; import edu.wpi.first.math.kinematics.SwerveModulePosition; import edu.wpi.first.math.kinematics.SwerveModuleState; import edu.wpi.first.math.trajectory.TrapezoidProfile; import edu.wpi.first.networktables.GenericEntry; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.SPI; import edu.wpi.first.wpilibj.shuffleboard.BuiltInWidgets; import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.smartdashboard.Field2d; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.*; import edu.wpi.first.wpilibj2.command.button.Trigger; import frc.lib.Limelight; import frc.robot.util.AllianceUtilities; import org.photonvision.EstimatedRobotPose; import java.util.Optional; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.DoubleSupplier; import static frc.robot.Constants.SwerveConstants.*; import static frc.robot.Constants.SwerveConstants.Modules.*;
5,297
.and(swerveModules[BACK_LEFT].isReset) .and(swerveModules[BACK_RIGHT].isReset), this); } public Command turnToAngleCommand(double setpoint) { return setClosedLoop(true).andThen( driveSwerveCommand( () -> 0, () -> 0, () -> anglePIDcontroller.calculate(getOdometryRotation2d().getDegrees(), setpoint), () -> false).until(new Trigger(anglePIDcontroller::atSetpoint).debounce(0.1)), setClosedLoop(false)); } /** * @param angle * @return returns the pid calculated controller input to rotate the swerve to the desired angle * the returned value should be inserted into the driveCommand instead of the driver's input */ public double getAngleDC(double angle) { System.out.println(getOdometryRotation2d().getDegrees() + " " + angle); return anglePIDcontroller.calculate(getOdometryRotation2d().getDegrees(), angle); } public double getAngleDC() { return getAngleDC(0); } // other methods private void resetAngleEncoders() { foreachModule(SwerveModule::resetEncoders); } private void stopModules() { foreachModule(SwerveModule::stopModule); } public void setModulesStates(SwerveModuleState[] states) { SwerveDriveKinematics.desaturateWheelSpeeds(states, MAX_VELOCITY_METER_PER_SECOND); swerveModules[FRONT_LEFT].setDesiredState(states[FRONT_LEFT]); swerveModules[FRONT_RIGHT].setDesiredState(states[FRONT_RIGHT]); swerveModules[BACK_LEFT].setDesiredState(states[BACK_LEFT]); swerveModules[BACK_RIGHT].setDesiredState(states[BACK_RIGHT]); } public SwerveModulePosition[] getModulesPositions() { return new SwerveModulePosition[]{ swerveModules[0].getPosition(), swerveModules[1].getPosition(), swerveModules[2].getPosition(), swerveModules[3].getPosition(), }; } public SwerveModuleState[] getModulesStates() { return new SwerveModuleState[]{ swerveModules[0].getState(), swerveModules[1].getState(), swerveModules[2].getState(), swerveModules[3].getState(), }; } private void foreachModule(Consumer<SwerveModule> module) { for (int i = 0; i < swerveModules.length; i++) { module.accept(swerveModules[i]); } } public Command toggleIdleModeCommand() { return new StartEndCommand( () -> foreachModule(SwerveModule::setIdleModeCoast), () -> foreachModule(SwerveModule::setIdleModebreak)) .ignoringDisable(true); } public Command setClosedLoop(boolean isCloseLoop) { return new InstantCommand(() -> this.isClosedloop = isCloseLoop); } @Override public void periodic() { odometry.update(getGyroRotation2d(), getModulesPositions()); // localization with PhotonPoseEstimator // Optional<EstimatedRobotPose> pose = limelight.getEstimatedGlobalPose(odometry.getEstimatedPosition()); // if (pose.isPresent()) odometry.addVisionMeasurement(pose.get().estimatedPose.toPose2d(), pose.get().timestampSeconds); // localization with SwervePoseEstimator // if (limelight.getLatestResualt().hasTargets()) limelight.updateFromAprilTagPose(odometry::addVisionMeasurement); field.setRobotPose(odometry.getEstimatedPosition()); SmartDashboard.putData(field); if (DriverStation.isEnabled()) { System.out.println(getPose2d()); System.out.println(xTranslationPIDcontroller.calculate(getPose2d().getX(), 0)); } } // on-the-fly auto generation functions public Command followPath(double endVel, double endDegrees, Pose2d... positions) { return AutoBuilder.followPathWithEvents( new PathPlannerPath( PathPlannerPath.bezierFromPoses(getAlliancePositions(positions)), PATH_CONSTRAINTS, new GoalEndState(endVel, Rotation2d.fromDegrees(endDegrees))) ); } // drives the robot from current location to a given Pose2d public Command pathPlannerToPose(Pose2d position, double endVel) { return new ProxyCommand(() -> followPath(endVel, position.getRotation().getDegrees(), getStraightLinePoses(position.getTranslation())) ); } public Pose2d[] getAlliancePositions(Pose2d... poses) { for (int i = 0; i < poses.length; i++) {
package frc.robot.subsystems.swerve; public class Swerve extends SubsystemBase { private final SwerveModule[] swerveModules = { new SwerveModule( Modules.FL.DRIVE_MOTOR_ID, Modules.FL.SPIN_MOTOR_ID, Modules.FL.DRIVE_MOTOR_REVERSED, Modules.FL.SPIN_MOTOR_REVERSED, Modules.FL.ABS_ENCODER_CHANNEL, Modules.FL.OFFSET_ANGLE), new SwerveModule( Modules.FR.DRIVE_MOTOR_ID, Modules.FR.SPIN_MOTOR_ID, Modules.FR.DRIVE_MOTOR_REVERSED, Modules.FR.SPIN_MOTOR_REVERSED, Modules.FR.ABS_ENCODER_CHANNEL, Modules.FR.OFFSET_ANGLE), new SwerveModule( Modules.BL.DRIVE_MOTOR_ID, Modules.BL.SPIN_MOTOR_ID, Modules.BL.DRIVE_MOTOR_REVERSED, Modules.BL.SPIN_MOTOR_REVERSED, Modules.BL.ABS_ENCODER_CHANNEL, Modules.BL.OFFSET_ANGLE), new SwerveModule( Modules.BR.DRIVE_MOTOR_ID, Modules.BR.SPIN_MOTOR_ID, Modules.BR.DRIVE_MOTOR_REVERSED, Modules.BR.SPIN_MOTOR_REVERSED, Modules.BR.ABS_ENCODER_CHANNEL, Modules.BR.OFFSET_ANGLE)}; private boolean hasStraighten = false; private final AHRS _gyro = new AHRS(SPI.Port.kMXP); private final ProfiledPIDController anglePIDcontroller = new ProfiledPIDController( ANGLE_GAINS.kp, ANGLE_GAINS.ki, ANGLE_GAINS.kd, new TrapezoidProfile.Constraints(MAX_VELOCITY_METER_PER_SECOND, MAX_VELOCITY_ACCELERATION_METER_PER_SECOND)); private final PIDController xTranslationPIDcontroller = new PIDController(PATHPLANNER_TRANSLATION_GAINS.kp, PATHPLANNER_TRANSLATION_GAINS.ki, PATHPLANNER_TRANSLATION_GAINS.kd); private final PIDController yTranslationPIDcontroller = new PIDController(PATHPLANNER_TRANSLATION_GAINS.kp, PATHPLANNER_TRANSLATION_GAINS.ki, PATHPLANNER_TRANSLATION_GAINS.kd); private final SwerveDrivePoseEstimator odometry = new SwerveDrivePoseEstimator( kSwerveKinematics, getGyroRotation2d(), getModulesPositions(), new Pose2d()); private final Field2d field = new Field2d(); // private final Limelight limelight = Limelight.INSTANCE; private GenericEntry maxSpeed = Shuffleboard.getTab("Swerve").add("speedPercent", DRIVE_SPEED_PERCENTAGE).withPosition(2, 0).withSize(2, 2).getEntry(); private final InterpolatingTreeMap interpolate = new InterpolatingTreeMap(InverseInterpolator.forDouble(), Interpolator.forDouble()); private boolean isClosedloop = false; public Swerve() { resetGyroHardware(); AutoBuilder.configureHolonomic( this::getPose2d, this::setPose2d, this::getRobotRelativeSpeeds, this::driveRobotRelative, new HolonomicPathFollowerConfig( new PIDConstants(PATHPLANNER_TRANSLATION_GAINS.kp, 0.0, PATHPLANNER_TRANSLATION_GAINS.kd), new PIDConstants(PATHPLANNER_ANGLE_GAINS.kp, 0.0, PATHPLANNER_ANGLE_GAINS.kd), MAX_VELOCITY_METER_PER_SECOND, Math.sqrt(2) * (TRACK_WIDTH / 2), // needs to change for a non-square swerve // Math.sqrt(Math.pow(TRACK_WIDTH, 2) / 2), // needs to change for a non-square swerve new ReplanningConfig() ), this ); odometry.resetPosition(getGyroRotation2d(), getModulesPositions(), new Pose2d(0, 0, new Rotation2d())); resetOdometryAngleCommand(); anglePIDcontroller.enableContinuousInput(0, 360); anglePIDcontroller.setTolerance(1); interpolate.put(1.0, 0.2); interpolate.put(-1.0, 1.0); initShuffleboardData(); } // gyro getters and setters public void resetGyroHardware() { _gyro.reset(); } private double getGyroDegrees() { return Math.IEEEremainder(_gyro.getAngle(), 360); } public double getRobotPitch() { return _gyro.getRoll() - 0.46; } // odometry getters and setters private void setPose2d(Pose2d pose) { odometry.resetPosition(getGyroRotation2d(), getModulesPositions(), pose); } public Pose2d getPose2d() { return odometry.getEstimatedPosition(); } public Rotation2d getGyroRotation2d() { return Rotation2d.fromDegrees(getGyroDegrees()).times(-1); } public Rotation2d getOdometryRotation2d() { return odometry.getEstimatedPosition().getRotation(); } public ChassisSpeeds getRobotRelativeSpeeds() { return kSwerveKinematics.toChassisSpeeds(getModulesStates()); } public Command setOdometryPositionCommand(Pose2d pose) { return new InstantCommand(() -> setPose2d(pose)).ignoringDisable(true); } public Command setOdometryAngleCommand(double angle) { return new ProxyCommand(() -> setOdometryPositionCommand( new Pose2d(odometry.getEstimatedPosition().getTranslation(), Rotation2d.fromDegrees(angle))).ignoringDisable(true)); } public Command resetOdometryAngleCommand() { return setOdometryAngleCommand(0); } // drive commands public Command driveSwerveCommand( DoubleSupplier xSpeedSupplier, DoubleSupplier ySpeedSupplier, DoubleSupplier spinningSpeedSupplier, BooleanSupplier fieldOriented, DoubleSupplier decelerator, DoubleSupplier turnToAngle) { return new ConditionalCommand(new InstantCommand(), straightenModulesCommand(), () -> hasStraighten) .andThen( this.runEnd( () -> { double xSpeed = xSpeedSupplier.getAsDouble(), ySpeed = ySpeedSupplier.getAsDouble(), spinningSpeed = spinningSpeedSupplier.getAsDouble(); if (!isClosedloop) { double spinning = turnToAngle.getAsDouble() == -1 ? spinningSpeedSupplier.getAsDouble() : getAngleDC(turnToAngle.getAsDouble()); //create the speeds for x,y and spin xSpeed = xSpeedSupplier.getAsDouble() * MAX_VELOCITY_METER_PER_SECOND / 100 * maxSpeed.getDouble(DRIVE_SPEED_PERCENTAGE) * (double) interpolate.get(decelerator.getAsDouble()); ySpeed = ySpeedSupplier.getAsDouble() * MAX_VELOCITY_METER_PER_SECOND / 100 * maxSpeed.getDouble(DRIVE_SPEED_PERCENTAGE) * (double) interpolate.get(decelerator.getAsDouble()); spinningSpeed = spinning * MAX_VELOCITY_METER_PER_SECOND / 100 * maxSpeed.getDouble(DRIVE_SPEED_PERCENTAGE) * (double) interpolate.get(decelerator.getAsDouble()); } // create a CassisSpeeds object and apply it the speeds ChassisSpeeds chassisSpeeds = fieldOriented.getAsBoolean() ? ChassisSpeeds.fromFieldRelativeSpeeds(xSpeed, ySpeed, spinningSpeed, getOdometryRotation2d()) : new ChassisSpeeds(xSpeed, ySpeed, spinningSpeed); //use the ChassisSpeedsObject to create an array of SwerveModuleStates SwerveModuleState[] moduleStates = kSwerveKinematics.toSwerveModuleStates(chassisSpeeds); //apply the array to the swerve modules of the robot setModulesStates(moduleStates); }, this::stopModules )); } public Command driveSwerveCommand( DoubleSupplier xSpeedSupplier, DoubleSupplier ySpeedSupplier, DoubleSupplier spinningSpeedSupplier, BooleanSupplier fieldOriented) { return driveSwerveCommand(xSpeedSupplier, ySpeedSupplier, spinningSpeedSupplier, fieldOriented, () -> 1, () -> -1); } public Command tankDriveCommand(DoubleSupplier speed, DoubleSupplier turn, boolean fieldOriented) { return driveSwerveCommand(speed, () -> 0, turn, () -> fieldOriented); } private void driveRobotRelative(ChassisSpeeds chassisSpeeds) { setModulesStates(kSwerveKinematics.toSwerveModuleStates(chassisSpeeds)); } public Command straightenModulesCommand() { return new FunctionalCommand( () -> hasStraighten = true, () -> { swerveModules[FRONT_LEFT].spinTo(0); swerveModules[FRONT_RIGHT].spinTo(0); swerveModules[BACK_LEFT].spinTo(0); swerveModules[BACK_RIGHT].spinTo(0); }, (__) -> { stopModules(); resetAngleEncoders(); }, swerveModules[FRONT_LEFT].isReset .and(swerveModules[FRONT_RIGHT].isReset) .and(swerveModules[BACK_LEFT].isReset) .and(swerveModules[BACK_RIGHT].isReset), this); } public Command turnToAngleCommand(double setpoint) { return setClosedLoop(true).andThen( driveSwerveCommand( () -> 0, () -> 0, () -> anglePIDcontroller.calculate(getOdometryRotation2d().getDegrees(), setpoint), () -> false).until(new Trigger(anglePIDcontroller::atSetpoint).debounce(0.1)), setClosedLoop(false)); } /** * @param angle * @return returns the pid calculated controller input to rotate the swerve to the desired angle * the returned value should be inserted into the driveCommand instead of the driver's input */ public double getAngleDC(double angle) { System.out.println(getOdometryRotation2d().getDegrees() + " " + angle); return anglePIDcontroller.calculate(getOdometryRotation2d().getDegrees(), angle); } public double getAngleDC() { return getAngleDC(0); } // other methods private void resetAngleEncoders() { foreachModule(SwerveModule::resetEncoders); } private void stopModules() { foreachModule(SwerveModule::stopModule); } public void setModulesStates(SwerveModuleState[] states) { SwerveDriveKinematics.desaturateWheelSpeeds(states, MAX_VELOCITY_METER_PER_SECOND); swerveModules[FRONT_LEFT].setDesiredState(states[FRONT_LEFT]); swerveModules[FRONT_RIGHT].setDesiredState(states[FRONT_RIGHT]); swerveModules[BACK_LEFT].setDesiredState(states[BACK_LEFT]); swerveModules[BACK_RIGHT].setDesiredState(states[BACK_RIGHT]); } public SwerveModulePosition[] getModulesPositions() { return new SwerveModulePosition[]{ swerveModules[0].getPosition(), swerveModules[1].getPosition(), swerveModules[2].getPosition(), swerveModules[3].getPosition(), }; } public SwerveModuleState[] getModulesStates() { return new SwerveModuleState[]{ swerveModules[0].getState(), swerveModules[1].getState(), swerveModules[2].getState(), swerveModules[3].getState(), }; } private void foreachModule(Consumer<SwerveModule> module) { for (int i = 0; i < swerveModules.length; i++) { module.accept(swerveModules[i]); } } public Command toggleIdleModeCommand() { return new StartEndCommand( () -> foreachModule(SwerveModule::setIdleModeCoast), () -> foreachModule(SwerveModule::setIdleModebreak)) .ignoringDisable(true); } public Command setClosedLoop(boolean isCloseLoop) { return new InstantCommand(() -> this.isClosedloop = isCloseLoop); } @Override public void periodic() { odometry.update(getGyroRotation2d(), getModulesPositions()); // localization with PhotonPoseEstimator // Optional<EstimatedRobotPose> pose = limelight.getEstimatedGlobalPose(odometry.getEstimatedPosition()); // if (pose.isPresent()) odometry.addVisionMeasurement(pose.get().estimatedPose.toPose2d(), pose.get().timestampSeconds); // localization with SwervePoseEstimator // if (limelight.getLatestResualt().hasTargets()) limelight.updateFromAprilTagPose(odometry::addVisionMeasurement); field.setRobotPose(odometry.getEstimatedPosition()); SmartDashboard.putData(field); if (DriverStation.isEnabled()) { System.out.println(getPose2d()); System.out.println(xTranslationPIDcontroller.calculate(getPose2d().getX(), 0)); } } // on-the-fly auto generation functions public Command followPath(double endVel, double endDegrees, Pose2d... positions) { return AutoBuilder.followPathWithEvents( new PathPlannerPath( PathPlannerPath.bezierFromPoses(getAlliancePositions(positions)), PATH_CONSTRAINTS, new GoalEndState(endVel, Rotation2d.fromDegrees(endDegrees))) ); } // drives the robot from current location to a given Pose2d public Command pathPlannerToPose(Pose2d position, double endVel) { return new ProxyCommand(() -> followPath(endVel, position.getRotation().getDegrees(), getStraightLinePoses(position.getTranslation())) ); } public Pose2d[] getAlliancePositions(Pose2d... poses) { for (int i = 0; i < poses.length; i++) {
poses[i] = AllianceUtilities.toAlliancePose(poses[i]);
1
2023-12-13 22:33:35+00:00
8k
muchfish/ruoyi-vue-pro-sample
yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/admin/oauth2/OAuth2ClientController.java
[ { "identifier": "CommonResult", "path": "yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/pojo/CommonResult.java", "snippet": "@Data\npublic class CommonResult<T> implements Serializable {\n\n /**\n * 错误码\n *\n * @see ErrorCode#getCode()\n */\n private I...
import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.client.OAuth2ClientCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.client.OAuth2ClientPageReqVO; import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.client.OAuth2ClientRespVO; import cn.iocoder.yudao.module.system.controller.admin.oauth2.vo.client.OAuth2ClientUpdateReqVO; import cn.iocoder.yudao.module.system.convert.auth.OAuth2ClientConvert; import cn.iocoder.yudao.module.system.dal.dataobject.oauth2.OAuth2ClientDO; import cn.iocoder.yudao.module.system.service.oauth2.OAuth2ClientService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.validation.Valid; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
3,875
package cn.iocoder.yudao.module.system.controller.admin.oauth2; @Tag(name = "管理后台 - OAuth2 客户端") @RestController @RequestMapping("/system/oauth2-client") @Validated public class OAuth2ClientController { @Resource private OAuth2ClientService oAuth2ClientService; @PostMapping("/create") @Operation(summary = "创建 OAuth2 客户端") @PreAuthorize("@ss.hasPermission('system:oauth2-client:create')") public CommonResult<Long> createOAuth2Client(@Valid @RequestBody OAuth2ClientCreateReqVO createReqVO) { return success(oAuth2ClientService.createOAuth2Client(createReqVO)); } @PutMapping("/update") @Operation(summary = "更新 OAuth2 客户端") @PreAuthorize("@ss.hasPermission('system:oauth2-client:update')") public CommonResult<Boolean> updateOAuth2Client(@Valid @RequestBody OAuth2ClientUpdateReqVO updateReqVO) { oAuth2ClientService.updateOAuth2Client(updateReqVO); return success(true); } @DeleteMapping("/delete") @Operation(summary = "删除 OAuth2 客户端") @Parameter(name = "id", description = "编号", required = true) @PreAuthorize("@ss.hasPermission('system:oauth2-client:delete')") public CommonResult<Boolean> deleteOAuth2Client(@RequestParam("id") Long id) { oAuth2ClientService.deleteOAuth2Client(id); return success(true); } @GetMapping("/get") @Operation(summary = "获得 OAuth2 客户端") @Parameter(name = "id", description = "编号", required = true, example = "1024") @PreAuthorize("@ss.hasPermission('system:oauth2-client:query')")
package cn.iocoder.yudao.module.system.controller.admin.oauth2; @Tag(name = "管理后台 - OAuth2 客户端") @RestController @RequestMapping("/system/oauth2-client") @Validated public class OAuth2ClientController { @Resource private OAuth2ClientService oAuth2ClientService; @PostMapping("/create") @Operation(summary = "创建 OAuth2 客户端") @PreAuthorize("@ss.hasPermission('system:oauth2-client:create')") public CommonResult<Long> createOAuth2Client(@Valid @RequestBody OAuth2ClientCreateReqVO createReqVO) { return success(oAuth2ClientService.createOAuth2Client(createReqVO)); } @PutMapping("/update") @Operation(summary = "更新 OAuth2 客户端") @PreAuthorize("@ss.hasPermission('system:oauth2-client:update')") public CommonResult<Boolean> updateOAuth2Client(@Valid @RequestBody OAuth2ClientUpdateReqVO updateReqVO) { oAuth2ClientService.updateOAuth2Client(updateReqVO); return success(true); } @DeleteMapping("/delete") @Operation(summary = "删除 OAuth2 客户端") @Parameter(name = "id", description = "编号", required = true) @PreAuthorize("@ss.hasPermission('system:oauth2-client:delete')") public CommonResult<Boolean> deleteOAuth2Client(@RequestParam("id") Long id) { oAuth2ClientService.deleteOAuth2Client(id); return success(true); } @GetMapping("/get") @Operation(summary = "获得 OAuth2 客户端") @Parameter(name = "id", description = "编号", required = true, example = "1024") @PreAuthorize("@ss.hasPermission('system:oauth2-client:query')")
public CommonResult<OAuth2ClientRespVO> getOAuth2Client(@RequestParam("id") Long id) {
4
2023-12-08 02:48:42+00:00
8k
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;
7,087
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
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;
4
2023-12-05 22:19:00+00:00
8k
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;
5,993
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; }
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) ||
12
2023-12-07 16:34:39+00:00
8k
Khoshimjonov/SalahTimes
src/main/java/uz/khoshimjonov/widget/SettingsWindow.java
[ { "identifier": "Api", "path": "src/main/java/uz/khoshimjonov/api/Api.java", "snippet": "public class Api {\n private static final String AL_ADHAN_URL = \"https://api.aladhan.com/v1/timings/%s?school=%s&method=%s&latitude=%s&longitude=%s\";\n private static final String NOMINATIM_URL = \"https://n...
import uz.khoshimjonov.api.Api; import uz.khoshimjonov.dto.MethodEnum; import uz.khoshimjonov.dto.NominatimResponse; import uz.khoshimjonov.service.ConfigurationManager; import uz.khoshimjonov.service.LanguageHelper; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.text.NumberFormatter; import java.awt.*; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.NumberFormat; import java.util.Arrays; import java.util.List; import java.util.Objects;
3,939
package uz.khoshimjonov.widget; public class SettingsWindow extends JFrame { private final ConfigurationManager configManager; private final Api api = new Api(); private final JRadioButton shafiRadioButton; private final JRadioButton hanafiRadioButton; private final JTextField addressTextField; private final JLabel addressLabel; private final JTextField latitudeTextField; private final JTextField longitudeTextField; private final JComboBox<String> methodComboBox; private final JComboBox<String> languageComboBox; private final JFormattedTextField updateIntervalField; private final JFormattedTextField notificationBeforeField; private final JCheckBox notificationsCheckBox; private final JCheckBox lookAndFeelCheckBox; private final JCheckBox draggableCheckBox; private final JCheckBox alwaysOnTopCheckBox; public SettingsWindow() { this.configManager = ConfigurationManager.getInstance();
package uz.khoshimjonov.widget; public class SettingsWindow extends JFrame { private final ConfigurationManager configManager; private final Api api = new Api(); private final JRadioButton shafiRadioButton; private final JRadioButton hanafiRadioButton; private final JTextField addressTextField; private final JLabel addressLabel; private final JTextField latitudeTextField; private final JTextField longitudeTextField; private final JComboBox<String> methodComboBox; private final JComboBox<String> languageComboBox; private final JFormattedTextField updateIntervalField; private final JFormattedTextField notificationBeforeField; private final JCheckBox notificationsCheckBox; private final JCheckBox lookAndFeelCheckBox; private final JCheckBox draggableCheckBox; private final JCheckBox alwaysOnTopCheckBox; public SettingsWindow() { this.configManager = ConfigurationManager.getInstance();
setTitle(LanguageHelper.getText("settingsTitle"));
4
2023-12-07 13:40:16+00:00
8k
Akshar062/MovieReviews
app/src/main/java/com/akshar/moviereviews/adapters/PersonAdapter.java
[ { "identifier": "MainActivity", "path": "app/src/main/java/com/akshar/moviereviews/MainActivity.java", "snippet": "public class MainActivity extends AppCompatActivity {\n\n //Define parameters here\n private ViewPager viewPager;\n private BottomNavigationView bottomNavigationView;\n\n\n @Ove...
import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import androidx.fragment.app.FragmentTransaction; import androidx.recyclerview.widget.RecyclerView; import com.akshar.moviereviews.MainActivity; import com.akshar.moviereviews.Models.PeopleModel; import com.akshar.moviereviews.R; import com.akshar.moviereviews.Utils.Constants; import com.akshar.moviereviews.Utils.GenreHelper; import com.akshar.moviereviews.fragments.DetailsFragment; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; import java.util.Map;
3,748
package com.akshar.moviereviews.adapters; public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.PersonViewHolder> { private Context context; private List<PeopleModel.Person> resultList; public PersonAdapter(Context context, List<PeopleModel.Person> resultList) { this.context = context; this.resultList = resultList; } @NonNull @Override public PersonViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.card_item, parent, false); return new PersonViewHolder(view); } @Override public void onBindViewHolder(@NonNull PersonViewHolder holder, int position) { PeopleModel.Person result = resultList.get(position); holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showDetailsDialog(result); } }); holder.progressBar.setVisibility(View.VISIBLE); holder.movieName.setText(result.getName()); holder.movieReleaseDate.setText(result.getKnownForDepartment()); holder.movieRating.setText(String.valueOf(result.getPopularity())); setImage(holder,result.getProfilePath()); } private void showDetailsDialog(PeopleModel.Person result) { List<PeopleModel.Person.KnownFor> knownForList = result.getKnownFor(); DetailsFragment detailsFragment = new DetailsFragment(); // Pass data to the fragment using Bundle Bundle bundle = new Bundle(); bundle.putString("title", result.getName()); bundle.putString("releaseDate", result.getKnownForDepartment()); bundle.putString("posterPath", result.getProfilePath()); bundle.putString("overview", knownForList.get(0).getOverview()); List<Integer> personGenreIds = knownForList.get(0).getGenreIds(); String mediaType = knownForList.get(0).getMediaType(); if ("movie".equals(mediaType)) {
package com.akshar.moviereviews.adapters; public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.PersonViewHolder> { private Context context; private List<PeopleModel.Person> resultList; public PersonAdapter(Context context, List<PeopleModel.Person> resultList) { this.context = context; this.resultList = resultList; } @NonNull @Override public PersonViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.card_item, parent, false); return new PersonViewHolder(view); } @Override public void onBindViewHolder(@NonNull PersonViewHolder holder, int position) { PeopleModel.Person result = resultList.get(position); holder.cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showDetailsDialog(result); } }); holder.progressBar.setVisibility(View.VISIBLE); holder.movieName.setText(result.getName()); holder.movieReleaseDate.setText(result.getKnownForDepartment()); holder.movieRating.setText(String.valueOf(result.getPopularity())); setImage(holder,result.getProfilePath()); } private void showDetailsDialog(PeopleModel.Person result) { List<PeopleModel.Person.KnownFor> knownForList = result.getKnownFor(); DetailsFragment detailsFragment = new DetailsFragment(); // Pass data to the fragment using Bundle Bundle bundle = new Bundle(); bundle.putString("title", result.getName()); bundle.putString("releaseDate", result.getKnownForDepartment()); bundle.putString("posterPath", result.getProfilePath()); bundle.putString("overview", knownForList.get(0).getOverview()); List<Integer> personGenreIds = knownForList.get(0).getGenreIds(); String mediaType = knownForList.get(0).getMediaType(); if ("movie".equals(mediaType)) {
List<String> personGenres = getGenresAsString(personGenreIds, GenreHelper.getAllMovieGenres());
3
2023-12-05 10:20:16+00:00
8k
fabriciofx/cactoos-pdf
src/main/java/com/github/fabriciofx/cactoos/pdf/content/Image.java
[ { "identifier": "Content", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/Content.java", "snippet": "@SuppressWarnings(\"PMD.ExtendsObject\")\npublic interface Content extends Object {\n /**\n * Stream of a content.\n *\n * @return The stream content\n * @throws Exception if...
import com.github.fabriciofx.cactoos.pdf.type.Dictionary; import com.github.fabriciofx.cactoos.pdf.type.Int; import com.github.fabriciofx.cactoos.pdf.type.Stream; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Locale; import org.cactoos.list.ListOf; import org.cactoos.text.FormattedText; import org.cactoos.text.UncheckedText; import com.github.fabriciofx.cactoos.pdf.Content; import com.github.fabriciofx.cactoos.pdf.Id; import com.github.fabriciofx.cactoos.pdf.Indirect; import com.github.fabriciofx.cactoos.pdf.Resource; import com.github.fabriciofx.cactoos.pdf.image.Format; import com.github.fabriciofx.cactoos.pdf.indirect.DefaultIndirect; import com.github.fabriciofx.cactoos.pdf.resource.XObject;
3,693
/* * 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.content; /** * Image. * * @since 0.0.1 */ public final class Image implements Content { /** * Object number. */ private final int number; /** * Generation number. */ private final int generation; /** * Resource. */
/* * 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.content; /** * Image. * * @since 0.0.1 */ public final class Image implements Content { /** * Object number. */ private final int number; /** * Generation number. */ private final int generation; /** * Resource. */
private final Resource resrc;
3
2023-12-05 00:07:24+00:00
8k
IzanagiCraft/message-format
src/main/java/com/izanagicraft/messages/translations/TranslationHandler.java
[ { "identifier": "MessagePlaceholderHandler", "path": "src/main/java/com/izanagicraft/messages/placeholders/MessagePlaceholderHandler.java", "snippet": "public class MessagePlaceholderHandler {\n\n private Map<String, Object> defaultReplacements;\n\n /**\n * Constructs a new MessagePlaceholderH...
import com.izanagicraft.messages.placeholders.MessagePlaceholderHandler; import com.izanagicraft.messages.placeholders.StaticMessagePlaceholders; import com.izanagicraft.messages.strings.WrappedString; import java.io.File; import java.io.FileInputStream; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap;
4,032
/* * ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄ * ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██ * ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪ * ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌· * ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀ * * * @@@@@ * @@* *@@ * @@@ @@@ * @@@ @@ @@@ @@@@@@@@@@@ * @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ * @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@ @@ @@ @@@@ @@@@ * @@@@ @@@ @@@@ @@@@ @@@ * @@@@@@ @@@@@@ @@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@ * * 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.messages.translations; /** * message-format; com.izanagicraft.messages.translations:TranslationHandler * <p> * Utility class for handling translations with placeholders. * <p> * The {@code TranslationHandler} class provides methods to manage translations * for different locales with support for placeholders. * <p> * Example usage: * <pre> * {@code * TranslationHandler translations = new TranslationHandler(); * translations.init(new File("en_US.properties"), new File("es_ES.properties")); * String translatedText = translations.translate("greeting", "John"); * } * </pre> * <p> * Note: The class follows the singleton pattern, and instances should * be created using the provided constructors or by calling the {@code init} method. * <p> * This class is not meant to be instantiated directly; instead, use the provided * constructors or the {@code init} method to initialize the translations. * * @author <a href="https://github.com/LuciferMorningstarDev">LuciferMorningstarDev</a> * @since 13.12.2023 */ public class TranslationHandler { private MessagePlaceholderHandler placeholderHandler = new MessagePlaceholderHandler(); /** * A map that stores translations for different locales. * The keys are locale codes, and the values are Properties objects containing translations. */ private Map<String, Properties> translations = new ConcurrentHashMap<>(); /** * The fallback Properties object used when a translation is not available for a specific locale. */ private Properties fallback; /** * Default constructor for the Translations class. * <p> * Creates an instance of the Translations class without initializing translations. * To initialize translations, use the {@code init} method. */ public TranslationHandler() { // Empty constructor } /** * Constructor for the Translations class with language properties files. * <p> * Creates an instance of the Translations class and initializes translations * using the provided language properties files. * * @param files Language properties files to load. */ public TranslationHandler(File... files) { init(null, files); } /** * Constructor for the Translations class with default replacements and language properties files. * <p> * Creates an instance of the Translations class and initializes translations * using the provided default replacements and language properties files. * * @param defaultReplacements Default replacement map for placeholders. * @param files Language properties files to load. */ public TranslationHandler(Map<String, Object> defaultReplacements, File... files) { init(defaultReplacements, files); } /** * Gets the map of translations for different locales. * * @return The map of translations with locale codes as keys and Properties objects as values. */ public Map<String, Properties> getTranslations() { return translations; } /** * Gets the fallback Properties object. * * @return The fallback Properties object. */ public Properties getFallback() { return fallback; } /** * Gets the default replacements used by the Formatter for placeholder substitution. * * @return A map of default replacements with String keys and Object values. * These replacements are used by the {@link StaticMessagePlaceholders} class during text formatting. */ public Map<String, Object> getDefaultReplacements() { return StaticMessagePlaceholders.getDefaultReplacements(); } /** * Load language properties from a file and process them. * * @param properties The properties object to load into. * @param file The file to load properties from. */ void loadLang(Properties properties, File file) { try (FileInputStream fileInputStream = new FileInputStream(file)) { properties.load(fileInputStream); // Iterate through the loaded properties and modify the values as needed for (String propName : properties.stringPropertyNames()) { String propValue = properties.getProperty(propName); if (!propValue.startsWith("'")) continue; // Remove single quotes from the property value propValue = propValue.replace("'", ""); properties.setProperty(propName, propValue); } } catch (Exception e) { e.printStackTrace(); } } /** * Initialize the translations with default replacements and language files. * * @param files Language properties files to load. */ public void init(File... files) { init(null, files); } /** * Initialize the translations with default replacements and language files. * * @param defaultReplacements Default replacement map for placeholders. * @param files Language properties files to load. */ public void init(Map<String, Object> defaultReplacements, File... files) { StaticMessagePlaceholders.addDefaultReplacements(defaultReplacements); // Load each language properties file for (File file : files) { // Skip directories, only process individual files if (file.isDirectory()) continue; // Get the name of the current file String fileName = file.getName(); if (fileName.contains("platform")) continue; // Create a new properties object to store language data Properties properties = new Properties(); // Extract the language name from the file name String langName = fileName.substring(0, fileName.lastIndexOf('.')); // Check if the file is a language properties file and not a platform-specific one if (fileName.endsWith(".properties")) { // Load language properties from the file loadLang(properties, file); } // If the file is not a valid language properties file, continue to the next iteration else continue; // Add the loaded language properties to the translations map translations.put(langName, properties); if (fallback == null) { fallback = new Properties(); fallback = properties; } } // Set the default fallback properties based on the system's default locale if (translations.containsKey(Locale.getDefault().getLanguage())) { fallback = translations.get(Locale.getDefault().getLanguage()); } } /** * Translate a key using default replacements and fallback properties. * * @param key The translation key. * @param args Arguments for placeholders. * @return Translated and formatted text. */ public String translate(String key, Object... args) { Map<String, Object> replace = new HashMap<>(getDefaultReplacements()); for (int i = 0; i < args.length; i++) { replace.put("" + i, args[i]); } return placeholderHandler.fastFormat(fallback.getProperty(key, key), replace); } /** * Translate a key using default replacements and fallback properties. * * @param key The translation key. * @param args Arguments for placeholders. * @return Translated and formatted text. */ public String translate(String key, String... args) { Map<String, Object> replace = new HashMap<>(getDefaultReplacements()); for (int i = 0; i < args.length; i++) { replace.put("" + i, args[i]); } return placeholderHandler.fastFormat(fallback.getProperty(key, key), replace); } /** * Translate a key using default replacements and fallback properties. * * @param key The translation key. * @return Translated and formatted text. */ public String translate(String key) { return placeholderHandler.fastFormat(fallback.getProperty(key, key), getDefaultReplacements()); } /** * Translate a key using default replacements and fallback properties. * * @param locale The locale to translate in. * @param key The translation key. * @param args Arguments for placeholders. * @return Translated and formatted text. */ public String translate(Locale locale, String key, Object... args) { if (!translations.containsKey(locale.getLanguage())) return translate(key, args); Map<String, Object> replace = new HashMap<>(getDefaultReplacements()); for (int i = 0; i < args.length; i++) { replace.put("" + i, args[i]); } return placeholderHandler.fastFormat(translations.get(locale.getLanguage()).getProperty(key, key), replace); } /** * Translate a key using default replacements and fallback properties. * * @param locale The locale to translate in. * @param key The translation key. * @param args Arguments for placeholders. * @return Translated and formatted text. */ public String translate(Locale locale, String key, String... args) { if (!translations.containsKey(locale.getLanguage())) return translate(key, args); Map<String, Object> replace = new HashMap<>(getDefaultReplacements()); for (int i = 0; i < args.length; i++) { replace.put("" + i, args[i]); } return placeholderHandler.fastFormat(translations.get(locale.getLanguage()).getProperty(key, key), replace); } /** * Translate a key using default replacements and fallback properties. * * @param locale The locale to translate in. * @param key The translation key. * @return Translated and formatted text. */ public String translate(Locale locale, String key) { if (!translations.containsKey(locale.getLanguage())) return translate(key); return placeholderHandler.fastFormat(translations.get(locale.getLanguage()).getProperty(key, key), getDefaultReplacements()); } /** * Translate a key using default replacements and fallback properties. * * @param langName The language name to translate in. * @param key The translation key. * @param args Arguments for placeholders. * @return Translated and formatted text. */
/* * ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄ * ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██ * ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪ * ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌· * ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀ * * * @@@@@ * @@* *@@ * @@@ @@@ * @@@ @@ @@@ @@@@@@@@@@@ * @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ * @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@ @@ @@ @@@@ @@@@ * @@@@ @@@ @@@@ @@@@ @@@ * @@@@@@ @@@@@@ @@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@ * * 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.messages.translations; /** * message-format; com.izanagicraft.messages.translations:TranslationHandler * <p> * Utility class for handling translations with placeholders. * <p> * The {@code TranslationHandler} class provides methods to manage translations * for different locales with support for placeholders. * <p> * Example usage: * <pre> * {@code * TranslationHandler translations = new TranslationHandler(); * translations.init(new File("en_US.properties"), new File("es_ES.properties")); * String translatedText = translations.translate("greeting", "John"); * } * </pre> * <p> * Note: The class follows the singleton pattern, and instances should * be created using the provided constructors or by calling the {@code init} method. * <p> * This class is not meant to be instantiated directly; instead, use the provided * constructors or the {@code init} method to initialize the translations. * * @author <a href="https://github.com/LuciferMorningstarDev">LuciferMorningstarDev</a> * @since 13.12.2023 */ public class TranslationHandler { private MessagePlaceholderHandler placeholderHandler = new MessagePlaceholderHandler(); /** * A map that stores translations for different locales. * The keys are locale codes, and the values are Properties objects containing translations. */ private Map<String, Properties> translations = new ConcurrentHashMap<>(); /** * The fallback Properties object used when a translation is not available for a specific locale. */ private Properties fallback; /** * Default constructor for the Translations class. * <p> * Creates an instance of the Translations class without initializing translations. * To initialize translations, use the {@code init} method. */ public TranslationHandler() { // Empty constructor } /** * Constructor for the Translations class with language properties files. * <p> * Creates an instance of the Translations class and initializes translations * using the provided language properties files. * * @param files Language properties files to load. */ public TranslationHandler(File... files) { init(null, files); } /** * Constructor for the Translations class with default replacements and language properties files. * <p> * Creates an instance of the Translations class and initializes translations * using the provided default replacements and language properties files. * * @param defaultReplacements Default replacement map for placeholders. * @param files Language properties files to load. */ public TranslationHandler(Map<String, Object> defaultReplacements, File... files) { init(defaultReplacements, files); } /** * Gets the map of translations for different locales. * * @return The map of translations with locale codes as keys and Properties objects as values. */ public Map<String, Properties> getTranslations() { return translations; } /** * Gets the fallback Properties object. * * @return The fallback Properties object. */ public Properties getFallback() { return fallback; } /** * Gets the default replacements used by the Formatter for placeholder substitution. * * @return A map of default replacements with String keys and Object values. * These replacements are used by the {@link StaticMessagePlaceholders} class during text formatting. */ public Map<String, Object> getDefaultReplacements() { return StaticMessagePlaceholders.getDefaultReplacements(); } /** * Load language properties from a file and process them. * * @param properties The properties object to load into. * @param file The file to load properties from. */ void loadLang(Properties properties, File file) { try (FileInputStream fileInputStream = new FileInputStream(file)) { properties.load(fileInputStream); // Iterate through the loaded properties and modify the values as needed for (String propName : properties.stringPropertyNames()) { String propValue = properties.getProperty(propName); if (!propValue.startsWith("'")) continue; // Remove single quotes from the property value propValue = propValue.replace("'", ""); properties.setProperty(propName, propValue); } } catch (Exception e) { e.printStackTrace(); } } /** * Initialize the translations with default replacements and language files. * * @param files Language properties files to load. */ public void init(File... files) { init(null, files); } /** * Initialize the translations with default replacements and language files. * * @param defaultReplacements Default replacement map for placeholders. * @param files Language properties files to load. */ public void init(Map<String, Object> defaultReplacements, File... files) { StaticMessagePlaceholders.addDefaultReplacements(defaultReplacements); // Load each language properties file for (File file : files) { // Skip directories, only process individual files if (file.isDirectory()) continue; // Get the name of the current file String fileName = file.getName(); if (fileName.contains("platform")) continue; // Create a new properties object to store language data Properties properties = new Properties(); // Extract the language name from the file name String langName = fileName.substring(0, fileName.lastIndexOf('.')); // Check if the file is a language properties file and not a platform-specific one if (fileName.endsWith(".properties")) { // Load language properties from the file loadLang(properties, file); } // If the file is not a valid language properties file, continue to the next iteration else continue; // Add the loaded language properties to the translations map translations.put(langName, properties); if (fallback == null) { fallback = new Properties(); fallback = properties; } } // Set the default fallback properties based on the system's default locale if (translations.containsKey(Locale.getDefault().getLanguage())) { fallback = translations.get(Locale.getDefault().getLanguage()); } } /** * Translate a key using default replacements and fallback properties. * * @param key The translation key. * @param args Arguments for placeholders. * @return Translated and formatted text. */ public String translate(String key, Object... args) { Map<String, Object> replace = new HashMap<>(getDefaultReplacements()); for (int i = 0; i < args.length; i++) { replace.put("" + i, args[i]); } return placeholderHandler.fastFormat(fallback.getProperty(key, key), replace); } /** * Translate a key using default replacements and fallback properties. * * @param key The translation key. * @param args Arguments for placeholders. * @return Translated and formatted text. */ public String translate(String key, String... args) { Map<String, Object> replace = new HashMap<>(getDefaultReplacements()); for (int i = 0; i < args.length; i++) { replace.put("" + i, args[i]); } return placeholderHandler.fastFormat(fallback.getProperty(key, key), replace); } /** * Translate a key using default replacements and fallback properties. * * @param key The translation key. * @return Translated and formatted text. */ public String translate(String key) { return placeholderHandler.fastFormat(fallback.getProperty(key, key), getDefaultReplacements()); } /** * Translate a key using default replacements and fallback properties. * * @param locale The locale to translate in. * @param key The translation key. * @param args Arguments for placeholders. * @return Translated and formatted text. */ public String translate(Locale locale, String key, Object... args) { if (!translations.containsKey(locale.getLanguage())) return translate(key, args); Map<String, Object> replace = new HashMap<>(getDefaultReplacements()); for (int i = 0; i < args.length; i++) { replace.put("" + i, args[i]); } return placeholderHandler.fastFormat(translations.get(locale.getLanguage()).getProperty(key, key), replace); } /** * Translate a key using default replacements and fallback properties. * * @param locale The locale to translate in. * @param key The translation key. * @param args Arguments for placeholders. * @return Translated and formatted text. */ public String translate(Locale locale, String key, String... args) { if (!translations.containsKey(locale.getLanguage())) return translate(key, args); Map<String, Object> replace = new HashMap<>(getDefaultReplacements()); for (int i = 0; i < args.length; i++) { replace.put("" + i, args[i]); } return placeholderHandler.fastFormat(translations.get(locale.getLanguage()).getProperty(key, key), replace); } /** * Translate a key using default replacements and fallback properties. * * @param locale The locale to translate in. * @param key The translation key. * @return Translated and formatted text. */ public String translate(Locale locale, String key) { if (!translations.containsKey(locale.getLanguage())) return translate(key); return placeholderHandler.fastFormat(translations.get(locale.getLanguage()).getProperty(key, key), getDefaultReplacements()); } /** * Translate a key using default replacements and fallback properties. * * @param langName The language name to translate in. * @param key The translation key. * @param args Arguments for placeholders. * @return Translated and formatted text. */
public String translate(WrappedString langName, String key, Object... args) {
2
2023-12-13 02:31:22+00:00
8k
ibm-messaging/kafka-connect-xml-converter
src/main/java/com/ibm/eventstreams/kafkaconnect/plugins/xml/XmlTransformation.java
[ { "identifier": "CollectionToXmlBytes", "path": "src/main/java/com/ibm/eventstreams/kafkaconnect/plugins/xml/engines/CollectionToXmlBytes.java", "snippet": "public class CollectionToXmlBytes extends ToXmlBytes {\n\n private final Logger log = LoggerFactory.getLogger(CollectionToXmlBytes.class);\n\n ...
import com.ibm.eventstreams.kafkaconnect.plugins.xml.engines.CollectionToXmlBytes; import com.ibm.eventstreams.kafkaconnect.plugins.xml.engines.StructToXmlBytes; import com.ibm.eventstreams.kafkaconnect.plugins.xml.engines.XmlBytesToStruct; import com.ibm.eventstreams.kafkaconnect.plugins.xml.exceptions.NotImplementedException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.connect.connector.ConnectRecord; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.connect.data.SchemaAndValue; import org.apache.kafka.connect.data.Struct; import org.apache.kafka.connect.storage.ConverterConfig; import org.apache.kafka.connect.storage.ConverterType; import org.apache.kafka.connect.transforms.Transformation; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
6,197
/** * Copyright 2023 IBM Corp. All Rights Reserved. * * 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.ibm.eventstreams.kafkaconnect.plugins.xml; public class XmlTransformation<R extends ConnectRecord<R>> implements Transformation<R> { private final Logger log = LoggerFactory.getLogger(XmlTransformation.class); private XmlPluginsConfig config;
/** * Copyright 2023 IBM Corp. All Rights Reserved. * * 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.ibm.eventstreams.kafkaconnect.plugins.xml; public class XmlTransformation<R extends ConnectRecord<R>> implements Transformation<R> { private final Logger log = LoggerFactory.getLogger(XmlTransformation.class); private XmlPluginsConfig config;
private XmlBytesToStruct xmlToStruct = null;
2
2023-12-11 13:56:48+00:00
8k
BeansGalaxy/Beans-Backpacks-2
common/src/main/java/com/beansgalaxy/backpacks/mixin/client/UpdateSprintKey.java
[ { "identifier": "Tooltip", "path": "common/src/main/java/com/beansgalaxy/backpacks/items/Tooltip.java", "snippet": "public class Tooltip {\n\n protected static Optional<TooltipComponent> get(ItemStack stack) {\n Player player = Minecraft.getInstance().player;\n if (player == n...
import com.beansgalaxy.backpacks.items.Tooltip; import com.beansgalaxy.backpacks.platform.Services; import com.beansgalaxy.backpacks.screen.BackSlot; import com.mojang.blaze3d.platform.InputConstants; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
5,333
package com.beansgalaxy.backpacks.mixin.client; @Mixin(LocalPlayer.class) public class UpdateSprintKey { @Inject(method = "tick", at = @At("TAIL")) public void tick(CallbackInfo ci) { LocalPlayer localPlayer = (LocalPlayer) (Object) this; long clientWindowHandle = Minecraft.getInstance().getWindow().getWindow(); String keyName = Tooltip.getKeyBinding().saveString(); int keyCode = InputConstants.getKey(keyName).getValue(); boolean actionKeyPressed = InputConstants.isKeyDown(clientWindowHandle, keyCode); boolean actionKeyPrevious = BackSlot.get(localPlayer).actionKeyPressed; if (actionKeyPressed != actionKeyPrevious) { BackSlot.get(localPlayer).actionKeyPressed = actionKeyPressed;
package com.beansgalaxy.backpacks.mixin.client; @Mixin(LocalPlayer.class) public class UpdateSprintKey { @Inject(method = "tick", at = @At("TAIL")) public void tick(CallbackInfo ci) { LocalPlayer localPlayer = (LocalPlayer) (Object) this; long clientWindowHandle = Minecraft.getInstance().getWindow().getWindow(); String keyName = Tooltip.getKeyBinding().saveString(); int keyCode = InputConstants.getKey(keyName).getValue(); boolean actionKeyPressed = InputConstants.isKeyDown(clientWindowHandle, keyCode); boolean actionKeyPrevious = BackSlot.get(localPlayer).actionKeyPressed; if (actionKeyPressed != actionKeyPrevious) { BackSlot.get(localPlayer).actionKeyPressed = actionKeyPressed;
Services.NETWORK.SprintKey(actionKeyPressed);
1
2023-12-14 21:55:00+00:00
8k
CADIndie/Scout
src/main/java/pm/c7/scout/mixin/ServerPlayerEntityMixin.java
[ { "identifier": "ScoutNetworking", "path": "src/main/java/pm/c7/scout/ScoutNetworking.java", "snippet": "public class ScoutNetworking {\n public static final Identifier ENABLE_SLOTS = new Identifier(Scout.MOD_ID, \"enable_slots\");\n}" }, { "identifier": "ScoutPlayerScreenHandler", "path"...
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import io.netty.buffer.Unpooled; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.entity.damage.DamageSource; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketByteBuf; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.util.collection.DefaultedList; import net.minecraft.world.GameRules; import pm.c7.scout.ScoutNetworking; import pm.c7.scout.ScoutPlayerScreenHandler; import pm.c7.scout.ScoutUtil; import pm.c7.scout.item.BaseBagItem; import pm.c7.scout.item.BaseBagItem.BagType; import pm.c7.scout.screen.BagSlot;
3,956
package pm.c7.scout.mixin; @SuppressWarnings("deprecation") @Mixin(ServerPlayerEntity.class) public class ServerPlayerEntityMixin { @Inject(method = "onDeath", at = @At("HEAD")) private void scout$attemptFixGraveMods(DamageSource source, CallbackInfo callbackInfo) { ServerPlayerEntity player = (ServerPlayerEntity) (Object) this; ScoutPlayerScreenHandler handler = (ScoutPlayerScreenHandler) player.playerScreenHandler; if (!player.world.getGameRules().getBoolean(GameRules.KEEP_INVENTORY)) { ItemStack backStack = ScoutUtil.findBagItem(player, BagType.SATCHEL, false); if (!backStack.isEmpty()) { BaseBagItem bagItem = (BaseBagItem) backStack.getItem(); int slots = bagItem.getSlotCount();
package pm.c7.scout.mixin; @SuppressWarnings("deprecation") @Mixin(ServerPlayerEntity.class) public class ServerPlayerEntityMixin { @Inject(method = "onDeath", at = @At("HEAD")) private void scout$attemptFixGraveMods(DamageSource source, CallbackInfo callbackInfo) { ServerPlayerEntity player = (ServerPlayerEntity) (Object) this; ScoutPlayerScreenHandler handler = (ScoutPlayerScreenHandler) player.playerScreenHandler; if (!player.world.getGameRules().getBoolean(GameRules.KEEP_INVENTORY)) { ItemStack backStack = ScoutUtil.findBagItem(player, BagType.SATCHEL, false); if (!backStack.isEmpty()) { BaseBagItem bagItem = (BaseBagItem) backStack.getItem(); int slots = bagItem.getSlotCount();
DefaultedList<BagSlot> bagSlots = handler.scout$getSatchelSlots();
5
2023-12-10 07:43:34+00:00
8k
Viola-Siemens/Mod-Whitelist
src/main/java/com/hexagram2021/mod_whitelist/mixin/ServerHandshakePacketListenerImplMixin.java
[ { "identifier": "IPacketWithModIds", "path": "src/main/java/com/hexagram2021/mod_whitelist/common/network/IPacketWithModIds.java", "snippet": "public interface IPacketWithModIds {\n\t@Nullable\n\tList<String> getModIds();\n\n\t@SuppressWarnings(\"unused\")\n\tvoid setModIds(@Nullable List<String> modIds...
import com.hexagram2021.mod_whitelist.common.network.IPacketWithModIds; import com.hexagram2021.mod_whitelist.server.config.MWServerConfig; import com.hexagram2021.mod_whitelist.server.config.MismatchType; import net.minecraft.network.Connection; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.protocol.handshake.ClientIntentionPacket; import net.minecraft.network.protocol.login.ClientboundLoginDisconnectPacket; import net.minecraft.server.network.ServerHandshakePacketListenerImpl; import org.apache.commons.lang3.tuple.Pair; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.List;
3,911
package com.hexagram2021.mod_whitelist.mixin; @Mixin(ServerHandshakePacketListenerImpl.class) public class ServerHandshakePacketListenerImplMixin { @Shadow @Final private Connection connection; @Inject(method = "handleIntention", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/Connection;setProtocol(Lnet/minecraft/network/ConnectionProtocol;)V", shift = At.Shift.AFTER, ordinal = 0), cancellable = true) private void tryDisconnectPlayersIfModlistNotMatches(ClientIntentionPacket clientIntentionPacket, CallbackInfo ci) { MutableComponent reason = null; if(clientIntentionPacket instanceof IPacketWithModIds packetWithModIds && packetWithModIds.getModIds() != null) {
package com.hexagram2021.mod_whitelist.mixin; @Mixin(ServerHandshakePacketListenerImpl.class) public class ServerHandshakePacketListenerImplMixin { @Shadow @Final private Connection connection; @Inject(method = "handleIntention", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/Connection;setProtocol(Lnet/minecraft/network/ConnectionProtocol;)V", shift = At.Shift.AFTER, ordinal = 0), cancellable = true) private void tryDisconnectPlayersIfModlistNotMatches(ClientIntentionPacket clientIntentionPacket, CallbackInfo ci) { MutableComponent reason = null; if(clientIntentionPacket instanceof IPacketWithModIds packetWithModIds && packetWithModIds.getModIds() != null) {
List<Pair<String, MismatchType>> mismatches = MWServerConfig.test(packetWithModIds.getModIds());
1
2023-12-06 12:16:52+00:00
8k
sinbad-navigator/erp-crm
auth/src/main/java/com/ec/auth/aspectj/RateLimiterAspect.java
[ { "identifier": "LimitType", "path": "common/src/main/java/com/ec/common/enums/LimitType.java", "snippet": "public enum LimitType {\n /**\n * 默认策略全局限流\n */\n DEFAULT,\n\n /**\n * 根据请求者IP进行限流\n */\n IP\n}" }, { "identifier": "ServiceException", "path": "common/src/...
import java.lang.reflect.Method; import java.util.Collections; import java.util.List; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.script.RedisScript; import org.springframework.stereotype.Component; import com.ec.common.annotation.RateLimiter; import com.ec.common.enums.LimitType; import com.ec.common.exception.ServiceException; import com.ec.common.utils.ServletUtils; import com.ec.common.utils.StringUtils; import com.ec.common.utils.ip.IpUtils;
6,687
package com.ec.auth.aspectj; /** * 限流处理 * * @author ec */ @Aspect @Component public class RateLimiterAspect { private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class); private RedisTemplate<Object, Object> redisTemplate; private RedisScript<Long> limitScript; @Autowired public void setRedisTemplate1(RedisTemplate<Object, Object> redisTemplate) { this.redisTemplate = redisTemplate; } @Autowired public void setLimitScript(RedisScript<Long> limitScript) { this.limitScript = limitScript; } @Before("@annotation(rateLimiter)") public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable { String key = rateLimiter.key(); int time = rateLimiter.time(); int count = rateLimiter.count(); String combineKey = getCombineKey(rateLimiter, point); List<Object> keys = Collections.singletonList(combineKey); try { Long number = redisTemplate.execute(limitScript, keys, count, time);
package com.ec.auth.aspectj; /** * 限流处理 * * @author ec */ @Aspect @Component public class RateLimiterAspect { private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class); private RedisTemplate<Object, Object> redisTemplate; private RedisScript<Long> limitScript; @Autowired public void setRedisTemplate1(RedisTemplate<Object, Object> redisTemplate) { this.redisTemplate = redisTemplate; } @Autowired public void setLimitScript(RedisScript<Long> limitScript) { this.limitScript = limitScript; } @Before("@annotation(rateLimiter)") public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable { String key = rateLimiter.key(); int time = rateLimiter.time(); int count = rateLimiter.count(); String combineKey = getCombineKey(rateLimiter, point); List<Object> keys = Collections.singletonList(combineKey); try { Long number = redisTemplate.execute(limitScript, keys, count, time);
if (StringUtils.isNull(number) || number.intValue() > count) {
3
2023-12-07 14:23:12+00:00
8k
FRC8806/frcBT_2023
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "ChangPipeLine", "path": "src/main/java/frc/robot/commands/ChangPipeLine.java", "snippet": "public class ChangPipeLine extends CommandBase {\n Limelight limelight;\n int pipeLine;\n\n public ChangPipeLine(Limelight limelight, int pipeLine) {\n this.limelight = limelight;\n this....
import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.button.Trigger; import frc.robot.commands.ChangPipeLine; import frc.robot.commands.TeleSwerveControl; import frc.robot.commands.auto.AprilTagTracking; import frc.robot.commands.auto.AutoMap; import frc.robot.constants.ControllerConstants; import frc.robot.subsystems.Limelight; import frc.robot.subsystems.chassis.DriveTrain;
3,645
// ___________ // 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ___________ // 88 88 88 88 00 00 66 // 88 88 88 88 00 00 66 ________________________ // 88 88 88 88 00 00 66 // 8888888888888888 8888888888888888 00 00 6666666666666666 _____________ // 88 88 88 88 00 00 66 66 // 88 88 88 88 00 00 66 66 _____________________ // 88 88 88 88 00 00 66 66 ________________________ // 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ____________________ // __________________________ __________ package frc.robot; public class RobotContainer { // instantiate controller here public static XboxController driverController = new XboxController(ControllerConstants.DRIVER_CONTROLLER_PORT); public static XboxController operaterController = new XboxController(ControllerConstants.OPERATER_CONTROLLER_PORT); // instantiate subsystem here public static DriveTrain driveTrain = new DriveTrain(); public static Limelight limelight = new Limelight("limelight-front"); // instantiate command here
// ___________ // 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ___________ // 88 88 88 88 00 00 66 // 88 88 88 88 00 00 66 ________________________ // 88 88 88 88 00 00 66 // 8888888888888888 8888888888888888 00 00 6666666666666666 _____________ // 88 88 88 88 00 00 66 66 // 88 88 88 88 00 00 66 66 _____________________ // 88 88 88 88 00 00 66 66 ________________________ // 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ____________________ // __________________________ __________ package frc.robot; public class RobotContainer { // instantiate controller here public static XboxController driverController = new XboxController(ControllerConstants.DRIVER_CONTROLLER_PORT); public static XboxController operaterController = new XboxController(ControllerConstants.OPERATER_CONTROLLER_PORT); // instantiate subsystem here public static DriveTrain driveTrain = new DriveTrain(); public static Limelight limelight = new Limelight("limelight-front"); // instantiate command here
private TeleSwerveControl driveCommand = new TeleSwerveControl(driveTrain, driverController);
1
2023-12-13 11:38:11+00:00
8k
ganeshbabugb/NASC-CMS
src/main/java/com/nasc/application/views/auth/create/CreateUsers.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.User; import com.nasc.application.data.core.enums.Role; import com.nasc.application.data.core.enums.StudentSection; import com.nasc.application.services.AcademicYearService; import com.nasc.application.services.DepartmentService; import com.nasc.application.services.UserService; import com.nasc.application.utils.NotificationUtils; import com.nasc.application.views.MainLayout; import com.opencsv.CSVReader; import com.opencsv.bean.CsvToBeanBuilder; import com.opencsv.bean.HeaderColumnNameMappingStrategy; import com.opencsv.exceptions.CsvException; import com.vaadin.flow.component.HasValue; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.ButtonVariant; import com.vaadin.flow.component.checkbox.Checkbox; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.dependency.JsModule; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.grid.GridVariant; 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.upload.SucceededEvent; import com.vaadin.flow.component.upload.Upload; import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.data.provider.DataProvider; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.server.StreamResource; import com.vaadin.flow.theme.lumo.LumoIcon; import jakarta.annotation.security.RolesAllowed; import lombok.extern.slf4j.Slf4j; import org.springframework.security.crypto.password.PasswordEncoder; import org.vaadin.olli.FileDownloadWrapper; import java.io.*; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.stream.Collectors;
6,263
package com.nasc.application.views.auth.create; @PageTitle("Create User Account") @Route(value = "create-user", layout = MainLayout.class) @RolesAllowed({"EDITOR", "ADMIN"}) @JsModule("./recipe/copytoclipboard/copytoclipboard.js") @Slf4j public class CreateUsers extends VerticalLayout { private final DepartmentService departmentService; private final AcademicYearService academicYearService; private final UserService userService; private final PasswordEncoder passwordEncoder; private final Upload upload; private final Grid<User> userGrid; private final Checkbox verifyCheckbox; private final Button createUserButton; private ComboBox<Role> roleComboBox; private ComboBox<DepartmentEntity> departmentComboBox; private ComboBox<AcademicYearEntity> academicYearComboBox;
package com.nasc.application.views.auth.create; @PageTitle("Create User Account") @Route(value = "create-user", layout = MainLayout.class) @RolesAllowed({"EDITOR", "ADMIN"}) @JsModule("./recipe/copytoclipboard/copytoclipboard.js") @Slf4j public class CreateUsers extends VerticalLayout { private final DepartmentService departmentService; private final AcademicYearService academicYearService; private final UserService userService; private final PasswordEncoder passwordEncoder; private final Upload upload; private final Grid<User> userGrid; private final Checkbox verifyCheckbox; private final Button createUserButton; private ComboBox<Role> roleComboBox; private ComboBox<DepartmentEntity> departmentComboBox; private ComboBox<AcademicYearEntity> academicYearComboBox;
private ComboBox<StudentSection> studentSectionComboBox;
4
2023-12-10 18:07:28+00:00
8k
Viola-Siemens/StellarForge
src/main/java/com/hexagram2021/stellarforge/common/register/SFBlocks.java
[ { "identifier": "PillarBlock", "path": "src/main/java/com/hexagram2021/stellarforge/common/block/PillarBlock.java", "snippet": "@SuppressWarnings(\"deprecation\")\npublic class PillarBlock extends RotatedPillarBlock {\n\tpublic static final BooleanProperty HEAD = SFBlockStateProperties.HEAD;\n\tpublic s...
import com.google.common.collect.ImmutableList; import com.hexagram2021.stellarforge.common.block.PillarBlock; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.SlabType; import net.minecraft.world.level.material.MapColor; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; import org.apache.commons.lang3.tuple.Pair; import java.util.function.Function; import java.util.function.Supplier; import static com.hexagram2021.stellarforge.StellarForge.MODID; import static com.hexagram2021.stellarforge.common.util.RegistryHelper.getRegistryName;
6,741
} } } public static void init(IEventBus bus) { REGISTER.register(bus); Bricks.init(); Igneous.init(); Stone.init(); } public static <T extends Block> BlockItem toItem(T block) { return new BlockItem(block, new Item.Properties()); } public static final class BlockEntry<T extends Block> implements Supplier<T>, ItemLike { private final RegistryObject<T> regObject; private final Supplier<BlockBehaviour.Properties> properties; public BlockEntry(String name, Supplier<BlockBehaviour.Properties> properties, Function<BlockBehaviour.Properties, T> make) { this.properties = properties; this.regObject = REGISTER.register(name, () -> make.apply(properties.get())); } public BlockEntry(String name, Supplier<BlockBehaviour.Properties> properties, Function<BlockBehaviour.Properties, T> make, Function<T, Item> toItem) { this(name, properties, make); SFItems.ItemEntry.register(name, () -> toItem.apply(this.regObject.get())); } BlockEntry(RegistryObject<T> regObject) { this.regObject = regObject; this.properties = () -> regObject.get().properties; } @Override public T get() { return this.regObject.get(); } public BlockState defaultBlockState() { return this.get().defaultBlockState(); } public ResourceLocation getId() { return this.regObject.getId(); } public BlockBehaviour.Properties getProperties() { return this.properties.get(); } @Override public Item asItem() { return this.get().asItem(); } } public interface IDecorGroup { BlockEntry<Block> getFullBlock(); BlockEntry<StairBlock> getStairsBlock(); BlockEntry<SlabBlock> getSlabBlock(); BlockEntry<WallBlock> getWallBlock(); } public static final class DecorBlockEntry implements Supplier<Block>, ItemLike, IDecorGroup { private final RegistryObject<Block> full; private final RegistryObject<StairBlock> stairs; private final RegistryObject<SlabBlock> slab; private final RegistryObject<WallBlock> wall; private final Supplier<BlockBehaviour.Properties> properties; private static String changeNameTo(String name, String postfix) { if(name.endsWith("_block")) { name = name.replaceAll("_block", postfix); } else if(name.endsWith("_bricks")) { name = name.replaceAll("_bricks", "_brick" + postfix); } else if(name.endsWith("_tiles")) { name = name.replaceAll("_tiles", "_tile" + postfix); } else if(name.endsWith("_planks")) { name = name.replaceAll("_planks", postfix); } else { name = name + postfix; } return name; } public DecorBlockEntry(String name, Supplier<BlockBehaviour.Properties> properties) { this.properties = properties; this.full = REGISTER.register(name, () -> new Block(properties.get())); this.stairs = REGISTER.register(changeNameTo(name, "_stairs"), () -> new StairBlock(this.full.get()::defaultBlockState, properties.get())); this.slab = REGISTER.register(changeNameTo(name, "_slab"), () -> new SlabBlock( properties.get() .isSuffocating((state, level, pos) -> this.full.get().defaultBlockState().isSuffocating(level, pos) && state.getValue(SlabBlock.TYPE) == SlabType.DOUBLE) .isRedstoneConductor((state, level, pos) -> this.full.get().defaultBlockState().isRedstoneConductor(level, pos) && state.getValue(SlabBlock.TYPE) == SlabType.DOUBLE) )); this.wall = REGISTER.register(changeNameTo(name, "_wall"), () -> new WallBlock(properties.get())); } public DecorBlockEntry(String name, Supplier<BlockBehaviour.Properties> properties, Function<Block, Item> toItem) { this(name, properties); SFItems.ItemEntry.register(name, () -> toItem.apply(this.full.get())); SFItems.ItemEntry.register(changeNameTo(name, "_stairs"), () -> toItem.apply(this.stairs.get())); SFItems.ItemEntry.register(changeNameTo(name, "_slab"), () -> toItem.apply(this.slab.get())); SFItems.ItemEntry.register(changeNameTo(name, "_wall"), () -> toItem.apply(this.wall.get())); } private DecorBlockEntry(Supplier<BlockBehaviour.Properties> properties, RegistryObject<Block> full, RegistryObject<StairBlock> stairs, RegistryObject<SlabBlock> slab, RegistryObject<WallBlock> wall) { this.properties = properties; this.full = full; this.stairs = stairs; this.slab = slab; this.wall = wall; } public static DecorBlockEntry createFromFull(Block full, Function<Block, Item> toItem) {
package com.hexagram2021.stellarforge.common.register; public final class SFBlocks { public static final DeferredRegister<Block> REGISTER = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID); public static final class Bricks { public static final DecorBlockEntry MOSSY_BRICKS = new DecorBlockEntry("mossy_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), SFBlocks::toItem); public static final DecorBlockEntry CRACKED_BRICKS = new DecorBlockEntry("cracked_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), SFBlocks::toItem); public static final BlockEntry<Block> CHISELED_BRICKS = new BlockEntry<>("chiseled_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), Block::new, SFBlocks::toItem); public static final DecorBlockEntry CRACKED_NETHER_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_NETHER_BRICKS, SFBlocks::toItem); private Bricks() { } private static void init() { } } public static final class Igneous { public static final DecorBlockEntry ANDESITE_BRICKS = new DecorBlockEntry("andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem); public static final DecorBlockEntry MOSSY_ANDESITE_BRICKS = new DecorBlockEntry("mossy_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem); public static final BlockEntry<Block> CHISELED_ANDESITE_BRICKS = new BlockEntry<>("chiseled_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem); public static final DecorBlockEntry CRACKED_ANDESITE_BRICKS = new DecorBlockEntry("cracked_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem); public static final DecorBlockEntry DIORITE_BRICKS = new DecorBlockEntry("diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem); public static final DecorBlockEntry MOSSY_DIORITE_BRICKS = new DecorBlockEntry("mossy_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem); public static final BlockEntry<Block> CHISELED_DIORITE_BRICKS = new BlockEntry<>("chiseled_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem); public static final DecorBlockEntry CRACKED_DIORITE_BRICKS = new DecorBlockEntry("cracked_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem); public static final DecorBlockEntry GRANITE_BRICKS = new DecorBlockEntry("granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem); public static final DecorBlockEntry MOSSY_GRANITE_BRICKS = new DecorBlockEntry("mossy_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem); public static final BlockEntry<Block> CHISELED_GRANITE_BRICKS = new BlockEntry<>("chiseled_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem); public static final DecorBlockEntry CRACKED_GRANITE_BRICKS = new DecorBlockEntry("cracked_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem); private Igneous() { } private static void init() { } } public static final class Stone { //vanilla public static final DecorBlockEntry CRACKED_STONE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_STONE_BRICKS, SFBlocks::toItem); public static final DecorBlockEntry DEEPSLATE = DecorBlockEntry.createFromFull(Blocks.DEEPSLATE, SFBlocks::toItem); public static final BlockEntry<ButtonBlock> DEEPSLATE_BUTTON = new BlockEntry<>("deepslate_button", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BUTTON), props -> new ButtonBlock(props, SFBlockSetTypes.DEEPSLATE, 20, false), SFBlocks::toItem); public static final BlockEntry<PressurePlateBlock> DEEPSLATE_PRESSURE_PLATE = new BlockEntry<>("deepslate_pressure_plate", () -> BlockBehaviour.Properties.copy(Blocks.STONE_PRESSURE_PLATE), props -> new PressurePlateBlock(PressurePlateBlock.Sensitivity.MOBS, props, SFBlockSetTypes.DEEPSLATE), SFBlocks::toItem); public static final DecorBlockEntry CRACKED_DEEPSLATE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_DEEPSLATE_BRICKS, SFBlocks::toItem); public static final DecorBlockEntry CRACKED_DEEPSLATE_TILES = DecorBlockEntry.createFromFull(Blocks.CRACKED_DEEPSLATE_TILES, SFBlocks::toItem); public static final DecorBlockEntry CRACKED_POLISHED_BLACKSTONE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_POLISHED_BLACKSTONE_BRICKS, SFBlocks::toItem); //blackstone public static final DecorBlockEntry COBBLED_BLACKSTONE = new DecorBlockEntry("cobbled_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem); public static final DecorBlockEntry MOSSY_COBBLED_BLACKSTONE = new DecorBlockEntry("mossy_cobbled_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem); public static final DecorBlockEntry SMOOTH_BLACKSTONE = new DecorBlockEntry("smooth_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem); public static final BlockEntry<PillarBlock> POLISHED_BLACKSTONE_PILLAR = new BlockEntry<>("polished_blackstone_pillar", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), PillarBlock::new, SFBlocks::toItem); public static final BlockEntry<Block> CHISELED_BLACKSTONE = new BlockEntry<>("chiseled_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), Block::new, SFBlocks::toItem); public static final BlockEntry<Block> CHISELED_POLISHED_BLACKSTONE_BRICKS = new BlockEntry<>("chiseled_polished_blackstone_bricks", () -> BlockBehaviour.Properties.copy(Blocks.POLISHED_BLACKSTONE_BRICKS), Block::new, SFBlocks::toItem); public static final BlockEntry<Block> CHISELED_POLISHED_BLACKSTONE_TILES = new BlockEntry<>("chiseled_polished_blackstone_tiles", () -> BlockBehaviour.Properties.copy(Blocks.POLISHED_BLACKSTONE_BRICKS), Block::new, SFBlocks::toItem); public static final DecorBlockEntry POLISHED_BLACKSTONE_TILES = new DecorBlockEntry("polished_blackstone_tiles", () -> BlockBehaviour.Properties.copy(Blocks.POLISHED_BLACKSTONE_BRICKS), SFBlocks::toItem); public static final DecorBlockEntry CRACKED_POLISHED_BLACKSTONE_TILES = new DecorBlockEntry("cracked_polished_blackstone_tiles", () -> BlockBehaviour.Properties.copy(Blocks.POLISHED_BLACKSTONE_BRICKS), SFBlocks::toItem); public static final DecorBlockEntry MOSSY_POLISHED_BLACKSTONE_BRICKS = new DecorBlockEntry("mossy_polished_blackstone_bricks", () -> BlockBehaviour.Properties.copy(Blocks.POLISHED_BLACKSTONE_BRICKS), SFBlocks::toItem); public static final DecorBlockEntry MOSSY_POLISHED_BLACKSTONE_TILES = new DecorBlockEntry("mossy_polished_blackstone_tiles", () -> BlockBehaviour.Properties.copy(Blocks.POLISHED_BLACKSTONE_BRICKS), SFBlocks::toItem); //stone public static final BlockEntry<PillarBlock> STONE_PILLAR = new BlockEntry<>("stone_pillar", () -> BlockBehaviour.Properties.copy(Blocks.STONE), PillarBlock::new, SFBlocks::toItem); public static final DecorBlockEntry STONE = DecorBlockEntry.createFromFullSlabStairs(Blocks.STONE, Blocks.STONE_SLAB, Blocks.STONE_STAIRS, SFBlocks::toItem); public static final DecorBlockEntry SMOOTH_STONE = DecorBlockEntry.createFromFullSlab(Blocks.SMOOTH_STONE, Blocks.SMOOTH_STONE_SLAB, SFBlocks::toItem); public static final BlockEntry<Block> CHISELED_STONE = new BlockEntry<>("chiseled_stone", () -> BlockBehaviour.Properties.copy(Blocks.STONE), Block::new, SFBlocks::toItem); public static final DecorBlockEntry POLISHED_STONE = new DecorBlockEntry("polished_stone", () -> BlockBehaviour.Properties.copy(Blocks.STONE), SFBlocks::toItem); public static final BlockEntry<Block> CHISELED_POLISHED_STONE = new BlockEntry<>("chiseled_polished_stone", () -> BlockBehaviour.Properties.copy(Blocks.STONE), Block::new, SFBlocks::toItem); public static final DecorBlockEntry STONE_TILES = new DecorBlockEntry("stone_tiles", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem); public static final DecorBlockEntry MOSSY_STONE_TILES = new DecorBlockEntry("mossy_stone_tiles", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem); public static final DecorBlockEntry CRACKED_STONE_TILES = new DecorBlockEntry("cracked_stone_tiles", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem); public static final BlockEntry<Block> CHISELED_STONE_TILES = new BlockEntry<>("chiseled_stone_tiles", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), Block::new, SFBlocks::toItem); //deepslate public static final DecorBlockEntry MOSSY_COBBLED_DEEPSLATE = new DecorBlockEntry("mossy_cobbled_deepslate", () -> BlockBehaviour.Properties.copy(Blocks.COBBLED_DEEPSLATE), SFBlocks::toItem); public static final DecorBlockEntry SMOOTH_DEEPSLATE = new DecorBlockEntry("smooth_deepslate", () -> BlockBehaviour.Properties.copy(Blocks.DEEPSLATE), SFBlocks::toItem); public static final BlockEntry<PillarBlock> DEEPSLATE_PILLAR = new BlockEntry<>("deepslate_pillar", () -> BlockBehaviour.Properties.copy(Blocks.DEEPSLATE), PillarBlock::new, SFBlocks::toItem); public static final BlockEntry<Block> CHISELED_POLISHED_DEEPSLATE = new BlockEntry<>("chiseled_polished_deepslate", () -> BlockBehaviour.Properties.copy(Blocks.POLISHED_DEEPSLATE), Block::new, SFBlocks::toItem); public static final BlockEntry<Block> CHISELED_DEEPSLATE_BRICKS = new BlockEntry<>("chiseled_deepslate_bricks", () -> BlockBehaviour.Properties.copy(Blocks.DEEPSLATE_BRICKS), Block::new, SFBlocks::toItem); public static final BlockEntry<Block> CHISELED_DEEPSLATE_TILES = new BlockEntry<>("chiseled_deepslate_tiles", () -> BlockBehaviour.Properties.copy(Blocks.DEEPSLATE_TILES), Block::new, SFBlocks::toItem); public static final DecorBlockEntry MOSSY_DEEPSLATE_BRICKS = new DecorBlockEntry("mossy_deepslate_bricks", () -> BlockBehaviour.Properties.copy(Blocks.DEEPSLATE_BRICKS), SFBlocks::toItem); public static final DecorBlockEntry MOSSY_DEEPSLATE_TILES = new DecorBlockEntry("mossy_deepslate_tiles", () -> BlockBehaviour.Properties.copy(Blocks.DEEPSLATE_BRICKS), SFBlocks::toItem); private Stone() { } private static void init() { Infested.init(); } public static final class Infested { private static final Supplier<BlockBehaviour.Properties> INFESTED_STONE_PROPERTIES = () -> BlockBehaviour.Properties.of().mapColor(MapColor.CLAY); private static final Supplier<BlockBehaviour.Properties> INFESTED_DEEPSLATE_PROPERTIES = () -> BlockBehaviour.Properties.of().mapColor(MapColor.STONE); private static final Supplier<BlockBehaviour.Properties> INFESTED_BLACKSTONE_PROPERTIES = () -> BlockBehaviour.Properties.of().mapColor(MapColor.COLOR_GRAY); public static final BlockEntry<InfestedBlock> INFESTED_CHISELED_STONE = infestedStone("infested_chiseled_stone", Stone.CHISELED_STONE); public static final BlockEntry<InfestedBlock> INFESTED_POLISHED_STONE = infestedStone("infested_polished_stone", Stone.POLISHED_STONE); public static final BlockEntry<InfestedBlock> INFESTED_CHISELED_POLISHED_STONE = infestedStone("infested_chiseled_polished_stone", Stone.CHISELED_POLISHED_STONE); public static final BlockEntry<InfestedBlock> INFESTED_SMOOTH_STONE = infestedStone("infested_smooth_stone", Blocks.SMOOTH_STONE); public static final BlockEntry<InfestedBlock> INFESTED_MOSSY_COBBLESTONE = infestedStone("infested_mossy_cobblestone", Blocks.MOSSY_COBBLESTONE); public static final BlockEntry<InfestedBlock> INFESTED_STONE_TILES = infestedStone("infested_stone_tiles", Stone.STONE_TILES); public static final BlockEntry<InfestedBlock> INFESTED_CHISELED_STONE_TILES = infestedStone("infested_chiseled_stone_tiles", Stone.CHISELED_STONE_TILES); public static final BlockEntry<InfestedBlock> INFESTED_MOSSY_STONE_TILES = infestedStone("infested_mossy_stone_tiles", Stone.MOSSY_STONE_TILES); public static final BlockEntry<InfestedBlock> INFESTED_CRACKED_STONE_TILES = infestedStone("infested_cracked_stone_tiles", Stone.CRACKED_STONE_TILES); public static final BlockEntry<InfestedBlock> INFESTED_CHISELED_DEEPSLATE = infestedDeepslate("infested_chiseled_deepslate", Blocks.CHISELED_DEEPSLATE); public static final BlockEntry<InfestedBlock> INFESTED_POLISHED_DEEPSLATE = infestedDeepslate("infested_polished_deepslate", Blocks.POLISHED_DEEPSLATE); public static final BlockEntry<InfestedBlock> INFESTED_CHISELED_POLISHED_DEEPSLATE = infestedDeepslate("infested_chiseled_polished_deepslate", Stone.CHISELED_POLISHED_DEEPSLATE); public static final BlockEntry<InfestedBlock> INFESTED_SMOOTH_DEEPSLATE = infestedDeepslate("infested_smooth_deepslate", Stone.SMOOTH_DEEPSLATE); public static final BlockEntry<InfestedBlock> INFESTED_COBBLED_DEEPSLATE = infestedDeepslate("infested_cobbled_deepslate", Blocks.COBBLED_DEEPSLATE); public static final BlockEntry<InfestedBlock> INFESTED_MOSSY_COBBLED_DEEPSLATE = infestedDeepslate("infested_mossy_cobbled_deepslate", Stone.MOSSY_COBBLED_DEEPSLATE); public static final BlockEntry<InfestedBlock> INFESTED_DEEPSLATE_BRICKS = infestedDeepslate("infested_deepslate_bricks", Blocks.DEEPSLATE_BRICKS); public static final BlockEntry<InfestedBlock> INFESTED_CHISELED_DEEPSLATE_BRICKS = infestedDeepslate("infested_chiseled_deepslate_bricks", Stone.CHISELED_DEEPSLATE_BRICKS); public static final BlockEntry<InfestedBlock> INFESTED_MOSSY_DEEPSLATE_BRICKS = infestedDeepslate("infested_mossy_deepslate_bricks", Stone.MOSSY_DEEPSLATE_BRICKS); public static final BlockEntry<InfestedBlock> INFESTED_CRACKED_DEEPSLATE_BRICKS = infestedDeepslate("infested_cracked_deepslate_bricks", Blocks.CRACKED_DEEPSLATE_BRICKS); public static final BlockEntry<InfestedBlock> INFESTED_DEEPSLATE_TILES = infestedDeepslate("infested_deepslate_tiles", Blocks.DEEPSLATE_TILES); public static final BlockEntry<InfestedBlock> INFESTED_CHISELED_DEEPSLATE_TILES = infestedDeepslate("infested_chiseled_deepslate_tiles", Stone.CHISELED_DEEPSLATE_TILES); public static final BlockEntry<InfestedBlock> INFESTED_MOSSY_DEEPSLATE_TILES = infestedDeepslate("infested_mossy_deepslate_tiles", Stone.MOSSY_DEEPSLATE_TILES); public static final BlockEntry<InfestedBlock> INFESTED_CRACKED_DEEPSLATE_TILES = infestedDeepslate("infested_cracked_deepslate_tiles", Blocks.CRACKED_DEEPSLATE_TILES); public static final BlockEntry<InfestedBlock> INFESTED_BLACKSTONE = infestedBlackstone("infested_blackstone", Blocks.BLACKSTONE); public static final BlockEntry<InfestedBlock> INFESTED_CHISELED_BLACKSTONE = infestedBlackstone("infested_chiseled_blackstone", Stone.CHISELED_BLACKSTONE); public static final BlockEntry<InfestedBlock> INFESTED_POLISHED_BLACKSTONE = infestedBlackstone("infested_polished_blackstone", Blocks.POLISHED_BLACKSTONE); public static final BlockEntry<InfestedBlock> INFESTED_CHISELED_POLISHED_BLACKSTONE = infestedBlackstone("infested_chiseled_polished_blackstone", Blocks.CHISELED_POLISHED_BLACKSTONE); public static final BlockEntry<InfestedBlock> INFESTED_SMOOTH_BLACKSTONE = infestedBlackstone("infested_smooth_blackstone", Stone.SMOOTH_BLACKSTONE); public static final BlockEntry<InfestedBlock> INFESTED_COBBLED_BLACKSTONE = infestedBlackstone("infested_cobbled_blackstone", Stone.COBBLED_BLACKSTONE); public static final BlockEntry<InfestedBlock> INFESTED_MOSSY_COBBLED_BLACKSTONE = infestedBlackstone("infested_mossy_cobbled_blackstone", Stone.MOSSY_COBBLED_BLACKSTONE); public static final BlockEntry<InfestedBlock> INFESTED_POLISHED_BLACKSTONE_BRICKS = infestedBlackstone("infested_polished_blackstone_bricks", Blocks.POLISHED_BLACKSTONE_BRICKS); public static final BlockEntry<InfestedBlock> INFESTED_CHISELED_BLACKSTONE_BRICKS = infestedBlackstone("infested_chiseled_polished_blackstone_bricks", Stone.CHISELED_POLISHED_BLACKSTONE_BRICKS); public static final BlockEntry<InfestedBlock> INFESTED_MOSSY_BLACKSTONE_BRICKS = infestedBlackstone("infested_mossy_polished_blackstone_bricks", Stone.MOSSY_POLISHED_BLACKSTONE_BRICKS); public static final BlockEntry<InfestedBlock> INFESTED_CRACKED_BLACKSTONE_BRICKS = infestedBlackstone("infested_cracked_polished_blackstone_bricks", Blocks.CRACKED_POLISHED_BLACKSTONE_BRICKS); public static final BlockEntry<InfestedBlock> INFESTED_BLACKSTONE_TILES = infestedBlackstone("infested_polished_blackstone_tiles", Stone.POLISHED_BLACKSTONE_TILES); public static final BlockEntry<InfestedBlock> INFESTED_CHISELED_BLACKSTONE_TILES = infestedBlackstone("infested_chiseled_polished_blackstone_tiles", Stone.CHISELED_POLISHED_BLACKSTONE_TILES); public static final BlockEntry<InfestedBlock> INFESTED_MOSSY_BLACKSTONE_TILES = infestedBlackstone("infested_mossy_polished_blackstone_tiles", Stone.MOSSY_POLISHED_BLACKSTONE_TILES); public static final BlockEntry<InfestedBlock> INFESTED_CRACKED_BLACKSTONE_TILES = infestedBlackstone("infested_cracked_polished_blackstone_tiles", Stone.CRACKED_POLISHED_BLACKSTONE_TILES); private Infested() { } private static void init() { } @SuppressWarnings("SameParameterValue") private static BlockEntry<InfestedBlock> infestedStone(String name, Block host) { return new BlockEntry<>(name, INFESTED_STONE_PROPERTIES, props -> new InfestedBlock(host, props), SFBlocks::toItem); } private static BlockEntry<InfestedBlock> infestedDeepslate(String name, Block host) { return new BlockEntry<>(name, INFESTED_DEEPSLATE_PROPERTIES, props -> new InfestedBlock(host, props), SFBlocks::toItem); } private static BlockEntry<InfestedBlock> infestedBlackstone(String name, Block host) { return new BlockEntry<>(name, INFESTED_BLACKSTONE_PROPERTIES, props -> new InfestedBlock(host, props), SFBlocks::toItem); } private static BlockEntry<InfestedBlock> infestedStone(String name, Supplier<Block> host) { return new BlockEntry<>(name, INFESTED_STONE_PROPERTIES, props -> new InfestedBlock(host.get(), props), SFBlocks::toItem); } private static BlockEntry<InfestedBlock> infestedDeepslate(String name, Supplier<Block> host) { return new BlockEntry<>(name, INFESTED_DEEPSLATE_PROPERTIES, props -> new InfestedBlock(host.get(), props), SFBlocks::toItem); } private static BlockEntry<InfestedBlock> infestedBlackstone(String name, Supplier<Block> host) { return new BlockEntry<>(name, INFESTED_BLACKSTONE_PROPERTIES, props -> new InfestedBlock(host.get(), props), SFBlocks::toItem); } } } public static void init(IEventBus bus) { REGISTER.register(bus); Bricks.init(); Igneous.init(); Stone.init(); } public static <T extends Block> BlockItem toItem(T block) { return new BlockItem(block, new Item.Properties()); } public static final class BlockEntry<T extends Block> implements Supplier<T>, ItemLike { private final RegistryObject<T> regObject; private final Supplier<BlockBehaviour.Properties> properties; public BlockEntry(String name, Supplier<BlockBehaviour.Properties> properties, Function<BlockBehaviour.Properties, T> make) { this.properties = properties; this.regObject = REGISTER.register(name, () -> make.apply(properties.get())); } public BlockEntry(String name, Supplier<BlockBehaviour.Properties> properties, Function<BlockBehaviour.Properties, T> make, Function<T, Item> toItem) { this(name, properties, make); SFItems.ItemEntry.register(name, () -> toItem.apply(this.regObject.get())); } BlockEntry(RegistryObject<T> regObject) { this.regObject = regObject; this.properties = () -> regObject.get().properties; } @Override public T get() { return this.regObject.get(); } public BlockState defaultBlockState() { return this.get().defaultBlockState(); } public ResourceLocation getId() { return this.regObject.getId(); } public BlockBehaviour.Properties getProperties() { return this.properties.get(); } @Override public Item asItem() { return this.get().asItem(); } } public interface IDecorGroup { BlockEntry<Block> getFullBlock(); BlockEntry<StairBlock> getStairsBlock(); BlockEntry<SlabBlock> getSlabBlock(); BlockEntry<WallBlock> getWallBlock(); } public static final class DecorBlockEntry implements Supplier<Block>, ItemLike, IDecorGroup { private final RegistryObject<Block> full; private final RegistryObject<StairBlock> stairs; private final RegistryObject<SlabBlock> slab; private final RegistryObject<WallBlock> wall; private final Supplier<BlockBehaviour.Properties> properties; private static String changeNameTo(String name, String postfix) { if(name.endsWith("_block")) { name = name.replaceAll("_block", postfix); } else if(name.endsWith("_bricks")) { name = name.replaceAll("_bricks", "_brick" + postfix); } else if(name.endsWith("_tiles")) { name = name.replaceAll("_tiles", "_tile" + postfix); } else if(name.endsWith("_planks")) { name = name.replaceAll("_planks", postfix); } else { name = name + postfix; } return name; } public DecorBlockEntry(String name, Supplier<BlockBehaviour.Properties> properties) { this.properties = properties; this.full = REGISTER.register(name, () -> new Block(properties.get())); this.stairs = REGISTER.register(changeNameTo(name, "_stairs"), () -> new StairBlock(this.full.get()::defaultBlockState, properties.get())); this.slab = REGISTER.register(changeNameTo(name, "_slab"), () -> new SlabBlock( properties.get() .isSuffocating((state, level, pos) -> this.full.get().defaultBlockState().isSuffocating(level, pos) && state.getValue(SlabBlock.TYPE) == SlabType.DOUBLE) .isRedstoneConductor((state, level, pos) -> this.full.get().defaultBlockState().isRedstoneConductor(level, pos) && state.getValue(SlabBlock.TYPE) == SlabType.DOUBLE) )); this.wall = REGISTER.register(changeNameTo(name, "_wall"), () -> new WallBlock(properties.get())); } public DecorBlockEntry(String name, Supplier<BlockBehaviour.Properties> properties, Function<Block, Item> toItem) { this(name, properties); SFItems.ItemEntry.register(name, () -> toItem.apply(this.full.get())); SFItems.ItemEntry.register(changeNameTo(name, "_stairs"), () -> toItem.apply(this.stairs.get())); SFItems.ItemEntry.register(changeNameTo(name, "_slab"), () -> toItem.apply(this.slab.get())); SFItems.ItemEntry.register(changeNameTo(name, "_wall"), () -> toItem.apply(this.wall.get())); } private DecorBlockEntry(Supplier<BlockBehaviour.Properties> properties, RegistryObject<Block> full, RegistryObject<StairBlock> stairs, RegistryObject<SlabBlock> slab, RegistryObject<WallBlock> wall) { this.properties = properties; this.full = full; this.stairs = stairs; this.slab = slab; this.wall = wall; } public static DecorBlockEntry createFromFull(Block full, Function<Block, Item> toItem) {
ResourceLocation fullId = getRegistryName(full);
2
2023-12-10 07:20:43+00:00
8k
nilsgenge/finite-state-machine-visualizer
src/gui/Toolbar.java
[ { "identifier": "MouseInputs", "path": "src/inputs/MouseInputs.java", "snippet": "public class MouseInputs implements MouseListener {\n\n\tprivate Boolean m1Pressed = false; // left mouse button\n\tprivate Boolean m2Pressed = false; // right mouse button\n\tprivate Boolean m3Pressed = false; // middle m...
import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.util.LinkedList; import inputs.MouseInputs; import utilz.colortable; import utilz.tools; import workspace.ToolHandler; import workspace.Transition;
5,458
package gui; public class Toolbar { private GuiHandler gh;
package gui; public class Toolbar { private GuiHandler gh;
private MouseInputs m;
0
2023-12-12 20:43:41+00:00
8k
kaushikMreddy293/Cafe-Management-with-Java
CafeManagement/src/main/java/edu/neu/cafemanagement/Items.java
[ { "identifier": "BeverageFactoryLazySingleton", "path": "CafeManagement/src/main/java/edu/neu/csye6200/BeverageFactoryLazySingleton.java", "snippet": "public class BeverageFactoryLazySingleton implements CafeItemFactoryAPI {\n private static BeverageFactoryLazySingleton instance;\n\n private Bever...
import edu.neu.csye6200.BeverageFactoryLazySingleton; import edu.neu.csye6200.CafeItem; import edu.neu.csye6200.CakeFactoryLazySingleton; import edu.neu.csye6200.ShakeFactoryEagerSingleton; import java.sql.Statement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import net.proteanit.sql.DbUtils;
3,958
} }); VIewBillsLb.setFont(new java.awt.Font("Malgun Gothic", 1, 18)); // NOI18N VIewBillsLb.setForeground(new java.awt.Color(255, 51, 51)); VIewBillsLb.setText("View Bills"); VIewBillsLb.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { VIewBillsLbMouseClicked(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(SellingLb, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ItemsLogoutBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(14, 14, 14) .addComponent(VIewBillsLb, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE) .addGap(18, 18, 18))) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(920, Short.MAX_VALUE))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(183, 183, 183) .addComponent(SellingLb, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(VIewBillsLb, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(148, 148, 148) .addComponent(ItemsLogoutBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(20, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(145, 145, 145) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(394, 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) ); 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) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void PriceTbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PriceTbActionPerformed // TODO add your handling code here: }//GEN-LAST:event_PriceTbActionPerformed private void PrNameTbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PrNameTbActionPerformed // TODO add your handling code here: }//GEN-LAST:event_PrNameTbActionPerformed private void ShowProducts(){ try { Con = DriverManager.getConnection(Constants.dbUrl, Constants.dbUser, Constants.dbPwd); St = Con.createStatement(); Rs = St.executeQuery("select * from ProductTbl"); ProductList.setModel(DbUtils.resultSetToTableModel(Rs)); } catch (Exception e) { } } private void FilterProducts(){ try { Con = DriverManager.getConnection(Constants.dbUrl, Constants.dbUser, Constants.dbPwd); St = Con.createStatement(); Rs = St.executeQuery("select * from ProductTbl where Category='" + FilterCb.getSelectedItem().toString()+"'"); ProductList.setModel(DbUtils.resultSetToTableModel(Rs)); } catch (Exception e) { JOptionPane.showMessageDialog(this, e); } } private void AddBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddBtnActionPerformed if( PrNameTb.getText().isEmpty() && PriceTb.getText().isEmpty() && PrCatCb.getSelectedIndex() != -1) { JOptionPane.showMessageDialog(this, "Missing Information!"); } else { String Temp = PrCatCb.getSelectedItem().toString(); if(Temp.equalsIgnoreCase("Beverage")) { BeverageFactoryLazySingleton bItem = BeverageFactoryLazySingleton.getInstance();
/* * 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 */ package edu.neu.cafemanagement; /** * * @author kaush */ public class Items extends javax.swing.JFrame { /** * Creates new form Items */ public Items() { initComponents(); ShowProducts(); } ResultSet Rs = null, Rs1 = null; Connection Con = null; Statement St = null, St1 = null; int PrNum; String dbUrl = "jdbc:mysql://localhost:3306/cafedb"; String dbUser = "root"; String dbPwd = "cnwFri_123"; private void CountProd() { try { St1 = Con.createStatement(); Rs1 = St1.executeQuery("select Max(PNum) from ProductTbl"); Rs1.next(); PrNum = Rs1.getInt(1)+1; } catch (Exception e) { } } /** * 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(); jPanel2 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); PriceTb = new javax.swing.JTextField(); PrNameTb = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); PrCatCb = new javax.swing.JComboBox<>(); jLabel9 = new javax.swing.JLabel(); AddBtn = new javax.swing.JButton(); DeleteBtn = new javax.swing.JButton(); EditBtn = new javax.swing.JButton(); FilterCb = new javax.swing.JComboBox<>(); jScrollPane1 = new javax.swing.JScrollPane(); ProductList = new javax.swing.JTable(); RefreshBtn = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); ItemsLogoutBtn = new javax.swing.JLabel(); SellingLb = new javax.swing.JLabel(); VIewBillsLb = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel2.setBackground(new java.awt.Color(255, 51, 102)); jLabel4.setFont(new java.awt.Font("Malgun Gothic", 1, 18)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("Items List"); PriceTb.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { PriceTbActionPerformed(evt); } }); PrNameTb.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { PrNameTbActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Price"); jLabel3.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("Category"); jLabel7.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N jLabel7.setForeground(new java.awt.Color(255, 255, 255)); jLabel7.setText("Name"); jLabel8.setFont(new java.awt.Font("Malgun Gothic", 1, 18)); // NOI18N jLabel8.setForeground(new java.awt.Color(255, 255, 255)); jLabel8.setText("Items Management"); PrCatCb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Beverage", "Shake", "Cake", " " })); PrCatCb.setToolTipText(""); jLabel9.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jLabel9.setForeground(new java.awt.Color(255, 255, 255)); jLabel9.setText("Filter"); AddBtn.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N AddBtn.setText("Add"); AddBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddBtnActionPerformed(evt); } }); DeleteBtn.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N DeleteBtn.setText("Delete"); DeleteBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DeleteBtnActionPerformed(evt); } }); EditBtn.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N EditBtn.setText("Edit"); EditBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EditBtnActionPerformed(evt); } }); FilterCb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Beverage", "Shake", "Cake", " " })); FilterCb.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { FilterCbItemStateChanged(evt); } }); ProductList.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "ID", "Name", "Category", "Price" } )); ProductList.setRowHeight(30); ProductList.setShowHorizontalLines(true); ProductList.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ProductListMouseClicked(evt); } }); jScrollPane1.setViewportView(ProductList); RefreshBtn.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N RefreshBtn.setText("Refresh"); RefreshBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { RefreshBtnActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(103, 103, 103) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(PrNameTb, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 89, Short.MAX_VALUE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(132, 132, 132)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(50, 50, 50) .addComponent(PrCatCb, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(PriceTb, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(126, 126, 126)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(324, 324, 324) .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(FilterCb, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(38, 38, 38) .addComponent(RefreshBtn)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(198, 198, 198) .addComponent(DeleteBtn) .addGap(108, 108, 108) .addComponent(AddBtn) .addGap(132, 132, 132) .addComponent(EditBtn)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(45, 45, 45) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 797, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(357, 357, 357) .addComponent(jLabel4))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(345, 345, 345) .addComponent(jLabel8) .addContainerGap(372, Short.MAX_VALUE))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(75, 75, 75) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel3) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(PriceTb, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(PrNameTb, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(PrCatCb, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(AddBtn) .addComponent(DeleteBtn) .addComponent(EditBtn)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(FilterCb, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)) .addGap(21, 21, 21)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(RefreshBtn) .addGap(27, 27, 27))) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(26, 26, 26) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(487, Short.MAX_VALUE))) ); jLabel2.setFont(new java.awt.Font("Malgun Gothic", 1, 18)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 51, 51)); jLabel2.setText("Items"); ItemsLogoutBtn.setFont(new java.awt.Font("Malgun Gothic", 1, 18)); // NOI18N ItemsLogoutBtn.setForeground(new java.awt.Color(255, 51, 51)); ItemsLogoutBtn.setText("Logout"); ItemsLogoutBtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ItemsLogoutBtnMouseClicked(evt); } }); SellingLb.setFont(new java.awt.Font("Malgun Gothic", 1, 18)); // NOI18N SellingLb.setForeground(new java.awt.Color(255, 51, 51)); SellingLb.setText("Selling"); SellingLb.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { SellingLbMouseClicked(evt); } }); VIewBillsLb.setFont(new java.awt.Font("Malgun Gothic", 1, 18)); // NOI18N VIewBillsLb.setForeground(new java.awt.Color(255, 51, 51)); VIewBillsLb.setText("View Bills"); VIewBillsLb.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { VIewBillsLbMouseClicked(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(SellingLb, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ItemsLogoutBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(14, 14, 14) .addComponent(VIewBillsLb, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE) .addGap(18, 18, 18))) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(920, Short.MAX_VALUE))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(183, 183, 183) .addComponent(SellingLb, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(VIewBillsLb, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(148, 148, 148) .addComponent(ItemsLogoutBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(20, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(145, 145, 145) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(394, 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) ); 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) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void PriceTbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PriceTbActionPerformed // TODO add your handling code here: }//GEN-LAST:event_PriceTbActionPerformed private void PrNameTbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PrNameTbActionPerformed // TODO add your handling code here: }//GEN-LAST:event_PrNameTbActionPerformed private void ShowProducts(){ try { Con = DriverManager.getConnection(Constants.dbUrl, Constants.dbUser, Constants.dbPwd); St = Con.createStatement(); Rs = St.executeQuery("select * from ProductTbl"); ProductList.setModel(DbUtils.resultSetToTableModel(Rs)); } catch (Exception e) { } } private void FilterProducts(){ try { Con = DriverManager.getConnection(Constants.dbUrl, Constants.dbUser, Constants.dbPwd); St = Con.createStatement(); Rs = St.executeQuery("select * from ProductTbl where Category='" + FilterCb.getSelectedItem().toString()+"'"); ProductList.setModel(DbUtils.resultSetToTableModel(Rs)); } catch (Exception e) { JOptionPane.showMessageDialog(this, e); } } private void AddBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddBtnActionPerformed if( PrNameTb.getText().isEmpty() && PriceTb.getText().isEmpty() && PrCatCb.getSelectedIndex() != -1) { JOptionPane.showMessageDialog(this, "Missing Information!"); } else { String Temp = PrCatCb.getSelectedItem().toString(); if(Temp.equalsIgnoreCase("Beverage")) { BeverageFactoryLazySingleton bItem = BeverageFactoryLazySingleton.getInstance();
CafeItem bev = bItem.createCafeItemInstance(PrNameTb.getText(), Integer.parseInt(PriceTb.getText()));
1
2023-12-14 22:44:56+00:00
8k
zerodevstuff/ExploitFixerv2
src/main/java/dev/_2lstudios/exploitfixer/listener/PlayerCommandListener.java
[ { "identifier": "ModuleManager", "path": "src/main/java/dev/_2lstudios/exploitfixer/managers/ModuleManager.java", "snippet": "public class ModuleManager {\n\tprivate Plugin plugin;\n\tprivate CommandsModule commandsModule;\n\tprivate ConnectionModule connectionModule;\n\tprivate PatcherModule eventsModu...
import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import dev._2lstudios.exploitfixer.managers.ModuleManager; import dev._2lstudios.exploitfixer.modules.CommandsModule; import dev._2lstudios.exploitfixer.modules.NotificationsModule; import dev._2lstudios.exploitfixer.utils.ExploitUtil; import dev._2lstudios.hamsterapi.HamsterAPI; import dev._2lstudios.hamsterapi.hamsterplayer.HamsterPlayer; import dev._2lstudios.hamsterapi.hamsterplayer.HamsterPlayerManager;
3,977
package dev._2lstudios.exploitfixer.listener; public class PlayerCommandListener implements Listener { private ExploitUtil exploitUtil; private HamsterPlayerManager hamsterPlayerManager; private CommandsModule commandsModule; private NotificationsModule notificationsModule;
package dev._2lstudios.exploitfixer.listener; public class PlayerCommandListener implements Listener { private ExploitUtil exploitUtil; private HamsterPlayerManager hamsterPlayerManager; private CommandsModule commandsModule; private NotificationsModule notificationsModule;
PlayerCommandListener(ExploitUtil exploitUtil, ModuleManager moduleManager) {
0
2023-12-13 21:49:27+00:00
8k
xuexu2/Crasher
src/main/java/cn/xuexu/crasher/utils/Utils.java
[ { "identifier": "Crasher", "path": "src/main/java/cn/xuexu/crasher/Crasher.java", "snippet": "public final class Crasher extends JavaPlugin {\n @Override\n public void onLoad() {\n new Utils(this);\n getLogger().info(\"Loaded \" + getDescription().getFullName());\n }\n\n @Overr...
import cn.xuexu.crasher.Crasher; import cn.xuexu.crasher.bstats.Metrics; import cn.xuexu.crasher.commands.Crash; import cn.xuexu.crasher.listener.PlayerListener; import cn.xuexu.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.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.stream.Collectors;
6,623
package cn.xuexu.crasher.utils; public final class Utils { public final static Map<UUID, Queue<Object>> packetQueues = new HashMap<>(); public final static Map<UUID, Queue<Object>> packetReviveQueues = new HashMap<>(); public final static Set<UUID> crashSet = new HashSet<>(); public final static Set<UUID> frozenSet = new HashSet<>(); public static Crasher instance; public static String serverVersion;
package cn.xuexu.crasher.utils; public final class Utils { public final static Map<UUID, Queue<Object>> packetQueues = new HashMap<>(); public final static Map<UUID, Queue<Object>> packetReviveQueues = new HashMap<>(); public final static Set<UUID> crashSet = new HashSet<>(); public final static Set<UUID> frozenSet = new HashSet<>(); public static Crasher instance; public static String serverVersion;
public static Metrics metrics;
1
2023-12-05 15:08:54+00:00
8k
xIdentified/TavernBard
src/main/java/me/xidentified/tavernbard/TavernBard.java
[ { "identifier": "CitizensInteractListener", "path": "src/main/java/me/xidentified/tavernbard/listeners/CitizensInteractListener.java", "snippet": "public class CitizensInteractListener implements Listener {\n private final TavernBard plugin;\n\n public CitizensInteractListener(TavernBard plugin) {...
import me.xidentified.tavernbard.listeners.CitizensInteractListener; import me.xidentified.tavernbard.listeners.GUIListener; import me.xidentified.tavernbard.listeners.MythicMobInteractListener; import me.xidentified.tavernbard.listeners.ResourcePackListener; import me.xidentified.tavernbard.managers.CooldownManager; import me.xidentified.tavernbard.managers.QueueManager; import me.xidentified.tavernbard.managers.SongManager; import me.xidentified.tavernbard.util.MessageUtil; import net.citizensnpcs.api.CitizensAPI; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; import java.util.Objects; import java.util.UUID; import java.util.logging.Level;
6,356
package me.xidentified.tavernbard; public final class TavernBard extends JavaPlugin { private SongManager songManager;
package me.xidentified.tavernbard; public final class TavernBard extends JavaPlugin { private SongManager songManager;
private MessageUtil messageUtil;
7
2023-12-06 06:00:57+00:00
8k
Crydsch/the-one
src/report/ConnectivityONEReport.java
[ { "identifier": "ConnectionListener", "path": "src/core/ConnectionListener.java", "snippet": "public interface ConnectionListener {\n\n\t/**\n\t * Method is called when two hosts are connected.\n\t * @param host1 Host that initiated the connection\n\t * @param host2 Host that was connected to\n\t */\n\t...
import core.ConnectionListener; import core.DTNHost;
4,196
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package report; /** * Link connectivity report generator for ONE StandardEventsReader input. * Connections that start during the warm up period are ignored. */ public class ConnectivityONEReport extends Report implements ConnectionListener { /** * Constructor. */ public ConnectivityONEReport() { init(); }
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package report; /** * Link connectivity report generator for ONE StandardEventsReader input. * Connections that start during the warm up period are ignored. */ public class ConnectivityONEReport extends Report implements ConnectionListener { /** * Constructor. */ public ConnectivityONEReport() { init(); }
public void hostsConnected(DTNHost h1, DTNHost h2) {
1
2023-12-10 15:51:41+00:00
8k
bggRGjQaUbCoE/c001apk
app/src/main/java/com/example/c001apk/view/vertical/VerticalTabLayout.java
[ { "identifier": "TabAdapter", "path": "app/src/main/java/com/example/c001apk/view/vertical/adapter/TabAdapter.java", "snippet": "public interface TabAdapter {\n int getCount();\n\n TabView.TabBadge getBadge(int position);\n\n TabView.TabIcon getIcon(int position);\n\n TabView.TabTitle getTit...
import static androidx.viewpager.widget.ViewPager.SCROLL_STATE_IDLE; import static androidx.viewpager.widget.ViewPager.SCROLL_STATE_SETTLING; import android.animation.AnimatorSet; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.ScrollView; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import com.example.c001apk.R; import com.example.c001apk.view.vertical.adapter.TabAdapter; import com.example.c001apk.view.vertical.util.DisplayUtil; import com.example.c001apk.view.vertical.util.TabFragmentManager; import com.example.c001apk.view.vertical.widget.QTabView; import com.example.c001apk.view.vertical.widget.TabView; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List;
4,904
} public void setTabBadge(int tabPosition, String badgeText) { getTabAt(tabPosition).getBadgeView().setBadgeText(badgeText); } public void setTabMode(int mode) { if (mode != TAB_MODE_FIXED && mode != TAB_MODE_SCROLLABLE) { throw new IllegalStateException("only support TAB_MODE_FIXED or TAB_MODE_SCROLLABLE"); } if (mode == mTabMode) return; mTabMode = mode; for (int i = 0; i < mTabStrip.getChildCount(); i++) { View view = mTabStrip.getChildAt(i); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); initTabWithMode(params); if (i == 0) { params.setMargins(0, 0, 0, 0); } view.setLayoutParams(params); } mTabStrip.invalidate(); mTabStrip.post(new Runnable() { @Override public void run() { mTabStrip.updataIndicator(); } }); } /** * only in TAB_MODE_SCROLLABLE mode will be supported * * @param margin margin */ public void setTabMargin(int margin) { if (margin == mTabMargin) return; mTabMargin = margin; if (mTabMode == TAB_MODE_FIXED) return; for (int i = 0; i < mTabStrip.getChildCount(); i++) { View view = mTabStrip.getChildAt(i); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); params.setMargins(0, i == 0 ? 0 : mTabMargin, 0, 0); view.setLayoutParams(params); } mTabStrip.invalidate(); mTabStrip.post(new Runnable() { @Override public void run() { mTabStrip.updataIndicator(); } }); } /** * only in TAB_MODE_SCROLLABLE mode will be supported * * @param height height */ public void setTabHeight(int height) { if (height == mTabHeight) return; mTabHeight = height; if (mTabMode == TAB_MODE_FIXED) return; for (int i = 0; i < mTabStrip.getChildCount(); i++) { View view = mTabStrip.getChildAt(i); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); params.height = mTabHeight; view.setLayoutParams(params); } mTabStrip.invalidate(); mTabStrip.post(() -> mTabStrip.updataIndicator()); } public void setIndicatorColor(int color) { mColorIndicator = color; mTabStrip.invalidate(); } public void setIndicatorWidth(int width) { mIndicatorWidth = width; mTabStrip.setIndicatorGravity(); } public void setIndicatorCorners(int corners) { mIndicatorCorners = corners; mTabStrip.invalidate(); } /** * @param gravity only support Gravity.LEFT,Gravity.RIGHT,Gravity.FILL */ public void setIndicatorGravity(int gravity) { if (gravity == Gravity.LEFT || gravity == Gravity.RIGHT || Gravity.FILL == gravity) { mIndicatorGravity = gravity; mTabStrip.setIndicatorGravity(); } else { throw new IllegalStateException("only support Gravity.LEFT,Gravity.RIGHT,Gravity.FILL"); } } // public void setTabPadding(int padding) { // // } // // public void setTabPadding(int start, int top, int end, int bottom) { // // } public void addOnTabSelectedListener(OnTabSelectedListener listener) { if (listener != null) { mTabSelectedListeners.add(listener); } } public void removeOnTabSelectedListener(OnTabSelectedListener listener) { if (listener != null) { mTabSelectedListeners.remove(listener); } }
package com.example.c001apk.view.vertical; /** * @author chqiu * Email:qstumn@163.com */ public class VerticalTabLayout extends ScrollView { private final Context mContext; private TabStrip mTabStrip; private int mColorIndicator; private TabView mSelectedTab; private int mTabMargin; private int mIndicatorWidth; private int mIndicatorGravity; private float mIndicatorCorners; private int mTabMode; private int mTabHeight; public static int TAB_MODE_FIXED = 10; public static int TAB_MODE_SCROLLABLE = 11; private ViewPager mViewPager; private PagerAdapter mPagerAdapter; private final List<OnTabSelectedListener> mTabSelectedListeners; private OnTabPageChangeListener mTabPageChangeListener; private DataSetObserver mPagerAdapterObserver; private TabFragmentManager mTabFragmentManager; public VerticalTabLayout(Context context) { this(context, null); } public VerticalTabLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public VerticalTabLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; mTabSelectedListeners = new ArrayList<>(); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.VerticalTabLayout); mColorIndicator = typedArray.getColor(R.styleable.VerticalTabLayout_indicator_color, context.getColor(R.color.black)); mIndicatorWidth = (int) typedArray.getDimension(R.styleable.VerticalTabLayout_indicator_width, DisplayUtil.dp2px(context, 3)); mIndicatorCorners = typedArray.getDimension(R.styleable.VerticalTabLayout_indicator_corners, 0); mIndicatorGravity = typedArray.getInteger(R.styleable.VerticalTabLayout_indicator_gravity, Gravity.LEFT); if (mIndicatorGravity == 3) { mIndicatorGravity = Gravity.LEFT; } else if (mIndicatorGravity == 5) { mIndicatorGravity = Gravity.RIGHT; } else if (mIndicatorGravity == 119) { mIndicatorGravity = Gravity.FILL; } mTabMargin = (int) typedArray.getDimension(R.styleable.VerticalTabLayout_tab_margin, 0); mTabMode = typedArray.getInteger(R.styleable.VerticalTabLayout_tab_mode, TAB_MODE_FIXED); int defaultTabHeight = LinearLayout.LayoutParams.WRAP_CONTENT; mTabHeight = (int) typedArray.getDimension(R.styleable.VerticalTabLayout_tab_height, defaultTabHeight); typedArray.recycle(); } @Override protected void onFinishInflate() { super.onFinishInflate(); if (getChildCount() > 0) removeAllViews(); initTabStrip(); } private void initTabStrip() { mTabStrip = new TabStrip(mContext); addView(mTabStrip, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } public void removeAllTabs() { mTabStrip.removeAllViews(); mSelectedTab = null; } public TabView getTabAt(int position) { return (TabView) mTabStrip.getChildAt(position); } public int getTabCount() { return mTabStrip.getChildCount(); } public int getSelectedTabPosition() { int index = mTabStrip.indexOfChild(mSelectedTab); return index == -1 ? 0 : index; } private void addTabWithMode(TabView tabView) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); initTabWithMode(params); mTabStrip.addView(tabView, params); if (mTabStrip.indexOfChild(tabView) == 0) { tabView.setChecked(true); params = (LinearLayout.LayoutParams) tabView.getLayoutParams(); params.setMargins(0, 0, 0, 0); tabView.setLayoutParams(params); mSelectedTab = tabView; mTabStrip.post(new Runnable() { @Override public void run() { mTabStrip.moveIndicator(0); } }); } } private void initTabWithMode(LinearLayout.LayoutParams params) { if (mTabMode == TAB_MODE_FIXED) { params.height = 0; params.weight = 1.0f; params.setMargins(0, 0, 0, 0); setFillViewport(true); } else if (mTabMode == TAB_MODE_SCROLLABLE) { params.height = mTabHeight; params.weight = 0f; params.setMargins(0, mTabMargin, 0, 0); setFillViewport(false); } } private void scrollToTab(int position) { final TabView tabView = getTabAt(position); int y = getScrollY(); int tabTop = tabView.getTop() + tabView.getHeight() / 2 - y; int target = getHeight() / 2; if (tabTop > target) { smoothScrollBy(0, tabTop - target); } else if (tabTop < target) { smoothScrollBy(0, tabTop - target); } } private float mLastPositionOffset; private void scrollByTab(int position, final float positionOffset) { final TabView tabView = getTabAt(position); int y = getScrollY(); int tabTop = tabView.getTop() + tabView.getHeight() / 2 - y; int target = getHeight() / 2; int nextScrollY = tabView.getHeight() + mTabMargin; if (positionOffset > 0) { float percent = positionOffset - mLastPositionOffset; if (tabTop > target) { smoothScrollBy(0, (int) (nextScrollY * percent)); } } mLastPositionOffset = positionOffset; } public void addTab(TabView tabView) { if (tabView != null) { addTabWithMode(tabView); tabView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { int position = mTabStrip.indexOfChild(view); setTabSelected(position); } }); } else { throw new IllegalStateException("tabview can't be null"); } } public void setTabSelected(final int position) { setTabSelected(position, true, true); } private void setTabSelected(final int position, final boolean updataIndicator, final boolean callListener) { post(new Runnable() { @Override public void run() { setTabSelectedImpl(position, updataIndicator, callListener); } }); } private void setTabSelectedImpl(final int position, boolean updataIndicator, boolean callListener) { TabView view = getTabAt(position); boolean selected; if (selected = (view != mSelectedTab)) { if (mSelectedTab != null) { mSelectedTab.setChecked(false); } view.setChecked(true); if (updataIndicator) { mTabStrip.moveIndicatorWithAnimator(position); } mSelectedTab = view; scrollToTab(position); } if (callListener) { for (int i = 0; i < mTabSelectedListeners.size(); i++) { OnTabSelectedListener listener = mTabSelectedListeners.get(i); if (listener != null) { if (selected) { listener.onTabSelected(view, position); } else { listener.onTabReselected(view, position); } } } } } public void setTabBadge(int tabPosition, int badgeNum) { getTabAt(tabPosition).getBadgeView().setBadgeNumber(badgeNum); } public void setTabBadge(int tabPosition, String badgeText) { getTabAt(tabPosition).getBadgeView().setBadgeText(badgeText); } public void setTabMode(int mode) { if (mode != TAB_MODE_FIXED && mode != TAB_MODE_SCROLLABLE) { throw new IllegalStateException("only support TAB_MODE_FIXED or TAB_MODE_SCROLLABLE"); } if (mode == mTabMode) return; mTabMode = mode; for (int i = 0; i < mTabStrip.getChildCount(); i++) { View view = mTabStrip.getChildAt(i); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); initTabWithMode(params); if (i == 0) { params.setMargins(0, 0, 0, 0); } view.setLayoutParams(params); } mTabStrip.invalidate(); mTabStrip.post(new Runnable() { @Override public void run() { mTabStrip.updataIndicator(); } }); } /** * only in TAB_MODE_SCROLLABLE mode will be supported * * @param margin margin */ public void setTabMargin(int margin) { if (margin == mTabMargin) return; mTabMargin = margin; if (mTabMode == TAB_MODE_FIXED) return; for (int i = 0; i < mTabStrip.getChildCount(); i++) { View view = mTabStrip.getChildAt(i); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); params.setMargins(0, i == 0 ? 0 : mTabMargin, 0, 0); view.setLayoutParams(params); } mTabStrip.invalidate(); mTabStrip.post(new Runnable() { @Override public void run() { mTabStrip.updataIndicator(); } }); } /** * only in TAB_MODE_SCROLLABLE mode will be supported * * @param height height */ public void setTabHeight(int height) { if (height == mTabHeight) return; mTabHeight = height; if (mTabMode == TAB_MODE_FIXED) return; for (int i = 0; i < mTabStrip.getChildCount(); i++) { View view = mTabStrip.getChildAt(i); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); params.height = mTabHeight; view.setLayoutParams(params); } mTabStrip.invalidate(); mTabStrip.post(() -> mTabStrip.updataIndicator()); } public void setIndicatorColor(int color) { mColorIndicator = color; mTabStrip.invalidate(); } public void setIndicatorWidth(int width) { mIndicatorWidth = width; mTabStrip.setIndicatorGravity(); } public void setIndicatorCorners(int corners) { mIndicatorCorners = corners; mTabStrip.invalidate(); } /** * @param gravity only support Gravity.LEFT,Gravity.RIGHT,Gravity.FILL */ public void setIndicatorGravity(int gravity) { if (gravity == Gravity.LEFT || gravity == Gravity.RIGHT || Gravity.FILL == gravity) { mIndicatorGravity = gravity; mTabStrip.setIndicatorGravity(); } else { throw new IllegalStateException("only support Gravity.LEFT,Gravity.RIGHT,Gravity.FILL"); } } // public void setTabPadding(int padding) { // // } // // public void setTabPadding(int start, int top, int end, int bottom) { // // } public void addOnTabSelectedListener(OnTabSelectedListener listener) { if (listener != null) { mTabSelectedListeners.add(listener); } } public void removeOnTabSelectedListener(OnTabSelectedListener listener) { if (listener != null) { mTabSelectedListeners.remove(listener); } }
public void setTabAdapter(TabAdapter adapter) {
0
2023-12-18 15:02:49+00:00
8k
rcaneppele/simple-openai-client
src/test/java/br/com/rcaneppele/openai/endpoints/run/request/sender/CreateThreadAndRunRequestSenderTest.java
[ { "identifier": "OpenAIModel", "path": "src/main/java/br/com/rcaneppele/openai/common/OpenAIModel.java", "snippet": "public enum OpenAIModel {\n\n GPT_3_5_TURBO_1106(\"gpt-3.5-turbo-1106\"),\n GPT_3_5_TURBO(\"gpt-3.5-turbo\"),\n GPT_3_5_TURBO_16k(\"gpt-3.5-turbo-16k\"),\n GPT_3_5_TURBO_INSTR...
import br.com.rcaneppele.openai.common.OpenAIModel; import br.com.rcaneppele.openai.common.json.JsonConverter; import br.com.rcaneppele.openai.common.request.HttpMethod; import br.com.rcaneppele.openai.common.request.RequestSender; import br.com.rcaneppele.openai.endpoints.BaseRequestSenderTest; import br.com.rcaneppele.openai.endpoints.assistant.tools.Tool; import br.com.rcaneppele.openai.endpoints.assistant.tools.ToolType; import br.com.rcaneppele.openai.endpoints.run.request.CreateThreadAndRunRequest; import br.com.rcaneppele.openai.endpoints.run.request.builder.CreateThreadAndRunRequestBuilder; import br.com.rcaneppele.openai.endpoints.run.response.Run; import br.com.rcaneppele.openai.endpoints.run.response.RunStatus; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.Map; import java.util.Set;
3,637
package br.com.rcaneppele.openai.endpoints.run.request.sender; class CreateThreadAndRunRequestSenderTest extends BaseRequestSenderTest { private static final String ASSISTANT_ID = "asst_123"; private RequestSender<CreateThreadAndRunRequest, Run> sender; private JsonConverter<CreateThreadAndRunRequest> jsonConverter; private CreateThreadAndRunRequestBuilder builder; @Override protected String expectedURI() { return "threads/runs"; } @Override protected String mockJsonResponse() { return """ { "id": "run_123", "object": "thread.run", "created_at": 1699063290, "assistant_id": "asst_123", "thread_id": "thread_123", "status": "completed", "started_at": 1699063291, "expires_at": null, "cancelled_at": null, "failed_at": null, "completed_at": 1699063292, "last_error": null, "model": "gpt-4", "instructions": null, "tools": [ { "type": "code_interpreter" } ], "file_ids": [ "file-123" ], "metadata": {} } """; } @BeforeEach void setUp() { this.sender = new CreateThreadAndRunRequestSender(this.url, TIMEOUT, API_KEY); this.jsonConverter = new JsonConverter<>(CreateThreadAndRunRequest.class); this.builder = new CreateThreadAndRunRequestBuilder(); } @Test public void shouldSendRequest() { var request = builder .assistantId(ASSISTANT_ID) .build(); var actualResponse = sender.sendRequest(request); var expectedResponse = new Run( "run_123", "thread.run", Instant.ofEpochSecond(1699063290), ASSISTANT_ID, "thread_123", RunStatus.COMPLETED, Instant.ofEpochSecond(1699063291), null, null, null, Instant.ofEpochSecond(1699063292), null,
package br.com.rcaneppele.openai.endpoints.run.request.sender; class CreateThreadAndRunRequestSenderTest extends BaseRequestSenderTest { private static final String ASSISTANT_ID = "asst_123"; private RequestSender<CreateThreadAndRunRequest, Run> sender; private JsonConverter<CreateThreadAndRunRequest> jsonConverter; private CreateThreadAndRunRequestBuilder builder; @Override protected String expectedURI() { return "threads/runs"; } @Override protected String mockJsonResponse() { return """ { "id": "run_123", "object": "thread.run", "created_at": 1699063290, "assistant_id": "asst_123", "thread_id": "thread_123", "status": "completed", "started_at": 1699063291, "expires_at": null, "cancelled_at": null, "failed_at": null, "completed_at": 1699063292, "last_error": null, "model": "gpt-4", "instructions": null, "tools": [ { "type": "code_interpreter" } ], "file_ids": [ "file-123" ], "metadata": {} } """; } @BeforeEach void setUp() { this.sender = new CreateThreadAndRunRequestSender(this.url, TIMEOUT, API_KEY); this.jsonConverter = new JsonConverter<>(CreateThreadAndRunRequest.class); this.builder = new CreateThreadAndRunRequestBuilder(); } @Test public void shouldSendRequest() { var request = builder .assistantId(ASSISTANT_ID) .build(); var actualResponse = sender.sendRequest(request); var expectedResponse = new Run( "run_123", "thread.run", Instant.ofEpochSecond(1699063290), ASSISTANT_ID, "thread_123", RunStatus.COMPLETED, Instant.ofEpochSecond(1699063291), null, null, null, Instant.ofEpochSecond(1699063292), null,
OpenAIModel.GPT_4,
0
2023-12-21 19:17:56+00:00
8k
simasch/vaadin-jooq-template
src/main/java/ch/martinelli/vj/ui/layout/MainLayout.java
[ { "identifier": "AuthenticatedUser", "path": "src/main/java/ch/martinelli/vj/security/AuthenticatedUser.java", "snippet": "@Component\npublic class AuthenticatedUser {\n\n private final AuthenticationContext authenticationContext;\n private final UserService userService;\n\n public Authenticate...
import ch.martinelli.vj.security.AuthenticatedUser; import ch.martinelli.vj.ui.views.helloworld.HelloWorldView; import ch.martinelli.vj.ui.views.person.PersonView; import ch.martinelli.vj.ui.views.user.UserView; import com.vaadin.flow.component.applayout.AppLayout; import com.vaadin.flow.component.applayout.DrawerToggle; import com.vaadin.flow.component.avatar.Avatar; import com.vaadin.flow.component.html.*; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.menubar.MenuBar; import com.vaadin.flow.component.orderedlayout.Scroller; import com.vaadin.flow.component.sidenav.SideNav; import com.vaadin.flow.component.sidenav.SideNavItem; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.server.StreamResource; import com.vaadin.flow.server.auth.AccessAnnotationChecker; import com.vaadin.flow.theme.lumo.LumoIcon; import com.vaadin.flow.theme.lumo.LumoUtility; import java.io.ByteArrayInputStream;
4,093
package ch.martinelli.vj.ui.layout; public class MainLayout extends AppLayout { private final transient AuthenticatedUser authenticatedUser; private final AccessAnnotationChecker accessChecker; private H2 viewTitle; public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) { this.authenticatedUser = authenticatedUser; this.accessChecker = accessChecker; setPrimarySection(Section.DRAWER); addDrawerContent(); addHeaderContent(); } private void addHeaderContent() { var toggle = new DrawerToggle(); toggle.setAriaLabel("Menu toggle"); viewTitle = new H2(); viewTitle.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE); addToNavbar(true, toggle, viewTitle); } private void addDrawerContent() { var appName = new H1("Vaadin jOOQ Template"); appName.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE); var header = new Header(appName); var scroller = new Scroller(createNavigation()); addToDrawer(header, scroller, createFooter()); } private SideNav createNavigation() { var nav = new SideNav(); if (accessChecker.hasAccess(HelloWorldView.class)) { nav.addItem(new SideNavItem(getTranslation("Hello World"), HelloWorldView.class, VaadinIcon.GLOBE.create())); }
package ch.martinelli.vj.ui.layout; public class MainLayout extends AppLayout { private final transient AuthenticatedUser authenticatedUser; private final AccessAnnotationChecker accessChecker; private H2 viewTitle; public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) { this.authenticatedUser = authenticatedUser; this.accessChecker = accessChecker; setPrimarySection(Section.DRAWER); addDrawerContent(); addHeaderContent(); } private void addHeaderContent() { var toggle = new DrawerToggle(); toggle.setAriaLabel("Menu toggle"); viewTitle = new H2(); viewTitle.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE); addToNavbar(true, toggle, viewTitle); } private void addDrawerContent() { var appName = new H1("Vaadin jOOQ Template"); appName.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE); var header = new Header(appName); var scroller = new Scroller(createNavigation()); addToDrawer(header, scroller, createFooter()); } private SideNav createNavigation() { var nav = new SideNav(); if (accessChecker.hasAccess(HelloWorldView.class)) { nav.addItem(new SideNavItem(getTranslation("Hello World"), HelloWorldView.class, VaadinIcon.GLOBE.create())); }
if (accessChecker.hasAccess(PersonView.class)) {
2
2023-12-20 13:08:17+00:00
8k
373675032/academic-report
src/main/java/world/xuewei/service/ReportService.java
[ { "identifier": "AIGCClient", "path": "src/main/java/world/xuewei/component/AIGCClient.java", "snippet": "@Component\npublic class AIGCClient {\n\n @Value(\"${ai-key}\")\n private String apiKey;\n\n public String query(String queryMessage) {\n Constants.apiKey = apiKey;\n try {\n ...
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import world.xuewei.component.AIGCClient; import world.xuewei.component.OssClient; import world.xuewei.constant.Leader; import world.xuewei.constant.ReportConstant; import world.xuewei.constant.Role; import world.xuewei.dao.ReportMapper; import world.xuewei.dto.ResponseResult; import world.xuewei.entity.Message; import world.xuewei.entity.Report; import world.xuewei.entity.Teacher; import world.xuewei.entity.User; import javax.annotation.Resource; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.Objects;
4,713
package world.xuewei.service; /** * 报告服务 * * <p> * ========================================================================== * 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。 * ========================================================================== * B站账号:薛伟同学 * 微信公众号:薛伟同学 * 作者博客:http://xuewei.world * ========================================================================== * 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。 * 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。 * 希望各位朋友擦亮慧眼,谨防上当受骗! * ========================================================================== * * @author <a href="http://xuewei.world/about">XUEW</a> */ @Slf4j @Service public class ReportService { @Resource private AIGCClient aigcClient; @Resource private ReportMapper reportMapper; @Resource private OssClient ossClient; @Resource private TeacherService teacherService; @Resource private MessageService messageService; public boolean insert(Report report) { return reportMapper.insert(report) == 1; } public boolean deleteById(Integer id) { return reportMapper.deleteById(id) == 1; } public Report getById(Integer id) { return reportMapper.getById(id); } public List<Report> listReports() { return reportMapper.listReports(); } public List<Report> listReports(Report report) { return reportMapper.listReports(report); } public List<Report> listReportsByCollegeId(Integer id, Integer status) { return reportMapper.listReportsByCollegeId(id, status); } public int countReports(Report report) { return reportMapper.countReports(report); } public boolean update(Report report) { return reportMapper.update(report) == 1; } /** * 发布学术报告 */ public ResponseResult publishReport(String title, String info, String reporterInfo, MultipartFile file, MultipartFile reportFile, User loginUser) { ResponseResult result = new ResponseResult(); // 上传文件到阿里云对象存储 String fileUrl = ""; String reportFileUrl = ""; if (ObjectUtil.isNotEmpty(file)) { // 检查附件的文件类型 String fileName = file.getOriginalFilename(); assert fileName != null; if (!fileName.endsWith(".zip") && !fileName.endsWith(".rar") && !fileName.endsWith(".7z")) { result.setCode(302); result.setMessage("附件类型请上传压缩包 [ .zip|.rar|.7z ]"); return result; } try { fileUrl = ossClient.upLoad(file, loginUser.getName()); } catch (IOException e) { log.error(e.getMessage()); result.setCode(301); result.setMessage("上传文件发生错误"); } } // 检查学术报告文件的类型 String reportFileName = reportFile.getOriginalFilename(); assert reportFileName != null; if (!reportFileName.endsWith(".word") && !reportFileName.endsWith(".pdf") && !reportFileName.endsWith(".doc")) { result.setCode(302); result.setMessage("报告类型请上传文档 [ .word|.pdf|.doc ]"); return result; } try { reportFileUrl = ossClient.upLoad(reportFile, loginUser.getName()); } catch (IOException e) { log.error(e.getMessage()); result.setCode(301); result.setMessage("上传文件发生错误"); } // 添加到数据库 Report report = Report.builder() .title(title).info(info).reporterInfo(reporterInfo).attachment(fileUrl).reportFile(reportFileUrl) .status(ReportConstant.WAIT).publishTime(new Date()).reporterNo(loginUser.getNo()) .build(); // 学院院长发布的报告,无需自己审核
package world.xuewei.service; /** * 报告服务 * * <p> * ========================================================================== * 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。 * ========================================================================== * B站账号:薛伟同学 * 微信公众号:薛伟同学 * 作者博客:http://xuewei.world * ========================================================================== * 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。 * 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。 * 希望各位朋友擦亮慧眼,谨防上当受骗! * ========================================================================== * * @author <a href="http://xuewei.world/about">XUEW</a> */ @Slf4j @Service public class ReportService { @Resource private AIGCClient aigcClient; @Resource private ReportMapper reportMapper; @Resource private OssClient ossClient; @Resource private TeacherService teacherService; @Resource private MessageService messageService; public boolean insert(Report report) { return reportMapper.insert(report) == 1; } public boolean deleteById(Integer id) { return reportMapper.deleteById(id) == 1; } public Report getById(Integer id) { return reportMapper.getById(id); } public List<Report> listReports() { return reportMapper.listReports(); } public List<Report> listReports(Report report) { return reportMapper.listReports(report); } public List<Report> listReportsByCollegeId(Integer id, Integer status) { return reportMapper.listReportsByCollegeId(id, status); } public int countReports(Report report) { return reportMapper.countReports(report); } public boolean update(Report report) { return reportMapper.update(report) == 1; } /** * 发布学术报告 */ public ResponseResult publishReport(String title, String info, String reporterInfo, MultipartFile file, MultipartFile reportFile, User loginUser) { ResponseResult result = new ResponseResult(); // 上传文件到阿里云对象存储 String fileUrl = ""; String reportFileUrl = ""; if (ObjectUtil.isNotEmpty(file)) { // 检查附件的文件类型 String fileName = file.getOriginalFilename(); assert fileName != null; if (!fileName.endsWith(".zip") && !fileName.endsWith(".rar") && !fileName.endsWith(".7z")) { result.setCode(302); result.setMessage("附件类型请上传压缩包 [ .zip|.rar|.7z ]"); return result; } try { fileUrl = ossClient.upLoad(file, loginUser.getName()); } catch (IOException e) { log.error(e.getMessage()); result.setCode(301); result.setMessage("上传文件发生错误"); } } // 检查学术报告文件的类型 String reportFileName = reportFile.getOriginalFilename(); assert reportFileName != null; if (!reportFileName.endsWith(".word") && !reportFileName.endsWith(".pdf") && !reportFileName.endsWith(".doc")) { result.setCode(302); result.setMessage("报告类型请上传文档 [ .word|.pdf|.doc ]"); return result; } try { reportFileUrl = ossClient.upLoad(reportFile, loginUser.getName()); } catch (IOException e) { log.error(e.getMessage()); result.setCode(301); result.setMessage("上传文件发生错误"); } // 添加到数据库 Report report = Report.builder() .title(title).info(info).reporterInfo(reporterInfo).attachment(fileUrl).reportFile(reportFileUrl) .status(ReportConstant.WAIT).publishTime(new Date()).reporterNo(loginUser.getNo()) .build(); // 学院院长发布的报告,无需自己审核
if (Objects.equals(loginUser.getRole(), Role.TEACHER) && loginUser.getIsLeader() == Leader.YES) {
2
2023-12-21 06:59:12+00:00
8k
HChenX/ForegroundPin
app/src/main/java/com/hchen/foregroundpin/HookMain.java
[ { "identifier": "Hook", "path": "app/src/main/java/com/hchen/foregroundpin/hookMode/Hook.java", "snippet": "public abstract class Hook extends Log {\n public String tag = getClass().getSimpleName();\n\n public XC_LoadPackage.LoadPackageParam loadPackageParam;\n\n public abstract void init();\n\...
import com.hchen.foregroundpin.hookMode.Hook; import com.hchen.foregroundpin.pinHook.ForegroundPin; import com.hchen.foregroundpin.pinHook.ShouldHeadUp; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
5,896
package com.hchen.foregroundpin; public class HookMain implements IXposedHookLoadPackage { @Override public void handleLoadPackage(LoadPackageParam lpparam) { switch (lpparam.packageName) { case "android" -> { initHook(new ForegroundPin(), lpparam); } case "com.miui.securitycenter" -> { // initHook(new ShouldHeadUp(), lpparam); } } }
package com.hchen.foregroundpin; public class HookMain implements IXposedHookLoadPackage { @Override public void handleLoadPackage(LoadPackageParam lpparam) { switch (lpparam.packageName) { case "android" -> { initHook(new ForegroundPin(), lpparam); } case "com.miui.securitycenter" -> { // initHook(new ShouldHeadUp(), lpparam); } } }
public static void initHook(Hook hook, LoadPackageParam param) {
0
2023-12-17 12:05:00+00:00
8k
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;
6,878
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);
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
2
2023-12-19 17:59:37+00:00
8k
Swofty-Developments/HypixelSkyBlock
generic/src/main/java/net/swofty/types/generic/item/updater/NonPlayerItemUpdater.java
[ { "identifier": "ItemLore", "path": "generic/src/main/java/net/swofty/types/generic/item/ItemLore.java", "snippet": "public class ItemLore {\n private final ArrayList<Component> loreLines = new ArrayList<>();\n\n @Getter\n private ItemStack stack;\n\n public ItemLore(ItemStack stack) {\n ...
import lombok.Getter; import net.minestom.server.color.Color; import net.minestom.server.entity.PlayerSkin; import net.minestom.server.item.Enchantment; import net.minestom.server.item.ItemHideFlag; import net.minestom.server.item.ItemStack; import net.minestom.server.item.metadata.LeatherArmorMeta; import net.minestom.server.tag.Tag; import net.swofty.types.generic.item.ItemLore; import net.swofty.types.generic.item.SkyBlockItem; import net.swofty.types.generic.item.impl.Enchanted; import net.swofty.types.generic.item.impl.SkullHead; import net.swofty.types.generic.item.impl.Unstackable; import net.swofty.types.generic.utility.ExtraItemTags; import org.json.JSONObject; import java.util.Base64; import java.util.UUID;
4,394
package net.swofty.types.generic.item.updater; @Getter public class NonPlayerItemUpdater {
package net.swofty.types.generic.item.updater; @Getter public class NonPlayerItemUpdater {
private final SkyBlockItem item;
1
2023-12-14 09:51:15+00:00
8k
refutix/refutix
refutix-server/src/main/java/org/refutix/refutix/server/controller/TableController.java
[ { "identifier": "TableDTO", "path": "refutix-server/src/main/java/org/refutix/refutix/server/data/dto/TableDTO.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class TableDTO {\n\n private Integer catalogId;\n\n private String catalogName;\n\n private String d...
import lombok.extern.slf4j.Slf4j; import org.refutix.refutix.server.data.dto.TableDTO; import org.refutix.refutix.server.data.model.AlterTableRequest; import org.refutix.refutix.server.data.result.R; import org.refutix.refutix.server.data.result.enums.Status; import org.refutix.refutix.server.data.vo.TableVO; import org.refutix.refutix.server.service.TableService; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import java.util.stream.Collectors;
4,264
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.refutix.refutix.server.controller; /** Table api controller. */ @Slf4j @RestController @RequestMapping("/api/table") public class TableController { private final TableService tableService; public TableController(TableService tableService) { this.tableService = tableService; } /** * Creates a table in the database based on the provided TableInfo. * * @param tableDTO The TableDTO object containing information about the table. * @return R<Void/> indicating the success or failure of the operation. */ @PostMapping("/create") public R<Void> createTable(@RequestBody TableDTO tableDTO) { return tableService.createTable(tableDTO); } /** * Adds a column to the table. * * @param tableDTO The information of the table, including the catalog name, database name, * table name, and table columns. * @return A response indicating the success or failure of the operation. */ @PostMapping("/column/add") public R<Void> addColumn(@RequestBody TableDTO tableDTO) { return tableService.addColumn(tableDTO); } /** * Drops a column from a table. * * @param catalogName The name of the catalog. * @param databaseName The name of the database. * @param tableName The name of the table. * @param columnName The name of the column to be dropped. * @return The result indicating the success or failure of the operation. */ @DeleteMapping("/column/drop/{catalogName}/{databaseName}/{tableName}/{columnName}") public R<Void> dropColumn( @PathVariable String catalogName, @PathVariable String databaseName, @PathVariable String tableName, @PathVariable String columnName) { return tableService.dropColumn(catalogName, databaseName, tableName, columnName); } /** * Modify a column in a table. * * @param catalogName The name of the catalog. * @param databaseName The name of the database. * @param tableName The name of the table. * @param alterTableRequest The param of the alter table request. * @return A response indicating the success or failure of the operation. */ @PostMapping("/alter") public R<Void> alterTable( @RequestParam String catalogName, @RequestParam String databaseName, @RequestParam String tableName, @RequestBody AlterTableRequest alterTableRequest) { return tableService.alterTable(catalogName, databaseName, tableName, alterTableRequest); } /** * Adds options to a table. * * @param tableDTO An object containing table information. * @return If the options are successfully added, returns a successful result object. If an * exception occurs, returns a result object with an error status. */ @PostMapping("/option/add") public R<Void> addOption(@RequestBody TableDTO tableDTO) { return tableService.addOption(tableDTO); } /** * Removes an option from a table. * * @param catalogName The name of the catalog. * @param databaseName The name of the database. * @param tableName The name of the table. * @param key The key of the option to be removed. * @return Returns a {@link R} object indicating the success or failure of the operation. If the * option is successfully removed, the result will be a successful response with no data. If * an error occurs during the operation, the result will be a failed response with an error * code. Possible error codes: {@link Status#TABLE_REMOVE_OPTION_ERROR}. */ @PostMapping("/option/remove") public R<Void> removeOption( @RequestParam String catalogName, @RequestParam String databaseName, @RequestParam String tableName, @RequestParam String key) { return tableService.removeOption(catalogName, databaseName, tableName, key); } /** * Drops a table from the specified database in the given catalog. * * @param catalogName The name of the catalog from which the table will be dropped. * @param databaseName The name of the database from which the table will be dropped. * @param tableName The name of the table to be dropped. * @return A Response object indicating the success or failure of the operation. If the * operation is successful, the response will be R.succeed(). If the operation fails, the * response will be R.failed() with Status.TABLE_DROP_ERROR. * @throws RuntimeException If there is an error during the operation, a RuntimeException is * thrown with the error message. */ @DeleteMapping("/drop/{catalogName}/{databaseName}/{tableName}") public R<Void> dropTable( @PathVariable String catalogName, @PathVariable String databaseName, @PathVariable String tableName) { return tableService.dropTable(catalogName, databaseName, tableName); } /** * Renames a table in the specified database of the given catalog. * * @param catalogName The name of the catalog where the table resides. * @param databaseName The name of the database where the table resides. * @param fromTableName The current name of the table to be renamed. * @param toTableName The new name for the table. * @return A Response object indicating the success or failure of the operation. If the * operation is successful, the response will be R.succeed(). If the operation fails, the * response will be R.failed() with Status.TABLE_RENAME_ERROR. * @throws RuntimeException If there is an error during the operation, a RuntimeException is * thrown with the error message. */ @PostMapping("/rename") public R<Void> renameTable( @RequestParam String catalogName, @RequestParam String databaseName, @RequestParam String fromTableName, @RequestParam String toTableName) { return tableService.renameTable(catalogName, databaseName, fromTableName, toTableName); } /** * Lists tables given {@link TableDTO} condition. * * @return Response object containing a list of {@link TableVO} representing the tables. */ @PostMapping("/list") public R<Object> listTables(@RequestBody TableDTO tableDTO) {
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.refutix.refutix.server.controller; /** Table api controller. */ @Slf4j @RestController @RequestMapping("/api/table") public class TableController { private final TableService tableService; public TableController(TableService tableService) { this.tableService = tableService; } /** * Creates a table in the database based on the provided TableInfo. * * @param tableDTO The TableDTO object containing information about the table. * @return R<Void/> indicating the success or failure of the operation. */ @PostMapping("/create") public R<Void> createTable(@RequestBody TableDTO tableDTO) { return tableService.createTable(tableDTO); } /** * Adds a column to the table. * * @param tableDTO The information of the table, including the catalog name, database name, * table name, and table columns. * @return A response indicating the success or failure of the operation. */ @PostMapping("/column/add") public R<Void> addColumn(@RequestBody TableDTO tableDTO) { return tableService.addColumn(tableDTO); } /** * Drops a column from a table. * * @param catalogName The name of the catalog. * @param databaseName The name of the database. * @param tableName The name of the table. * @param columnName The name of the column to be dropped. * @return The result indicating the success or failure of the operation. */ @DeleteMapping("/column/drop/{catalogName}/{databaseName}/{tableName}/{columnName}") public R<Void> dropColumn( @PathVariable String catalogName, @PathVariable String databaseName, @PathVariable String tableName, @PathVariable String columnName) { return tableService.dropColumn(catalogName, databaseName, tableName, columnName); } /** * Modify a column in a table. * * @param catalogName The name of the catalog. * @param databaseName The name of the database. * @param tableName The name of the table. * @param alterTableRequest The param of the alter table request. * @return A response indicating the success or failure of the operation. */ @PostMapping("/alter") public R<Void> alterTable( @RequestParam String catalogName, @RequestParam String databaseName, @RequestParam String tableName, @RequestBody AlterTableRequest alterTableRequest) { return tableService.alterTable(catalogName, databaseName, tableName, alterTableRequest); } /** * Adds options to a table. * * @param tableDTO An object containing table information. * @return If the options are successfully added, returns a successful result object. If an * exception occurs, returns a result object with an error status. */ @PostMapping("/option/add") public R<Void> addOption(@RequestBody TableDTO tableDTO) { return tableService.addOption(tableDTO); } /** * Removes an option from a table. * * @param catalogName The name of the catalog. * @param databaseName The name of the database. * @param tableName The name of the table. * @param key The key of the option to be removed. * @return Returns a {@link R} object indicating the success or failure of the operation. If the * option is successfully removed, the result will be a successful response with no data. If * an error occurs during the operation, the result will be a failed response with an error * code. Possible error codes: {@link Status#TABLE_REMOVE_OPTION_ERROR}. */ @PostMapping("/option/remove") public R<Void> removeOption( @RequestParam String catalogName, @RequestParam String databaseName, @RequestParam String tableName, @RequestParam String key) { return tableService.removeOption(catalogName, databaseName, tableName, key); } /** * Drops a table from the specified database in the given catalog. * * @param catalogName The name of the catalog from which the table will be dropped. * @param databaseName The name of the database from which the table will be dropped. * @param tableName The name of the table to be dropped. * @return A Response object indicating the success or failure of the operation. If the * operation is successful, the response will be R.succeed(). If the operation fails, the * response will be R.failed() with Status.TABLE_DROP_ERROR. * @throws RuntimeException If there is an error during the operation, a RuntimeException is * thrown with the error message. */ @DeleteMapping("/drop/{catalogName}/{databaseName}/{tableName}") public R<Void> dropTable( @PathVariable String catalogName, @PathVariable String databaseName, @PathVariable String tableName) { return tableService.dropTable(catalogName, databaseName, tableName); } /** * Renames a table in the specified database of the given catalog. * * @param catalogName The name of the catalog where the table resides. * @param databaseName The name of the database where the table resides. * @param fromTableName The current name of the table to be renamed. * @param toTableName The new name for the table. * @return A Response object indicating the success or failure of the operation. If the * operation is successful, the response will be R.succeed(). If the operation fails, the * response will be R.failed() with Status.TABLE_RENAME_ERROR. * @throws RuntimeException If there is an error during the operation, a RuntimeException is * thrown with the error message. */ @PostMapping("/rename") public R<Void> renameTable( @RequestParam String catalogName, @RequestParam String databaseName, @RequestParam String fromTableName, @RequestParam String toTableName) { return tableService.renameTable(catalogName, databaseName, fromTableName, toTableName); } /** * Lists tables given {@link TableDTO} condition. * * @return Response object containing a list of {@link TableVO} representing the tables. */ @PostMapping("/list") public R<Object> listTables(@RequestBody TableDTO tableDTO) {
List<TableVO> tables = tableService.listTables(tableDTO);
4
2023-12-21 03:39:07+00:00
8k
Tianscar/uxgl
base/src/main/java/unrefined/beans/Property.java
[ { "identifier": "Producer", "path": "base/src/main/java/unrefined/util/concurrent/Producer.java", "snippet": "@FunctionalInterface\npublic interface Producer<V> extends Callable<V> {\n\n @Override\n default V call() throws Exception {\n return get();\n }\n\n V get();\n\n}" }, { ...
import unrefined.util.concurrent.Producer; import unrefined.util.event.Event; import unrefined.util.event.EventSlot; import unrefined.util.function.BiSlot; import unrefined.util.function.Functor; import unrefined.util.function.Slot; import unrefined.util.ref.Cleaner; import unrefined.util.signal.Signal; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference;
4,957
return new Instance<>(initialValue); } public static <V> Property<V> ofDefault() { return new Instance<>(); } private static class MappedPropertyMapBinding<K, V> extends Property<V> { private final PropertyMap map; private final K key; private final Functor<V, String> toStringProc; private final Functor<String, V> fromStringProc; public MappedPropertyMapBinding(PropertyMap map, K key, Functor<V, String> toStringProc, Functor<String, V> fromStringProc) { this.map = Objects.requireNonNull(map); this.key = Objects.requireNonNull(key); map.onChange().connect(changedEvent -> { V previousValue = fromStringProc.apply(changedEvent.getPreviousValue(String.class)); V currentValue = fromStringProc.apply(changedEvent.getCurrentValue(String.class)); if (previousValue != null || currentValue != null && !onChange().isEmpty()) { onChange().emit(new ChangeEvent<>(MappedPropertyMapBinding.this, previousValue, currentValue)); } }); this.toStringProc = Objects.requireNonNull(toStringProc); this.fromStringProc = Objects.requireNonNull(fromStringProc); } @Override public boolean isReadOnly() { return false; } @Override public void set(V value) { if (value == null) map.remove(key); else map.put(key, toStringProc.apply(value)); } @Override public V get() { return fromStringProc.apply(map.get(key, String.class)); } } private static class PropertyMapBinding<K, V> extends Property<V> { private final PropertyMap map; private final K key; @SuppressWarnings("unchecked") public PropertyMapBinding(PropertyMap map, K key) { this.map = Objects.requireNonNull(map); this.key = Objects.requireNonNull(key); map.onChange().connect(changedEvent -> { V previousValue, currentValue; try { previousValue = (V) changedEvent.getPreviousValue(); } catch (ClassCastException e) { previousValue = null; } try { currentValue = (V) changedEvent.getCurrentValue(); } catch (ClassCastException e) { currentValue = null; } if (previousValue != null || currentValue != null && !onChange().isEmpty()) { onChange().emit(new ChangeEvent<>(PropertyMapBinding.this, previousValue, currentValue)); } }); } @Override public boolean isReadOnly() { return false; } @Override public void set(V value) { if (value == null) map.remove(key); else map.put(key, value); } @SuppressWarnings("unchecked") @Override public V get() { try { return (V) map.get(key); } catch (ClassCastException e) { return null; } } } private static class FunctionBinding<V> extends Property<V> { private final Producer<V> getter; private final Slot<V> setter; public FunctionBinding(Producer<V> getter) { this.getter = Objects.requireNonNull(getter); this.setter = null; } public FunctionBinding(Producer<V> getter, Slot<V> setter) { this.getter = Objects.requireNonNull(getter); this.setter = setter; } @Override public boolean isReadOnly() { return setter == null; } @Override public void set(V value) { if (setter == null) throw new IllegalArgumentException("Property is read-only"); else setter.accept(value); } @Override public V get() { return getter.get(); } } private static class BeanBinding<V> extends Property<V> implements PropertyChangeListener { private final String key; private final Functor<String, V> getter; private final Slot<V> setter; public BeanBinding(String key, BiSlot<String, PropertyChangeListener> registerProc, BiSlot<String, PropertyChangeListener> unregisterProc, Functor<String, V> getter, Slot<V> setter) { this.key = Objects.requireNonNull(key); registerProc.accept(key, this);
package unrefined.beans; public abstract class Property<V> { public static <K, V> Property<V> bind(PropertyMap map, K key, Functor<V, String> toStringProc, Functor<String, V> fromStringProc) { return new MappedPropertyMapBinding<>(map, key, toStringProc, fromStringProc); } public static <K, V> Property<V> bind(PropertyMap map, K key) { return new PropertyMapBinding<>(map, key); } public static <V> Property<V> bind(Producer<V> getter, Slot<V> setter) { return new FunctionBinding<>(getter, setter); } public static <V> Property<V> bind(Producer<V> getter) { return new FunctionBinding<>(getter); } public static <V> Property<V> bind(String key, BiSlot<String, PropertyChangeListener> registerProc, BiSlot<String, PropertyChangeListener> unregisterProc, Functor<String, V> getter, Slot<V> setter) { return new BeanBinding<>(key, registerProc, unregisterProc, getter, setter); } public static <V> Property<V> bind(String key, BiSlot<String, PropertyChangeListener> registerProc, BiSlot<String, PropertyChangeListener> unregisterProc, Functor<String, V> getter) { return new BeanBinding<>(key, registerProc, unregisterProc, getter); } public static <V> Property<V> ofAtomic(V initialValue) { return new AtomicInstance<>(initialValue); } public static <V> Property<V> ofAtomic() { return new AtomicInstance<>(); } public static <V> Property<V> of(V initialValue) { return new Instance<>(initialValue); } public static <V> Property<V> ofDefault() { return new Instance<>(); } private static class MappedPropertyMapBinding<K, V> extends Property<V> { private final PropertyMap map; private final K key; private final Functor<V, String> toStringProc; private final Functor<String, V> fromStringProc; public MappedPropertyMapBinding(PropertyMap map, K key, Functor<V, String> toStringProc, Functor<String, V> fromStringProc) { this.map = Objects.requireNonNull(map); this.key = Objects.requireNonNull(key); map.onChange().connect(changedEvent -> { V previousValue = fromStringProc.apply(changedEvent.getPreviousValue(String.class)); V currentValue = fromStringProc.apply(changedEvent.getCurrentValue(String.class)); if (previousValue != null || currentValue != null && !onChange().isEmpty()) { onChange().emit(new ChangeEvent<>(MappedPropertyMapBinding.this, previousValue, currentValue)); } }); this.toStringProc = Objects.requireNonNull(toStringProc); this.fromStringProc = Objects.requireNonNull(fromStringProc); } @Override public boolean isReadOnly() { return false; } @Override public void set(V value) { if (value == null) map.remove(key); else map.put(key, toStringProc.apply(value)); } @Override public V get() { return fromStringProc.apply(map.get(key, String.class)); } } private static class PropertyMapBinding<K, V> extends Property<V> { private final PropertyMap map; private final K key; @SuppressWarnings("unchecked") public PropertyMapBinding(PropertyMap map, K key) { this.map = Objects.requireNonNull(map); this.key = Objects.requireNonNull(key); map.onChange().connect(changedEvent -> { V previousValue, currentValue; try { previousValue = (V) changedEvent.getPreviousValue(); } catch (ClassCastException e) { previousValue = null; } try { currentValue = (V) changedEvent.getCurrentValue(); } catch (ClassCastException e) { currentValue = null; } if (previousValue != null || currentValue != null && !onChange().isEmpty()) { onChange().emit(new ChangeEvent<>(PropertyMapBinding.this, previousValue, currentValue)); } }); } @Override public boolean isReadOnly() { return false; } @Override public void set(V value) { if (value == null) map.remove(key); else map.put(key, value); } @SuppressWarnings("unchecked") @Override public V get() { try { return (V) map.get(key); } catch (ClassCastException e) { return null; } } } private static class FunctionBinding<V> extends Property<V> { private final Producer<V> getter; private final Slot<V> setter; public FunctionBinding(Producer<V> getter) { this.getter = Objects.requireNonNull(getter); this.setter = null; } public FunctionBinding(Producer<V> getter, Slot<V> setter) { this.getter = Objects.requireNonNull(getter); this.setter = setter; } @Override public boolean isReadOnly() { return setter == null; } @Override public void set(V value) { if (setter == null) throw new IllegalArgumentException("Property is read-only"); else setter.accept(value); } @Override public V get() { return getter.get(); } } private static class BeanBinding<V> extends Property<V> implements PropertyChangeListener { private final String key; private final Functor<String, V> getter; private final Slot<V> setter; public BeanBinding(String key, BiSlot<String, PropertyChangeListener> registerProc, BiSlot<String, PropertyChangeListener> unregisterProc, Functor<String, V> getter, Slot<V> setter) { this.key = Objects.requireNonNull(key); registerProc.accept(key, this);
Cleaner.getInstance().register(this, () -> unregisterProc.accept(key, BeanBinding.this));
6
2023-12-15 19:03:31+00:00
8k
Outspending/BiomesAPI
src/main/java/me/outspending/biomesapi/registry/CustomBiomeRegistry.java
[ { "identifier": "BiomeLock", "path": "src/main/java/me/outspending/biomesapi/BiomeLock.java", "snippet": "@AsOf(\"0.0.1\")\npublic interface BiomeLock {\n\n /**\n * Unlocks the biome registry, performs an operation, and then locks the biome registry again.\n * This method is useful when you n...
import com.google.common.base.Preconditions; import me.outspending.biomesapi.BiomeLock; import me.outspending.biomesapi.BiomeSettings; import me.outspending.biomesapi.annotations.AsOf; import me.outspending.biomesapi.biome.BiomeHandler; import me.outspending.biomesapi.biome.CustomBiome; import me.outspending.biomesapi.nms.NMSHandler; import me.outspending.biomesapi.renderer.ParticleRenderer; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.biome.*; import org.jetbrains.annotations.NotNull;
6,435
package me.outspending.biomesapi.registry; /** * This class implements the BiomeRegistry interface and provides a method to register a custom biome to a Minecraft server. * It uses the BiomeLock class to unlock the biome registry before registering the custom biome, and then freezes the registry again. * * @version 0.0.1 */ @AsOf("0.0.1") public class CustomBiomeRegistry implements BiomeRegistry { /** * This method registers a custom biome to a Minecraft server. * It first unlocks the biome registry using the BiomeLock class. * Then, it retrieves the biome registry from the server and creates a new Biome object with the settings and colors from the CustomBiome object. * The new Biome object is then registered to the biome registry using the ResourceLocation from the CustomBiome object. * Finally, it freezes the biome registry again using the BiomeLock class. * * @param biome The CustomBiome object that should be registered to the server. * @version 0.0.1 */ @Override @AsOf("0.0.1") @SuppressWarnings("unchecked") public void register(@NotNull CustomBiome biome) { Preconditions.checkNotNull(biome, "biome cannot be null");
package me.outspending.biomesapi.registry; /** * This class implements the BiomeRegistry interface and provides a method to register a custom biome to a Minecraft server. * It uses the BiomeLock class to unlock the biome registry before registering the custom biome, and then freezes the registry again. * * @version 0.0.1 */ @AsOf("0.0.1") public class CustomBiomeRegistry implements BiomeRegistry { /** * This method registers a custom biome to a Minecraft server. * It first unlocks the biome registry using the BiomeLock class. * Then, it retrieves the biome registry from the server and creates a new Biome object with the settings and colors from the CustomBiome object. * The new Biome object is then registered to the biome registry using the ResourceLocation from the CustomBiome object. * Finally, it freezes the biome registry again using the BiomeLock class. * * @param biome The CustomBiome object that should be registered to the server. * @version 0.0.1 */ @Override @AsOf("0.0.1") @SuppressWarnings("unchecked") public void register(@NotNull CustomBiome biome) { Preconditions.checkNotNull(biome, "biome cannot be null");
BiomeLock.unlock(() -> {
0
2023-12-17 17:41:45+00:00
8k
jlokitha/layered-architecture-jlokitha
src/main/java/lk/jl/layeredarchitecture/controller/PlaceOrderFormController.java
[ { "identifier": "BOFactory", "path": "src/main/java/lk/jl/layeredarchitecture/bo/BOFactory.java", "snippet": "public class BOFactory {\n private static BOFactory boFactory;\n\n private BOFactory() {\n\n }\n\n public static BOFactory getBoFactory() {\n return (boFactory == null) ? boFa...
import lk.jl.layeredarchitecture.bo.BOFactory; import lk.jl.layeredarchitecture.bo.custom.PlaceOrderBO; import lk.jl.layeredarchitecture.dto.CustomerDTO; import lk.jl.layeredarchitecture.dto.ItemDTO; import lk.jl.layeredarchitecture.dto.OrderDetailDTO; import lk.jl.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;
4,012
package lk.jl.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().getBO( BOFactory.BOType.PLACE_ORDER ); public void initialize() { 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*/ try { if (!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(); } CustomerDTO dto = placeOrderBO.searchCustomer(newValue); if (dto != null) { txtCustomerName.setText(dto.getName()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } ItemDTO item = placeOrderBO.searchItem(newItemCode); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException | ClassNotFoundException throwable) { throwable.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } private boolean existItem(String code) throws SQLException, ClassNotFoundException { return placeOrderBO.isExistsItem(code); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { return placeOrderBO.isExistsCustomer(id); } public String generateNewOrderId() { try { String newId = placeOrderBO.generateNewOrderId(); if (newId != null) { return String.format("OID-%03d", (Integer.parseInt(newId.replace("OID-", "")) + 1)); } else { return "OID-001"; } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { ArrayList<CustomerDTO> allCustomers = placeOrderBO.getAllCustomer(); for (CustomerDTO dto : allCustomers) { cmbCustomerId.getItems().add(dto.getId()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ ArrayList<ItemDTO> allItem = placeOrderBO.getAllItems(); for (ItemDTO dto : allItem) { cmbItemCode.getItems().add(dto.getCode()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource( "/lk/jl/layeredarchitecture/main-form.fxml" ); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
package lk.jl.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().getBO( BOFactory.BOType.PLACE_ORDER ); public void initialize() { 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*/ try { if (!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(); } CustomerDTO dto = placeOrderBO.searchCustomer(newValue); if (dto != null) { txtCustomerName.setText(dto.getName()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } ItemDTO item = placeOrderBO.searchItem(newItemCode); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException | ClassNotFoundException throwable) { throwable.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } private boolean existItem(String code) throws SQLException, ClassNotFoundException { return placeOrderBO.isExistsItem(code); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { return placeOrderBO.isExistsCustomer(id); } public String generateNewOrderId() { try { String newId = placeOrderBO.generateNewOrderId(); if (newId != null) { return String.format("OID-%03d", (Integer.parseInt(newId.replace("OID-", "")) + 1)); } else { return "OID-001"; } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { ArrayList<CustomerDTO> allCustomers = placeOrderBO.getAllCustomer(); for (CustomerDTO dto : allCustomers) { cmbCustomerId.getItems().add(dto.getId()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ ArrayList<ItemDTO> allItem = placeOrderBO.getAllItems(); for (ItemDTO dto : allItem) { cmbItemCode.getItems().add(dto.getCode()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource( "/lk/jl/layeredarchitecture/main-form.fxml" ); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
tblOrderDetails.getItems().stream().map(tm -> new OrderDetailDTO(tm.getCode(), tm.getQty(), tm.getUnitPrice())).collect(Collectors.toList()));
4
2023-12-16 04:21:58+00:00
8k
lemonguge/autogen4j
src/main/java/cn/homj/autogen4j/OpenAiAgent.java
[ { "identifier": "Client", "path": "src/main/java/cn/homj/autogen4j/support/Client.java", "snippet": "public class Client {\n /**\n * application/json\n */\n private static final MediaType APPLICATION_JSON = MediaType.parse(\"application/json\");\n /**\n * OpenAI API\n */\n pr...
import java.util.ArrayList; import java.util.List; import cn.homj.autogen4j.support.Client; import cn.homj.autogen4j.support.LogUtils; import cn.homj.autogen4j.support.Message; import cn.homj.autogen4j.support.openai.chat.CompletionRequest; import cn.homj.autogen4j.support.openai.chat.CompletionResponse; import cn.homj.autogen4j.support.openai.chat.Tool; import cn.homj.autogen4j.support.openai.chat.ToolCall; import cn.homj.autogen4j.support.openai.chat.tool.Function; import cn.homj.autogen4j.support.openai.chat.tool.FunctionCall; import lombok.Setter; import lombok.experimental.Accessors; import static cn.homj.autogen4j.support.Message.ofAssistant; import static cn.homj.autogen4j.support.Message.ofSystem; import static cn.homj.autogen4j.support.Message.ofTool;
5,761
package cn.homj.autogen4j; /** * @author jiehong.jh * @date 2023/11/29 */ @Setter @Accessors(fluent = true) public class OpenAiAgent extends Agent { private Client client; private String model; private String apiKey; private Integer maxTokens; private Integer n = 1; private List<String> stop; private Double temperature; private Double topP; private List<Tool> tools; private String systemMessage = "You are a helpful assistant."; private String unconfirmedMessage = "Anything else I can do for you?"; public OpenAiAgent(String name) { super(name); } public OpenAiAgent addFunction(String name) { AgentFunction function = toolkit.getFunction(name); if (function == null) { throw new IllegalArgumentException("Function is not in toolkit: " + name); } if (tools == null) { tools = new ArrayList<>(); } tools.add(Tool.of(new Function() .setName(name) .setDescription(function.description()) .setParameters(function.parameters()))); return this; } @Override protected AgentRecord generateReply(Agent sender, AgentRecord record) { while (true) { CompletionRequest request = new CompletionRequest() .setModel(model) .setMaxTokens(maxTokens) .setN(n) .setStop(stop) .setTemperature(temperature) .setTopP(topP) .setTools(tools); List<AgentRecord> c = conversations.get(sender.name); if (sender.name.equals(record.getName())) { request.addSystemMessage(systemMessage); c.forEach(e -> request.addMessage(e.getMessage())); } else { // in group chat request.addMessage(ofSystem(systemMessage).setName(name)); c.stream() .map(e -> e.getMessage().clone().setName(e.getName())) .forEach(request::addMessage); } CompletionResponse response; try { response = client.complete(apiKey, request); } catch (Exception e) { LogUtils.error(loggerName, "response failed", e); return AgentRecord.of(name, ofAssistant("Service interrupted.")); } if (!response.isSuccess()) { LogUtils.warn(loggerName, response.getError().toString()); return AgentRecord.of(name, ofAssistant("Service temporarily unavailable.")); } Message message = response.getChoices().get(0).getMessage(); List<ToolCall> toolCalls = message.getToolCalls(); if (toolCalls == null || toolCalls.isEmpty()) { return AgentRecord.of(name, message); } addConversation(sender, AgentRecord.of(name, message)); if (callTools(sender, toolCalls) == 0) { return AgentRecord.of(name, ofAssistant(unconfirmedMessage)); } } } private int callTools(Agent sender, List<ToolCall> toolCalls) { int numberOfConfirmed = 0; for (ToolCall toolCall : toolCalls) { // only function is supported
package cn.homj.autogen4j; /** * @author jiehong.jh * @date 2023/11/29 */ @Setter @Accessors(fluent = true) public class OpenAiAgent extends Agent { private Client client; private String model; private String apiKey; private Integer maxTokens; private Integer n = 1; private List<String> stop; private Double temperature; private Double topP; private List<Tool> tools; private String systemMessage = "You are a helpful assistant."; private String unconfirmedMessage = "Anything else I can do for you?"; public OpenAiAgent(String name) { super(name); } public OpenAiAgent addFunction(String name) { AgentFunction function = toolkit.getFunction(name); if (function == null) { throw new IllegalArgumentException("Function is not in toolkit: " + name); } if (tools == null) { tools = new ArrayList<>(); } tools.add(Tool.of(new Function() .setName(name) .setDescription(function.description()) .setParameters(function.parameters()))); return this; } @Override protected AgentRecord generateReply(Agent sender, AgentRecord record) { while (true) { CompletionRequest request = new CompletionRequest() .setModel(model) .setMaxTokens(maxTokens) .setN(n) .setStop(stop) .setTemperature(temperature) .setTopP(topP) .setTools(tools); List<AgentRecord> c = conversations.get(sender.name); if (sender.name.equals(record.getName())) { request.addSystemMessage(systemMessage); c.forEach(e -> request.addMessage(e.getMessage())); } else { // in group chat request.addMessage(ofSystem(systemMessage).setName(name)); c.stream() .map(e -> e.getMessage().clone().setName(e.getName())) .forEach(request::addMessage); } CompletionResponse response; try { response = client.complete(apiKey, request); } catch (Exception e) { LogUtils.error(loggerName, "response failed", e); return AgentRecord.of(name, ofAssistant("Service interrupted.")); } if (!response.isSuccess()) { LogUtils.warn(loggerName, response.getError().toString()); return AgentRecord.of(name, ofAssistant("Service temporarily unavailable.")); } Message message = response.getChoices().get(0).getMessage(); List<ToolCall> toolCalls = message.getToolCalls(); if (toolCalls == null || toolCalls.isEmpty()) { return AgentRecord.of(name, message); } addConversation(sender, AgentRecord.of(name, message)); if (callTools(sender, toolCalls) == 0) { return AgentRecord.of(name, ofAssistant(unconfirmedMessage)); } } } private int callTools(Agent sender, List<ToolCall> toolCalls) { int numberOfConfirmed = 0; for (ToolCall toolCall : toolCalls) { // only function is supported
FunctionCall functionCall = toolCall.getFunctionCall();
8
2023-12-15 01:43:11+00:00
8k
Valerde/vadb
va-collection/src/main/java/com/sovava/vacollection/valist/VaAbstractList.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.VaList; import com.sovava.vacollection.api.VaListIterator; import com.sovava.vacollection.collections.VaAbstractCollection; import com.sovava.vacollection.exception.VaNoSuchElementException; import java.util.NoSuchElementException; import java.util.RandomAccess;
3,626
package com.sovava.vacollection.valist; /** * Description: 此类提供了List接口的骨架实现,以最大限度地减少实现由“随机访问”数据存储(例如数组)支持的接口所需的工作量。对于顺序访问数据(例如链表),应优先使用AbstractSequentialList而不是此类。 * 要实现不可修改的列表,程序员只需扩展此类并提供get(int)和size()方法的实现。 * 要实现可修改列表,程序员必须另外重写set(int, E)方法(否则会抛出UnsupportedOperationException )。如果列表是可变大小的,程序员必须另外重写add(int, E)和remove(int)方法。 * 程序员通常应该根据Collection接口规范中的建议提供 void(无参数)和集合构造函数。 * 与其他抽象集合实现不同,程序员不必提供迭代器实现;迭代器和列表迭代器由此类在“随机访问”方法之上实现: get(int) 、 set(int, E) 、 add(int, E)和remove(int) * * @author: ykn * @date: 2023年12月20日 4:50 PM **/ public abstract class VaAbstractList<E> extends VaAbstractCollection<E> implements VaList<E> { /** * description: 对于子类构造函数的调用,通常是隐式的 * * @Author sovava * @Date 12/20/23 4:52 PM */ protected VaAbstractList() { } public void add(int idx, E e) { throw new UnsupportedOperationException("该集合不允许对某一位置元素进行add操作"); } public boolean add(E e) { add(size(), e); return true; } abstract public E get(int idx); public E set(int idx, E e) { throw new UnsupportedOperationException("该集合不允许对某一位置元素进行set操作"); } public E remove(int idx) { throw new UnsupportedOperationException("该集合不允许对某一位置元素进行remove操作"); } public int indexOf(Object o) {
package com.sovava.vacollection.valist; /** * Description: 此类提供了List接口的骨架实现,以最大限度地减少实现由“随机访问”数据存储(例如数组)支持的接口所需的工作量。对于顺序访问数据(例如链表),应优先使用AbstractSequentialList而不是此类。 * 要实现不可修改的列表,程序员只需扩展此类并提供get(int)和size()方法的实现。 * 要实现可修改列表,程序员必须另外重写set(int, E)方法(否则会抛出UnsupportedOperationException )。如果列表是可变大小的,程序员必须另外重写add(int, E)和remove(int)方法。 * 程序员通常应该根据Collection接口规范中的建议提供 void(无参数)和集合构造函数。 * 与其他抽象集合实现不同,程序员不必提供迭代器实现;迭代器和列表迭代器由此类在“随机访问”方法之上实现: get(int) 、 set(int, E) 、 add(int, E)和remove(int) * * @author: ykn * @date: 2023年12月20日 4:50 PM **/ public abstract class VaAbstractList<E> extends VaAbstractCollection<E> implements VaList<E> { /** * description: 对于子类构造函数的调用,通常是隐式的 * * @Author sovava * @Date 12/20/23 4:52 PM */ protected VaAbstractList() { } public void add(int idx, E e) { throw new UnsupportedOperationException("该集合不允许对某一位置元素进行add操作"); } public boolean add(E e) { add(size(), e); return true; } abstract public E get(int idx); public E set(int idx, E e) { throw new UnsupportedOperationException("该集合不允许对某一位置元素进行set操作"); } public E remove(int idx) { throw new UnsupportedOperationException("该集合不允许对某一位置元素进行remove操作"); } public int indexOf(Object o) {
VaListIterator<E> vlit = listIterator();
3
2023-12-17 13:29:10+00:00
8k
chamithKavinda/layered-architecture-ChamithKavinda
src/main/java/com/example/layeredarchitecture/controller/PlaceOrderFormController.java
[ { "identifier": "PlaceOrderBO", "path": "src/main/java/com/example/layeredarchitecture/bo/custom/PlaceOrderBO.java", "snippet": "public interface PlaceOrderBO extends SuperBO {\n\n boolean placeOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQL...
import com.example.layeredarchitecture.bo.custom.PlaceOrderBO; import com.example.layeredarchitecture.bo.custom.impl.PlaceOrderBOImpl; import com.example.layeredarchitecture.dto.CustomerDTO; import com.example.layeredarchitecture.dto.ItemDTO; import com.example.layeredarchitecture.dto.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.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
3,610
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=new PlaceOrderBOImpl(); 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 { try { if (!existCustomer(newValue + "")) { new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show(); } CustomerDTO customerDTO = placeOrderBO.searchCustomer(newValue + ""); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); }
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=new PlaceOrderBOImpl(); 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 { try { if (!existCustomer(newValue + "")) { new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show(); } CustomerDTO customerDTO = placeOrderBO.searchCustomer(newValue + ""); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); }
ItemDTO item = placeOrderBO.searchItem(newItemCode + "");
3
2023-12-16 04:21:25+00:00
8k
ZakariaAitAli/MesDepensesTelecom
app/src/main/java/com/gi3/mesdepensestelecom/MainActivity.java
[ { "identifier": "AbonnementRepository", "path": "app/src/main/java/com/gi3/mesdepensestelecom/database/AbonnementRepository.java", "snippet": "public class AbonnementRepository extends SQLiteOpenHelper {\n public static final String databaseName = \"Depense.db\";\n DatabaseHelper databaseHelper;\n...
import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.fragment.NavHostFragment; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import com.gi3.mesdepensestelecom.database.AbonnementRepository; import com.gi3.mesdepensestelecom.database.DatabaseHelper; import com.gi3.mesdepensestelecom.databinding.ActivityMainBinding; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.navigation.NavigationView; import com.google.android.material.snackbar.Snackbar; import java.util.Objects;
4,205
package com.gi3.mesdepensestelecom; public class MainActivity extends AppCompatActivity { private AppBarConfiguration mAppBarConfiguration;
package com.gi3.mesdepensestelecom; public class MainActivity extends AppCompatActivity { private AppBarConfiguration mAppBarConfiguration;
DatabaseHelper databaseHelper ;
1
2023-12-20 13:43:21+00:00
8k
acatai/pn-mcts
src/experiments/RunCustomMatch.java
[ { "identifier": "PNSMCTS_Extension", "path": "src/mcts/PNSMCTS_Extension.java", "snippet": "public class PNSMCTS_Extension extends AI {\n\n\n public static boolean FIN_MOVE_SEL = false;\n public static int SOLVERLIKE_MINVISITS = Integer.MAX_VALUE; // 5; // Integer.MAX_VALUE;\n\n\n //-----------...
import game.Game; import mcts.PNSMCTS_Extension; import other.AI; import other.GameLoader; import other.context.Context; import other.model.Model; import other.trial.Trial; import search.mcts.MCTS; import utils.Utils; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
5,310
package experiments; /** * @author Daniel Górski */ public class RunCustomMatch { /** * Name of game we wish to play */ static final String GAME_NAME = "games/Minishogi.lud"; // static final String GAME_NAME = "games/Awari.lud"; // static final String GAME_NAME = "games/Lines of Action 8x8.lud"; // static final String GAME_NAME = "games/Knightthrough.lud"; static final File GAME_FILE = new File(GAME_NAME); private static double TIME_FOR_GAME = 1.0; static final int NUM_GAMES = 1000; public static void main(final String[] args) { System.out.println(GAME_FILE.getAbsolutePath()); // load and create game final Game game = GameLoader.loadGameFromFile(GAME_FILE); final Trial trial = new Trial(game); final Context context = new Context(game, trial); Map<String, Integer> results = new HashMap<>(); int draws = 0; // params to test: boolean finMove = false; int minVisits = 5; double pnCons = 1;
package experiments; /** * @author Daniel Górski */ public class RunCustomMatch { /** * Name of game we wish to play */ static final String GAME_NAME = "games/Minishogi.lud"; // static final String GAME_NAME = "games/Awari.lud"; // static final String GAME_NAME = "games/Lines of Action 8x8.lud"; // static final String GAME_NAME = "games/Knightthrough.lud"; static final File GAME_FILE = new File(GAME_NAME); private static double TIME_FOR_GAME = 1.0; static final int NUM_GAMES = 1000; public static void main(final String[] args) { System.out.println(GAME_FILE.getAbsolutePath()); // load and create game final Game game = GameLoader.loadGameFromFile(GAME_FILE); final Trial trial = new Trial(game); final Context context = new Context(game, trial); Map<String, Integer> results = new HashMap<>(); int draws = 0; // params to test: boolean finMove = false; int minVisits = 5; double pnCons = 1;
AI testedAI = new PNSMCTS_Extension(finMove, minVisits, pnCons);
0
2023-12-15 10:26:35+00:00
8k
litongjava/next-jfinal
src/main/java/com/jfinal/core/paragetter/JsonRequest.java
[ { "identifier": "AsyncContext", "path": "src/main/java/com/jfinal/servlet/AsyncContext.java", "snippet": "public class AsyncContext {\n\n}" }, { "identifier": "DispatcherType", "path": "src/main/java/com/jfinal/servlet/DispatcherType.java", "snippet": "public class DispatcherType {\n\n}"...
import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.Principal; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; import java.util.Map; import com.jfinal.servlet.AsyncContext; import com.jfinal.servlet.DispatcherType; import com.jfinal.servlet.RequestDispatcher; import com.jfinal.servlet.ServletContext; import com.jfinal.servlet.ServletException; import com.jfinal.servlet.ServletInputStream; import com.jfinal.servlet.ServletRequest; import com.jfinal.servlet.ServletResponse; import com.jfinal.servlet.http.Cookie; import com.jfinal.servlet.http.HttpServletRequest; import com.jfinal.servlet.http.HttpServletResponse; import com.jfinal.servlet.http.HttpSession; import com.jfinal.servlet.http.HttpUpgradeHandler; import com.jfinal.servlet.multipart.Part;
3,780
return req.getContentType(); } @Override public String getProtocol() { return req.getProtocol(); } @Override public String getScheme() { return req.getScheme(); } @Override public String getServerName() { return req.getServerName(); } @Override public int getServerPort() { return req.getServerPort(); } @Override public String getRemoteAddr() { return req.getRemoteAddr(); } @Override public String getRemoteHost() { return req.getRemoteHost(); } @Override public void setAttribute(String name, Object o) { req.setAttribute(name, o); } @Override public void removeAttribute(String name) { req.removeAttribute(name); } @Override public Locale getLocale() { return req.getLocale(); } @Override public Enumeration<Locale> getLocales() { return req.getLocales(); } @Override public boolean isSecure() { return req.isSecure(); } @Override public RequestDispatcher getRequestDispatcher(String path) { return req.getRequestDispatcher(path); } @Override public String getRealPath(String path) { return req.getRealPath(path); } @Override public int getRemotePort() { return req.getRemotePort(); } @Override public String getLocalName() { return req.getLocalName(); } @Override public String getLocalAddr() { return req.getLocalAddr(); } @Override public int getLocalPort() { return req.getLocalPort(); } @Override public ServletContext getServletContext() { return req.getServletContext(); } @Override public AsyncContext startAsync() throws IllegalStateException { return req.startAsync(); } @Override public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { return req.startAsync(servletRequest, servletResponse); } @Override public boolean isAsyncStarted() { return req.isAsyncStarted(); } @Override public boolean isAsyncSupported() { return req.isAsyncSupported(); } @Override public AsyncContext getAsyncContext() { return req.getAsyncContext(); } @Override
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com) / 玛雅牛 (myaniu AT gmail dot 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.core.paragetter; /** * JsonRequest 包装 json 请求,从底层接管所有 parameter 操作 */ public class JsonRequest implements HttpServletRequest { // 缓存 JSONObject、JSONArray 对象 private com.alibaba.fastjson.JSONObject jsonObject; private com.alibaba.fastjson.JSONArray jsonArray; // 包装请求对象 private HttpServletRequest req; // 通过 JSONObject 延迟生成 paraMap private HashMap<String, String[]> paraMap; public JsonRequest(String jsonString, HttpServletRequest req) { Object json = com.alibaba.fastjson.JSON.parse(jsonString); if (json instanceof com.alibaba.fastjson.JSONObject) { jsonObject = (com.alibaba.fastjson.JSONObject) json; } else if (json instanceof com.alibaba.fastjson.JSONArray) { jsonArray = (com.alibaba.fastjson.JSONArray) json; } this.req = req; } /** * 第一个版本只做简单转换,用户获取 JSONObject 与 JSONArray 后可以进一步进行复杂转换 */ public com.alibaba.fastjson.JSONObject getJSONObject() { return jsonObject; } public com.alibaba.fastjson.JSONArray getJSONArray() { return jsonArray; } /* * public Map<String, Object> getJsonMap() { return jsonObject; } public java.util.List<Object> getJsonList() { return jsonArray; } */ /** * 获取内部 HttpServletRequest 对象 */ public HttpServletRequest getInnerRequest() { return req; } /** * 请求参数是否为 JSONObject 对象 */ public boolean isJSONObject() { return jsonObject != null; } /** * 请求参数是否为 JSONArray 对象 */ public boolean isJSONArray() { return jsonArray != null; } // 延迟创建,不是每次都会调用 parameter 相关方法 private HashMap<String, String[]> getParaMap() { if (paraMap == null) { paraMap = (jsonObject != null ? createParaMap(jsonObject) : new HashMap<>()); } return paraMap; } private HashMap<String, String[]> createParaMap(com.alibaba.fastjson.JSONObject jsonPara) { HashMap<String, String[]> newPara = new HashMap<>(); // 先读取 parameter,否则后续从流中读取 rawData 后将无法读取 parameter(部分 servlet 容器) Map<String, String[]> oldPara = req.getParameterMap(); if (oldPara != null && oldPara.size() > 0) { newPara.putAll(oldPara); } for (Map.Entry<String, Object> e : jsonPara.entrySet()) { String key = e.getKey(); Object value = e.getValue(); // 只转换最外面一层 json 数据,如果存在多层 json 结构,仅将其视为 String 留给后续流程转换 if (value instanceof com.alibaba.fastjson.JSON) { newPara.put(key, new String[] { ((com.alibaba.fastjson.JSON) value).toJSONString() }); } else if (value != null) { newPara.put(key, new String[] { value.toString() }); } else { // 需要考虑 value 是否转成 String[] array = {""},ActionRepoter.getParameterValues() 有依赖 newPara.put(key, null); } } return newPara; } @Override public String getParameter(String name) { // String[] ret = getParaMap().get(name); // return ret != null && ret.length != 0 ? ret[0] : null; // 优化性能,避免调用 getParaMap() 触发调用 createParaMap(),从而大概率避免对整个 jsonObject 进行转换 if (jsonObject != null && jsonObject.containsKey(name)) { Object value = jsonObject.get(name); if (value instanceof com.alibaba.fastjson.JSON) { return ((com.alibaba.fastjson.JSON) value).toJSONString(); } else if (value != null) { return value.toString(); } else { // 需要考虑是否返回 "",表单提交请求只要 name 存在则值不会为 null return null; } } else { return req.getParameter(name); } } /** * 该方法将触发 createParaMap(),框架内部应尽可能避免该事情发生,以优化性能 */ @Override public Map<String, String[]> getParameterMap() { return getParaMap(); } /** * 该方法将触发 createParaMap(),框架内部应尽可能避免该事情发生,以优化性能 */ @Override public String[] getParameterValues(String name) { return getParaMap().get(name); } @Override public Enumeration<String> getParameterNames() { // return Collections.enumeration(getParaMap().keySet()); if (jsonObject != null) { return Collections.enumeration(jsonObject.keySet()); } else { return Collections.emptyEnumeration(); } } // --------------------------------------------------------------- // 以下方法仅为对 req 对象的转调 ------------------------------------- @Override public ServletInputStream getInputStream() throws IOException { return req.getInputStream(); } @Override public BufferedReader getReader() throws IOException { return req.getReader(); } @Override public Object getAttribute(String name) { return req.getAttribute(name); } @Override public Enumeration<String> getAttributeNames() { return req.getAttributeNames(); } @Override public String getCharacterEncoding() { return req.getCharacterEncoding(); } @Override public void setCharacterEncoding(String env) throws UnsupportedEncodingException { req.setCharacterEncoding(env); } @Override public int getContentLength() { return req.getContentLength(); } @Override public long getContentLengthLong() { return req.getContentLengthLong(); } @Override public String getContentType() { return req.getContentType(); } @Override public String getProtocol() { return req.getProtocol(); } @Override public String getScheme() { return req.getScheme(); } @Override public String getServerName() { return req.getServerName(); } @Override public int getServerPort() { return req.getServerPort(); } @Override public String getRemoteAddr() { return req.getRemoteAddr(); } @Override public String getRemoteHost() { return req.getRemoteHost(); } @Override public void setAttribute(String name, Object o) { req.setAttribute(name, o); } @Override public void removeAttribute(String name) { req.removeAttribute(name); } @Override public Locale getLocale() { return req.getLocale(); } @Override public Enumeration<Locale> getLocales() { return req.getLocales(); } @Override public boolean isSecure() { return req.isSecure(); } @Override public RequestDispatcher getRequestDispatcher(String path) { return req.getRequestDispatcher(path); } @Override public String getRealPath(String path) { return req.getRealPath(path); } @Override public int getRemotePort() { return req.getRemotePort(); } @Override public String getLocalName() { return req.getLocalName(); } @Override public String getLocalAddr() { return req.getLocalAddr(); } @Override public int getLocalPort() { return req.getLocalPort(); } @Override public ServletContext getServletContext() { return req.getServletContext(); } @Override public AsyncContext startAsync() throws IllegalStateException { return req.startAsync(); } @Override public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { return req.startAsync(servletRequest, servletResponse); } @Override public boolean isAsyncStarted() { return req.isAsyncStarted(); } @Override public boolean isAsyncSupported() { return req.isAsyncSupported(); } @Override public AsyncContext getAsyncContext() { return req.getAsyncContext(); } @Override
public DispatcherType getDispatcherType() {
1
2023-12-19 10:58:33+00:00
8k
ViniciusJPSilva/TSI-PizzeriaExpress
PizzeriaExpress/src/main/java/br/vjps/tsi/pe/managedbeans/RequestMB.java
[ { "identifier": "DAO", "path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/dao/DAO.java", "snippet": "public class DAO<T> {\n\tprivate Class<T> tClass;\n\n\t/**\n * Construtor que recebe a classe da entidade para ser manipulada pelo DAO.\n *\n * @param tClass A classe da entidade.\n */...
import java.io.IOException; import java.util.Calendar; import java.util.List; import java.util.Optional; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.ValidatorException; import br.vjps.tsi.pe.dao.DAO; import br.vjps.tsi.pe.dao.RequestDAO; import br.vjps.tsi.pe.enumeration.Category; import br.vjps.tsi.pe.model.Client; import br.vjps.tsi.pe.model.Item; import br.vjps.tsi.pe.model.Product; import br.vjps.tsi.pe.model.Request; import br.vjps.tsi.pe.system.SystemSettings; import br.vjps.tsi.pe.utility.EmailSender; import br.vjps.tsi.pe.utility.Utility; import br.vjps.tsi.pe.validator.ListSizeValidator;
6,243
package br.vjps.tsi.pe.managedbeans; @ViewScoped @ManagedBean public class RequestMB { private Request request = getOpenOrNewRequest(); private Item item = new Item(); private Long itemId; private Calendar searchDate = Utility.getTodayCalendar(); private List<Request> closedRequests; private List<Request> clientHistory; private List<Request> voucherHistory; /** * Define uma mesa para o cliente com base no ID. * * @param id O ID do cliente. */ public void setTable(Long id) {
package br.vjps.tsi.pe.managedbeans; @ViewScoped @ManagedBean public class RequestMB { private Request request = getOpenOrNewRequest(); private Item item = new Item(); private Long itemId; private Calendar searchDate = Utility.getTodayCalendar(); private List<Request> closedRequests; private List<Request> clientHistory; private List<Request> voucherHistory; /** * Define uma mesa para o cliente com base no ID. * * @param id O ID do cliente. */ public void setTable(Long id) {
Client client = new DAO<Client>(Client.class).findById(id);
3
2023-12-16 01:25:27+00:00
8k
Konloch/HeadlessIRC
src/main/java/com/konloch/ircbot/message/text/impl/Quit.java
[ { "identifier": "TextMessageEvent", "path": "src/main/java/com/konloch/ircbot/message/text/TextMessageEvent.java", "snippet": "public interface TextMessageEvent\n{\n\tvoid handle(Server server, String[] splitPartMessage);\n}" }, { "identifier": "Channel", "path": "src/main/java/com/konloch/i...
import com.konloch.ircbot.message.text.TextMessageEvent; import com.konloch.ircbot.server.Channel; import com.konloch.ircbot.server.Server; import com.konloch.ircbot.server.User; import static com.konloch.util.FastStringUtils.split;
4,382
package com.konloch.ircbot.message.text.impl; /** * @author Konloch * @since 12/15/2023 */ public class Quit implements TextMessageEvent { @Override public void handle(Server server, String[] splitPartMessage) { String nickname = split(splitPartMessage[0].substring(1), "!", 2)[0];
package com.konloch.ircbot.message.text.impl; /** * @author Konloch * @since 12/15/2023 */ public class Quit implements TextMessageEvent { @Override public void handle(Server server, String[] splitPartMessage) { String nickname = split(splitPartMessage[0].substring(1), "!", 2)[0];
for(Channel channel : server.getChannels())
1
2023-12-16 02:09:21+00:00
8k
sasmithx/layered-architecture-Sasmithx
src/main/java/lk/sasax/layeredarchitecture/controller/PlaceOrderFormController.java
[ { "identifier": "BOFactory", "path": "src/main/java/lk/sasax/layeredarchitecture/bo/BOFactory.java", "snippet": "public class BOFactory {\n\n private static BOFactory boFactory;\n\n private BOFactory() {\n }\n\n public static BOFactory getBoFactory() {\n return (boFactory == null) ? b...
import lk.sasax.layeredarchitecture.bo.BOFactory; import lk.sasax.layeredarchitecture.bo.custom.PlaceOrderBO; import lk.sasax.layeredarchitecture.dto.CustomerDTO; import lk.sasax.layeredarchitecture.dto.ItemDTO; import lk.sasax.layeredarchitecture.dto.OrderDetailDTO; import lk.sasax.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.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
4,353
e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { /*Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT * FROM Customer");*/ ArrayList<CustomerDTO> allCustomer = placeOrderBO.getAllCustomer(); for (CustomerDTO dto : allCustomer) { cmbCustomerId.getItems().add(dto.getId()); } /*while (rst.next()) { cmbCustomerId.getItems().add(rst.getString("id")); }*/ } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ /*Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT * FROM Item");*/ ArrayList<ItemDTO> allItems = placeOrderBO.getAllItem(); for (ItemDTO itemDTO : allItems) { cmbItemCode.getItems().add(itemDTO.getCode()); } /*while (rst.next()) { cmbItemCode.getItems().add(rst.getString("code")); }*/ } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/lk/sasax/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) throws SQLException, ClassNotFoundException { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
package lk.sasax.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().getTypes(BOFactory.BOTypes.PLACE_ORDER); public void initialize() { 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 { 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 dto = placeOrderBO.searchCustomer(newValue); CustomerDTO customerDTO = new CustomerDTO(newValue + "", dto.getName(), dto.getAddress()); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } /*Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?"); pstm.setString(1, newItemCode + ""); ResultSet rst = pstm.executeQuery(); rst.next();*/ ItemDTO dto = placeOrderBO.searchItem(newItemCode); ItemDTO item = new ItemDTO(newItemCode + "", dto.getDescription(), dto.getUnitPrice(), dto.getQtyOnHand()); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } private boolean existItem(String code) throws SQLException, ClassNotFoundException { /*Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT code FROM Item WHERE code=?"); pstm.setString(1, code); return pstm.executeQuery().next();*/ return placeOrderBO.existItem(code); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { /*Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT id FROM Customer WHERE id=?"); pstm.setString(1, id); return pstm.executeQuery().next();*/ return placeOrderBO.existCustomer(id); } public String generateNewOrderId() { try { /*Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT oid FROM `Orders` ORDER BY oid DESC LIMIT 1;");*/ ResultSet rst = placeOrderBO.generateNewOrderId(); return rst.next() ? String.format("OID-%03d", (Integer.parseInt(rst.getString("oid").replace("OID-", "")) + 1)) : "OID-001"; } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { /*Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT * FROM Customer");*/ ArrayList<CustomerDTO> allCustomer = placeOrderBO.getAllCustomer(); for (CustomerDTO dto : allCustomer) { cmbCustomerId.getItems().add(dto.getId()); } /*while (rst.next()) { cmbCustomerId.getItems().add(rst.getString("id")); }*/ } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ /*Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT * FROM Item");*/ ArrayList<ItemDTO> allItems = placeOrderBO.getAllItem(); for (ItemDTO itemDTO : allItems) { cmbItemCode.getItems().add(itemDTO.getCode()); } /*while (rst.next()) { cmbItemCode.getItems().add(rst.getString("code")); }*/ } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/lk/sasax/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) throws SQLException, ClassNotFoundException { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
tblOrderDetails.getItems().stream().map(tm -> new OrderDetailDTO(tm.getCode(), tm.getQty(), tm.getUnitPrice())).collect(Collectors.toList()));
4
2023-12-16 04:19:42+00:00
8k
madhushiillesinghe/layered-architecture-madhushi
src/main/java/com/example/layeredarchitecture/controller/PlaceOrderFormController.java
[ { "identifier": "PlaceOrderBo", "path": "src/main/java/com/example/layeredarchitecture/bo/custom/PlaceOrderBo.java", "snippet": "public interface PlaceOrderBo extends SuperBo {\n boolean saveOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLExc...
import com.example.layeredarchitecture.bo.custom.PlaceOrderBo; import com.example.layeredarchitecture.dao.BOFactory; import com.example.layeredarchitecture.dto.CustomerDTO; import com.example.layeredarchitecture.dto.ItemDTO; import com.example.layeredarchitecture.dto.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.Optional; import java.util.stream.Collectors;
4,383
ResultSet rst = stm.executeQuery("SELECT oid FROM `Orders` ORDER BY oid DESC LIMIT 1;"); */ ResultSet rst=placeOrderBo.genareteOrderId(); return rst.next() ? String.format("OID-%03d", (Integer.parseInt(rst.getString("oid").replace("OID-", "")) + 1)) : "OID-001"; } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { /*Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT * FROM Customer");*/ ArrayList<CustomerDTO> loadallcustomer= placeOrderBo.loadAllCustomer(); for (CustomerDTO dto:loadallcustomer) { cmbCustomerId.getItems().add(dto.getId()); } /*while (rst.next()) { cmbCustomerId.getItems().add(rst.getString("id")); }*/ } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ /* Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT * FROM Item"); while (rst.next()) { cmbItemCode.getItems().add(rst.getString("code")); }*/ ArrayList<ItemDTO> allitem=placeOrderBo.loadAllItem(); for(ItemDTO dto:allitem){ cmbItemCode.getItems().add(dto.getCode()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) throws SQLException, ClassNotFoundException { boolean b = placeOrderBo.saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
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; /*CustomerDao customerDao=new CustomerDaoImpl(); ItemDao itemDao=new ItemDaoImpl(); OrderDao orderDao=new OrderDaoImpl(); OrderDetailDao orderDetailDao=new OrderDetailDaoImpl();*/ PlaceOrderBo placeOrderBo= (PlaceOrderBo) BOFactory.getBoFactory().getBo(BOFactory.BOType.PLACEORDER); 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 { if (!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 dto=placeOrderBo.searchCustomer(newValue); CustomerDTO customerDTO = new CustomerDTO(newValue + "", dto.getName(), dto.getAddress()); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } /* Connection connection = DBConnection.getDbConnection().getConnection(); */ /*PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?"); pstm.setString(1, newItemCode + ""); ResultSet rst = pstm.executeQuery(); rst.next();*/ ItemDTO dto=placeOrderBo.searchItem(newItemCode); ItemDTO item = new ItemDTO(newItemCode + "", dto.getDescription(), dto.getUnitPrice(), dto.getQtyOnHand()); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } private boolean existItem(String code) throws SQLException, ClassNotFoundException { /* Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT code FROM Item WHERE code=?"); pstm.setString(1, code); return pstm.executeQuery().next();*/ boolean isExist=placeOrderBo.existItem(code); if(isExist){ return true; } return false; } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { /* Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT id FROM Customer WHERE id=?"); pstm.setString(1, id); return pstm.executeQuery().next();*/ boolean isExist=placeOrderBo.existCustomer(id); if(isExist){ return true; } return false; } public String generateNewOrderId() { try { /* Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT oid FROM `Orders` ORDER BY oid DESC LIMIT 1;"); */ ResultSet rst=placeOrderBo.genareteOrderId(); return rst.next() ? String.format("OID-%03d", (Integer.parseInt(rst.getString("oid").replace("OID-", "")) + 1)) : "OID-001"; } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { /*Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT * FROM Customer");*/ ArrayList<CustomerDTO> loadallcustomer= placeOrderBo.loadAllCustomer(); for (CustomerDTO dto:loadallcustomer) { cmbCustomerId.getItems().add(dto.getId()); } /*while (rst.next()) { cmbCustomerId.getItems().add(rst.getString("id")); }*/ } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ /* Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT * FROM Item"); while (rst.next()) { cmbItemCode.getItems().add(rst.getString("code")); }*/ ArrayList<ItemDTO> allitem=placeOrderBo.loadAllItem(); for(ItemDTO dto:allitem){ cmbItemCode.getItems().add(dto.getCode()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) throws SQLException, ClassNotFoundException { boolean b = placeOrderBo.saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
tblOrderDetails.getItems().stream().map(tm -> new OrderDetailDTO(tm.getCode(), tm.getQty(), tm.getUnitPrice())).collect(Collectors.toList()));
4
2023-12-17 02:17:36+00:00
8k
HypixelSkyblockmod/ChromaHud
src/java/xyz/apfelmus/cheeto/client/clickgui/settings/AbstractSliderComponent.java
[ { "identifier": "SettingComponent", "path": "src/java/xyz/apfelmus/cheeto/client/clickgui/settings/SettingComponent.java", "snippet": "@Metadata(mv={1, 6, 0}, k=1, xi=48, d1={\"\\u0000.\\n\\u0002\\u0018\\u0002\\n\\u0002\\u0018\\u0002\\n\\u0002\\b\\u0002\\n\\u0002\\u0010\\u0000\\n\\u0000\\n\\u0002\\u0018...
import gg.essential.elementa.UIComponent; import gg.essential.elementa.UIConstraints; import gg.essential.elementa.constraints.ChildBasedMaxSizeConstraint; import gg.essential.elementa.constraints.ChildBasedSizeConstraint; import gg.essential.elementa.constraints.HeightConstraint; import gg.essential.elementa.constraints.WidthConstraint; import gg.essential.elementa.constraints.animation.AnimatingConstraints; import gg.essential.elementa.constraints.animation.AnimationStrategy; import gg.essential.elementa.constraints.animation.Animations; import gg.essential.elementa.dsl.UtilitiesKt; import gg.essential.elementa.events.UIClickEvent; import gg.essential.universal.USound; import kotlin.Metadata; import kotlin.Unit; import kotlin.jvm.functions.Function1; import kotlin.jvm.functions.Function2; import kotlin.jvm.internal.Intrinsics; import org.jetbrains.annotations.NotNull; import xyz.apfelmus.cheeto.client.clickgui.settings.SettingComponent; import xyz.apfelmus.cheeto.client.clickgui.settings.Slider;
6,448
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * gg.essential.elementa.UIComponent * gg.essential.elementa.UIConstraints * gg.essential.elementa.constraints.ChildBasedMaxSizeConstraint * gg.essential.elementa.constraints.ChildBasedSizeConstraint * gg.essential.elementa.constraints.HeightConstraint * gg.essential.elementa.constraints.WidthConstraint * gg.essential.elementa.constraints.animation.AnimatingConstraints * gg.essential.elementa.constraints.animation.AnimationStrategy * gg.essential.elementa.constraints.animation.Animations * gg.essential.elementa.dsl.UtilitiesKt * gg.essential.elementa.events.UIClickEvent * gg.essential.universal.USound * kotlin.Metadata * kotlin.Unit * kotlin.jvm.functions.Function1 * kotlin.jvm.functions.Function2 * kotlin.jvm.internal.Intrinsics * org.jetbrains.annotations.NotNull */ package xyz.apfelmus.cheeto.client.clickgui.settings; @Metadata(mv={1, 6, 0}, k=1, xi=48, d1={"\u00002\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0010\u000b\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0003\n\u0002\u0010\u0002\n\u0000\n\u0002\u0010\u0007\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\b&\u0018\u00002\u00020\u0001B\u0005\u00a2\u0006\u0002\u0010\u0002J\u000e\u0010\n\u001a\u00020\u000b2\u0006\u0010\f\u001a\u00020\rJ\u0010\u0010\u000e\u001a\u00020\u000b2\u0006\u0010\u000f\u001a\u00020\u0010H\u0016J\b\u0010\u0011\u001a\u00020\u000bH\u0004R\u000e\u0010\u0003\u001a\u00020\u0004X\u0082\u000e\u00a2\u0006\u0002\n\u0000R\u000e\u0010\u0005\u001a\u00020\u0004X\u0082\u000e\u00a2\u0006\u0002\n\u0000R\u0012\u0010\u0006\u001a\u00020\u0007X\u00a4\u0004\u00a2\u0006\u0006\u001a\u0004\b\b\u0010\t\u00a8\u0006\u0012"}, d2={"Lxyz/apfelmus/cheeto/client/clickgui/settings/AbstractSliderComponent;", "Lxyz/apfelmus/cheeto/client/clickgui/settings/SettingComponent;", "()V", "expanded", "", "mouseHeld", "slider", "Lxyz/apfelmus/cheeto/client/clickgui/settings/Slider;", "getSlider", "()Lxyz/apfelmus/cheeto/client/clickgui/settings/Slider;", "incrementBy", "", "inc", "", "setupParentListeners", "parent", "Lgg/essential/elementa/UIComponent;", "sliderInit", "Cheeto"}) public abstract class AbstractSliderComponent extends SettingComponent { private boolean expanded; private boolean mouseHeld; public AbstractSliderComponent() { UIComponent uIComponent; UIComponent $this$constrain$iv = (UIComponent)this; boolean $i$f$constrain = false; UIComponent $this$constrain_u24lambda_u2d0$iv = uIComponent = $this$constrain$iv; boolean bl = false; UIConstraints $this$_init__u24lambda_u2d0 = $this$constrain_u24lambda_u2d0$iv.getConstraints(); boolean bl2 = false; $this$_init__u24lambda_u2d0.setWidth((WidthConstraint)new ChildBasedSizeConstraint(0.0f, 1, null)); $this$_init__u24lambda_u2d0.setHeight((HeightConstraint)new ChildBasedMaxSizeConstraint()); } @NotNull
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * gg.essential.elementa.UIComponent * gg.essential.elementa.UIConstraints * gg.essential.elementa.constraints.ChildBasedMaxSizeConstraint * gg.essential.elementa.constraints.ChildBasedSizeConstraint * gg.essential.elementa.constraints.HeightConstraint * gg.essential.elementa.constraints.WidthConstraint * gg.essential.elementa.constraints.animation.AnimatingConstraints * gg.essential.elementa.constraints.animation.AnimationStrategy * gg.essential.elementa.constraints.animation.Animations * gg.essential.elementa.dsl.UtilitiesKt * gg.essential.elementa.events.UIClickEvent * gg.essential.universal.USound * kotlin.Metadata * kotlin.Unit * kotlin.jvm.functions.Function1 * kotlin.jvm.functions.Function2 * kotlin.jvm.internal.Intrinsics * org.jetbrains.annotations.NotNull */ package xyz.apfelmus.cheeto.client.clickgui.settings; @Metadata(mv={1, 6, 0}, k=1, xi=48, d1={"\u00002\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0010\u000b\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0003\n\u0002\u0010\u0002\n\u0000\n\u0002\u0010\u0007\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\b&\u0018\u00002\u00020\u0001B\u0005\u00a2\u0006\u0002\u0010\u0002J\u000e\u0010\n\u001a\u00020\u000b2\u0006\u0010\f\u001a\u00020\rJ\u0010\u0010\u000e\u001a\u00020\u000b2\u0006\u0010\u000f\u001a\u00020\u0010H\u0016J\b\u0010\u0011\u001a\u00020\u000bH\u0004R\u000e\u0010\u0003\u001a\u00020\u0004X\u0082\u000e\u00a2\u0006\u0002\n\u0000R\u000e\u0010\u0005\u001a\u00020\u0004X\u0082\u000e\u00a2\u0006\u0002\n\u0000R\u0012\u0010\u0006\u001a\u00020\u0007X\u00a4\u0004\u00a2\u0006\u0006\u001a\u0004\b\b\u0010\t\u00a8\u0006\u0012"}, d2={"Lxyz/apfelmus/cheeto/client/clickgui/settings/AbstractSliderComponent;", "Lxyz/apfelmus/cheeto/client/clickgui/settings/SettingComponent;", "()V", "expanded", "", "mouseHeld", "slider", "Lxyz/apfelmus/cheeto/client/clickgui/settings/Slider;", "getSlider", "()Lxyz/apfelmus/cheeto/client/clickgui/settings/Slider;", "incrementBy", "", "inc", "", "setupParentListeners", "parent", "Lgg/essential/elementa/UIComponent;", "sliderInit", "Cheeto"}) public abstract class AbstractSliderComponent extends SettingComponent { private boolean expanded; private boolean mouseHeld; public AbstractSliderComponent() { UIComponent uIComponent; UIComponent $this$constrain$iv = (UIComponent)this; boolean $i$f$constrain = false; UIComponent $this$constrain_u24lambda_u2d0$iv = uIComponent = $this$constrain$iv; boolean bl = false; UIConstraints $this$_init__u24lambda_u2d0 = $this$constrain_u24lambda_u2d0$iv.getConstraints(); boolean bl2 = false; $this$_init__u24lambda_u2d0.setWidth((WidthConstraint)new ChildBasedSizeConstraint(0.0f, 1, null)); $this$_init__u24lambda_u2d0.setHeight((HeightConstraint)new ChildBasedMaxSizeConstraint()); } @NotNull
protected abstract Slider getSlider();
1
2023-12-21 16:22:25+00:00
8k
vitri-ent/finorza
src/main/java/io/pyke/vitri/finorza/inference/api/RemoteControlService.java
[ { "identifier": "AgentControl", "path": "src/main/java/io/pyke/vitri/finorza/inference/client/AgentControl.java", "snippet": "public class AgentControl {\r\n\tpublic static final Minecraft minecraft = Minecraft.getInstance();\r\n\tpublic static final ByteBuffer frameResizeBuffer = ByteBuffer.allocateDir...
import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.google.protobuf.ByteString; import com.google.protobuf.Empty; import io.grpc.stub.StreamObserver; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.ChatScreen; import net.minecraft.client.gui.screens.TitleScreen; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.client.multiplayer.ServerData; import net.minecraft.client.resources.language.I18n; import net.minecraft.world.level.storage.LevelStorageException; import net.minecraft.world.level.storage.LevelSummary; import io.pyke.vitri.finorza.inference.client.AgentControl; import io.pyke.vitri.finorza.inference.client.EnvironmentRecorder; import io.pyke.vitri.finorza.inference.gui.ConnectScreenWithCallback; import io.pyke.vitri.finorza.inference.proto.RemoteControlServiceGrpc; import io.pyke.vitri.finorza.inference.proto.VitriMcrl;
3,808
return 70; } case Drop -> { return 81; } case Hotbar1 -> { return 49; } case Hotbar2 -> { return 50; } case Hotbar3 -> { return 51; } case Hotbar4 -> { return 52; } case Hotbar5 -> { return 53; } case Hotbar6 -> { return 54; } case Hotbar7 -> { return 55; } case Hotbar8 -> { return 56; } case Hotbar9 -> { return 57; } default -> { throw new RuntimeException(); } } } private static int vitriButtonToCode(VitriMcrl.MouseButton button) { switch (button) { case Attack -> { return 0; } case Use -> { return 1; } case PickItem -> { return 2; } default -> { throw new RuntimeException(); } } } @Override public void listSingleplayerWorlds( Empty request, StreamObserver<VitriMcrl.SingleplayerWorlds> response ) { List<VitriMcrl.SingleplayerWorld> worlds = new ArrayList<>(); try { for (LevelSummary level : minecraft.getLevelSource().getLevelList()) { VitriMcrl.SingleplayerWorld world = VitriMcrl.SingleplayerWorld.newBuilder() .setIcon(ByteString.copyFrom(Files.readAllBytes(level.getIcon().toPath()))) .setName(level.getLevelName()).setId(level.getLevelId()).build(); worlds.add(world); } } catch (LevelStorageException | IOException exception) { response.onError(exception); } response.onNext(VitriMcrl.SingleplayerWorlds.newBuilder().addAllWorlds(worlds).build()); response.onCompleted(); } @Override public void enterSingleplayerWorld( VitriMcrl.EnterSingleplayerWorldRequest request, StreamObserver<Empty> response ) { if (minecraft.getLevelSource().levelExists(request.getId())) { AgentControl.dispatchMainThread(() -> { AgentControl.loadLevel(request.getId()); response.onNext(Empty.getDefaultInstance()); response.onCompleted(); }); } else { response.onError(new Exception("World with ID '" + request.getId() + "' not found.")); } } @Override public void enterMultiplayerServer( VitriMcrl.EnterMultiplayerServerRequest request, StreamObserver<Empty> response ) { AgentControl.dispatchMainThread(() -> { AgentControl.disconnect(); minecraft.setScreen(new ConnectScreenWithCallback(new TitleScreen(), minecraft, new ServerData( I18n.get("selectServer.defaultName", new Object[0]), request.getAddr(), false), response::onError, (c) -> { response.onNext(Empty.getDefaultInstance()); response.onCompleted(); } )); }); } @Override public void setHumanControl(VitriMcrl.SetHumanControlRequest request, StreamObserver<Empty> response) { boolean enable = request.getEnable(); AgentControl.setHumanControl(enable); response.onNext(Empty.getDefaultInstance()); response.onCompleted(); } @Override public void observe(Empty request, StreamObserver<VitriMcrl.ClientObservation> response) { boolean isGuiOpen = minecraft.screen != null; boolean isPaused = isGuiOpen && !(minecraft.screen instanceof ChatScreen || minecraft.screen instanceof AbstractContainerScreen<?>); VitriMcrl.ClientObservation.Builder builder = VitriMcrl.ClientObservation.newBuilder().setDone(false) .setIsGuiOpen(isGuiOpen).setIsPaused(isPaused || !AgentControl.hasAgentControl()); if (!isPaused) {
package io.pyke.vitri.finorza.inference.api; public class RemoteControlService extends RemoteControlServiceGrpc.RemoteControlServiceImplBase { private final Minecraft minecraft = Minecraft.getInstance(); private VitriMcrl.ActRequest lastAction = null; private static int vitriKeyToCode(VitriMcrl.Key key) { switch (key) { case Forward -> { return 87; } case Back -> { return 83; } case Left -> { return 65; } case Right -> { return 68; } case Jump -> { return 32; } case Sneak -> { return 340; } case Sprint -> { return 341; } case Esc -> { return 256; } case Inventory -> { return 69; } case SwapHands -> { return 70; } case Drop -> { return 81; } case Hotbar1 -> { return 49; } case Hotbar2 -> { return 50; } case Hotbar3 -> { return 51; } case Hotbar4 -> { return 52; } case Hotbar5 -> { return 53; } case Hotbar6 -> { return 54; } case Hotbar7 -> { return 55; } case Hotbar8 -> { return 56; } case Hotbar9 -> { return 57; } default -> { throw new RuntimeException(); } } } private static int vitriButtonToCode(VitriMcrl.MouseButton button) { switch (button) { case Attack -> { return 0; } case Use -> { return 1; } case PickItem -> { return 2; } default -> { throw new RuntimeException(); } } } @Override public void listSingleplayerWorlds( Empty request, StreamObserver<VitriMcrl.SingleplayerWorlds> response ) { List<VitriMcrl.SingleplayerWorld> worlds = new ArrayList<>(); try { for (LevelSummary level : minecraft.getLevelSource().getLevelList()) { VitriMcrl.SingleplayerWorld world = VitriMcrl.SingleplayerWorld.newBuilder() .setIcon(ByteString.copyFrom(Files.readAllBytes(level.getIcon().toPath()))) .setName(level.getLevelName()).setId(level.getLevelId()).build(); worlds.add(world); } } catch (LevelStorageException | IOException exception) { response.onError(exception); } response.onNext(VitriMcrl.SingleplayerWorlds.newBuilder().addAllWorlds(worlds).build()); response.onCompleted(); } @Override public void enterSingleplayerWorld( VitriMcrl.EnterSingleplayerWorldRequest request, StreamObserver<Empty> response ) { if (minecraft.getLevelSource().levelExists(request.getId())) { AgentControl.dispatchMainThread(() -> { AgentControl.loadLevel(request.getId()); response.onNext(Empty.getDefaultInstance()); response.onCompleted(); }); } else { response.onError(new Exception("World with ID '" + request.getId() + "' not found.")); } } @Override public void enterMultiplayerServer( VitriMcrl.EnterMultiplayerServerRequest request, StreamObserver<Empty> response ) { AgentControl.dispatchMainThread(() -> { AgentControl.disconnect(); minecraft.setScreen(new ConnectScreenWithCallback(new TitleScreen(), minecraft, new ServerData( I18n.get("selectServer.defaultName", new Object[0]), request.getAddr(), false), response::onError, (c) -> { response.onNext(Empty.getDefaultInstance()); response.onCompleted(); } )); }); } @Override public void setHumanControl(VitriMcrl.SetHumanControlRequest request, StreamObserver<Empty> response) { boolean enable = request.getEnable(); AgentControl.setHumanControl(enable); response.onNext(Empty.getDefaultInstance()); response.onCompleted(); } @Override public void observe(Empty request, StreamObserver<VitriMcrl.ClientObservation> response) { boolean isGuiOpen = minecraft.screen != null; boolean isPaused = isGuiOpen && !(minecraft.screen instanceof ChatScreen || minecraft.screen instanceof AbstractContainerScreen<?>); VitriMcrl.ClientObservation.Builder builder = VitriMcrl.ClientObservation.newBuilder().setDone(false) .setIsGuiOpen(isGuiOpen).setIsPaused(isPaused || !AgentControl.hasAgentControl()); if (!isPaused) {
EnvironmentRecorder recorder = EnvironmentRecorder.getInstance();
1
2023-12-20 05:19:21+00:00
8k
ciallo-dev/JWSystemLib
src/test/java/TestCourseReview.java
[ { "identifier": "JWSystem", "path": "src/main/java/moe/snowflake/jwSystem/JWSystem.java", "snippet": "public class JWSystem {\n public Connection.Response jwLoggedResponse;\n public Connection.Response courseSelectSystemResponse;\n public Map<String, String> headers = new HashMap<>();\n priv...
import moe.snowflake.jwSystem.JWSystem; import moe.snowflake.jwSystem.manager.URLManager; import org.junit.jupiter.api.Test;
4,783
public class TestCourseReview { @Test public void testReview() { // 使用备用路线登录 URLManager.useLocalNetServer(2);
public class TestCourseReview { @Test public void testReview() { // 使用备用路线登录 URLManager.useLocalNetServer(2);
JWSystem system = new JWSystem(false).login("username","password");
0
2023-12-21 10:58:12+00:00
8k
emtee40/ApkSignatureKill-pc
app/src/main/java/org/jf/dexlib2/writer/builder/BuilderEncodedValues.java
[ { "identifier": "BaseAnnotationEncodedValue", "path": "app/src/main/java/org/jf/dexlib2/base/value/BaseAnnotationEncodedValue.java", "snippet": "public abstract class BaseAnnotationEncodedValue implements AnnotationEncodedValue {\n @Override\n public int hashCode() {\n int hashCode = getTyp...
import androidx.annotation.NonNull; import org.jf.dexlib2.base.value.BaseAnnotationEncodedValue; import org.jf.dexlib2.base.value.BaseArrayEncodedValue; import org.jf.dexlib2.base.value.BaseBooleanEncodedValue; import org.jf.dexlib2.base.value.BaseEnumEncodedValue; import org.jf.dexlib2.base.value.BaseFieldEncodedValue; import org.jf.dexlib2.base.value.BaseMethodEncodedValue; import org.jf.dexlib2.base.value.BaseNullEncodedValue; import org.jf.dexlib2.base.value.BaseStringEncodedValue; import org.jf.dexlib2.base.value.BaseTypeEncodedValue; import org.jf.dexlib2.iface.value.EncodedValue; import org.jf.dexlib2.immutable.value.ImmutableByteEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableCharEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableDoubleEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableFloatEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableIntEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableLongEncodedValue; import org.jf.dexlib2.immutable.value.ImmutableShortEncodedValue; import org.jf.util.ExceptionWithContext; import java.util.List; import java.util.Set;
5,011
/* * Copyright 2013, 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 org.jf.dexlib2.writer.builder; public abstract class BuilderEncodedValues { @NonNull public static BuilderEncodedValue defaultValueForType(String type) { switch (type.charAt(0)) { case 'Z': return BuilderBooleanEncodedValue.FALSE_VALUE; case 'B': return new BuilderByteEncodedValue((byte) 0); case 'S': return new BuilderShortEncodedValue((short) 0); case 'C': return new BuilderCharEncodedValue((char) 0); case 'I': return new BuilderIntEncodedValue(0); case 'J': return new BuilderLongEncodedValue(0); case 'F': return new BuilderFloatEncodedValue(0); case 'D': return new BuilderDoubleEncodedValue(0); case 'L': case '[': return BuilderNullEncodedValue.INSTANCE; default: throw new ExceptionWithContext("Unrecognized type: %s", type); } } public static interface BuilderEncodedValue extends EncodedValue { } public static class BuilderAnnotationEncodedValue extends BaseAnnotationEncodedValue implements BuilderEncodedValue { @NonNull final BuilderTypeReference typeReference; @NonNull final Set<? extends BuilderAnnotationElement> elements; BuilderAnnotationEncodedValue(@NonNull BuilderTypeReference typeReference, @NonNull Set<? extends BuilderAnnotationElement> elements) { this.typeReference = typeReference; this.elements = elements; } @NonNull @Override public String getType() { return typeReference.getType(); } @NonNull @Override public Set<? extends BuilderAnnotationElement> getElements() { return elements; } } public static class BuilderArrayEncodedValue extends BaseArrayEncodedValue implements BuilderEncodedValue { @NonNull final List<? extends BuilderEncodedValue> elements; BuilderArrayEncodedValue(@NonNull List<? extends BuilderEncodedValue> elements) { this.elements = elements; } @NonNull @Override public List<? extends EncodedValue> getValue() { return elements; } }
/* * Copyright 2013, 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 org.jf.dexlib2.writer.builder; public abstract class BuilderEncodedValues { @NonNull public static BuilderEncodedValue defaultValueForType(String type) { switch (type.charAt(0)) { case 'Z': return BuilderBooleanEncodedValue.FALSE_VALUE; case 'B': return new BuilderByteEncodedValue((byte) 0); case 'S': return new BuilderShortEncodedValue((short) 0); case 'C': return new BuilderCharEncodedValue((char) 0); case 'I': return new BuilderIntEncodedValue(0); case 'J': return new BuilderLongEncodedValue(0); case 'F': return new BuilderFloatEncodedValue(0); case 'D': return new BuilderDoubleEncodedValue(0); case 'L': case '[': return BuilderNullEncodedValue.INSTANCE; default: throw new ExceptionWithContext("Unrecognized type: %s", type); } } public static interface BuilderEncodedValue extends EncodedValue { } public static class BuilderAnnotationEncodedValue extends BaseAnnotationEncodedValue implements BuilderEncodedValue { @NonNull final BuilderTypeReference typeReference; @NonNull final Set<? extends BuilderAnnotationElement> elements; BuilderAnnotationEncodedValue(@NonNull BuilderTypeReference typeReference, @NonNull Set<? extends BuilderAnnotationElement> elements) { this.typeReference = typeReference; this.elements = elements; } @NonNull @Override public String getType() { return typeReference.getType(); } @NonNull @Override public Set<? extends BuilderAnnotationElement> getElements() { return elements; } } public static class BuilderArrayEncodedValue extends BaseArrayEncodedValue implements BuilderEncodedValue { @NonNull final List<? extends BuilderEncodedValue> elements; BuilderArrayEncodedValue(@NonNull List<? extends BuilderEncodedValue> elements) { this.elements = elements; } @NonNull @Override public List<? extends EncodedValue> getValue() { return elements; } }
public static class BuilderBooleanEncodedValue extends BaseBooleanEncodedValue
2
2023-12-16 11:11:16+00:00
8k
nimashidewanmini/layered-architecture-nimashi
src/main/java/com/example/layeredarchitecture/controller/PlaceOrderFormController.java
[ { "identifier": "DBConnection", "path": "src/main/java/com/example/layeredarchitecture/db/DBConnection.java", "snippet": "public class DBConnection {\n private static DBConnection dbConnection;\n private final Connection connection;\n\n private DBConnection() throws ClassNotFoundException, SQLE...
import com.example.layeredarchitecture.dao.*; 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.util.TransactionConnection; 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;
4,267
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; ItemDao itemDao= new ItemDAOImpl(); OrderDAO orderDAO= new OrderDAOImpl(); CustomerDao customerDao=new customerDAOImpl(); OrderDetailDAO orderDetailDAO=new OrderDetailDAOImpl(); 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 { if (!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")); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?"); pstm.setString(1, newItemCode + ""); ResultSet rst = pstm.executeQuery(); rst.next(); ItemDTO item = new ItemDTO(newItemCode + "", rst.getString("description"), rst.getBigDecimal("unitPrice"), rst.getInt("qtyOnHand")); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } private boolean existItem(String code) throws SQLException, ClassNotFoundException { // Connection connection = DBConnection.getDbConnection().getConnection(); // PreparedStatement pstm = connection.prepareStatement("SELECT code FROM Item WHERE code=?"); // pstm.setString(1, code); // return pstm.executeQuery().next(); return itemDao.existItem(code); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT id FROM Customer WHERE id=?"); pstm.setString(1, id); return pstm.executeQuery().next(); } public String generateNewOrderId() { try { ResultSet resultSet = orderDAO.generateNewOrderID(); return resultSet.next() ? String.format("OID-%03d", (Integer.parseInt(resultSet.getString("oid").replace("OID-", "")) + 1)) : "OID-001"; } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { // Connection connection = DBConnection.getDbConnection().getConnection(); // Statement stm = connection.createStatement(); // ResultSet rst = stm.executeQuery("SELECT * FROM Customer"); // while (rst.next()) { // cmbCustomerId.getItems().add(rst.getString("id")); // } ArrayList <CustomerDTO> allCustomers=customerDao.getAllCustomer(); for (CustomerDTO customerDTO:allCustomers) { cmbCustomerId.getItems().add(customerDTO.getId()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ // Connection connection = DBConnection.getDbConnection().getConnection(); // Statement stm = connection.createStatement(); // ResultSet rst = stm.executeQuery("SELECT * FROM Item"); ArrayList <ItemDTO> allItems=itemDao.getAllItems(); // while (rst.next()) { // cmbItemCode.getItems().add(rst.getString("code")); // } for (ItemDTO itemDTO:allItems){ cmbItemCode.getItems().add(itemDTO.getCode()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
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; ItemDao itemDao= new ItemDAOImpl(); OrderDAO orderDAO= new OrderDAOImpl(); CustomerDao customerDao=new customerDAOImpl(); OrderDetailDAO orderDetailDAO=new OrderDetailDAOImpl(); 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 { if (!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")); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?"); pstm.setString(1, newItemCode + ""); ResultSet rst = pstm.executeQuery(); rst.next(); ItemDTO item = new ItemDTO(newItemCode + "", rst.getString("description"), rst.getBigDecimal("unitPrice"), rst.getInt("qtyOnHand")); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } private boolean existItem(String code) throws SQLException, ClassNotFoundException { // Connection connection = DBConnection.getDbConnection().getConnection(); // PreparedStatement pstm = connection.prepareStatement("SELECT code FROM Item WHERE code=?"); // pstm.setString(1, code); // return pstm.executeQuery().next(); return itemDao.existItem(code); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT id FROM Customer WHERE id=?"); pstm.setString(1, id); return pstm.executeQuery().next(); } public String generateNewOrderId() { try { ResultSet resultSet = orderDAO.generateNewOrderID(); return resultSet.next() ? String.format("OID-%03d", (Integer.parseInt(resultSet.getString("oid").replace("OID-", "")) + 1)) : "OID-001"; } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { // Connection connection = DBConnection.getDbConnection().getConnection(); // Statement stm = connection.createStatement(); // ResultSet rst = stm.executeQuery("SELECT * FROM Customer"); // while (rst.next()) { // cmbCustomerId.getItems().add(rst.getString("id")); // } ArrayList <CustomerDTO> allCustomers=customerDao.getAllCustomer(); for (CustomerDTO customerDTO:allCustomers) { cmbCustomerId.getItems().add(customerDTO.getId()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ // Connection connection = DBConnection.getDbConnection().getConnection(); // Statement stm = connection.createStatement(); // ResultSet rst = stm.executeQuery("SELECT * FROM Item"); ArrayList <ItemDTO> allItems=itemDao.getAllItems(); // while (rst.next()) { // cmbItemCode.getItems().add(rst.getString("code")); // } for (ItemDTO itemDTO:allItems){ cmbItemCode.getItems().add(itemDTO.getCode()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
tblOrderDetails.getItems().stream().map(tm -> new OrderDetailDTO(tm.getCode(), tm.getQty(), tm.getUnitPrice())).collect(Collectors.toList()));
3
2023-12-16 04:14:29+00:00
8k
IzanagiCraft/IzanagiWorldGuard
worldguard-plugin-bukkit/src/main/java/com/izanagicraft/guard/commands/WorldGuardCommand.java
[ { "identifier": "IzanagiWorldGuardPlugin", "path": "worldguard-plugin-bukkit/src/main/java/com/izanagicraft/guard/IzanagiWorldGuardPlugin.java", "snippet": "public class IzanagiWorldGuardPlugin extends JavaPlugin {\n\n private static IzanagiWorldGuardPlugin instance;\n\n /**\n * Gets the singl...
import com.izanagicraft.guard.IzanagiWorldGuardPlugin; import com.izanagicraft.guard.flags.GuardFlag; import com.izanagicraft.guard.permissions.GuardPermission; import com.izanagicraft.guard.utils.MessageUtils; import com.izanagicraft.guard.utils.StringUtils; import org.bukkit.command.Command; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import java.util.ArrayList; import java.util.List; import java.util.Map;
6,358
/* * ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄ * ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██ * ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪ * ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌· * ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀ * * * @@@@@ * @@* *@@ * @@@ @@@ * @@@ @@ @@@ @@@@@@@@@@@ * @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ * @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@ @@ @@ @@@@ @@@@ * @@@@ @@@ @@@@ @@@@ @@@ * @@@@@@ @@@@@@ @@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@ * * 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.commands; /** * IzanagiWorldGuard; com.izanagicraft.guard.commands:WorldGuardCommand * * @author <a href="https://github.com/sanguine6660">@sanguine6660</a> * @since 18.12.2023 */ public class WorldGuardCommand extends GuardCommand { private final IzanagiWorldGuardPlugin plugin; /** * Constructs a new GuardCommand with the given name. * * @param plugin the instance of the IzanagiWorldGuardPlugin */ public WorldGuardCommand(IzanagiWorldGuardPlugin plugin) { super("worldguard"); this.plugin = plugin; setAliases(List.of("g", "wg", "guard")); setDescription("Guard your worlds and set region specific flags."); setUsage("&e/worldguard <reload/flag/flags/tp> [flag: <flagname> <value> | tp: <regionName>]");
/* * ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄ * ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██ * ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪ * ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌· * ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀ * * * @@@@@ * @@* *@@ * @@@ @@@ * @@@ @@ @@@ @@@@@@@@@@@ * @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@ * @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * #@@@ @@ @@ @@@@ @@@@ * @@@@ @@@ @@@@ @@@@ @@@ * @@@@@@ @@@@@@ @@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@@@@@@@@@ * @@@@@@@@@@@ * * 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.commands; /** * IzanagiWorldGuard; com.izanagicraft.guard.commands:WorldGuardCommand * * @author <a href="https://github.com/sanguine6660">@sanguine6660</a> * @since 18.12.2023 */ public class WorldGuardCommand extends GuardCommand { private final IzanagiWorldGuardPlugin plugin; /** * Constructs a new GuardCommand with the given name. * * @param plugin the instance of the IzanagiWorldGuardPlugin */ public WorldGuardCommand(IzanagiWorldGuardPlugin plugin) { super("worldguard"); this.plugin = plugin; setAliases(List.of("g", "wg", "guard")); setDescription("Guard your worlds and set region specific flags."); setUsage("&e/worldguard <reload/flag/flags/tp> [flag: <flagname> <value> | tp: <regionName>]");
setPermission(GuardPermission.COMMAND_WORLDGUARD.getName());
2
2023-12-17 14:18:31+00:00
8k
dishantharuka/layered-architecture
src/main/java/com/example/layeredarchitecture/controller/PlaceOrderFormController.java
[ { "identifier": "DBConnection", "path": "src/main/java/com/example/layeredarchitecture/db/DBConnection.java", "snippet": "public class DBConnection {\n private static DBConnection dbConnection;\n private final Connection connection;\n\n private DBConnection() throws ClassNotFoundException, SQLE...
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.List; import java.util.Optional; import java.util.stream.Collectors;
3,998
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; 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 { if (!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")); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?"); pstm.setString(1, newItemCode + ""); ResultSet rst = pstm.executeQuery(); rst.next(); ItemDTO item = new ItemDTO(newItemCode + "", rst.getString("description"), rst.getBigDecimal("unitPrice"), rst.getInt("qtyOnHand")); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } private boolean existItem(String code) throws SQLException, ClassNotFoundException { Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT code FROM Item WHERE code=?"); pstm.setString(1, code); return pstm.executeQuery().next(); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT id FROM Customer WHERE id=?"); pstm.setString(1, id); return pstm.executeQuery().next(); } public String generateNewOrderId() { try { Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT oid FROM `Orders` ORDER BY oid DESC LIMIT 1;"); return rst.next() ? String.format("OID-%03d", (Integer.parseInt(rst.getString("oid").replace("OID-", "")) + 1)) : "OID-001"; } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT * FROM Customer"); while (rst.next()) { cmbCustomerId.getItems().add(rst.getString("id")); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT * FROM Item"); while (rst.next()) { cmbItemCode.getItems().add(rst.getString("code")); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
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; 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 { if (!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")); txtCustomerName.setText(customerDTO.getName()); } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?"); pstm.setString(1, newItemCode + ""); ResultSet rst = pstm.executeQuery(); rst.next(); ItemDTO item = new ItemDTO(newItemCode + "", rst.getString("description"), rst.getBigDecimal("unitPrice"), rst.getInt("qtyOnHand")); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException throwables) { throwables.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } private boolean existItem(String code) throws SQLException, ClassNotFoundException { Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT code FROM Item WHERE code=?"); pstm.setString(1, code); return pstm.executeQuery().next(); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { Connection connection = DBConnection.getDbConnection().getConnection(); PreparedStatement pstm = connection.prepareStatement("SELECT id FROM Customer WHERE id=?"); pstm.setString(1, id); return pstm.executeQuery().next(); } public String generateNewOrderId() { try { Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT oid FROM `Orders` ORDER BY oid DESC LIMIT 1;"); return rst.next() ? String.format("OID-%03d", (Integer.parseInt(rst.getString("oid").replace("OID-", "")) + 1)) : "OID-001"; } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT * FROM Customer"); while (rst.next()) { cmbCustomerId.getItems().add(rst.getString("id")); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ Connection connection = DBConnection.getDbConnection().getConnection(); Statement stm = connection.createStatement(); ResultSet rst = stm.executeQuery("SELECT * FROM Item"); while (rst.next()) { cmbItemCode.getItems().add(rst.getString("code")); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
tblOrderDetails.getItems().stream().map(tm -> new OrderDetailDTO(tm.getCode(), tm.getQty(), tm.getUnitPrice())).collect(Collectors.toList()));
3
2023-12-16 04:23:56+00:00
8k
123yyh123/xiaofanshu
xfs-gateway/src/main/java/com/yyh/xfs/gateway/filter/JWTFilter.java
[ { "identifier": "ReleasePath", "path": "xfs-gateway/src/main/java/com/yyh/xfs/gateway/properties/ReleasePath.java", "snippet": "@Component\n@Getter\n@Setter\n@ConfigurationProperties(prefix = \"release.auth\")\npublic class ReleasePath {\n private List<String> path;\n}" }, { "identifier": "Ex...
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.yyh.xfs.gateway.properties.ReleasePath; 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.gateway.properties.JwtProperties; import com.yyh.xfs.gateway.utils.JWTUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import java.util.HashMap; import java.util.List; import java.util.Map;
6,390
package com.yyh.xfs.gateway.filter; /** * @author yyh * @date 2023-11-30 */ @Component @Slf4j public class JWTFilter implements GlobalFilter { private final JwtProperties jwtProperties; private final RedisCache redisCache;
package com.yyh.xfs.gateway.filter; /** * @author yyh * @date 2023-11-30 */ @Component @Slf4j public class JWTFilter implements GlobalFilter { private final JwtProperties jwtProperties; private final RedisCache redisCache;
private final ReleasePath releasePath;
0
2023-12-15 08:13:42+00:00
8k
catools2/athena
athena-api-boot/src/test/java/org/catools/athena/rest/pipeline/mapper/AthenaPipelineMapperIT.java
[ { "identifier": "EnvironmentDto", "path": "athena-core/src/main/java/org/catools/athena/core/model/EnvironmentDto.java", "snippet": "@Data\n@Accessors(chain = true)\n@NoArgsConstructor\npublic class EnvironmentDto {\n private Long id;\n\n @NotBlank\n @Size(max = 5)\n private String code;\n\n @NotBl...
import org.catools.athena.core.model.EnvironmentDto; import org.catools.athena.core.model.MetadataDto; import org.catools.athena.core.model.ProjectDto; import org.catools.athena.core.model.UserDto; import org.catools.athena.pipeline.model.PipelineDto; import org.catools.athena.pipeline.model.PipelineExecutionDto; import org.catools.athena.pipeline.model.PipelineExecutionStatusDto; import org.catools.athena.pipeline.model.PipelineScenarioExecutionDto; import org.catools.athena.rest.AthenaBaseTest; import org.catools.athena.rest.core.builder.AthenaCoreBuilder; import org.catools.athena.rest.core.entity.Environment; import org.catools.athena.rest.core.entity.Project; import org.catools.athena.rest.core.entity.User; import org.catools.athena.rest.core.service.AthenaCoreService; import org.catools.athena.rest.pipeline.builder.AthenaPipelineBuilder; import org.catools.athena.rest.pipeline.entity.*; import org.catools.athena.rest.pipeline.service.AthenaPipelineService; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; import org.springframework.transaction.annotation.Transactional; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.core.IsEqual.equalTo;
5,293
package org.catools.athena.rest.pipeline.mapper; public class AthenaPipelineMapperIT extends AthenaBaseTest { private static PipelineDto PIPELINE_DTO; private static Pipeline PIPELINE; private static PipelineExecutionDto PIPELINE_EXECUTION_DTO; private static PipelineExecution PIPELINE_EXECUTION; private static PipelineScenarioExecutionDto PIPELINE_SCENARIO_EXECUTION_DTO; private static PipelineScenarioExecution PIPELINE_SCENARIO_EXECUTION; @Autowired AthenaPipelineMapper pipelineMapper; @Autowired AthenaCoreService athenaCoreService; @Autowired AthenaPipelineService athenaPipelineService; @BeforeAll public void beforeAll() { UserDto userDto = AthenaCoreBuilder.buildUserDto(); userDto.setId(athenaCoreService.saveUser(userDto).getId()); User user = AthenaCoreBuilder.buildUser(userDto); ProjectDto projectDto = AthenaCoreBuilder.buildProjectDto(); projectDto.setId(athenaCoreService.saveProject(projectDto).getId()); Project project = AthenaCoreBuilder.buildProject(projectDto);
package org.catools.athena.rest.pipeline.mapper; public class AthenaPipelineMapperIT extends AthenaBaseTest { private static PipelineDto PIPELINE_DTO; private static Pipeline PIPELINE; private static PipelineExecutionDto PIPELINE_EXECUTION_DTO; private static PipelineExecution PIPELINE_EXECUTION; private static PipelineScenarioExecutionDto PIPELINE_SCENARIO_EXECUTION_DTO; private static PipelineScenarioExecution PIPELINE_SCENARIO_EXECUTION; @Autowired AthenaPipelineMapper pipelineMapper; @Autowired AthenaCoreService athenaCoreService; @Autowired AthenaPipelineService athenaPipelineService; @BeforeAll public void beforeAll() { UserDto userDto = AthenaCoreBuilder.buildUserDto(); userDto.setId(athenaCoreService.saveUser(userDto).getId()); User user = AthenaCoreBuilder.buildUser(userDto); ProjectDto projectDto = AthenaCoreBuilder.buildProjectDto(); projectDto.setId(athenaCoreService.saveProject(projectDto).getId()); Project project = AthenaCoreBuilder.buildProject(projectDto);
PipelineExecutionStatusDto statusDto = AthenaPipelineBuilder.buildPipelineExecutionStatusDto();
6
2023-12-16 22:30:49+00:00
8k
premiering/permad-game
src/main/java/club/premiering/permad/entity/EntityPlayer.java
[ { "identifier": "AABoundingBox", "path": "src/main/java/club/premiering/permad/math/AABoundingBox.java", "snippet": "public class AABoundingBox {\n public float x, y, width, height;\n\n public AABoundingBox(Vector2 centerPos, Vector2 size) {\n this.x = centerPos.x - size.x / 2;\n thi...
import club.premiering.permad.math.AABoundingBox; import club.premiering.permad.math.MathUtil; import club.premiering.permad.math.Vector2; import club.premiering.permad.networking.GameSession; import club.premiering.permad.protocol.gameplay.ChatMessagePacketOut; import club.premiering.permad.protocol.gameplay.LocalPlayerStatePacketOut; import club.premiering.permad.protocol.gameplay.MoveDirection; import club.premiering.permad.util.NettyUtils; import io.netty.buffer.ByteBuf; import lombok.Getter; import java.awt.*; import java.util.HashSet; import java.util.Random; import java.util.Set;
4,048
this.velocity.y += playerSpeed.y; } if (this.isMovingRight()) { this.velocity.x += playerSpeed.x; } if (this.isOnGround() && this.boostAmount != 100) { this.setBoostAmount(this.boostAmount + BOOST_REFILL_PER_TICK); } } private void processAlivePhysics() { //Apply vertical gravity if we're in the air if (!this.isOnGround()) { this.velocity.y += GRAVITY_AMOUNT.y; if (this.velocity.y > MAX_GRAVITY_VEL_Y) { this.velocity.y = this.isMovingDown() ? (this.isSprinting() ? PLAYER_MAX_FALL_SPEED_SPRINTING : PLAYER_MAX_FALL_SPEED) : MAX_GRAVITY_VEL_Y; } } //Apply counter-velocity on x-axis (called drag?) if (this.velocity.x < 0) { this.velocity.x = Math.min(this.velocity.x + GRAVITY_AMOUNT.x, 0); } else { this.velocity.x = Math.max(this.velocity.x - GRAVITY_AMOUNT.x, 0); } //Clamp velocity to their movement maxes this.velocity.x = MathUtil.clamp(this.velocity.x, -PLAYER_MOVEMENT_MAX_VELOCITY.x, PLAYER_MOVEMENT_MAX_VELOCITY.x); this.velocity.y = MathUtil.clamp(this.velocity.y, -PLAYER_MOVEMENT_MAX_VELOCITY.y, PLAYER_MOVEMENT_MAX_VELOCITY.y); } private void processDeadPhysics() { //The goal is to apply *ONLY* counter velocity, no gravity or anything extra //Apply counter x if (this.velocity.x < 0) { this.velocity.x = Math.min(this.velocity.x + DEAD_COUNTER_VEL.x, 0); } else { this.velocity.x = Math.max(this.velocity.x - DEAD_COUNTER_VEL.x, 0); } //Apply counter y if (this.velocity.y < 0) { this.velocity.y = Math.min(this.velocity.y + DEAD_COUNTER_VEL.y, 0); } else { this.velocity.y = Math.max(this.velocity.y - DEAD_COUNTER_VEL.y, 0); } } private void applyVelocities() { this.pos.x += this.velocity.x; this.pos.y += this.velocity.y; } private void processGodMovement() { if (this.isMovingLeft()) this.pos.x -= GOD_MOVEMENT_SPEED; if (this.isMovingUp()) this.pos.y -= GOD_MOVEMENT_SPEED; if (this.isMovingRight()) this.pos.x += GOD_MOVEMENT_SPEED; if (this.isMovingDown()) this.pos.y += GOD_MOVEMENT_SPEED; } public void setBoostAmount(float boostAmount) { this.boostAmount = MathUtil.clamp(boostAmount, 0, 100); this.sendLocalStateUpdate(); } private void setPhysicsSettings(boolean god) { this.setCanBeOutsideWorld(god); this.setCollideWithSolids(!god); } public void setGod(boolean god) { this.setPhysicsSettings(god); this.god = god; } public void sendLocalStateUpdate() { this.world.submitPacket(this.session, new LocalPlayerStatePacketOut(this)); } public boolean isMovingUp() { return this.directions.contains(MoveDirection.W); } public boolean isMovingDown() { return this.directions.contains(MoveDirection.S); } public boolean isMovingLeft() { return this.directions.contains(MoveDirection.A); } public boolean isMovingRight() { return this.directions.contains(MoveDirection.D); } public boolean isSprinting() { return this.directions.contains(MoveDirection.SPRINT); } public boolean isCancelling() { return this.directions.contains(MoveDirection.CANCEL); } public void addDirectionState(MoveDirection dir) { this.directions.add(dir); } public void removeDirectionState(MoveDirection dir) { this.directions.remove(dir); } public void sendMessage(String s) {
package club.premiering.permad.entity; public class EntityPlayer extends RigidEntity { private static final Random RANDOM = new Random(); //Physics related constants private static final float PHYSICS_SCALE = 1.2f;// Mean for testing in the meantime, could be used in the future for a map element or something? private static final Vector2 PLAYER_SPEED = new Vector2(1.5f/PHYSICS_SCALE, 2.1f/PHYSICS_SCALE);//1.8 y private static final Vector2 PLAYER_SPRINT_SPEED = new Vector2(4.2f/PHYSICS_SCALE, 5f/PHYSICS_SCALE); private static final Vector2 GRAVITY_AMOUNT = new Vector2(0.25f/PHYSICS_SCALE, 0.45f/PHYSICS_SCALE);//X value is for counter velocity to stop infinte velocity on x axis (old y 0.65) private static final Vector2 PLAYER_MOVEMENT_MAX_VELOCITY = new Vector2(14f/PHYSICS_SCALE, 20f/PHYSICS_SCALE);//old y 20 private static final float PLAYER_MAX_FALL_SPEED = 12f/PHYSICS_SCALE;//14 private static final float PLAYER_MAX_FALL_SPEED_SPRINTING = 19.5f/PHYSICS_SCALE; private static final float MAX_GRAVITY_VEL_Y = 8f/PHYSICS_SCALE;//Min being how fast an object can go down due to gravity, this is separate from min vel private static final Vector2 DEAD_COUNTER_VEL = new Vector2(0.35f, 0.35f); private static final Vector2 DEAD_COLLISION_BOUNCE_VEL = new Vector2(9f, 9f); private static final float GOD_MOVEMENT_SPEED = 18f; //Boost constants private static final float BOOST_PER_TICK = 0.6f;//0.8f private static final float BOOST_PER_TICK_SPRINTING = 1.5f; private static final float BOOST_PER_TICK_CANCELLING = 20f; private static final float BOOST_REFILL_PER_TICK = 3f; // Used to give the seemings of circle collision, noted in lower TODO private static final float PLACEBO_CONST = 6f; public GameSession session; @Getter private String name = "Guest"; @Getter private final Color color; @Getter private float boostAmount = 100f;//0 - 100 @Getter private boolean dead; @Getter private boolean god = false; private boolean wasCancellingLastTick = false; private Set<MoveDirection> directions = new HashSet<>(); public EntityPlayer(GameSession session) { super(); this.session = session; this.size = new Vector2(48, 48); this.setPhysicsSettings(false); //Set random color final float hue = RANDOM.nextFloat(); this.color = Color.getHSBColor(hue, 1f, 1f); } @Override public void doTick() { if (this.god) { this.processGodMovement(); return; } if (!this.dead) { this.processMovement(); this.processAlivePhysics(); } else { this.processDeadPhysics(); } this.applyVelocities(); // Done ticking! super.doTick(); } // TODO: Implement circle collision detection @Override public void createAABBs() { this.aabbs.add(new AABoundingBox(this.pos, this.size.clone().sub(PLACEBO_CONST, PLACEBO_CONST))); } @Override public void onCollision(RigidEntity entity, AABBCollisionInfo colInfo) { if (entity instanceof EntityPlayer otherPlayer) { //Respawn both players since they're touching if (this.dead) this.respawnPlayer(); if (otherPlayer.dead) otherPlayer.respawnPlayer(); //Add boost since they're touching and reviving each other (div 2 because this will be called by both parties) this.setBoostAmount(this.getBoostAmount() + BOOST_REFILL_PER_TICK / 2); otherPlayer.setBoostAmount(otherPlayer.getBoostAmount() + BOOST_REFILL_PER_TICK / 2); } if (this.dead && entity.isSolid() && entity.isActive()) this.bounceOffCollision(colInfo, DEAD_COLLISION_BOUNCE_VEL); } public void killPlayer(AABBCollisionInfo colInfo) { if (this.dead) return; this.dead = true; this.setOnGround(false); this.bounceOffCollision(colInfo, DEAD_COLLISION_BOUNCE_VEL); this.broadcastMetadataUpdate(); } public void revivePlayer() { this.dead = false; this.broadcastMetadataUpdate(); } public void respawnPlayer() { this.revivePlayer(); } private void processMovement() { var playerSpeed = this.isSprinting() && this.boostAmount > 0 ? PLAYER_SPRINT_SPEED : PLAYER_SPEED; if (this.isCancelling() && !this.wasCancellingLastTick && this.boostAmount > 0) { this.velocity.x = 0; this.velocity.y = 0; this.setBoostAmount(this.boostAmount - BOOST_PER_TICK_CANCELLING); this.wasCancellingLastTick = true; } else if (!this.isCancelling()) { this.wasCancellingLastTick = false; } if (this.isMovingUp() && this.boostAmount > 0) { this.velocity.y -= playerSpeed.y; //Remove boost from the player if (this.isSprinting()) this.setBoostAmount(this.boostAmount - BOOST_PER_TICK_SPRINTING); else this.setBoostAmount(this.boostAmount - BOOST_PER_TICK); } if (this.isMovingLeft()) { this.velocity.x -= playerSpeed.x; } if (this.isMovingDown() && this.boostAmount > 0) { this.velocity.y += playerSpeed.y; } if (this.isMovingRight()) { this.velocity.x += playerSpeed.x; } if (this.isOnGround() && this.boostAmount != 100) { this.setBoostAmount(this.boostAmount + BOOST_REFILL_PER_TICK); } } private void processAlivePhysics() { //Apply vertical gravity if we're in the air if (!this.isOnGround()) { this.velocity.y += GRAVITY_AMOUNT.y; if (this.velocity.y > MAX_GRAVITY_VEL_Y) { this.velocity.y = this.isMovingDown() ? (this.isSprinting() ? PLAYER_MAX_FALL_SPEED_SPRINTING : PLAYER_MAX_FALL_SPEED) : MAX_GRAVITY_VEL_Y; } } //Apply counter-velocity on x-axis (called drag?) if (this.velocity.x < 0) { this.velocity.x = Math.min(this.velocity.x + GRAVITY_AMOUNT.x, 0); } else { this.velocity.x = Math.max(this.velocity.x - GRAVITY_AMOUNT.x, 0); } //Clamp velocity to their movement maxes this.velocity.x = MathUtil.clamp(this.velocity.x, -PLAYER_MOVEMENT_MAX_VELOCITY.x, PLAYER_MOVEMENT_MAX_VELOCITY.x); this.velocity.y = MathUtil.clamp(this.velocity.y, -PLAYER_MOVEMENT_MAX_VELOCITY.y, PLAYER_MOVEMENT_MAX_VELOCITY.y); } private void processDeadPhysics() { //The goal is to apply *ONLY* counter velocity, no gravity or anything extra //Apply counter x if (this.velocity.x < 0) { this.velocity.x = Math.min(this.velocity.x + DEAD_COUNTER_VEL.x, 0); } else { this.velocity.x = Math.max(this.velocity.x - DEAD_COUNTER_VEL.x, 0); } //Apply counter y if (this.velocity.y < 0) { this.velocity.y = Math.min(this.velocity.y + DEAD_COUNTER_VEL.y, 0); } else { this.velocity.y = Math.max(this.velocity.y - DEAD_COUNTER_VEL.y, 0); } } private void applyVelocities() { this.pos.x += this.velocity.x; this.pos.y += this.velocity.y; } private void processGodMovement() { if (this.isMovingLeft()) this.pos.x -= GOD_MOVEMENT_SPEED; if (this.isMovingUp()) this.pos.y -= GOD_MOVEMENT_SPEED; if (this.isMovingRight()) this.pos.x += GOD_MOVEMENT_SPEED; if (this.isMovingDown()) this.pos.y += GOD_MOVEMENT_SPEED; } public void setBoostAmount(float boostAmount) { this.boostAmount = MathUtil.clamp(boostAmount, 0, 100); this.sendLocalStateUpdate(); } private void setPhysicsSettings(boolean god) { this.setCanBeOutsideWorld(god); this.setCollideWithSolids(!god); } public void setGod(boolean god) { this.setPhysicsSettings(god); this.god = god; } public void sendLocalStateUpdate() { this.world.submitPacket(this.session, new LocalPlayerStatePacketOut(this)); } public boolean isMovingUp() { return this.directions.contains(MoveDirection.W); } public boolean isMovingDown() { return this.directions.contains(MoveDirection.S); } public boolean isMovingLeft() { return this.directions.contains(MoveDirection.A); } public boolean isMovingRight() { return this.directions.contains(MoveDirection.D); } public boolean isSprinting() { return this.directions.contains(MoveDirection.SPRINT); } public boolean isCancelling() { return this.directions.contains(MoveDirection.CANCEL); } public void addDirectionState(MoveDirection dir) { this.directions.add(dir); } public void removeDirectionState(MoveDirection dir) { this.directions.remove(dir); } public void sendMessage(String s) {
this.world.submitPacket(this.session, new ChatMessagePacketOut(s));
4
2023-12-20 03:13:05+00:00
8k
VRavindu/layered-architecture-Vimukthi-Ravindu
src/main/java/com/example/layeredarchitecture/controller/PlaceOrderFormController.java
[ { "identifier": "CustomerDAO", "path": "src/main/java/com/example/layeredarchitecture/dao/custom/CustomerDAO.java", "snippet": "public interface CustomerDAO extends CrudDAO<CustomerDTO> {\n /*ArrayList<CustomerDTO> getAllCustomer() throws SQLException, ClassNotFoundException;\n\n boolean saveCusto...
import com.example.layeredarchitecture.dao.custom.CustomerDAO; import com.example.layeredarchitecture.dao.custom.ItemDAO; import com.example.layeredarchitecture.dao.custom.OrderDAO; import com.example.layeredarchitecture.dao.custom.OrderDetailsDAO; import com.example.layeredarchitecture.dao.custom.impl.CustomerDAOimpl; import com.example.layeredarchitecture.dao.custom.impl.ItemDAOimpl; import com.example.layeredarchitecture.dao.custom.impl.OrderDAOimpl; import com.example.layeredarchitecture.dao.custom.impl.OrderDetailsDAOimpl; 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;
3,882
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; CustomerDAO customerDAO = new CustomerDAOimpl(); ItemDAO itemDAO = new ItemDAOimpl();
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; CustomerDAO customerDAO = new CustomerDAOimpl(); ItemDAO itemDAO = new ItemDAOimpl();
OrderDAO ordersDAO = new OrderDAOimpl();
2
2023-12-16 04:19:18+00:00
8k
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;
6,866
package net.egis.ethicalvoting; @Getter public final class EthicalVoting extends JavaPlugin { @Getter private static EthicalVoting self; private StorageInterface storage;
package net.egis.ethicalvoting; @Getter public final class EthicalVoting extends JavaPlugin { @Getter private static EthicalVoting self; private StorageInterface storage;
private ProfileManager profiles;
2
2023-12-15 16:48:38+00:00
8k
SAMJ-CSDC26BB/samj-javafx
samj/src/main/java/com/samj/Application.java
[ { "identifier": "Server", "path": "samj/src/main/java/com/samj/backend/Server.java", "snippet": "public class Server {\n public static List<String> list_features = Arrays.asList(\"forwardcheck\");\n private Database db;\n\n private int port;\n private HttpServer webServer;\n\n public Serv...
import com.samj.backend.Server; import com.samj.frontend.AuthenticationService; import com.samj.frontend.MainTable; import com.samj.shared.CallForwardingDTO; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; import java.awt.*; import java.time.LocalDateTime;
4,461
package com.samj; public class Application extends javafx.application.Application { public void start(Stage primaryStage) { primaryStage.setTitle("SAMJ Login"); // Create the layout GridPane grid = new GridPane(); grid.setAlignment(Pos.CENTER); grid.setVgap(10); grid.setHgap(10); grid.setPadding(new Insets(25, 25, 25, 25)); //Label CapsLock Label capsLockLabel = new Label("Caps Lock is ON"); capsLockLabel.setVisible(false); // Initially hidden // Create the components Label userName = new Label("User: "); grid.add(userName, 0, 0); TextField userTextField = new TextField(); grid.add(userTextField, 1, 0); Label pw = new Label("Password:"); grid.add(pw, 0, 1); PasswordField pwBox = new PasswordField(); grid.add(pwBox, 1, 1); Button btn = new Button("Sign in"); btn.setDefaultButton(true); grid.add(btn, 1, 2); final Text actionTarget = new Text(); grid.add(actionTarget, 1, 6); // Add event handling (simple example) AuthenticationService authService = new AuthenticationService(); btn.setOnAction(e -> { String username = userTextField.getText(); String password = pwBox.getText(); if (authService.authenticate(username, password)) { actionTarget.setText("Login successful."); // Proceed to next view or functionality _setMainSceneAfterLogin(primaryStage); } else { actionTarget.setText("Login failed."); } }); pwBox.setOnKeyReleased(event -> { boolean isCapsOn = Toolkit.getDefaultToolkit().getLockingKeyState(java.awt.event.KeyEvent.VK_CAPS_LOCK); capsLockLabel.setVisible(isCapsOn); }); userTextField.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.ENTER) { btn.fire(); } }); pwBox.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.ENTER) { btn.fire(); } }); Scene scene = new Scene(grid, 300, 275); primaryStage.setScene(scene); primaryStage.show(); } /** * Method responsible for setting the scene after login. The scene contains a table with CallForwardingDTOs. * * @param primaryStage - the stage where the new scene is set */ private void _setMainSceneAfterLogin(Stage primaryStage) { ObservableList<CallForwardingDTO> tableData = _getTableData(); MainTable mainTable = new MainTable(tableData); HBox tableSearchFields = new HBox(mainTable.getSearchFieldCalledNumber(), mainTable.getSearchFieldBeginTime(), mainTable.getSearchFieldEndTime(), mainTable.getSearchFieldDestinationNumber()); // Layout setup VBox vbox = new VBox(tableSearchFields, mainTable.getMainTable()); // Set scene Scene scene = new Scene(vbox); primaryStage.setScene(scene); primaryStage.show(); } /** * Helper method for populating the main table with data from the database. * TODO implement when database is ready */ private ObservableList<CallForwardingDTO> _getTableData() { // Original data list ObservableList<CallForwardingDTO> tableData = FXCollections.observableArrayList(); // Add sample data to the list tableData.addAll( new CallForwardingDTO(1, "22132131", LocalDateTime.now(), LocalDateTime.of(2024, 2, 1, 23, 59), "1231231", "johnDoe","John Doe"), new CallForwardingDTO(2, "1231", LocalDateTime.of(2024, 2, 2, 0, 0), LocalDateTime.of(2024, 2, 9, 0, 0), "3333", "gigiBecaliDollar", "Gigi Becali"), new CallForwardingDTO(3, "12312", LocalDateTime.of(2024, 3, 26, 12, 11), LocalDateTime.of(2024, 6, 13, 8, 7), "3333", "florinSalamNumber1","Florin Salam") // add more CallForwardingDTOs ); return tableData; } public static void main(String[] args) { // Creating the first thread for the server Thread serverThread = new Thread(() -> { System.out.println("start server");
package com.samj; public class Application extends javafx.application.Application { public void start(Stage primaryStage) { primaryStage.setTitle("SAMJ Login"); // Create the layout GridPane grid = new GridPane(); grid.setAlignment(Pos.CENTER); grid.setVgap(10); grid.setHgap(10); grid.setPadding(new Insets(25, 25, 25, 25)); //Label CapsLock Label capsLockLabel = new Label("Caps Lock is ON"); capsLockLabel.setVisible(false); // Initially hidden // Create the components Label userName = new Label("User: "); grid.add(userName, 0, 0); TextField userTextField = new TextField(); grid.add(userTextField, 1, 0); Label pw = new Label("Password:"); grid.add(pw, 0, 1); PasswordField pwBox = new PasswordField(); grid.add(pwBox, 1, 1); Button btn = new Button("Sign in"); btn.setDefaultButton(true); grid.add(btn, 1, 2); final Text actionTarget = new Text(); grid.add(actionTarget, 1, 6); // Add event handling (simple example) AuthenticationService authService = new AuthenticationService(); btn.setOnAction(e -> { String username = userTextField.getText(); String password = pwBox.getText(); if (authService.authenticate(username, password)) { actionTarget.setText("Login successful."); // Proceed to next view or functionality _setMainSceneAfterLogin(primaryStage); } else { actionTarget.setText("Login failed."); } }); pwBox.setOnKeyReleased(event -> { boolean isCapsOn = Toolkit.getDefaultToolkit().getLockingKeyState(java.awt.event.KeyEvent.VK_CAPS_LOCK); capsLockLabel.setVisible(isCapsOn); }); userTextField.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.ENTER) { btn.fire(); } }); pwBox.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.ENTER) { btn.fire(); } }); Scene scene = new Scene(grid, 300, 275); primaryStage.setScene(scene); primaryStage.show(); } /** * Method responsible for setting the scene after login. The scene contains a table with CallForwardingDTOs. * * @param primaryStage - the stage where the new scene is set */ private void _setMainSceneAfterLogin(Stage primaryStage) { ObservableList<CallForwardingDTO> tableData = _getTableData(); MainTable mainTable = new MainTable(tableData); HBox tableSearchFields = new HBox(mainTable.getSearchFieldCalledNumber(), mainTable.getSearchFieldBeginTime(), mainTable.getSearchFieldEndTime(), mainTable.getSearchFieldDestinationNumber()); // Layout setup VBox vbox = new VBox(tableSearchFields, mainTable.getMainTable()); // Set scene Scene scene = new Scene(vbox); primaryStage.setScene(scene); primaryStage.show(); } /** * Helper method for populating the main table with data from the database. * TODO implement when database is ready */ private ObservableList<CallForwardingDTO> _getTableData() { // Original data list ObservableList<CallForwardingDTO> tableData = FXCollections.observableArrayList(); // Add sample data to the list tableData.addAll( new CallForwardingDTO(1, "22132131", LocalDateTime.now(), LocalDateTime.of(2024, 2, 1, 23, 59), "1231231", "johnDoe","John Doe"), new CallForwardingDTO(2, "1231", LocalDateTime.of(2024, 2, 2, 0, 0), LocalDateTime.of(2024, 2, 9, 0, 0), "3333", "gigiBecaliDollar", "Gigi Becali"), new CallForwardingDTO(3, "12312", LocalDateTime.of(2024, 3, 26, 12, 11), LocalDateTime.of(2024, 6, 13, 8, 7), "3333", "florinSalamNumber1","Florin Salam") // add more CallForwardingDTOs ); return tableData; } public static void main(String[] args) { // Creating the first thread for the server Thread serverThread = new Thread(() -> { System.out.println("start server");
Server backend = new Server(8000);
0
2023-12-18 09:42:06+00:00
8k
jollyboss123/astra
modules/heimdall/src/main/java/com/jolly/heimdall/HeimdallResourceServerBeans.java
[ { "identifier": "DefaultAuthenticationManagerResolverCondition", "path": "modules/heimdall/src/main/java/com/jolly/heimdall/condition/DefaultAuthenticationManagerResolverCondition.java", "snippet": "public class DefaultAuthenticationManagerResolverCondition extends AllNestedConditions {\n DefaultAuthen...
import com.jolly.heimdall.condition.DefaultAuthenticationManagerResolverCondition; import com.jolly.heimdall.condition.IsOidcResourceServerCondition; import com.jolly.heimdall.hooks.ExpressionInterceptUrlRegistryPostProcessor; import com.jolly.heimdall.hooks.ServerHttpSecurityPostProcessor; import com.jolly.heimdall.properties.HeimdallOidcProperties; import com.jolly.heimdall.properties.OpenIdProviderProperties; import jakarta.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManagerResolver; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator; import org.springframework.security.oauth2.core.OAuth2TokenValidator; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtClaimNames; import org.springframework.security.oauth2.jwt.JwtClaimValidator; import org.springframework.security.oauth2.jwt.JwtValidators; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider; import org.springframework.security.oauth2.server.resource.authentication.JwtIssuerAuthenticationManagerResolver; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.util.StringUtils; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors;
4,018
package com.jolly.heimdall; /** * All beans defined here are {@link ConditionalOnMissingBean}, define your own beans to override. * * @author jolly */ @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @Conditional(IsOidcResourceServerCondition.class) @EnableWebSecurity @AutoConfiguration @ImportAutoConfiguration(HeimdallOidcBeans.class) public class HeimdallResourceServerBeans { private static final Logger log = LoggerFactory.getLogger(HeimdallResourceServerBeans.class); /** * Configures a {@link SecurityFilterChain} for a resource server with JwtDecoder with {@link Ordered#LOWEST_PRECEDENCE}. Defining a * {@link SecurityFilterChain} bean with no security matcher and an order higher than {@link Ordered#LOWEST_PRECEDENCE} will hide this * filter chain and disable most of heimdall autoconfiguration for OpenID resource servers. * * @param http HttpSecurity to configure * @param serverProperties Spring "server" configuration properties * @param heimdallProperties "com.jolly.heimdall" configuration properties * @param authorizePostProcessor Hook to override access control rules for all paths that are not listed in "permit-all" * @param httpPostProcessor Hook to override all or part of HttpSecurity autoconfiguration * @param authenticationManagerResolver Converts successful JWT decoding result into an {@link Authentication} * @param authenticationEntryPoint Spring oauth2 authentication entry point * @param accessDeniedHandler Spring oauth2 access denied handler * @return A {@link SecurityFilterChain} for servlet resource servers with JWT decoder. */ @Order(Ordered.LOWEST_PRECEDENCE) @Bean SecurityFilterChain heimdallJwtResourceServerSecurityFilterChain( HttpSecurity http, ServerProperties serverProperties, HeimdallOidcProperties heimdallProperties, ExpressionInterceptUrlRegistryPostProcessor authorizePostProcessor, ServerHttpSecurityPostProcessor httpPostProcessor, AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver, AuthenticationEntryPoint authenticationEntryPoint, Optional<AccessDeniedHandler> accessDeniedHandler ) throws Exception { http.oauth2ResourceServer(oauth2 -> { oauth2.authenticationManagerResolver(authenticationManagerResolver); oauth2.authenticationEntryPoint(authenticationEntryPoint); accessDeniedHandler.ifPresent(oauth2::accessDeniedHandler); }); ServletConfigurationUtils.configureResourceServer(http, serverProperties, heimdallProperties, authorizePostProcessor, httpPostProcessor); return http.build(); } /** * Hook to override security rules for all paths that are not listed in "permit-all". Default is isAuthenticated(). * * @return the hook. */ @ConditionalOnMissingBean @Bean ExpressionInterceptUrlRegistryPostProcessor authorizePostProcessor() { return registry -> registry.anyRequest().authenticated(); } /** * Hook to override all or part of {@link HttpSecurity} autoconfiguration. Called after heimdall configuration is applied so that you * can modify anything. * * @return the hook. */ @ConditionalOnMissingBean @Bean ServerHttpSecurityPostProcessor httpPostProcessor() { return http -> http; } /** * Provides with multi-tenancy: builds a {@link AuthenticationManagerResolver<HttpServletRequest>} per provided OIDC issuer URI. * * @param oAuth2ResourceServerProperties "spring.security.oauth2.resourceserver" configuration properties * @param heimdallProperties "com.jolly.heimdall" configuration properties * @param jwtAuthenticationConverter converts a {@link Jwt} to {@link Authentication} * @return multi-tenant {@link AuthenticationManagerResolver<HttpServletRequest>} (one for each configured issuer) */ @Conditional(DefaultAuthenticationManagerResolverCondition.class) @Bean AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver( OAuth2ResourceServerProperties oAuth2ResourceServerProperties, HeimdallOidcProperties heimdallProperties, JwtAbstractAuthenticationTokenConverter jwtAuthenticationConverter ) { final OAuth2ResourceServerProperties.Jwt jwtProps = Optional.ofNullable(oAuth2ResourceServerProperties) .map(OAuth2ResourceServerProperties::getJwt) .orElse(null); if (jwtProps != null) { String uri; if (jwtProps.getIssuerUri() != null) { uri = jwtProps.getIssuerUri(); } else { uri = jwtProps.getJwkSetUri(); } if (StringUtils.hasLength(uri)) { log.warn("spring.security.oauth2.resourceserver configuration will be ignored in favour of com.jolly.heimdall"); } } final Map<String, AuthenticationManager> jwtManagers = heimdallProperties.getOps().stream() .collect(Collectors.toMap(issuer -> issuer.getIss().toString(), issuer -> getAuthenticationManager(issuer, jwtAuthenticationConverter))); log.debug("building default JwtIssuerAuthenticationManagerResolver with: ", oAuth2ResourceServerProperties.getJwt(), heimdallProperties.getOps()); return new JwtIssuerAuthenticationManagerResolver(jwtManagers::get); } @ConditionalOnMissingBean @Bean AuthenticationEntryPoint authenticationEntryPoint() { return (request, response, authException) -> { response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer realm=\"Restricted Content\""); response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()); }; } private static AuthenticationManager getAuthenticationManager(
package com.jolly.heimdall; /** * All beans defined here are {@link ConditionalOnMissingBean}, define your own beans to override. * * @author jolly */ @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @Conditional(IsOidcResourceServerCondition.class) @EnableWebSecurity @AutoConfiguration @ImportAutoConfiguration(HeimdallOidcBeans.class) public class HeimdallResourceServerBeans { private static final Logger log = LoggerFactory.getLogger(HeimdallResourceServerBeans.class); /** * Configures a {@link SecurityFilterChain} for a resource server with JwtDecoder with {@link Ordered#LOWEST_PRECEDENCE}. Defining a * {@link SecurityFilterChain} bean with no security matcher and an order higher than {@link Ordered#LOWEST_PRECEDENCE} will hide this * filter chain and disable most of heimdall autoconfiguration for OpenID resource servers. * * @param http HttpSecurity to configure * @param serverProperties Spring "server" configuration properties * @param heimdallProperties "com.jolly.heimdall" configuration properties * @param authorizePostProcessor Hook to override access control rules for all paths that are not listed in "permit-all" * @param httpPostProcessor Hook to override all or part of HttpSecurity autoconfiguration * @param authenticationManagerResolver Converts successful JWT decoding result into an {@link Authentication} * @param authenticationEntryPoint Spring oauth2 authentication entry point * @param accessDeniedHandler Spring oauth2 access denied handler * @return A {@link SecurityFilterChain} for servlet resource servers with JWT decoder. */ @Order(Ordered.LOWEST_PRECEDENCE) @Bean SecurityFilterChain heimdallJwtResourceServerSecurityFilterChain( HttpSecurity http, ServerProperties serverProperties, HeimdallOidcProperties heimdallProperties, ExpressionInterceptUrlRegistryPostProcessor authorizePostProcessor, ServerHttpSecurityPostProcessor httpPostProcessor, AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver, AuthenticationEntryPoint authenticationEntryPoint, Optional<AccessDeniedHandler> accessDeniedHandler ) throws Exception { http.oauth2ResourceServer(oauth2 -> { oauth2.authenticationManagerResolver(authenticationManagerResolver); oauth2.authenticationEntryPoint(authenticationEntryPoint); accessDeniedHandler.ifPresent(oauth2::accessDeniedHandler); }); ServletConfigurationUtils.configureResourceServer(http, serverProperties, heimdallProperties, authorizePostProcessor, httpPostProcessor); return http.build(); } /** * Hook to override security rules for all paths that are not listed in "permit-all". Default is isAuthenticated(). * * @return the hook. */ @ConditionalOnMissingBean @Bean ExpressionInterceptUrlRegistryPostProcessor authorizePostProcessor() { return registry -> registry.anyRequest().authenticated(); } /** * Hook to override all or part of {@link HttpSecurity} autoconfiguration. Called after heimdall configuration is applied so that you * can modify anything. * * @return the hook. */ @ConditionalOnMissingBean @Bean ServerHttpSecurityPostProcessor httpPostProcessor() { return http -> http; } /** * Provides with multi-tenancy: builds a {@link AuthenticationManagerResolver<HttpServletRequest>} per provided OIDC issuer URI. * * @param oAuth2ResourceServerProperties "spring.security.oauth2.resourceserver" configuration properties * @param heimdallProperties "com.jolly.heimdall" configuration properties * @param jwtAuthenticationConverter converts a {@link Jwt} to {@link Authentication} * @return multi-tenant {@link AuthenticationManagerResolver<HttpServletRequest>} (one for each configured issuer) */ @Conditional(DefaultAuthenticationManagerResolverCondition.class) @Bean AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver( OAuth2ResourceServerProperties oAuth2ResourceServerProperties, HeimdallOidcProperties heimdallProperties, JwtAbstractAuthenticationTokenConverter jwtAuthenticationConverter ) { final OAuth2ResourceServerProperties.Jwt jwtProps = Optional.ofNullable(oAuth2ResourceServerProperties) .map(OAuth2ResourceServerProperties::getJwt) .orElse(null); if (jwtProps != null) { String uri; if (jwtProps.getIssuerUri() != null) { uri = jwtProps.getIssuerUri(); } else { uri = jwtProps.getJwkSetUri(); } if (StringUtils.hasLength(uri)) { log.warn("spring.security.oauth2.resourceserver configuration will be ignored in favour of com.jolly.heimdall"); } } final Map<String, AuthenticationManager> jwtManagers = heimdallProperties.getOps().stream() .collect(Collectors.toMap(issuer -> issuer.getIss().toString(), issuer -> getAuthenticationManager(issuer, jwtAuthenticationConverter))); log.debug("building default JwtIssuerAuthenticationManagerResolver with: ", oAuth2ResourceServerProperties.getJwt(), heimdallProperties.getOps()); return new JwtIssuerAuthenticationManagerResolver(jwtManagers::get); } @ConditionalOnMissingBean @Bean AuthenticationEntryPoint authenticationEntryPoint() { return (request, response, authException) -> { response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer realm=\"Restricted Content\""); response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()); }; } private static AuthenticationManager getAuthenticationManager(
OpenIdProviderProperties op,
5
2023-12-17 05:24:05+00:00
8k
Blawuken/MicroG-Extended
play-services-base/src/main/java/com/google/android/gms/common/api/GoogleApi.java
[ { "identifier": "ApiKey", "path": "play-services-base/src/main/java/com/google/android/gms/common/api/internal/ApiKey.java", "snippet": "public class ApiKey<O extends Api.ApiOptions> {\n private Api<O> api;\n}" }, { "identifier": "Task", "path": "play-services-tasks/src/main/java/com/goog...
import android.content.Context; import com.google.android.gms.common.api.internal.ApiKey; import com.google.android.gms.tasks.Task; import com.google.android.gms.tasks.TaskCompletionSource; import org.microg.gms.common.Hide; import org.microg.gms.common.PublicApi; import org.microg.gms.common.api.GoogleApiManager; import org.microg.gms.common.api.PendingGoogleApiCall;
5,197
/* * SPDX-FileCopyrightText: 2020, microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package com.google.android.gms.common.api; @PublicApi public abstract class GoogleApi<O extends Api.ApiOptions> implements HasApiKey<O> {
/* * SPDX-FileCopyrightText: 2020, microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package com.google.android.gms.common.api; @PublicApi public abstract class GoogleApi<O extends Api.ApiOptions> implements HasApiKey<O> {
private GoogleApiManager manager;
3
2023-12-17 16:14:53+00:00
8k
Yolka5/FTC-Imu3
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/opmode/FinalAutoLeft1.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.trajectory.Trajectory; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import org.firstinspires.ftc.teamcode.drive.SampleMecanumDrive; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.hardware.TouchSensor; 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 java.util.ArrayList;
4,356
package org.firstinspires.ftc.teamcode.drive.opmode; @Autonomous(group = "drive") public class FinalAutoLeft1 extends LinearOpMode { public static double SPEED = 0.15; boolean Starting = false; int ConusIndex = 0; double value; public static double FirstDistance = 46.5; 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; private Servo Armservo; private Servo AngleServo; private Servo Claw; private Servo orangeCone; private Servo ConeLocker; private DcMotor elevator; private DcMotor slider; private TouchSensor magnetic1; private TouchSensor magnetic2; private boolean toggle; private boolean result; Pose2d myPose = new Pose2d(-36, -60, Math.toRadians(-90)); Pose2d startPose = new Pose2d(-36, -60, Math.toRadians(90)); Pose2d EndPose = new Pose2d(-38.6, -18, Math.toRadians(172)); // 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); Armservo = hardwareMap.get(Servo.class, "arm"); AngleServo = hardwareMap.get(Servo.class, "arm angle"); Claw = hardwareMap.get(Servo.class, "clips"); orangeCone = hardwareMap.get(Servo.class, "orangeCone"); ConeLocker = hardwareMap.get(Servo.class, "coneLocker"); elevator = hardwareMap.dcMotor.get("elevator"); elevator.setTargetPosition(0); elevator.setMode(DcMotor.RunMode.RUN_TO_POSITION); elevator.setMode(DcMotor.RunMode.RUN_USING_ENCODER); elevator.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); slider = hardwareMap.dcMotor.get("leftEncoder"); double ArmIntoCone = 0.17; double ArmIntake = 1; double ArmSecondFloor = 0.91; double ArmThirdfloor = 0.84; double ArmForthFloor = 0.79; double ArmThithFloor = 0.76; double Angle = 0.4; double ClawPos = 0.65; 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); AngleServo.setPosition(Angle); Claw.setPosition(ClawPos); waitForStart(); if (isStopRequested()) return; //-------------------------------------------------------------------------------------- Trajectory trajectoryForwardFirst = drive.trajectoryBuilder(new Pose2d()) .back(FirstDistance) .build(); Trajectory trajectoryBackFromParkingConus = drive.trajectoryBuilder(new Pose2d()) .forward(5.3) .build();
package org.firstinspires.ftc.teamcode.drive.opmode; @Autonomous(group = "drive") public class FinalAutoLeft1 extends LinearOpMode { public static double SPEED = 0.15; boolean Starting = false; int ConusIndex = 0; double value; public static double FirstDistance = 46.5; 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; private Servo Armservo; private Servo AngleServo; private Servo Claw; private Servo orangeCone; private Servo ConeLocker; private DcMotor elevator; private DcMotor slider; private TouchSensor magnetic1; private TouchSensor magnetic2; private boolean toggle; private boolean result; Pose2d myPose = new Pose2d(-36, -60, Math.toRadians(-90)); Pose2d startPose = new Pose2d(-36, -60, Math.toRadians(90)); Pose2d EndPose = new Pose2d(-38.6, -18, Math.toRadians(172)); // 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); Armservo = hardwareMap.get(Servo.class, "arm"); AngleServo = hardwareMap.get(Servo.class, "arm angle"); Claw = hardwareMap.get(Servo.class, "clips"); orangeCone = hardwareMap.get(Servo.class, "orangeCone"); ConeLocker = hardwareMap.get(Servo.class, "coneLocker"); elevator = hardwareMap.dcMotor.get("elevator"); elevator.setTargetPosition(0); elevator.setMode(DcMotor.RunMode.RUN_TO_POSITION); elevator.setMode(DcMotor.RunMode.RUN_USING_ENCODER); elevator.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); slider = hardwareMap.dcMotor.get("leftEncoder"); double ArmIntoCone = 0.17; double ArmIntake = 1; double ArmSecondFloor = 0.91; double ArmThirdfloor = 0.84; double ArmForthFloor = 0.79; double ArmThithFloor = 0.76; double Angle = 0.4; double ClawPos = 0.65; 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); AngleServo.setPosition(Angle); Claw.setPosition(ClawPos); waitForStart(); if (isStopRequested()) return; //-------------------------------------------------------------------------------------- Trajectory trajectoryForwardFirst = drive.trajectoryBuilder(new Pose2d()) .back(FirstDistance) .build(); Trajectory trajectoryBackFromParkingConus = drive.trajectoryBuilder(new Pose2d()) .forward(5.3) .build();
TrajectorySequence trajectoryBackFirst = drive.trajectorySequenceBuilder(new Pose2d())
1
2023-12-15 16:57:19+00:00
8k
Dhananjay-mygithubcode/CRM-PROJECT
src/main/java/com/inn/cafe/serviceImpl/UserServiceImpl.java
[ { "identifier": "CustomerUserDetailsService", "path": "src/main/java/com/inn/cafe/JWT/CustomerUserDetailsService.java", "snippet": "@Slf4j\n@Service\npublic class CustomerUserDetailsService implements UserDetailsService {\n\n @Autowired\n UserDao userDao;\n\n private com.inn.cafe.POJO.User user...
import com.google.common.base.Strings; import com.inn.cafe.JWT.CustomerUserDetailsService; import com.inn.cafe.JWT.JwtFilter; import com.inn.cafe.JWT.jwtUtil; import com.inn.cafe.POJO.User; import com.inn.cafe.constents.CafeConstants; import com.inn.cafe.dao.UserDao; import com.inn.cafe.service.UserService; import com.inn.cafe.utils.CafeUtils; import com.inn.cafe.utils.EmailUtil; import com.inn.cafe.wrapper.UserWrapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.neo4j.Neo4jProperties; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Service; import java.util.*;
3,845
package com.inn.cafe.serviceImpl; @Slf4j @Service public class UserServiceImpl implements UserService { @Autowired UserDao userDao; @Autowired AuthenticationManager authenticationManager; @Autowired jwtUtil jwtUtil; @Autowired JwtFilter jwtFilter; @Autowired CustomerUserDetailsService customerUserDetailsService; @Autowired EmailUtil emailUtil; @Override public ResponseEntity<String> signUp(Map<String, String> requestMap) { log.info("Inside signup {}", requestMap); try { if (validaSignUpMap(requestMap)) { //System.out.println("inside validaSignUpMap"); User user = userDao.findByEmailId(requestMap.get("email")); if (Objects.isNull(user)) { userDao.save(getUserFromMap(requestMap)); //System.out.println("Successfully Registered."); return CafeUtils.getResponeEntity("Successfully Registered.", HttpStatus.OK); } else { //System.out.println("Email already exits."); return CafeUtils.getResponeEntity("Email already exits.", HttpStatus.BAD_REQUEST); } } else { //System.out.println(CafeConstants.INVALID_DATA); return CafeUtils.getResponeEntity(CafeConstants.INVALID_DATA, HttpStatus.BAD_REQUEST); } } catch (Exception ex) { ex.printStackTrace(); } //System.out.println(CafeConstants.SOMETHING_WENT_WRONG); return CafeUtils.getResponeEntity(CafeConstants.SOMETHING_WENT_WRONG, HttpStatus.INTERNAL_SERVER_ERROR); } @Override public ResponseEntity<String> login(Map<String, String> requestMap) { log.info("Inside login {}", requestMap); try { Authentication auth = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(requestMap.get("email"), requestMap.get("password"))); if (auth.isAuthenticated()) { if (customerUserDetailsService.getUserDatails().getStatus().equalsIgnoreCase("true")) { return new ResponseEntity<String>("{\"token\":\"" + jwtUtil.generateToken( customerUserDetailsService.getUserDatails().getEmail(), customerUserDetailsService.getUserDatails().getRole()) + "\"}", HttpStatus.OK); } else { return new ResponseEntity<String>("{\"message\":\"" + "Wait for Admin Approvel." + "\"}", HttpStatus.BAD_REQUEST); } } } catch (Exception ex) { log.error("{}", ex); } return new ResponseEntity<String>("{\"message\":\"" + "Bad Credentials." + "\"}", HttpStatus.BAD_REQUEST); } private boolean validaSignUpMap(Map<String, String> requestMap) { if (requestMap.containsKey("name") && requestMap.containsKey("contactNumber") && requestMap.containsKey("email") && requestMap.containsKey("password")) { return true; } return false; } private User getUserFromMap(Map<String, String> requestMap) { User user = new User(); user.setName(requestMap.get("name")); user.setContactNumber(requestMap.get("contactNumber")); user.setEmail(requestMap.get("email")); user.setPassword(requestMap.get("password")); user.setStatus(requestMap.get("status")); user.setRole("user"); return user; } @Override
package com.inn.cafe.serviceImpl; @Slf4j @Service public class UserServiceImpl implements UserService { @Autowired UserDao userDao; @Autowired AuthenticationManager authenticationManager; @Autowired jwtUtil jwtUtil; @Autowired JwtFilter jwtFilter; @Autowired CustomerUserDetailsService customerUserDetailsService; @Autowired EmailUtil emailUtil; @Override public ResponseEntity<String> signUp(Map<String, String> requestMap) { log.info("Inside signup {}", requestMap); try { if (validaSignUpMap(requestMap)) { //System.out.println("inside validaSignUpMap"); User user = userDao.findByEmailId(requestMap.get("email")); if (Objects.isNull(user)) { userDao.save(getUserFromMap(requestMap)); //System.out.println("Successfully Registered."); return CafeUtils.getResponeEntity("Successfully Registered.", HttpStatus.OK); } else { //System.out.println("Email already exits."); return CafeUtils.getResponeEntity("Email already exits.", HttpStatus.BAD_REQUEST); } } else { //System.out.println(CafeConstants.INVALID_DATA); return CafeUtils.getResponeEntity(CafeConstants.INVALID_DATA, HttpStatus.BAD_REQUEST); } } catch (Exception ex) { ex.printStackTrace(); } //System.out.println(CafeConstants.SOMETHING_WENT_WRONG); return CafeUtils.getResponeEntity(CafeConstants.SOMETHING_WENT_WRONG, HttpStatus.INTERNAL_SERVER_ERROR); } @Override public ResponseEntity<String> login(Map<String, String> requestMap) { log.info("Inside login {}", requestMap); try { Authentication auth = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(requestMap.get("email"), requestMap.get("password"))); if (auth.isAuthenticated()) { if (customerUserDetailsService.getUserDatails().getStatus().equalsIgnoreCase("true")) { return new ResponseEntity<String>("{\"token\":\"" + jwtUtil.generateToken( customerUserDetailsService.getUserDatails().getEmail(), customerUserDetailsService.getUserDatails().getRole()) + "\"}", HttpStatus.OK); } else { return new ResponseEntity<String>("{\"message\":\"" + "Wait for Admin Approvel." + "\"}", HttpStatus.BAD_REQUEST); } } } catch (Exception ex) { log.error("{}", ex); } return new ResponseEntity<String>("{\"message\":\"" + "Bad Credentials." + "\"}", HttpStatus.BAD_REQUEST); } private boolean validaSignUpMap(Map<String, String> requestMap) { if (requestMap.containsKey("name") && requestMap.containsKey("contactNumber") && requestMap.containsKey("email") && requestMap.containsKey("password")) { return true; } return false; } private User getUserFromMap(Map<String, String> requestMap) { User user = new User(); user.setName(requestMap.get("name")); user.setContactNumber(requestMap.get("contactNumber")); user.setEmail(requestMap.get("email")); user.setPassword(requestMap.get("password")); user.setStatus(requestMap.get("status")); user.setRole("user"); return user; } @Override
public ResponseEntity<List<UserWrapper>> getAllUser() {
9
2023-12-20 11:47:58+00:00
8k
TheEpicBlock/FLUIwID
src/main/java/nl/theepicblock/fluiwid/mixin/AttachWaterData.java
[ { "identifier": "FishyBusiness", "path": "src/main/java/nl/theepicblock/fluiwid/FishyBusiness.java", "snippet": "public class FishyBusiness {\n public final static float DELTA_T = 1/20f;\n public final static float DROPLET_SIZE = 1/16f;\n public final static float GRAVITY = 2f*DELTA_T;\n pub...
import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.data.DataTracker; import net.minecraft.entity.data.TrackedData; import net.minecraft.entity.data.TrackedDataHandlerRegistry; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.world.World; import nl.theepicblock.fluiwid.FishyBusiness; import nl.theepicblock.fluiwid.Fluiwid; import nl.theepicblock.fluiwid.PlayerDuck; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
4,402
package nl.theepicblock.fluiwid.mixin; @Mixin(PlayerEntity.class) public abstract class AttachWaterData extends LivingEntity implements PlayerDuck { @Unique
package nl.theepicblock.fluiwid.mixin; @Mixin(PlayerEntity.class) public abstract class AttachWaterData extends LivingEntity implements PlayerDuck { @Unique
private FishyBusiness waterData;
0
2023-12-18 12:05:13+00:00
8k
PeytonPlayz595/0.30-WebGL-Server
src/com/mojang/net/NetworkHandler.java
[ { "identifier": "PacketType", "path": "src/com/mojang/minecraft/net/PacketType.java", "snippet": "public final class PacketType {\r\n\r\n public static final PacketType[] packets = new PacketType[256];\r\n public static final PacketType INDENTIFICATION = new PacketType(new Class[]{Byte.TYPE, String....
import com.mojang.minecraft.net.PacketType; import com.mojang.minecraft.server.NetworkManager; import net.io.DummyLogger; import net.io.WebSocketChannel; import java.nio.ByteBuffer; import java.util.Arrays; import org.eclipse.jetty.util.log.Log;
6,064
package com.mojang.net; public final class NetworkHandler { public volatile boolean connected; public ByteBuffer in = ByteBuffer.allocate(1048576); public ByteBuffer out = ByteBuffer.allocate(1048576); public NetworkManager networkManager; private boolean h = false; public String address; private byte[] stringBytes = new byte[64]; public static boolean gay = false;
package com.mojang.net; public final class NetworkHandler { public volatile boolean connected; public ByteBuffer in = ByteBuffer.allocate(1048576); public ByteBuffer out = ByteBuffer.allocate(1048576); public NetworkManager networkManager; private boolean h = false; public String address; private byte[] stringBytes = new byte[64]; public static boolean gay = false;
public WebSocketChannel channel;
3
2023-12-18 15:38:59+00:00
8k
Frig00/Progetto-Ing-Software
src/main/java/it/unipv/po/aioobe/trenissimo/model/viaggio/Viaggio.java
[ { "identifier": "Utils", "path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/Utils.java", "snippet": "public class Utils {\n\n /**\n * Metodo che converte una stringa contente un tempo, in secondi.\n *\n * @param time in formato \"ore:minuti:secondi\"\n * @return Integer, i sec...
import it.unipv.po.aioobe.trenissimo.model.Utils; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.StopsEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.service.CachedStopsService; import it.unipv.po.aioobe.trenissimo.model.viaggio.ricerca.utils.Connection; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoIva.IPrezzoIvaStrategy; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoIva.PrezzoIvaFactory; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoPerDistanza.IPrezzoPerDistanzaStrategy; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoPerDistanza.PrezzoPerDistanzaFactory; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoTot.IPrezzoTotStrategy; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoTot.PrezzoTotFactory; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoTotCambi.IPrezzoTotCambiStrategy; import it.unipv.po.aioobe.trenissimo.model.viaggio.utils.strategy.prezzoTotCambi.PrezzoTotCambiFactory; import org.jetbrains.annotations.NotNull; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.concurrent.atomic.AtomicInteger;
5,719
package it.unipv.po.aioobe.trenissimo.model.viaggio; /** * Classe che modellizza un viaggio. * * @author ArrayIndexOutOfBoundsException */ public class Viaggio { private static final AtomicInteger count = new AtomicInteger(0); private int numAdulti; private int numRagazzi; private int numBambini; private int numAnimali; private LocalDate dataPartenza; private List<Connection> cambi;
package it.unipv.po.aioobe.trenissimo.model.viaggio; /** * Classe che modellizza un viaggio. * * @author ArrayIndexOutOfBoundsException */ public class Viaggio { private static final AtomicInteger count = new AtomicInteger(0); private int numAdulti; private int numRagazzi; private int numBambini; private int numAnimali; private LocalDate dataPartenza; private List<Connection> cambi;
private final IPrezzoPerDistanzaStrategy prezzoPerDistanzaStrategy;
6
2023-12-21 10:41:11+00:00
8k
kavindumal/layered-architecture-kavindu-malshan-jayasinghe
src/main/java/com/example/layeredarchitecture/controller/PlaceOrderFormController.java
[ { "identifier": "CustomerDTO", "path": "src/main/java/com/example/layeredarchitecture/model/CustomerDTO.java", "snippet": "public class CustomerDTO implements Serializable {\n private String id;\n private String name;\n private String address;\n\n public CustomerDTO() {\n }\n\n public ...
import com.example.layeredarchitecture.bo.*; 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;
3,656
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; CustomerBO customerBO = (CustomerBO) BOFactory.getBOFactory().getBO(BOFactory.BOType.CUSTOMER); ItemBO itemBO = (ItemBO) BOFactory.getBOFactory().getBO(BOFactory.BOType.ITEM); PlaceOrderBO placeOrderBO = (PlaceOrderBO) BOFactory.getBOFactory().getBO(BOFactory.BOType.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*/ try { if (!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(); } CustomerDTO dto = customerBO.searchCustomer(newValue); if (dto != null) { txtCustomerName.setText(dto.getName()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } ItemDTO item = itemBO.searchItem(newItemCode); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException | ClassNotFoundException throwable) { throwable.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } private boolean existItem(String code) throws SQLException, ClassNotFoundException { return itemBO.existItem(code); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { return customerBO.existCustomer(id); } public String generateNewOrderId() { try { String newId = placeOrderBO.generateNextOrderId(); if (newId != null) { return String.format("OID-%03d", (Integer.parseInt(newId.replace("OID-", "")) + 1)); } else { return "OID-001"; } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { ArrayList<CustomerDTO> allCustomers = customerBO.getAllCustomer(); for (CustomerDTO dto : allCustomers) { cmbCustomerId.getItems().add(dto.getId()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ ArrayList<ItemDTO> allItem = itemBO.getAllItem(); for (ItemDTO dto : allItem) { cmbItemCode.getItems().add(dto.getCode()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
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; CustomerBO customerBO = (CustomerBO) BOFactory.getBOFactory().getBO(BOFactory.BOType.CUSTOMER); ItemBO itemBO = (ItemBO) BOFactory.getBOFactory().getBO(BOFactory.BOType.ITEM); PlaceOrderBO placeOrderBO = (PlaceOrderBO) BOFactory.getBOFactory().getBO(BOFactory.BOType.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*/ try { if (!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(); } CustomerDTO dto = customerBO.searchCustomer(newValue); if (dto != null) { txtCustomerName.setText(dto.getName()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { txtCustomerName.clear(); } }); cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> { txtQty.setEditable(newItemCode != null); btnSave.setDisable(newItemCode == null); if (newItemCode != null) { /*Find Item*/ try { if (!existItem(newItemCode + "")) { // throw new NotFoundException("There is no such item associated with the id " + code); } ItemDTO item = itemBO.searchItem(newItemCode); txtDescription.setText(item.getDescription()); txtUnitPrice.setText(item.getUnitPrice().setScale(2).toString()); // txtQtyOnHand.setText(tblOrderDetails.getItems().stream().filter(detail-> detail.getCode().equals(item.getCode())).<Integer>map(detail-> item.getQtyOnHand() - detail.getQty()).findFirst().orElse(item.getQtyOnHand()) + ""); Optional<OrderDetailTM> optOrderDetail = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(newItemCode)).findFirst(); txtQtyOnHand.setText((optOrderDetail.isPresent() ? item.getQtyOnHand() - optOrderDetail.get().getQty() : item.getQtyOnHand()) + ""); } catch (SQLException | ClassNotFoundException throwable) { throwable.printStackTrace(); } } else { txtDescription.clear(); txtQty.clear(); txtQtyOnHand.clear(); txtUnitPrice.clear(); } }); tblOrderDetails.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selectedOrderDetail) -> { if (selectedOrderDetail != null) { cmbItemCode.setDisable(true); cmbItemCode.setValue(selectedOrderDetail.getCode()); btnSave.setText("Update"); txtQtyOnHand.setText(Integer.parseInt(txtQtyOnHand.getText()) + selectedOrderDetail.getQty() + ""); txtQty.setText(selectedOrderDetail.getQty() + ""); } else { btnSave.setText("Add"); cmbItemCode.setDisable(false); cmbItemCode.getSelectionModel().clearSelection(); txtQty.clear(); } }); loadAllCustomerIds(); loadAllItemCodes(); } private boolean existItem(String code) throws SQLException, ClassNotFoundException { return itemBO.existItem(code); } boolean existCustomer(String id) throws SQLException, ClassNotFoundException { return customerBO.existCustomer(id); } public String generateNewOrderId() { try { String newId = placeOrderBO.generateNextOrderId(); if (newId != null) { return String.format("OID-%03d", (Integer.parseInt(newId.replace("OID-", "")) + 1)); } else { return "OID-001"; } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to generate a new order id").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return "OID-001"; } private void loadAllCustomerIds() { try { ArrayList<CustomerDTO> allCustomers = customerBO.getAllCustomer(); for (CustomerDTO dto : allCustomers) { cmbCustomerId.getItems().add(dto.getId()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void loadAllItemCodes() { try { /*Get all items*/ ArrayList<ItemDTO> allItem = itemBO.getAllItem(); for (ItemDTO dto : allItem) { cmbItemCode.getItems().add(dto.getCode()); } } catch (SQLException e) { new Alert(Alert.AlertType.ERROR, e.getMessage()).show(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } @FXML private void navigateToHome(MouseEvent event) throws IOException { URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml"); Parent root = FXMLLoader.load(resource); Scene scene = new Scene(root); Stage primaryStage = (Stage) (this.root.getScene().getWindow()); primaryStage.setScene(scene); primaryStage.centerOnScreen(); Platform.runLater(() -> primaryStage.sizeToScene()); } public void btnAdd_OnAction(ActionEvent actionEvent) { if (!txtQty.getText().matches("\\d+") || Integer.parseInt(txtQty.getText()) <= 0 || Integer.parseInt(txtQty.getText()) > Integer.parseInt(txtQtyOnHand.getText())) { new Alert(Alert.AlertType.ERROR, "Invalid qty").show(); txtQty.requestFocus(); txtQty.selectAll(); return; } String itemCode = cmbItemCode.getSelectionModel().getSelectedItem(); String description = txtDescription.getText(); BigDecimal unitPrice = new BigDecimal(txtUnitPrice.getText()).setScale(2); int qty = Integer.parseInt(txtQty.getText()); BigDecimal total = unitPrice.multiply(new BigDecimal(qty)).setScale(2); boolean exists = tblOrderDetails.getItems().stream().anyMatch(detail -> detail.getCode().equals(itemCode)); if (exists) { OrderDetailTM orderDetailTM = tblOrderDetails.getItems().stream().filter(detail -> detail.getCode().equals(itemCode)).findFirst().get(); if (btnSave.getText().equalsIgnoreCase("Update")) { orderDetailTM.setQty(qty); orderDetailTM.setTotal(total); tblOrderDetails.getSelectionModel().clearSelection(); } else { orderDetailTM.setQty(orderDetailTM.getQty() + qty); total = new BigDecimal(orderDetailTM.getQty()).multiply(unitPrice).setScale(2); orderDetailTM.setTotal(total); } tblOrderDetails.refresh(); } else { tblOrderDetails.getItems().add(new OrderDetailTM(itemCode, description, qty, unitPrice, total)); } cmbItemCode.getSelectionModel().clearSelection(); cmbItemCode.requestFocus(); calculateTotal(); enableOrDisablePlaceOrderButton(); } private void calculateTotal() { BigDecimal total = new BigDecimal(0); for (OrderDetailTM detail : tblOrderDetails.getItems()) { total = total.add(detail.getTotal()); } lblTotal.setText("Total: " +total); } private void enableOrDisablePlaceOrderButton() { btnPlaceOrder.setDisable(!(cmbCustomerId.getSelectionModel().getSelectedItem() != null && !tblOrderDetails.getItems().isEmpty())); } public void txtQty_OnAction(ActionEvent actionEvent) { } public void btnPlaceOrder_OnAction(ActionEvent actionEvent) { boolean b = saveOrder(orderId, LocalDate.now(), cmbCustomerId.getValue(),
tblOrderDetails.getItems().stream().map(tm -> new OrderDetailDTO(tm.getCode(), tm.getQty(), tm.getUnitPrice())).collect(Collectors.toList()));
2
2023-12-16 04:16:50+00:00
8k
chulakasam/layered
src/main/java/com/example/layeredarchitecture/bo/PlaceOrderBOImpl.java
[ { "identifier": "DAOFactory", "path": "src/main/java/com/example/layeredarchitecture/dao/DAOFactory.java", "snippet": "public class DAOFactory {\n private static DAOFactory daoFactory;\n private DAOFactory(){\n\n }\n public static DAOFactory getDaoFactory(){\n return (daoFactory==null)...
import com.example.layeredarchitecture.dao.DAOFactory; 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 java.sql.Connection; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List;
5,576
package com.example.layeredarchitecture.bo; public class PlaceOrderBOImpl implements PlaceOrderBO{ OrderDao orderDAO = (OrderDao) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER); CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.CUSTOMER); ItemDao itemDAO = (ItemDao) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ITEM); OrderDetailDAO orderDetailDAOImpl = (OrderDetailDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER_DETAILS);
package com.example.layeredarchitecture.bo; public class PlaceOrderBOImpl implements PlaceOrderBO{ OrderDao orderDAO = (OrderDao) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER); CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.CUSTOMER); ItemDao itemDAO = (ItemDao) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ITEM); OrderDetailDAO orderDetailDAOImpl = (OrderDetailDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER_DETAILS);
public boolean PlaceOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLException, ClassNotFoundException {
12
2023-12-15 04:45:10+00:00
8k
pan2013e/ppt4j
framework/src/main/java/ppt4j/util/StringUtils.java
[ { "identifier": "Main", "path": "framework/src/main/java/ppt4j/Main.java", "snippet": "public final class Main {\n\n private static final String VM_OPTIONS =\n \"-javaagent:lib/aspectjweaver-1.9.19.jar \" +\n \"-Xss2m -XX:CompilerThreadStackSize=2048 -XX:VMThreadStackSize=2048 \...
import lombok.NonNull; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.analysis.BasicValue; import ppt4j.Main; import ppt4j.annotation.Property; import ppt4j.database.Vulnerability; import ppt4j.database.VulnerabilityInfo; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Set;
3,797
System.exit(1); } matched = command; } } if(matched == null) { System.err.println("Unknown command: " + prefix); System.exit(1); } return matched; } public static byte[] toBytes(List<String> lines) { return String.join("\n", lines).getBytes(); } @SuppressWarnings("HttpUrlsUsage") public static URL toURL(String path) { try { if(path.startsWith("http://") || path.startsWith("https://")) { return new URL(path); } else { return new File(path).toURI().toURL(); } } catch (MalformedURLException e) { throw new IllegalStateException(e); } } public static String extractClassName(String filePath, String topLevelPrefix) { if(topLevelPrefix.endsWith("/")) { topLevelPrefix = topLevelPrefix.substring(0, topLevelPrefix.length() - 1); } String className = filePath.substring( topLevelPrefix.length() + 1, filePath.length() - 5 ); return className.replace("/", "."); } public static String buildMethodSignature(MethodInsnNode minsn, BasicValue[] args) { String returnType = minsn.desc.split("\\)")[1]; StringBuilder argTypes = new StringBuilder(); for(BasicValue arg : args) { argTypes.append(arg.getType().getDescriptor()); } return "(" + argTypes + ")" + returnType; } public static String substringBetween(String str, char c1, char c2) { int start = str.indexOf(c1); int end = str.lastIndexOf(c2); if(start == -1 || end == -1) { return null; } return str.substring(start + 1, end); } public static String toWrapperType(String type) { return switch (type) { case "boolean" -> "java/lang/Boolean"; case "byte" -> "java/lang/Byte"; case "char" -> "java/lang/Character"; case "short" -> "java/lang/Short"; case "int" -> "java/lang/Integer"; case "long" -> "java/lang/Long"; case "float" -> "java/lang/Float"; case "double" -> "java/lang/Double"; default -> type; }; } public static String resolvePath(String path) { // if the path begins with ~, replace it with the home directory if(path.startsWith("~")) { path = USER_HOME + path.substring(1); } return path; } public static String[] splitArgDesc(String desc) { String argDescs = substringBetween(desc, '(', ')'); if(argDescs == null || argDescs.isEmpty()) { return new String[0]; } List<String> args = new ArrayList<>(); for(int i = 0; i < argDescs.length(); i++) { char c = argDescs.charAt(i); if(c == 'L') { int end = argDescs.indexOf(';', i); args.add(argDescs.substring(i, end + 1)); i = end; } else if(c == '[') { int end = i; while(argDescs.charAt(end) == '[') { end++; } if(argDescs.charAt(end) == 'L') { end = argDescs.indexOf(';', end); } args.add(argDescs.substring(i, end + 1)); i = end; } else { args.add(String.valueOf(c)); } } return args.toArray(String[]::new); } public static String joinArgDesc(List<String> descList) { StringBuilder sb = new StringBuilder(); sb.append("("); for(String desc : descList) { sb.append(desc); } sb.append(")"); return sb.toString(); }
package ppt4j.util; public class StringUtils { @Property("user.home") private static String USER_HOME; @Property("ppt4j.database.root") private static String DB_ROOT; @Property("ppt4j.database.prepatch.name") private static String PREPATCH_NAME; @Property("ppt4j.database.postpatch.name") private static String POSTPATCH_NAME; @Property("ppt4j.classpath") private static String CLASSPATH; public static String printSet(Set<?> set) { return printSet(set, false, false); } public static String printSet(Set<?> set, boolean emphasizeString, boolean printType) { if(set.isEmpty()) { return "[]"; } StringBuilder sb = new StringBuilder(); sb.append("[ "); Object[] arr = set.toArray(); for (int i = 0; i < set.size(); i++) { Object s = arr[i]; if(emphasizeString && s instanceof String) { sb.append(String.format("\"%s\"", s)); } else { sb.append(String.format("%s", s)); } if(printType) { sb.append(String.format(":%s", s.getClass().getSimpleName())); } if(i != set.size() - 1) { sb.append(", "); } } sb.append(" ]"); return sb.toString(); } public static String convertToDescriptor(String type) { type = type.replaceAll("<.*>", ""); type = type.trim().replace(".", "/"); return switch (type) { case "" -> ""; case "<unknown>", "void" -> "V"; case "boolean" -> "Z"; case "byte" -> "B"; case "char" -> "C"; case "short" -> "S"; case "int" -> "I"; case "long" -> "J"; case "float" -> "F"; case "double" -> "D"; default -> { if(type.endsWith("[]")) { String baseType = type.substring(0, type.length() - 2); yield String.format("[%s", convertToDescriptor(baseType)); } else { yield String.format("L%s;", type); } } }; } public static boolean isPrimitive(String type) { if(type.startsWith("java.lang.")) { type = type.substring("java.lang.".length()); } return switch (type) { case "Boolean", "Byte", "Character", "Short", "Integer", "Long", "Float", "Double", "boolean", "byte", "char", "short", "int", "long", "float", "double", "Z", "B", "C", "S", "I", "J", "F", "D" -> true; default -> false; }; } public static String convertMethodSignature( String nameAndArgs, String returnType) { String name = nameAndArgs.substring(0, nameAndArgs.indexOf("(")); String[] args = nameAndArgs.substring( nameAndArgs.indexOf("(") + 1, nameAndArgs.indexOf(")") ).split(","); StringBuilder sb = new StringBuilder(); sb.append(name); sb.append(":("); for (String arg : args) { sb.append(convertToDescriptor(arg)); } sb.append(")"); sb.append(convertToDescriptor(returnType)); return sb.toString(); } public static String convertQualifiedName(String name, String className) { return convertQualifiedName(name, className, true); } public static String convertQualifiedName(String name, String className, boolean retainClassName) { String _className = name.split("#")[0]; if((_className.equals(className) || isPrimitive(_className)) && !retainClassName) { return name.split("#")[1]; } else { return _className.replace(".", "/") + "." + name.split("#")[1]; } } public static boolean isJavaComment(String line) { String trimmed = line.trim(); return trimmed.matches("//.*") || trimmed.matches("/\\*.*\\*/"); } public static boolean isJavaCode(String line) { if(isJavaComment(line)) { return false; } String trimmed = line.trim(); if(trimmed.isEmpty()) { return false; } String[] patterns = { "\\{", "\\}", "\\};", "else", "\\}\\s*else\\s*\\{", "else\\s*\\{", "\\}\\s*else", }; for (String pattern : patterns) { if(trimmed.matches(pattern)) { return false; } } return true; } public static String trimJavaCodeLine(String codeLine) { codeLine = codeLine.replaceAll("//.*", ""); codeLine = codeLine.replaceAll("/\\*.*\\*/", ""); codeLine = codeLine.replaceAll("\\s+$", ""); codeLine = codeLine.replaceAll("^\\s+", ""); if (codeLine.endsWith("{")) { codeLine = codeLine.substring(0, codeLine.length() - 1); } return codeLine.trim(); } public static @NonNull Main.Command matchPrefix(String prefix) { Main.Command matched = null; for (Main.Command command : Main.Command.values()) { if(command.name.startsWith(prefix.toLowerCase())) { if(matched != null) { System.err.println("Ambiguous command: " + prefix); System.err.println("Possible commands:"); for (Main.Command c : Main.Command.values()) { if(c.name.startsWith(prefix)) { System.err.println(c.name); } } System.exit(1); } matched = command; } } if(matched == null) { System.err.println("Unknown command: " + prefix); System.exit(1); } return matched; } public static byte[] toBytes(List<String> lines) { return String.join("\n", lines).getBytes(); } @SuppressWarnings("HttpUrlsUsage") public static URL toURL(String path) { try { if(path.startsWith("http://") || path.startsWith("https://")) { return new URL(path); } else { return new File(path).toURI().toURL(); } } catch (MalformedURLException e) { throw new IllegalStateException(e); } } public static String extractClassName(String filePath, String topLevelPrefix) { if(topLevelPrefix.endsWith("/")) { topLevelPrefix = topLevelPrefix.substring(0, topLevelPrefix.length() - 1); } String className = filePath.substring( topLevelPrefix.length() + 1, filePath.length() - 5 ); return className.replace("/", "."); } public static String buildMethodSignature(MethodInsnNode minsn, BasicValue[] args) { String returnType = minsn.desc.split("\\)")[1]; StringBuilder argTypes = new StringBuilder(); for(BasicValue arg : args) { argTypes.append(arg.getType().getDescriptor()); } return "(" + argTypes + ")" + returnType; } public static String substringBetween(String str, char c1, char c2) { int start = str.indexOf(c1); int end = str.lastIndexOf(c2); if(start == -1 || end == -1) { return null; } return str.substring(start + 1, end); } public static String toWrapperType(String type) { return switch (type) { case "boolean" -> "java/lang/Boolean"; case "byte" -> "java/lang/Byte"; case "char" -> "java/lang/Character"; case "short" -> "java/lang/Short"; case "int" -> "java/lang/Integer"; case "long" -> "java/lang/Long"; case "float" -> "java/lang/Float"; case "double" -> "java/lang/Double"; default -> type; }; } public static String resolvePath(String path) { // if the path begins with ~, replace it with the home directory if(path.startsWith("~")) { path = USER_HOME + path.substring(1); } return path; } public static String[] splitArgDesc(String desc) { String argDescs = substringBetween(desc, '(', ')'); if(argDescs == null || argDescs.isEmpty()) { return new String[0]; } List<String> args = new ArrayList<>(); for(int i = 0; i < argDescs.length(); i++) { char c = argDescs.charAt(i); if(c == 'L') { int end = argDescs.indexOf(';', i); args.add(argDescs.substring(i, end + 1)); i = end; } else if(c == '[') { int end = i; while(argDescs.charAt(end) == '[') { end++; } if(argDescs.charAt(end) == 'L') { end = argDescs.indexOf(';', end); } args.add(argDescs.substring(i, end + 1)); i = end; } else { args.add(String.valueOf(c)); } } return args.toArray(String[]::new); } public static String joinArgDesc(List<String> descList) { StringBuilder sb = new StringBuilder(); sb.append("("); for(String desc : descList) { sb.append(desc); } sb.append(")"); return sb.toString(); }
public static String getDatabasePrepatchSrcPath(Vulnerability vuln) {
1
2023-12-14 15:33:50+00:00
8k
MalithShehan/layered-architecture-Malith-Shehan
src/main/java/lk/ijse/layeredarchitecture/bo/custom/impl/PlaceOrderBOImpl.java
[ { "identifier": "PlaceOrderBO", "path": "src/main/java/lk/ijse/layeredarchitecture/bo/custom/PlaceOrderBO.java", "snippet": "public interface PlaceOrderBO extends SuperBO {\n boolean placeOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLExcept...
import com.example.layeredarchitecture.bo.custom.PlaceOrderBO; import com.example.layeredarchitecture.dao.DAOFactory; import com.example.layeredarchitecture.dao.custom.*; import com.example.layeredarchitecture.db.DBConnection; import com.example.layeredarchitecture.dto.CustomerDTO; import com.example.layeredarchitecture.dto.ItemDTO; import com.example.layeredarchitecture.dto.OrderDTO; import com.example.layeredarchitecture.dto.OrderDetailDTO; import com.example.layeredarchitecture.entity.Customer; import com.example.layeredarchitecture.entity.Item; import com.example.layeredarchitecture.entity.Order; import com.example.layeredarchitecture.entity.OrderDetails; import java.sql.Connection; import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List;
3,976
package com.example.layeredarchitecture.bo.custom.impl; public class PlaceOrderBOImpl implements PlaceOrderBO { CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.CUSTOMER); ItemDAO itemDAO = (ItemDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ITEM); QueryDAO queryDAO = (QueryDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.QUERY); OrderDAO orderDAO = (OrderDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER); OrderDetailsDAO orderDetailsDAO = (OrderDetailsDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER_DETAIL); @Override public CustomerDTO searchCustomer(String id) throws SQLException, ClassNotFoundException { Customer customer=customerDAO.search(id); CustomerDTO customerDTO=new CustomerDTO(customer.getId(),customer.getName(),customer.getAddress()); return customerDTO; } @Override public ItemDTO searchItem(String code) throws SQLException, ClassNotFoundException { Item item = itemDAO.search(code); ItemDTO itemDTO = new ItemDTO(item.getCode(), item.getDescription(), item.getUnitPrice(), item.getQtyOnHand()); return itemDTO; } @Override public boolean existItem(String code) throws SQLException, ClassNotFoundException { return itemDAO.exist(code); } @Override public boolean existCustomer(String id) throws SQLException, ClassNotFoundException { return customerDAO.exist(id); } @Override public String generateOrderID() throws SQLException, ClassNotFoundException { return orderDAO.generateID(); } @Override public ArrayList<CustomerDTO> getAllCustomer() throws SQLException, ClassNotFoundException { ArrayList<Customer> customers = customerDAO.getAll(); ArrayList<CustomerDTO> customerDTOS=new ArrayList<>(); for (Customer customer:customers) { customerDTOS.add(new CustomerDTO(customer.getId(),customer.getName(),customer.getAddress())); } return customerDTOS; } @Override public ArrayList<ItemDTO> getAllItems() throws SQLException, ClassNotFoundException { ArrayList<Item> items = itemDAO.getAll(); ArrayList<ItemDTO> itemDTOS =new ArrayList<>(); for (Item item : items) { itemDTOS.add(new ItemDTO(item.getCode(),item.getDescription(),item.getUnitPrice(), item.getQtyOnHand())); } return itemDTOS; } @Override
package com.example.layeredarchitecture.bo.custom.impl; public class PlaceOrderBOImpl implements PlaceOrderBO { CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.CUSTOMER); ItemDAO itemDAO = (ItemDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ITEM); QueryDAO queryDAO = (QueryDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.QUERY); OrderDAO orderDAO = (OrderDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER); OrderDetailsDAO orderDetailsDAO = (OrderDetailsDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER_DETAIL); @Override public CustomerDTO searchCustomer(String id) throws SQLException, ClassNotFoundException { Customer customer=customerDAO.search(id); CustomerDTO customerDTO=new CustomerDTO(customer.getId(),customer.getName(),customer.getAddress()); return customerDTO; } @Override public ItemDTO searchItem(String code) throws SQLException, ClassNotFoundException { Item item = itemDAO.search(code); ItemDTO itemDTO = new ItemDTO(item.getCode(), item.getDescription(), item.getUnitPrice(), item.getQtyOnHand()); return itemDTO; } @Override public boolean existItem(String code) throws SQLException, ClassNotFoundException { return itemDAO.exist(code); } @Override public boolean existCustomer(String id) throws SQLException, ClassNotFoundException { return customerDAO.exist(id); } @Override public String generateOrderID() throws SQLException, ClassNotFoundException { return orderDAO.generateID(); } @Override public ArrayList<CustomerDTO> getAllCustomer() throws SQLException, ClassNotFoundException { ArrayList<Customer> customers = customerDAO.getAll(); ArrayList<CustomerDTO> customerDTOS=new ArrayList<>(); for (Customer customer:customers) { customerDTOS.add(new CustomerDTO(customer.getId(),customer.getName(),customer.getAddress())); } return customerDTOS; } @Override public ArrayList<ItemDTO> getAllItems() throws SQLException, ClassNotFoundException { ArrayList<Item> items = itemDAO.getAll(); ArrayList<ItemDTO> itemDTOS =new ArrayList<>(); for (Item item : items) { itemDTOS.add(new ItemDTO(item.getCode(),item.getDescription(),item.getUnitPrice(), item.getQtyOnHand())); } return itemDTOS; } @Override
public boolean placeOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLException, ClassNotFoundException {
6
2023-12-16 04:19:09+00:00
8k
f1den/MrCrayfishGunMod
src/main/java/com/mrcrayfish/guns/client/handler/BulletTrailRenderingHandler.java
[ { "identifier": "BulletTrail", "path": "src/main/java/com/mrcrayfish/guns/client/BulletTrail.java", "snippet": "public class BulletTrail\n{\n private int entityId;\n private Vec3 position;\n private Vec3 motion;\n private float yaw;\n private float pitch;\n private boolean dead;\n p...
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.math.Matrix4f; import com.mojang.math.Vector3f; import com.mrcrayfish.guns.client.BulletTrail; import com.mrcrayfish.guns.client.GunRenderType; import com.mrcrayfish.guns.client.util.RenderUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.LevelRenderer; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.model.ItemTransforms; import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.core.BlockPos; import net.minecraft.world.entity.Entity; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.minecraftforge.client.event.ClientPlayerNetworkEvent; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import java.util.HashMap; import java.util.Map;
4,861
package com.mrcrayfish.guns.client.handler; /** * Author: MrCrayfish */ public class BulletTrailRenderingHandler { private static BulletTrailRenderingHandler instance; public static BulletTrailRenderingHandler get() { if(instance == null) { instance = new BulletTrailRenderingHandler(); } return instance; }
package com.mrcrayfish.guns.client.handler; /** * Author: MrCrayfish */ public class BulletTrailRenderingHandler { private static BulletTrailRenderingHandler instance; public static BulletTrailRenderingHandler get() { if(instance == null) { instance = new BulletTrailRenderingHandler(); } return instance; }
private Map<Integer, BulletTrail> bullets = new HashMap<>();
0
2023-12-18 15:04:35+00:00
8k
Qzimyion/BucketEm
src/main/java/com/qzimyion/bucketem/items/ModItems.java
[ { "identifier": "Bucketem", "path": "src/main/java/com/qzimyion/bucketem/Bucketem.java", "snippet": "public class Bucketem implements ModInitializer {\n\n\tpublic static final String MOD_ID = \"bucketem\";\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n\t@Override\n\tpublic v...
import com.qzimyion.bucketem.Bucketem; import com.qzimyion.bucketem.items.NewItems.Bottles.EntityBottle; import com.qzimyion.bucketem.items.NewItems.Bottles.MagmaCubeBottle; import com.qzimyion.bucketem.items.NewItems.Bottles.SlimeBottle; import com.qzimyion.bucketem.items.NewItems.EntityBook; import com.qzimyion.bucketem.items.NewItems.FrogBuckets.DryVariants.DryTemperateFrogBuckets; import com.qzimyion.bucketem.items.NewItems.FrogBuckets.DryVariants.DryTropicalFrogBuckets; import com.qzimyion.bucketem.items.NewItems.FrogBuckets.DryVariants.DryTundraFrogBuckets; import com.qzimyion.bucketem.items.NewItems.FrogBuckets.TemperateFrogBuckets; import com.qzimyion.bucketem.items.NewItems.FrogBuckets.TropicalFrogBuckets; import com.qzimyion.bucketem.items.NewItems.FrogBuckets.TundraFrogBuckets; import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.minecraft.entity.EntityType; import net.minecraft.fluid.Fluids; import net.minecraft.item.EntityBucketItem; import net.minecraft.item.Item; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.sound.SoundEvents; import net.minecraft.util.Identifier; import net.minecraft.util.Rarity; import static net.minecraft.item.Items.GLASS_BOTTLE;
5,085
package com.qzimyion.bucketem.items; public class ModItems { //Buckets public static final Item STRIDER_BUCKET = registerItem("strider_bucket", new EntityBucketItem(EntityType.STRIDER, Fluids.LAVA, SoundEvents.ITEM_BUCKET_EMPTY_LAVA, new FabricItemSettings().maxCount(1))); public static final Item SQUID_BUCKET = registerItem("squid_bucket", new EntityBucketItem(EntityType.SQUID, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1))); public static final Item GLOW_SQUID_BUCKET = registerItem("glow_squid_bucket", new EntityBucketItem(EntityType.GLOW_SQUID, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1))); public static final Item TEMPERATE_FROG_BUCKET = registerItem("temperate_frog_bucket", new TemperateFrogBuckets(Fluids.WATER ,new FabricItemSettings().maxCount(1))); public static final Item TROPICAL_FROG_BUCKET = registerItem("tropical_frog_bucket", new TropicalFrogBuckets(Fluids.WATER , new FabricItemSettings().maxCount(1))); public static final Item TUNDRA_FROG_BUCKET = registerItem("tundra_frog_bucket", new TundraFrogBuckets(Fluids.WATER ,new FabricItemSettings().maxCount(1))); public static final Item TURTLE_BUCKET = registerItem("turtle_bucket", new EntityBucketItem(EntityType.TURTLE, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1))); public static final Item DRY_TEMPERATE_FROG_BUCKET = registerItem("dry_temperate_frog_bucket", new DryTemperateFrogBuckets(new FabricItemSettings().maxCount(1))); public static final Item DRY_TROPICAL_FROG_BUCKET = registerItem("dry_tropical_frog_bucket", new DryTropicalFrogBuckets(new FabricItemSettings().maxCount(1))); public static final Item DRY_TUNDRA_FROG_BUCKET = registerItem("dry_tundra_frog_bucket", new DryTundraFrogBuckets(new FabricItemSettings().maxCount(1))); //Books public static final Item ALLAY_POSSESSED_BOOK = registerItem("allay_possessed_book", new EntityBook(EntityType.ALLAY ,new FabricItemSettings().maxCount(1).rarity(Rarity.UNCOMMON))); public static final Item VEX_POSSESSED_BOOK = registerItem("vex_possessed_book", new EntityBook(EntityType.VEX, new FabricItemSettings().maxCount(1).rarity(Rarity.UNCOMMON))); //Bottles
package com.qzimyion.bucketem.items; public class ModItems { //Buckets public static final Item STRIDER_BUCKET = registerItem("strider_bucket", new EntityBucketItem(EntityType.STRIDER, Fluids.LAVA, SoundEvents.ITEM_BUCKET_EMPTY_LAVA, new FabricItemSettings().maxCount(1))); public static final Item SQUID_BUCKET = registerItem("squid_bucket", new EntityBucketItem(EntityType.SQUID, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1))); public static final Item GLOW_SQUID_BUCKET = registerItem("glow_squid_bucket", new EntityBucketItem(EntityType.GLOW_SQUID, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1))); public static final Item TEMPERATE_FROG_BUCKET = registerItem("temperate_frog_bucket", new TemperateFrogBuckets(Fluids.WATER ,new FabricItemSettings().maxCount(1))); public static final Item TROPICAL_FROG_BUCKET = registerItem("tropical_frog_bucket", new TropicalFrogBuckets(Fluids.WATER , new FabricItemSettings().maxCount(1))); public static final Item TUNDRA_FROG_BUCKET = registerItem("tundra_frog_bucket", new TundraFrogBuckets(Fluids.WATER ,new FabricItemSettings().maxCount(1))); public static final Item TURTLE_BUCKET = registerItem("turtle_bucket", new EntityBucketItem(EntityType.TURTLE, Fluids.WATER, SoundEvents.ITEM_BUCKET_EMPTY_FISH, new FabricItemSettings().maxCount(1))); public static final Item DRY_TEMPERATE_FROG_BUCKET = registerItem("dry_temperate_frog_bucket", new DryTemperateFrogBuckets(new FabricItemSettings().maxCount(1))); public static final Item DRY_TROPICAL_FROG_BUCKET = registerItem("dry_tropical_frog_bucket", new DryTropicalFrogBuckets(new FabricItemSettings().maxCount(1))); public static final Item DRY_TUNDRA_FROG_BUCKET = registerItem("dry_tundra_frog_bucket", new DryTundraFrogBuckets(new FabricItemSettings().maxCount(1))); //Books public static final Item ALLAY_POSSESSED_BOOK = registerItem("allay_possessed_book", new EntityBook(EntityType.ALLAY ,new FabricItemSettings().maxCount(1).rarity(Rarity.UNCOMMON))); public static final Item VEX_POSSESSED_BOOK = registerItem("vex_possessed_book", new EntityBook(EntityType.VEX, new FabricItemSettings().maxCount(1).rarity(Rarity.UNCOMMON))); //Bottles
public static final Item BEE_BOTTLE = registerItem("bee_bottle", new EntityBottle(EntityType.BEE ,new FabricItemSettings().maxCount(1)));
1
2023-12-16 08:12:37+00:00
8k
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;
6,993
// 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(),
// 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),
7
2023-12-16 14:59:04+00:00
8k
lpyleo/disk-back-end
file-web/src/main/java/com/disk/file/controller/FileController.java
[ { "identifier": "RestResult", "path": "file-web/src/main/java/com/disk/file/common/RestResult.java", "snippet": "@Data\npublic class RestResult<T> {\n private Boolean success = true;\n private Integer code;\n private String message;\n private T data;\n\n // 自定义返回数据\n public RestResult ...
import java.util.*; import javax.annotation.Resource; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.disk.file.common.RestResult; import com.disk.file.dto.*; import com.disk.file.model.File; import com.disk.file.model.User; import com.disk.file.model.UserFile; import com.disk.file.service.FileService; import com.disk.file.service.UserService; import com.disk.file.service.UserfileService; import com.disk.file.util.DateUtil; import com.disk.file.vo.TreeNodeVO; import com.disk.file.vo.UserfileListVO; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j;
3,606
package com.disk.file.controller; @Tag(name = "file", description = "该接口为文件接口,主要用来做一些文件的基本操作,如创建目录,删除,移动,复制等。") @RestController @Slf4j @RequestMapping("/file") public class FileController { @Resource FileService fileService; @Resource UserService userService; @Resource UserfileService userfileService; public TreeNodeVO insertTreeNode(TreeNodeVO treeNode, String filePath, Queue<String> nodeNameQueue) { List<TreeNodeVO> childrenTreeNodes = treeNode.getChildren(); String currentNodeName = nodeNameQueue.peek(); if (currentNodeName == null) { return treeNode; } Map<String, String> map = new HashMap<>(); filePath = filePath + currentNodeName + "/"; map.put("filePath", filePath); if (!isExistPath(childrenTreeNodes, currentNodeName)) { //1、判断有没有该子节点,如果没有则插入 //插入 TreeNodeVO resultTreeNode = new TreeNodeVO(); resultTreeNode.setAttributes(map); resultTreeNode.setLabel(nodeNameQueue.poll()); // resultTreeNode.setId(treeid++); childrenTreeNodes.add(resultTreeNode); } else { //2、如果有,则跳过 nodeNameQueue.poll(); } if (nodeNameQueue.size() != 0) { for (int i = 0; i < childrenTreeNodes.size(); i++) { TreeNodeVO childrenTreeNode = childrenTreeNodes.get(i); if (currentNodeName.equals(childrenTreeNode.getLabel())) { childrenTreeNode = insertTreeNode(childrenTreeNode, filePath, nodeNameQueue); childrenTreeNodes.remove(i); childrenTreeNodes.add(childrenTreeNode); treeNode.setChildren(childrenTreeNodes); } } } else { treeNode.setChildren(childrenTreeNodes); } return treeNode; } public boolean isExistPath(List<TreeNodeVO> childrenTreeNodes, String path) { boolean isExistPath = false; try { for (int i = 0; i < childrenTreeNodes.size(); i++) { if (path.equals(childrenTreeNodes.get(i).getLabel())) { isExistPath = true; } } } catch (Exception e) { e.printStackTrace(); } return isExistPath; } @Operation(summary = "创建文件", description = "目录(文件夹)的创建", tags = {"file"}) @PostMapping(value = "/createfile") @ResponseBody public RestResult<String> createFile(@RequestBody CreateFileDTO createFileDto, @RequestHeader("token") String token) { User sessionUser = userService.getUserByToken(token); if (sessionUser == null) { RestResult.fail().message("token认证失败"); } LambdaQueryWrapper<UserFile> lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.eq(UserFile::getFileName, "").eq(UserFile::getFilePath, "").eq(UserFile::getUserId, 0); List<UserFile> userfiles = userfileService.list(lambdaQueryWrapper); if (!userfiles.isEmpty()) { RestResult.fail().message("同目录下文件名重复"); } UserFile userFile = new UserFile(); userFile.setUserId(sessionUser.getUserId()); userFile.setFileName(createFileDto.getFileName()); userFile.setFilePath(createFileDto.getFilePath()); userFile.setIsDir(1); userFile.setUploadTime(DateUtil.getCurrentTime()); userFile.setDeleteFlag(0); userfileService.save(userFile); return RestResult.success(); } @Operation(summary = "获取文件列表", description = "用来做前台文件列表展示", tags = {"file"}) @GetMapping(value = "/getfilelist") @ResponseBody
package com.disk.file.controller; @Tag(name = "file", description = "该接口为文件接口,主要用来做一些文件的基本操作,如创建目录,删除,移动,复制等。") @RestController @Slf4j @RequestMapping("/file") public class FileController { @Resource FileService fileService; @Resource UserService userService; @Resource UserfileService userfileService; public TreeNodeVO insertTreeNode(TreeNodeVO treeNode, String filePath, Queue<String> nodeNameQueue) { List<TreeNodeVO> childrenTreeNodes = treeNode.getChildren(); String currentNodeName = nodeNameQueue.peek(); if (currentNodeName == null) { return treeNode; } Map<String, String> map = new HashMap<>(); filePath = filePath + currentNodeName + "/"; map.put("filePath", filePath); if (!isExistPath(childrenTreeNodes, currentNodeName)) { //1、判断有没有该子节点,如果没有则插入 //插入 TreeNodeVO resultTreeNode = new TreeNodeVO(); resultTreeNode.setAttributes(map); resultTreeNode.setLabel(nodeNameQueue.poll()); // resultTreeNode.setId(treeid++); childrenTreeNodes.add(resultTreeNode); } else { //2、如果有,则跳过 nodeNameQueue.poll(); } if (nodeNameQueue.size() != 0) { for (int i = 0; i < childrenTreeNodes.size(); i++) { TreeNodeVO childrenTreeNode = childrenTreeNodes.get(i); if (currentNodeName.equals(childrenTreeNode.getLabel())) { childrenTreeNode = insertTreeNode(childrenTreeNode, filePath, nodeNameQueue); childrenTreeNodes.remove(i); childrenTreeNodes.add(childrenTreeNode); treeNode.setChildren(childrenTreeNodes); } } } else { treeNode.setChildren(childrenTreeNodes); } return treeNode; } public boolean isExistPath(List<TreeNodeVO> childrenTreeNodes, String path) { boolean isExistPath = false; try { for (int i = 0; i < childrenTreeNodes.size(); i++) { if (path.equals(childrenTreeNodes.get(i).getLabel())) { isExistPath = true; } } } catch (Exception e) { e.printStackTrace(); } return isExistPath; } @Operation(summary = "创建文件", description = "目录(文件夹)的创建", tags = {"file"}) @PostMapping(value = "/createfile") @ResponseBody public RestResult<String> createFile(@RequestBody CreateFileDTO createFileDto, @RequestHeader("token") String token) { User sessionUser = userService.getUserByToken(token); if (sessionUser == null) { RestResult.fail().message("token认证失败"); } LambdaQueryWrapper<UserFile> lambdaQueryWrapper = new LambdaQueryWrapper<>(); lambdaQueryWrapper.eq(UserFile::getFileName, "").eq(UserFile::getFilePath, "").eq(UserFile::getUserId, 0); List<UserFile> userfiles = userfileService.list(lambdaQueryWrapper); if (!userfiles.isEmpty()) { RestResult.fail().message("同目录下文件名重复"); } UserFile userFile = new UserFile(); userFile.setUserId(sessionUser.getUserId()); userFile.setFileName(createFileDto.getFileName()); userFile.setFilePath(createFileDto.getFilePath()); userFile.setIsDir(1); userFile.setUploadTime(DateUtil.getCurrentTime()); userFile.setDeleteFlag(0); userfileService.save(userFile); return RestResult.success(); } @Operation(summary = "获取文件列表", description = "用来做前台文件列表展示", tags = {"file"}) @GetMapping(value = "/getfilelist") @ResponseBody
public RestResult<UserfileListVO> getUserfileList(UserfileListDTO userfileListDto,
9
2023-12-17 05:12:43+00:00
8k
civso/Live2DViewerEXModelDownload
src/main/java/org/Live2DViewerEX/ModelDownload/ListSelector.java
[ { "identifier": "FormatteName", "path": "src/main/java/org/Live2DViewerEX/ModelDownload/LpxFileName/FormatteName.java", "snippet": "public class FormatteName {\r\n\r\n FileUtils Utils;\r\n ArrayList<Live2dModeConfig> LpxConfigrList = new ArrayList<>();\r\n\r\n public String Main(JSONObject conf...
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.Live2DViewerEX.ModelDownload.LpxFileName.FormatteName; import org.Live2DViewerEX.ModelDownload.utils.LpxDecrypt; import org.Live2DViewerEX.ModelDownload.utils.LpxHttpInterface; import org.Live2DViewerEX.ModelDownload.utils.ModelInfoPrinter; import java.util.Scanner;
5,743
return; } if (option.length() < 8 || !option.startsWith("list -p")){ System.out.println("未知命令行选项"); return; } option = option.replaceAll("[^\\d]", ""); if (option.equals("")){ System.out.println("页数输入错误"); return; } if (option.length() > 8) { option = option.substring(0, 8); } postData.put("page",Integer.parseInt(option)); postData.put("search_text",""); showModelList(); } public void inputSearch(String option){ option = option.substring(7); if (option.equals("")){ System.out.println("请输入模型名称"); return; } postData.put("search_text",option); postData.put("page",1); showModelList(); } //------- public void showModelList(){ ModelInfoPrinter mp = new ModelInfoPrinter(); JSONArray json = mp.printModelList(postData); while(true){ String option = getUserInput(); if (option.matches("\\d+")){ int inputId = Integer.parseInt(option); if (inputId < 1 || inputId > json.size()){ System.out.println("输入值错误"); continue; } showModelDetails(json.getJSONObject(inputId-1)); json = mp.printModelList(postData); continue; } //--------- if (option.equals("n") || option.equals("next")){ postData.put("page", postData.getIntValue("page")+1); json = mp.printModelList(postData); continue; } if (option.equals("p") || option.equals("prev")){ if (postData.getIntValue("page") <=1){ System.out.println("已到第一页"); continue; } postData.put("page", postData.getIntValue("page")-1); json = mp.printModelList(postData); continue; } if (option.equals("e") || option.equals("exit")){ System.out.println("\n"); break; } if (option.equals("download all")){ for (int i = 0; i < json.size(); i++){ JSONObject thisjson = json.getJSONObject(i); DownloadModel(thisjson); } continue; } if (!option.equals("")){ System.out.println("未知命令"); System.out.println(" 当前第"+postData.getIntValue("page")+"页 [int]-输入序号选择项目 n/next-下一页 p/prev-上一页 e/exit-退出选择"); } } } private void showModelDetails(JSONObject thisjson){ ModelInfoPrinter mp = new ModelInfoPrinter(); mp.printModelDetails(thisjson); while(true) { String option = getUserInput(); if (option.equals("d") ||option.equals("download")){ DownloadModel(thisjson); System.out.println(" d/download-下载 previewurl-查看封面链接 e/exit-退出选择"); continue; } if (option.equals("previewurl")){ System.out.println(thisjson.getString("preview_url")); continue; } if (option.equals("e") ||option.equals("exit")){ System.out.println("---------------------"); break; } if (!option.equals("")){ System.out.println("未知命令"); } } } private void DownloadModel(JSONObject thisjson){ LpxHttpInterface lpxHttp = new LpxHttpInterface(); String Link = lpxHttp.getDownloadLink(thisjson.getString("publishedfileid"),thisjson.getString("hcontent_file")); if (Link == null){ System.err.println("无法获取下载链接"); return; } System.out.println("下载链接: " + Link); String lpkpath = lpxHttp.DownloadFile(Link,thisjson.getString("title")); if (lpkpath == null){ System.err.println("文件下载失败"); return; } System.out.println("文件下载完成,准备解密..."); LpxDecrypt lpxDecrypt = new LpxDecrypt(); JSONObject json = lpxDecrypt.decrypt(lpkpath); if (json == null){ System.err.println("文件解密失败"); return; } System.out.println("文件解密完成,准备整理文件内容..");
package org.Live2DViewerEX.ModelDownload; public class ListSelector { JSONObject postData; //获取请求体json public ListSelector(){ LpxHttpInterface lpxHttp = new LpxHttpInterface(); postData = lpxHttp.Getjson(); if(postData == null){ System.err.println("无法获取请求json,请检查网络连接"); Scanner scan = new Scanner(System.in); scan.nextLine(); System.exit(0); } } public void inputList(String option){ if (option.equals("list")){ postData.put("page",1); postData.put("search_text",""); showModelList(); return; } if (option.length() < 8 || !option.startsWith("list -p")){ System.out.println("未知命令行选项"); return; } option = option.replaceAll("[^\\d]", ""); if (option.equals("")){ System.out.println("页数输入错误"); return; } if (option.length() > 8) { option = option.substring(0, 8); } postData.put("page",Integer.parseInt(option)); postData.put("search_text",""); showModelList(); } public void inputSearch(String option){ option = option.substring(7); if (option.equals("")){ System.out.println("请输入模型名称"); return; } postData.put("search_text",option); postData.put("page",1); showModelList(); } //------- public void showModelList(){ ModelInfoPrinter mp = new ModelInfoPrinter(); JSONArray json = mp.printModelList(postData); while(true){ String option = getUserInput(); if (option.matches("\\d+")){ int inputId = Integer.parseInt(option); if (inputId < 1 || inputId > json.size()){ System.out.println("输入值错误"); continue; } showModelDetails(json.getJSONObject(inputId-1)); json = mp.printModelList(postData); continue; } //--------- if (option.equals("n") || option.equals("next")){ postData.put("page", postData.getIntValue("page")+1); json = mp.printModelList(postData); continue; } if (option.equals("p") || option.equals("prev")){ if (postData.getIntValue("page") <=1){ System.out.println("已到第一页"); continue; } postData.put("page", postData.getIntValue("page")-1); json = mp.printModelList(postData); continue; } if (option.equals("e") || option.equals("exit")){ System.out.println("\n"); break; } if (option.equals("download all")){ for (int i = 0; i < json.size(); i++){ JSONObject thisjson = json.getJSONObject(i); DownloadModel(thisjson); } continue; } if (!option.equals("")){ System.out.println("未知命令"); System.out.println(" 当前第"+postData.getIntValue("page")+"页 [int]-输入序号选择项目 n/next-下一页 p/prev-上一页 e/exit-退出选择"); } } } private void showModelDetails(JSONObject thisjson){ ModelInfoPrinter mp = new ModelInfoPrinter(); mp.printModelDetails(thisjson); while(true) { String option = getUserInput(); if (option.equals("d") ||option.equals("download")){ DownloadModel(thisjson); System.out.println(" d/download-下载 previewurl-查看封面链接 e/exit-退出选择"); continue; } if (option.equals("previewurl")){ System.out.println(thisjson.getString("preview_url")); continue; } if (option.equals("e") ||option.equals("exit")){ System.out.println("---------------------"); break; } if (!option.equals("")){ System.out.println("未知命令"); } } } private void DownloadModel(JSONObject thisjson){ LpxHttpInterface lpxHttp = new LpxHttpInterface(); String Link = lpxHttp.getDownloadLink(thisjson.getString("publishedfileid"),thisjson.getString("hcontent_file")); if (Link == null){ System.err.println("无法获取下载链接"); return; } System.out.println("下载链接: " + Link); String lpkpath = lpxHttp.DownloadFile(Link,thisjson.getString("title")); if (lpkpath == null){ System.err.println("文件下载失败"); return; } System.out.println("文件下载完成,准备解密..."); LpxDecrypt lpxDecrypt = new LpxDecrypt(); JSONObject json = lpxDecrypt.decrypt(lpkpath); if (json == null){ System.err.println("文件解密失败"); return; } System.out.println("文件解密完成,准备整理文件内容..");
FormatteName formatteName = new FormatteName();
0
2023-12-16 14:51:01+00:00
8k
ReChronoRain/HyperCeiler
app/src/main/java/com/sevtinge/hyperceiler/ui/fragment/VariousFragment.java
[ { "identifier": "SettingsPreferenceFragment", "path": "app/src/main/java/com/sevtinge/hyperceiler/ui/fragment/base/SettingsPreferenceFragment.java", "snippet": "public abstract class SettingsPreferenceFragment extends BasePreferenceFragment {\n\n public String mTitle;\n public String mPreferenceKe...
import static com.sevtinge.hyperceiler.utils.api.VoyagerApisKt.isPad; import android.os.Handler; import androidx.annotation.NonNull; import com.sevtinge.hyperceiler.R; import com.sevtinge.hyperceiler.ui.fragment.base.SettingsPreferenceFragment; import com.sevtinge.hyperceiler.utils.PrefsUtils; import com.sevtinge.hyperceiler.utils.ShellUtils; import moralnorm.preference.DropDownPreference; import moralnorm.preference.Preference; import moralnorm.preference.PreferenceCategory; import moralnorm.preference.SwitchPreference;
4,390
package com.sevtinge.hyperceiler.ui.fragment; public class VariousFragment extends SettingsPreferenceFragment implements Preference.OnPreferenceChangeListener { DropDownPreference mSuperModePreference; PreferenceCategory mDefault; SwitchPreference mClipboard; Preference mMipad; // 平板相关功能 Handler handler; @Override public int getContentResId() { return R.xml.various; } @Override public void initPrefs() { int mode = Integer.parseInt(PrefsUtils.getSharedStringPrefs(getContext(), "prefs_key_various_super_clipboard_e", "0")); mSuperModePreference = findPreference("prefs_key_various_super_clipboard_e"); mDefault = findPreference("prefs_key_various_super_clipboard_key"); mMipad = findPreference("prefs_key_various_mipad"); mClipboard = findPreference("prefs_key_sogou_xiaomi_clipboard"); mMipad.setVisible(isPad()); handler = new Handler(); mClipboard.setOnPreferenceChangeListener((preference, o) -> { initKill(); return true; }); setSuperMode(mode); mSuperModePreference.setOnPreferenceChangeListener(this); } private void initKill() { new Thread(() -> handler.post(() ->
package com.sevtinge.hyperceiler.ui.fragment; public class VariousFragment extends SettingsPreferenceFragment implements Preference.OnPreferenceChangeListener { DropDownPreference mSuperModePreference; PreferenceCategory mDefault; SwitchPreference mClipboard; Preference mMipad; // 平板相关功能 Handler handler; @Override public int getContentResId() { return R.xml.various; } @Override public void initPrefs() { int mode = Integer.parseInt(PrefsUtils.getSharedStringPrefs(getContext(), "prefs_key_various_super_clipboard_e", "0")); mSuperModePreference = findPreference("prefs_key_various_super_clipboard_e"); mDefault = findPreference("prefs_key_various_super_clipboard_key"); mMipad = findPreference("prefs_key_various_mipad"); mClipboard = findPreference("prefs_key_sogou_xiaomi_clipboard"); mMipad.setVisible(isPad()); handler = new Handler(); mClipboard.setOnPreferenceChangeListener((preference, o) -> { initKill(); return true; }); setSuperMode(mode); mSuperModePreference.setOnPreferenceChangeListener(this); } private void initKill() { new Thread(() -> handler.post(() ->
ShellUtils.execCommand("killall -s 9 com.sohu.inputmethod.sogou.xiaomi ;" +
2
2023-10-27 17:17:42+00:00
8k
thebatmanfuture/fofa_search
src/main/java/org/fofaviewer/controllers/SaveOptionsController.java
[ { "identifier": "SaveOptionCallback", "path": "src/main/java/org/fofaviewer/callback/SaveOptionCallback.java", "snippet": "public interface SaveOptionCallback{\n default void setProjectName(String name){}\n default String getProjectName(){\n return null;\n }\n}" }, { "identifier"...
import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.scene.text.Font; import javafx.stage.DirectoryChooser; import org.fofaviewer.callback.SaveOptionCallback; import org.fofaviewer.controls.CloseableTabPane; import org.fofaviewer.utils.DataUtil; import org.fofaviewer.utils.ResourceBundleUtil; import org.fofaviewer.utils.SQLiteUtils; import org.tinylog.Logger; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*;
5,745
package org.fofaviewer.controllers; public class SaveOptionsController { private ArrayList<CheckBox> boxes; private boolean isProject; private ResourceBundle bundle; private Map<String, String> ruleMap; @FXML private VBox window; @FXML private VBox vbox; @FXML private Label title; @FXML private Button selectAll; @FXML private Button unselect; @FXML private VBox project; @FXML private Label label_project_name; @FXML private TextField project_name; @FXML private GridPane rule; @FXML private Label labelRuleName; @FXML private Label labelRuleDescription; @FXML private TextField ruleName; @FXML private TextField ruleDescription; @FXML private void initialize(){
package org.fofaviewer.controllers; public class SaveOptionsController { private ArrayList<CheckBox> boxes; private boolean isProject; private ResourceBundle bundle; private Map<String, String> ruleMap; @FXML private VBox window; @FXML private VBox vbox; @FXML private Label title; @FXML private Button selectAll; @FXML private Button unselect; @FXML private VBox project; @FXML private Label label_project_name; @FXML private TextField project_name; @FXML private GridPane rule; @FXML private Label labelRuleName; @FXML private Label labelRuleDescription; @FXML private TextField ruleName; @FXML private TextField ruleDescription; @FXML private void initialize(){
bundle = ResourceBundleUtil.getResource();
3
2023-10-25 11:13:47+00:00
8k
qguangyao/MySound
src/main/java/com/jvspiano/sound/file/MyStringDistributerIMPL.java
[ { "identifier": "InstrumentEnum", "path": "src/main/java/com/jvspiano/sound/note/InstrumentEnum.java", "snippet": "public enum InstrumentEnum {\n\n ACOUSTIC_GRAND_PIANO(0,\"大钢琴\"),\n ELECTRIC_GRAND_PIANO(2,\"电钢琴\"),\n VIOLIN(40,\"小提琴\"),\n ;\n\n public final int value;\n public final S...
import com.jvspiano.sound.note.InstrumentEnum; import com.jvspiano.sound.note.MyNoteIMPL; import com.jvspiano.sound.note.NoteInfo; import com.jvspiano.sound.resolver.AppoggiaturaResolverIMPL; import com.jvspiano.sound.resolver.SingleNoteResolver; import com.jvspiano.sound.resolver.SingleNoteResolverIMPL; import javax.sound.midi.*; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Collections; import java.util.Comparator; import java.util.concurrent.CopyOnWriteArrayList;
4,955
package com.jvspiano.sound.file; /** * 行解析分发器 */ public class MyStringDistributerIMPL implements MyStringDistributer { private MyNoteIMPL myNoteIMPL = new MyNoteIMPL(); private Sequence sequence; private Track track;
package com.jvspiano.sound.file; /** * 行解析分发器 */ public class MyStringDistributerIMPL implements MyStringDistributer { private MyNoteIMPL myNoteIMPL = new MyNoteIMPL(); private Sequence sequence; private Track track;
private SingleNoteResolver singleNoteResolver = new SingleNoteResolverIMPL();
4
2023-10-27 11:07:06+00:00
8k
rweisleder/archunit-spring
src/test/java/de/rweisleder/archunit/spring/SpringComponentRulesTest.java
[ { "identifier": "ControllerWithDependencyToConfiguration", "path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java", "snippet": "@Controller\npublic static class ControllerWithDependencyToConfiguration {\n @SuppressWarnings(\"unused\")\n public ControllerWi...
import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.lang.EvaluationResult; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToConfiguration; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToController; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToService; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToSpringDataRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithoutDependency; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToConfiguration; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToController; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToService; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToSpringDataRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithoutDependency; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToConfiguration; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToController; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToService; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToSpringDataRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithoutDependency; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToConfiguration; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToController; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToService; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToSpringDataRepository; import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithoutDependency; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import static de.rweisleder.archunit.spring.TestUtils.importClasses; import static org.assertj.core.api.Assertions.assertThat;
3,703
void controller_with_dependency_to_Spring_Data_repository_is_not_a_violation() { JavaClasses classes = importClasses(ControllerWithDependencyToSpringDataRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void controller_with_dependency_to_configuration_is_a_violation() { JavaClasses classes = importClasses(ControllerWithDependencyToConfiguration.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(ControllerWithDependencyToConfiguration.class.getName()); }); } } @Nested class Rule_DependenciesOfServices { @Test void provides_a_description() { String description = SpringComponentRules.DependenciesOfServices.getDescription(); assertThat(description).isEqualTo("Spring services should only depend on other Spring components that are services or repositories"); } @Test void service_without_dependency_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithoutDependency.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_controller_is_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToController.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(ServiceWithDependencyToController.class.getName()); }); } @Test void service_with_dependency_to_other_service_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToService.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_repository_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_Spring_Data_repository_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToSpringDataRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_configuration_is_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToConfiguration.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(ServiceWithDependencyToConfiguration.class.getName()); }); } } @Nested class Rule_DependenciesOfRepositories { @Test void provides_a_description() { String description = SpringComponentRules.DependenciesOfRepositories.getDescription(); assertThat(description).isEqualTo("Spring repositories should only depend on other Spring components that are repositories"); } @Test void repository_without_dependency_is_not_a_violation() { JavaClasses classes = importClasses(RepositoryWithoutDependency.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void repository_with_dependency_to_controller_is_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToController.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(RepositoryWithDependencyToController.class.getName()); }); } @Test void repository_with_dependency_to_service_is_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToService.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(RepositoryWithDependencyToService.class.getName()); }); } @Test void repository_with_dependency_to_other_repository_is_not_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void repository_with_dependency_to_Spring_Data_repository_is_not_a_violation() {
/* * #%L * ArchUnit Spring Integration * %% * Copyright (C) 2023 Roland Weisleder * %% * 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. * #L% */ package de.rweisleder.archunit.spring; @SuppressWarnings("CodeBlock2Expr") class SpringComponentRulesTest { @Nested class Rule_DependenciesOfControllers { @Test void provides_a_description() { String description = SpringComponentRules.DependenciesOfControllers.getDescription(); assertThat(description).isEqualTo("Spring controller should only depend on other Spring components that are services or repositories"); } @Test void controller_without_dependency_is_not_a_violation() { JavaClasses classes = importClasses(ControllerWithoutDependency.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void controller_with_dependency_to_other_controller_is_a_violation() { JavaClasses classes = importClasses(ControllerWithDependencyToController.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(ControllerWithDependencyToController.class.getName()); }); } @Test void controller_with_dependency_to_service_is_not_a_violation() { JavaClasses classes = importClasses(ControllerWithDependencyToService.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void controller_with_dependency_to_repository_is_not_a_violation() { JavaClasses classes = importClasses(ControllerWithDependencyToRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void controller_with_dependency_to_Spring_Data_repository_is_not_a_violation() { JavaClasses classes = importClasses(ControllerWithDependencyToSpringDataRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void controller_with_dependency_to_configuration_is_a_violation() { JavaClasses classes = importClasses(ControllerWithDependencyToConfiguration.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(ControllerWithDependencyToConfiguration.class.getName()); }); } } @Nested class Rule_DependenciesOfServices { @Test void provides_a_description() { String description = SpringComponentRules.DependenciesOfServices.getDescription(); assertThat(description).isEqualTo("Spring services should only depend on other Spring components that are services or repositories"); } @Test void service_without_dependency_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithoutDependency.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_controller_is_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToController.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(ServiceWithDependencyToController.class.getName()); }); } @Test void service_with_dependency_to_other_service_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToService.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_repository_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_Spring_Data_repository_is_not_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToSpringDataRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void service_with_dependency_to_configuration_is_a_violation() { JavaClasses classes = importClasses(ServiceWithDependencyToConfiguration.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(ServiceWithDependencyToConfiguration.class.getName()); }); } } @Nested class Rule_DependenciesOfRepositories { @Test void provides_a_description() { String description = SpringComponentRules.DependenciesOfRepositories.getDescription(); assertThat(description).isEqualTo("Spring repositories should only depend on other Spring components that are repositories"); } @Test void repository_without_dependency_is_not_a_violation() { JavaClasses classes = importClasses(RepositoryWithoutDependency.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void repository_with_dependency_to_controller_is_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToController.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(RepositoryWithDependencyToController.class.getName()); }); } @Test void repository_with_dependency_to_service_is_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToService.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isTrue(); assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> { assertThat(detail).contains(RepositoryWithDependencyToService.class.getName()); }); } @Test void repository_with_dependency_to_other_repository_is_not_a_violation() { JavaClasses classes = importClasses(RepositoryWithDependencyToRepository.class); EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfRepositories.evaluate(classes); assertThat(evaluationResult.hasViolation()).isFalse(); } @Test void repository_with_dependency_to_Spring_Data_repository_is_not_a_violation() {
JavaClasses classes = importClasses(RepositoryWithDependencyToSpringDataRepository.class);
10
2023-10-29 10:50:24+00:00
8k
373675032/verio-house
src/main/java/com/verio/controller/RoomOrderController.java
[ { "identifier": "Resp", "path": "src/main/java/com/verio/dto/Resp.java", "snippet": "public class Resp {\n public static String resp(RespResult result) {\n return JSONObject.toJSONString(result);\n }\n}" }, { "identifier": "RespResult", "path": "src/main/java/com/verio/dto/RespR...
import com.verio.dto.Resp; import com.verio.dto.RespResult; import com.verio.entity.Room; import com.verio.entity.RoomDetail; import com.verio.entity.RoomOrder; import com.verio.utils.Assert; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Calendar; import java.util.Date; import java.util.List;
3,859
package com.verio.controller; /** * 订单控制器 * ========================================================================== * 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。 * ========================================================================== * B站账号:薛伟同学 * 微信公众号:薛伟同学 * 作者博客:http://xuewei.world * ========================================================================== * 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。 * 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。 * 希望各位朋友擦亮慧眼,谨防上当受骗! * ========================================================================== * * @author <a href="http://xuewei.world/about">XUEW</a> */ @Controller @RequestMapping(value = "roomOrder") public class RoomOrderController extends BaseController<RoomOrder> { /** * 支付 */ @PostMapping("/pay") @ResponseBody public String pay(Integer id) { RoomOrder order = roomOrderService.get(id); List<RoomDetail> roomDetails = roomDetailService.query(RoomDetail.builder().roomId(order.getRoomId()).build()); if (Assert.notEmpty(roomDetails)) { RoomDetail detail = roomDetails.get(0); if ("已支付".equals(detail.getStatus())) { order.setPayOrder(System.currentTimeMillis() + "UNPAYED"); order.setStatus("已支付"); order = roomOrderService.save(order); return Resp.resp(RespResult.fail("支付失败,房源被他人抢先租下~")); } } else { return Resp.resp(RespResult.fail("支付失败,房源信息有误~")); } order.setPayOrder(System.currentTimeMillis() + "PAYED"); order.setStatus("已支付"); order = roomOrderService.save(order); if (Assert.notEmpty(order)) { // 更新房源的状态 RoomDetail detail = roomDetails.get(0); detail.setStatus("已租"); roomDetailService.save(detail); } return Resp.resp(RespResult.success("支付成功")); } /** * 创建订单 */ @PostMapping("/saveOrder") @ResponseBody public String saveOrder(Integer roomId, Integer month, Integer person) {
package com.verio.controller; /** * 订单控制器 * ========================================================================== * 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。 * ========================================================================== * B站账号:薛伟同学 * 微信公众号:薛伟同学 * 作者博客:http://xuewei.world * ========================================================================== * 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。 * 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。 * 希望各位朋友擦亮慧眼,谨防上当受骗! * ========================================================================== * * @author <a href="http://xuewei.world/about">XUEW</a> */ @Controller @RequestMapping(value = "roomOrder") public class RoomOrderController extends BaseController<RoomOrder> { /** * 支付 */ @PostMapping("/pay") @ResponseBody public String pay(Integer id) { RoomOrder order = roomOrderService.get(id); List<RoomDetail> roomDetails = roomDetailService.query(RoomDetail.builder().roomId(order.getRoomId()).build()); if (Assert.notEmpty(roomDetails)) { RoomDetail detail = roomDetails.get(0); if ("已支付".equals(detail.getStatus())) { order.setPayOrder(System.currentTimeMillis() + "UNPAYED"); order.setStatus("已支付"); order = roomOrderService.save(order); return Resp.resp(RespResult.fail("支付失败,房源被他人抢先租下~")); } } else { return Resp.resp(RespResult.fail("支付失败,房源信息有误~")); } order.setPayOrder(System.currentTimeMillis() + "PAYED"); order.setStatus("已支付"); order = roomOrderService.save(order); if (Assert.notEmpty(order)) { // 更新房源的状态 RoomDetail detail = roomDetails.get(0); detail.setStatus("已租"); roomDetailService.save(detail); } return Resp.resp(RespResult.success("支付成功")); } /** * 创建订单 */ @PostMapping("/saveOrder") @ResponseBody public String saveOrder(Integer roomId, Integer month, Integer person) {
Room room = roomService.get(roomId);
2
2023-10-29 14:50:56+00:00
8k
Changbaiqi/yatori
yatori-core/src/main/java/com/cbq/yatori/core/action/yinghua/CourseAction.java
[ { "identifier": "ConverterAllCourse", "path": "yatori-core/src/main/java/com/cbq/yatori/core/action/yinghua/entity/allcourse/ConverterAllCourse.java", "snippet": "public class ConverterAllCourse {\n // Date-time helpers\n\n private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeF...
import com.cbq.yatori.core.action.yinghua.entity.allcourse.ConverterAllCourse; 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.action.yinghua.entity.allvideo.ConverterVideo; import com.cbq.yatori.core.action.yinghua.entity.allvideo.NodeList; import com.cbq.yatori.core.action.yinghua.entity.allvideo.VideoRequest; import com.cbq.yatori.core.action.yinghua.entity.submitstudy.ConverterSubmitStudyTime; import com.cbq.yatori.core.action.yinghua.entity.submitstudy.SubmitStudyTimeRequest; import com.cbq.yatori.core.action.yinghua.entity.videomessage.VideoInformStudyTotal; import com.cbq.yatori.core.action.yinghua.entity.videomessage.ConverterVideoMessage; import com.cbq.yatori.core.action.yinghua.entity.videomessage.VideoInformRequest; import com.cbq.yatori.core.entity.AccountCacheYingHua; import com.cbq.yatori.core.entity.User; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import java.io.IOException; import java.net.SocketTimeoutException; import java.time.Duration;
6,218
package com.cbq.yatori.core.action.yinghua; @Slf4j public class CourseAction { /** * 获取课程信息 * @param user * @return */ public static CourseRequest getAllCourseRequest(User user) { //判断是否初始化 if(user.getAccount()==null) user.setCache(new AccountCacheYingHua()); OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("text/plain"); RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM) .addFormDataPart("platform", "Android") .addFormDataPart("version", "1.4.8") .addFormDataPart("type", "0") .addFormDataPart("token", ((AccountCacheYingHua) user.getCache()).getToken()) .build(); Request request = new Request.Builder() .url(user.getUrl()+"/api/course/list.json") .method("POST", body) .addHeader("Cookie", "tgw_I7_route=3d5c4e13e7d88bb6849295ab943042a2") .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)") .build(); try { Response response = client.newCall(request).execute(); if(!response.isSuccessful()){//当响应失败时 response.close(); return null; } String json = response.body().string(); CourseRequest courseRequest = ConverterAllCourse.fromJsonString(json); return courseRequest; } catch (SocketTimeoutException e){ return null; } catch (IOException e) { log.error(""); e.printStackTrace(); } return null; } /** * 获取对应课程的视屏章节等信息 * @param user * @param courseInform * @return */ public static VideoRequest getCourseVideosList(User user, CourseInform courseInform){ OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("text/plain"); RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM) .addFormDataPart("platform","Android") .addFormDataPart("version","1.4.8") .addFormDataPart("token",((AccountCacheYingHua)user.getCache()).getToken()) .addFormDataPart("courseId", String.valueOf(courseInform.getId())) .build(); Request request = new Request.Builder() .url(user.getUrl()+"/api/course/chapter.json") .method("POST", body) .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)") .build(); try { Response response = client.newCall(request).execute(); if(!response.isSuccessful()){//当响应失败时 response.close(); return null; } String json = response.body().string(); VideoRequest videoRequest = ConverterVideo.fromJsonString(json); return videoRequest; }catch (SocketTimeoutException e){ return null; } catch (IOException e) { log.error(""); e.printStackTrace(); } return null; } /** * 获取单个视屏的详细观看信息,比如观看的学习时长 * @param user * @param videoInform * @return */
package com.cbq.yatori.core.action.yinghua; @Slf4j public class CourseAction { /** * 获取课程信息 * @param user * @return */ public static CourseRequest getAllCourseRequest(User user) { //判断是否初始化 if(user.getAccount()==null) user.setCache(new AccountCacheYingHua()); OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("text/plain"); RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM) .addFormDataPart("platform", "Android") .addFormDataPart("version", "1.4.8") .addFormDataPart("type", "0") .addFormDataPart("token", ((AccountCacheYingHua) user.getCache()).getToken()) .build(); Request request = new Request.Builder() .url(user.getUrl()+"/api/course/list.json") .method("POST", body) .addHeader("Cookie", "tgw_I7_route=3d5c4e13e7d88bb6849295ab943042a2") .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)") .build(); try { Response response = client.newCall(request).execute(); if(!response.isSuccessful()){//当响应失败时 response.close(); return null; } String json = response.body().string(); CourseRequest courseRequest = ConverterAllCourse.fromJsonString(json); return courseRequest; } catch (SocketTimeoutException e){ return null; } catch (IOException e) { log.error(""); e.printStackTrace(); } return null; } /** * 获取对应课程的视屏章节等信息 * @param user * @param courseInform * @return */ public static VideoRequest getCourseVideosList(User user, CourseInform courseInform){ OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("text/plain"); RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM) .addFormDataPart("platform","Android") .addFormDataPart("version","1.4.8") .addFormDataPart("token",((AccountCacheYingHua)user.getCache()).getToken()) .addFormDataPart("courseId", String.valueOf(courseInform.getId())) .build(); Request request = new Request.Builder() .url(user.getUrl()+"/api/course/chapter.json") .method("POST", body) .addHeader("User-Agent", "Apifox/1.0.0 (https://www.apifox.cn)") .build(); try { Response response = client.newCall(request).execute(); if(!response.isSuccessful()){//当响应失败时 response.close(); return null; } String json = response.body().string(); VideoRequest videoRequest = ConverterVideo.fromJsonString(json); return videoRequest; }catch (SocketTimeoutException e){ return null; } catch (IOException e) { log.error(""); e.printStackTrace(); } return null; } /** * 获取单个视屏的详细观看信息,比如观看的学习时长 * @param user * @param videoInform * @return */
public static VideoInformRequest getVideMessage(User user, NodeList videoInform){
10
2023-10-30 04:15:41+00:00
8k
hezean/sustc
sustc-runner/src/main/java/io/sustc/command/VideoCommand.java
[ { "identifier": "AuthInfo", "path": "sustc-api/src/main/java/io/sustc/dto/AuthInfo.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class AuthInfo implements Serializable {\n\n /**\n * The user's mid.\n */\n private long mid;\n\n /**\n * The passwo...
import io.sustc.dto.AuthInfo; import io.sustc.dto.PostVideoReq; import io.sustc.service.VideoService; import lombok.val; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.shell.standard.ShellComponent; import org.springframework.shell.standard.ShellMethod; import org.springframework.shell.standard.ShellOption; import java.sql.Timestamp; import java.util.List; import java.util.Set;
3,696
package io.sustc.command; @ShellComponent @ConditionalOnBean(VideoService.class) public class VideoCommand { @Autowired private VideoService videoService; @ShellMethod(key = "video post") public String postVideo( @ShellOption(defaultValue = ShellOption.NULL) Long mid, @ShellOption(defaultValue = ShellOption.NULL) String pwd, @ShellOption(defaultValue = ShellOption.NULL) String qq, @ShellOption(defaultValue = ShellOption.NULL) String wechat, String title, @ShellOption(defaultValue = ShellOption.NULL) String description, Long duration, Timestamp publicTime ) {
package io.sustc.command; @ShellComponent @ConditionalOnBean(VideoService.class) public class VideoCommand { @Autowired private VideoService videoService; @ShellMethod(key = "video post") public String postVideo( @ShellOption(defaultValue = ShellOption.NULL) Long mid, @ShellOption(defaultValue = ShellOption.NULL) String pwd, @ShellOption(defaultValue = ShellOption.NULL) String qq, @ShellOption(defaultValue = ShellOption.NULL) String wechat, String title, @ShellOption(defaultValue = ShellOption.NULL) String description, Long duration, Timestamp publicTime ) {
val auth = AuthInfo.builder()
0
2023-10-27 03:27:20+00:00
8k
sgware/sabre
src/edu/uky/cs/nil/sabre/Problem.java
[ { "identifier": "Expression", "path": "src/edu/uky/cs/nil/sabre/logic/Expression.java", "snippet": "public interface Expression extends Typed, Simplifiable {\n\t\n\t@Override\n\tpublic Expression apply(Function<Object, Object> function);\n\t\n\t@Override\n\tpublic default Expression simplify() {\n\t\tre...
import java.io.Serializable; import java.util.LinkedHashSet; import edu.uky.cs.nil.sabre.logic.Expression; import edu.uky.cs.nil.sabre.logic.HashSubstitution; import edu.uky.cs.nil.sabre.logic.Unknown; import edu.uky.cs.nil.sabre.logic.Value; import edu.uky.cs.nil.sabre.util.ImmutableSet;
5,738
package edu.uky.cs.nil.sabre; /** * Represents all the definitions needed to define a full planning task. * A problem defines: * <ul> * <li>a {@link #name name}</li> * <li>a list of {@link Type types} and {@link Entity entities} defined in a * {@link Universe universe}</li> * <li>a list of {@link Fluent fluents}</li> * <li>a list of {@link Event events}, as well as smaller lists of {@link * Action actions} and {@link Trigger triggers}</li> * <li>a {@link Expression logical expression} defining the initial state</li> * <li>an {@link #utility author utility}</li> * <li>a {@link #utilities character utility} for each character</li> * </ul> * Problem objects usually should not be constructed directly. They should be * defined using a {@link ProblemBuilder} to ensure correct formatting. * <p> * The fluents and events defined in a problem can be templates, meaning their * signatures contain {@link edu.uky.cs.nil.sabre.logic.Variable variables}. A * fluent or event template implicitly defines all possible {@link * Expression#isGround() ground} versions of that template. Every ground fluent * or event must have a unique {@link Signature signature}; A * {@link ProblemBuilder problem builder} enforces this by preventing two * templates from ambiguously defining two ground objects that would be * different but have the same signature. * * @author Stephen G. Ware */ public class Problem implements Serializable { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** The name of the problem */ public final String name; /** * The universe defining the problem's {@link Type types} and {@link Entity * entities} */ public final Universe universe; /** The {@link Fluent fluents} tracked in every state of the problem */ public final ImmutableSet<Fluent> fluents; /** A set of all {@link Event events} that can occur */ public final ImmutableSet<Event> events; /** * All the {@link Action actions} defined in this problem (a subset of * {@link #events events}) */ public final ImmutableSet<Action> actions; /** * All the {@link Trigger triggers} defined in this problem (a subset of * {@link #events events}) */ public final ImmutableSet<Trigger> triggers; /** * A {@link Expression logical expression} representing the initial state */
package edu.uky.cs.nil.sabre; /** * Represents all the definitions needed to define a full planning task. * A problem defines: * <ul> * <li>a {@link #name name}</li> * <li>a list of {@link Type types} and {@link Entity entities} defined in a * {@link Universe universe}</li> * <li>a list of {@link Fluent fluents}</li> * <li>a list of {@link Event events}, as well as smaller lists of {@link * Action actions} and {@link Trigger triggers}</li> * <li>a {@link Expression logical expression} defining the initial state</li> * <li>an {@link #utility author utility}</li> * <li>a {@link #utilities character utility} for each character</li> * </ul> * Problem objects usually should not be constructed directly. They should be * defined using a {@link ProblemBuilder} to ensure correct formatting. * <p> * The fluents and events defined in a problem can be templates, meaning their * signatures contain {@link edu.uky.cs.nil.sabre.logic.Variable variables}. A * fluent or event template implicitly defines all possible {@link * Expression#isGround() ground} versions of that template. Every ground fluent * or event must have a unique {@link Signature signature}; A * {@link ProblemBuilder problem builder} enforces this by preventing two * templates from ambiguously defining two ground objects that would be * different but have the same signature. * * @author Stephen G. Ware */ public class Problem implements Serializable { /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** The name of the problem */ public final String name; /** * The universe defining the problem's {@link Type types} and {@link Entity * entities} */ public final Universe universe; /** The {@link Fluent fluents} tracked in every state of the problem */ public final ImmutableSet<Fluent> fluents; /** A set of all {@link Event events} that can occur */ public final ImmutableSet<Event> events; /** * All the {@link Action actions} defined in this problem (a subset of * {@link #events events}) */ public final ImmutableSet<Action> actions; /** * All the {@link Trigger triggers} defined in this problem (a subset of * {@link #events events}) */ public final ImmutableSet<Trigger> triggers; /** * A {@link Expression logical expression} representing the initial state */
public final Expression initial;
0
2023-10-26 18:14:19+00:00
8k
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;
5,872
/* * 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())
/* * 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())
6
2023-10-25 14:36:38+00:00
8k
granny/Pl3xMap
bukkit/src/main/java/net/pl3x/map/bukkit/Pl3xMapBukkit.java
[ { "identifier": "BukkitCommandManager", "path": "bukkit/src/main/java/net/pl3x/map/bukkit/command/BukkitCommandManager.java", "snippet": "public class BukkitCommandManager implements CommandHandler {\n private final PaperCommandManager<@NotNull Sender> manager;\n private final Command.Builder<@Not...
import java.util.UUID; import net.pl3x.map.bukkit.command.BukkitCommandManager; import net.pl3x.map.core.Pl3xMap; import net.pl3x.map.core.event.server.ServerLoadedEvent; import net.pl3x.map.core.network.Network; import net.pl3x.map.core.player.Player; import net.pl3x.map.core.player.PlayerListener; import net.pl3x.map.core.player.PlayerRegistry; import org.bukkit.World; import org.bukkit.craftbukkit.v1_20_R3.CraftWorld; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.server.ServerLoadEvent; import org.bukkit.event.world.WorldLoadEvent; import org.bukkit.event.world.WorldUnloadEvent; import org.bukkit.plugin.java.JavaPlugin; import org.jetbrains.annotations.NotNull;
6,175
/* * 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.bukkit; public class Pl3xMapBukkit extends JavaPlugin implements Listener { private final Pl3xMapImpl pl3xmap; private final PlayerListener playerListener = new PlayerListener(); private Network network; public Pl3xMapBukkit() { super(); this.pl3xmap = new Pl3xMapImpl(this); } @Override public void onEnable() { try { io.papermc.paper.chunk.system.scheduling.ChunkFullTask.class.getDeclaredField("chunkLoads"); io.papermc.paper.chunk.system.scheduling.ChunkFullTask.class.getDeclaredField("chunkGenerates"); getLogger().severe("Pl3xMap does not support Folia"); getLogger().severe("Pl3xMap will now disable itself"); getServer().getPluginManager().disablePlugin(this); return; } catch (Throwable ignore) { } this.pl3xmap.enable(); getServer().getPluginManager().registerEvents(this, this); this.network = new BukkitNetwork(this); this.network.register(); try { new BukkitCommandManager(this); } catch (Exception e) { throw new RuntimeException(e); } getServer().getScheduler().runTaskTimer(this, () -> this.pl3xmap.getScheduler().tick(), 20, 20); } @Override public void onDisable() { if (this.network != null) { this.network.unregister(); this.network = null; } this.pl3xmap.disable(); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPlayerJoin(@NotNull PlayerJoinEvent event) { PlayerRegistry registry = Pl3xMap.api().getPlayerRegistry(); UUID uuid = event.getPlayer().getUniqueId(); Player bukkitPlayer = registry.getOrDefault(uuid, () -> new BukkitPlayer(event.getPlayer())); this.playerListener.onJoin(bukkitPlayer); } @EventHandler(priority = EventPriority.MONITOR) public void onPlayerQuit(@NotNull PlayerQuitEvent event) { PlayerRegistry registry = Pl3xMap.api().getPlayerRegistry(); UUID uuid = event.getPlayer().getUniqueId(); Player bukkitPlayer = registry.unregister(uuid); if (bukkitPlayer != null) { this.playerListener.onQuit(bukkitPlayer); } } @EventHandler(priority = EventPriority.MONITOR) public void onWorldLoad(WorldLoadEvent event) { World world = event.getWorld(); Pl3xMap.api().getWorldRegistry().getOrDefault(world.getName(), () -> new BukkitWorld(((CraftWorld) world).getHandle(), world.getName())); } @EventHandler(priority = EventPriority.MONITOR) public void onWorldUnload(WorldUnloadEvent event) { Pl3xMap.api().getWorldRegistry().unregister(event.getWorld().getName()); } @EventHandler(priority = EventPriority.LOWEST) public void onServerLoaded(ServerLoadEvent event) {
/* * 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.bukkit; public class Pl3xMapBukkit extends JavaPlugin implements Listener { private final Pl3xMapImpl pl3xmap; private final PlayerListener playerListener = new PlayerListener(); private Network network; public Pl3xMapBukkit() { super(); this.pl3xmap = new Pl3xMapImpl(this); } @Override public void onEnable() { try { io.papermc.paper.chunk.system.scheduling.ChunkFullTask.class.getDeclaredField("chunkLoads"); io.papermc.paper.chunk.system.scheduling.ChunkFullTask.class.getDeclaredField("chunkGenerates"); getLogger().severe("Pl3xMap does not support Folia"); getLogger().severe("Pl3xMap will now disable itself"); getServer().getPluginManager().disablePlugin(this); return; } catch (Throwable ignore) { } this.pl3xmap.enable(); getServer().getPluginManager().registerEvents(this, this); this.network = new BukkitNetwork(this); this.network.register(); try { new BukkitCommandManager(this); } catch (Exception e) { throw new RuntimeException(e); } getServer().getScheduler().runTaskTimer(this, () -> this.pl3xmap.getScheduler().tick(), 20, 20); } @Override public void onDisable() { if (this.network != null) { this.network.unregister(); this.network = null; } this.pl3xmap.disable(); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPlayerJoin(@NotNull PlayerJoinEvent event) { PlayerRegistry registry = Pl3xMap.api().getPlayerRegistry(); UUID uuid = event.getPlayer().getUniqueId(); Player bukkitPlayer = registry.getOrDefault(uuid, () -> new BukkitPlayer(event.getPlayer())); this.playerListener.onJoin(bukkitPlayer); } @EventHandler(priority = EventPriority.MONITOR) public void onPlayerQuit(@NotNull PlayerQuitEvent event) { PlayerRegistry registry = Pl3xMap.api().getPlayerRegistry(); UUID uuid = event.getPlayer().getUniqueId(); Player bukkitPlayer = registry.unregister(uuid); if (bukkitPlayer != null) { this.playerListener.onQuit(bukkitPlayer); } } @EventHandler(priority = EventPriority.MONITOR) public void onWorldLoad(WorldLoadEvent event) { World world = event.getWorld(); Pl3xMap.api().getWorldRegistry().getOrDefault(world.getName(), () -> new BukkitWorld(((CraftWorld) world).getHandle(), world.getName())); } @EventHandler(priority = EventPriority.MONITOR) public void onWorldUnload(WorldUnloadEvent event) { Pl3xMap.api().getWorldRegistry().unregister(event.getWorld().getName()); } @EventHandler(priority = EventPriority.LOWEST) public void onServerLoaded(ServerLoadEvent event) {
Pl3xMap.api().getEventRegistry().callEvent(new ServerLoadedEvent());
2
2023-10-26 01:14:31+00:00
8k
jd-opensource/sql-analysis
sql-analysis/src/main/java/com/jd/sql/analysis/score/SqlScoreServiceDefault.java
[ { "identifier": "SqlAnalysisResult", "path": "sql-analysis/src/main/java/com/jd/sql/analysis/analysis/SqlAnalysisResult.java", "snippet": "public class SqlAnalysisResult {\n\n /**\n * 执行序号\n */\n private Long id;\n\n /**\n * 查询类型\n */\n private String selectType;\n\n /**\n...
import com.jd.sql.analysis.analysis.SqlAnalysisResult; import com.jd.sql.analysis.analysis.SqlAnalysisResultList; import com.jd.sql.analysis.config.SqlAnalysisConfig; import com.jd.sql.analysis.rule.SqlScoreRule; import com.jd.sql.analysis.util.GsonUtil; import org.apache.commons.collections4.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List;
4,130
package com.jd.sql.analysis.score; /** * @Author huhaitao21 * @Description 评分服务默认实现 * @Date 20:43 2022/11/1 **/ @Deprecated public class SqlScoreServiceDefault implements SqlScoreService { private static Logger logger = LoggerFactory.getLogger(SqlScoreServiceDefault.class); private static final Integer WARN_SCORE = 80; @Override public SqlScoreResult score(SqlAnalysisResultList sqlAnalysisResultList) { if (sqlAnalysisResultList == null || CollectionUtils.isEmpty(sqlAnalysisResultList.getResultList())) { return null; } //默认100分,扣分制 Integer score = 100; SqlScoreResult scoreResult = new SqlScoreResult(); List<SqlScoreResultDetail> analysisResults = new ArrayList<>(); //遍历分析结果,匹配评分规则
package com.jd.sql.analysis.score; /** * @Author huhaitao21 * @Description 评分服务默认实现 * @Date 20:43 2022/11/1 **/ @Deprecated public class SqlScoreServiceDefault implements SqlScoreService { private static Logger logger = LoggerFactory.getLogger(SqlScoreServiceDefault.class); private static final Integer WARN_SCORE = 80; @Override public SqlScoreResult score(SqlAnalysisResultList sqlAnalysisResultList) { if (sqlAnalysisResultList == null || CollectionUtils.isEmpty(sqlAnalysisResultList.getResultList())) { return null; } //默认100分,扣分制 Integer score = 100; SqlScoreResult scoreResult = new SqlScoreResult(); List<SqlScoreResultDetail> analysisResults = new ArrayList<>(); //遍历分析结果,匹配评分规则
for (SqlAnalysisResult result : sqlAnalysisResultList.getResultList()) {
0
2023-10-25 08:59:26+00:00
8k
easy-do/dnf-admin
be/src/main/java/plus/easydo/dnf/service/impl/DaGameConfigServiceImpl.java
[ { "identifier": "DaChannel", "path": "be/src/main/java/plus/easydo/dnf/entity/DaChannel.java", "snippet": "@Data\n@Table(value = \"da_channel\", onSet = Base64OnSetListener.class , onInsert = ChannelBase64InsertListener.class, onUpdate = ChannelBase64UpdateListener.class)\npublic class DaChannel {\n\n ...
import com.mybatisflex.core.paginate.Page; import com.mybatisflex.core.query.QueryWrapper; import com.mybatisflex.spring.service.impl.ServiceImpl; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import plus.easydo.dnf.entity.DaChannel; import plus.easydo.dnf.entity.DaGameConfig; import plus.easydo.dnf.manager.CacheManager; import plus.easydo.dnf.mapper.DaGameConfigMapper; import plus.easydo.dnf.qo.DaGameConfigQo; import plus.easydo.dnf.service.IDaChannelService; import plus.easydo.dnf.service.IDaGameConfigService; import plus.easydo.dnf.util.DockerUtil; import plus.easydo.dnf.util.WebSocketUtil; import java.util.List; import static plus.easydo.dnf.entity.table.DaGameConfigTableDef.DA_GAME_CONFIG;
4,412
package plus.easydo.dnf.service.impl; /** * 游戏配置 服务层实现。 * * @author mybatis-flex-helper automatic generation * @since 1.0 */ @Slf4j @Service @RequiredArgsConstructor
package plus.easydo.dnf.service.impl; /** * 游戏配置 服务层实现。 * * @author mybatis-flex-helper automatic generation * @since 1.0 */ @Slf4j @Service @RequiredArgsConstructor
public class DaGameConfigServiceImpl extends ServiceImpl<DaGameConfigMapper, DaGameConfig> implements IDaGameConfigService {
6
2023-10-29 03:26:16+00:00
8k
d0ge/sessionless
src/main/java/one/d4d/sessionless/forms/dialog/BruteForceAttackDialog.java
[ { "identifier": "Attack", "path": "src/main/java/one/d4d/sessionless/itsdangerous/Attack.java", "snippet": "public enum Attack {\n @SerializedName(\"Known\")\n KNOWN(\"Known\"),\n @SerializedName(\"Fast\")\n FAST(\"Fast\"),\n @SerializedName(\"Balanced\")\n Balanced(\"Balanced\"),\n ...
import one.d4d.sessionless.itsdangerous.Attack; import one.d4d.sessionless.itsdangerous.BruteForce; import one.d4d.sessionless.itsdangerous.model.SignedToken; import one.d4d.sessionless.keys.SecretKey; import one.d4d.sessionless.utils.ErrorLoggingActionListenerFactory; import one.d4d.sessionless.utils.Utils; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.List;
5,262
package one.d4d.sessionless.forms.dialog; public class BruteForceAttackDialog extends AbstractDialog { private JPanel contentPane; private JButton buttonCancel; private JProgressBar progressBarBruteForce; private JLabel lblStatus; private SecretKey secretKey; public BruteForceAttackDialog( Window parent, ErrorLoggingActionListenerFactory actionListenerFactory, List<String> signingSecrets, List<String> signingSalts, List<SecretKey> signingKeys,
package one.d4d.sessionless.forms.dialog; public class BruteForceAttackDialog extends AbstractDialog { private JPanel contentPane; private JButton buttonCancel; private JProgressBar progressBarBruteForce; private JLabel lblStatus; private SecretKey secretKey; public BruteForceAttackDialog( Window parent, ErrorLoggingActionListenerFactory actionListenerFactory, List<String> signingSecrets, List<String> signingSalts, List<SecretKey> signingKeys,
Attack mode,
0
2023-10-30 09:12:06+00:00
8k
ballerina-platform/module-ballerinax-ibm.ibmmq
native/src/main/java/io/ballerina/lib/ibm.ibmmq/CommonUtils.java
[ { "identifier": "MQRFH2Header", "path": "native/src/main/java/io/ballerina/lib/ibm.ibmmq/headers/MQRFH2Header.java", "snippet": "public class MQRFH2Header {\n\n private static final BString FIELD_VALUES_FIELD = StringUtils.fromString(\"fieldValues\");\n private static final BString FOLDER_STRINGS_...
import com.ibm.mq.MQException; import com.ibm.mq.MQGetMessageOptions; import com.ibm.mq.MQMessage; import com.ibm.mq.MQPropertyDescriptor; import com.ibm.mq.headers.MQHeaderList; import io.ballerina.lib.ibm.ibmmq.headers.MQRFH2Header; import io.ballerina.runtime.api.PredefinedTypes; import io.ballerina.runtime.api.Runtime; import io.ballerina.runtime.api.creators.ErrorCreator; import io.ballerina.runtime.api.creators.TypeCreator; import io.ballerina.runtime.api.creators.ValueCreator; import io.ballerina.runtime.api.flags.SymbolFlags; import io.ballerina.runtime.api.types.ArrayType; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.values.BArray; import io.ballerina.runtime.api.values.BError; import io.ballerina.runtime.api.values.BMap; import io.ballerina.runtime.api.values.BString; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Objects; import java.util.Optional; import static io.ballerina.lib.ibm.ibmmq.Constants.CORRELATION_ID_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.BPROPERTY; import static io.ballerina.lib.ibm.ibmmq.Constants.BMESSAGE_NAME; import static io.ballerina.lib.ibm.ibmmq.Constants.ERROR_COMPLETION_CODE; import static io.ballerina.lib.ibm.ibmmq.Constants.ERROR_DETAILS; import static io.ballerina.lib.ibm.ibmmq.Constants.ERROR_ERROR_CODE; import static io.ballerina.lib.ibm.ibmmq.Constants.ERROR_REASON_CODE; import static io.ballerina.lib.ibm.ibmmq.Constants.EXPIRY_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.FORMAT_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.IBMMQ_ERROR; import static io.ballerina.lib.ibm.ibmmq.Constants.MQCIH_RECORD_NAME; import static io.ballerina.lib.ibm.ibmmq.Constants.MQIIH_RECORD_NAME; import static io.ballerina.lib.ibm.ibmmq.Constants.MQRFH2_RECORD_NAME; import static io.ballerina.lib.ibm.ibmmq.Constants.MQRFH_RECORD_NAME; import static io.ballerina.lib.ibm.ibmmq.Constants.MESSAGE_HEADERS; import static io.ballerina.lib.ibm.ibmmq.Constants.MESSAGE_ID_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.MESSAGE_PAYLOAD; import static io.ballerina.lib.ibm.ibmmq.Constants.MESSAGE_PROPERTY; import static io.ballerina.lib.ibm.ibmmq.Constants.MESSAGE_PROPERTIES; import static io.ballerina.lib.ibm.ibmmq.Constants.MESSAGE_TYPE_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.OPTIONS; import static io.ballerina.lib.ibm.ibmmq.Constants.PD_CONTEXT; import static io.ballerina.lib.ibm.ibmmq.Constants.PD_COPY_OPTIONS; import static io.ballerina.lib.ibm.ibmmq.Constants.PD_OPTIONS; import static io.ballerina.lib.ibm.ibmmq.Constants.PD_SUPPORT; import static io.ballerina.lib.ibm.ibmmq.Constants.PD_VERSION; import static io.ballerina.lib.ibm.ibmmq.Constants.PERSISTENCE_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.PRIORITY_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.PROPERTY_DESCRIPTOR; import static io.ballerina.lib.ibm.ibmmq.Constants.PROPERTY_VALUE; import static io.ballerina.lib.ibm.ibmmq.Constants.PUT_APPLICATION_TYPE_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.REPLY_TO_QM_NAME_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.REPLY_TO_QUEUE_NAME_FIELD; import static io.ballerina.lib.ibm.ibmmq.Constants.WAIT_INTERVAL; import static io.ballerina.lib.ibm.ibmmq.ModuleUtils.getModule; import static io.ballerina.lib.ibm.ibmmq.headers.MQCIHHeader.createMQCIHHeaderFromBHeader; import static io.ballerina.lib.ibm.ibmmq.headers.MQIIHHeader.createMQIIHHeaderFromBHeader; import static io.ballerina.lib.ibm.ibmmq.headers.MQRFH2Header.createMQRFH2HeaderFromBHeader; import static io.ballerina.lib.ibm.ibmmq.headers.MQRFHHeader.createMQRFHHeaderFromBHeader;
6,611
Enumeration<String> propertyNames = mqMessage.getPropertyNames("%"); for (String propertyName : Collections.list(propertyNames)) { BMap<BString, Object> property = ValueCreator.createRecordValue(getModule(), BPROPERTY); MQPropertyDescriptor propertyDescriptor = new MQPropertyDescriptor(); Object propertyObject = mqMessage.getObjectProperty(propertyName, propertyDescriptor); if (propertyObject instanceof Integer intProperty) { property.put(PROPERTY_VALUE, intProperty.longValue()); } else if (propertyObject instanceof String stringProperty) { property.put(PROPERTY_VALUE, StringUtils.fromString(stringProperty)); } else if (propertyObject instanceof byte[] bytesProperty) { property.put(PROPERTY_VALUE, ValueCreator.createArrayValue(bytesProperty)); } else { property.put(PROPERTY_VALUE, propertyObject); } property.put(PROPERTY_DESCRIPTOR, populateDescriptorFromMQPropertyDescriptor(propertyDescriptor)); properties.put(StringUtils.fromString(propertyName), property); } return properties; } private static void populateMQProperties(BMap<BString, Object> properties, MQMessage mqMessage) { for (BString key : properties.getKeys()) { try { handlePropertyValue(properties, mqMessage, key); } catch (MQException e) { throw createError(IBMMQ_ERROR, String.format("Error occurred while setting message properties: %s", e.getMessage()), e); } } } @SuppressWarnings("unchecked") private static void handlePropertyValue(BMap<BString, Object> properties, MQMessage mqMessage, BString key) throws MQException { BMap<BString, Object> property = (BMap<BString, Object>) properties.getMapValue(key); MQPropertyDescriptor propertyDescriptor = defaultPropertyDescriptor; if (property.containsKey(PROPERTY_DESCRIPTOR)) { propertyDescriptor = getMQPropertyDescriptor( (BMap<BString, Object>) properties.getMapValue(PROPERTY_DESCRIPTOR)); } Object value = property.get(PROPERTY_VALUE); if (value instanceof Long longValue) { mqMessage.setIntProperty(key.getValue(), propertyDescriptor, longValue.intValue()); } else if (value instanceof Boolean booleanValue) { mqMessage.setBooleanProperty(key.getValue(), propertyDescriptor, booleanValue); } else if (value instanceof Byte byteValue) { mqMessage.setByteProperty(key.getValue(), propertyDescriptor, byteValue); } else if (value instanceof byte[] bytesValue) { mqMessage.setBytesProperty(key.getValue(), propertyDescriptor, bytesValue); } else if (value instanceof Float floatValue) { mqMessage.setFloatProperty(key.getValue(), propertyDescriptor, floatValue); } else if (value instanceof Double doubleValue) { mqMessage.setDoubleProperty(key.getValue(), propertyDescriptor, doubleValue); } else if (value instanceof BString stringValue) { mqMessage.setStringProperty(key.getValue(), propertyDescriptor, stringValue.getValue()); } } private static void assignOptionalFieldsToMqMessage(BMap<BString, Object> bMessage, MQMessage mqMessage) { if (bMessage.containsKey(FORMAT_FIELD)) { mqMessage.format = bMessage.getStringValue(FORMAT_FIELD).getValue(); } if (bMessage.containsKey(MESSAGE_ID_FIELD)) { mqMessage.messageId = bMessage.getArrayValue(MESSAGE_ID_FIELD).getByteArray(); } if (bMessage.containsKey(CORRELATION_ID_FIELD)) { mqMessage.correlationId = bMessage.getArrayValue(CORRELATION_ID_FIELD).getByteArray(); } if (bMessage.containsKey(EXPIRY_FIELD)) { mqMessage.expiry = bMessage.getIntValue(EXPIRY_FIELD).intValue(); } if (bMessage.containsKey(PRIORITY_FIELD)) { mqMessage.priority = bMessage.getIntValue(PRIORITY_FIELD).intValue(); } if (bMessage.containsKey(PERSISTENCE_FIELD)) { mqMessage.persistence = bMessage.getIntValue(PERSISTENCE_FIELD).intValue(); } if (bMessage.containsKey(MESSAGE_TYPE_FIELD)) { mqMessage.messageType = bMessage.getIntValue(MESSAGE_TYPE_FIELD).intValue(); } if (bMessage.containsKey(PUT_APPLICATION_TYPE_FIELD)) { mqMessage.putApplicationType = bMessage.getIntValue(PUT_APPLICATION_TYPE_FIELD).intValue(); } if (bMessage.containsKey(REPLY_TO_QUEUE_NAME_FIELD)) { mqMessage.replyToQueueName = bMessage.getStringValue(REPLY_TO_QUEUE_NAME_FIELD).getValue(); } if (bMessage.containsKey(REPLY_TO_QM_NAME_FIELD)) { mqMessage.replyToQueueManagerName = bMessage.getStringValue(REPLY_TO_QM_NAME_FIELD).getValue(); } } private static MQPropertyDescriptor getMQPropertyDescriptor(BMap<BString, Object> descriptor) { MQPropertyDescriptor propertyDescriptor = new MQPropertyDescriptor(); if (descriptor.containsKey(PD_VERSION)) { propertyDescriptor.version = ((Long) descriptor.get(PD_VERSION)).intValue(); } if (descriptor.containsKey(PD_COPY_OPTIONS)) { propertyDescriptor.copyOptions = ((Long) descriptor.get(PD_COPY_OPTIONS)).intValue(); } if (descriptor.containsKey(PD_OPTIONS)) { propertyDescriptor.options = ((Long) descriptor.get(PD_OPTIONS)).intValue(); } if (descriptor.containsKey(PD_SUPPORT)) { propertyDescriptor.support = ((Long) descriptor.get(PD_SUPPORT)).intValue(); } if (descriptor.containsKey(PD_CONTEXT)) { propertyDescriptor.context = ((Long) descriptor.get(PD_CONTEXT)).intValue(); } return propertyDescriptor; } private static void populateMQHeaders(BArray bHeaders, MQMessage mqMessage) { MQHeaderList headerList = new MQHeaderList(); for (int i = 0; i < bHeaders.size(); i++) { BMap<BString, Object> bHeader = (BMap) bHeaders.get(i); HeaderType headerType = HeaderType.valueOf(bHeader.getType().getName()); switch (headerType) { case MQRFH2 -> headerList.add(createMQRFH2HeaderFromBHeader(bHeader)); case MQRFH -> headerList.add(createMQRFHHeaderFromBHeader(bHeader));
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.lib.ibm.ibmmq; /** * {@code CommonUtils} contains the common utility functions for the Ballerina IBM MQ connector. */ public class CommonUtils { private static final MQPropertyDescriptor defaultPropertyDescriptor = new MQPropertyDescriptor(); private static final ArrayType BHeaderUnionType = TypeCreator.createArrayType( TypeCreator.createUnionType(List.of( TypeCreator.createRecordType(MQRFH2_RECORD_NAME, getModule(), SymbolFlags.PUBLIC, true, 0), TypeCreator.createRecordType(MQRFH_RECORD_NAME, getModule(), SymbolFlags.PUBLIC, true, 0), TypeCreator.createRecordType(MQCIH_RECORD_NAME, getModule(), SymbolFlags.PUBLIC, true, 0), TypeCreator.createRecordType(MQIIH_RECORD_NAME, getModule(), SymbolFlags.PUBLIC, true, 0)))); public static MQMessage getMqMessageFromBMessage(BMap<BString, Object> bMessage) { MQMessage mqMessage = new MQMessage(); BMap<BString, Object> properties = (BMap<BString, Object>) bMessage.getMapValue(MESSAGE_PROPERTIES); if (Objects.nonNull(properties)) { populateMQProperties(properties, mqMessage); } BArray headers = bMessage.getArrayValue(MESSAGE_HEADERS); if (Objects.nonNull(headers)) { populateMQHeaders(headers, mqMessage); } byte[] payload = bMessage.getArrayValue(MESSAGE_PAYLOAD).getBytes(); assignOptionalFieldsToMqMessage(bMessage, mqMessage); try { mqMessage.write(payload); } catch (IOException e) { throw createError(IBMMQ_ERROR, String.format("Error occurred while populating payload: %s", e.getMessage()), e); } return mqMessage; } public static BMap<BString, Object> getBMessageFromMQMessage(Runtime runtime, MQMessage mqMessage) { BMap<BString, Object> bMessage = ValueCreator.createRecordValue(getModule(), BMESSAGE_NAME); try { bMessage.put(MESSAGE_HEADERS, getBHeaders(runtime, mqMessage)); bMessage.put(MESSAGE_PROPERTY, getBProperties(mqMessage)); bMessage.put(FORMAT_FIELD, StringUtils.fromString(mqMessage.format)); bMessage.put(MESSAGE_ID_FIELD, ValueCreator.createArrayValue(mqMessage.messageId)); bMessage.put(CORRELATION_ID_FIELD, ValueCreator.createArrayValue((mqMessage.correlationId))); bMessage.put(EXPIRY_FIELD, mqMessage.expiry); bMessage.put(PRIORITY_FIELD, mqMessage.priority); bMessage.put(PERSISTENCE_FIELD, mqMessage.persistence); bMessage.put(MESSAGE_TYPE_FIELD, mqMessage.messageType); bMessage.put(PUT_APPLICATION_TYPE_FIELD, mqMessage.putApplicationType); bMessage.put(REPLY_TO_QUEUE_NAME_FIELD, StringUtils.fromString(mqMessage.replyToQueueName.strip())); bMessage.put(REPLY_TO_QM_NAME_FIELD, StringUtils.fromString(mqMessage.replyToQueueManagerName.strip())); byte[] payload = mqMessage.readStringOfByteLength(mqMessage.getDataLength()) .getBytes(StandardCharsets.UTF_8); bMessage.put(MESSAGE_PAYLOAD, ValueCreator.createArrayValue(payload)); return bMessage; } catch (MQException | IOException e) { throw createError(IBMMQ_ERROR, String.format("Error occurred while reading the message: %s", e.getMessage()), e); } } private static BMap<BString, Object> getBProperties(MQMessage mqMessage) throws MQException { BMap<BString, Object> properties = ValueCreator.createMapValue(TypeCreator .createMapType(TypeCreator.createRecordType(BPROPERTY, getModule(), 0, false, 0))); Enumeration<String> propertyNames = mqMessage.getPropertyNames("%"); for (String propertyName : Collections.list(propertyNames)) { BMap<BString, Object> property = ValueCreator.createRecordValue(getModule(), BPROPERTY); MQPropertyDescriptor propertyDescriptor = new MQPropertyDescriptor(); Object propertyObject = mqMessage.getObjectProperty(propertyName, propertyDescriptor); if (propertyObject instanceof Integer intProperty) { property.put(PROPERTY_VALUE, intProperty.longValue()); } else if (propertyObject instanceof String stringProperty) { property.put(PROPERTY_VALUE, StringUtils.fromString(stringProperty)); } else if (propertyObject instanceof byte[] bytesProperty) { property.put(PROPERTY_VALUE, ValueCreator.createArrayValue(bytesProperty)); } else { property.put(PROPERTY_VALUE, propertyObject); } property.put(PROPERTY_DESCRIPTOR, populateDescriptorFromMQPropertyDescriptor(propertyDescriptor)); properties.put(StringUtils.fromString(propertyName), property); } return properties; } private static void populateMQProperties(BMap<BString, Object> properties, MQMessage mqMessage) { for (BString key : properties.getKeys()) { try { handlePropertyValue(properties, mqMessage, key); } catch (MQException e) { throw createError(IBMMQ_ERROR, String.format("Error occurred while setting message properties: %s", e.getMessage()), e); } } } @SuppressWarnings("unchecked") private static void handlePropertyValue(BMap<BString, Object> properties, MQMessage mqMessage, BString key) throws MQException { BMap<BString, Object> property = (BMap<BString, Object>) properties.getMapValue(key); MQPropertyDescriptor propertyDescriptor = defaultPropertyDescriptor; if (property.containsKey(PROPERTY_DESCRIPTOR)) { propertyDescriptor = getMQPropertyDescriptor( (BMap<BString, Object>) properties.getMapValue(PROPERTY_DESCRIPTOR)); } Object value = property.get(PROPERTY_VALUE); if (value instanceof Long longValue) { mqMessage.setIntProperty(key.getValue(), propertyDescriptor, longValue.intValue()); } else if (value instanceof Boolean booleanValue) { mqMessage.setBooleanProperty(key.getValue(), propertyDescriptor, booleanValue); } else if (value instanceof Byte byteValue) { mqMessage.setByteProperty(key.getValue(), propertyDescriptor, byteValue); } else if (value instanceof byte[] bytesValue) { mqMessage.setBytesProperty(key.getValue(), propertyDescriptor, bytesValue); } else if (value instanceof Float floatValue) { mqMessage.setFloatProperty(key.getValue(), propertyDescriptor, floatValue); } else if (value instanceof Double doubleValue) { mqMessage.setDoubleProperty(key.getValue(), propertyDescriptor, doubleValue); } else if (value instanceof BString stringValue) { mqMessage.setStringProperty(key.getValue(), propertyDescriptor, stringValue.getValue()); } } private static void assignOptionalFieldsToMqMessage(BMap<BString, Object> bMessage, MQMessage mqMessage) { if (bMessage.containsKey(FORMAT_FIELD)) { mqMessage.format = bMessage.getStringValue(FORMAT_FIELD).getValue(); } if (bMessage.containsKey(MESSAGE_ID_FIELD)) { mqMessage.messageId = bMessage.getArrayValue(MESSAGE_ID_FIELD).getByteArray(); } if (bMessage.containsKey(CORRELATION_ID_FIELD)) { mqMessage.correlationId = bMessage.getArrayValue(CORRELATION_ID_FIELD).getByteArray(); } if (bMessage.containsKey(EXPIRY_FIELD)) { mqMessage.expiry = bMessage.getIntValue(EXPIRY_FIELD).intValue(); } if (bMessage.containsKey(PRIORITY_FIELD)) { mqMessage.priority = bMessage.getIntValue(PRIORITY_FIELD).intValue(); } if (bMessage.containsKey(PERSISTENCE_FIELD)) { mqMessage.persistence = bMessage.getIntValue(PERSISTENCE_FIELD).intValue(); } if (bMessage.containsKey(MESSAGE_TYPE_FIELD)) { mqMessage.messageType = bMessage.getIntValue(MESSAGE_TYPE_FIELD).intValue(); } if (bMessage.containsKey(PUT_APPLICATION_TYPE_FIELD)) { mqMessage.putApplicationType = bMessage.getIntValue(PUT_APPLICATION_TYPE_FIELD).intValue(); } if (bMessage.containsKey(REPLY_TO_QUEUE_NAME_FIELD)) { mqMessage.replyToQueueName = bMessage.getStringValue(REPLY_TO_QUEUE_NAME_FIELD).getValue(); } if (bMessage.containsKey(REPLY_TO_QM_NAME_FIELD)) { mqMessage.replyToQueueManagerName = bMessage.getStringValue(REPLY_TO_QM_NAME_FIELD).getValue(); } } private static MQPropertyDescriptor getMQPropertyDescriptor(BMap<BString, Object> descriptor) { MQPropertyDescriptor propertyDescriptor = new MQPropertyDescriptor(); if (descriptor.containsKey(PD_VERSION)) { propertyDescriptor.version = ((Long) descriptor.get(PD_VERSION)).intValue(); } if (descriptor.containsKey(PD_COPY_OPTIONS)) { propertyDescriptor.copyOptions = ((Long) descriptor.get(PD_COPY_OPTIONS)).intValue(); } if (descriptor.containsKey(PD_OPTIONS)) { propertyDescriptor.options = ((Long) descriptor.get(PD_OPTIONS)).intValue(); } if (descriptor.containsKey(PD_SUPPORT)) { propertyDescriptor.support = ((Long) descriptor.get(PD_SUPPORT)).intValue(); } if (descriptor.containsKey(PD_CONTEXT)) { propertyDescriptor.context = ((Long) descriptor.get(PD_CONTEXT)).intValue(); } return propertyDescriptor; } private static void populateMQHeaders(BArray bHeaders, MQMessage mqMessage) { MQHeaderList headerList = new MQHeaderList(); for (int i = 0; i < bHeaders.size(); i++) { BMap<BString, Object> bHeader = (BMap) bHeaders.get(i); HeaderType headerType = HeaderType.valueOf(bHeader.getType().getName()); switch (headerType) { case MQRFH2 -> headerList.add(createMQRFH2HeaderFromBHeader(bHeader)); case MQRFH -> headerList.add(createMQRFHHeaderFromBHeader(bHeader));
case MQCIH -> headerList.add(createMQCIHHeaderFromBHeader(bHeader));
2
2023-10-27 05:54:44+00:00
8k
LEAWIND/Third-Person
common/src/main/java/net/leawind/mc/thirdperson/mixin/LocalPlayerMixin.java
[ { "identifier": "CameraAgent", "path": "common/src/main/java/net/leawind/mc/thirdperson/core/CameraAgent.java", "snippet": "public final class CameraAgent {\n\tpublic static final @NotNull Camera fakeCamera = new Camera();\n\tpublic static final @NotNull Vector2d relativ...
import net.leawind.mc.thirdperson.core.CameraAgent; import net.leawind.mc.thirdperson.core.ModReferee; import net.leawind.mc.thirdperson.core.PlayerAgent; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
6,729
package net.leawind.mc.thirdperson.mixin; /** * 计算玩家移动方向和速度 * <p> * 第三人称视角下,按下方向键时,玩家的移动方向应由相机朝向和按键决定 */ @Mixin(value=net.minecraft.client.player.LocalPlayer.class, priority=2000) public class LocalPlayerMixin { @Inject(method="serverAiStep", at=@At(value="TAIL")) public void serverAiStep_inject_tail (CallbackInfo ci) {
package net.leawind.mc.thirdperson.mixin; /** * 计算玩家移动方向和速度 * <p> * 第三人称视角下,按下方向键时,玩家的移动方向应由相机朝向和按键决定 */ @Mixin(value=net.minecraft.client.player.LocalPlayer.class, priority=2000) public class LocalPlayerMixin { @Inject(method="serverAiStep", at=@At(value="TAIL")) public void serverAiStep_inject_tail (CallbackInfo ci) {
if (CameraAgent.isAvailable() && ModReferee.isThirdPerson() && CameraAgent.isControlledCamera()) {
1
2023-10-31 05:52:36+00:00
8k
kandybaby/S3mediaArchival
backend/src/main/java/com/example/mediaarchival/tasks/RestoreChecker.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.models.MediaModel; import com.example.mediaarchival.repositories.MediaRepository; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsTemplate; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
6,409
package com.example.mediaarchival.tasks; /** * Scheduled task that checks the restore status of media items from S3 Glacier to S3. */ @Component public class RestoreChecker { private final MediaRepository mediaRepository; private final S3Client s3Client; private final JmsTemplate jmsTemplate;
package com.example.mediaarchival.tasks; /** * Scheduled task that checks the restore status of media items from S3 Glacier to S3. */ @Component public class RestoreChecker { private final MediaRepository mediaRepository; private final S3Client s3Client; private final JmsTemplate jmsTemplate;
private final MediaController mediaController;
0
2023-10-27 01:54:57+00:00
8k
siam1026/siam-cloud
siam-user/user-provider/src/main/java/com/siam/package_user/controller/member/internal/VipRechargeRecordController.java
[ { "identifier": "StoneCustomerException", "path": "siam-common/src/main/java/com/siam/package_common/exception/StoneCustomerException.java", "snippet": "public class StoneCustomerException extends RuntimeException{\n // 结果码\n private Integer code = BasicResultCode.ERR;\n\n // 结果码描述\n private...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.package_common.exception.StoneCustomerException; import com.siam.package_user.auth.cache.MemberSessionManager; import com.siam.package_user.entity.Member; 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_common.constant.Quantity; import com.siam.package_user.entity.internal.VipRechargeRecord; import com.siam.package_user.service.internal.VipRechargeRecordService; import com.siam.package_user.util.TokenUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; 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.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest;
4,992
package com.siam.package_user.controller.member.internal; @Slf4j @RestController @RequestMapping(value = "/rest/member/vipRechargeRecord") @Transactional(rollbackFor = Exception.class) @Api(tags = "会员充值记录模块相关接口", description = "VipRechargeRecordController") public class VipRechargeRecordController { @Autowired private VipRechargeRecordService vipRechargeRecordService; @Autowired private MemberSessionManager memberSessionManager; @ApiOperation(value = "会员充值记录列表") @PostMapping(value = "/list") public BasicResult list(@RequestBody @Validated(value = {}) VipRechargeRecord vipRechargeRecord, HttpServletRequest request){ BasicData basicResult = new BasicData(); Member loginMember = memberSessionManager.getSession(TokenUtil.getToken()); //只查询当前登录用户的会员充值记录 vipRechargeRecord.setMemberId(loginMember.getId());
package com.siam.package_user.controller.member.internal; @Slf4j @RestController @RequestMapping(value = "/rest/member/vipRechargeRecord") @Transactional(rollbackFor = Exception.class) @Api(tags = "会员充值记录模块相关接口", description = "VipRechargeRecordController") public class VipRechargeRecordController { @Autowired private VipRechargeRecordService vipRechargeRecordService; @Autowired private MemberSessionManager memberSessionManager; @ApiOperation(value = "会员充值记录列表") @PostMapping(value = "/list") public BasicResult list(@RequestBody @Validated(value = {}) VipRechargeRecord vipRechargeRecord, HttpServletRequest request){ BasicData basicResult = new BasicData(); Member loginMember = memberSessionManager.getSession(TokenUtil.getToken()); //只查询当前登录用户的会员充值记录 vipRechargeRecord.setMemberId(loginMember.getId());
vipRechargeRecord.setStatus(Quantity.INT_2);
6
2023-10-26 10:45:10+00:00
8k
SealParadise/Andrade-S-AES
Code/S-AES/src/main/java/org/aes/controller/IndexController.java
[ { "identifier": "CBC", "path": "Code/S-AES/src/main/java/org/aes/cipher/CBC.java", "snippet": "public class CBC {\r\n //初始化编码器\r\n Encoder encoder = new Encoder();\r\n //初始化解码器\r\n Decoder decoder = new Decoder();\r\n //初始化通用操作对象\r\n Common common = new Common();\r\n\r\n /*\r\n C...
import javafx.fxml.FXML; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import org.aes.cipher.CBC; import org.aes.cipher.Decoder; import org.aes.cipher.Encoder; import org.aes.cipher.MeetInTheMid; import org.aes.commen.Common; import java.util.ArrayList; import java.util.List;
5,681
package org.aes.controller; public class IndexController { //初始化通用操作对象 Common common = new Common(); //初始化解码器 Decoder decoder = new Decoder(); //初始化编码器 Encoder encoder = new Encoder(); //初始化中间相遇攻击对象 MeetInTheMid attacker = new MeetInTheMid(); //初始化CBC密码器
package org.aes.controller; public class IndexController { //初始化通用操作对象 Common common = new Common(); //初始化解码器 Decoder decoder = new Decoder(); //初始化编码器 Encoder encoder = new Encoder(); //初始化中间相遇攻击对象 MeetInTheMid attacker = new MeetInTheMid(); //初始化CBC密码器
CBC cbc = new CBC();
0
2023-10-27 09:38:12+00:00
8k
elizagamedev/android-libre-japanese-input
app/src/main/java/sh/eliza/japaneseinput/model/JapaneseSoftwareKeyboardModel.java
[ { "identifier": "MozcLog", "path": "app/src/main/java/sh/eliza/japaneseinput/MozcLog.java", "snippet": "public class MozcLog {\n private MozcLog() {}\n\n public static boolean isLoggable(int logLevel) {\n return Log.isLoggable(MozcUtil.LOGTAG, logLevel);\n }\n\n public static void v(String msg) {...
import android.text.InputType; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.util.Collections; import java.util.EnumSet; import java.util.Set; import sh.eliza.japaneseinput.MozcLog; import sh.eliza.japaneseinput.MozcUtil; import sh.eliza.japaneseinput.keyboard.Keyboard.KeyboardSpecification; import sh.eliza.japaneseinput.preference.ClientSidePreference.InputStyle; import sh.eliza.japaneseinput.preference.ClientSidePreference.KeyboardLayout; import android.inputmethodservice.InputMethodService;
4,358
// 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.model; /** * Model class to represent Mozc's software keyboard. * * <p>Currently, this class manages four states: * * <ul> * <li>{@code KeyboardLayout} * <li>{@code KeyboardMode} * <li>{@code InputStyle} * <li>{@code qwertyLayoutForAlphabet} * </ul> * * For {@code TWLEVE_KEY} layout, we have three {@code InputStyle}, which are {@code TOGGLE}, {@code * FLICK} and {@code TOGGLE_FLICK}. Also, users can use {@code QWERTY} style layout for alphabet * mode by setting {@code qwertyLayoutForAlphabet} {@code true}. * * <p>{@code TWLEVE_KEY} layout has two {@code KeyboardMode}, which are {@code KANA}, {@code * ALPHABET}. * * <p>On {@code SymbolInputView}, we have a special {@code KeyboardMode}, which is {@code * SYMBOL_NUMBER}. It is NOT used on normal view. * * <p>For {@code QWERTY} layout, we have two {@code KeyboardMode}, which are {@code KANA}, {@code * ALPHABET}. The parameters, {@code InputStyle} and {@code qwertyLayoutForAlphabet}, are simply * ignored. * * <p>This class manages the "default mode" of software keyboard depending on {@code inputType}. It * is expected that the {@code inputType} is given by system via {@link * InputMethodService#onStartInputView}. */ public class JapaneseSoftwareKeyboardModel { /** Keyboard mode that indicates supported character types. */ public enum KeyboardMode { KANA, ALPHABET, ALPHABET_NUMBER, NUMBER, SYMBOL_NUMBER, } /** Keyboard modes which can be kept even if a focused text field is changed. */ private static final Set<KeyboardMode> REMEMBERABLE_KEYBOARD_MODE_SET = Collections.unmodifiableSet( EnumSet.of(KeyboardMode.KANA, KeyboardMode.ALPHABET, KeyboardMode.ALPHABET_NUMBER)); private static final KeyboardMode DEFAULT_KEYBOARD_MODE = KeyboardMode.KANA; private KeyboardLayout keyboardLayout = KeyboardLayout.TWELVE_KEYS; private KeyboardMode keyboardMode = DEFAULT_KEYBOARD_MODE; private InputStyle inputStyle = InputStyle.TOGGLE; private boolean qwertyLayoutForAlphabet = false; private int inputType; // This is just saved mode for setInputType. So, after that when qwertyLayoutForAlphabet is // edited, the mode can be un-expected one. // (e.g., TWELVE_KEY_LAYOUT + (qwertyLayoutForAlphabet = false) + ALPHABET_NUMBER). // For now, getKeyboardLayout handles it, so it should fine. We may want to change the // strategy in future. private Optional<KeyboardMode> savedMode = Optional.absent(); public JapaneseSoftwareKeyboardModel() {} public KeyboardLayout getKeyboardLayout() { return keyboardLayout; } public void setKeyboardLayout(KeyboardLayout keyboardLayout) { Preconditions.checkNotNull(keyboardLayout); Optional<KeyboardMode> optionalMode = getPreferredKeyboardMode(this.inputType, keyboardLayout); KeyboardMode mode = optionalMode.or(DEFAULT_KEYBOARD_MODE); this.keyboardLayout = keyboardLayout; // Reset keyboard mode as well. this.keyboardMode = mode; this.savedMode = Optional.absent(); } public KeyboardMode getKeyboardMode() { return keyboardMode; } public void setKeyboardMode(KeyboardMode keyboardMode) { this.keyboardMode = Preconditions.checkNotNull(keyboardMode); } public InputStyle getInputStyle() { return inputStyle; } public void setInputStyle(InputStyle inputStyle) { this.inputStyle = Preconditions.checkNotNull(inputStyle); } public boolean isQwertyLayoutForAlphabet() { return qwertyLayoutForAlphabet; } public void setQwertyLayoutForAlphabet(boolean qwertyLayoutForAlphabet) { this.qwertyLayoutForAlphabet = qwertyLayoutForAlphabet; } /** * Sets {@code inputType} and update the {@code keyboardMode} if necessary. See the class comment * for details. */ public void setInputType(int inputType) { Optional<KeyboardMode> mode = getPreferredKeyboardMode(inputType, this.keyboardLayout); if (mode.isPresent()) { if (!getPreferredKeyboardMode(this.inputType, this.keyboardLayout).isPresent()) { // Remember the current keyboard mode. savedMode = Optional.of(keyboardMode); } } else { // Restore the saved mode. mode = savedMode; savedMode = Optional.absent(); } this.inputType = inputType; if (mode.isPresent()) { this.keyboardMode = mode.get(); } else if (!REMEMBERABLE_KEYBOARD_MODE_SET.contains(this.keyboardMode)) { // Disable a non-rememberable keyboard here since neither mode nor saved mode are specified. this.keyboardMode = DEFAULT_KEYBOARD_MODE; } } public static Optional<KeyboardMode> getPreferredKeyboardMode( int inputType, KeyboardLayout layout) { if (MozcUtil.isNumberKeyboardPreferred(inputType)) { switch (Preconditions.checkNotNull(layout)) { case GODAN: case QWERTY: case TWELVE_KEYS: return Optional.of(KeyboardMode.NUMBER); } } if ((inputType & InputType.TYPE_MASK_CLASS) == InputType.TYPE_CLASS_TEXT) { switch (inputType & InputType.TYPE_MASK_VARIATION) { case InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS: case InputType.TYPE_TEXT_VARIATION_PASSWORD: case InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD: case InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS: case InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD: return Optional.of(KeyboardMode.ALPHABET); } } // KeyboardMode recommended strongly is not found here, so just return null. return Optional.absent(); } /** Returns {@link KeyboardSpecification} instance based on the current state. */
// 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.model; /** * Model class to represent Mozc's software keyboard. * * <p>Currently, this class manages four states: * * <ul> * <li>{@code KeyboardLayout} * <li>{@code KeyboardMode} * <li>{@code InputStyle} * <li>{@code qwertyLayoutForAlphabet} * </ul> * * For {@code TWLEVE_KEY} layout, we have three {@code InputStyle}, which are {@code TOGGLE}, {@code * FLICK} and {@code TOGGLE_FLICK}. Also, users can use {@code QWERTY} style layout for alphabet * mode by setting {@code qwertyLayoutForAlphabet} {@code true}. * * <p>{@code TWLEVE_KEY} layout has two {@code KeyboardMode}, which are {@code KANA}, {@code * ALPHABET}. * * <p>On {@code SymbolInputView}, we have a special {@code KeyboardMode}, which is {@code * SYMBOL_NUMBER}. It is NOT used on normal view. * * <p>For {@code QWERTY} layout, we have two {@code KeyboardMode}, which are {@code KANA}, {@code * ALPHABET}. The parameters, {@code InputStyle} and {@code qwertyLayoutForAlphabet}, are simply * ignored. * * <p>This class manages the "default mode" of software keyboard depending on {@code inputType}. It * is expected that the {@code inputType} is given by system via {@link * InputMethodService#onStartInputView}. */ public class JapaneseSoftwareKeyboardModel { /** Keyboard mode that indicates supported character types. */ public enum KeyboardMode { KANA, ALPHABET, ALPHABET_NUMBER, NUMBER, SYMBOL_NUMBER, } /** Keyboard modes which can be kept even if a focused text field is changed. */ private static final Set<KeyboardMode> REMEMBERABLE_KEYBOARD_MODE_SET = Collections.unmodifiableSet( EnumSet.of(KeyboardMode.KANA, KeyboardMode.ALPHABET, KeyboardMode.ALPHABET_NUMBER)); private static final KeyboardMode DEFAULT_KEYBOARD_MODE = KeyboardMode.KANA; private KeyboardLayout keyboardLayout = KeyboardLayout.TWELVE_KEYS; private KeyboardMode keyboardMode = DEFAULT_KEYBOARD_MODE; private InputStyle inputStyle = InputStyle.TOGGLE; private boolean qwertyLayoutForAlphabet = false; private int inputType; // This is just saved mode for setInputType. So, after that when qwertyLayoutForAlphabet is // edited, the mode can be un-expected one. // (e.g., TWELVE_KEY_LAYOUT + (qwertyLayoutForAlphabet = false) + ALPHABET_NUMBER). // For now, getKeyboardLayout handles it, so it should fine. We may want to change the // strategy in future. private Optional<KeyboardMode> savedMode = Optional.absent(); public JapaneseSoftwareKeyboardModel() {} public KeyboardLayout getKeyboardLayout() { return keyboardLayout; } public void setKeyboardLayout(KeyboardLayout keyboardLayout) { Preconditions.checkNotNull(keyboardLayout); Optional<KeyboardMode> optionalMode = getPreferredKeyboardMode(this.inputType, keyboardLayout); KeyboardMode mode = optionalMode.or(DEFAULT_KEYBOARD_MODE); this.keyboardLayout = keyboardLayout; // Reset keyboard mode as well. this.keyboardMode = mode; this.savedMode = Optional.absent(); } public KeyboardMode getKeyboardMode() { return keyboardMode; } public void setKeyboardMode(KeyboardMode keyboardMode) { this.keyboardMode = Preconditions.checkNotNull(keyboardMode); } public InputStyle getInputStyle() { return inputStyle; } public void setInputStyle(InputStyle inputStyle) { this.inputStyle = Preconditions.checkNotNull(inputStyle); } public boolean isQwertyLayoutForAlphabet() { return qwertyLayoutForAlphabet; } public void setQwertyLayoutForAlphabet(boolean qwertyLayoutForAlphabet) { this.qwertyLayoutForAlphabet = qwertyLayoutForAlphabet; } /** * Sets {@code inputType} and update the {@code keyboardMode} if necessary. See the class comment * for details. */ public void setInputType(int inputType) { Optional<KeyboardMode> mode = getPreferredKeyboardMode(inputType, this.keyboardLayout); if (mode.isPresent()) { if (!getPreferredKeyboardMode(this.inputType, this.keyboardLayout).isPresent()) { // Remember the current keyboard mode. savedMode = Optional.of(keyboardMode); } } else { // Restore the saved mode. mode = savedMode; savedMode = Optional.absent(); } this.inputType = inputType; if (mode.isPresent()) { this.keyboardMode = mode.get(); } else if (!REMEMBERABLE_KEYBOARD_MODE_SET.contains(this.keyboardMode)) { // Disable a non-rememberable keyboard here since neither mode nor saved mode are specified. this.keyboardMode = DEFAULT_KEYBOARD_MODE; } } public static Optional<KeyboardMode> getPreferredKeyboardMode( int inputType, KeyboardLayout layout) { if (MozcUtil.isNumberKeyboardPreferred(inputType)) { switch (Preconditions.checkNotNull(layout)) { case GODAN: case QWERTY: case TWELVE_KEYS: return Optional.of(KeyboardMode.NUMBER); } } if ((inputType & InputType.TYPE_MASK_CLASS) == InputType.TYPE_CLASS_TEXT) { switch (inputType & InputType.TYPE_MASK_VARIATION) { case InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS: case InputType.TYPE_TEXT_VARIATION_PASSWORD: case InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD: case InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS: case InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD: return Optional.of(KeyboardMode.ALPHABET); } } // KeyboardMode recommended strongly is not found here, so just return null. return Optional.absent(); } /** Returns {@link KeyboardSpecification} instance based on the current state. */
public KeyboardSpecification getKeyboardSpecification() {
1
2023-10-25 07:33:25+00:00
8k
Lyn4ever29/halo-plugin-export-md
src/main/java/cn/lyn4ever/export2md/rest/ExportController.java
[ { "identifier": "ExportLogSchema", "path": "src/main/java/cn/lyn4ever/export2md/schema/ExportLogSchema.java", "snippet": "@Data\n@ToString\n@EqualsAndHashCode(callSuper = true)\n@GVK(kind = \"ExportLog\", group = \"cn.lyn4ever.export2doc\",\n version = \"v1alpha1\", singular = \"exportLog\", plural =...
import cn.lyn4ever.export2md.schema.ExportLogSchema; import cn.lyn4ever.export2md.service.impl.ExportServiceImpl; import cn.lyn4ever.export2md.util.FileUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ZeroCopyHttpOutputMessage; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import run.halo.app.extension.ExtensionClient; import run.halo.app.extension.Metadata; import run.halo.app.extension.ReactiveExtensionClient; import run.halo.app.plugin.ApiVersion; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.Arrays; import java.util.Date;
3,627
package cn.lyn4ever.export2md.rest; /** * 自定义导出接口 * * @author Lyn4ever29 * @url https://jhacker.cn * @date 2023/11/1 */ @ApiVersion("v1alpha1") @RequestMapping("/doExport") @RestController @Slf4j public class ExportController { // /apis/plugin.api.halo.run/v1alpha1/plugins/export-anything/doExport/** private final String EXPORT_ONE_DIR = "markdown_post"; @Autowired private ExportServiceImpl exportService; @Autowired private ReactiveExtensionClient reactiveClient; @Autowired private ExtensionClient commonClient; @PostMapping("/export")
package cn.lyn4ever.export2md.rest; /** * 自定义导出接口 * * @author Lyn4ever29 * @url https://jhacker.cn * @date 2023/11/1 */ @ApiVersion("v1alpha1") @RequestMapping("/doExport") @RestController @Slf4j public class ExportController { // /apis/plugin.api.halo.run/v1alpha1/plugins/export-anything/doExport/** private final String EXPORT_ONE_DIR = "markdown_post"; @Autowired private ExportServiceImpl exportService; @Autowired private ReactiveExtensionClient reactiveClient; @Autowired private ExtensionClient commonClient; @PostMapping("/export")
public Mono<ExportLogSchema> export(@RequestBody final ExportLogSchema exportLogSchema) {
0
2023-10-29 16:01:45+00:00
8k
PhilipPanda/Temple-Client
src/main/java/xyz/templecheats/templeclient/TempleClient.java
[ { "identifier": "AnnotatedEventManager", "path": "src/main/java/team/stiff/pomelo/impl/annotated/AnnotatedEventManager.java", "snippet": "public final class AnnotatedEventManager implements EventManager {\n /**\n * Listener scanner implementation used to find all listeners inside\n * of a spe...
import net.minecraft.client.Minecraft; import net.minecraft.util.Session; import net.minecraftforge.client.event.ClientChatEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.apache.logging.log4j.Logger; import org.lwjgl.opengl.Display; import team.stiff.pomelo.impl.annotated.AnnotatedEventManager; import xyz.templecheats.templeclient.api.cape.CapeManager; import xyz.templecheats.templeclient.api.config.ShutdownHook; import xyz.templecheats.templeclient.api.config.rewrite.ConfigManager; import xyz.templecheats.templeclient.api.event.EventManager; import xyz.templecheats.templeclient.api.util.keys.key; import xyz.templecheats.templeclient.impl.command.CommandManager; import xyz.templecheats.templeclient.impl.gui.clickgui.ClickGuiManager; import xyz.templecheats.templeclient.impl.gui.clickgui.setting.SettingsManager; import xyz.templecheats.templeclient.impl.gui.font.FontUtils; import xyz.templecheats.templeclient.impl.gui.menu.GuiEventsListener; import xyz.templecheats.templeclient.impl.gui.ui.watermark; import java.lang.reflect.Field;
5,142
package xyz.templecheats.templeclient; @Mod(modid = TempleClient.MODID, name = TempleClient.NAME, version = TempleClient.VERSION) public class TempleClient { public static String name = "Temple Client 1.8.2"; public static final String MODID = "templeclient"; public static final String NAME = "Temple Client"; public static final String VERSION = "1.8.2"; public static AnnotatedEventManager eventBus; public static SettingsManager settingsManager; public static ModuleManager moduleManager; public static EventManager clientEventManager; public static CommandManager commandManager; public static ClickGuiManager clickGui; public static ConfigManager configManager; public static CapeManager capeManager; private static Logger logger; @EventHandler public void preInit(FMLPreInitializationEvent event) { Display.setTitle("Loading " + name); logger = event.getModLog(); } @EventHandler public void init(FMLInitializationEvent event) { Display.setTitle(name); MinecraftForge.EVENT_BUS.register(new TempleClient()); eventBus = new AnnotatedEventManager(); clientEventManager = new EventManager(); MinecraftForge.EVENT_BUS.register(clientEventManager); settingsManager = new SettingsManager(); (TempleClient.moduleManager = new ModuleManager()).initMods(); logger.info("Module Manager Loaded."); (TempleClient.commandManager = new CommandManager()).commandInit(); logger.info("Commands Loaded."); capeManager = new CapeManager(); MinecraftForge.EVENT_BUS.register(clientEventManager); MinecraftForge.EVENT_BUS.register(commandManager); MinecraftForge.EVENT_BUS.register(new key());
package xyz.templecheats.templeclient; @Mod(modid = TempleClient.MODID, name = TempleClient.NAME, version = TempleClient.VERSION) public class TempleClient { public static String name = "Temple Client 1.8.2"; public static final String MODID = "templeclient"; public static final String NAME = "Temple Client"; public static final String VERSION = "1.8.2"; public static AnnotatedEventManager eventBus; public static SettingsManager settingsManager; public static ModuleManager moduleManager; public static EventManager clientEventManager; public static CommandManager commandManager; public static ClickGuiManager clickGui; public static ConfigManager configManager; public static CapeManager capeManager; private static Logger logger; @EventHandler public void preInit(FMLPreInitializationEvent event) { Display.setTitle("Loading " + name); logger = event.getModLog(); } @EventHandler public void init(FMLInitializationEvent event) { Display.setTitle(name); MinecraftForge.EVENT_BUS.register(new TempleClient()); eventBus = new AnnotatedEventManager(); clientEventManager = new EventManager(); MinecraftForge.EVENT_BUS.register(clientEventManager); settingsManager = new SettingsManager(); (TempleClient.moduleManager = new ModuleManager()).initMods(); logger.info("Module Manager Loaded."); (TempleClient.commandManager = new CommandManager()).commandInit(); logger.info("Commands Loaded."); capeManager = new CapeManager(); MinecraftForge.EVENT_BUS.register(clientEventManager); MinecraftForge.EVENT_BUS.register(commandManager); MinecraftForge.EVENT_BUS.register(new key());
MinecraftForge.EVENT_BUS.register(new watermark());
11
2023-10-28 12:03:50+00:00
8k
PlayReissLP/Continuity
src/main/java/me/pepperbell/continuity/client/handler/ModelsAddedCallbackHandler.java
[ { "identifier": "ModelsAddedCallback", "path": "src/main/java/me/pepperbell/continuity/client/event/ModelsAddedCallback.java", "snippet": "public interface ModelsAddedCallback {\n\tEvent<ModelsAddedCallback> EVENT = EventFactory.createArrayBacked(ModelsAddedCallback.class,\n\t\t\tlisteners -> (modelLoad...
import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import com.mojang.datafixers.util.Pair; import it.unimi.dsi.fastutil.objects.Object2ObjectMap; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectArraySet; import it.unimi.dsi.fastutil.objects.ObjectIterator; import me.pepperbell.continuity.client.event.ModelsAddedCallback; import me.pepperbell.continuity.client.model.CTMUnbakedModel; import me.pepperbell.continuity.client.resource.CTMLoadingContainer; import me.pepperbell.continuity.client.resource.CTMPropertiesLoader; import me.pepperbell.continuity.client.util.VoidSet; import net.minecraft.block.BlockState; import net.minecraft.client.render.model.ModelLoader; import net.minecraft.client.render.model.UnbakedModel; import net.minecraft.client.util.ModelIdentifier; import net.minecraft.client.util.SpriteIdentifier; import net.minecraft.resource.ResourceManager; import net.minecraft.util.Identifier; import net.minecraft.util.profiler.Profiler;
4,914
package me.pepperbell.continuity.client.handler; public class ModelsAddedCallbackHandler implements ModelsAddedCallback { private final Map<ModelIdentifier, BlockState> modelId2StateMap; private final Map<ModelIdentifier, List<CTMLoadingContainer<?>>> modelId2ContainersMap; public ModelsAddedCallbackHandler(Map<ModelIdentifier, BlockState> modelId2StateMap, Map<ModelIdentifier, List<CTMLoadingContainer<?>>> modelId2ContainersMap) { this.modelId2StateMap = modelId2StateMap; this.modelId2ContainersMap = modelId2ContainersMap; } @Override public void onModelsAdded(ModelLoader modelLoader, ResourceManager resourceManager, Profiler profiler, Map<Identifier, UnbakedModel> unbakedModels, Map<Identifier, UnbakedModel> modelsToBake) { Object2ObjectOpenHashMap<Identifier, UnbakedModel> wrappedModels = new Object2ObjectOpenHashMap<>(); UnbakedModel missingModel = unbakedModels.get(ModelLoader.MISSING_ID); Function<Identifier, UnbakedModel> unbakedModelGetter = id -> { UnbakedModel model = unbakedModels.get(id); if (model == null) { return missingModel; } return model; }; VoidSet<Pair<String, String>> voidSet = VoidSet.get(); CollectionBasedConsumer<CTMLoadingContainer<?>> reusableConsumer = new CollectionBasedConsumer<>(); // Check which models should be wrapped for (Map.Entry<Identifier, UnbakedModel> entry : unbakedModels.entrySet()) { if (entry.getKey() instanceof ModelIdentifier) { ModelIdentifier id = (ModelIdentifier)entry.getKey(); // Only wrap final block state models if (isBlockStateModelId(id)) { UnbakedModel model = entry.getValue(); Collection<SpriteIdentifier> dependencies = model.getTextureDependencies(unbakedModelGetter, voidSet); List<CTMLoadingContainer<?>> containerList = modelId2ContainersMap.get(id); if (containerList == null) { containerList = CTMPropertiesLoader.getAllAffecting(dependencies); if (containerList == null) { continue; } } else { reusableConsumer.setCollection(containerList); CTMPropertiesLoader.consumeAllAffecting(dependencies, reusableConsumer); } containerList.sort(Collections.reverseOrder()); Set<CTMLoadingContainer<?>> multipassContainerSet = null; int amount = containerList.size(); for (int i = 0; i < amount; i++) { CTMLoadingContainer<?> container = containerList.get(i); Set<CTMLoadingContainer<?>> dependents = container.getRecursiveMultipassDependents(); if (dependents != null) { if (multipassContainerSet == null) { multipassContainerSet = new ObjectArraySet<>(); } multipassContainerSet.addAll(dependents); } } List<CTMLoadingContainer<?>> multipassContainerList = null; if (multipassContainerSet != null) { BlockState state = modelId2StateMap.get(id); for (CTMLoadingContainer<?> container : multipassContainerSet) { if (!container.getProperties().affectsBlockStates() || container.getProperties().affectsBlockState(state)) { if (multipassContainerList == null) { multipassContainerList = new ObjectArrayList<>(); } multipassContainerList.add(container); } } if (multipassContainerList != null) { multipassContainerList.sort(Collections.reverseOrder()); } }
package me.pepperbell.continuity.client.handler; public class ModelsAddedCallbackHandler implements ModelsAddedCallback { private final Map<ModelIdentifier, BlockState> modelId2StateMap; private final Map<ModelIdentifier, List<CTMLoadingContainer<?>>> modelId2ContainersMap; public ModelsAddedCallbackHandler(Map<ModelIdentifier, BlockState> modelId2StateMap, Map<ModelIdentifier, List<CTMLoadingContainer<?>>> modelId2ContainersMap) { this.modelId2StateMap = modelId2StateMap; this.modelId2ContainersMap = modelId2ContainersMap; } @Override public void onModelsAdded(ModelLoader modelLoader, ResourceManager resourceManager, Profiler profiler, Map<Identifier, UnbakedModel> unbakedModels, Map<Identifier, UnbakedModel> modelsToBake) { Object2ObjectOpenHashMap<Identifier, UnbakedModel> wrappedModels = new Object2ObjectOpenHashMap<>(); UnbakedModel missingModel = unbakedModels.get(ModelLoader.MISSING_ID); Function<Identifier, UnbakedModel> unbakedModelGetter = id -> { UnbakedModel model = unbakedModels.get(id); if (model == null) { return missingModel; } return model; }; VoidSet<Pair<String, String>> voidSet = VoidSet.get(); CollectionBasedConsumer<CTMLoadingContainer<?>> reusableConsumer = new CollectionBasedConsumer<>(); // Check which models should be wrapped for (Map.Entry<Identifier, UnbakedModel> entry : unbakedModels.entrySet()) { if (entry.getKey() instanceof ModelIdentifier) { ModelIdentifier id = (ModelIdentifier)entry.getKey(); // Only wrap final block state models if (isBlockStateModelId(id)) { UnbakedModel model = entry.getValue(); Collection<SpriteIdentifier> dependencies = model.getTextureDependencies(unbakedModelGetter, voidSet); List<CTMLoadingContainer<?>> containerList = modelId2ContainersMap.get(id); if (containerList == null) { containerList = CTMPropertiesLoader.getAllAffecting(dependencies); if (containerList == null) { continue; } } else { reusableConsumer.setCollection(containerList); CTMPropertiesLoader.consumeAllAffecting(dependencies, reusableConsumer); } containerList.sort(Collections.reverseOrder()); Set<CTMLoadingContainer<?>> multipassContainerSet = null; int amount = containerList.size(); for (int i = 0; i < amount; i++) { CTMLoadingContainer<?> container = containerList.get(i); Set<CTMLoadingContainer<?>> dependents = container.getRecursiveMultipassDependents(); if (dependents != null) { if (multipassContainerSet == null) { multipassContainerSet = new ObjectArraySet<>(); } multipassContainerSet.addAll(dependents); } } List<CTMLoadingContainer<?>> multipassContainerList = null; if (multipassContainerSet != null) { BlockState state = modelId2StateMap.get(id); for (CTMLoadingContainer<?> container : multipassContainerSet) { if (!container.getProperties().affectsBlockStates() || container.getProperties().affectsBlockState(state)) { if (multipassContainerList == null) { multipassContainerList = new ObjectArrayList<>(); } multipassContainerList.add(container); } } if (multipassContainerList != null) { multipassContainerList.sort(Collections.reverseOrder()); } }
wrappedModels.put(id, new CTMUnbakedModel(model, containerList, multipassContainerList));
1
2023-10-29 00:08:50+00:00
8k
BBMQyyds/Bright-Light-Building-Dreams
children/src/main/java/com/blbd/children/service/impl/FileServiceImpl.java
[ { "identifier": "Task", "path": "children/src/main/java/com/blbd/children/dao/entity/Task.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = false)\n@Accessors(chain = true)\n@TableName(\"task\")\n//@ApiModel(value=\"Task对象\", description=\"\")\npublic class Task implements Serializable {\n\n p...
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.blbd.children.dao.entity.Task; import com.blbd.children.dao.entity.TaskChild; import com.blbd.children.mapper.TaskChildMapper; import com.blbd.children.mapper.TaskMapper; import com.blbd.children.service.FileService; import com.blbd.children.service.TaskChildService; import com.blbd.children.service.TaskService; import com.blbd.children.utils.MinioUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.util.Date;
3,872
package com.blbd.children.service.impl; /** * @author sq ♥ovo♥ * @date 2023/11/8 - 21:33 */ @Service public class FileServiceImpl implements FileService { private static final Logger Runtimelogger = LoggerFactory.getLogger("RuntimeLogger"); @Autowired MinioUtil minioUtil; @Autowired private TaskChildService taskChildService; @Autowired private TaskMapper taskMapper; @Autowired private TaskChildMapper taskChildMapper; /** * 显示当前孩子当前任务(作业)的图片 */ @Override public void getTaskChildPhoto(String childId,String taskId, HttpServletResponse httpServletResponse) { String objectName = taskChildService.selectHomeworkPhoto(childId, taskId); objectName = objectName.substring(36, objectName.length()); System.out.println(objectName); if (objectName == null || objectName.equals("")){ Runtimelogger.error("FileServiceImpl.getTaskChildPhoto:获取作业图片失败"); } else { try { minioUtil.download(objectName,httpServletResponse); } catch (Exception e){ Runtimelogger.error("FileServiceImpl.getTaskChildPhoto:获取作业图片失败"); } } } /** * 下载当前孩子当前任务(作业)的图片 */ @Override public void downloadTaskChildPhoto(String childId, String taskId, HttpServletResponse httpServletResponse) { String objectName = taskChildService.selectHomeworkPhoto(childId, taskId); objectName = objectName.substring(36, objectName.length()); System.out.println(objectName); if (objectName == null || objectName.equals("")){ Runtimelogger.error("FileServiceImpl.getTaskChildPhoto:获取作业图片失败"); } else { try { // 设置响应头,告诉浏览器该文件需要下载 // httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + objectName); // 使用 minioUtil.download 下载图片 minioUtil.download(objectName,httpServletResponse); } catch (Exception e){ Runtimelogger.error("FileServiceImpl.getTaskChildPhoto:获取作业图片失败"); } } } /** * 当前孩子上传当前任务(作业)的图片 */ @Override public int uploadTaskChildPhoto(String childId,String taskId, MultipartFile file) { String objectName = minioUtil.upload(file); if (objectName == null || objectName.equals("")){ Runtimelogger.error("FileServiceImpl.uploadTaskChildPhoto:上传作业图片失败"); return -1; } else { Runtimelogger.info("FileServiceImpl.uploadTaskChildPhoto:上传作业图片成功");
package com.blbd.children.service.impl; /** * @author sq ♥ovo♥ * @date 2023/11/8 - 21:33 */ @Service public class FileServiceImpl implements FileService { private static final Logger Runtimelogger = LoggerFactory.getLogger("RuntimeLogger"); @Autowired MinioUtil minioUtil; @Autowired private TaskChildService taskChildService; @Autowired private TaskMapper taskMapper; @Autowired private TaskChildMapper taskChildMapper; /** * 显示当前孩子当前任务(作业)的图片 */ @Override public void getTaskChildPhoto(String childId,String taskId, HttpServletResponse httpServletResponse) { String objectName = taskChildService.selectHomeworkPhoto(childId, taskId); objectName = objectName.substring(36, objectName.length()); System.out.println(objectName); if (objectName == null || objectName.equals("")){ Runtimelogger.error("FileServiceImpl.getTaskChildPhoto:获取作业图片失败"); } else { try { minioUtil.download(objectName,httpServletResponse); } catch (Exception e){ Runtimelogger.error("FileServiceImpl.getTaskChildPhoto:获取作业图片失败"); } } } /** * 下载当前孩子当前任务(作业)的图片 */ @Override public void downloadTaskChildPhoto(String childId, String taskId, HttpServletResponse httpServletResponse) { String objectName = taskChildService.selectHomeworkPhoto(childId, taskId); objectName = objectName.substring(36, objectName.length()); System.out.println(objectName); if (objectName == null || objectName.equals("")){ Runtimelogger.error("FileServiceImpl.getTaskChildPhoto:获取作业图片失败"); } else { try { // 设置响应头,告诉浏览器该文件需要下载 // httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + objectName); // 使用 minioUtil.download 下载图片 minioUtil.download(objectName,httpServletResponse); } catch (Exception e){ Runtimelogger.error("FileServiceImpl.getTaskChildPhoto:获取作业图片失败"); } } } /** * 当前孩子上传当前任务(作业)的图片 */ @Override public int uploadTaskChildPhoto(String childId,String taskId, MultipartFile file) { String objectName = minioUtil.upload(file); if (objectName == null || objectName.equals("")){ Runtimelogger.error("FileServiceImpl.uploadTaskChildPhoto:上传作业图片失败"); return -1; } else { Runtimelogger.info("FileServiceImpl.uploadTaskChildPhoto:上传作业图片成功");
TaskChild taskChild = new TaskChild();
1
2023-10-30 12:49:28+00:00
8k
oghenevovwerho/yaa
src/main/java/yaa/semantic/handlers/TimesOp.java
[ { "identifier": "Times", "path": "src/main/java/yaa/ast/Times.java", "snippet": "public class Times extends BinaryStmt {\r\n public Times(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.$times(this);\r\n }\...
import yaa.ast.Times; import yaa.pojos.GlobalData; import yaa.pojos.YaaInfo; import static yaa.semantic.handlers.OpUtils.binaryOp;
5,024
package yaa.semantic.handlers; public class TimesOp { public static YaaInfo times(Times ctx) {
package yaa.semantic.handlers; public class TimesOp { public static YaaInfo times(Times ctx) {
return binaryOp(GlobalData.times_op_name, ctx);
1
2023-10-26 17:41:13+00:00
8k
echcz/web-service
src/main/java/cn/echcz/webservice/adapter/repository/JooqDocumentRepository.java
[ { "identifier": "DocumentRecord", "path": "src/main/jooq/cn/echcz/webservice/adapter/repository/tables/records/DocumentRecord.java", "snippet": "@SuppressWarnings({ \"all\", \"unchecked\", \"rawtypes\" })\npublic class DocumentRecord extends UpdatableRecordImpl<DocumentRecord> implements Record7<Long, S...
import cn.echcz.webservice.adapter.repository.tables.records.DocumentRecord; import cn.echcz.webservice.entity.DefaultUser; import cn.echcz.webservice.entity.Document; import cn.echcz.webservice.entity.DocumentInitParams; import cn.echcz.webservice.entity.User; import cn.echcz.webservice.usecase.repository.DocumentRepository; import cn.echcz.webservice.usecase.repository.QueryField; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import org.jooq.DSLContext; import org.jooq.Table; import org.jooq.TableField; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.time.LocalDateTime; import java.util.List;
4,188
package cn.echcz.webservice.adapter.repository; /** * 文档 JOOQ仓库 */ @Repository public class JooqDocumentRepository
package cn.echcz.webservice.adapter.repository; /** * 文档 JOOQ仓库 */ @Repository public class JooqDocumentRepository
extends AbstractJooqRepository<Long, Document, DocumentRecord,
2
2023-10-30 18:55:49+00:00
8k
tom5454/Toms-Peripherals
Forge/src/platform-shared/java/com/tom/peripherals/block/RedstonePortBlock.java
[ { "identifier": "Content", "path": "Forge/src/platform-shared/java/com/tom/peripherals/Content.java", "snippet": "public class Content {\n\tpublic static final GameObject<GPUBlock> gpu = blockWithItem(\"gpu\", GPUBlock::new);\n\tpublic static final GameObject<MonitorBlock> monitor = blockWithItem(\"moni...
import java.util.List; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import com.tom.peripherals.Content; import com.tom.peripherals.block.entity.RedstonePortBlockEntity; import com.tom.peripherals.client.ClientUtil; import com.tom.peripherals.util.TickerUtil; import dan200.computercraft.shared.common.IBundledRedstoneBlock;
3,889
package com.tom.peripherals.block; public class RedstonePortBlock extends Block implements EntityBlock, IForgeBlock, IBundledRedstoneBlock { public RedstonePortBlock() { super(Block.Properties.of().mapColor(DyeColor.RED).sound(SoundType.METAL).strength(5).isRedstoneConductor((a, b, c) -> false)); } @Override public BlockEntity newBlockEntity(BlockPos p_153215_, BlockState p_153216_) {
package com.tom.peripherals.block; public class RedstonePortBlock extends Block implements EntityBlock, IForgeBlock, IBundledRedstoneBlock { public RedstonePortBlock() { super(Block.Properties.of().mapColor(DyeColor.RED).sound(SoundType.METAL).strength(5).isRedstoneConductor((a, b, c) -> false)); } @Override public BlockEntity newBlockEntity(BlockPos p_153215_, BlockState p_153216_) {
return Content.redstonePortBE.get().create(p_153215_, p_153216_);
0
2023-10-30 17:05:11+00:00
8k
unloggedio/intellij-java-plugin
src/main/java/com/insidious/plugin/util/DiffUtils.java
[ { "identifier": "AgentCommandResponse", "path": "src/main/java/com/insidious/plugin/agent/AgentCommandResponse.java", "snippet": "public class AgentCommandResponse<T> {\n private T methodReturnValue;\n private ResponseType responseType;\n private String responseClassName;\n private String me...
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.insidious.plugin.agent.AgentCommandResponse; import com.insidious.plugin.agent.ResponseType; import com.insidious.plugin.assertions.*; import com.insidious.plugin.pojo.atomic.StoredCandidate; import com.insidious.plugin.ui.methodscope.DiffResultType; import com.insidious.plugin.ui.methodscope.DifferenceInstance; import com.insidious.plugin.ui.methodscope.DifferenceResult; import com.intellij.openapi.diagnostic.Logger; import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; import static com.insidious.plugin.util.ParameterUtils.processResponseForFloatAndDoubleTypes;
4,230
package com.insidious.plugin.util; public class DiffUtils { static final private Logger logger = LoggerUtil.getInstance(DiffUtils.class); static final private ObjectMapper objectMapper = ObjectMapperInstance.getInstance(); static public DifferenceResult calculateDifferences( StoredCandidate testCandidateMetadata, AgentCommandResponse<String> agentCommandResponse ) { AtomicAssertion testAssertions = testCandidateMetadata.getTestAssertions();
package com.insidious.plugin.util; public class DiffUtils { static final private Logger logger = LoggerUtil.getInstance(DiffUtils.class); static final private ObjectMapper objectMapper = ObjectMapperInstance.getInstance(); static public DifferenceResult calculateDifferences( StoredCandidate testCandidateMetadata, AgentCommandResponse<String> agentCommandResponse ) { AtomicAssertion testAssertions = testCandidateMetadata.getTestAssertions();
String returnValueAsString = processResponseForFloatAndDoubleTypes(
6
2023-10-31 09:07:46+00:00
8k