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
ProfessorFichte/More-RPG-Classes
src/main/java/net/more_rpg_classes/MRPGCMod.java
[ { "identifier": "MoreParticles", "path": "src/main/java/net/more_rpg_classes/client/particle/MoreParticles.java", "snippet": "public class MoreParticles {\n public static final DefaultParticleType IGNI_SIGN = FabricParticleTypes.simple();\n public static final DefaultParticleType AARD_SIGN = Fabri...
import net.fabricmc.api.ModInitializer; import net.more_rpg_classes.client.particle.MoreParticles; import net.more_rpg_classes.custom.custom_spells.CustomSpells; import net.more_rpg_classes.effect.MRPGCEffects; import net.more_rpg_classes.entity.attribute.MRPGCEntityAttributes; import net.more_rpg_classes.item.MRPGCBooks; import net.more_rpg_classes.item.MRPGCGroup; import net.more_rpg_classes.item.MRPGCItems; import net.more_rpg_classes.sounds.ModSounds; import net.more_rpg_classes.util.MRPGCLootTableChestModifiers; import net.more_rpg_classes.util.MRPGCLootTableEntityModifiers; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
11,401
package net.more_rpg_classes; public class MRPGCMod implements ModInitializer { public static final String MOD_ID = "more_rpg_classes"; public static final Logger LOGGER = LoggerFactory.getLogger("more_rpg_classes"); @Override public void onInitialize() {
package net.more_rpg_classes; public class MRPGCMod implements ModInitializer { public static final String MOD_ID = "more_rpg_classes"; public static final Logger LOGGER = LoggerFactory.getLogger("more_rpg_classes"); @Override public void onInitialize() {
MRPGCItems.registerModItems();
6
2023-10-14 12:44:07+00:00
16k
5152Alotobots/2024_Crescendo_Preseason
src/main/java/frc/robot/chargedup/commands/auto/doubleelement/Auto_middleblueconeleftescape_Cmd.java
[ { "identifier": "Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj", "path": "src/main/java/frc/robot/library/drivetrains/commands/Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj.java", "snippet": "public class Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj extends CommandBase {\n /** Creates a new Cmd_SubSys_Dr...
import edu.wpi.first.wpilibj.DriverStation.Alliance; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.ParallelCommandGroup; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import frc.robot.library.drivetrains.commands.Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj; import frc.robot.chargedup.subsystems.arm.SubSys_Arm; import frc.robot.chargedup.subsystems.arm.commands.Cmd_SubSys_Arm_RotateAndExtend; import frc.robot.chargedup.subsystems.hand.SubSys_Hand; import frc.robot.library.drivetrains.SubSys_DriveTrain; import frc.robot.library.gyroscopes.pigeon2.SubSys_PigeonGyro;
13,392
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. /* _____ _ / ____| /\ | | | (___ ___ __ _ _ __ / \ _ __ _ __ _ __ _____ _____ __| | \___ \ / _ \/ _` | '_ \ / /\ \ | '_ \| '_ \| '__/ _ \ \ / / _ \/ _` | ____) | __/ (_| | | | | / ____ \| |_) | |_) | | | (_) \ V / __/ (_| | |_____/ \___|\__,_|_| |_| /_/ \_\ .__/| .__/|_| \___/ \_/ \___|\__,_| | | | | |_| |_| */ package frc.robot.chargedup.commands.auto.doubleelement; /** * *Link For PathPlaner * * https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e65ac68f1d_0_48 */ public class Auto_middleblueconeleftescape_Cmd extends SequentialCommandGroup { private final SubSys_DriveTrain m_DriveTrain; private final SubSys_PigeonGyro m_pigeonGyro; private final SubSys_Arm m_Arm;
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. /* _____ _ / ____| /\ | | | (___ ___ __ _ _ __ / \ _ __ _ __ _ __ _____ _____ __| | \___ \ / _ \/ _` | '_ \ / /\ \ | '_ \| '_ \| '__/ _ \ \ / / _ \/ _` | ____) | __/ (_| | | | | / ____ \| |_) | |_) | | | (_) \ V / __/ (_| | |_____/ \___|\__,_|_| |_| /_/ \_\ .__/| .__/|_| \___/ \_/ \___|\__,_| | | | | |_| |_| */ package frc.robot.chargedup.commands.auto.doubleelement; /** * *Link For PathPlaner * * https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e65ac68f1d_0_48 */ public class Auto_middleblueconeleftescape_Cmd extends SequentialCommandGroup { private final SubSys_DriveTrain m_DriveTrain; private final SubSys_PigeonGyro m_pigeonGyro; private final SubSys_Arm m_Arm;
private final SubSys_Hand m_Hand;
3
2023-10-09 00:27:11+00:00
16k
nexus3a/monitor-remote-agent
src/main/java/com/monitor/agent/server/handler/AckHandler.java
[ { "identifier": "FileState", "path": "src/main/java/com/monitor/agent/server/FileState.java", "snippet": "public class FileState {\n\n @JsonIgnore\n private File file;\n private String directory;\n private String fileName;\n @JsonIgnore\n private long lastModified;\n @JsonIgnore\n ...
import com.monitor.agent.server.FileState; import com.monitor.agent.server.FileWatcher; import com.monitor.agent.server.Registrar; import com.monitor.agent.server.Section; import com.monitor.agent.server.Server; import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.router.RouterNanoHTTPD; import java.util.Collection; import java.util.Map;
11,677
package com.monitor.agent.server.handler; /* * Copyright 2022 Aleksei Andreev * * 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. * */ public class AckHandler extends DefaultResponder { @Override @SuppressWarnings("UseSpecificCatch") public NanoHTTPD.Response get( RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { super.get(uriResource, urlParams, session); Server server = uriResource.initParameter(Server.class); server.waitForUnpause(); // ожидания снятия сервера с паузы try { RequestParameters parameters = getParameters(); // получаем секцию, в пределах которой нужно подтввердить получение данных // String sectionName = (String) parameters.get("section", null); Section section = Section.byName(sectionName); Object sectionLock = section == null ? server : section; synchronized (sectionLock) {
package com.monitor.agent.server.handler; /* * Copyright 2022 Aleksei Andreev * * 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. * */ public class AckHandler extends DefaultResponder { @Override @SuppressWarnings("UseSpecificCatch") public NanoHTTPD.Response get( RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { super.get(uriResource, urlParams, session); Server server = uriResource.initParameter(Server.class); server.waitForUnpause(); // ожидания снятия сервера с паузы try { RequestParameters parameters = getParameters(); // получаем секцию, в пределах которой нужно подтввердить получение данных // String sectionName = (String) parameters.get("section", null); Section section = Section.byName(sectionName); Object sectionLock = section == null ? server : section; synchronized (sectionLock) {
Collection<FileWatcher> watchers = server.getWatchers(Section.byName(sectionName));
1
2023-10-11 20:25:12+00:00
16k
mhaupt/basicode
src/main/java/de/haupz/basicode/ast/GotoNode.java
[ { "identifier": "InterpreterState", "path": "src/main/java/de/haupz/basicode/interpreter/InterpreterState.java", "snippet": "public class InterpreterState {\n\n /**\n * The root node of the program whose state this instance represents.\n */\n private final ProgramNode program;\n\n /**\n...
import de.haupz.basicode.interpreter.InterpreterState; import de.haupz.basicode.subroutines.Subroutines;
12,584
package de.haupz.basicode.ast; /** * <p>{@code GOTO}. The implementation performs a {@linkplain InterpreterState#requestLineJump() jump} to the * {@linkplain InterpreterState#setLineJumpTarget(int)} target line.</p> * * <p>In case the target line number is less than 1000, a jump to a {@linkplain Subroutines subroutine} is executed * instead of the normal {@code GOTO}.</p> */ public class GotoNode extends StatementNode { private final int target; public GotoNode(int target) { this.target = target; } @Override public void run(InterpreterState state) { if (target < 1000) {
package de.haupz.basicode.ast; /** * <p>{@code GOTO}. The implementation performs a {@linkplain InterpreterState#requestLineJump() jump} to the * {@linkplain InterpreterState#setLineJumpTarget(int)} target line.</p> * * <p>In case the target line number is less than 1000, a jump to a {@linkplain Subroutines subroutine} is executed * instead of the normal {@code GOTO}.</p> */ public class GotoNode extends StatementNode { private final int target; public GotoNode(int target) { this.target = target; } @Override public void run(InterpreterState state) { if (target < 1000) {
Subroutines.runGoto(target, state);
1
2023-10-14 12:20:59+00:00
16k
giteecode/bookmanage2-public
nhXJH-system/src/main/java/com/nhXJH/system/service/impl/SysRoleServiceImpl.java
[ { "identifier": "UserConstants", "path": "nhXJH-common/src/main/java/com/nhXJH/common/constant/UserConstants.java", "snippet": "public class UserConstants {\n /**\n * 平台内系统用户的唯一标志\n */\n public static final String SYS_USER = \"SYS_USER\";\n\n /** 正常状态 */\n public static final String ...
import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.nhXJH.common.annotation.DataScope; import com.nhXJH.common.constant.UserConstants; import com.nhXJH.common.core.domain.entity.SysRole; import com.nhXJH.common.core.domain.entity.SysUser; import com.nhXJH.common.exception.ServiceException; import com.nhXJH.common.utils.SecurityUtils; import com.nhXJH.common.utils.StringUtils; import com.nhXJH.common.utils.spring.SpringUtils; import com.nhXJH.system.domain.SysRoleDept; import com.nhXJH.system.domain.SysRoleMenu; import com.nhXJH.system.domain.SysUserRole; import com.nhXJH.system.mapper.SysRoleDeptMapper; import com.nhXJH.system.mapper.SysRoleMapper; import com.nhXJH.system.mapper.SysRoleMenuMapper; import com.nhXJH.system.mapper.SysUserRoleMapper; import com.nhXJH.system.service.ISysRoleService;
13,864
package com.nhXJH.system.service.impl; /** * 角色 业务层处理 * * @author nhXJH */ @Service public class SysRoleServiceImpl implements ISysRoleService { @Autowired private SysRoleMapper roleMapper; @Autowired private SysRoleMenuMapper roleMenuMapper; @Autowired private SysUserRoleMapper userRoleMapper; @Autowired private SysRoleDeptMapper roleDeptMapper; /** * 根据条件分页查询角色数据 * * @param role 角色信息 * @return 角色数据集合信息 */ @Override @DataScope(deptAlias = "d")
package com.nhXJH.system.service.impl; /** * 角色 业务层处理 * * @author nhXJH */ @Service public class SysRoleServiceImpl implements ISysRoleService { @Autowired private SysRoleMapper roleMapper; @Autowired private SysRoleMenuMapper roleMenuMapper; @Autowired private SysUserRoleMapper userRoleMapper; @Autowired private SysRoleDeptMapper roleDeptMapper; /** * 根据条件分页查询角色数据 * * @param role 角色信息 * @return 角色数据集合信息 */ @Override @DataScope(deptAlias = "d")
public List<SysRole> selectRoleList(SysRole role) {
1
2023-10-13 07:19:20+00:00
16k
M-D-Team/ait-fabric-1.20.1
src/main/java/mdteam/ait/client/registry/exterior/impl/classic/ClientClassicBoxVariant.java
[ { "identifier": "AITMod", "path": "src/main/java/mdteam/ait/AITMod.java", "snippet": "public class AITMod implements ModInitializer {\n public static final String MOD_ID = \"ait\";\n public static final Logger LOGGER = LoggerFactory.getLogger(\"ait\");\n public static final Boolean DEBUG = true...
import mdteam.ait.AITMod; import mdteam.ait.client.models.exteriors.ClassicExteriorModel; import mdteam.ait.client.models.exteriors.ExteriorModel; import mdteam.ait.client.models.exteriors.PoliceBoxModel; import mdteam.ait.client.registry.exterior.ClientExteriorVariantSchema; import net.minecraft.util.Identifier;
13,062
package mdteam.ait.client.registry.exterior.impl.classic; // a useful class for creating tardim variants as they all have the same filepath you know public abstract class ClientClassicBoxVariant extends ClientExteriorVariantSchema { private final String name; protected static final String TEXTURE_PATH = "textures/blockentities/exteriors/classic/classic_"; protected ClientClassicBoxVariant(String name) { super(new Identifier(AITMod.MOD_ID, "exterior/classic/" + name)); this.name = name; } @Override
package mdteam.ait.client.registry.exterior.impl.classic; // a useful class for creating tardim variants as they all have the same filepath you know public abstract class ClientClassicBoxVariant extends ClientExteriorVariantSchema { private final String name; protected static final String TEXTURE_PATH = "textures/blockentities/exteriors/classic/classic_"; protected ClientClassicBoxVariant(String name) { super(new Identifier(AITMod.MOD_ID, "exterior/classic/" + name)); this.name = name; } @Override
public ExteriorModel model() {
2
2023-10-08 00:38:53+00:00
16k
jianjian3219/044_bookmanage2-public
nhXJH-framework/src/main/java/com/nhXJH/framework/web/service/SysLoginService.java
[ { "identifier": "Constants", "path": "nhXJH-common/src/main/java/com/nhXJH/common/constant/Constants.java", "snippet": "public class Constants {\n /**\n * UTF-8 字符集\n */\n public static final String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n public static final String GBK =...
import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import com.nhXJH.common.constant.Constants; import com.nhXJH.common.core.domain.entity.SysUser; import com.nhXJH.common.core.domain.model.LoginUser; import com.nhXJH.common.core.redis.RedisCache; import com.nhXJH.common.exception.ServiceException; import com.nhXJH.common.exception.user.CaptchaException; import com.nhXJH.common.exception.user.CaptchaExpireException; import com.nhXJH.common.exception.user.UserPasswordNotMatchException; import com.nhXJH.common.utils.DateUtils; import com.nhXJH.common.utils.MessageUtils; import com.nhXJH.common.utils.ServletUtils; import com.nhXJH.common.utils.ip.IpUtils; import com.nhXJH.framework.manager.AsyncManager; import com.nhXJH.framework.manager.factory.AsyncFactory; import com.nhXJH.system.service.ISysConfigService; import com.nhXJH.system.service.ISysUserService;
13,769
package com.nhXJH.framework.web.service; /** * 登录校验方法 * * @author nhXJH */ @Component public class SysLoginService { @Autowired private TokenService tokenService; @Resource private AuthenticationManager authenticationManager; @Autowired private RedisCache redisCache; @Autowired private ISysUserService userService; @Autowired private ISysConfigService configService; /** * 登录验证 * * @param username 用户名 * @param password 密码 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public String login(String username, String password, String code, String uuid) { boolean captchaOnOff = configService.selectCaptchaOnOff(); // 验证码开关 if (captchaOnOff) { validateCaptcha(username, code, uuid); } // 用户验证 Authentication authentication = null; try { // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(username, password)); } catch (Exception e) { if (e instanceof BadCredentialsException) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); throw new UserPasswordNotMatchException(); } else { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage())); throw new ServiceException(e.getMessage()); } } AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"))); LoginUser loginUser = (LoginUser) authentication.getPrincipal(); recordLoginInfo(loginUser.getUserId()); // 生成token return tokenService.createToken(loginUser); } /** * 校验验证码 * * @param username 用户名 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public void validateCaptcha(String username, String code, String uuid) { String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid; String captcha = redisCache.getCacheObject(verifyKey); redisCache.deleteObject(verifyKey); if (captcha == null) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"))); throw new CaptchaExpireException(); } if (!code.equalsIgnoreCase(captcha)) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); throw new CaptchaException(); } } /** * 记录登录信息 * * @param userId 用户ID */ public void recordLoginInfo(Long userId) { SysUser sysUser = new SysUser(); sysUser.setUserId(userId); sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
package com.nhXJH.framework.web.service; /** * 登录校验方法 * * @author nhXJH */ @Component public class SysLoginService { @Autowired private TokenService tokenService; @Resource private AuthenticationManager authenticationManager; @Autowired private RedisCache redisCache; @Autowired private ISysUserService userService; @Autowired private ISysConfigService configService; /** * 登录验证 * * @param username 用户名 * @param password 密码 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public String login(String username, String password, String code, String uuid) { boolean captchaOnOff = configService.selectCaptchaOnOff(); // 验证码开关 if (captchaOnOff) { validateCaptcha(username, code, uuid); } // 用户验证 Authentication authentication = null; try { // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(username, password)); } catch (Exception e) { if (e instanceof BadCredentialsException) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); throw new UserPasswordNotMatchException(); } else { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage())); throw new ServiceException(e.getMessage()); } } AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"))); LoginUser loginUser = (LoginUser) authentication.getPrincipal(); recordLoginInfo(loginUser.getUserId()); // 生成token return tokenService.createToken(loginUser); } /** * 校验验证码 * * @param username 用户名 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public void validateCaptcha(String username, String code, String uuid) { String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid; String captcha = redisCache.getCacheObject(verifyKey); redisCache.deleteObject(verifyKey); if (captcha == null) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"))); throw new CaptchaExpireException(); } if (!code.equalsIgnoreCase(captcha)) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); throw new CaptchaException(); } } /** * 记录登录信息 * * @param userId 用户ID */ public void recordLoginInfo(Long userId) { SysUser sysUser = new SysUser(); sysUser.setUserId(userId); sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
sysUser.setLoginDate(DateUtils.getNowDate());
8
2023-10-14 04:57:42+00:00
16k
DrMango14/Create-Design-n-Decor
src/main/java/com/mangomilk/design_decor/registry/MmbBlockEntities.java
[ { "identifier": "BlueContainerBlockEntity", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/blue/BlueContainerBlockEntity.java", "snippet": "public class BlueContainerBlockEntity extends ItemVaultBlockEntity implements IMultiBlockEntityContainer.Inventory {\n\n\tprotected LazyOptiona...
import com.mangomilk.design_decor.blocks.containers.blue.BlueContainerBlockEntity; import com.mangomilk.design_decor.blocks.containers.green.GreenContainerBlockEntity; import com.mangomilk.design_decor.blocks.containers.red.RedContainerBlockEntity; import com.mangomilk.design_decor.blocks.crushing_wheels.MmbCrushingWheelBlockEntity; import com.mangomilk.design_decor.blocks.crushing_wheels.MmbCrushingWheelControllerBlockEntity; import com.mangomilk.design_decor.blocks.gas_tank.GasTankBlockEntity; import com.mangomilk.design_decor.blocks.industrial_gear.IndustrialGearInstance; import com.mangomilk.design_decor.blocks.industrial_gear.IndustrialGearRenderer; import com.mangomilk.design_decor.blocks.millstone.DecoMillStoneBlockEntity; import com.mangomilk.design_decor.blocks.millstone.instance.*; import com.mangomilk.design_decor.blocks.millstone.renderer.*; import com.simibubi.create.AllBlocks; import com.simibubi.create.content.kinetics.base.CutoutRotatingInstance; import com.simibubi.create.content.kinetics.base.KineticBlockEntityRenderer; import com.simibubi.create.content.kinetics.simpleRelays.BracketedKineticBlockEntity; import com.tterrag.registrate.util.entry.BlockEntityEntry; import static com.mangomilk.design_decor.CreateMMBuilding.REGISTRATE;
13,849
package com.mangomilk.design_decor.registry; public class MmbBlockEntities { public static final BlockEntityEntry<BracketedKineticBlockEntity> BRACKETED_KINETIC = REGISTRATE .blockEntity("simple_kinetic", BracketedKineticBlockEntity::new) .instance(() -> IndustrialGearInstance::new, false) .validBlocks(MmbBlocks.COGWHEEL, MmbBlocks.LARGE_COGWHEEL)
package com.mangomilk.design_decor.registry; public class MmbBlockEntities { public static final BlockEntityEntry<BracketedKineticBlockEntity> BRACKETED_KINETIC = REGISTRATE .blockEntity("simple_kinetic", BracketedKineticBlockEntity::new) .instance(() -> IndustrialGearInstance::new, false) .validBlocks(MmbBlocks.COGWHEEL, MmbBlocks.LARGE_COGWHEEL)
.renderer(() -> IndustrialGearRenderer::new)
7
2023-10-14 21:51:49+00:00
16k
giteecode/supermarket2Public
src/main/java/com/ruoyi/framework/web/controller/BaseController.java
[ { "identifier": "DateUtils", "path": "src/main/java/com/ruoyi/common/utils/DateUtils.java", "snippet": "public class DateUtils extends org.apache.commons.lang3.time.DateUtils\n{\n public static String YYYY = \"yyyy\";\n\n public static String YYYY_MM = \"yyyy-MM\";\n\n public static String YYYY...
import java.beans.PropertyEditorSupport; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.PageUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.security.ShiroUtils; import com.ruoyi.common.utils.sql.SqlUtil; import com.ruoyi.framework.web.domain.AjaxResult; import com.ruoyi.framework.web.domain.AjaxResult.Type; import com.ruoyi.framework.web.page.PageDomain; import com.ruoyi.framework.web.page.TableDataInfo; import com.ruoyi.framework.web.page.TableSupport; import com.ruoyi.project.system.user.domain.User;
11,825
package com.ruoyi.framework.web.controller; /** * web层通用数据处理 * * @author ruoyi */ public class BaseController { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 将前台传递过来的日期格式的字符串,自动转化为Date类型 */ @InitBinder public void initBinder(WebDataBinder binder) { // Date 类型转换 binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { @Override public void setAsText(String text) { setValue(DateUtils.parseDate(text)); } }); } /** * 设置请求分页数据 */ protected void startPage() { PageUtils.startPage(); } /** * 设置请求排序数据 */ protected void startOrderBy() { PageDomain pageDomain = TableSupport.buildPageRequest(); if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) { String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); PageHelper.orderBy(orderBy); } } /** * 响应请求分页数据 */ @SuppressWarnings({ "rawtypes", "unchecked" })
package com.ruoyi.framework.web.controller; /** * web层通用数据处理 * * @author ruoyi */ public class BaseController { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 将前台传递过来的日期格式的字符串,自动转化为Date类型 */ @InitBinder public void initBinder(WebDataBinder binder) { // Date 类型转换 binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { @Override public void setAsText(String text) { setValue(DateUtils.parseDate(text)); } }); } /** * 设置请求分页数据 */ protected void startPage() { PageUtils.startPage(); } /** * 设置请求排序数据 */ protected void startOrderBy() { PageDomain pageDomain = TableSupport.buildPageRequest(); if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) { String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); PageHelper.orderBy(orderBy); } } /** * 响应请求分页数据 */ @SuppressWarnings({ "rawtypes", "unchecked" })
protected TableDataInfo getDataTable(List<?> list)
8
2023-10-14 02:27:47+00:00
16k
davidsaltacc/shadowclient
src/main/java/net/shadowclient/main/SCMain.java
[ { "identifier": "CommandManager", "path": "src/main/java/net/shadowclient/main/command/CommandManager.java", "snippet": "public class CommandManager {\n public static final Map<String, Command> commands = new HashMap<>();\n\n public static void registerCommands() {\n registerCommand(new Hel...
import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.ModContainer; import net.fabricmc.loader.api.metadata.ModMetadata; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.option.KeyBinding; import net.minecraft.client.util.InputUtil; import net.shadowclient.main.command.CommandManager; import net.shadowclient.main.config.Config; import net.shadowclient.main.config.SCSettings; import net.shadowclient.main.module.ModuleManager; import net.shadowclient.main.ui.clickgui.ClickGUI; import net.shadowclient.main.ui.clickgui.Frame; import net.shadowclient.main.ui.clickgui.MainClickGUI; import net.shadowclient.main.ui.clickgui.ModuleButton; import net.shadowclient.main.ui.clickgui.settings.scsettings.components.SCBoolSetting; import net.shadowclient.main.ui.clickgui.text.TextField; import net.shadowclient.main.ui.notifications.Notification; import net.shadowclient.main.ui.notifications.NotificationsManager; import net.shadowclient.main.util.ChatUtils; import net.shadowclient.main.util.JavaUtils; import net.shadowclient.mixin.KeyBindingAccessor; import org.jetbrains.annotations.Nullable; import org.lwjgl.glfw.GLFW; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import java.util.stream.Stream;
13,063
package net.shadowclient.main; public class SCMain { public static final String ClientModId = "shadowclient"; public static final String ClientName = "ShadowClient"; public static final String ClientVersion = "0.2.0"; public static final String ClientCommandPrefix = "sc/"; public static MainClickGUI clickGui; public static ClickGUI settingsGui; public static final MinecraftClient mc = MinecraftClient.getInstance(); public static final Logger logger = LoggerFactory.getLogger(ClientName); public static boolean configDeleted = false; public static List<KeyBinding> keyBindings = new ArrayList<>(); public static KeyBinding ToggleGUIKeyBinding; public static void init() { try { info("Starting " + ClientName + " " + ClientVersion); ToggleGUIKeyBinding = registerKeyBinding( new KeyBinding( "key." + ClientModId + ".togglegui", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_RIGHT_SHIFT, "category." + ClientModId + ".clientcategory" )); CommandManager.registerCommands(); ModuleManager.registerModules(); clickGui = new MainClickGUI(); settingsGui = new ClickGUI("Settings"); initSettingsScreen(settingsGui); Config.loadConfig(); checkConflictingMods(); Runtime.getRuntime().addShutdownHook(new Thread(SCMain::closed)); info("Finished " + ClientName + " initialization"); } catch (Exception e) { error(JavaUtils.stackTraceFromThrowable(e)); } } public static void closed() { Thread.currentThread().setName("ShadowClient Shutdown"); if (!configDeleted) { Config.saveConfig(); } } public static KeyBinding registerKeyBinding(KeyBinding bind) { keyBindings.add(bind); addKeybindCategory(bind.getCategory()); return bind; } public static void addKeybindCategory(String category) { Map<String, Integer> map = KeyBindingAccessor.getCategoryMap(); if (map.containsKey(category)) { return; } Optional<Integer> largest = map.values().stream().max(Integer::compareTo); int largestInt = largest.orElse(0); map.put(category, largestInt + 1); } public static void initSettingsScreen(ClickGUI gui) { int offset = 5; Frame settingsframe = new Frame("Settings", offset, 5, 100, 14); gui.frames.add(settingsframe); offset += 105; Frame hideframe = new Frame("Options", offset, 5, 100, 14); gui.frames.add(hideframe); hideframe.children.add(new ModuleButton("hidesettings", hideframe, 14)); hideframe.children.add(new ModuleButton("loaddata", hideframe, 28)); hideframe.children.add(new ModuleButton("savedata", hideframe, 42)); hideframe.children.add(new ModuleButton("resetdata", hideframe, 56)); offset += 105;
package net.shadowclient.main; public class SCMain { public static final String ClientModId = "shadowclient"; public static final String ClientName = "ShadowClient"; public static final String ClientVersion = "0.2.0"; public static final String ClientCommandPrefix = "sc/"; public static MainClickGUI clickGui; public static ClickGUI settingsGui; public static final MinecraftClient mc = MinecraftClient.getInstance(); public static final Logger logger = LoggerFactory.getLogger(ClientName); public static boolean configDeleted = false; public static List<KeyBinding> keyBindings = new ArrayList<>(); public static KeyBinding ToggleGUIKeyBinding; public static void init() { try { info("Starting " + ClientName + " " + ClientVersion); ToggleGUIKeyBinding = registerKeyBinding( new KeyBinding( "key." + ClientModId + ".togglegui", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_RIGHT_SHIFT, "category." + ClientModId + ".clientcategory" )); CommandManager.registerCommands(); ModuleManager.registerModules(); clickGui = new MainClickGUI(); settingsGui = new ClickGUI("Settings"); initSettingsScreen(settingsGui); Config.loadConfig(); checkConflictingMods(); Runtime.getRuntime().addShutdownHook(new Thread(SCMain::closed)); info("Finished " + ClientName + " initialization"); } catch (Exception e) { error(JavaUtils.stackTraceFromThrowable(e)); } } public static void closed() { Thread.currentThread().setName("ShadowClient Shutdown"); if (!configDeleted) { Config.saveConfig(); } } public static KeyBinding registerKeyBinding(KeyBinding bind) { keyBindings.add(bind); addKeybindCategory(bind.getCategory()); return bind; } public static void addKeybindCategory(String category) { Map<String, Integer> map = KeyBindingAccessor.getCategoryMap(); if (map.containsKey(category)) { return; } Optional<Integer> largest = map.values().stream().max(Integer::compareTo); int largestInt = largest.orElse(0); map.put(category, largestInt + 1); } public static void initSettingsScreen(ClickGUI gui) { int offset = 5; Frame settingsframe = new Frame("Settings", offset, 5, 100, 14); gui.frames.add(settingsframe); offset += 105; Frame hideframe = new Frame("Options", offset, 5, 100, 14); gui.frames.add(hideframe); hideframe.children.add(new ModuleButton("hidesettings", hideframe, 14)); hideframe.children.add(new ModuleButton("loaddata", hideframe, 28)); hideframe.children.add(new ModuleButton("savedata", hideframe, 42)); hideframe.children.add(new ModuleButton("resetdata", hideframe, 56)); offset += 105;
settingsframe.children.add(new SCBoolSetting(SCSettings.VanillaSpoof, settingsframe, 14));
8
2023-10-07 06:55:12+00:00
16k
lukas-mb/ABAP-SQL-Beautifier
ABAP SQL Beautifier/src/com/abap/sql/beautifier/StatementProcessor.java
[ { "identifier": "PreferenceConstants", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/preferences/PreferenceConstants.java", "snippet": "public class PreferenceConstants {\n\n\tpublic static final String ALLIGN_OPERS = \"ALLIGN_OPERS\";\n\n\tpublic static final String COMBINE_CHAR_LIMIT = \"CO...
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext; import org.eclipse.jface.text.quickassist.IQuickAssistProcessor; import org.eclipse.jface.text.source.Annotation; import org.eclipse.ui.PlatformUI; import com.abap.sql.beautifier.preferences.PreferenceConstants; import com.abap.sql.beautifier.settings.AbstractSqlSetting; import com.abap.sql.beautifier.settings.CommentsAdder; import com.abap.sql.beautifier.settings.ConditionAligner; import com.abap.sql.beautifier.settings.JoinCombiner; import com.abap.sql.beautifier.settings.OperatorUnifier; import com.abap.sql.beautifier.settings.Restructor; import com.abap.sql.beautifier.settings.SelectCombiner; import com.abap.sql.beautifier.settings.SpaceAdder; import com.abap.sql.beautifier.statement.AbapSql; import com.abap.sql.beautifier.utility.BeautifierIcon; import com.abap.sql.beautifier.utility.Utility; import com.sap.adt.tools.abapsource.ui.AbapSourceUi; import com.sap.adt.tools.abapsource.ui.IAbapSourceUi; import com.sap.adt.tools.abapsource.ui.sources.IAbapSourceScannerServices; import com.sap.adt.tools.abapsource.ui.sources.IAbapSourceScannerServices.Token; import com.sap.adt.tools.abapsource.ui.sources.editors.AbapSourcePage;
13,811
package com.abap.sql.beautifier; public class StatementProcessor implements IQuickAssistProcessor { public IDocument document = null; public IAbapSourceScannerServices scannerServices = null; public AbapSourcePage sourcePage; public IAbapSourceUi sourceUi = null; private String sql = ""; private String code; private int diff; private int end; private int offsetCursor; private int startReplacement; private boolean oldSyntax = true; private String beautifyStatement(String inputCode) { // otherwise the whole beautifier would not work inputCode = inputCode.toUpperCase(); AbapSql abapSql = new AbapSql(inputCode, diff); System.out.println("=================================="); System.out.println("Input"); System.out.println(inputCode); List<AbstractSqlSetting> settings = generateSettings(); // apply settings for (AbstractSqlSetting setting : settings) { System.out.println("=================================="); System.out.println(setting.getClass().getSimpleName()); setting.setAbapSql(abapSql); setting.apply(); abapSql = setting.getAbapSql(); System.out.println(abapSql.toString()); } abapSql.setPoint(); String outputCode = abapSql.toString(); // delete last empty row if (outputCode.endsWith("\r\n")) { outputCode = outputCode.substring(0, outputCode.length() - "\r\n".length()); } System.out.println("=================================="); System.out.println("Output"); System.out.println(outputCode); return outputCode; } @Override public boolean canAssist(IQuickAssistInvocationContext invocationContext) { // get part of code and check if the current code part is a sql statement document = invocationContext.getSourceViewer().getDocument(); sourceUi = AbapSourceUi.getInstance(); scannerServices = sourceUi.getSourceScannerServices(); sourcePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor() .getAdapter(AbapSourcePage.class); code = document.get(); // offset of current cursor offsetCursor = invocationContext.getOffset(); // get offset of last and next dot int start = scannerServices.goBackToDot(document, offsetCursor) + 1; end = scannerServices.goForwardToDot(document, offsetCursor); // all words in selected code List<Token> statementTokens = scannerServices.getStatementTokens(document, start); // check first word if (statementTokens.size() > 0) { String firstToken = null; // get first non comment token for (int i = 0; i < statementTokens.size(); i++) { Token t = statementTokens.get(i); if (!scannerServices.isComment(document, t.offset)) { firstToken = t.toString(); // offset of last dot and startReplacement could be different startReplacement = t.offset; try { int line = document.getLineOfOffset(startReplacement); int lineOffset = document.getLineOffset(line); diff = startReplacement - lineOffset; } catch (BadLocationException e) { e.printStackTrace(); } break; } } if (firstToken != null) { if (firstToken.equalsIgnoreCase(Abap.SELECT)) { sql = code.substring(startReplacement, end); String sqlHelper = sql.replaceAll(",", "");
package com.abap.sql.beautifier; public class StatementProcessor implements IQuickAssistProcessor { public IDocument document = null; public IAbapSourceScannerServices scannerServices = null; public AbapSourcePage sourcePage; public IAbapSourceUi sourceUi = null; private String sql = ""; private String code; private int diff; private int end; private int offsetCursor; private int startReplacement; private boolean oldSyntax = true; private String beautifyStatement(String inputCode) { // otherwise the whole beautifier would not work inputCode = inputCode.toUpperCase(); AbapSql abapSql = new AbapSql(inputCode, diff); System.out.println("=================================="); System.out.println("Input"); System.out.println(inputCode); List<AbstractSqlSetting> settings = generateSettings(); // apply settings for (AbstractSqlSetting setting : settings) { System.out.println("=================================="); System.out.println(setting.getClass().getSimpleName()); setting.setAbapSql(abapSql); setting.apply(); abapSql = setting.getAbapSql(); System.out.println(abapSql.toString()); } abapSql.setPoint(); String outputCode = abapSql.toString(); // delete last empty row if (outputCode.endsWith("\r\n")) { outputCode = outputCode.substring(0, outputCode.length() - "\r\n".length()); } System.out.println("=================================="); System.out.println("Output"); System.out.println(outputCode); return outputCode; } @Override public boolean canAssist(IQuickAssistInvocationContext invocationContext) { // get part of code and check if the current code part is a sql statement document = invocationContext.getSourceViewer().getDocument(); sourceUi = AbapSourceUi.getInstance(); scannerServices = sourceUi.getSourceScannerServices(); sourcePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor() .getAdapter(AbapSourcePage.class); code = document.get(); // offset of current cursor offsetCursor = invocationContext.getOffset(); // get offset of last and next dot int start = scannerServices.goBackToDot(document, offsetCursor) + 1; end = scannerServices.goForwardToDot(document, offsetCursor); // all words in selected code List<Token> statementTokens = scannerServices.getStatementTokens(document, start); // check first word if (statementTokens.size() > 0) { String firstToken = null; // get first non comment token for (int i = 0; i < statementTokens.size(); i++) { Token t = statementTokens.get(i); if (!scannerServices.isComment(document, t.offset)) { firstToken = t.toString(); // offset of last dot and startReplacement could be different startReplacement = t.offset; try { int line = document.getLineOfOffset(startReplacement); int lineOffset = document.getLineOffset(line); diff = startReplacement - lineOffset; } catch (BadLocationException e) { e.printStackTrace(); } break; } } if (firstToken != null) { if (firstToken.equalsIgnoreCase(Abap.SELECT)) { sql = code.substring(startReplacement, end); String sqlHelper = sql.replaceAll(",", "");
sqlHelper = Utility.cleanString(sqlHelper);
11
2023-10-10 18:56:27+00:00
16k
Spider-Admin/Frost
src/main/java/frost/messaging/freetalk/transfer/CreateBoardCallback.java
[ { "identifier": "MainFrame", "path": "src/main/java/frost/MainFrame.java", "snippet": "@SuppressWarnings(\"serial\")\r\npublic class MainFrame extends JFrame implements SettingsUpdater, LanguageListener {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(MainFrame.class);\r\n\r\n ...
import javax.swing.JOptionPane; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import frost.MainFrame; import frost.fcp.fcp07.NodeMessage; import frost.fcp.fcp07.freetalk.FcpFreetalkConnection.FreetalkNodeMessageCallback; import frost.messaging.freetalk.FreetalkManager; import frost.messaging.freetalk.boards.FreetalkBoard;
11,436
/* CreateBoardCallback.java / Frost Copyright (C) 2009 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.messaging.freetalk.transfer; public class CreateBoardCallback implements FreetalkNodeMessageCallback { private static final Logger logger = LoggerFactory.getLogger(CreateBoardCallback.class);
/* CreateBoardCallback.java / Frost Copyright (C) 2009 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.messaging.freetalk.transfer; public class CreateBoardCallback implements FreetalkNodeMessageCallback { private static final Logger logger = LoggerFactory.getLogger(CreateBoardCallback.class);
private final MainFrame mainFrame;
0
2023-10-07 22:25:20+00:00
16k
openpilot-hub/devpilot-intellij
src/main/java/com/zhongan/devpilot/actions/editor/popupmenu/PopupMenuEditorActionGroupUtil.java
[ { "identifier": "DevPilotNotification", "path": "src/main/java/com/zhongan/devpilot/actions/notifications/DevPilotNotification.java", "snippet": "public class DevPilotNotification {\n\n public static void info(String content) {\n var notification = new Notification(\n \"DevPilot Not...
import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowManager; import com.zhongan.devpilot.actions.notifications.DevPilotNotification; import com.zhongan.devpilot.constant.DefaultConst; import com.zhongan.devpilot.constant.PromptConst; import com.zhongan.devpilot.enums.EditorActionEnum; import com.zhongan.devpilot.enums.SessionTypeEnum; import com.zhongan.devpilot.gui.toolwindows.chat.DevPilotChatToolWindowService; import com.zhongan.devpilot.gui.toolwindows.components.EditorInfo; import com.zhongan.devpilot.settings.actionconfiguration.EditorActionConfigurationState; import com.zhongan.devpilot.settings.state.DevPilotLlmSettingsState; import com.zhongan.devpilot.settings.state.LanguageSettingsState; import com.zhongan.devpilot.util.DevPilotMessageBundle; import com.zhongan.devpilot.util.DocumentUtil; import com.zhongan.devpilot.util.LanguageUtil; import com.zhongan.devpilot.util.PerformanceCheckUtils; import com.zhongan.devpilot.util.PromptTemplate; import com.zhongan.devpilot.util.PsiFileUtil; import com.zhongan.devpilot.webview.model.CodeReferenceModel; import com.zhongan.devpilot.webview.model.MessageModel; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.function.Consumer; import javax.swing.Icon; import static com.zhongan.devpilot.constant.PlaceholderConst.ADDITIONAL_MOCK_PROMPT; import static com.zhongan.devpilot.constant.PlaceholderConst.LANGUAGE; import static com.zhongan.devpilot.constant.PlaceholderConst.MOCK_FRAMEWORK; import static com.zhongan.devpilot.constant.PlaceholderConst.SELECTED_CODE; import static com.zhongan.devpilot.constant.PlaceholderConst.TEST_FRAMEWORK;
11,939
package com.zhongan.devpilot.actions.editor.popupmenu; public class PopupMenuEditorActionGroupUtil { private static final Map<String, Icon> ICONS = new LinkedHashMap<>(Map.of( EditorActionEnum.PERFORMANCE_CHECK.getLabel(), AllIcons.Plugins.Updated, EditorActionEnum.GENERATE_COMMENTS.getLabel(), AllIcons.Actions.InlayRenameInCommentsActive, EditorActionEnum.GENERATE_TESTS.getLabel(), AllIcons.Modules.GeneratedTestRoot, EditorActionEnum.FIX_THIS.getLabel(), AllIcons.Actions.QuickfixBulb, EditorActionEnum.REVIEW_CODE.getLabel(), AllIcons.Actions.PreviewDetailsVertically, EditorActionEnum.EXPLAIN_THIS.getLabel(), AllIcons.Actions.Preview)); public static void refreshActions(Project project) { AnAction actionGroup = ActionManager.getInstance().getAction("com.zhongan.devpilot.actions.editor.popupmenu.BasicEditorAction"); if (actionGroup instanceof DefaultActionGroup) { DefaultActionGroup group = (DefaultActionGroup) actionGroup; group.removeAll(); group.add(new NewChatAction()); group.addSeparator(); var defaultActions = EditorActionConfigurationState.getInstance().getDefaultActions(); defaultActions.forEach((label, prompt) -> { var action = new BasicEditorAction(DevPilotMessageBundle.get(label), DevPilotMessageBundle.get(label), ICONS.getOrDefault(label, AllIcons.FileTypes.Unknown)) { @Override protected void actionPerformed(Project project, Editor editor, String selectedText) { ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow("DevPilot"); toolWindow.show(); if (isInputExceedLimit(selectedText, prompt)) { DevPilotNotification.info(DevPilotMessageBundle.get("devpilot.notification.input.tooLong")); return; } var editorActionEnum = EditorActionEnum.getEnumByLabel(label); if (Objects.isNull(editorActionEnum)) { return; } Consumer<String> callback = result -> { if (validateResult(result)) { DevPilotNotification.info(DevPilotMessageBundle.get("devpilot.notification.input.tooLong")); return; } switch (editorActionEnum) { case PERFORMANCE_CHECK: // display result, and open diff window PerformanceCheckUtils.showDiffWindow(selectedText, project, editor); break; case GENERATE_COMMENTS: DocumentUtil.diffCommentAndFormatWindow(project, editor, result); break; default: break; } }; EditorInfo editorInfo = new EditorInfo(editor); PromptTemplate promptTemplate = PromptTemplate.of(prompt); promptTemplate.setVariable(SELECTED_CODE, selectedText); if (editorActionEnum == EditorActionEnum.GENERATE_TESTS) { Optional.ofNullable(FileDocumentManager.getInstance().getFile(editor.getDocument())) .map(vFile -> LanguageUtil.getLanguageByExtension(vFile.getExtension())) .ifPresent(language -> { promptTemplate.setVariable(LANGUAGE, language.getLanguageName());
package com.zhongan.devpilot.actions.editor.popupmenu; public class PopupMenuEditorActionGroupUtil { private static final Map<String, Icon> ICONS = new LinkedHashMap<>(Map.of( EditorActionEnum.PERFORMANCE_CHECK.getLabel(), AllIcons.Plugins.Updated, EditorActionEnum.GENERATE_COMMENTS.getLabel(), AllIcons.Actions.InlayRenameInCommentsActive, EditorActionEnum.GENERATE_TESTS.getLabel(), AllIcons.Modules.GeneratedTestRoot, EditorActionEnum.FIX_THIS.getLabel(), AllIcons.Actions.QuickfixBulb, EditorActionEnum.REVIEW_CODE.getLabel(), AllIcons.Actions.PreviewDetailsVertically, EditorActionEnum.EXPLAIN_THIS.getLabel(), AllIcons.Actions.Preview)); public static void refreshActions(Project project) { AnAction actionGroup = ActionManager.getInstance().getAction("com.zhongan.devpilot.actions.editor.popupmenu.BasicEditorAction"); if (actionGroup instanceof DefaultActionGroup) { DefaultActionGroup group = (DefaultActionGroup) actionGroup; group.removeAll(); group.add(new NewChatAction()); group.addSeparator(); var defaultActions = EditorActionConfigurationState.getInstance().getDefaultActions(); defaultActions.forEach((label, prompt) -> { var action = new BasicEditorAction(DevPilotMessageBundle.get(label), DevPilotMessageBundle.get(label), ICONS.getOrDefault(label, AllIcons.FileTypes.Unknown)) { @Override protected void actionPerformed(Project project, Editor editor, String selectedText) { ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow("DevPilot"); toolWindow.show(); if (isInputExceedLimit(selectedText, prompt)) { DevPilotNotification.info(DevPilotMessageBundle.get("devpilot.notification.input.tooLong")); return; } var editorActionEnum = EditorActionEnum.getEnumByLabel(label); if (Objects.isNull(editorActionEnum)) { return; } Consumer<String> callback = result -> { if (validateResult(result)) { DevPilotNotification.info(DevPilotMessageBundle.get("devpilot.notification.input.tooLong")); return; } switch (editorActionEnum) { case PERFORMANCE_CHECK: // display result, and open diff window PerformanceCheckUtils.showDiffWindow(selectedText, project, editor); break; case GENERATE_COMMENTS: DocumentUtil.diffCommentAndFormatWindow(project, editor, result); break; default: break; } }; EditorInfo editorInfo = new EditorInfo(editor); PromptTemplate promptTemplate = PromptTemplate.of(prompt); promptTemplate.setVariable(SELECTED_CODE, selectedText); if (editorActionEnum == EditorActionEnum.GENERATE_TESTS) { Optional.ofNullable(FileDocumentManager.getInstance().getFile(editor.getDocument())) .map(vFile -> LanguageUtil.getLanguageByExtension(vFile.getExtension())) .ifPresent(language -> { promptTemplate.setVariable(LANGUAGE, language.getLanguageName());
promptTemplate.setVariable(TEST_FRAMEWORK, language.getDefaultTestFramework());
22
2023-11-29 06:37:51+00:00
16k
Gaia3D/mago-3d-tiler
tiler/src/test/java/com/gaia3d/converter/AssimpConverterTest.java
[ { "identifier": "Configurator", "path": "tiler/src/main/java/com/gaia3d/command/Configurator.java", "snippet": "public class Configurator {\n public static final Level LEVEL = Level.ALL;\n private static final String DEFAULT_PATTERN = \"%message%n\";\n\n public static void initConsoleLogger() {...
import com.gaia3d.command.Configurator; import com.gaia3d.converter.kml.FastKmlReader; import com.gaia3d.converter.kml.KmlInfo; import com.gaia3d.converter.assimp.AssimpConverter; import com.gaia3d.process.postprocess.batch.Batcher; import com.gaia3d.process.postprocess.batch.GaiaBatcher; import com.gaia3d.basic.structure.GaiaScene; import org.junit.jupiter.api.Test; import com.gaia3d.process.tileprocess.tile.ContentInfo; import com.gaia3d.process.tileprocess.tile.LevelOfDetail; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.List; import static org.junit.jupiter.api.Assertions.assertNotNull;
13,944
package com.gaia3d.converter; class AssimpConverterTest { private static final String INPUT_PATH = "../sample/"; private static final String OUTPUT_PATH = "../output/"; @Test void load() throws URISyntaxException { Converter converter = new AssimpConverter(null); List<GaiaScene> scenes = converter.load(getAbsolutePath(INPUT_PATH) + "a_bd001.3ds"); assertNotNull(scenes); } @Test void loadCollada() throws URISyntaxException { Converter converter = new AssimpConverter(null); List<GaiaScene> scenes = converter.load(getAbsolutePath(INPUT_PATH) + "a_bd001.dae"); assertNotNull(scenes); } @Test void loadColladaWithKml() throws URISyntaxException, IOException, ParserConfigurationException { Configurator.initConsoleLogger(); File kml = new File(getAbsolutePath(INPUT_PATH) + "a_bd001.kml"); //KmlReader kmlReader = new KmlReader(); FastKmlReader kmlReader = new FastKmlReader(); KmlInfo kmlInfo = kmlReader.read(kml); Converter converter = new AssimpConverter(null); List<GaiaScene> scenes = converter.load(getAbsolutePath(INPUT_PATH) + kmlInfo.getHref()); assertNotNull(scenes); ContentInfo batchInfo = new ContentInfo(); //GaiaUniverse universe = new GaiaUniverse("test", new File(getAbsolutePath(INPUT_PATH)), new File(getAbsolutePath(OUTPUT_PATH))); //universe.getScenes().add(scene); batchInfo.setLod(LevelOfDetail.LOD0); batchInfo.setNodeCode("TEST"); batchInfo.setBoundingBox(scenes.get(0).getBoundingBox());
package com.gaia3d.converter; class AssimpConverterTest { private static final String INPUT_PATH = "../sample/"; private static final String OUTPUT_PATH = "../output/"; @Test void load() throws URISyntaxException { Converter converter = new AssimpConverter(null); List<GaiaScene> scenes = converter.load(getAbsolutePath(INPUT_PATH) + "a_bd001.3ds"); assertNotNull(scenes); } @Test void loadCollada() throws URISyntaxException { Converter converter = new AssimpConverter(null); List<GaiaScene> scenes = converter.load(getAbsolutePath(INPUT_PATH) + "a_bd001.dae"); assertNotNull(scenes); } @Test void loadColladaWithKml() throws URISyntaxException, IOException, ParserConfigurationException { Configurator.initConsoleLogger(); File kml = new File(getAbsolutePath(INPUT_PATH) + "a_bd001.kml"); //KmlReader kmlReader = new KmlReader(); FastKmlReader kmlReader = new FastKmlReader(); KmlInfo kmlInfo = kmlReader.read(kml); Converter converter = new AssimpConverter(null); List<GaiaScene> scenes = converter.load(getAbsolutePath(INPUT_PATH) + kmlInfo.getHref()); assertNotNull(scenes); ContentInfo batchInfo = new ContentInfo(); //GaiaUniverse universe = new GaiaUniverse("test", new File(getAbsolutePath(INPUT_PATH)), new File(getAbsolutePath(OUTPUT_PATH))); //universe.getScenes().add(scene); batchInfo.setLod(LevelOfDetail.LOD0); batchInfo.setNodeCode("TEST"); batchInfo.setBoundingBox(scenes.get(0).getBoundingBox());
Batcher batcher = new GaiaBatcher(null);
4
2023-11-30 01:59:44+00:00
16k
okx/OKBund
aa-task/src/main/java/com/okcoin/dapp/bundler/manager/BundlerServiceImpl.java
[ { "identifier": "BundleConfig", "path": "aa-task/src/main/java/com/okcoin/dapp/bundler/config/BundleConfig.java", "snippet": "@Configuration\n@ConfigurationProperties(prefix = \"bundler.bundle\")\n@Data\npublic class BundleConfig {\n\n private BigInteger maxBundleGas;\n\n private BigDecimal baseFe...
import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.okcoin.dapp.bundler.config.BundleConfig; import com.okcoin.dapp.bundler.config.OnChainConfig; import com.okcoin.dapp.bundler.domain.UopBundleDO; import com.okcoin.dapp.bundler.infra.chain.FieldUtil; import com.okcoin.dapp.bundler.infra.chain.IChain; import com.okcoin.dapp.bundler.infra.chain.ReceiptUtil; import com.okcoin.dapp.bundler.infra.chain.web3j.resp.TransactionReceiptCommon; import com.okcoin.dapp.bundler.pool.bundler.IBundleService; import com.okcoin.dapp.bundler.pool.config.ChainConfig; import com.okcoin.dapp.bundler.pool.config.PoolConfig; import com.okcoin.dapp.bundler.pool.domain.TxAndOpHashMappingDO; import com.okcoin.dapp.bundler.pool.domain.UserOperationDO; import com.okcoin.dapp.bundler.pool.domain.debug.SimulateValidationResult; import com.okcoin.dapp.bundler.pool.domain.debug.SlotMap; import com.okcoin.dapp.bundler.pool.domain.pool.MempoolEntry; import com.okcoin.dapp.bundler.pool.domain.reputation.ReputationStatusEnum; import com.okcoin.dapp.bundler.pool.entrypoint.Entrypoint; import com.okcoin.dapp.bundler.pool.gasprice.GasPriceInfo; import com.okcoin.dapp.bundler.pool.gasprice.GasService; import com.okcoin.dapp.bundler.pool.mem.MempoolService; import com.okcoin.dapp.bundler.pool.reputation.ReputationService; import com.okcoin.dapp.bundler.pool.result.OnChainTxFailedService; import com.okcoin.dapp.bundler.pool.simulation.EntryPointSimulationsFactory; import com.okcoin.dapp.bundler.pool.simulation.IEntryPointSimulations; import com.okcoin.dapp.bundler.pool.util.AddressUtil; import com.okcoin.dapp.bundler.pool.util.MathUtil; import com.okcoin.dapp.bundler.task.logevent.LogEventService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.web3j.crypto.Credentials; import javax.annotation.Resource; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors;
11,857
package com.okcoin.dapp.bundler.manager; /** * @ClassName BundlerServiceImpl * @Author qunqin * @Date 2023/10/25 **/ @Component @Slf4j public class BundlerServiceImpl implements IBundleService { @Resource private MempoolService mempoolService; @Resource private BundleConfig bundleConfig; @Resource
package com.okcoin.dapp.bundler.manager; /** * @ClassName BundlerServiceImpl * @Author qunqin * @Date 2023/10/25 **/ @Component @Slf4j public class BundlerServiceImpl implements IBundleService { @Resource private MempoolService mempoolService; @Resource private BundleConfig bundleConfig; @Resource
private GasService gasService;
18
2023-11-27 10:54:49+00:00
16k
seraxis/lr2oraja-endlessdream
core/src/bms/player/beatoraja/select/bar/SearchWordBar.java
[ { "identifier": "MusicSelector", "path": "core/src/bms/player/beatoraja/select/MusicSelector.java", "snippet": "public class MusicSelector extends MainState {\n\n\t// TODO ミラーランダム段位のスコア表示\n\n\tprivate int selectedreplay;\n\n\t/**\n\t * 楽曲DBアクセサ\n\t */\n\tprivate SongDatabaseAccessor songdb;\n\n\tpublic ...
import bms.player.beatoraja.select.MusicSelector; import bms.player.beatoraja.song.SongData;
10,806
package bms.player.beatoraja.select.bar; /** * 検索用バー * * @author exch */ public class SearchWordBar extends DirectoryBar { private String text; private String title;
package bms.player.beatoraja.select.bar; /** * 検索用バー * * @author exch */ public class SearchWordBar extends DirectoryBar { private String text; private String title;
public SearchWordBar(MusicSelector selector, String text) {
0
2023-12-02 23:41:17+00:00
16k
Elb1to/FFA
src/main/java/me/elb1to/ffa/FfaPlugin.java
[ { "identifier": "Assemble", "path": "src/main/java/io/github/thatkawaiisam/assemble/Assemble.java", "snippet": "@Getter\n@Setter\npublic class Assemble {\n\n\tprivate final JavaPlugin plugin;\n\tprivate final ChatColor[] chatColorCache = ChatColor.values();\n\tprivate AssembleAdapter adapter;\n\tprivate...
import io.github.thatkawaiisam.assemble.Assemble; import io.github.thatkawaiisam.assemble.AssembleStyle; import lombok.Getter; import me.elb1to.ffa.command.manager.CommandManager; import me.elb1to.ffa.database.MongoSrv; import me.elb1to.ffa.game.listener.FfaListener; import me.elb1to.ffa.game.manager.FfaManager; import me.elb1to.ffa.game.task.ItemRemovalTask; import me.elb1to.ffa.kit.manager.KitManager; import me.elb1to.ffa.layout.ScoreboardLayout; import me.elb1to.ffa.leaderboard.manager.LeaderboardManager; import me.elb1to.ffa.map.FfaMap; import me.elb1to.ffa.map.manager.MapManager; import me.elb1to.ffa.user.UserProfile; import me.elb1to.ffa.user.listener.UserProfileListener; import me.elb1to.ffa.user.manager.UserProfileManager; import me.elb1to.ffa.util.menu.listener.ButtonListener; import me.elb1to.ffa.util.world.Cuboid; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.WorldCreator; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.plugin.java.JavaPlugin;
11,472
package me.elb1to.ffa; /** * @author Elb1to * @since 11/22/2023 */ @Getter public class FfaPlugin extends JavaPlugin { private MongoSrv mongoSrv; private MapManager mapManager; private KitManager kitManager; private FfaManager ffaManager; private UserProfileManager userProfileManager; private LeaderboardManager leaderboardManager; private CommandManager commandManager; @Override public void onEnable() { saveDefaultConfig(); mongoSrv = new MongoSrv(this, getConfig().getConfigurationSection("mongo")); mapManager = new MapManager(this, getConfig().getConfigurationSection("maps")); kitManager = new KitManager(this, getConfig().getConfigurationSection("kits")); ffaManager = new FfaManager(this); userProfileManager = new UserProfileManager(this); leaderboardManager = new LeaderboardManager(this); commandManager = new CommandManager(this); getServer().getPluginManager().registerEvents(new FfaListener(this), this); getServer().getPluginManager().registerEvents(new ButtonListener(this), this); getServer().getPluginManager().registerEvents(new UserProfileListener(this), this); getServer().getScheduler().runTaskLater(this, () -> { for (FfaMap ffaMap : mapManager.getMaps()) { ffaMap.setWorld(Bukkit.getWorld(ffaMap.getName())); Cuboid cuboid = new Cuboid(ffaMap.getMin().toBukkitLocation(), ffaMap.getMax().toBukkitLocation()); ffaMap.setCuboid(cuboid); } leaderboardManager.updateLeaderboards(); }, 100L); getServer().getScheduler().runTaskTimerAsynchronously(this, new ItemRemovalTask(this), 1L, 1L);
package me.elb1to.ffa; /** * @author Elb1to * @since 11/22/2023 */ @Getter public class FfaPlugin extends JavaPlugin { private MongoSrv mongoSrv; private MapManager mapManager; private KitManager kitManager; private FfaManager ffaManager; private UserProfileManager userProfileManager; private LeaderboardManager leaderboardManager; private CommandManager commandManager; @Override public void onEnable() { saveDefaultConfig(); mongoSrv = new MongoSrv(this, getConfig().getConfigurationSection("mongo")); mapManager = new MapManager(this, getConfig().getConfigurationSection("maps")); kitManager = new KitManager(this, getConfig().getConfigurationSection("kits")); ffaManager = new FfaManager(this); userProfileManager = new UserProfileManager(this); leaderboardManager = new LeaderboardManager(this); commandManager = new CommandManager(this); getServer().getPluginManager().registerEvents(new FfaListener(this), this); getServer().getPluginManager().registerEvents(new ButtonListener(this), this); getServer().getPluginManager().registerEvents(new UserProfileListener(this), this); getServer().getScheduler().runTaskLater(this, () -> { for (FfaMap ffaMap : mapManager.getMaps()) { ffaMap.setWorld(Bukkit.getWorld(ffaMap.getName())); Cuboid cuboid = new Cuboid(ffaMap.getMin().toBukkitLocation(), ffaMap.getMax().toBukkitLocation()); ffaMap.setCuboid(cuboid); } leaderboardManager.updateLeaderboards(); }, 100L); getServer().getScheduler().runTaskTimerAsynchronously(this, new ItemRemovalTask(this), 1L, 1L);
Assemble assemble = new Assemble(this, new ScoreboardLayout(this));
0
2023-11-28 16:53:29+00:00
16k
Hoto-Mocha/Re-ARranged-Pixel-Dungeon
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/effects/Speck.java
[ { "identifier": "Assets", "path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/Assets.java", "snippet": "public class Assets {\n\n\tpublic static class Effects {\n\t\tpublic static final String EFFECTS = \"effects/effects.png\";\n\t\tpublic static final String FIREBALL = \"effec...
import com.shatteredpixel.shatteredpixeldungeon.Assets; import com.watabou.noosa.Game; import com.watabou.noosa.Image; import com.watabou.noosa.TextureFilm; import com.watabou.noosa.particles.Emitter; import com.watabou.utils.ColorMath; import com.watabou.utils.PointF; import com.watabou.utils.Random; import com.watabou.utils.SparseArray;
14,076
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.effects; public class Speck extends Image { public static final int HEALING = 0; public static final int STAR = 1; public static final int LIGHT = 2; public static final int QUESTION = 3; public static final int UP = 4; public static final int SCREAM = 5; public static final int BONE = 6; public static final int WOOL = 7; public static final int ROCK = 8; public static final int NOTE = 9; public static final int CHANGE = 10; public static final int HEART = 11; public static final int BUBBLE = 12; public static final int STEAM = 13; public static final int COIN = 14; public static final int DISCOVER = 101; public static final int EVOKE = 102; public static final int MASK = 103; public static final int CROWN = 104; public static final int RATTLE = 105; public static final int JET = 106; public static final int TOXIC = 107; public static final int CORROSION = 108; public static final int PARALYSIS = 109; public static final int DUST = 110; public static final int STENCH = 111; public static final int FORGE = 112; public static final int CONFUSION = 113; public static final int RED_LIGHT = 114; public static final int CALM = 115; public static final int SMOKE = 116; public static final int STORM = 117; public static final int INFERNO = 118; public static final int BLIZZARD = 119; private static final int SIZE = 7; private int type; private float lifespan; private float left; private static TextureFilm film;
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.effects; public class Speck extends Image { public static final int HEALING = 0; public static final int STAR = 1; public static final int LIGHT = 2; public static final int QUESTION = 3; public static final int UP = 4; public static final int SCREAM = 5; public static final int BONE = 6; public static final int WOOL = 7; public static final int ROCK = 8; public static final int NOTE = 9; public static final int CHANGE = 10; public static final int HEART = 11; public static final int BUBBLE = 12; public static final int STEAM = 13; public static final int COIN = 14; public static final int DISCOVER = 101; public static final int EVOKE = 102; public static final int MASK = 103; public static final int CROWN = 104; public static final int RATTLE = 105; public static final int JET = 106; public static final int TOXIC = 107; public static final int CORROSION = 108; public static final int PARALYSIS = 109; public static final int DUST = 110; public static final int STENCH = 111; public static final int FORGE = 112; public static final int CONFUSION = 113; public static final int RED_LIGHT = 114; public static final int CALM = 115; public static final int SMOKE = 116; public static final int STORM = 117; public static final int INFERNO = 118; public static final int BLIZZARD = 119; private static final int SIZE = 7; private int type; private float lifespan; private float left; private static TextureFilm film;
private static SparseArray<Emitter.Factory> factories = new SparseArray<>();
8
2023-11-27 05:56:58+00:00
16k
WiIIiam278/HuskClaims
bukkit/src/main/java/net/william278/huskclaims/event/BukkitEventDispatcher.java
[ { "identifier": "BukkitHuskClaims", "path": "bukkit/src/main/java/net/william278/huskclaims/BukkitHuskClaims.java", "snippet": "@NoArgsConstructor\n@Getter\npublic class BukkitHuskClaims extends JavaPlugin implements HuskClaims, BukkitTask.Supplier, BukkitBlockProvider,\n BukkitEventDispatcher, B...
import org.bukkit.event.Cancellable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import net.william278.huskclaims.BukkitHuskClaims; import net.william278.huskclaims.claim.Claim; import net.william278.huskclaims.claim.ClaimWorld; import net.william278.huskclaims.claim.Region; import net.william278.huskclaims.claim.ServerWorldClaim; import net.william278.huskclaims.position.Position; import net.william278.huskclaims.trust.TrustLevel; import net.william278.huskclaims.trust.Trustable; import net.william278.huskclaims.user.OnlineUser; import net.william278.huskclaims.user.User; import net.william278.huskclaims.user.UserManager;
13,963
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <will27528@gmail.com> * Copyright (c) contributors * * 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 net.william278.huskclaims.event; public interface BukkitEventDispatcher extends EventDispatcher { @Override default <T extends Event> boolean fireIsCancelled(@NotNull T event) { ((BukkitHuskClaims) getPlugin()).getServer().getPluginManager().callEvent((org.bukkit.event.Event) event); return event instanceof Cancellable cancellable && cancellable.isCancelled(); } @Override @NotNull default ClaimBlocksChangeEvent getClaimBlocksChangeEvent(@NotNull User user, long oldBlocks, long newBlocks, @NotNull UserManager.ClaimBlockSource reason) { return new BukkitClaimBlocksChangeEvent(user, oldBlocks, newBlocks, reason, getPlugin()); } @Override @NotNull
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <will27528@gmail.com> * Copyright (c) contributors * * 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 net.william278.huskclaims.event; public interface BukkitEventDispatcher extends EventDispatcher { @Override default <T extends Event> boolean fireIsCancelled(@NotNull T event) { ((BukkitHuskClaims) getPlugin()).getServer().getPluginManager().callEvent((org.bukkit.event.Event) event); return event instanceof Cancellable cancellable && cancellable.isCancelled(); } @Override @NotNull default ClaimBlocksChangeEvent getClaimBlocksChangeEvent(@NotNull User user, long oldBlocks, long newBlocks, @NotNull UserManager.ClaimBlockSource reason) { return new BukkitClaimBlocksChangeEvent(user, oldBlocks, newBlocks, reason, getPlugin()); } @Override @NotNull
default CreateChildClaimEvent getCreateChildClaimEvent(@NotNull OnlineUser claimer, @NotNull Claim parent,
7
2023-11-28 01:09:43+00:00
16k
Manzzx/multi-channel-message-reach
metax-modules/metax-system/src/main/java/com/metax/system/service/impl/SysRoleServiceImpl.java
[ { "identifier": "UserConstants", "path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/constant/UserConstants.java", "snippet": "public class UserConstants\n{\n /**\n * 平台内系统用户的唯一标志\n */\n public static final String SYS_USER = \"SYS_USER\";\n\n /** 正常状态 */\n pub...
import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.metax.common.core.constant.UserConstants; import com.metax.common.core.exception.ServiceException; import com.metax.common.core.utils.SpringUtils; import com.metax.common.core.utils.StringUtils; import com.metax.common.datascope.annotation.DataScope; import com.metax.common.security.utils.SecurityUtils; import com.metax.system.api.domain.SysRole; import com.metax.system.api.domain.SysUser; import com.metax.system.domain.SysRoleDept; import com.metax.system.domain.SysRoleMenu; import com.metax.system.domain.SysUserRole; import com.metax.system.mapper.SysRoleDeptMapper; import com.metax.system.mapper.SysRoleMapper; import com.metax.system.mapper.SysRoleMenuMapper; import com.metax.system.mapper.SysUserRoleMapper; import com.metax.system.service.ISysRoleService;
14,256
package com.metax.system.service.impl; /** * 角色 业务层处理 * * @author ruoyi */ @Service public class SysRoleServiceImpl implements ISysRoleService { @Autowired private SysRoleMapper roleMapper; @Autowired private SysRoleMenuMapper roleMenuMapper; @Autowired private SysUserRoleMapper userRoleMapper; @Autowired private SysRoleDeptMapper roleDeptMapper; /** * 根据条件分页查询角色数据 * * @param role 角色信息 * @return 角色数据集合信息 */ @Override @DataScope(deptAlias = "d") public List<SysRole> selectRoleList(SysRole role) { return roleMapper.selectRoleList(role); } /** * 根据用户ID查询角色 * * @param userId 用户ID * @return 角色列表 */ @Override public List<SysRole> selectRolesByUserId(Long userId) { List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(userId); List<SysRole> roles = selectRoleAll(); for (SysRole role : roles) { for (SysRole userRole : userRoles) { if (role.getRoleId().longValue() == userRole.getRoleId().longValue()) { role.setFlag(true); break; } } } return roles; } /** * 根据用户ID查询权限 * * @param userId 用户ID * @return 权限列表 */ @Override public Set<String> selectRolePermissionByUserId(Long userId) { List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId); Set<String> permsSet = new HashSet<>(); for (SysRole perm : perms) { if (StringUtils.isNotNull(perm)) { permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(","))); } } return permsSet; } /** * 查询所有角色 * * @return 角色列表 */ @Override public List<SysRole> selectRoleAll() {
package com.metax.system.service.impl; /** * 角色 业务层处理 * * @author ruoyi */ @Service public class SysRoleServiceImpl implements ISysRoleService { @Autowired private SysRoleMapper roleMapper; @Autowired private SysRoleMenuMapper roleMenuMapper; @Autowired private SysUserRoleMapper userRoleMapper; @Autowired private SysRoleDeptMapper roleDeptMapper; /** * 根据条件分页查询角色数据 * * @param role 角色信息 * @return 角色数据集合信息 */ @Override @DataScope(deptAlias = "d") public List<SysRole> selectRoleList(SysRole role) { return roleMapper.selectRoleList(role); } /** * 根据用户ID查询角色 * * @param userId 用户ID * @return 角色列表 */ @Override public List<SysRole> selectRolesByUserId(Long userId) { List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(userId); List<SysRole> roles = selectRoleAll(); for (SysRole role : roles) { for (SysRole userRole : userRoles) { if (role.getRoleId().longValue() == userRole.getRoleId().longValue()) { role.setFlag(true); break; } } } return roles; } /** * 根据用户ID查询权限 * * @param userId 用户ID * @return 权限列表 */ @Override public Set<String> selectRolePermissionByUserId(Long userId) { List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId); Set<String> permsSet = new HashSet<>(); for (SysRole perm : perms) { if (StringUtils.isNotNull(perm)) { permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(","))); } } return permsSet; } /** * 查询所有角色 * * @return 角色列表 */ @Override public List<SysRole> selectRoleAll() {
return SpringUtils.getAopProxy(this).selectRoleList(new SysRole());
2
2023-12-04 05:10:13+00:00
16k
ydb-platform/yoj-project
repository/src/main/java/tech/ydb/yoj/repository/db/list/ListRequest.java
[ { "identifier": "FilterBuilder", "path": "databind/src/main/java/tech/ydb/yoj/databind/expression/FilterBuilder.java", "snippet": "@RequiredArgsConstructor(access = PRIVATE)\npublic final class FilterBuilder<T> {\n private final Schema<T> schema;\n\n private FilterExpression<T> current;\n priva...
import com.google.common.hash.Hashing; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Value; import lombok.With; import tech.ydb.yoj.databind.expression.FilterBuilder; import tech.ydb.yoj.databind.expression.FilterExpression; import tech.ydb.yoj.databind.expression.OrderBuilder; import tech.ydb.yoj.databind.expression.OrderExpression; import tech.ydb.yoj.databind.schema.Schema; import tech.ydb.yoj.repository.db.Entity; import tech.ydb.yoj.repository.db.EntitySchema; import tech.ydb.yoj.repository.db.list.token.PageToken; import javax.annotation.Nullable; import java.util.Objects; import java.util.function.UnaryOperator; import static lombok.AccessLevel.PRIVATE;
11,708
package tech.ydb.yoj.repository.db.list; /** * Listing request. */ @Value @RequiredArgsConstructor(access = PRIVATE) public class ListRequest<T> { @With long offset; @With int pageSize; Schema<T> schema; @With ListingParams<T> params; @With String index; public static <T extends Entity<T>> Builder<T> builder(@NonNull Class<T> entityClass) { return builder(EntitySchema.of(entityClass)); } public static <T> Builder<T> builder(@NonNull Schema<T> schema) { return new Builder<>(schema); } @Nullable
package tech.ydb.yoj.repository.db.list; /** * Listing request. */ @Value @RequiredArgsConstructor(access = PRIVATE) public class ListRequest<T> { @With long offset; @With int pageSize; Schema<T> schema; @With ListingParams<T> params; @With String index; public static <T extends Entity<T>> Builder<T> builder(@NonNull Class<T> entityClass) { return builder(EntitySchema.of(entityClass)); } public static <T> Builder<T> builder(@NonNull Schema<T> schema) { return new Builder<>(schema); } @Nullable
public FilterExpression<T> getFilter() {
1
2023-12-05 15:57:58+00:00
16k
Vera-Firefly/PojavLauncher-Experimental-Edition
app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/CustomControlsActivity.java
[ { "identifier": "ControlData", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/customcontrols/ControlData.java", "snippet": "@Keep\npublic class ControlData {\n\n public static final int SPECIALBTN_KEYBOARD = -1;\n public static final int SPECIALBTN_TOGGLECTRL = -2;\n public static...
import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.DocumentsContract; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import androidx.drawerlayout.widget.DrawerLayout; import net.kdt.pojavlaunch.customcontrols.ControlData; import net.kdt.pojavlaunch.customcontrols.ControlDrawerData; import net.kdt.pojavlaunch.customcontrols.ControlJoystickData; import net.kdt.pojavlaunch.customcontrols.ControlLayout; import net.kdt.pojavlaunch.customcontrols.EditorExitable; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import java.io.IOException;
11,192
package net.kdt.pojavlaunch; public class CustomControlsActivity extends BaseActivity implements EditorExitable { private DrawerLayout mDrawerLayout; private ListView mDrawerNavigationView; private ControlLayout mControlLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_controls); mControlLayout = findViewById(R.id.customctrl_controllayout); mDrawerLayout = findViewById(R.id.customctrl_drawerlayout); mDrawerNavigationView = findViewById(R.id.customctrl_navigation_view); View mPullDrawerButton = findViewById(R.id.drawer_button); mPullDrawerButton.setOnClickListener(v -> mDrawerLayout.openDrawer(mDrawerNavigationView)); mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); mDrawerNavigationView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.menu_customcontrol_customactivity))); mDrawerNavigationView.setOnItemClickListener((parent, view, position, id) -> { switch(position) { case 0: mControlLayout.addControlButton(new ControlData("New")); break; case 1: mControlLayout.addDrawer(new ControlDrawerData()); break;
package net.kdt.pojavlaunch; public class CustomControlsActivity extends BaseActivity implements EditorExitable { private DrawerLayout mDrawerLayout; private ListView mDrawerNavigationView; private ControlLayout mControlLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_controls); mControlLayout = findViewById(R.id.customctrl_controllayout); mDrawerLayout = findViewById(R.id.customctrl_drawerlayout); mDrawerNavigationView = findViewById(R.id.customctrl_navigation_view); View mPullDrawerButton = findViewById(R.id.drawer_button); mPullDrawerButton.setOnClickListener(v -> mDrawerLayout.openDrawer(mDrawerNavigationView)); mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); mDrawerNavigationView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.menu_customcontrol_customactivity))); mDrawerNavigationView.setOnItemClickListener((parent, view, position, id) -> { switch(position) { case 0: mControlLayout.addControlButton(new ControlData("New")); break; case 1: mControlLayout.addDrawer(new ControlDrawerData()); break;
case 2: mControlLayout.addJoystickButton(new ControlJoystickData()); break;
2
2023-12-01 16:16:12+00:00
16k
kawashirov/distant-horizons
common/src/main/java/com/seibel/distanthorizons/common/wrappers/world/ServerLevelWrapper.java
[ { "identifier": "McObjectConverter", "path": "common/src/main/java/com/seibel/distanthorizons/common/wrappers/McObjectConverter.java", "snippet": "public class McObjectConverter\n{\n\tprivate static int bufferIndex(int x, int y)\n\t{\n\t\treturn y * 4 + x;\n\t}\n\t/** Taken from Minecraft's com.mojang.m...
import java.io.File; import java.util.concurrent.ConcurrentHashMap; import com.seibel.distanthorizons.api.enums.worldGeneration.EDhApiLevelType; import com.seibel.distanthorizons.common.wrappers.McObjectConverter; import com.seibel.distanthorizons.common.wrappers.block.BiomeWrapper; import com.seibel.distanthorizons.common.wrappers.block.BlockStateWrapper; import com.seibel.distanthorizons.common.wrappers.block.cache.ServerBlockDetailMap; import com.seibel.distanthorizons.common.wrappers.chunk.ChunkWrapper; import com.seibel.distanthorizons.common.wrappers.minecraft.MinecraftClientWrapper; import com.seibel.distanthorizons.core.logging.DhLoggerBuilder; import com.seibel.distanthorizons.core.pos.DhBlockPos; import com.seibel.distanthorizons.core.pos.DhChunkPos; import com.seibel.distanthorizons.core.wrapperInterfaces.block.IBlockStateWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.chunk.IChunkWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IBiomeWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IClientLevelWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IServerLevelWrapper; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkSource; import net.minecraft.world.level.chunk.ChunkStatus; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Nullable;
12,689
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.common.wrappers.world; /** * @version 2022-9-16 */ public class ServerLevelWrapper implements IServerLevelWrapper { private static final Logger LOGGER = DhLoggerBuilder.getLogger(); private static final ConcurrentHashMap<ServerLevel, ServerLevelWrapper> LEVEL_WRAPPER_BY_SERVER_LEVEL = new ConcurrentHashMap<>(); final ServerLevel level;
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.common.wrappers.world; /** * @version 2022-9-16 */ public class ServerLevelWrapper implements IServerLevelWrapper { private static final Logger LOGGER = DhLoggerBuilder.getLogger(); private static final ConcurrentHashMap<ServerLevel, ServerLevelWrapper> LEVEL_WRAPPER_BY_SERVER_LEVEL = new ConcurrentHashMap<>(); final ServerLevel level;
ServerBlockDetailMap blockMap = new ServerBlockDetailMap(this);
3
2023-12-04 11:41:46+00:00
16k
hmcts/juror-sql-support-library
src/main/java/uk/gov/hmcts/juror/support/sql/service/SqlSupportService.java
[ { "identifier": "Constants", "path": "src/main/java/uk/gov/hmcts/juror/support/sql/Constants.java", "snippet": "public class Constants {\n\n public static final String PHONE_REGEX = \"^(\\\\+44|0)7\\\\d{9}$\";\n public static final String NOTES_REGEX = \"[A-Za-z0-9]{10,501}\";\n public static f...
import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StopWatch; import uk.gov.hmcts.juror.support.generation.generators.value.RandomFromCollectionGeneratorImpl; import uk.gov.hmcts.juror.support.generation.util.RandomGenerator; import uk.gov.hmcts.juror.support.sql.Constants; import uk.gov.hmcts.juror.support.sql.Util; import uk.gov.hmcts.juror.support.sql.dto.JurorAccountDetailsDto; import uk.gov.hmcts.juror.support.sql.entity.CourtLocation; import uk.gov.hmcts.juror.support.sql.entity.Juror; import uk.gov.hmcts.juror.support.sql.entity.JurorGenerator; import uk.gov.hmcts.juror.support.sql.entity.JurorPool; import uk.gov.hmcts.juror.support.sql.entity.JurorPoolGenerator; import uk.gov.hmcts.juror.support.sql.entity.JurorStatus; import uk.gov.hmcts.juror.support.sql.entity.PoolRequest; import uk.gov.hmcts.juror.support.sql.entity.PoolRequestGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.AbstractJurorResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.AbstractJurorResponseGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.DigitalResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.DigitalResponseGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.PaperResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.PaperResponseGenerator; import uk.gov.hmcts.juror.support.sql.generators.DigitalResponseGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.JurorGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.JurorPoolGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.PaperResponseGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.PoolRequestGeneratorUtil; import uk.gov.hmcts.juror.support.sql.repository.CourtLocationRepository; import uk.gov.hmcts.juror.support.sql.repository.DigitalResponseRepository; import uk.gov.hmcts.juror.support.sql.repository.JurorPoolRepository; import uk.gov.hmcts.juror.support.sql.repository.JurorRepository; import uk.gov.hmcts.juror.support.sql.repository.PaperResponseRepository; import uk.gov.hmcts.juror.support.sql.repository.PoolRequestRepository; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiFunction; import java.util.stream.Collectors;
13,509
package uk.gov.hmcts.juror.support.sql.service; @Component @RequiredArgsConstructor(onConstructor = @__(@Autowired)) @Slf4j public class SqlSupportService { private final JurorRepository jurorRepository; private final PoolRequestRepository poolRequestRepository; private final JurorPoolRepository jurorPoolRepository; private final DigitalResponseRepository digitalResponseRepository; private final PaperResponseRepository paperResponseRepository; private StopWatch stopWatch; private final CourtLocationRepository courtLocationRepository; private static final List<CourtLocation> courtLocations; private static final Set<String> courtOwners; private static final int BATCH_SIZE = 100; static { courtLocations = new ArrayList<>(); courtOwners = new HashSet<>(); } public static List<CourtLocation> getCourtLocations() { return Collections.unmodifiableList(courtLocations); } public static Set<String> getCourtOwners() { return Collections.unmodifiableSet(courtOwners); } @PostConstruct //Temporary for testing purposes public void postConstruct() { this.stopWatch = new StopWatch(); courtLocationRepository.findAll().forEach(courtLocations::add); courtOwners.add("400"); courtOwners.add("415"); //TODO add back courtLocations.forEach(courtLocation -> courtOwners.add(courtLocation.getOwner())); clearDownDatabase(); Map<JurorStatus, Integer> jurorStatusCountMapCourt = new EnumMap<>(JurorStatus.class); jurorStatusCountMapCourt.put(JurorStatus.DEFERRED, 12585); jurorStatusCountMapCourt.put(JurorStatus.DISQUALIFIED, 126); jurorStatusCountMapCourt.put(JurorStatus.EXCUSED, 15607); jurorStatusCountMapCourt.put(JurorStatus.FAILED_TO_ATTEND, 705); jurorStatusCountMapCourt.put(JurorStatus.JUROR, 3916); jurorStatusCountMapCourt.put(JurorStatus.PANEL, 472); jurorStatusCountMapCourt.put(JurorStatus.REASSIGNED, 41313); jurorStatusCountMapCourt.put(JurorStatus.RESPONDED, 208525); jurorStatusCountMapCourt.put(JurorStatus.SUMMONED, 56443); jurorStatusCountMapCourt.put(JurorStatus.TRANSFERRED, 1075); //TODO uncomment createJurorsAssociatedToPools(true, 12, 16, jurorStatusCountMapCourt); //TODO remove Map<JurorStatus, Integer> jurorStatusCountMapCourtTmp = new EnumMap<>(JurorStatus.class); jurorStatusCountMapCourtTmp.put(JurorStatus.SUMMONED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.RESPONDED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.DEFERRED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.EXCUSED, 100); //TODO remove end createJurorsAssociatedToPools(true, 12, 16, jurorStatusCountMapCourtTmp); log.info("DONE: " + stopWatch.prettyPrint()); } private void clearDownDatabase() { log.info("Clearing database"); stopWatch.start("Cleaning database"); jurorPoolRepository.deleteAll(); poolRequestRepository.deleteAll(); digitalResponseRepository.deleteAll(); paperResponseRepository.deleteAll(); jurorRepository.deleteAll(); stopWatch.stop(); log.info("Clearing database: DONE"); } public void createJurorsAssociatedToPools(boolean isCourtOwned, int jurorsInPoolMinimumInclusive, int jurorsInPoolMaximumExclusive, Map<JurorStatus, Integer> jurorStatusCountMap) { final int totalCount = jurorStatusCountMap.values().stream().reduce(0, Integer::sum); log.info("Creating Jurors save dtos"); List<JurorAccountDetailsDto> jurorAccountDetailsDtos = createJurorAccountDetailsDtos(isCourtOwned, jurorStatusCountMap); assert totalCount == jurorAccountDetailsDtos.size(); log.info("Creating Pool Request's"); List<JurorPool> needRandomPool = new ArrayList<>(); List<PoolRequest> pools = new ArrayList<>(totalCount / jurorsInPoolMinimumInclusive); PoolRequestGenerator poolRequestGenerator =
package uk.gov.hmcts.juror.support.sql.service; @Component @RequiredArgsConstructor(onConstructor = @__(@Autowired)) @Slf4j public class SqlSupportService { private final JurorRepository jurorRepository; private final PoolRequestRepository poolRequestRepository; private final JurorPoolRepository jurorPoolRepository; private final DigitalResponseRepository digitalResponseRepository; private final PaperResponseRepository paperResponseRepository; private StopWatch stopWatch; private final CourtLocationRepository courtLocationRepository; private static final List<CourtLocation> courtLocations; private static final Set<String> courtOwners; private static final int BATCH_SIZE = 100; static { courtLocations = new ArrayList<>(); courtOwners = new HashSet<>(); } public static List<CourtLocation> getCourtLocations() { return Collections.unmodifiableList(courtLocations); } public static Set<String> getCourtOwners() { return Collections.unmodifiableSet(courtOwners); } @PostConstruct //Temporary for testing purposes public void postConstruct() { this.stopWatch = new StopWatch(); courtLocationRepository.findAll().forEach(courtLocations::add); courtOwners.add("400"); courtOwners.add("415"); //TODO add back courtLocations.forEach(courtLocation -> courtOwners.add(courtLocation.getOwner())); clearDownDatabase(); Map<JurorStatus, Integer> jurorStatusCountMapCourt = new EnumMap<>(JurorStatus.class); jurorStatusCountMapCourt.put(JurorStatus.DEFERRED, 12585); jurorStatusCountMapCourt.put(JurorStatus.DISQUALIFIED, 126); jurorStatusCountMapCourt.put(JurorStatus.EXCUSED, 15607); jurorStatusCountMapCourt.put(JurorStatus.FAILED_TO_ATTEND, 705); jurorStatusCountMapCourt.put(JurorStatus.JUROR, 3916); jurorStatusCountMapCourt.put(JurorStatus.PANEL, 472); jurorStatusCountMapCourt.put(JurorStatus.REASSIGNED, 41313); jurorStatusCountMapCourt.put(JurorStatus.RESPONDED, 208525); jurorStatusCountMapCourt.put(JurorStatus.SUMMONED, 56443); jurorStatusCountMapCourt.put(JurorStatus.TRANSFERRED, 1075); //TODO uncomment createJurorsAssociatedToPools(true, 12, 16, jurorStatusCountMapCourt); //TODO remove Map<JurorStatus, Integer> jurorStatusCountMapCourtTmp = new EnumMap<>(JurorStatus.class); jurorStatusCountMapCourtTmp.put(JurorStatus.SUMMONED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.RESPONDED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.DEFERRED, 100); jurorStatusCountMapCourtTmp.put(JurorStatus.EXCUSED, 100); //TODO remove end createJurorsAssociatedToPools(true, 12, 16, jurorStatusCountMapCourtTmp); log.info("DONE: " + stopWatch.prettyPrint()); } private void clearDownDatabase() { log.info("Clearing database"); stopWatch.start("Cleaning database"); jurorPoolRepository.deleteAll(); poolRequestRepository.deleteAll(); digitalResponseRepository.deleteAll(); paperResponseRepository.deleteAll(); jurorRepository.deleteAll(); stopWatch.stop(); log.info("Clearing database: DONE"); } public void createJurorsAssociatedToPools(boolean isCourtOwned, int jurorsInPoolMinimumInclusive, int jurorsInPoolMaximumExclusive, Map<JurorStatus, Integer> jurorStatusCountMap) { final int totalCount = jurorStatusCountMap.values().stream().reduce(0, Integer::sum); log.info("Creating Jurors save dtos"); List<JurorAccountDetailsDto> jurorAccountDetailsDtos = createJurorAccountDetailsDtos(isCourtOwned, jurorStatusCountMap); assert totalCount == jurorAccountDetailsDtos.size(); log.info("Creating Pool Request's"); List<JurorPool> needRandomPool = new ArrayList<>(); List<PoolRequest> pools = new ArrayList<>(totalCount / jurorsInPoolMinimumInclusive); PoolRequestGenerator poolRequestGenerator =
PoolRequestGeneratorUtil.create(isCourtOwned, Constants.POOL_REQUEST_WEIGHT_MAP);
15
2023-12-01 11:38:42+00:00
16k
SuperRicky14/TpaPlusPlus
src/main/java/net/superricky/tpaplusplus/util/manager/RequestManager.java
[ { "identifier": "Request", "path": "src/main/java/net/superricky/tpaplusplus/util/Request.java", "snippet": "public class Request {\n private final ServerPlayer sender;\n private final ServerPlayer receiver;\n private final boolean hereRequest;\n private boolean accepted;\n private double...
import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.superricky.tpaplusplus.util.Request; import net.superricky.tpaplusplus.util.configuration.Config; import net.superricky.tpaplusplus.util.configuration.Messages; import net.superricky.tpaplusplus.util.configuration.formatters.MessageParser; import net.superricky.tpaplusplus.util.limitations.LimitationManager; import net.superricky.tpaplusplus.util.manager.saved.PlayerData; import net.superricky.tpaplusplus.util.manager.saved.SaveDataManager; import javax.annotation.Nullable; import java.util.*;
13,729
package net.superricky.tpaplusplus.util.manager; public class RequestManager { static final Set<Request> requestSet = new HashSet<>(); private RequestManager() { } public static boolean isPlayerIdentical(ServerPlayer player1, ServerPlayer player2) { return player1.getUUID().equals(player2.getUUID()); } public static void clearRequestSet() { requestSet.clear(); } public static boolean alreadySentTeleportRequest(Request request) { for (Request currentRequest : requestSet) { if (isPlayerIdentical(request.getSender(), currentRequest.getSender()) && isPlayerIdentical(request.getReceiver(), currentRequest.getReceiver())) { return true; } } return false; } // Deny command is run by the receiver, hence why it's in the receiver's point of view. private static void denyFunctionality(Request request, ServerPlayer receiver) { if (Objects.isNull(request)) { receiver.sendSystemMessage(Component.literal(Messages.ERR_REQUEST_NOT_FOUND.get())); return; } request.getReceiver().sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_DENIES_TPA.get(), request.getSender().getName().getString()))); request.getSender().sendSystemMessage(Component.literal(String.format(Messages.SENDER_GOT_DENIED_TPA.get(), request.getReceiver().getName().getString()))); requestSet.remove(request); } public static void denyTeleportRequest(ServerPlayer receiver) { Request request = RequestGrabUtil.getReceiverRequest(receiver); denyFunctionality(request, receiver); } // Deny command is run by the receiver, hence why it's in the receiver's point of view. public static void denyTeleportRequest(ServerPlayer receiver, ServerPlayer sender) { Request request = RequestGrabUtil.getReceiverRequest(receiver, sender); denyFunctionality(request, receiver); } // Cancel command is run by the sender, hence why it's in the sender's point of view. private static void cancelFunctionality(Request request, ServerPlayer sender) { if (Objects.isNull(request)) { sender.sendSystemMessage(Component.literal(Messages.ERR_REQUEST_NOT_FOUND.get())); return; } request.getSender().sendSystemMessage(Component.literal(String.format(Messages.SENDER_CANCELS_TPA.get(), request.getReceiver().getName().getString()))); request.getReceiver().sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_GOT_CANCELLED_TPA.get(), request.getSender().getName().getString()))); requestSet.remove(request); } public static void cancelTeleportRequest(ServerPlayer sender) { Request request = RequestGrabUtil.getSenderRequest(sender); cancelFunctionality(request, sender); } public static void cancelTeleportRequest(ServerPlayer sender, ServerPlayer receiver) { Request request = RequestGrabUtil.getSenderRequest(sender, receiver); cancelFunctionality(request, sender); } // Send command is run by the sender, hence why its in the sender's point of view public static void sendTeleportRequest(ServerPlayer sender, ServerPlayer receiver, boolean isHereRequest) { if (isPlayerIdentical(sender, receiver)) { sender.sendSystemMessage(Component.literal(Messages.ERR_NO_SELF_TELEPORT.get())); return; } if (PlayerBlockingManager.isPlayerBlocked(sender, receiver)) return; // Return if one of the players has blocked the other player. PlayerData receiverData = SaveDataManager.getPlayerData(receiver); if (Boolean.FALSE.equals(Objects.isNull(receiverData)) && receiverData.getTPToggle()) { // receiverData is not null && receiver TP toggle is enabled. sender.sendSystemMessage(Component.literal(MessageParser.enhancedFormatter(Messages.ERR_RECEIVER_TP_DISABLED.get(), Map.of("receiverName", receiver.getName().getString())))); return; }
package net.superricky.tpaplusplus.util.manager; public class RequestManager { static final Set<Request> requestSet = new HashSet<>(); private RequestManager() { } public static boolean isPlayerIdentical(ServerPlayer player1, ServerPlayer player2) { return player1.getUUID().equals(player2.getUUID()); } public static void clearRequestSet() { requestSet.clear(); } public static boolean alreadySentTeleportRequest(Request request) { for (Request currentRequest : requestSet) { if (isPlayerIdentical(request.getSender(), currentRequest.getSender()) && isPlayerIdentical(request.getReceiver(), currentRequest.getReceiver())) { return true; } } return false; } // Deny command is run by the receiver, hence why it's in the receiver's point of view. private static void denyFunctionality(Request request, ServerPlayer receiver) { if (Objects.isNull(request)) { receiver.sendSystemMessage(Component.literal(Messages.ERR_REQUEST_NOT_FOUND.get())); return; } request.getReceiver().sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_DENIES_TPA.get(), request.getSender().getName().getString()))); request.getSender().sendSystemMessage(Component.literal(String.format(Messages.SENDER_GOT_DENIED_TPA.get(), request.getReceiver().getName().getString()))); requestSet.remove(request); } public static void denyTeleportRequest(ServerPlayer receiver) { Request request = RequestGrabUtil.getReceiverRequest(receiver); denyFunctionality(request, receiver); } // Deny command is run by the receiver, hence why it's in the receiver's point of view. public static void denyTeleportRequest(ServerPlayer receiver, ServerPlayer sender) { Request request = RequestGrabUtil.getReceiverRequest(receiver, sender); denyFunctionality(request, receiver); } // Cancel command is run by the sender, hence why it's in the sender's point of view. private static void cancelFunctionality(Request request, ServerPlayer sender) { if (Objects.isNull(request)) { sender.sendSystemMessage(Component.literal(Messages.ERR_REQUEST_NOT_FOUND.get())); return; } request.getSender().sendSystemMessage(Component.literal(String.format(Messages.SENDER_CANCELS_TPA.get(), request.getReceiver().getName().getString()))); request.getReceiver().sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_GOT_CANCELLED_TPA.get(), request.getSender().getName().getString()))); requestSet.remove(request); } public static void cancelTeleportRequest(ServerPlayer sender) { Request request = RequestGrabUtil.getSenderRequest(sender); cancelFunctionality(request, sender); } public static void cancelTeleportRequest(ServerPlayer sender, ServerPlayer receiver) { Request request = RequestGrabUtil.getSenderRequest(sender, receiver); cancelFunctionality(request, sender); } // Send command is run by the sender, hence why its in the sender's point of view public static void sendTeleportRequest(ServerPlayer sender, ServerPlayer receiver, boolean isHereRequest) { if (isPlayerIdentical(sender, receiver)) { sender.sendSystemMessage(Component.literal(Messages.ERR_NO_SELF_TELEPORT.get())); return; } if (PlayerBlockingManager.isPlayerBlocked(sender, receiver)) return; // Return if one of the players has blocked the other player. PlayerData receiverData = SaveDataManager.getPlayerData(receiver); if (Boolean.FALSE.equals(Objects.isNull(receiverData)) && receiverData.getTPToggle()) { // receiverData is not null && receiver TP toggle is enabled. sender.sendSystemMessage(Component.literal(MessageParser.enhancedFormatter(Messages.ERR_RECEIVER_TP_DISABLED.get(), Map.of("receiverName", receiver.getName().getString())))); return; }
if (Boolean.FALSE.equals(Config.ALLOW_TPTOGGLED_PLAYERS_TO_SEND_REQUESTS.get())) { // Allow TPToggled players to send requests is disabled in the config
1
2023-12-02 05:41:24+00:00
16k
shawn-sheep/Activity_Diary
app/src/main/java/de/rampro/activitydiary/model/conditions/Condition.java
[ { "identifier": "ActivityDiaryApplication", "path": "app/src/main/java/de/rampro/activitydiary/ActivityDiaryApplication.java", "snippet": "public class ActivityDiaryApplication extends Application {\n\n private static Context context;\n\n public void onCreate() {\n SpeechUtility.createUtili...
import static java.lang.Thread.State.NEW; import android.content.SharedPreferences; import androidx.annotation.NonNull; import androidx.preference.PreferenceManager; import java.util.ArrayList; import java.util.List; import de.rampro.activitydiary.ActivityDiaryApplication; import de.rampro.activitydiary.db.LocalDBHelper; import de.rampro.activitydiary.helpers.ActivityHelper; import de.rampro.activitydiary.model.DiaryActivity;
11,602
/* * ActivityDiary * * Copyright (C) 2018 Raphael Mack http://www.raphael-mack.de * * 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 de.rampro.activitydiary.model.conditions; /* * Conditions model a specific aspect which influences the likelihood of the activities. **/ public abstract class Condition { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext()); public class Likelihood{
/* * ActivityDiary * * Copyright (C) 2018 Raphael Mack http://www.raphael-mack.de * * 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 de.rampro.activitydiary.model.conditions; /* * Conditions model a specific aspect which influences the likelihood of the activities. **/ public abstract class Condition { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext()); public class Likelihood{
public DiaryActivity activity;
3
2023-12-02 12:36:40+00:00
16k
Ethylene9160/Chess
src/chess/panels/WebPanel.java
[ { "identifier": "Chess", "path": "src/chess/pieces/Chess.java", "snippet": "public abstract class Chess {\n public final static String KING = \"king\", ROOK = \"rook\", QUEEN = \"queen\",\n KNIGHT = \"knight\", BISHOP = \"bishop\", PAWN = \"pawn\";\n public static Style style = Style.DE...
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.Socket; import chess.pieces.Chess; import chess.recorder.Record; import chess.shop.MoneyShop; import chess.shop.ShengwangShop; import chess.shop.Shop; import chess.style.Style; import chess.threads.OpponentEmoThread; import chess.threads.YourEmoThread; import chess.util.Constants; import chess.util.ImagePath; import chess.web.ChessChannel; import chess.web.Receiver; import chess.web.Sender;
11,390
package chess.panels; public class WebPanel extends PanelBase implements MouseListener, ActionListener, KeyListener { public final static String SIGN_SPLIT = "&", LINE_SPLIT = "#"; public final static char SIGN_SPLIT_CHAR = '&', LINE_SPLIT_CHAR = '#'; public static final char INVITE_CONNECT = 'a', NO_PERSON_FOUND = 'b', REGIST = 'c', PREPARE = 'd', APPLY_ACCOUNT = 'e', POSITION = 'f', ACCEPT_CONNECT = 'g', ERROR = 'h', APPLY_REGRET = 'i', ACCEPT_REGRET = 'j', REJECT_REGRET = 'k', SET_NAME = 'l', RESET_PASSWARD = 'm', SUCCESS_SET_PASSWARD = 'n', SYSTEM_WINDOWS = 'o', REJECT_CONNECT = 'p', FIND_ONLINE = 'q', SURREND = 'r', GET_ID = 's', SEND_MESSAGE = 't', APPLY_PEACE = 'u', AGREE_PEACE = 'v', REJECT_PEACE = 'w', DISCONNECT = 'x', PLAYER_INFO = 'y', WRONG_PASSWARD = 'z', APPLY_SWAP = 'A', AGREE_SWAP = 'B', REJECT_SWAP ='C', SERVER_CLOSE = 'D', CHANGE_HEAD = 'E', CHANGE_NAME ='F', EMO_MES ='G', SHENGBIAN = 'H', LONG_CHANGE = 'I', TO_SHENGWANG ='J', GET_MONEY = 'K'; public static final String DEFAULT_NAME = "default", COLOR_BUTTON = "Cl", DISCONNECT_BUTTON = "Db", DEFAULT_HEAD = "default.png"; private String opponentName = DEFAULT_NAME, opponentID, yourName = DEFAULT_NAME, yourID, yourHead = DEFAULT_HEAD, opponentHead = DEFAULT_HEAD, yourEmo, opponentEmo; private StringBuilder messageBuilder = new StringBuilder(); private boolean isConnect, isYouPrepare, isOpponentPrepare, isYou; private int yourColor, oOX,oOY,oNX, oNY; private JButton confirmButton, applyButton, forgetButton, emoButton, setSignButton, prepareButton, clorButton, disconnectBut; public JDialog registerDialog = new JDialog(); private JTextField account = new JTextField("10001"), passward = new JTextField("123456"); private Sender sender; private Receiver receiver; private Socket client; private YourEmoThread yourEmoThread; private OpponentEmoThread opponentEmoThread; public Shop shengwangShop, moneyShop; JTextArea textArea = new JTextArea("系统消息:\n"); JScrollPane scrollPane; private void setRegisterDialog(){ registerDialog.setLocationRelativeTo(null); registerDialog.setLayout(new GridLayout(4,2)); confirmButton = setButton("确定", Constants.CONFIRM_BUTTON); applyButton = setButton("注册", Constants.APPLY_BUTTON); forgetButton = setButton("找密码",Constants.FORGET_BUTTON); setSignButton = setButton("换签名", Constants.SIGN_BUTTON); registerDialog.setSize(159,150); registerDialog.add(new JLabel("账号")); registerDialog.add(account); registerDialog.add(new JLabel("密码")); registerDialog.add(passward); registerDialog.add(confirmButton); registerDialog.add(applyButton); registerDialog.add(forgetButton); registerDialog.add(setSignButton); } @Override public int reverseX(int x){ return 7-x; } public WebPanel(JLabel hint, String IP, int port){ shengwangShop = new ShengwangShop(this);
package chess.panels; public class WebPanel extends PanelBase implements MouseListener, ActionListener, KeyListener { public final static String SIGN_SPLIT = "&", LINE_SPLIT = "#"; public final static char SIGN_SPLIT_CHAR = '&', LINE_SPLIT_CHAR = '#'; public static final char INVITE_CONNECT = 'a', NO_PERSON_FOUND = 'b', REGIST = 'c', PREPARE = 'd', APPLY_ACCOUNT = 'e', POSITION = 'f', ACCEPT_CONNECT = 'g', ERROR = 'h', APPLY_REGRET = 'i', ACCEPT_REGRET = 'j', REJECT_REGRET = 'k', SET_NAME = 'l', RESET_PASSWARD = 'm', SUCCESS_SET_PASSWARD = 'n', SYSTEM_WINDOWS = 'o', REJECT_CONNECT = 'p', FIND_ONLINE = 'q', SURREND = 'r', GET_ID = 's', SEND_MESSAGE = 't', APPLY_PEACE = 'u', AGREE_PEACE = 'v', REJECT_PEACE = 'w', DISCONNECT = 'x', PLAYER_INFO = 'y', WRONG_PASSWARD = 'z', APPLY_SWAP = 'A', AGREE_SWAP = 'B', REJECT_SWAP ='C', SERVER_CLOSE = 'D', CHANGE_HEAD = 'E', CHANGE_NAME ='F', EMO_MES ='G', SHENGBIAN = 'H', LONG_CHANGE = 'I', TO_SHENGWANG ='J', GET_MONEY = 'K'; public static final String DEFAULT_NAME = "default", COLOR_BUTTON = "Cl", DISCONNECT_BUTTON = "Db", DEFAULT_HEAD = "default.png"; private String opponentName = DEFAULT_NAME, opponentID, yourName = DEFAULT_NAME, yourID, yourHead = DEFAULT_HEAD, opponentHead = DEFAULT_HEAD, yourEmo, opponentEmo; private StringBuilder messageBuilder = new StringBuilder(); private boolean isConnect, isYouPrepare, isOpponentPrepare, isYou; private int yourColor, oOX,oOY,oNX, oNY; private JButton confirmButton, applyButton, forgetButton, emoButton, setSignButton, prepareButton, clorButton, disconnectBut; public JDialog registerDialog = new JDialog(); private JTextField account = new JTextField("10001"), passward = new JTextField("123456"); private Sender sender; private Receiver receiver; private Socket client; private YourEmoThread yourEmoThread; private OpponentEmoThread opponentEmoThread; public Shop shengwangShop, moneyShop; JTextArea textArea = new JTextArea("系统消息:\n"); JScrollPane scrollPane; private void setRegisterDialog(){ registerDialog.setLocationRelativeTo(null); registerDialog.setLayout(new GridLayout(4,2)); confirmButton = setButton("确定", Constants.CONFIRM_BUTTON); applyButton = setButton("注册", Constants.APPLY_BUTTON); forgetButton = setButton("找密码",Constants.FORGET_BUTTON); setSignButton = setButton("换签名", Constants.SIGN_BUTTON); registerDialog.setSize(159,150); registerDialog.add(new JLabel("账号")); registerDialog.add(account); registerDialog.add(new JLabel("密码")); registerDialog.add(passward); registerDialog.add(confirmButton); registerDialog.add(applyButton); registerDialog.add(forgetButton); registerDialog.add(setSignButton); } @Override public int reverseX(int x){ return 7-x; } public WebPanel(JLabel hint, String IP, int port){ shengwangShop = new ShengwangShop(this);
moneyShop = new MoneyShop(this);
2
2023-12-01 02:33:32+00:00
16k
tuxiaobei-scu/Draw-and-guess
entry/src/main/java/com/tuxiaobei/drawandguess/slice/MainAbilitySlice.java
[ { "identifier": "MainAbility", "path": "entry/src/main/java/com/tuxiaobei/drawandguess/MainAbility.java", "snippet": "public class MainAbility extends Ability {\n @Override\n public void onStart(Intent intent) {\n super.onStart(intent);\n super.setMainRoute(MainAbilitySlice.class.get...
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT; import static ohos.security.SystemPermission.DISTRIBUTED_DATASYNC; import com.tuxiaobei.drawandguess.MainAbility; import com.tuxiaobei.drawandguess.ResourceTable; import com.tuxiaobei.drawandguess.bean.AnswerItem; import com.tuxiaobei.drawandguess.bean.MyPoint; import com.tuxiaobei.drawandguess.component.ChangeName; import com.tuxiaobei.drawandguess.component.DeviceSelectDialog; import com.tuxiaobei.drawandguess.component.DrawPoint; import com.tuxiaobei.drawandguess.component.WordSelectDialog; import com.tuxiaobei.drawandguess.game.Guesser; import com.tuxiaobei.drawandguess.game.MainGame; import com.tuxiaobei.drawandguess.provider.AnswerItemProvider; import com.tuxiaobei.drawandguess.util.GsonUtil; import com.tuxiaobei.drawandguess.util.LogUtils; import com.tuxiaobei.drawandguess.util.Tools; import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; import ohos.aafwk.content.Operation; import ohos.agp.components.*; import ohos.bundle.IBundleManager; import ohos.data.distributed.common.*; import ohos.data.distributed.user.SingleKvStore; import ohos.global.resource.NotExistException; import ohos.global.resource.WrongTypeException; import java.io.IOException; import java.util.ArrayList; import java.util.List;
10,824
super.setUIContent(ResourceTable.Layout_ability_main); storeId = STORE_ID_KEY + Tools.getRandom(); isLocal = !intent.getBooleanParam(IS_FORM_LOCAL_KEY, false); drawl = new DrawPoint(this, isLocal); findComponentById(isLocal); requestPermission(); initView(intent); initDatabase(); if (isLocal) { nameSingleKvStore.putString(Tools.getDeviceId(this), "系统"); } initDraw(intent); ohos.global.resource.ResourceManager resManager = getResourceManager(); String[] words = null; try { words = resManager.getElement(ResourceTable.Strarray_words).getStringArray(); } catch (IOException e) { e.printStackTrace(); } catch (NotExistException e) { e.printStackTrace(); } catch (WrongTypeException e) { e.printStackTrace(); } main_game = new MainGame(this, words); initListContainer(); } private void initListContainer() { answerItemProvider = new AnswerItemProvider(ansData, this, isLocal); ans_list.setItemProvider(answerItemProvider); } private void initView(Intent intent) { if (!isLocal) { local_name = Tools.getDeviceId(this).substring(0, 6); storeId = intent.getStringParam(STORE_ID_KEY); } title.setText(isLocal ? "本地端" : local_name); transform.setVisibility(isLocal ? Component.VISIBLE : Component.INVISIBLE); } private void requestPermission() { if (verifySelfPermission(DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED) { if (canRequestPermission(DISTRIBUTED_DATASYNC)) { requestPermissionsFromUser(new String[]{DISTRIBUTED_DATASYNC}, PERMISSION_CODE); } } } private void findComponentById(Boolean isLocal) { if (findComponentById(ResourceTable.Id_canvas) instanceof DependentLayout) { canvas = (DependentLayout) findComponentById(ResourceTable.Id_canvas); } if (findComponentById(ResourceTable.Id_transform) instanceof Image) { transform = (Image) findComponentById(ResourceTable.Id_transform); } if (findComponentById(ResourceTable.Id_change_name) instanceof Image) { change_name = (Image) findComponentById(ResourceTable.Id_change_name); } if (findComponentById(ResourceTable.Id_play) instanceof Image) { play = (Image) findComponentById(ResourceTable.Id_play); } if (findComponentById(ResourceTable.Id_title) instanceof Text) { title = (Text) findComponentById(ResourceTable.Id_title); } if (findComponentById(ResourceTable.Id_back) instanceof Button) { back = (Button) findComponentById(ResourceTable.Id_back); } if (findComponentById(ResourceTable.Id_ans) instanceof TextField) { ans = (TextField) findComponentById(ResourceTable.Id_ans); } if (findComponentById(ResourceTable.Id_submit) instanceof Button) { submit = (Button) findComponentById(ResourceTable.Id_submit); } if (findComponentById(ResourceTable.Id_tip) instanceof Text) { tip = (Text) findComponentById(ResourceTable.Id_tip); } if (findComponentById(ResourceTable.Id_list_answers) instanceof ListContainer) { ans_list = (ListContainer) findComponentById(ResourceTable.Id_list_answers); } if (findComponentById(ResourceTable.Id_show_score) instanceof Text) { show_score = (Text) findComponentById(ResourceTable.Id_show_score); } if (isLocal) { if (findComponentById(ResourceTable.Id_red) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_red)); } if (findComponentById(ResourceTable.Id_green) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_green)); } if (findComponentById(ResourceTable.Id_blue) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_blue)); } if (findComponentById(ResourceTable.Id_yellow) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_yellow)); } if (findComponentById(ResourceTable.Id_pink) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_pink)); } if (findComponentById(ResourceTable.Id_cyan) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_cyan)); } if (findComponentById(ResourceTable.Id_black) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_black)); } ans.setVisibility(Component.HIDE); submit.setVisibility(Component.HIDE); } else { back.setVisibility(Component.HIDE); play.setVisibility(Component.HIDE); show_score.setVisibility(Component.VISIBLE); change_name.setVisibility(Component.VISIBLE); guesser = new Guesser(submit, ans, tip, show_score, this); } transform.setClickedListener(component -> {
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuxiaobei.drawandguess.slice; /** * MainAbilitySlice * * @since 2021-04-06 */ public class MainAbilitySlice extends AbilitySlice { private static final String TAG = MainAbilitySlice.class.getName(); private static final int PERMISSION_CODE = 20201203; private static final int DELAY_TIME = 10; private static final String STORE_ID_KEY = "storeId"; private static final String POINTS_KEY = "points"; private static final String ANS_KEY = "ans"; private static final String COLOR_INDEX_KEY = "colorIndex"; private static final String IS_FORM_LOCAL_KEY = "isFormLocal"; private static String storeId; private DependentLayout canvas; private Image transform; private Image change_name; private KvManager kvManager; private SingleKvStore pointsSingleKvStore; private SingleKvStore ansSingleKvStore; private SingleKvStore nameSingleKvStore; private Text title; private DrawPoint drawl; private Image play; private Button back; private Text show_score; private Guesser guesser; private Text tip; private Button submit; private TextField ans; private MainGame main_game; private ListContainer ans_list; private final List<AnswerItem> ansData = new ArrayList<>(); private AnswerItemProvider answerItemProvider; private String deviceId; private String local_name; private boolean isLocal; @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_main); storeId = STORE_ID_KEY + Tools.getRandom(); isLocal = !intent.getBooleanParam(IS_FORM_LOCAL_KEY, false); drawl = new DrawPoint(this, isLocal); findComponentById(isLocal); requestPermission(); initView(intent); initDatabase(); if (isLocal) { nameSingleKvStore.putString(Tools.getDeviceId(this), "系统"); } initDraw(intent); ohos.global.resource.ResourceManager resManager = getResourceManager(); String[] words = null; try { words = resManager.getElement(ResourceTable.Strarray_words).getStringArray(); } catch (IOException e) { e.printStackTrace(); } catch (NotExistException e) { e.printStackTrace(); } catch (WrongTypeException e) { e.printStackTrace(); } main_game = new MainGame(this, words); initListContainer(); } private void initListContainer() { answerItemProvider = new AnswerItemProvider(ansData, this, isLocal); ans_list.setItemProvider(answerItemProvider); } private void initView(Intent intent) { if (!isLocal) { local_name = Tools.getDeviceId(this).substring(0, 6); storeId = intent.getStringParam(STORE_ID_KEY); } title.setText(isLocal ? "本地端" : local_name); transform.setVisibility(isLocal ? Component.VISIBLE : Component.INVISIBLE); } private void requestPermission() { if (verifySelfPermission(DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED) { if (canRequestPermission(DISTRIBUTED_DATASYNC)) { requestPermissionsFromUser(new String[]{DISTRIBUTED_DATASYNC}, PERMISSION_CODE); } } } private void findComponentById(Boolean isLocal) { if (findComponentById(ResourceTable.Id_canvas) instanceof DependentLayout) { canvas = (DependentLayout) findComponentById(ResourceTable.Id_canvas); } if (findComponentById(ResourceTable.Id_transform) instanceof Image) { transform = (Image) findComponentById(ResourceTable.Id_transform); } if (findComponentById(ResourceTable.Id_change_name) instanceof Image) { change_name = (Image) findComponentById(ResourceTable.Id_change_name); } if (findComponentById(ResourceTable.Id_play) instanceof Image) { play = (Image) findComponentById(ResourceTable.Id_play); } if (findComponentById(ResourceTable.Id_title) instanceof Text) { title = (Text) findComponentById(ResourceTable.Id_title); } if (findComponentById(ResourceTable.Id_back) instanceof Button) { back = (Button) findComponentById(ResourceTable.Id_back); } if (findComponentById(ResourceTable.Id_ans) instanceof TextField) { ans = (TextField) findComponentById(ResourceTable.Id_ans); } if (findComponentById(ResourceTable.Id_submit) instanceof Button) { submit = (Button) findComponentById(ResourceTable.Id_submit); } if (findComponentById(ResourceTable.Id_tip) instanceof Text) { tip = (Text) findComponentById(ResourceTable.Id_tip); } if (findComponentById(ResourceTable.Id_list_answers) instanceof ListContainer) { ans_list = (ListContainer) findComponentById(ResourceTable.Id_list_answers); } if (findComponentById(ResourceTable.Id_show_score) instanceof Text) { show_score = (Text) findComponentById(ResourceTable.Id_show_score); } if (isLocal) { if (findComponentById(ResourceTable.Id_red) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_red)); } if (findComponentById(ResourceTable.Id_green) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_green)); } if (findComponentById(ResourceTable.Id_blue) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_blue)); } if (findComponentById(ResourceTable.Id_yellow) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_yellow)); } if (findComponentById(ResourceTable.Id_pink) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_pink)); } if (findComponentById(ResourceTable.Id_cyan) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_cyan)); } if (findComponentById(ResourceTable.Id_black) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_black)); } ans.setVisibility(Component.HIDE); submit.setVisibility(Component.HIDE); } else { back.setVisibility(Component.HIDE); play.setVisibility(Component.HIDE); show_score.setVisibility(Component.VISIBLE); change_name.setVisibility(Component.VISIBLE); guesser = new Guesser(submit, ans, tip, show_score, this); } transform.setClickedListener(component -> {
DeviceSelectDialog dialog = new DeviceSelectDialog(MainAbilitySlice.this);
5
2023-12-03 13:36:00+00:00
16k
godheaven/klib-data-jdbc
src/main/java/cl/kanopus/jdbc/impl/AbstractDAO.java
[ { "identifier": "DAOInterface", "path": "src/main/java/cl/kanopus/jdbc/DAOInterface.java", "snippet": "public interface DAOInterface<T, I> {\r\n\r\n long generateID() throws DataException;\r\n\r\n void persist(T entity) throws DataException;\r\n\r\n int update(T entity) throws DataException;\r\...
import cl.kanopus.common.data.Paginator; import cl.kanopus.common.data.enums.SortOrder; import cl.kanopus.common.enums.EnumIdentifiable; import cl.kanopus.common.util.CryptographyUtils; import cl.kanopus.common.util.GsonUtils; import cl.kanopus.common.util.Utils; import cl.kanopus.jdbc.DAOInterface; import cl.kanopus.jdbc.entity.Mapping; import cl.kanopus.jdbc.entity.annotation.Column; import cl.kanopus.jdbc.entity.annotation.ColumnGroup; import cl.kanopus.jdbc.entity.annotation.JoinTable; import cl.kanopus.jdbc.entity.annotation.Table; import cl.kanopus.jdbc.entity.mapper.AbstractRowMapper; import cl.kanopus.jdbc.exception.DataException; import cl.kanopus.jdbc.impl.engine.CustomEngine; import cl.kanopus.jdbc.impl.engine.Engine; import cl.kanopus.jdbc.impl.engine.OracleEngine; import cl.kanopus.jdbc.impl.engine.PostgresEngine; import cl.kanopus.jdbc.impl.engine.SQLServerEngine; import cl.kanopus.jdbc.util.JdbcCache; import cl.kanopus.jdbc.util.QueryIterator; import cl.kanopus.jdbc.util.SQLQueryDynamic; import cl.kanopus.jdbc.util.parser.ByteaJsonListParser; import cl.kanopus.jdbc.util.parser.ByteaJsonParser; import cl.kanopus.jdbc.util.parser.EnumParser; import cl.kanopus.jdbc.util.parser.JsonListParser; import cl.kanopus.jdbc.util.parser.JsonParser; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.postgresql.util.PGobject; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcCall;
13,284
package cl.kanopus.jdbc.impl; /** * This abstract class defines methods for data access that are common, * generally, all kinds of data access DAO must implement this class.Thus it is * given safely access the Connection database. The JdbcTemplate property is * kept private and gives access to the database through the methods implemented * in this AbstractDAO. * * @param <T> * @param <ID> * @author Pablo Diaz Saavedra * @email pabloandres.diazsaavedra@gmail.com * */ @SuppressWarnings("all") public abstract class AbstractDAO<T extends Mapping, ID> implements DAOInterface<T, ID> { enum Operation { UPDATE, PERSIST } private final Class<T> genericTypeClass; protected AbstractDAO() { Type type = getClass().getGenericSuperclass(); ParameterizedType paramType = (ParameterizedType) type; genericTypeClass = (Class<T>) paramType.getActualTypeArguments()[0]; } protected abstract NamedParameterJdbcTemplate getJdbcTemplate(); private static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1; protected abstract Engine getEngine(); private String createSqlPagination2Engine(SQLQueryDynamic sqlQuery) { String sql = getCustom().prepareSQL2Engine(sqlQuery.getSQL()); if (sqlQuery.isLimited()) { return getCustom().createSqlPagination(sql, sqlQuery.getLimit(), sqlQuery.getOffset()).toString(); } else { return sql; } } private String createSqlPagination(String sql, int limit, int offset) { return getCustom().createSqlPagination(sql, limit, offset).toString(); } @Override
package cl.kanopus.jdbc.impl; /** * This abstract class defines methods for data access that are common, * generally, all kinds of data access DAO must implement this class.Thus it is * given safely access the Connection database. The JdbcTemplate property is * kept private and gives access to the database through the methods implemented * in this AbstractDAO. * * @param <T> * @param <ID> * @author Pablo Diaz Saavedra * @email pabloandres.diazsaavedra@gmail.com * */ @SuppressWarnings("all") public abstract class AbstractDAO<T extends Mapping, ID> implements DAOInterface<T, ID> { enum Operation { UPDATE, PERSIST } private final Class<T> genericTypeClass; protected AbstractDAO() { Type type = getClass().getGenericSuperclass(); ParameterizedType paramType = (ParameterizedType) type; genericTypeClass = (Class<T>) paramType.getActualTypeArguments()[0]; } protected abstract NamedParameterJdbcTemplate getJdbcTemplate(); private static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1; protected abstract Engine getEngine(); private String createSqlPagination2Engine(SQLQueryDynamic sqlQuery) { String sql = getCustom().prepareSQL2Engine(sqlQuery.getSQL()); if (sqlQuery.isLimited()) { return getCustom().createSqlPagination(sql, sqlQuery.getLimit(), sqlQuery.getOffset()).toString(); } else { return sql; } } private String createSqlPagination(String sql, int limit, int offset) { return getCustom().createSqlPagination(sql, limit, offset).toString(); } @Override
public int deleteByID(ID id) throws DataException {
3
2023-11-27 18:25:00+00:00
16k
andre111/voxedit
src/client/java/me/andre111/voxedit/client/VoxEditClient.java
[ { "identifier": "Presets", "path": "src/main/java/me/andre111/voxedit/Presets.java", "snippet": "public class Presets {\n\tpublic static final ToolItem.Data andre111;\n\tpublic static final ItemStack andre111Stack;\n\tstatic {\n\t\tandre111 = new ToolItem.Data(Util.make(new ArrayList<>(), list -> {\n\t\...
import org.lwjgl.glfw.GLFW; import org.spongepowered.include.com.google.common.base.Objects; import me.andre111.voxedit.Presets; import me.andre111.voxedit.VoxEdit; import me.andre111.voxedit.client.gui.screen.ToolSelectionScreen; import me.andre111.voxedit.client.network.ClientNetworking; import me.andre111.voxedit.client.renderer.EditorRenderer; import me.andre111.voxedit.client.renderer.HudRenderer; import me.andre111.voxedit.client.renderer.SelectionRenderer; import me.andre111.voxedit.client.renderer.ToolRenderer; import me.andre111.voxedit.item.ToolItem; import me.andre111.voxedit.item.VoxEditItem; import me.andre111.voxedit.network.Command; import me.andre111.voxedit.tool.ConfiguredTool; import me.andre111.voxedit.tool.Tool; import me.andre111.voxedit.tool.config.ToolConfig; import me.andre111.voxedit.tool.data.Selection; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; import net.fabricmc.fabric.api.client.rendering.v1.BuiltinItemRendererRegistry; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents; import net.fabricmc.fabric.api.event.client.player.ClientPreAttackCallback; import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.option.KeyBinding; import net.minecraft.client.util.InputUtil; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.text.Text; import net.minecraft.util.hit.BlockHitResult;
11,776
/* * Copyright (c) 2023 André Schweiger * * 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 me.andre111.voxedit.client; @Environment(value=EnvType.CLIENT) public class VoxEditClient implements ClientModInitializer { public static final KeyBinding INCREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_UP, "key.category.voxedit")); public static final KeyBinding DECREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_DOWN, "key.category.voxedit")); public static final KeyBinding INCREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_ADD, "key.category.voxedit")); public static final KeyBinding DECREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_SUBTRACT, "key.category.voxedit")); public static final KeyBinding UNDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.undo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Z, "key.category.voxedit")); public static final KeyBinding REDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.redo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Y, "key.category.voxedit")); public static final KeyBinding OPEN_MENU = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.openMenu", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_V, "key.category.voxedit")); public static int retargetCooldown; @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void onInitializeClient() { ClientNetworking.init(); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_TOOL, ToolRenderer.INSTANCE); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_EDITOR, EditorRenderer.INSTANCE); HudRenderer.init(); ItemGroupEvents.MODIFY_ENTRIES_ALL.register((group, entries) -> { if(group.getType() == ItemGroup.Type.CATEGORY && entries.shouldShowOpRestrictedItems()) { boolean hasCB = entries.getDisplayStacks().stream().filter(stack -> stack.getItem() == Items.COMMAND_BLOCK).findAny().isPresent(); if(hasCB) { for(Tool<?, ?> tool : VoxEdit.TOOL_REGISTRY) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(tool.getDefault())); for(ToolConfig config : tool.getAdditionalCreativeMenuConfigs()) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(new ConfiguredTool(tool, config))); } } entries.add(Presets.andre111Stack); entries.add(VoxEdit.ITEM_EDITOR.getDefaultStack()); } } }); ClientTickEvents.START_CLIENT_TICK.register((mc) -> { if(mc.world != null && mc.player != null) tick(); }); WorldRenderEvents.LAST.register((context) -> { render(context.matrixStack(), context.tickDelta()); }); ClientPreAttackCallback.EVENT.register((client, player, clickCount) -> { ItemStack stack = player.getMainHandStack(); if(stack.getItem() instanceof VoxEditItem) { if(player.isCreative() && MinecraftClient.getInstance().attackCooldown <= 0) { MinecraftClient.getInstance().attackCooldown = 5; ClientNetworking.sendCommand(Command.LEFT_CLICK); } return true; } return false; }); } public static void tick() { if(retargetCooldown > 0) retargetCooldown--; ClientState.player = MinecraftClient.getInstance().player; ToolItem.Data oldActive = ClientState.active; BlockHitResult oldTarget = ClientState.target; ClientState.active = null; ItemStack stack = ClientState.player.getMainHandStack(); if(stack.getItem() instanceof ToolItem toolItem) { ClientState.active = ToolItem.readToolData(stack); } if(ClientState.active != null) { if(oldActive == null || !ClientState.active.selected().equals(oldActive.selected())) { HudRenderer.getToolSettingsScreen().rebuild(); ClientState.positions = null; } if(MinecraftClient.getInstance().currentScreen != null) return;
/* * Copyright (c) 2023 André Schweiger * * 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 me.andre111.voxedit.client; @Environment(value=EnvType.CLIENT) public class VoxEditClient implements ClientModInitializer { public static final KeyBinding INCREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_UP, "key.category.voxedit")); public static final KeyBinding DECREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_DOWN, "key.category.voxedit")); public static final KeyBinding INCREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_ADD, "key.category.voxedit")); public static final KeyBinding DECREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_SUBTRACT, "key.category.voxedit")); public static final KeyBinding UNDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.undo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Z, "key.category.voxedit")); public static final KeyBinding REDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.redo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Y, "key.category.voxedit")); public static final KeyBinding OPEN_MENU = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.openMenu", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_V, "key.category.voxedit")); public static int retargetCooldown; @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void onInitializeClient() { ClientNetworking.init(); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_TOOL, ToolRenderer.INSTANCE); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_EDITOR, EditorRenderer.INSTANCE); HudRenderer.init(); ItemGroupEvents.MODIFY_ENTRIES_ALL.register((group, entries) -> { if(group.getType() == ItemGroup.Type.CATEGORY && entries.shouldShowOpRestrictedItems()) { boolean hasCB = entries.getDisplayStacks().stream().filter(stack -> stack.getItem() == Items.COMMAND_BLOCK).findAny().isPresent(); if(hasCB) { for(Tool<?, ?> tool : VoxEdit.TOOL_REGISTRY) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(tool.getDefault())); for(ToolConfig config : tool.getAdditionalCreativeMenuConfigs()) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(new ConfiguredTool(tool, config))); } } entries.add(Presets.andre111Stack); entries.add(VoxEdit.ITEM_EDITOR.getDefaultStack()); } } }); ClientTickEvents.START_CLIENT_TICK.register((mc) -> { if(mc.world != null && mc.player != null) tick(); }); WorldRenderEvents.LAST.register((context) -> { render(context.matrixStack(), context.tickDelta()); }); ClientPreAttackCallback.EVENT.register((client, player, clickCount) -> { ItemStack stack = player.getMainHandStack(); if(stack.getItem() instanceof VoxEditItem) { if(player.isCreative() && MinecraftClient.getInstance().attackCooldown <= 0) { MinecraftClient.getInstance().attackCooldown = 5; ClientNetworking.sendCommand(Command.LEFT_CLICK); } return true; } return false; }); } public static void tick() { if(retargetCooldown > 0) retargetCooldown--; ClientState.player = MinecraftClient.getInstance().player; ToolItem.Data oldActive = ClientState.active; BlockHitResult oldTarget = ClientState.target; ClientState.active = null; ItemStack stack = ClientState.player.getMainHandStack(); if(stack.getItem() instanceof ToolItem toolItem) { ClientState.active = ToolItem.readToolData(stack); } if(ClientState.active != null) { if(oldActive == null || !ClientState.active.selected().equals(oldActive.selected())) { HudRenderer.getToolSettingsScreen().rebuild(); ClientState.positions = null; } if(MinecraftClient.getInstance().currentScreen != null) return;
ClientState.target = Selection.getTargetOf(ClientState.player, ClientState.active.selected().config());
13
2023-12-01 15:12:26+00:00
16k
bioastroiner/Minetweaker-Gregtech6-Addon
src/main/java/mods/bio/gttweaker/core/GTTweaker.java
[ { "identifier": "IMaterial", "path": "src/main/java/mods/bio/gttweaker/api/mods/gregtech/oredict/IMaterial.java", "snippet": "@ZenClass(\"mods.gregtech.oredict.IMaterial\")\npublic interface IMaterial {\n\tOreDictMaterial getMaterial();\n\n\t@ZenOperator(OperatorType.MUL)\n\tIMaterialStack multiply(long...
import cpw.mods.fml.common.event.FMLInitializationEvent; import gregapi.recipes.Recipe; import minetweaker.MineTweakerAPI; import minetweaker.MineTweakerImplementationAPI; import minetweaker.api.item.IIngredient; import minetweaker.util.IEventHandler; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterial; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialData; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialStack; import mods.bio.gttweaker.api.mods.gregtech.oredict.IPrefix; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipe; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipeFactory; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipeMap; import mods.bio.gttweaker.core.command.GTCommand; import mods.bio.gttweaker.core.json.OreDictMaterial_Serializable; import mods.bio.gttweaker.mods.gregtech.oredict.*; import mods.bio.gttweaker.mods.gregtech.recipe.CTRecipe; import mods.bio.gttweaker.mods.gregtech.recipe.CTRecipeMaps; import mods.bio.gttweaker.mods.gregtech.oredict.bracket.CTMaterialBracketHandler; import mods.bio.gttweaker.mods.gregtech.oredict.bracket.CTPrefixBracketHandler; import mods.bio.gttweaker.mods.gregtech.recipe.bracket.CTRecipeMapBracketHandler; import mods.bio.gttweaker.mods.minetweaker.CTIItemStackExpansion; import mods.bio.gttweaker.mods.minetweaker.CTILiquidStackExpansion; import mods.bio.gttweaker.mods.minetweaker.CTIOreDictExpansion; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import java.util.Objects;
11,271
package mods.bio.gttweaker.core; @cpw.mods.fml.common.Mod(modid = GTTweaker.MOD_ID, name = GTTweaker.MOD_NAME, version = GTTweaker.VERSION) public final class GTTweaker extends gregapi.api.Abstract_Mod { // https://github.com/GTNewHorizons/Minetweaker-Gregtech-5-Addon/blob/master/src/main/java/gttweaker/GTTweaker.java public static final String MOD_ID = "GRADLETOKEN_MODID"; public static final String MOD_NAME = "GRADLETOKEN_MODNAME"; public static final String VERSION = "GRADLETOKEN_VERSION"; public static final String GROUPNAME = "GRADLETOKEN_GROUPNAME"; public static gregapi.code.ModData MOD_DATA = new gregapi.code.ModData(MOD_ID, MOD_NAME); //@cpw.mods.fml.common.SidedProxy(modId = MOD_ID, clientSide = "gregapi.api.example.Example_Proxy_Client", serverSide = "gregapi.api.example.Example_Proxy_Server") public static gregapi.api.Abstract_Proxy PROXY; public static String FORMAT_RECIPE_MAP(Recipe.RecipeMap map){ String[] tmp = map.toString().split("\\."); return tmp[tmp.length-1]; } public static Recipe.RecipeMap FORMAT_RECIPE_MAP(String name){ Recipe.RecipeMap out = null; if(Recipe.RecipeMap.RECIPE_MAPS.containsKey(name)){ out = Recipe.RecipeMap.RECIPE_MAPS.get(name); } if(out == null) for (Recipe.RecipeMap map: Recipe.RecipeMap.RECIPE_MAP_LIST) { String[] tmp = map.toString().split("\\."); String sName = tmp[tmp.length-1]; if(Objects.equals(sName.toLowerCase(),name.toLowerCase())){ out = map; } } if(out!=null){ return out; } else { MineTweakerAPI.logError(name + " is not a valid recipemap name!"); } return out; } public GTTweaker() { } @Override public String getModID() { return MOD_ID; } @Override public String getModName() { return MOD_NAME; } @Override public String getModNameForLog() { return "GTTWEAKER"; } @Override public gregapi.api.Abstract_Proxy getProxy() { return PROXY; } // Do not change these 7 Functions. Just keep them this way. @cpw.mods.fml.common.Mod.EventHandler public final void onPreLoad(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { onModPreInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onLoad(cpw.mods.fml.common.event.FMLInitializationEvent aEvent) { onModInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onPostLoad(cpw.mods.fml.common.event.FMLPostInitializationEvent aEvent) { onModPostInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarting(cpw.mods.fml.common.event.FMLServerStartingEvent aEvent) { onModServerStarting(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarted(cpw.mods.fml.common.event.FMLServerStartedEvent aEvent) { onModServerStarted(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopping(cpw.mods.fml.common.event.FMLServerStoppingEvent aEvent) { onModServerStopping(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopped(cpw.mods.fml.common.event.FMLServerStoppedEvent aEvent) { onModServerStopped(aEvent); } @Override public void onModPreInit2(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { } @Override public void onModInit2(FMLInitializationEvent aEvent) { OreDictMaterial_Serializable._INITLIZE(); MineTweakerAPI.registerClass(IRecipe.class); MineTweakerAPI.registerClass(IRecipeFactory.class); MineTweakerAPI.registerClass(IRecipeMap.class); MineTweakerAPI.registerClass(IMaterial.class);
package mods.bio.gttweaker.core; @cpw.mods.fml.common.Mod(modid = GTTweaker.MOD_ID, name = GTTweaker.MOD_NAME, version = GTTweaker.VERSION) public final class GTTweaker extends gregapi.api.Abstract_Mod { // https://github.com/GTNewHorizons/Minetweaker-Gregtech-5-Addon/blob/master/src/main/java/gttweaker/GTTweaker.java public static final String MOD_ID = "GRADLETOKEN_MODID"; public static final String MOD_NAME = "GRADLETOKEN_MODNAME"; public static final String VERSION = "GRADLETOKEN_VERSION"; public static final String GROUPNAME = "GRADLETOKEN_GROUPNAME"; public static gregapi.code.ModData MOD_DATA = new gregapi.code.ModData(MOD_ID, MOD_NAME); //@cpw.mods.fml.common.SidedProxy(modId = MOD_ID, clientSide = "gregapi.api.example.Example_Proxy_Client", serverSide = "gregapi.api.example.Example_Proxy_Server") public static gregapi.api.Abstract_Proxy PROXY; public static String FORMAT_RECIPE_MAP(Recipe.RecipeMap map){ String[] tmp = map.toString().split("\\."); return tmp[tmp.length-1]; } public static Recipe.RecipeMap FORMAT_RECIPE_MAP(String name){ Recipe.RecipeMap out = null; if(Recipe.RecipeMap.RECIPE_MAPS.containsKey(name)){ out = Recipe.RecipeMap.RECIPE_MAPS.get(name); } if(out == null) for (Recipe.RecipeMap map: Recipe.RecipeMap.RECIPE_MAP_LIST) { String[] tmp = map.toString().split("\\."); String sName = tmp[tmp.length-1]; if(Objects.equals(sName.toLowerCase(),name.toLowerCase())){ out = map; } } if(out!=null){ return out; } else { MineTweakerAPI.logError(name + " is not a valid recipemap name!"); } return out; } public GTTweaker() { } @Override public String getModID() { return MOD_ID; } @Override public String getModName() { return MOD_NAME; } @Override public String getModNameForLog() { return "GTTWEAKER"; } @Override public gregapi.api.Abstract_Proxy getProxy() { return PROXY; } // Do not change these 7 Functions. Just keep them this way. @cpw.mods.fml.common.Mod.EventHandler public final void onPreLoad(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { onModPreInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onLoad(cpw.mods.fml.common.event.FMLInitializationEvent aEvent) { onModInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onPostLoad(cpw.mods.fml.common.event.FMLPostInitializationEvent aEvent) { onModPostInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarting(cpw.mods.fml.common.event.FMLServerStartingEvent aEvent) { onModServerStarting(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarted(cpw.mods.fml.common.event.FMLServerStartedEvent aEvent) { onModServerStarted(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopping(cpw.mods.fml.common.event.FMLServerStoppingEvent aEvent) { onModServerStopping(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopped(cpw.mods.fml.common.event.FMLServerStoppedEvent aEvent) { onModServerStopped(aEvent); } @Override public void onModPreInit2(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { } @Override public void onModInit2(FMLInitializationEvent aEvent) { OreDictMaterial_Serializable._INITLIZE(); MineTweakerAPI.registerClass(IRecipe.class); MineTweakerAPI.registerClass(IRecipeFactory.class); MineTweakerAPI.registerClass(IRecipeMap.class); MineTweakerAPI.registerClass(IMaterial.class);
MineTweakerAPI.registerClass(IMaterialStack.class);
2
2023-12-03 11:55:49+00:00
16k
tuxiaobei-scu/SCU-CCSOJ-Backend
DataBackup/src/main/java/top/hcode/hoj/manager/oj/ContestManager.java
[ { "identifier": "StatusFailException", "path": "DataBackup/src/main/java/top/hcode/hoj/common/exception/StatusFailException.java", "snippet": "public class StatusFailException extends Exception{\n public StatusFailException() {\n }\n\n public StatusFailException(String message) {\n super...
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import top.hcode.hoj.common.exception.StatusFailException; import top.hcode.hoj.common.exception.StatusForbiddenException; import top.hcode.hoj.common.exception.StatusNotFoundException; import top.hcode.hoj.common.result.CommonResult; import top.hcode.hoj.dao.common.AnnouncementEntityService; import top.hcode.hoj.dao.contest.*; import top.hcode.hoj.dao.discussion.CommentEntityService; import top.hcode.hoj.dao.group.GroupMemberEntityService; import top.hcode.hoj.dao.judge.JudgeEntityService; import top.hcode.hoj.dao.problem.*; import top.hcode.hoj.dao.user.UserInfoEntityService; import top.hcode.hoj.pojo.dto.ContestPrintDto; import top.hcode.hoj.pojo.dto.ContestRankDto; import top.hcode.hoj.pojo.dto.RegisterContestDto; import top.hcode.hoj.pojo.dto.UserReadContestAnnouncementDto; import top.hcode.hoj.pojo.entity.common.Announcement; import top.hcode.hoj.pojo.entity.contest.*; import top.hcode.hoj.pojo.entity.problem.*; import top.hcode.hoj.pojo.vo.*; import top.hcode.hoj.utils.Constants; import top.hcode.hoj.utils.RedisUtils; import top.hcode.hoj.validator.ContestValidator; import top.hcode.hoj.validator.GroupValidator; import java.util.*; import java.util.stream.Collectors;
12,100
package top.hcode.hoj.manager.oj; /** * @Author: Himit_ZH * @Date: 2022/3/11 22:26 * @Description: */ @Component public class ContestManager { @Autowired private ContestEntityService contestEntityService; @Autowired private ProblemCaseEntityService problemCaseEntityService; @Autowired private ContestRecordEntityService contestRecordEntityService; @Autowired private ContestProblemEntityService contestProblemEntityService; @Autowired private ContestAnnouncementEntityService contestAnnouncementEntityService; @Autowired private AnnouncementEntityService announcementEntityService; @Autowired private ContestRegisterEntityService contestRegisterEntityService; @Autowired private ProblemEntityService problemEntityService; @Autowired private ProblemTagEntityService problemTagEntityService; @Autowired private TagEntityService tagEntityService; @Autowired private LanguageEntityService languageEntityService; @Autowired private ProblemLanguageEntityService problemLanguageEntityService; @Autowired private JudgeEntityService judgeEntityService; @Autowired private CodeTemplateEntityService codeTemplateEntityService; @Autowired private ContestPrintEntityService contestPrintEntityService; @Autowired private UserInfoEntityService userInfoEntityService; @Autowired private RedisUtils redisUtils; @Autowired private CommentEntityService commentEntityService; @Autowired private ContestValidator contestValidator; @Autowired private ContestRankManager contestRankManager; @Autowired private GroupMemberEntityService groupMemberEntityService; @Autowired
package top.hcode.hoj.manager.oj; /** * @Author: Himit_ZH * @Date: 2022/3/11 22:26 * @Description: */ @Component public class ContestManager { @Autowired private ContestEntityService contestEntityService; @Autowired private ProblemCaseEntityService problemCaseEntityService; @Autowired private ContestRecordEntityService contestRecordEntityService; @Autowired private ContestProblemEntityService contestProblemEntityService; @Autowired private ContestAnnouncementEntityService contestAnnouncementEntityService; @Autowired private AnnouncementEntityService announcementEntityService; @Autowired private ContestRegisterEntityService contestRegisterEntityService; @Autowired private ProblemEntityService problemEntityService; @Autowired private ProblemTagEntityService problemTagEntityService; @Autowired private TagEntityService tagEntityService; @Autowired private LanguageEntityService languageEntityService; @Autowired private ProblemLanguageEntityService problemLanguageEntityService; @Autowired private JudgeEntityService judgeEntityService; @Autowired private CodeTemplateEntityService codeTemplateEntityService; @Autowired private ContestPrintEntityService contestPrintEntityService; @Autowired private UserInfoEntityService userInfoEntityService; @Autowired private RedisUtils redisUtils; @Autowired private CommentEntityService commentEntityService; @Autowired private ContestValidator contestValidator; @Autowired private ContestRankManager contestRankManager; @Autowired private GroupMemberEntityService groupMemberEntityService; @Autowired
private GroupValidator groupValidator;
17
2023-12-03 14:15:51+00:00
16k
yichenhsiaonz/EscAIpe-room-final
src/main/java/nz/ac/auckland/se206/GameState.java
[ { "identifier": "SharedElements", "path": "src/main/java/nz/ac/auckland/se206/controllers/SharedElements.java", "snippet": "public class SharedElements {\n\n private static SharedElements instance;\n private static HBox[] taskBarHorizontalBoxList = new HBox[3];\n private static VBox[] inventoryVBoxLi...
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Random; import javafx.animation.FadeTransition; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.ParallelTransition; import javafx.animation.ScaleTransition; import javafx.animation.Timeline; import javafx.animation.TranslateTransition; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.event.EventHandler; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.util.Duration; import nz.ac.auckland.se206.controllers.SharedElements; import nz.ac.auckland.se206.gpt.ChatMessage; import nz.ac.auckland.se206.gpt.GptPromptEngineering; import nz.ac.auckland.se206.gpt.openai.ApiProxyException; import nz.ac.auckland.se206.gpt.openai.ChatCompletionRequest; import nz.ac.auckland.se206.gpt.openai.ChatCompletionResult; import nz.ac.auckland.se206.gpt.openai.ChatCompletionResult.Choice;
12,128
package nz.ac.auckland.se206; /** Represents the state of the game. */ public class GameState { /** The items that the player can pick up. */ public enum Items { BREAD_TOASTED, BREAD_UNTOASTED, PAPER, USB } private static GameState instance; private static int windowWidth = 1920; private static int windowHeight = 1080; private static int width = 1920; private static int height = 1080; public static boolean hasBread = false; public static boolean hasToast = false; public static boolean toasterPuzzleHints = true; public static boolean paperPuzzleHints = true; public static boolean computerPuzzleHints = true; public static boolean isExitUnlocked = false; public static boolean isUsbEnding = false; public static String code; public static String endingCongrats = ""; public static String endingReveal = ""; public static String usbEndingReveal = ""; private static HashMap<Items, ImageView[]> inventoryMap = new HashMap<Items, ImageView[]>(); private static MediaPlayer mediaPlayer; private static boolean moving = false; /** Resets fields to start a new game. */ public static void newGame() { // reset flags endingCongrats = ""; endingReveal = ""; usbEndingReveal = ""; hasBread = false; hasToast = false; toasterPuzzleHints = true; paperPuzzleHints = true; computerPuzzleHints = true; isExitUnlocked = false; isUsbEnding = false; moving = false; // create new instance instance = new GameState(); } public static void foundUsb() { isUsbEnding = true; } private static void inventoryMapAdd(Items item, ImageView[] itemImageView) { // add list of instances of identical items to the map inventoryMap.put(item, itemImageView); } /** This method starts the timer of the game. */ public static void startTimer() { // allocate a thread to the timer System.out.println(instance.chosenTime); instance.timerThread = new Thread(instance.timerTask); instance.timerThread.start(); } public static Task<Void> getTimer() { // return the currently running timer return instance.timerTask; } public static void stopTimer() { // stop the timer instance.timerThread.interrupt(); } /** * This method sets the difficulty of the game for the user. * * @param difficulty the difficulty of the game */ public static void setDifficulty(int difficulty) { // set the difficulty and update the hints button accordingly instance.chosenDifficulty = difficulty; instance.hints = difficulty; SharedElements.setHintsText(instance.hints); } public static int getDifficulty() { return instance.chosenDifficulty; } public static void setTime(int time) { instance.chosenTime = time; } public static void setWidth(int newWidth) { width = newWidth; } public static void setHeight(int newHeight) { height = newHeight; } public static void setWindowWidth(int width) { windowWidth = width; } public static void setWindowHeight(int height) { windowHeight = height; } public static int getWindowHeight() { return height; } public static int getWindowWidth() { return width; } public static String getSecondDigits() { return String.valueOf(instance.secondDigits); } public static boolean getMuted() { return instance.muted; } /** This method toggles whether the game is muted or not. */ public static void toggleMuted() { SharedElements.toggleMuteText(); instance.muted = !instance.muted; if (instance.muted) { TextToSpeechManager.cutOff(); stopSound(); } } /** * Gets a response from GPT the AI application. * * @param msg the message to send to GPT * @param hintFlag whether the message is a hint * @return the response from GPT * @throws ApiProxyException if there is an error with the API */
package nz.ac.auckland.se206; /** Represents the state of the game. */ public class GameState { /** The items that the player can pick up. */ public enum Items { BREAD_TOASTED, BREAD_UNTOASTED, PAPER, USB } private static GameState instance; private static int windowWidth = 1920; private static int windowHeight = 1080; private static int width = 1920; private static int height = 1080; public static boolean hasBread = false; public static boolean hasToast = false; public static boolean toasterPuzzleHints = true; public static boolean paperPuzzleHints = true; public static boolean computerPuzzleHints = true; public static boolean isExitUnlocked = false; public static boolean isUsbEnding = false; public static String code; public static String endingCongrats = ""; public static String endingReveal = ""; public static String usbEndingReveal = ""; private static HashMap<Items, ImageView[]> inventoryMap = new HashMap<Items, ImageView[]>(); private static MediaPlayer mediaPlayer; private static boolean moving = false; /** Resets fields to start a new game. */ public static void newGame() { // reset flags endingCongrats = ""; endingReveal = ""; usbEndingReveal = ""; hasBread = false; hasToast = false; toasterPuzzleHints = true; paperPuzzleHints = true; computerPuzzleHints = true; isExitUnlocked = false; isUsbEnding = false; moving = false; // create new instance instance = new GameState(); } public static void foundUsb() { isUsbEnding = true; } private static void inventoryMapAdd(Items item, ImageView[] itemImageView) { // add list of instances of identical items to the map inventoryMap.put(item, itemImageView); } /** This method starts the timer of the game. */ public static void startTimer() { // allocate a thread to the timer System.out.println(instance.chosenTime); instance.timerThread = new Thread(instance.timerTask); instance.timerThread.start(); } public static Task<Void> getTimer() { // return the currently running timer return instance.timerTask; } public static void stopTimer() { // stop the timer instance.timerThread.interrupt(); } /** * This method sets the difficulty of the game for the user. * * @param difficulty the difficulty of the game */ public static void setDifficulty(int difficulty) { // set the difficulty and update the hints button accordingly instance.chosenDifficulty = difficulty; instance.hints = difficulty; SharedElements.setHintsText(instance.hints); } public static int getDifficulty() { return instance.chosenDifficulty; } public static void setTime(int time) { instance.chosenTime = time; } public static void setWidth(int newWidth) { width = newWidth; } public static void setHeight(int newHeight) { height = newHeight; } public static void setWindowWidth(int width) { windowWidth = width; } public static void setWindowHeight(int height) { windowHeight = height; } public static int getWindowHeight() { return height; } public static int getWindowWidth() { return width; } public static String getSecondDigits() { return String.valueOf(instance.secondDigits); } public static boolean getMuted() { return instance.muted; } /** This method toggles whether the game is muted or not. */ public static void toggleMuted() { SharedElements.toggleMuteText(); instance.muted = !instance.muted; if (instance.muted) { TextToSpeechManager.cutOff(); stopSound(); } } /** * Gets a response from GPT the AI application. * * @param msg the message to send to GPT * @param hintFlag whether the message is a hint * @return the response from GPT * @throws ApiProxyException if there is an error with the API */
public static ChatMessage runGpt(ChatMessage msg, boolean hintFlag) throws ApiProxyException {
1
2023-12-02 04:57:43+00:00
16k
nageoffer/shortlink
project/src/main/java/com/nageoffer/shortlink/project/service/impl/ShortLinkStatsServiceImpl.java
[ { "identifier": "LinkAccessLogsDO", "path": "project/src/main/java/com/nageoffer/shortlink/project/dao/entity/LinkAccessLogsDO.java", "snippet": "@Data\n@TableName(\"t_link_access_logs\")\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class LinkAccessLogsDO extends BaseDO {\n\n /**\n ...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateField; import cn.hutool.core.date.DateUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.nageoffer.shortlink.project.dao.entity.LinkAccessLogsDO; import com.nageoffer.shortlink.project.dao.entity.LinkAccessStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkDeviceStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkLocaleStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkNetworkStatsDO; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessLogsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkBrowserStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkDeviceStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkLocaleStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkNetworkStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkOsStatsMapper; import com.nageoffer.shortlink.project.dto.req.ShortLinkGroupStatsAccessRecordReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkGroupStatsReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsAccessRecordReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsReqDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsAccessDailyRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsAccessRecordRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsBrowserRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsDeviceRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsLocaleCNRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsNetworkRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsOsRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsTopIpRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsUvRespDTO; import com.nageoffer.shortlink.project.service.ShortLinkStatsService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger;
13,313
int weekdayCnt = listWeekdayStatsByGroup.stream() .filter(each -> Objects.equals(each.getWeekday(), weekday.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); weekdayStats.add(weekdayCnt); } // 浏览器访问详情 List<ShortLinkStatsBrowserRespDTO> browserStats = new ArrayList<>(); List<HashMap<String, Object>> listBrowserStatsByGroup = linkBrowserStatsMapper.listBrowserStatsByGroup(requestParam); int browserSum = listBrowserStatsByGroup.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listBrowserStatsByGroup.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / browserSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsBrowserRespDTO browserRespDTO = ShortLinkStatsBrowserRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .browser(each.get("browser").toString()) .ratio(actualRatio) .build(); browserStats.add(browserRespDTO); }); // 操作系统访问详情 List<ShortLinkStatsOsRespDTO> osStats = new ArrayList<>(); List<HashMap<String, Object>> listOsStatsByGroup = linkOsStatsMapper.listOsStatsByGroup(requestParam); int osSum = listOsStatsByGroup.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listOsStatsByGroup.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / osSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsOsRespDTO osRespDTO = ShortLinkStatsOsRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .os(each.get("os").toString()) .ratio(actualRatio) .build(); osStats.add(osRespDTO); }); // 访问设备类型详情 List<ShortLinkStatsDeviceRespDTO> deviceStats = new ArrayList<>(); List<LinkDeviceStatsDO> listDeviceStatsByGroup = linkDeviceStatsMapper.listDeviceStatsByGroup(requestParam); int deviceSum = listDeviceStatsByGroup.stream() .mapToInt(LinkDeviceStatsDO::getCnt) .sum(); listDeviceStatsByGroup.forEach(each -> { double ratio = (double) each.getCnt() / deviceSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsDeviceRespDTO deviceRespDTO = ShortLinkStatsDeviceRespDTO.builder() .cnt(each.getCnt()) .device(each.getDevice()) .ratio(actualRatio) .build(); deviceStats.add(deviceRespDTO); }); // 访问网络类型详情 List<ShortLinkStatsNetworkRespDTO> networkStats = new ArrayList<>(); List<LinkNetworkStatsDO> listNetworkStatsByGroup = linkNetworkStatsMapper.listNetworkStatsByGroup(requestParam); int networkSum = listNetworkStatsByGroup.stream() .mapToInt(LinkNetworkStatsDO::getCnt) .sum(); listNetworkStatsByGroup.forEach(each -> { double ratio = (double) each.getCnt() / networkSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsNetworkRespDTO networkRespDTO = ShortLinkStatsNetworkRespDTO.builder() .cnt(each.getCnt()) .network(each.getNetwork()) .ratio(actualRatio) .build(); networkStats.add(networkRespDTO); }); return ShortLinkStatsRespDTO.builder() .pv(pvUvUidStatsByGroup.getPv()) .uv(pvUvUidStatsByGroup.getUv()) .uip(pvUvUidStatsByGroup.getUip()) .daily(daily) .localeCnStats(localeCnStats) .hourStats(hourStats) .topIpStats(topIpStats) .weekdayStats(weekdayStats) .browserStats(browserStats) .osStats(osStats) .deviceStats(deviceStats) .networkStats(networkStats) .build(); } @Override public IPage<ShortLinkStatsAccessRecordRespDTO> shortLinkStatsAccessRecord(ShortLinkStatsAccessRecordReqDTO requestParam) { LambdaQueryWrapper<LinkAccessLogsDO> queryWrapper = Wrappers.lambdaQuery(LinkAccessLogsDO.class) .eq(LinkAccessLogsDO::getGid, requestParam.getGid()) .eq(LinkAccessLogsDO::getFullShortUrl, requestParam.getFullShortUrl()) .between(LinkAccessLogsDO::getCreateTime, requestParam.getStartDate(), requestParam.getEndDate()) .eq(LinkAccessLogsDO::getDelFlag, 0) .orderByDesc(LinkAccessLogsDO::getCreateTime); IPage<LinkAccessLogsDO> linkAccessLogsDOIPage = linkAccessLogsMapper.selectPage(requestParam, queryWrapper); IPage<ShortLinkStatsAccessRecordRespDTO> actualResult = linkAccessLogsDOIPage.convert(each -> BeanUtil.toBean(each, ShortLinkStatsAccessRecordRespDTO.class)); List<String> userAccessLogsList = actualResult.getRecords().stream() .map(ShortLinkStatsAccessRecordRespDTO::getUser) .toList(); List<Map<String, Object>> uvTypeList = linkAccessLogsMapper.selectUvTypeByUsers( requestParam.getGid(), requestParam.getFullShortUrl(), requestParam.getStartDate(), requestParam.getEndDate(), userAccessLogsList ); actualResult.getRecords().forEach(each -> { String uvType = uvTypeList.stream() .filter(item -> Objects.equals(each.getUser(), item.get("user"))) .findFirst() .map(item -> item.get("uvType")) .map(Object::toString) .orElse("旧访客"); each.setUvType(uvType); }); return actualResult; } @Override
/* * 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 com.nageoffer.shortlink.project.service.impl; /** * 短链接监控接口实现层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Service @RequiredArgsConstructor public class ShortLinkStatsServiceImpl implements ShortLinkStatsService { private final LinkAccessStatsMapper linkAccessStatsMapper; private final LinkLocaleStatsMapper linkLocaleStatsMapper; private final LinkAccessLogsMapper linkAccessLogsMapper; private final LinkBrowserStatsMapper linkBrowserStatsMapper; private final LinkOsStatsMapper linkOsStatsMapper; private final LinkDeviceStatsMapper linkDeviceStatsMapper; private final LinkNetworkStatsMapper linkNetworkStatsMapper; @Override public ShortLinkStatsRespDTO oneShortLinkStats(ShortLinkStatsReqDTO requestParam) { List<LinkAccessStatsDO> listStatsByShortLink = linkAccessStatsMapper.listStatsByShortLink(requestParam); if (CollUtil.isEmpty(listStatsByShortLink)) { return null; } // 基础访问数据 LinkAccessStatsDO pvUvUidStatsByShortLink = linkAccessLogsMapper.findPvUvUidStatsByShortLink(requestParam); // 基础访问详情 List<ShortLinkStatsAccessDailyRespDTO> daily = new ArrayList<>(); List<String> rangeDates = DateUtil.rangeToList(DateUtil.parse(requestParam.getStartDate()), DateUtil.parse(requestParam.getEndDate()), DateField.DAY_OF_MONTH).stream() .map(DateUtil::formatDate) .toList(); rangeDates.forEach(each -> listStatsByShortLink.stream() .filter(item -> Objects.equals(each, DateUtil.formatDate(item.getDate()))) .findFirst() .ifPresentOrElse(item -> { ShortLinkStatsAccessDailyRespDTO accessDailyRespDTO = ShortLinkStatsAccessDailyRespDTO.builder() .date(each) .pv(item.getPv()) .uv(item.getUv()) .uip(item.getUip()) .build(); daily.add(accessDailyRespDTO); }, () -> { ShortLinkStatsAccessDailyRespDTO accessDailyRespDTO = ShortLinkStatsAccessDailyRespDTO.builder() .date(each) .pv(0) .uv(0) .uip(0) .build(); daily.add(accessDailyRespDTO); })); // 地区访问详情(仅国内) List<ShortLinkStatsLocaleCNRespDTO> localeCnStats = new ArrayList<>(); List<LinkLocaleStatsDO> listedLocaleByShortLink = linkLocaleStatsMapper.listLocaleByShortLink(requestParam); int localeCnSum = listedLocaleByShortLink.stream() .mapToInt(LinkLocaleStatsDO::getCnt) .sum(); listedLocaleByShortLink.forEach(each -> { double ratio = (double) each.getCnt() / localeCnSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsLocaleCNRespDTO localeCNRespDTO = ShortLinkStatsLocaleCNRespDTO.builder() .cnt(each.getCnt()) .locale(each.getProvince()) .ratio(actualRatio) .build(); localeCnStats.add(localeCNRespDTO); }); // 小时访问详情 List<Integer> hourStats = new ArrayList<>(); List<LinkAccessStatsDO> listHourStatsByShortLink = linkAccessStatsMapper.listHourStatsByShortLink(requestParam); for (int i = 0; i < 24; i++) { AtomicInteger hour = new AtomicInteger(i); int hourCnt = listHourStatsByShortLink.stream() .filter(each -> Objects.equals(each.getHour(), hour.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); hourStats.add(hourCnt); } // 高频访问IP详情 List<ShortLinkStatsTopIpRespDTO> topIpStats = new ArrayList<>(); List<HashMap<String, Object>> listTopIpByShortLink = linkAccessLogsMapper.listTopIpByShortLink(requestParam); listTopIpByShortLink.forEach(each -> { ShortLinkStatsTopIpRespDTO statsTopIpRespDTO = ShortLinkStatsTopIpRespDTO.builder() .ip(each.get("ip").toString()) .cnt(Integer.parseInt(each.get("count").toString())) .build(); topIpStats.add(statsTopIpRespDTO); }); // 一周访问详情 List<Integer> weekdayStats = new ArrayList<>(); List<LinkAccessStatsDO> listWeekdayStatsByShortLink = linkAccessStatsMapper.listWeekdayStatsByShortLink(requestParam); for (int i = 1; i < 8; i++) { AtomicInteger weekday = new AtomicInteger(i); int weekdayCnt = listWeekdayStatsByShortLink.stream() .filter(each -> Objects.equals(each.getWeekday(), weekday.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); weekdayStats.add(weekdayCnt); } // 浏览器访问详情 List<ShortLinkStatsBrowserRespDTO> browserStats = new ArrayList<>(); List<HashMap<String, Object>> listBrowserStatsByShortLink = linkBrowserStatsMapper.listBrowserStatsByShortLink(requestParam); int browserSum = listBrowserStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listBrowserStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / browserSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsBrowserRespDTO browserRespDTO = ShortLinkStatsBrowserRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .browser(each.get("browser").toString()) .ratio(actualRatio) .build(); browserStats.add(browserRespDTO); }); // 操作系统访问详情 List<ShortLinkStatsOsRespDTO> osStats = new ArrayList<>(); List<HashMap<String, Object>> listOsStatsByShortLink = linkOsStatsMapper.listOsStatsByShortLink(requestParam); int osSum = listOsStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listOsStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / osSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsOsRespDTO osRespDTO = ShortLinkStatsOsRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .os(each.get("os").toString()) .ratio(actualRatio) .build(); osStats.add(osRespDTO); }); // 访客访问类型详情 List<ShortLinkStatsUvRespDTO> uvTypeStats = new ArrayList<>(); HashMap<String, Object> findUvTypeByShortLink = linkAccessLogsMapper.findUvTypeCntByShortLink(requestParam); int oldUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("oldUserCnt")) .map(Object::toString) .orElse("0") ); int newUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("newUserCnt")) .map(Object::toString) .orElse("0") ); int uvSum = oldUserCnt + newUserCnt; double oldRatio = (double) oldUserCnt / uvSum; double actualOldRatio = Math.round(oldRatio * 100.0) / 100.0; double newRatio = (double) newUserCnt / uvSum; double actualNewRatio = Math.round(newRatio * 100.0) / 100.0; ShortLinkStatsUvRespDTO newUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("newUser") .cnt(newUserCnt) .ratio(actualNewRatio) .build(); uvTypeStats.add(newUvRespDTO); ShortLinkStatsUvRespDTO oldUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("oldUser") .cnt(oldUserCnt) .ratio(actualOldRatio) .build(); uvTypeStats.add(oldUvRespDTO); // 访问设备类型详情 List<ShortLinkStatsDeviceRespDTO> deviceStats = new ArrayList<>(); List<LinkDeviceStatsDO> listDeviceStatsByShortLink = linkDeviceStatsMapper.listDeviceStatsByShortLink(requestParam); int deviceSum = listDeviceStatsByShortLink.stream() .mapToInt(LinkDeviceStatsDO::getCnt) .sum(); listDeviceStatsByShortLink.forEach(each -> { double ratio = (double) each.getCnt() / deviceSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsDeviceRespDTO deviceRespDTO = ShortLinkStatsDeviceRespDTO.builder() .cnt(each.getCnt()) .device(each.getDevice()) .ratio(actualRatio) .build(); deviceStats.add(deviceRespDTO); }); // 访问网络类型详情 List<ShortLinkStatsNetworkRespDTO> networkStats = new ArrayList<>(); List<LinkNetworkStatsDO> listNetworkStatsByShortLink = linkNetworkStatsMapper.listNetworkStatsByShortLink(requestParam); int networkSum = listNetworkStatsByShortLink.stream() .mapToInt(LinkNetworkStatsDO::getCnt) .sum(); listNetworkStatsByShortLink.forEach(each -> { double ratio = (double) each.getCnt() / networkSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsNetworkRespDTO networkRespDTO = ShortLinkStatsNetworkRespDTO.builder() .cnt(each.getCnt()) .network(each.getNetwork()) .ratio(actualRatio) .build(); networkStats.add(networkRespDTO); }); return ShortLinkStatsRespDTO.builder() .pv(pvUvUidStatsByShortLink.getPv()) .uv(pvUvUidStatsByShortLink.getUv()) .uip(pvUvUidStatsByShortLink.getUip()) .daily(daily) .localeCnStats(localeCnStats) .hourStats(hourStats) .topIpStats(topIpStats) .weekdayStats(weekdayStats) .browserStats(browserStats) .osStats(osStats) .uvTypeStats(uvTypeStats) .deviceStats(deviceStats) .networkStats(networkStats) .build(); } @Override public ShortLinkStatsRespDTO groupShortLinkStats(ShortLinkGroupStatsReqDTO requestParam) { List<LinkAccessStatsDO> listStatsByGroup = linkAccessStatsMapper.listStatsByGroup(requestParam); if (CollUtil.isEmpty(listStatsByGroup)) { return null; } // 基础访问数据 LinkAccessStatsDO pvUvUidStatsByGroup = linkAccessLogsMapper.findPvUvUidStatsByGroup(requestParam); // 基础访问详情 List<ShortLinkStatsAccessDailyRespDTO> daily = new ArrayList<>(); List<String> rangeDates = DateUtil.rangeToList(DateUtil.parse(requestParam.getStartDate()), DateUtil.parse(requestParam.getEndDate()), DateField.DAY_OF_MONTH).stream() .map(DateUtil::formatDate) .toList(); rangeDates.forEach(each -> listStatsByGroup.stream() .filter(item -> Objects.equals(each, DateUtil.formatDate(item.getDate()))) .findFirst() .ifPresentOrElse(item -> { ShortLinkStatsAccessDailyRespDTO accessDailyRespDTO = ShortLinkStatsAccessDailyRespDTO.builder() .date(each) .pv(item.getPv()) .uv(item.getUv()) .uip(item.getUip()) .build(); daily.add(accessDailyRespDTO); }, () -> { ShortLinkStatsAccessDailyRespDTO accessDailyRespDTO = ShortLinkStatsAccessDailyRespDTO.builder() .date(each) .pv(0) .uv(0) .uip(0) .build(); daily.add(accessDailyRespDTO); })); // 地区访问详情(仅国内) List<ShortLinkStatsLocaleCNRespDTO> localeCnStats = new ArrayList<>(); List<LinkLocaleStatsDO> listedLocaleByGroup = linkLocaleStatsMapper.listLocaleByGroup(requestParam); int localeCnSum = listedLocaleByGroup.stream() .mapToInt(LinkLocaleStatsDO::getCnt) .sum(); listedLocaleByGroup.forEach(each -> { double ratio = (double) each.getCnt() / localeCnSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsLocaleCNRespDTO localeCNRespDTO = ShortLinkStatsLocaleCNRespDTO.builder() .cnt(each.getCnt()) .locale(each.getProvince()) .ratio(actualRatio) .build(); localeCnStats.add(localeCNRespDTO); }); // 小时访问详情 List<Integer> hourStats = new ArrayList<>(); List<LinkAccessStatsDO> listHourStatsByGroup = linkAccessStatsMapper.listHourStatsByGroup(requestParam); for (int i = 0; i < 24; i++) { AtomicInteger hour = new AtomicInteger(i); int hourCnt = listHourStatsByGroup.stream() .filter(each -> Objects.equals(each.getHour(), hour.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); hourStats.add(hourCnt); } // 高频访问IP详情 List<ShortLinkStatsTopIpRespDTO> topIpStats = new ArrayList<>(); List<HashMap<String, Object>> listTopIpByGroup = linkAccessLogsMapper.listTopIpByGroup(requestParam); listTopIpByGroup.forEach(each -> { ShortLinkStatsTopIpRespDTO statsTopIpRespDTO = ShortLinkStatsTopIpRespDTO.builder() .ip(each.get("ip").toString()) .cnt(Integer.parseInt(each.get("count").toString())) .build(); topIpStats.add(statsTopIpRespDTO); }); // 一周访问详情 List<Integer> weekdayStats = new ArrayList<>(); List<LinkAccessStatsDO> listWeekdayStatsByGroup = linkAccessStatsMapper.listWeekdayStatsByGroup(requestParam); for (int i = 1; i < 8; i++) { AtomicInteger weekday = new AtomicInteger(i); int weekdayCnt = listWeekdayStatsByGroup.stream() .filter(each -> Objects.equals(each.getWeekday(), weekday.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); weekdayStats.add(weekdayCnt); } // 浏览器访问详情 List<ShortLinkStatsBrowserRespDTO> browserStats = new ArrayList<>(); List<HashMap<String, Object>> listBrowserStatsByGroup = linkBrowserStatsMapper.listBrowserStatsByGroup(requestParam); int browserSum = listBrowserStatsByGroup.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listBrowserStatsByGroup.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / browserSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsBrowserRespDTO browserRespDTO = ShortLinkStatsBrowserRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .browser(each.get("browser").toString()) .ratio(actualRatio) .build(); browserStats.add(browserRespDTO); }); // 操作系统访问详情 List<ShortLinkStatsOsRespDTO> osStats = new ArrayList<>(); List<HashMap<String, Object>> listOsStatsByGroup = linkOsStatsMapper.listOsStatsByGroup(requestParam); int osSum = listOsStatsByGroup.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listOsStatsByGroup.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / osSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsOsRespDTO osRespDTO = ShortLinkStatsOsRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .os(each.get("os").toString()) .ratio(actualRatio) .build(); osStats.add(osRespDTO); }); // 访问设备类型详情 List<ShortLinkStatsDeviceRespDTO> deviceStats = new ArrayList<>(); List<LinkDeviceStatsDO> listDeviceStatsByGroup = linkDeviceStatsMapper.listDeviceStatsByGroup(requestParam); int deviceSum = listDeviceStatsByGroup.stream() .mapToInt(LinkDeviceStatsDO::getCnt) .sum(); listDeviceStatsByGroup.forEach(each -> { double ratio = (double) each.getCnt() / deviceSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsDeviceRespDTO deviceRespDTO = ShortLinkStatsDeviceRespDTO.builder() .cnt(each.getCnt()) .device(each.getDevice()) .ratio(actualRatio) .build(); deviceStats.add(deviceRespDTO); }); // 访问网络类型详情 List<ShortLinkStatsNetworkRespDTO> networkStats = new ArrayList<>(); List<LinkNetworkStatsDO> listNetworkStatsByGroup = linkNetworkStatsMapper.listNetworkStatsByGroup(requestParam); int networkSum = listNetworkStatsByGroup.stream() .mapToInt(LinkNetworkStatsDO::getCnt) .sum(); listNetworkStatsByGroup.forEach(each -> { double ratio = (double) each.getCnt() / networkSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsNetworkRespDTO networkRespDTO = ShortLinkStatsNetworkRespDTO.builder() .cnt(each.getCnt()) .network(each.getNetwork()) .ratio(actualRatio) .build(); networkStats.add(networkRespDTO); }); return ShortLinkStatsRespDTO.builder() .pv(pvUvUidStatsByGroup.getPv()) .uv(pvUvUidStatsByGroup.getUv()) .uip(pvUvUidStatsByGroup.getUip()) .daily(daily) .localeCnStats(localeCnStats) .hourStats(hourStats) .topIpStats(topIpStats) .weekdayStats(weekdayStats) .browserStats(browserStats) .osStats(osStats) .deviceStats(deviceStats) .networkStats(networkStats) .build(); } @Override public IPage<ShortLinkStatsAccessRecordRespDTO> shortLinkStatsAccessRecord(ShortLinkStatsAccessRecordReqDTO requestParam) { LambdaQueryWrapper<LinkAccessLogsDO> queryWrapper = Wrappers.lambdaQuery(LinkAccessLogsDO.class) .eq(LinkAccessLogsDO::getGid, requestParam.getGid()) .eq(LinkAccessLogsDO::getFullShortUrl, requestParam.getFullShortUrl()) .between(LinkAccessLogsDO::getCreateTime, requestParam.getStartDate(), requestParam.getEndDate()) .eq(LinkAccessLogsDO::getDelFlag, 0) .orderByDesc(LinkAccessLogsDO::getCreateTime); IPage<LinkAccessLogsDO> linkAccessLogsDOIPage = linkAccessLogsMapper.selectPage(requestParam, queryWrapper); IPage<ShortLinkStatsAccessRecordRespDTO> actualResult = linkAccessLogsDOIPage.convert(each -> BeanUtil.toBean(each, ShortLinkStatsAccessRecordRespDTO.class)); List<String> userAccessLogsList = actualResult.getRecords().stream() .map(ShortLinkStatsAccessRecordRespDTO::getUser) .toList(); List<Map<String, Object>> uvTypeList = linkAccessLogsMapper.selectUvTypeByUsers( requestParam.getGid(), requestParam.getFullShortUrl(), requestParam.getStartDate(), requestParam.getEndDate(), userAccessLogsList ); actualResult.getRecords().forEach(each -> { String uvType = uvTypeList.stream() .filter(item -> Objects.equals(each.getUser(), item.get("user"))) .findFirst() .map(item -> item.get("uvType")) .map(Object::toString) .orElse("旧访客"); each.setUvType(uvType); }); return actualResult; } @Override
public IPage<ShortLinkStatsAccessRecordRespDTO> groupShortLinkStatsAccessRecord(ShortLinkGroupStatsAccessRecordReqDTO requestParam) {
12
2023-11-19 16:04:32+00:00
16k
TongchengOpenSource/ckibana
src/main/java/com/ly/ckibana/strategy/clause/converter/QueryStringClauseConverter.java
[ { "identifier": "Constants", "path": "src/main/java/com/ly/ckibana/constants/Constants.java", "snippet": "public class Constants {\n\n public static final String HEADER_ELASTICSEARCH = \"Elasticsearch\";\n\n public static final String HEADER_X_ELASTIC_PRODUCT = \"X-elastic-product\";\n\n public...
import com.ly.ckibana.constants.Constants; import com.ly.ckibana.constants.SqlConstants; import com.ly.ckibana.model.compute.QueryStringField; import com.ly.ckibana.model.enums.IPType; import com.ly.ckibana.util.ProxyUtils; import com.ly.ckibana.util.QueryConvertUtils; import com.ly.ckibana.util.SqlUtils; import com.ly.ckibana.util.Utils; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.commons.lang3.StringUtils; import java.util.StringJoiner;
12,350
/* * Copyright (c) 2023 LY.com 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.ly.ckibana.strategy.clause.converter; @Data @AllArgsConstructor @NoArgsConstructor public class QueryStringClauseConverter { public static final String LOGICALOP_RANGE_TEMPLATE_DEFAULT = "%s ( %s AND %s)"; private String logicalOp; private QueryStringField field; private String expr; private String content; /** * 默认为忽略大小检索. * */ public String toSql() { if (StringUtils.isNotBlank(content)) { return content; } String value = Utils.trimByPrefixAndSuffixChars(getExpr(), Constants.Symbol.DOUBLE_QUOTA, Constants.Symbol.DOUBLE_QUOTA); String ckFieldNameSql = ProxyUtils.getFieldSqlPart(field.getCkName()); field.setCkName(ckFieldNameSql); // range操作 if (isRangeQuery()) { return generateRangeSql(); } else if (isInQuery()) { return generateInSql(value); } return generateSql(value, ckFieldNameSql); } /** * 基于ck字段类型得到运算解析sql. * 适用于:和ui运算逻辑一致,无需二次变更,支持等于、不等于、相似,不相似,大于(等于),小于(等于)等检索逻辑 * * @param value 值 * @param ckFieldNameSql ck字段名 * @return sql */ private String generateSql(String value, String ckFieldNameSql) {
/* * Copyright (c) 2023 LY.com 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.ly.ckibana.strategy.clause.converter; @Data @AllArgsConstructor @NoArgsConstructor public class QueryStringClauseConverter { public static final String LOGICALOP_RANGE_TEMPLATE_DEFAULT = "%s ( %s AND %s)"; private String logicalOp; private QueryStringField field; private String expr; private String content; /** * 默认为忽略大小检索. * */ public String toSql() { if (StringUtils.isNotBlank(content)) { return content; } String value = Utils.trimByPrefixAndSuffixChars(getExpr(), Constants.Symbol.DOUBLE_QUOTA, Constants.Symbol.DOUBLE_QUOTA); String ckFieldNameSql = ProxyUtils.getFieldSqlPart(field.getCkName()); field.setCkName(ckFieldNameSql); // range操作 if (isRangeQuery()) { return generateRangeSql(); } else if (isInQuery()) { return generateInSql(value); } return generateSql(value, ckFieldNameSql); } /** * 基于ck字段类型得到运算解析sql. * 适用于:和ui运算逻辑一致,无需二次变更,支持等于、不等于、相似,不相似,大于(等于),小于(等于)等检索逻辑 * * @param value 值 * @param ckFieldNameSql ck字段名 * @return sql */ private String generateSql(String value, String ckFieldNameSql) {
IPType ipType = ProxyUtils.getIpType(field.getCkType(), value);
3
2023-11-21 09:12:07+00:00
16k
libgdx/gdx-particle-editor
core/src/main/java/com/ray3k/gdxparticleeditor/runnables/MergeRunnable.java
[ { "identifier": "FileDialogs", "path": "core/src/main/java/com/ray3k/gdxparticleeditor/FileDialogs.java", "snippet": "public class FileDialogs {\n public static Array<FileHandle> openMultipleDialog(String title, String defaultPath, String[] filterPatterns, String filterDescription) {\n //fix f...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.OrderedMap; import com.ray3k.gdxparticleeditor.FileDialogs; import com.ray3k.gdxparticleeditor.Settings; import com.ray3k.gdxparticleeditor.Utils; import com.ray3k.gdxparticleeditor.undo.UndoManager; import com.ray3k.gdxparticleeditor.undo.undoables.MergeEmitterUndoable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static com.ray3k.gdxparticleeditor.Core.*; import static com.ray3k.gdxparticleeditor.Settings.*; import static com.ray3k.gdxparticleeditor.Utils.showToast; import static com.ray3k.gdxparticleeditor.widgets.panels.EffectEmittersPanel.effectEmittersPanel; import static com.ray3k.gdxparticleeditor.widgets.panels.EmitterPropertiesPanel.emitterPropertiesPanel;
13,285
package com.ray3k.gdxparticleeditor.runnables; public class MergeRunnable implements Runnable { private static boolean open; @Override public void run () { if (open) return; ExecutorService service = Executors.newSingleThreadExecutor(); service.execute(() -> { open = true; stage.getRoot().setTouchable(Touchable.disabled);
package com.ray3k.gdxparticleeditor.runnables; public class MergeRunnable implements Runnable { private static boolean open; @Override public void run () { if (open) return; ExecutorService service = Executors.newSingleThreadExecutor(); service.execute(() -> { open = true; stage.getRoot().setTouchable(Touchable.disabled);
if (effectEmittersPanel == null || emitterPropertiesPanel == null) return;
8
2023-11-24 15:58:20+00:00
16k
siam1026/siam-server
siam-system/system-provider/src/main/java/com/siam/system/modular/package_order/service_impl/OrderRefundProcessServiceImpl.java
[ { "identifier": "OrderRefundProcessMapper", "path": "siam-system/system-provider/src/main/java/com/siam/system/modular/package_order/mapper/OrderRefundProcessMapper.java", "snippet": "public interface OrderRefundProcessMapper extends BaseMapper<OrderRefundProcess> {\n int countByExample(OrderRefundPr...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.system.modular.package_order.mapper.OrderRefundProcessMapper; import com.siam.system.modular.package_order.mapper.OrderMapper; import com.siam.system.modular.package_order.service.OrderRefundProcessService; import com.siam.system.modular.package_order.entity.OrderRefundProcess; import com.siam.system.modular.package_order.model.example.OrderRefundProcessExample; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map;
13,734
package com.siam.system.modular.package_order.service_impl; @Service public class OrderRefundProcessServiceImpl implements OrderRefundProcessService { @Autowired
package com.siam.system.modular.package_order.service_impl; @Service public class OrderRefundProcessServiceImpl implements OrderRefundProcessService { @Autowired
private OrderRefundProcessMapper orderRefundProcessMapper;
0
2023-11-26 12:41:06+00:00
16k
3dcitydb/citydb-tool
citydb-io-citygml/src/main/java/org/citydb/io/citygml/adapter/appearance/TextureAdapter.java
[ { "identifier": "ModelBuildException", "path": "citydb-io-citygml/src/main/java/org/citydb/io/citygml/builder/ModelBuildException.java", "snippet": "public class ModelBuildException extends Exception {\n\n public ModelBuildException() {\n super();\n }\n\n public ModelBuildException(Strin...
import org.citygml4j.core.model.appearance.ColorPlusOpacity; import java.io.IOException; import org.apache.logging.log4j.Level; import org.citydb.io.citygml.builder.ModelBuildException; import org.citydb.io.citygml.reader.ModelBuilderHelper; import org.citydb.io.citygml.serializer.ModelSerializeException; import org.citydb.io.citygml.writer.ModelSerializerHelper; import org.citydb.model.appearance.*; import org.citydb.model.common.ExternalFile; import org.citydb.model.common.Reference; import org.citygml4j.core.model.appearance.AbstractTexture;
13,247
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.io.citygml.adapter.appearance; public abstract class TextureAdapter<T extends Texture<?>, R extends AbstractTexture> extends SurfaceDataAdapter<T, R> { @Override
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.io.citygml.adapter.appearance; public abstract class TextureAdapter<T extends Texture<?>, R extends AbstractTexture> extends SurfaceDataAdapter<T, R> { @Override
public void build(R source, T target, ModelBuilderHelper helper) throws ModelBuildException {
0
2023-11-19 12:29:54+00:00
16k
magmamaintained/Magma-1.12.2
src/main/java/org/magmafoundation/magma/metrics/Metrics.java
[ { "identifier": "Bukkit", "path": "src/main/java/org/bukkit/Bukkit.java", "snippet": "public final class Bukkit {\n private static Server server;\n\n /**\n * Static class cannot be initialized.\n */\n private Bukkit() {}\n\n /**\n * Gets the current {@link Server} singleton\n ...
import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.zip.GZIPOutputStream; import net.minecraft.server.MinecraftServer; import org.bukkit.Bukkit; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.Plugin; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.magmafoundation.magma.Magma; import org.magmafoundation.magma.api.ServerAPI; import javax.net.ssl.HttpsURLConnection; import java.io.*; import java.net.URL;
13,283
/* * Magma Server * Copyright (C) 2019-2022. * * 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 org.magmafoundation.magma.metrics; /** * bStats collects some data for plugin authors. * * Check out https://bStats.org/ to learn more about bStats! */ public class Metrics { // The version of this bStats class public static final int B_STATS_VERSION = 1; // The url to which the data is sent private static final String URL = "https://bStats.org/submitData/server-implementation"; // Should failed requests be logged? private static boolean logFailedRequests; // Should the sent data be logged? private static boolean logSentData; // Should the response text be logged? private static boolean logResponseStatusText; // The uuid of the server private static String serverUUID; // A list with all custom charts private final List<CustomChart> charts = new ArrayList<>(); private final String pluginName = "Magma Maintained"; private final String pluginVersion = Magma.getVersion(); // Is bStats enabled on this server? private boolean enabled; public Metrics() { // Get the config file File bStatsFolder = new File(new File((File) MinecraftServer.getServerInstance().options.valueOf("plugins"), "bStats"), "config"); File configFile = new File(bStatsFolder, "config.yml");
/* * Magma Server * Copyright (C) 2019-2022. * * 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 org.magmafoundation.magma.metrics; /** * bStats collects some data for plugin authors. * * Check out https://bStats.org/ to learn more about bStats! */ public class Metrics { // The version of this bStats class public static final int B_STATS_VERSION = 1; // The url to which the data is sent private static final String URL = "https://bStats.org/submitData/server-implementation"; // Should failed requests be logged? private static boolean logFailedRequests; // Should the sent data be logged? private static boolean logSentData; // Should the response text be logged? private static boolean logResponseStatusText; // The uuid of the server private static String serverUUID; // A list with all custom charts private final List<CustomChart> charts = new ArrayList<>(); private final String pluginName = "Magma Maintained"; private final String pluginVersion = Magma.getVersion(); // Is bStats enabled on this server? private boolean enabled; public Metrics() { // Get the config file File bStatsFolder = new File(new File((File) MinecraftServer.getServerInstance().options.valueOf("plugins"), "bStats"), "config"); File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
1
2023-11-22 11:25:51+00:00
16k
logaritex/assistant-api
src/test/java/com/logaritex/ai/api/samples/codeinterpreter/FintechCodeInterpreterTool.java
[ { "identifier": "AssistantApi", "path": "src/main/java/com/logaritex/ai/api/AssistantApi.java", "snippet": "public class AssistantApi {\n\n\t/**\n\t * OpenAI assistant api beta marker.\n\t */\n\tpublic static final String OPEN_AI_BETA = \"OpenAI-Beta\";\n\n\t/**\n\t * OpenAI assistant api version.\n\t *...
import org.springframework.core.io.DefaultResourceLoader; import org.springframework.util.StreamUtils; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.logaritex.ai.api.AssistantApi; import com.logaritex.ai.api.Data; import com.logaritex.ai.api.Data.Assistant; import com.logaritex.ai.api.Data.Run; import com.logaritex.ai.api.Data.ThreadRequest; import com.logaritex.ai.api.FileApi; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory;
13,607
/* * Copyright 2023-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.logaritex.ai.api.samples.codeinterpreter; /** * * The "Code Interpreter" expands the Assistant's capabilities to include: accurate math, processing files, data * analysis, generating images... * * @author Christian Tzolov */ public class FintechCodeInterpreterTool { private static final Log logger = LogFactory.getLog(FintechCodeInterpreterTool.class); public static void main(String[] args) throws InterruptedException, IOException { logger.info("Create FileApi and AssistantApi with your OPENAI_API_KEY."); FileApi fileApi = new FileApi(System.getenv("OPENAI_API_KEY"));
/* * Copyright 2023-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.logaritex.ai.api.samples.codeinterpreter; /** * * The "Code Interpreter" expands the Assistant's capabilities to include: accurate math, processing files, data * analysis, generating images... * * @author Christian Tzolov */ public class FintechCodeInterpreterTool { private static final Log logger = LogFactory.getLog(FintechCodeInterpreterTool.class); public static void main(String[] args) throws InterruptedException, IOException { logger.info("Create FileApi and AssistantApi with your OPENAI_API_KEY."); FileApi fileApi = new FileApi(System.getenv("OPENAI_API_KEY"));
AssistantApi assistantApi = new AssistantApi(System.getenv("OPENAI_API_KEY"));
0
2023-11-25 18:52:37+00:00
16k
GregTech-Chinese-Community/EPCore
src/main/java/cn/gtcommunity/epimorphism/common/metatileentities/multiblock/EPMetaTileEntityStellarFurnace.java
[ { "identifier": "EPRecipeMaps", "path": "src/main/java/cn/gtcommunity/epimorphism/api/recipe/EPRecipeMaps.java", "snippet": "@ZenClass(\"mods.epimorphism.recipe.RecipeMaps\")\n@ZenRegister\npublic class EPRecipeMaps {\n\n // Singleblock Machine Recipemap\n @ZenProperty\n public static final Re...
import cn.gtcommunity.epimorphism.api.recipe.EPRecipeMaps; import cn.gtcommunity.epimorphism.client.renderer.texture.EPTextures; import cn.gtcommunity.epimorphism.common.blocks.EPBlockMultiblockCasing; import cn.gtcommunity.epimorphism.common.blocks.EPBlockMultiblockCasingB; import cn.gtcommunity.epimorphism.common.blocks.EPMetablocks; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockPart; import gregtech.api.metatileentity.multiblock.RecipeMapMultiblockController; import gregtech.api.pattern.BlockPattern; import gregtech.api.pattern.FactoryBlockPattern; import gregtech.api.unification.material.Materials; import gregtech.client.renderer.ICubeRenderer; import gregtech.common.blocks.BlockFusionCasing; import gregtech.common.blocks.MetaBlocks; import net.minecraft.block.state.IBlockState; import net.minecraft.client.resources.I18n; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List;
12,710
package cn.gtcommunity.epimorphism.common.metatileentities.multiblock; public class EPMetaTileEntityStellarFurnace extends RecipeMapMultiblockController { public EPMetaTileEntityStellarFurnace(ResourceLocation metaTileEntityId) {
package cn.gtcommunity.epimorphism.common.metatileentities.multiblock; public class EPMetaTileEntityStellarFurnace extends RecipeMapMultiblockController { public EPMetaTileEntityStellarFurnace(ResourceLocation metaTileEntityId) {
super(metaTileEntityId, EPRecipeMaps.STELLAR_FURNACE_RECIPES);
0
2023-11-26 01:56:35+00:00
16k
ZayrexDev/ZPixiv
src/main/java/xyz/zcraft/zpixiv/ui/controller/ArtworkController.java
[ { "identifier": "PixivClient", "path": "src/main/java/xyz/zcraft/zpixiv/api/PixivClient.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class PixivClient {\n private static final Logger LOG = LogManager.getLogger(PixivClient.class);\n private static final String userAgent = \"Mozilla/5.0 ...
import javafx.animation.FadeTransition; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.web.WebView; import javafx.stage.DirectoryChooser; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import xyz.zcraft.zpixiv.api.PixivClient; import xyz.zcraft.zpixiv.api.artwork.Identifier; import xyz.zcraft.zpixiv.api.artwork.PixivArtwork; import xyz.zcraft.zpixiv.api.artwork.Quality; import xyz.zcraft.zpixiv.ui.Main; import xyz.zcraft.zpixiv.util.*; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Objects; import java.util.ResourceBundle; import java.util.TimerTask; import java.util.concurrent.LinkedBlockingQueue;
10,857
str = str.concat(" ").concat(currentTask.getName()); } LOG.info("AFTER:{}", str); synchronized (this) { final String finalStr = str; Platform.runLater(() -> { synchronized (this) { processLabel.setText(finalStr); } }); } } @Override public void initialize(URL url, ResourceBundle resourceBundle) { imgView.fitWidthProperty().bind(((HBox) imgView.getParent()).widthProperty()); imgView.fitHeightProperty().bind(((HBox) imgView.getParent()).heightProperty()); loadPane.setVisible(false); pageWrapperPane.setVisible(false); Rectangle r = new Rectangle(authorImg.getFitWidth(), authorImg.getFitHeight()); r.setArcWidth(authorImg.getFitWidth()); r.setArcHeight(authorImg.getFitHeight()); authorImg.setClip(r); pageWrapperPaneFadeOutTransition = AnimationHelper.getFadeOutTransition(pageWrapperPane); pageWrapperPaneFadeOutTransition.setOnFinished(actionEvent -> pageWrapperPane.setVisible(false)); pageWrapperPaneFadeInTransition = AnimationHelper.getFadeInTransition(pageWrapperPane); Main.getTimer().schedule(refreshTask, 0, 250); } public void load(PixivClient client, PixivArtwork art) { if (client == null && art == null) return; this.client = client; this.artwork = art; LOG.info("Loading artwork {}", artwork.getOrigData().getId()); reloadArtworkStatus(); titleLbl.setText(artwork.getOrigData().getTitle()); if (artwork.getOrigData().getXRestrict() == 1) { xResLbl.setVisible(true); } else { titleBox.getChildren().remove(0); } if (artwork.getOrigData().getDescription().trim().isEmpty()) { ((VBox) descView.getParent()).getChildren().remove(descView); } else { Platform.runLater(() -> { descView.setContextMenuEnabled(false); descView.getEngine().setUserStyleSheetLocation("data:,body{font: 12px Arial;}"); descView.getEngine().loadContent(this.artwork.getOrigData().getDescription()); }); } if (artwork.getAuthor() != null) authorNameLbl.setText(artwork.getAuthor().getName()); pubDateLbl.setText(artwork.getOrigData().getCreateDate()); likeLbl.setText(String.valueOf(artwork.getOrigData().getLikeCount())); bookmarkLbl.setText(String.valueOf(artwork.getOrigData().getBookmarkCount())); viewLbl.setText(String.valueOf(artwork.getOrigData().getViewCount())); images = new CachedImage[artwork.getOrigData().getPageCount()]; if (artwork.getOrigData().getPageCount() <= 1) { pageWrapperPane.setVisible(false); pageLbl.setVisible(false); } else { prevPageBtn.setDisable(true); nextPageBtn.setDisable(artwork.getOrigData().getPageCount() == 1); pageLbl.setText("1/" + artwork.getOrigData().getPageCount()); } loadProgressBar.setProgress(ProgressBar.INDETERMINATE_PROGRESS); loadTags(); Main.getTpe().submit(() -> { if (this.artwork.getAuthor() == null) { try { final LoadTask t = new LoadTask("获取完整信息"); postLoadTask(t); this.artwork = client.getFullData(art); t.setFinished(true); Platform.runLater(() -> { likeLbl.setText(String.valueOf(artwork.getOrigData().getLikeCount())); bookmarkLbl.setText(String.valueOf(artwork.getOrigData().getBookmarkCount())); viewLbl.setText(String.valueOf(artwork.getOrigData().getViewCount())); }); } catch (IOException e) { LOG.error("Failed to load artwork.", e); Main.showAlert("错误", "加载失败"); return; } } Main.getTpe().submit(getAuthorImgRunnable()); if (artwork.isGif()) { Main.getTpe().submit(getGifLoadRunnable()); } else { Main.getTpe().submit(getImageLoadRunnable()); } }); LOG.info("Loading artwork {} complete", artwork.getOrigData().getId()); } private Runnable getGifLoadRunnable() { return () -> { LOG.info("Loading gif artwork {}", artwork.getOrigData().getId()); final LoadTask t = new LoadTask("加载动图"); final LoadTask t1 = new LoadTask("解析动图"); postLoadTask(t); postLoadTask(t1);
package xyz.zcraft.zpixiv.ui.controller; public class ArtworkController implements Initializable, Refreshable, Closeable { private static final Logger LOG = LogManager.getLogger(ArtworkController.class); private final LinkedBlockingQueue<LoadTask> tasks = new LinkedBlockingQueue<>(); @FXML public ImageView imgView; @FXML public Button nextPageBtn; @FXML public Button prevPageBtn; @FXML public Label titleLbl; @FXML public ImageView authorImg; @FXML public Label authorNameLbl; @FXML public Label pubDateLbl; @FXML public Region followBtn; @FXML public Label likeLbl; @FXML public Label bookmarkLbl; @FXML public Label viewLbl; @FXML public Region likeBtn; @FXML public Region bookmarkBtn; @FXML public Label xResLbl; @FXML public HBox titleBox; @FXML public WebView descView; @FXML public ScrollPane root; @FXML public AnchorPane imgAnchor; @FXML public ProgressBar loadProgressBar; @FXML public Label processLabel; @FXML public VBox loadPane; @FXML public Label likeTextLbl; @FXML public Label pageLbl; public AnchorPane pageWrapperPane; public FlowPane tagsPane; public Button downloadBtn; private PixivClient client; private volatile PixivArtwork artwork; private volatile LoadTask currentTask = null; private final TimerTask refreshTask = new TimerTask() { @Override public void run() { if (currentTask != null || !tasks.isEmpty()) refreshTasks(); } }; private CachedImage[] images; private int currentIndex = 1; private FadeTransition pageWrapperPaneFadeOutTransition; private FadeTransition pageWrapperPaneFadeInTransition; private Image previewImg; public void nextPageBtnOnAction() { if (currentIndex + 1 <= artwork.getOrigData().getPageCount()) { currentIndex++; updateImageIndex(); } } public void prevPageBtnOnAction() { if (currentIndex >= 2) { currentIndex--; updateImageIndex(); } } private void updateImageIndex() { Platform.runLater(() -> { pageLbl.setText(currentIndex + "/" + artwork.getOrigData().getPageCount()); if (currentIndex == 1 && images[0] == null) { imgView.setImage(previewImg); } else { imgView.setImage(images[currentIndex - 1].getImage()); } nextPageBtn.setDisable(currentIndex >= artwork.getOrigData().getPageCount()); prevPageBtn.setDisable(currentIndex <= 1); }); } public void followBtnOnAction() { } private synchronized void postLoadTask(LoadTask task) { tasks.add(task); // task.addListener(t -> refreshTasks()); if (!loadPane.isVisible()) { final FadeTransition fadeInTransition = AnimationHelper.getFadeInTransition(loadPane); Platform.runLater(() -> { loadProgressBar.setProgress(task.getProgress()); fadeInTransition.playFromStart(); loadPane.setVisible(true); }); } refreshTaskName(); } private synchronized void refreshTasks() { tasks.removeIf(e -> e == null || e.isFailed() || e.isFinished()); if (currentTask != null) { if (currentTask.isFinished() || currentTask.isFailed()) { currentTask = null; refreshTasks(); } } else { if (tasks.isEmpty() || tasks.peek() == null) { Platform.runLater(() -> { synchronized (this) { AnimationHelper.getFadeOutTransition(loadPane).playFromStart(); } }); } else { currentTask = tasks.poll(); if (currentTask.isFinished() || currentTask.isFailed()) { currentTask = null; refreshTasks(); } else { Platform.runLater(() -> { synchronized (this) { if (currentTask == null) return; processLabel.setText(currentTask.getName()); loadProgressBar.setProgress(ProgressIndicator.INDETERMINATE_PROGRESS); currentTask.addListener((v) -> Platform.runLater(() -> loadProgressBar.setProgress(v))); } }); } } refreshTaskName(); } } private void refreshTaskName() { String str = tasks.stream().map(LoadTask::getName) .reduce((s, s2) -> s.concat(" ").concat(s2)) .orElse(""); LOG.info("ORIG:{}", str); if (currentTask != null) { str = str.concat(" ").concat(currentTask.getName()); } LOG.info("AFTER:{}", str); synchronized (this) { final String finalStr = str; Platform.runLater(() -> { synchronized (this) { processLabel.setText(finalStr); } }); } } @Override public void initialize(URL url, ResourceBundle resourceBundle) { imgView.fitWidthProperty().bind(((HBox) imgView.getParent()).widthProperty()); imgView.fitHeightProperty().bind(((HBox) imgView.getParent()).heightProperty()); loadPane.setVisible(false); pageWrapperPane.setVisible(false); Rectangle r = new Rectangle(authorImg.getFitWidth(), authorImg.getFitHeight()); r.setArcWidth(authorImg.getFitWidth()); r.setArcHeight(authorImg.getFitHeight()); authorImg.setClip(r); pageWrapperPaneFadeOutTransition = AnimationHelper.getFadeOutTransition(pageWrapperPane); pageWrapperPaneFadeOutTransition.setOnFinished(actionEvent -> pageWrapperPane.setVisible(false)); pageWrapperPaneFadeInTransition = AnimationHelper.getFadeInTransition(pageWrapperPane); Main.getTimer().schedule(refreshTask, 0, 250); } public void load(PixivClient client, PixivArtwork art) { if (client == null && art == null) return; this.client = client; this.artwork = art; LOG.info("Loading artwork {}", artwork.getOrigData().getId()); reloadArtworkStatus(); titleLbl.setText(artwork.getOrigData().getTitle()); if (artwork.getOrigData().getXRestrict() == 1) { xResLbl.setVisible(true); } else { titleBox.getChildren().remove(0); } if (artwork.getOrigData().getDescription().trim().isEmpty()) { ((VBox) descView.getParent()).getChildren().remove(descView); } else { Platform.runLater(() -> { descView.setContextMenuEnabled(false); descView.getEngine().setUserStyleSheetLocation("data:,body{font: 12px Arial;}"); descView.getEngine().loadContent(this.artwork.getOrigData().getDescription()); }); } if (artwork.getAuthor() != null) authorNameLbl.setText(artwork.getAuthor().getName()); pubDateLbl.setText(artwork.getOrigData().getCreateDate()); likeLbl.setText(String.valueOf(artwork.getOrigData().getLikeCount())); bookmarkLbl.setText(String.valueOf(artwork.getOrigData().getBookmarkCount())); viewLbl.setText(String.valueOf(artwork.getOrigData().getViewCount())); images = new CachedImage[artwork.getOrigData().getPageCount()]; if (artwork.getOrigData().getPageCount() <= 1) { pageWrapperPane.setVisible(false); pageLbl.setVisible(false); } else { prevPageBtn.setDisable(true); nextPageBtn.setDisable(artwork.getOrigData().getPageCount() == 1); pageLbl.setText("1/" + artwork.getOrigData().getPageCount()); } loadProgressBar.setProgress(ProgressBar.INDETERMINATE_PROGRESS); loadTags(); Main.getTpe().submit(() -> { if (this.artwork.getAuthor() == null) { try { final LoadTask t = new LoadTask("获取完整信息"); postLoadTask(t); this.artwork = client.getFullData(art); t.setFinished(true); Platform.runLater(() -> { likeLbl.setText(String.valueOf(artwork.getOrigData().getLikeCount())); bookmarkLbl.setText(String.valueOf(artwork.getOrigData().getBookmarkCount())); viewLbl.setText(String.valueOf(artwork.getOrigData().getViewCount())); }); } catch (IOException e) { LOG.error("Failed to load artwork.", e); Main.showAlert("错误", "加载失败"); return; } } Main.getTpe().submit(getAuthorImgRunnable()); if (artwork.isGif()) { Main.getTpe().submit(getGifLoadRunnable()); } else { Main.getTpe().submit(getImageLoadRunnable()); } }); LOG.info("Loading artwork {} complete", artwork.getOrigData().getId()); } private Runnable getGifLoadRunnable() { return () -> { LOG.info("Loading gif artwork {}", artwork.getOrigData().getId()); final LoadTask t = new LoadTask("加载动图"); final LoadTask t1 = new LoadTask("解析动图"); postLoadTask(t); postLoadTask(t1);
Identifier identifier = Identifier.of(artwork.getOrigData().getId(), Identifier.Type.Gif, 0, Quality.Original);
1
2023-11-23 15:08:16+00:00
16k
myzticbean/QSFindItemAddOn
src/main/java/io/myzticbean/finditemaddon/Handlers/CommandHandler/CmdExecutorHandler.java
[ { "identifier": "ConfigSetup", "path": "src/main/java/io/myzticbean/finditemaddon/ConfigUtil/ConfigSetup.java", "snippet": "public class ConfigSetup {\n\n private static File configFile;\n private static File sampleConfigFile;\n private static FileConfiguration configFileConfiguration;\n pri...
import io.myzticbean.finditemaddon.ConfigUtil.ConfigSetup; import io.myzticbean.finditemaddon.FindItemAddOn; import io.myzticbean.finditemaddon.Handlers.GUIHandler.Menus.FoundShopsMenu; import io.myzticbean.finditemaddon.Models.FoundShopItemModel; import io.myzticbean.finditemaddon.Utils.Defaults.PlayerPerms; import io.myzticbean.finditemaddon.Utils.JsonStorageUtils.HiddenShopStorageUtil; import io.myzticbean.finditemaddon.Utils.LoggerUtils; import io.myzticbean.finditemaddon.Utils.WarpUtils.WarpUtils; import me.kodysimpson.simpapi.colors.ColorTranslator; import org.apache.commons.lang3.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.maxgamer.quickshop.api.shop.Shop; import java.util.List;
14,086
package io.myzticbean.finditemaddon.Handlers.CommandHandler; /** * Handler for different parameters of /finditem command * @author ronsane */ public class CmdExecutorHandler { /** * Handles the main shop search process * @param buySellSubCommand Whether player is buying or selling * @param commandSender Who is the command sender: console or player * @param itemArg Specifies Item ID or Item name */ public void handleShopSearch(String buySellSubCommand, CommandSender commandSender, String itemArg) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_USE.value())) { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_SEARCH_LOADING_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().SHOP_SEARCH_LOADING_MSG)); } boolean isBuying; if(StringUtils.isEmpty(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE) || StringUtils.containsIgnoreCase(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE, " ")) { isBuying = buySellSubCommand.equalsIgnoreCase("to_buy"); } else { isBuying = buySellSubCommand.equalsIgnoreCase(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE); } if(itemArg.equalsIgnoreCase("*")) { List<FoundShopItemModel> searchResultList = FindItemAddOn.getQsApiInstance().fetchAllItemsFromAllShops(isBuying, player); if(searchResultList.size() > 0) { Bukkit.getScheduler().runTaskAsynchronously(FindItemAddOn.getInstance(), () -> { FoundShopsMenu menu = new FoundShopsMenu(FindItemAddOn.getPlayerMenuUtility(player), searchResultList); Bukkit.getScheduler().runTask(FindItemAddOn.getInstance(), () -> menu.open(searchResultList)); }); } else { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().NO_SHOP_FOUND_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().NO_SHOP_FOUND_MSG)); } } } else { Material mat = Material.getMaterial(itemArg.toUpperCase()); if(mat != null) { LoggerUtils.logDebugInfo("Material found: " + mat.toString()); List<FoundShopItemModel> searchResultList = FindItemAddOn.getQsApiInstance().findItemBasedOnTypeFromAllShops(new ItemStack(mat), isBuying, player); if(searchResultList.size() > 0) { Bukkit.getScheduler().runTaskAsynchronously(FindItemAddOn.getInstance(), () -> { FoundShopsMenu menu = new FoundShopsMenu(FindItemAddOn.getPlayerMenuUtility(player), searchResultList); Bukkit.getScheduler().runTask(FindItemAddOn.getInstance(), () -> menu.open(searchResultList)); }); } else { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().NO_SHOP_FOUND_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().NO_SHOP_FOUND_MSG)); } } } else { LoggerUtils.logDebugInfo("Material not found! Performing query based search.."); List<FoundShopItemModel> searchResultList = FindItemAddOn.getQsApiInstance().findItemBasedOnDisplayNameFromAllShops(itemArg, isBuying, player); if(searchResultList.size() > 0) { Bukkit.getScheduler().runTaskAsynchronously(FindItemAddOn.getInstance(), () -> { FoundShopsMenu menu = new FoundShopsMenu(FindItemAddOn.getPlayerMenuUtility(player), searchResultList); Bukkit.getScheduler().runTask(FindItemAddOn.getInstance(), () -> menu.open(searchResultList)); }); } else { // Invalid Material if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().FIND_ITEM_CMD_INVALID_MATERIAL_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().FIND_ITEM_CMD_INVALID_MATERIAL_MSG)); } } } } } else { player.sendMessage(ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } /** * Handles the shop hiding feature * @param commandSender Who is the command sender: console or player */ public void handleHideShop(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_HIDESHOP.value())) { Block playerLookAtBlock = player.getTargetBlock(null, 100); if(FindItemAddOn.isQSReremakeInstalled()) { hideShop((Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } else { hideShop((com.ghostchu.quickshop.api.shop.Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } } else { player.sendMessage(ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } /** * Handles the shop reveal feature * @param commandSender Who is the command sender: console or player */ public void handleRevealShop(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_HIDESHOP.value())) { Block playerLookAtBlock = player.getTargetBlock(null, 100); if(FindItemAddOn.isQSReremakeInstalled()) { revealShop((Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } else { revealShop((com.ghostchu.quickshop.api.shop.Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } } else { player.sendMessage(ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } /** * Handles the saving hidden shops to file feature * @param commandSender Who is the command sender: console or player */ /* public void handleHiddenShopSavingToFile(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_ADMIN.toString())) { HiddenShopStorageUtil.saveHiddenShopsToFile(); player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&aSaved hidden shops!")); } else { player.sendMessage( ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } */ /** * Handles the loading of hidden shops from file feature * @param commandSender Who is the command sender: console or player */ /* public void handleHiddenShopLoadingFromFile(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_ADMIN.toString())) { HiddenShopStorageUtil.loadHiddenShopsFromFile(); player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&aSaved hidden shops!")); } else { player.sendMessage( ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } */ /** * Handles plugin reload * @param commandSender Who is the command sender: console or player */ public void handlePluginReload(CommandSender commandSender) { if (!(commandSender instanceof Player)) {
package io.myzticbean.finditemaddon.Handlers.CommandHandler; /** * Handler for different parameters of /finditem command * @author ronsane */ public class CmdExecutorHandler { /** * Handles the main shop search process * @param buySellSubCommand Whether player is buying or selling * @param commandSender Who is the command sender: console or player * @param itemArg Specifies Item ID or Item name */ public void handleShopSearch(String buySellSubCommand, CommandSender commandSender, String itemArg) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_USE.value())) { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_SEARCH_LOADING_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().SHOP_SEARCH_LOADING_MSG)); } boolean isBuying; if(StringUtils.isEmpty(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE) || StringUtils.containsIgnoreCase(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE, " ")) { isBuying = buySellSubCommand.equalsIgnoreCase("to_buy"); } else { isBuying = buySellSubCommand.equalsIgnoreCase(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE); } if(itemArg.equalsIgnoreCase("*")) { List<FoundShopItemModel> searchResultList = FindItemAddOn.getQsApiInstance().fetchAllItemsFromAllShops(isBuying, player); if(searchResultList.size() > 0) { Bukkit.getScheduler().runTaskAsynchronously(FindItemAddOn.getInstance(), () -> { FoundShopsMenu menu = new FoundShopsMenu(FindItemAddOn.getPlayerMenuUtility(player), searchResultList); Bukkit.getScheduler().runTask(FindItemAddOn.getInstance(), () -> menu.open(searchResultList)); }); } else { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().NO_SHOP_FOUND_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().NO_SHOP_FOUND_MSG)); } } } else { Material mat = Material.getMaterial(itemArg.toUpperCase()); if(mat != null) { LoggerUtils.logDebugInfo("Material found: " + mat.toString()); List<FoundShopItemModel> searchResultList = FindItemAddOn.getQsApiInstance().findItemBasedOnTypeFromAllShops(new ItemStack(mat), isBuying, player); if(searchResultList.size() > 0) { Bukkit.getScheduler().runTaskAsynchronously(FindItemAddOn.getInstance(), () -> { FoundShopsMenu menu = new FoundShopsMenu(FindItemAddOn.getPlayerMenuUtility(player), searchResultList); Bukkit.getScheduler().runTask(FindItemAddOn.getInstance(), () -> menu.open(searchResultList)); }); } else { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().NO_SHOP_FOUND_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().NO_SHOP_FOUND_MSG)); } } } else { LoggerUtils.logDebugInfo("Material not found! Performing query based search.."); List<FoundShopItemModel> searchResultList = FindItemAddOn.getQsApiInstance().findItemBasedOnDisplayNameFromAllShops(itemArg, isBuying, player); if(searchResultList.size() > 0) { Bukkit.getScheduler().runTaskAsynchronously(FindItemAddOn.getInstance(), () -> { FoundShopsMenu menu = new FoundShopsMenu(FindItemAddOn.getPlayerMenuUtility(player), searchResultList); Bukkit.getScheduler().runTask(FindItemAddOn.getInstance(), () -> menu.open(searchResultList)); }); } else { // Invalid Material if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().FIND_ITEM_CMD_INVALID_MATERIAL_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().FIND_ITEM_CMD_INVALID_MATERIAL_MSG)); } } } } } else { player.sendMessage(ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } /** * Handles the shop hiding feature * @param commandSender Who is the command sender: console or player */ public void handleHideShop(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_HIDESHOP.value())) { Block playerLookAtBlock = player.getTargetBlock(null, 100); if(FindItemAddOn.isQSReremakeInstalled()) { hideShop((Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } else { hideShop((com.ghostchu.quickshop.api.shop.Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } } else { player.sendMessage(ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } /** * Handles the shop reveal feature * @param commandSender Who is the command sender: console or player */ public void handleRevealShop(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_HIDESHOP.value())) { Block playerLookAtBlock = player.getTargetBlock(null, 100); if(FindItemAddOn.isQSReremakeInstalled()) { revealShop((Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } else { revealShop((com.ghostchu.quickshop.api.shop.Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } } else { player.sendMessage(ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } /** * Handles the saving hidden shops to file feature * @param commandSender Who is the command sender: console or player */ /* public void handleHiddenShopSavingToFile(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_ADMIN.toString())) { HiddenShopStorageUtil.saveHiddenShopsToFile(); player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&aSaved hidden shops!")); } else { player.sendMessage( ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } */ /** * Handles the loading of hidden shops from file feature * @param commandSender Who is the command sender: console or player */ /* public void handleHiddenShopLoadingFromFile(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_ADMIN.toString())) { HiddenShopStorageUtil.loadHiddenShopsFromFile(); player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&aSaved hidden shops!")); } else { player.sendMessage( ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } */ /** * Handles plugin reload * @param commandSender Who is the command sender: console or player */ public void handlePluginReload(CommandSender commandSender) { if (!(commandSender instanceof Player)) {
ConfigSetup.reloadConfig();
0
2023-11-22 11:36:01+00:00
16k
DIDA-lJ/qiyao-12306
services/order-service/src/main/java/org/opengoofy/index12306/biz/orderservice/service/impl/OrderServiceImpl.java
[ { "identifier": "OrderCanalErrorCodeEnum", "path": "services/order-service/src/main/java/org/opengoofy/index12306/biz/orderservice/common/enums/OrderCanalErrorCodeEnum.java", "snippet": "@AllArgsConstructor\npublic enum OrderCanalErrorCodeEnum implements IErrorCode {\n\n ORDER_CANAL_UNKNOWN_ERROR(\"B...
import cn.hutool.core.collection.ListUtil; import cn.hutool.core.text.StrBuilder; import com.alibaba.fastjson2.JSON; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.client.producer.SendStatus; import org.opengoofy.index12306.biz.orderservice.common.enums.OrderCanalErrorCodeEnum; import org.opengoofy.index12306.biz.orderservice.common.enums.OrderItemStatusEnum; import org.opengoofy.index12306.biz.orderservice.common.enums.OrderStatusEnum; import org.opengoofy.index12306.biz.orderservice.dao.entity.OrderDO; import org.opengoofy.index12306.biz.orderservice.dao.entity.OrderItemDO; import org.opengoofy.index12306.biz.orderservice.dao.entity.OrderItemPassengerDO; import org.opengoofy.index12306.biz.orderservice.dao.mapper.OrderItemMapper; import org.opengoofy.index12306.biz.orderservice.dao.mapper.OrderMapper; import org.opengoofy.index12306.biz.orderservice.dto.domain.OrderStatusReversalDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.CancelTicketOrderReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.TicketOrderCreateReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.TicketOrderItemCreateReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.TicketOrderPageQueryReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.req.TicketOrderSelfPageQueryReqDTO; import org.opengoofy.index12306.biz.orderservice.dto.resp.TicketOrderDetailRespDTO; import org.opengoofy.index12306.biz.orderservice.dto.resp.TicketOrderDetailSelfRespDTO; import org.opengoofy.index12306.biz.orderservice.dto.resp.TicketOrderPassengerDetailRespDTO; import org.opengoofy.index12306.biz.orderservice.mq.event.DelayCloseOrderEvent; import org.opengoofy.index12306.biz.orderservice.mq.event.PayResultCallbackOrderEvent; import org.opengoofy.index12306.biz.orderservice.mq.produce.DelayCloseOrderSendProduce; import org.opengoofy.index12306.biz.orderservice.remote.UserRemoteService; import org.opengoofy.index12306.biz.orderservice.remote.dto.UserQueryActualRespDTO; import org.opengoofy.index12306.biz.orderservice.service.OrderItemService; import org.opengoofy.index12306.biz.orderservice.service.OrderPassengerRelationService; import org.opengoofy.index12306.biz.orderservice.service.OrderService; import org.opengoofy.index12306.biz.orderservice.service.orderid.OrderIdGeneratorManager; import org.opengoofy.index12306.framework.starter.common.toolkit.BeanUtil; import org.opengoofy.index12306.framework.starter.convention.exception.ClientException; import org.opengoofy.index12306.framework.starter.convention.exception.ServiceException; import org.opengoofy.index12306.framework.starter.convention.page.PageResponse; import org.opengoofy.index12306.framework.starter.convention.result.Result; import org.opengoofy.index12306.framework.starter.database.toolkit.PageUtil; import org.opengoofy.index12306.frameworks.starter.user.core.UserContext; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; import java.util.Objects;
10,987
/* * 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.opengoofy.index12306.biz.orderservice.service.impl; /** * 订单服务接口层实现 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class OrderServiceImpl implements OrderService { private final OrderMapper orderMapper; private final OrderItemMapper orderItemMapper; private final OrderItemService orderItemService; private final OrderPassengerRelationService orderPassengerRelationService; private final RedissonClient redissonClient; private final DelayCloseOrderSendProduce delayCloseOrderSendProduce; private final UserRemoteService userRemoteService; @Override public TicketOrderDetailRespDTO queryTicketOrderByOrderSn(String orderSn) { LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class) .eq(OrderDO::getOrderSn, orderSn); OrderDO orderDO = orderMapper.selectOne(queryWrapper);
/* * 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.opengoofy.index12306.biz.orderservice.service.impl; /** * 订单服务接口层实现 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @Slf4j @Service @RequiredArgsConstructor public class OrderServiceImpl implements OrderService { private final OrderMapper orderMapper; private final OrderItemMapper orderItemMapper; private final OrderItemService orderItemService; private final OrderPassengerRelationService orderPassengerRelationService; private final RedissonClient redissonClient; private final DelayCloseOrderSendProduce delayCloseOrderSendProduce; private final UserRemoteService userRemoteService; @Override public TicketOrderDetailRespDTO queryTicketOrderByOrderSn(String orderSn) { LambdaQueryWrapper<OrderDO> queryWrapper = Wrappers.lambdaQuery(OrderDO.class) .eq(OrderDO::getOrderSn, orderSn); OrderDO orderDO = orderMapper.selectOne(queryWrapper);
TicketOrderDetailRespDTO result = BeanUtil.convert(orderDO, TicketOrderDetailRespDTO.class);
26
2023-11-23 07:59:11+00:00
16k
estkme-group/infineon-lpa-mirror
app/src/main/java/com/infineon/esim/lpa/data/DataModel.java
[ { "identifier": "ActivationCode", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/ActivationCode.java", "snippet": "public class ActivationCode implements Parcelable {\n private String activationCode;\n\n private final Boolean isValid;\n private String acFormat;\n private String ...
import android.content.Context; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.Observer; import com.infineon.esim.lpa.core.dtos.ActivationCode; import com.infineon.esim.lpa.core.dtos.EuiccInfo; import com.infineon.esim.lpa.core.dtos.profile.ProfileList; import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata; import com.infineon.esim.lpa.core.dtos.result.remote.AuthenticateResult; import com.infineon.esim.lpa.core.dtos.result.remote.CancelSessionResult; import com.infineon.esim.lpa.core.dtos.result.remote.DownloadResult; import com.infineon.esim.lpa.euicc.EuiccManager; import com.infineon.esim.lpa.lpa.LocalProfileAssistant; import com.infineon.esim.lpa.ui.generic.ActionStatus; import com.infineon.esim.lpa.ui.generic.AsyncActionStatus; import com.infineon.esim.lpa.ui.generic.Error; import com.infineon.esim.lpa.util.android.OneTimeEvent; import com.infineon.esim.util.Log; import java.util.List;
13,011
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.data; public class DataModel implements StatusAndEventHandler{ private static final String TAG = DataModel.class.getName(); private static DataModel instance; private final LocalProfileAssistant lpa; private final EuiccManager euiccManager; private final MutableLiveData<AsyncActionStatus> actionStatusLiveData; private final MutableLiveData<OneTimeEvent<Error>> errorEventLiveData; private DataModel(Context context) { this.euiccManager = new EuiccManager(context, this); this.lpa = new LocalProfileAssistant(euiccManager, this); this.actionStatusLiveData = new MutableLiveData<>(); this.errorEventLiveData = new MutableLiveData<>(); euiccManager.initializeInterfaces(); actionStatusLiveData.observeForever(actionStatusObserver); } public static void initializeInstance(Context context) { if(instance == null) { instance = new DataModel(context); } } public static DataModel getInstance() { return instance; } // observing action status final Observer<AsyncActionStatus> actionStatusObserver = actionStatus -> { Log.debug(TAG, "Observed that action status changed: " + actionStatus.getActionStatus()); switch (actionStatus.getActionStatus()) { case ENABLE_PROFILE_FINISHED: case DELETE_PROFILE_FINISHED: case DISABLE_PROFILE_FINISHED: case SET_NICKNAME_FINISHED: refreshProfileList(); break; } }; // region Getter public LiveData<String> getCurrentEuiccLiveData() { return euiccManager.getCurrentEuiccLiveData(); } public LiveData<List<String>> getEuiccListLiveData() { return euiccManager.getEuiccListLiveData(); } public LiveData<ProfileList> getProfileListLiveData() { return lpa.getProfileListLiveData(); } public LiveData<AsyncActionStatus> getAsyncActionStatusLiveData() { return actionStatusLiveData; } public LiveData<OneTimeEvent<Error>> getErrorEventLiveData() { return errorEventLiveData; } // endregion // region eUICC interface methods public void refreshEuiccs() { Log.debug(TAG, "Refreshing eUICC list..."); euiccManager.startRefreshingEuiccList(); } public void selectEuicc(String euiccName) { Log.debug(TAG, "Selecting euicc " + euiccName + "..."); euiccManager.selectEuicc(euiccName); } public void startConnectingEuiccInterface(String interfaceTag) { Log.debug(TAG, "Connecting eUICC interface " + interfaceTag + "..."); euiccManager.startConnectingEuiccInterface(interfaceTag); } @SuppressWarnings("unused") public void startDisconnectingReader(String interfaceTag) { Log.debug(TAG, "Disconnecting eUICC interface " + interfaceTag + "..."); euiccManager.startDisconnectingInterface(interfaceTag); } @SuppressWarnings("unused") public Boolean isEuiccInterfaceConnected(String readerTag) { return euiccManager.isEuiccInterfaceConnected(readerTag); } // endregion // region LPA methods public EuiccInfo getEuiccInfo() { return lpa.getEuiccInfo(); } public void refreshEuiccInfo() { lpa.refreshEuiccInfo(); } public void refreshProfileList() { lpa.refreshProfileList(); } public void enableProfile(ProfileMetadata profile) { lpa.enableProfile(profile); } public void disableProfile(ProfileMetadata profile) { lpa.disableProfile(profile); } public void deleteProfile(ProfileMetadata profile) { lpa.deleteProfile(profile); } public void setNickname(ProfileMetadata profile) { lpa.setNickname(profile); } public void handleAndClearAllNotifications() { lpa.handleAndClearAllNotifications(); } public void authenticate(ActivationCode activationCode) { lpa.startAuthentication(activationCode); } public AuthenticateResult getAuthenticateResult() { return lpa.getAuthenticateResult(); } public void downloadProfile(String confirmationCode) { lpa.startProfileDownload(confirmationCode); } public DownloadResult getDownloadResult() { return lpa.getDownloadResult(); } public void cancelSession(long cancelSessionReason) { lpa.startCancelSession(cancelSessionReason); }
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.data; public class DataModel implements StatusAndEventHandler{ private static final String TAG = DataModel.class.getName(); private static DataModel instance; private final LocalProfileAssistant lpa; private final EuiccManager euiccManager; private final MutableLiveData<AsyncActionStatus> actionStatusLiveData; private final MutableLiveData<OneTimeEvent<Error>> errorEventLiveData; private DataModel(Context context) { this.euiccManager = new EuiccManager(context, this); this.lpa = new LocalProfileAssistant(euiccManager, this); this.actionStatusLiveData = new MutableLiveData<>(); this.errorEventLiveData = new MutableLiveData<>(); euiccManager.initializeInterfaces(); actionStatusLiveData.observeForever(actionStatusObserver); } public static void initializeInstance(Context context) { if(instance == null) { instance = new DataModel(context); } } public static DataModel getInstance() { return instance; } // observing action status final Observer<AsyncActionStatus> actionStatusObserver = actionStatus -> { Log.debug(TAG, "Observed that action status changed: " + actionStatus.getActionStatus()); switch (actionStatus.getActionStatus()) { case ENABLE_PROFILE_FINISHED: case DELETE_PROFILE_FINISHED: case DISABLE_PROFILE_FINISHED: case SET_NICKNAME_FINISHED: refreshProfileList(); break; } }; // region Getter public LiveData<String> getCurrentEuiccLiveData() { return euiccManager.getCurrentEuiccLiveData(); } public LiveData<List<String>> getEuiccListLiveData() { return euiccManager.getEuiccListLiveData(); } public LiveData<ProfileList> getProfileListLiveData() { return lpa.getProfileListLiveData(); } public LiveData<AsyncActionStatus> getAsyncActionStatusLiveData() { return actionStatusLiveData; } public LiveData<OneTimeEvent<Error>> getErrorEventLiveData() { return errorEventLiveData; } // endregion // region eUICC interface methods public void refreshEuiccs() { Log.debug(TAG, "Refreshing eUICC list..."); euiccManager.startRefreshingEuiccList(); } public void selectEuicc(String euiccName) { Log.debug(TAG, "Selecting euicc " + euiccName + "..."); euiccManager.selectEuicc(euiccName); } public void startConnectingEuiccInterface(String interfaceTag) { Log.debug(TAG, "Connecting eUICC interface " + interfaceTag + "..."); euiccManager.startConnectingEuiccInterface(interfaceTag); } @SuppressWarnings("unused") public void startDisconnectingReader(String interfaceTag) { Log.debug(TAG, "Disconnecting eUICC interface " + interfaceTag + "..."); euiccManager.startDisconnectingInterface(interfaceTag); } @SuppressWarnings("unused") public Boolean isEuiccInterfaceConnected(String readerTag) { return euiccManager.isEuiccInterfaceConnected(readerTag); } // endregion // region LPA methods public EuiccInfo getEuiccInfo() { return lpa.getEuiccInfo(); } public void refreshEuiccInfo() { lpa.refreshEuiccInfo(); } public void refreshProfileList() { lpa.refreshProfileList(); } public void enableProfile(ProfileMetadata profile) { lpa.enableProfile(profile); } public void disableProfile(ProfileMetadata profile) { lpa.disableProfile(profile); } public void deleteProfile(ProfileMetadata profile) { lpa.deleteProfile(profile); } public void setNickname(ProfileMetadata profile) { lpa.setNickname(profile); } public void handleAndClearAllNotifications() { lpa.handleAndClearAllNotifications(); } public void authenticate(ActivationCode activationCode) { lpa.startAuthentication(activationCode); } public AuthenticateResult getAuthenticateResult() { return lpa.getAuthenticateResult(); } public void downloadProfile(String confirmationCode) { lpa.startProfileDownload(confirmationCode); } public DownloadResult getDownloadResult() { return lpa.getDownloadResult(); } public void cancelSession(long cancelSessionReason) { lpa.startCancelSession(cancelSessionReason); }
public CancelSessionResult getCancelSessionResult() {
5
2023-11-22 07:46:30+00:00
16k
phamdung2209/FAP
src/main/java/com/func/LectureHandler/Update.java
[ { "identifier": "DateOfBirth", "path": "src/main/java/com/Date/DateOfBirth.java", "snippet": "public class DateOfBirth {\n private int day;\n private int month;\n private int year;\n\n public DateOfBirth() {\n }\n\n public DateOfBirth(int day, int month, int year) {\n this.day =...
import java.util.Scanner; import com.date.DateOfBirth; import com.persons.Administrator; import com.persons.Lecturer;
11,178
package com.func.LectureHandler; public class Update { public Scanner scanner = new Scanner(System.in);
package com.func.LectureHandler; public class Update { public Scanner scanner = new Scanner(System.in);
public void updateLecture(Administrator admin, String lectureIdUpdate) {
1
2023-11-23 18:42:19+00:00
16k
morihofi/acmeserver
src/main/java/de/morihofi/acmeserver/certificate/acme/api/endpoints/account/NewAccountEndpoint.java
[ { "identifier": "Provisioner", "path": "src/main/java/de/morihofi/acmeserver/certificate/acme/api/Provisioner.java", "snippet": "public class Provisioner {\n\n\n /**\n * Get the ACME Server URL, reachable from other Hosts\n *\n * @return Full url (including HTTPS prefix) and port to this ...
import com.google.gson.Gson; import de.morihofi.acmeserver.certificate.acme.api.Provisioner; import de.morihofi.acmeserver.certificate.acme.api.abstractclass.AbstractAcmeEndpoint; import de.morihofi.acmeserver.certificate.acme.api.endpoints.account.objects.ACMEAccountRequestPayload; import de.morihofi.acmeserver.certificate.acme.api.endpoints.account.objects.AccountResponse; import de.morihofi.acmeserver.certificate.objects.ACMERequestBody; import de.morihofi.acmeserver.database.Database; import de.morihofi.acmeserver.certificate.acme.security.NonceManager; import de.morihofi.acmeserver.exception.exceptions.ACMEInvalidContactException; import de.morihofi.acmeserver.exception.exceptions.ACMEMalformedException; import de.morihofi.acmeserver.tools.crypto.Crypto; import de.morihofi.acmeserver.tools.regex.EmailValidation; import io.javalin.http.Context; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import java.util.List; import java.util.UUID;
11,072
package de.morihofi.acmeserver.certificate.acme.api.endpoints.account; public class NewAccountEndpoint extends AbstractAcmeEndpoint { /** * Logger */ public final Logger log = LogManager.getLogger(getClass()); public NewAccountEndpoint(Provisioner provisioner) { super(provisioner); } @Override
package de.morihofi.acmeserver.certificate.acme.api.endpoints.account; public class NewAccountEndpoint extends AbstractAcmeEndpoint { /** * Logger */ public final Logger log = LogManager.getLogger(getClass()); public NewAccountEndpoint(Provisioner provisioner) { super(provisioner); } @Override
public void handleRequest(Context ctx, Provisioner provisioner, Gson gson, ACMERequestBody acmeRequestBody) throws Exception {
4
2023-11-22 15:54:36+00:00
16k
clover/clover-tr34-host
src/main/java/com/clover/tr34/samples/CloverDevTr34KeyStoreData.java
[ { "identifier": "Tr34CryptoUtils", "path": "src/main/java/com/clover/tr34/Tr34CryptoUtils.java", "snippet": "public final class Tr34CryptoUtils {\n\n private Tr34CryptoUtils() { }\n\n public static PrivateKey parsePrivateKey(String pem) {\n if (pem.contains(\"BEGIN RSA PRIVATE KEY\")) {\n ...
import com.clover.tr34.Tr34CryptoUtils; import com.clover.tr34.Tr34KdhRevocation; import com.clover.tr34.Tr34KeyStoreData; import com.clover.tr34.Tr34ScdKeyStoreData; import java.math.BigInteger; import java.security.PrivateKey; import java.security.cert.CRLReason; import java.security.cert.X509Certificate; import java.util.Collections; import java.util.Date; import java.util.List;
13,488
"wflimluDSY8R/j9FhyfRWyP944X2tTmg+wfi2i7sAmuM+WKN+DxOaiFQ3zlgUDK5\n" + "cGqCXzYMN7phPUL4U1UQ9Ucgk7CIg8Cnn/ayyyo+GKFmMPo322r4H7A3ccRENQqq\n" + "DTNdAoGBALKefyenQOTgjdIXlDICTIM4VRAMzrGI43wnIPKE6DEZwxhzt0jE5NYu\n" + "jWpTbaTuduIC6/b0jbiIBDefrOh/Rw4iVicXxC4lJJCoLqrNdLBfqvt9JAvBndan\n" + "KlXNyoIMUktye1+fywLHfmU+k0tWMm2PacdD7V4aUpN3G1qQeIwt\n" + "-----END RSA PRIVATE KEY-----\n"; public static final String TR34_KRD_1_Cert_Pem = "-----BEGIN CERTIFICATE-----\n" + "MIIDcDCCAligAwIBAgIQbCpMOGMtYO46ksi7B0ziSTANBgkqhkiG9w0BAQsFADBT\n" + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xvdmVyMREwDwYDVQQLEwhkZXZpY2Vv\n" + "czEgMB4GA1UEAxMXVEVTVCBDbG92ZXIgVFIzNCBLUkQgQ0EwHhcNMjMwOTAxMjIw\n" + "NjUwWhcNMzgwODE0MjIwMDA5WjBSMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xv\n" + "dmVyMREwDwYDVQQLEwhkZXZpY2VvczEfMB0GA1UEAxMWVEVTVCBDbG92ZXIgVFIz\n" + "NCBLUkQgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALhilgrs5YCt\n" + "DSiWa/Z/TX96qztN0dLlyh7rYimeBkEpEU4kJwWogRrt6CGIQ1+guSZLm4QtqWzn\n" + "bR72bDSJHLArnWi+Dx+9AHMK1AaZUrf75eC/yh5yV/sI0YFmnWp4DjV0AtGKgzDm\n" + "cjgQloIR2zrUrPXihXSUcwxJe0q/IqrMEdQ+morvZ2w+8Vlo1WszyvknhrCUWzKg\n" + "zf9DZ+9BG1fKREffS2SUruBHCFkQeXDFdP3d1RtgZznWGXQhwUXa5jkoFkR4jQYK\n" + "R8Lhj8v9YEbWcG8L7lOMkCZfRWeGzuQnjKRS9bx6D67gxvY2XJLbmfov4HNVkdxS\n" + "O68xEd8qI6UCAwEAAaNBMD8wDgYDVR0PAQH/BAQDAgeAMAwGA1UdEwEB/wQCMAAw\n" + "HwYDVR0jBBgwFoAU11VYe+bdyaYUH4MF8MFoJvdaOFkwDQYJKoZIhvcNAQELBQAD\n" + "ggEBAKdiYCU87sxKtldqs+4bNrSIXEwc/6XKCG2nCCToGNYOE2FApDWBZcOUcSEd\n" + "Lp0n7FEa/gLWVr5J/EOUkDp+5gAgmtbyvHptla8ThxVWPFHCXXbo4qlylfFwcXF1\n" + "OG8I+mwggUSh9DFoq27JUJApjaDcVyQ2Ywvdq0EcITYgrrZKZrqD7JYTEYmVXtKq\n" + "B4091HxtSM9vWophBudJDfK308x9fj+PM6AZqWRG7XCMShi3tVERiImTw0Pqn2/P\n" + "K0aEafxpvTRJh0kjsujX4HteBGXzLjjikfyjJKGz6Fyl5A8T9VAEFObqqZQ6Sa92\n" + "wMMs9Ow1xNvbr1cGImewoVhyBJU=\n" + "-----END CERTIFICATE-----"; public static final String TR34_KRD_1_PrivateKey_Pem = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEogIBAAKCAQEAuGKWCuzlgK0NKJZr9n9Nf3qrO03R0uXKHutiKZ4GQSkRTiQn\n" + "BaiBGu3oIYhDX6C5JkubhC2pbOdtHvZsNIkcsCudaL4PH70AcwrUBplSt/vl4L/K\n" + "HnJX+wjRgWadangONXQC0YqDMOZyOBCWghHbOtSs9eKFdJRzDEl7Sr8iqswR1D6a\n" + "iu9nbD7xWWjVazPK+SeGsJRbMqDN/0Nn70EbV8pER99LZJSu4EcIWRB5cMV0/d3V\n" + "G2BnOdYZdCHBRdrmOSgWRHiNBgpHwuGPy/1gRtZwbwvuU4yQJl9FZ4bO5CeMpFL1\n" + "vHoPruDG9jZcktuZ+i/gc1WR3FI7rzER3yojpQIDAQABAoIBADJnKLLl3TrWk2FD\n" + "9VFVrV6qrsIwXKo1DJJ1L8lGnFkVm9hrg4tFa71ryWfZMumiKtqwElwIi2bswGSV\n" + "YjDeRkxWL9phEgtQBB5umFURdo46urU8WEkIYsqJt5OS9HcVSHUOOHMFVSV56UEw\n" + "L6Rwsyga2QkCGg8rQWPbdmuRYi2j0j95IFvszn7kzQZ6hcoEdbhedYX85Ij4mgR7\n" + "ydeli6SAMQ8dRIbsOFhdf07DvA5st59lRTDeC/kyYMN6SZHRl7Vr9cvsTVawJb7v\n" + "v94Q3fRqzq9rB/JdHjVjjx+NM97sc7azZFFFVtrnlOG80k4lMIZLnjH0ZMpXrkY6\n" + "4Vv7p6UCgYEA5uLIa9+vopgpgTR4CUmqAcDh6EAzAOyIRTxag5c0i2Tz+x4ffc2Y\n" + "6s7Rs9x1b8ypr+z8GKmsjhEyxlToFEG0cZTBQzQEMsQ89jJbbLz8pSglS1hM3W4Y\n" + "zDGhiBtiJRpvuA3ZJN0No09cYDbH/y5ZyM6AAgwK1uD0vu5eTvoP83MCgYEAzHDy\n" + "8rVoHfF82pHrmzz8NRhf8SuDI+rwm+ThDnphteMXmJSz9ki8lljaF2T/mMsCHn1B\n" + "o+R5WTg1b/0+YGEH7OAjKNx+6K7BCZ1dA5S+dHtZjCvp2Bp3UL7FtK3dptQEL3t+\n" + "0SnSFBZ9lpXLj8dQNTwISVM8LD7vOBtVAOZftocCgYApFqzSPcGU7v1b6AmApaJi\n" + "o3/QhDRPcsihgaceCfeo4vNkeizih4cyKlI5bv9bQRHlpAgNH4z8z2S41P1kNXk2\n" + "SWHHYudoXXH34mhQxqUzgxx39yPeuCwjkqWLgkwKDFVbbON64vf9Wy82VCltaUND\n" + "MDSpqJj5OplzrRoNdgUGrwKBgEPHrsSJIFvNFHfiqRpuva9cxXJP2sqtudf1qigC\n" + "qyKCh/AuXPvqYZv3GVdoRNWDeNBi9sA/n3vVBuJ6M5QAl4ART5bcg7bhOV7WrV/i\n" + "kMJNowK2DHF5VNWQajvc6P/Gixyy9PijxOKkEj86qqKgkhcUMCsfTXPd6bHQXf5O\n" + "Yq1BAoGAaYsPFFv1uZJSDLb4kd5wW1o2AV2a5PhKqn71dCvYal6Dtm66jQnSvWSN\n" + "Jo7ewgPInB6FGUiHkG0uxCDaWxbqMoX0Gv6qhXP70TNg6PxTFZYQIcMOtjMWtfbo\n" + "JJbzKc5rgdHayNGWor9LWY7Y3gFASuItLuHLyI8n8Xx/zuaLxv8=\n" + "-----END RSA PRIVATE KEY-----"; private final X509Certificate rootCert; private final X509Certificate krdCaCert; private final X509Certificate kdhCaCert; private final X509Certificate kdhCert; private final PrivateKey krdCaPrivateKey; private final PrivateKey kdhCaPrivateKey; private final PrivateKey kdhPrivateKey; private CloverDevTr34KeyStoreData(String kdhCertPem, String kdhPrivateKeyPem) { kdhCert = Tr34CryptoUtils.parseCert(kdhCertPem); kdhPrivateKey = Tr34CryptoUtils.parsePrivateKey(kdhPrivateKeyPem); rootCert = Tr34CryptoUtils.parseCert(TR34_Root_Cert_Pem); kdhCaCert = Tr34CryptoUtils.parseCert(TR34_KDH_CA_Cert_Pem); krdCaCert = Tr34CryptoUtils.parseCert(TR34_KRD_CA_Cert_Pem); kdhCaPrivateKey = Tr34CryptoUtils.parsePrivateKey(TR34_KDH_CA_PrivateKey_Pem); krdCaPrivateKey = Tr34CryptoUtils.parsePrivateKey(TR34_KRD_CA_PrivateKey_Pem); } public static final Tr34KeyStoreData KDH_1 = new CloverDevTr34KeyStoreData(TR34_KDH_1_Cert_Pem, TR34_KDH_1_PrivateKey_Pem); public static final Tr34KeyStoreData KDH_2 = new CloverDevTr34KeyStoreData(TR34_KDH_2_Cert_Pem, TR34_KDH_2_PrivateKey_Pem); @Override public X509Certificate getRootCert() { return rootCert; } @Override public X509Certificate getKdhCaCert() { return kdhCaCert; } @Override public X509Certificate getKdhCert() { return kdhCert; } @Override public X509Certificate getKrdCaCert() { return krdCaCert; } @Override public Tr34ScdKeyStoreData getKdhKeyStoreData() { return new Tr34ScdKeyStoreData(kdhCert, kdhPrivateKey); } @Override public Tr34ScdKeyStoreData getKdhCaKeyStoreData() { return new Tr34ScdKeyStoreData(kdhCaCert, kdhCaPrivateKey); } @Override public Tr34ScdKeyStoreData getKrdCaKeyStoreData() { return new Tr34ScdKeyStoreData(krdCaCert, krdCaPrivateKey); } @Override
package com.clover.tr34.samples; /** * Sample TR-34 keys and certificates generated by Clover for test and development purposes. */ public final class CloverDevTr34KeyStoreData extends Tr34KeyStoreData { // Generated via https://github.corp.clover.com/clover/go-pki-helpers/tree/tr34-test/TR34-sample static final String TR34_Root_Cert_Pem = "-----BEGIN CERTIFICATE-----\n" + "MIIDdDCCAlygAwIBAgIQTq9Hb668e0nzTs0Y45MgBTANBgkqhkiG9w0BAQsFADBU\n" + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xvdmVyMREwDwYDVQQLEwhkZXZpY2Vv\n" + "czEhMB8GA1UEAxMYVEVTVCBDbG92ZXIgVFIzNCBSb290IENBMB4XDTIzMDkwMTIy\n" + "MDAwOVoXDTM4MDgyODIyMDAwOVowVDELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkNs\n" + "b3ZlcjERMA8GA1UECxMIZGV2aWNlb3MxITAfBgNVBAMTGFRFU1QgQ2xvdmVyIFRS\n" + "MzQgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANeeAxCc\n" + "XTnUkxgp2UN5mZHS7sv3KaJ7iWqo16KxHlAKpC+DaN1e+fSFaXlI6tWs9VWqDuuv\n" + "H8xBUAoIWaPE/Rm7trgmYNjKtCs2v2QLAsq6rzfo1v3SjO9DjuiuZt9W7BpqTAOb\n" + "fzNXMb/W0gwL9cRn6Y9bMioumnW+Emhou3u4pU3wxIrt3zjqpQ2MhYBadWBb1ZtF\n" + "919NgI7H91MntGVrOOoteXPSK3ygWowJ2K7qgfT37pX13N1duZserHWZXjNU7GuC\n" + "NoNDnatnxBKRnoQLc3G47gNSVr6PGA0T4PzE/8j/S+OV2kLTU7JFQoPi7hXUHeCw\n" + "D0a1yiUVDzF8B+0CAwEAAaNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF\n" + "MAMBAf8wHQYDVR0OBBYEFEnohVQIi1LkEJlHSASkhosTKgiJMA0GCSqGSIb3DQEB\n" + "CwUAA4IBAQBOLLkBLVfa8cggTa4gx5WCKSucNM/1t81fC15r6B0/VjUPwKrRpd+T\n" + "akwsJ3ScjSOWk6rfWjzaXQMJfH5cKj2bmnSLPKYnVnX0UiWlckVKTGhl7oK1+eWE\n" + "QvZmPKD6oRKcsXjmi6E2ZdJEb0HzEm78eoa2Q61sCmL+aKVPBtctUuPrD84ETxd9\n" + "hNRdrzXGVJesg58q4ULGwd9qC/6eMDYbHX17E2Lf2XwM9/Aq6ITNlv8/fcBYIFPy\n" + "AVjPD+QqayNyC5LsLRGi9a76h8FDVHHKpMxg3vxbtiXIJ7Hg5vPrQWcFOpj1HQyC\n" + "L4aXPicIuSyrg3b8M1WSp24bJkMptmhj\n" + "-----END CERTIFICATE-----"; static final String TR34_Root_PrivateKey_Pem = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEowIBAAKCAQEA154DEJxdOdSTGCnZQ3mZkdLuy/cponuJaqjXorEeUAqkL4No\n" + "3V759IVpeUjq1az1VaoO668fzEFQCghZo8T9Gbu2uCZg2Mq0Kza/ZAsCyrqvN+jW\n" + "/dKM70OO6K5m31bsGmpMA5t/M1cxv9bSDAv1xGfpj1syKi6adb4SaGi7e7ilTfDE\n" + "iu3fOOqlDYyFgFp1YFvVm0X3X02Ajsf3Uye0ZWs46i15c9IrfKBajAnYruqB9Pfu\n" + "lfXc3V25mx6sdZleM1Tsa4I2g0Odq2fEEpGehAtzcbjuA1JWvo8YDRPg/MT/yP9L\n" + "45XaQtNTskVCg+LuFdQd4LAPRrXKJRUPMXwH7QIDAQABAoIBAQCcrGejuUsQi4N6\n" + "6mXB3ukVCgWU1fs94rBefWN7B2J0XNci40TennXYFN0oUTC6pRv77D89SJo9bDQB\n" + "pkGke65B9aF2vARhYyF5ySVXR5z2vKI3aQxXkZfw/9EnCBseLGYRZ63mbSYHo1M2\n" + "B53HPSWPWsZe8bBI8GYyKjPsBDY/Vf3uvgEnS7MeGqiXTtpBo0WBPrXcbu5GWO+/\n" + "ujmUyB7FWE2V+venTxP4vsDngtcrdhdw07K+vYlE6GWFsne44VT9qI9c3Qqs/QZ5\n" + "M2pzuuV9dm6nkZVTk4frI0FXh4H7n3Ir08qtw8pmQbms4nRXHorfluWgMnwOO/MN\n" + "Vn7MXzFNAoGBAOmpCDMin9AgWjb3Q6t6lllJLxbWqF5mLv3eergOhDS3dvEQIIIw\n" + "7HmHaoVnpcHXKVhHJZwgvjWzy3dD1ctxQGi/qxN0vTzpoy8uHKG6efyFHOjEFnD3\n" + "8uB3DiNvVQEDoXvDXow+pfbZ80PCPRZbYdt+j5gS84eQQvzHpK7sNMyTAoGBAOw7\n" + "XbpxzKElbJuDN4yisscG267ooQuEzANlvATP1dhnfPRx7JhKk0cOWVHq/sHrg7Z5\n" + "+g/qA/Q86Oi1x7qfDSfWy5X2nII0MVVQPVufTErxo06ammojDzGQACTWjWH5l+cG\n" + "uCsMo4Ij2t0/Ab3p/Wi4jkQ2mIb0ypTvE58ivSl/AoGANRdWKKBGZbjkJrcaJh1t\n" + "ig4J6AuQKBrZtI9XnPiXa48ANJfwewR4xshRGMzLKfckis1nq0j5TyRyJ8A/FMG/\n" + "280pJvuQgAWqMW8tzEWdsBXi0rSzUKnWAtCqYrzKOLfFemSS2BToCuXM02mQDcNn\n" + "wcLJB8nOkc/imKMYNTKwcIcCgYAFpuX3MAHVWS/gCKOrmbjtShy3cplnzSWUbzqw\n" + "YsibBN7YemFOw3oCmTVJ4HV37kqYcxKojtDJZyurZa4BqQyHh3wXem8ELnt/rwvI\n" + "xWbt5BokJ07Ke0xBw1A9kWSQk4gu3tpJLWQ8GN+Dq54/DPojJ0dAGo5LrE+sgIvX\n" + "ot0jwQKBgAlCkynsA1AeyuPZ/G7LXKzAGuCYZinDvrOwtpWNr0nQ/Ssj7UN9kg0/\n" + "rBCqZ+f3Nt3v8Scw9qwdEt7toemTKMgFr2UHa50tgFW01kcy8anAAJLO9CDgKIsz\n" + "T8hE9bnM3CWl4E/8jNCw3tIx8+xQruGZZ3GB8XsIWML2xzVziBaT\n" + "-----END RSA PRIVATE KEY-----"; static final String TR34_KDH_CA_Cert_Pem = "-----BEGIN CERTIFICATE-----\n" + "MIIDlDCCAnygAwIBAgIQTqak5H7dM9yiy3fI6yraoDANBgkqhkiG9w0BAQsFADBU\n" + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xvdmVyMREwDwYDVQQLEwhkZXZpY2Vv\n" + "czEhMB8GA1UEAxMYVEVTVCBDbG92ZXIgVFIzNCBSb290IENBMB4XDTIzMDkwMTIy\n" + "MDAzN1oXDTM4MDgyMTIyMDAwOVowUzELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkNs\n" + "b3ZlcjERMA8GA1UECxMIZGV2aWNlb3MxIDAeBgNVBAMTF1RFU1QgQ2xvdmVyIFRS\n" + "MzQgS0RIIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqH8jmFXC\n" + "FXIfo9EMWcvo6NDDkxtkSUwFV9T/ONkqEzydA16p/+Ja5+ythXTvXjMWXjfCpg76\n" + "83QSRASq2CV7VXIMAG/YosQWlbDTIniYcJn9naMBUoIIQ4nw6Hxs4x4X3IOi0c/+\n" + "80UIxd3lCuSh3Y6iDs08BUfe1g7XI0JGUrdEjL3VVD14N3fSNCxLiwsmbhcMjPPe\n" + "KpJdZB9rXpuxybHhvy1fyktOe+sXl+j+T5AfD3gbWjSQJfC5ylOS2b5jz56cO51c\n" + "T8RK/UWGHR4hwbiF+Of+HJKU6ZDLcDQ1XmUL1RC6c8QKW/Ziha5sbxlxmspendqR\n" + "ZQOLtLbTgTh4sQIDAQABo2MwYTAOBgNVHQ8BAf8EBAMCAgQwDwYDVR0TAQH/BAUw\n" + "AwEB/zAdBgNVHQ4EFgQUbeIyuJDjaE5J/WjddKCtqKMCQ4wwHwYDVR0jBBgwFoAU\n" + "SeiFVAiLUuQQmUdIBKSGixMqCIkwDQYJKoZIhvcNAQELBQADggEBAJ36O4R+sbAz\n" + "GResQmn66zoI+0OR0rHZbGvW5b/fjllGtn4L4CoyH+1VkOtBv+HEswGu/3Q4Chfg\n" + "Mo/rAX2gIHPqQhKlmETC/4wcSFp+ml6VC1exfsYjWggoWQ17NigRh8TMFBDHmxE+\n" + "PsdsKf8vzRYw603OYpAPKPiRotzCsMS25EGw+LbzT4C3peNQSz7DKWRB4Ynk6fj6\n" + "OPzWWOMHAtSufVQ1VUqUAqjxRbi78ze/iJf31cpTjw9IJUhRMZdYIHv6okM64QbH\n" + "HaewJPOBdsbwk+6A/6RT//gilj2i6SlIo3yAjvzFTWCeOPvgxI0pUV+DGCWSRHki\n" + "zqoixiFihpE=\n" + "-----END CERTIFICATE-----"; static final String TR34_KDH_CA_PrivateKey_Pem = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEpQIBAAKCAQEAqH8jmFXCFXIfo9EMWcvo6NDDkxtkSUwFV9T/ONkqEzydA16p\n" + "/+Ja5+ythXTvXjMWXjfCpg7683QSRASq2CV7VXIMAG/YosQWlbDTIniYcJn9naMB\n" + "UoIIQ4nw6Hxs4x4X3IOi0c/+80UIxd3lCuSh3Y6iDs08BUfe1g7XI0JGUrdEjL3V\n" + "VD14N3fSNCxLiwsmbhcMjPPeKpJdZB9rXpuxybHhvy1fyktOe+sXl+j+T5AfD3gb\n" + "WjSQJfC5ylOS2b5jz56cO51cT8RK/UWGHR4hwbiF+Of+HJKU6ZDLcDQ1XmUL1RC6\n" + "c8QKW/Ziha5sbxlxmspendqRZQOLtLbTgTh4sQIDAQABAoIBAQCDG+Ljnx9VNqcd\n" + "/gVBPiRuPDtiFTdUvV2O+YLahkhyDYETZS6cmFIqEwT2SoYTY2ctSvAf7Joio5eu\n" + "637Qj2HHm+Vw1ZbZGAGG2r9/HB1pyLkKVxMpU1sAyq31CRRlKT5h7N/dqJ32RypL\n" + "ZJzbfAnjbx/0qofgiAsBvyxyGBjGNOc0BLZLa7fIOVcq+G+SjPuWFFy3ehCcoko+\n" + "bW+zl8/21x1E8VEy4R0ftEMqsehFpUIV8Fbgj4yp+S1j6aFZ/kJqX6PdxbIyaVaf\n" + "UTGrLThHKaqYZWSXzgEv+M7e2nwBEwnUDl3KUchxsFSzNFY6zvTlT12s2xTIKa2m\n" + "gYKU5tXBAoGBANaOSHlshAdrDm/UJCREr7mTJZdpdrXQMKv7s0p0QRQp/loSms+N\n" + "+Fl35Sv7mdVyQCRJu2o5lGAto5y6YBe34NHBAcYwDU3fRBrDUfVQM6ZukSkQKgRC\n" + "0lWVYzv8hQBjyX2YxmlH1cGbflJ0Zf3KfVzxQOure/r4RR85Ej2R4AVJAoGBAMkL\n" + "PrvVZqShnVxE5SplvCgmXEQoh7l4ePta+utuX//ecnbC2AAwGoLVntK9wLRUhF2c\n" + "tziOIIUksdwunR+32RSclK6pEMblwKVz1D7Llg+7a+iZH5TzWwHOv65jL8Mro4SZ\n" + "+XQ+XJohW6l/yQKE9P+KljCqTqKynH0jhO76uqApAoGBAMQaxnldSwvwuQBTmTkh\n" + "IrBuozRSa/NgN6xqYYSS34zLmTTAvokozS8RXAEodYHXbHL+hXNg75I9BMdSvlPP\n" + "eIifbby03OQpRnljvzyGMr9TXhB3OsAsR018PnhspTAnBNpsUiWWR/Uu53X79+DR\n" + "PGZACEOfuLE6TQttwZNPCsApAoGBAKEnyHPdDlhtzKxH9cNUpc0xYsioDJQaBDDI\n" + "r1bFtWJvuCWG7orIBJhYEOYxgSWMkkZP93b4Rw0zavdqzjy8rOCe23hewboONazq\n" + "+noTzAh0Xn2nMO+/W3ZJetGZZJH4iy0iGBqcWrKahtWKP2ErnxCw0M/V1Q8KSfLt\n" + "5AOFLNBxAoGAHmCkNBjctPfG9Sl2/Tud2ERYiNZimSLdKn3UnOpY9W8Y97r6SBtP\n" + "qj8vDbVrhPwudEz8GfXsbUmwxP9LLqXndjURAosAtE79cdSckJETRbnAJBpZ756R\n" + "CDeQuo9S44CIbt0B9EfcGGN1uWKEsrfm7NdAWny5WH83y9T6jPsKOcQ=\n" + "-----END RSA PRIVATE KEY-----"; static final String TR34_KRD_CA_Cert_Pem = "-----BEGIN CERTIFICATE-----\n" + "MIIDlDCCAnygAwIBAgIQHIcewFfOHCCMjreEjAm3HDANBgkqhkiG9w0BAQsFADBU\n" + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xvdmVyMREwDwYDVQQLEwhkZXZpY2Vv\n" + "czEhMB8GA1UEAxMYVEVTVCBDbG92ZXIgVFIzNCBSb290IENBMB4XDTIzMDkwMTIy\n" + "MDY0N1oXDTM4MDgyMTIyMDAwOVowUzELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkNs\n" + "b3ZlcjERMA8GA1UECxMIZGV2aWNlb3MxIDAeBgNVBAMTF1RFU1QgQ2xvdmVyIFRS\n" + "MzQgS1JEIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzSvOA0+t\n" + "J/h2/6mZQw/s/WckpTEu6dAmi9LqtaAZMdT+0bjcPYKpLSFJ8l0p0lLOiv6OsEVd\n" + "n7kb+N5hCOpsnV1gWW1L57VSpIdBlqdPD6PggUPslu+9gxDDbyCIrvET36W628Q2\n" + "Q+nGwZV1muRU81SuR6G8Wopk2nruqLlTcR3+cnv683eQdsYvvq4mH0+wL4Sc3Se/\n" + "wIuhwy3IimZyZLlNKmZ4cXzC/qnZKEwTumTkDX0WQo3dRTGL+D+1CeuwuKIO2HeG\n" + "KjGCTWvw0xyP3IWDotEh9FJImV+9G0xKphMdfT5GJfj/+ix2J14qqvsZgQbLlHbo\n" + "S/kqwZOGZAwZywIDAQABo2MwYTAOBgNVHQ8BAf8EBAMCAgQwDwYDVR0TAQH/BAUw\n" + "AwEB/zAdBgNVHQ4EFgQU11VYe+bdyaYUH4MF8MFoJvdaOFkwHwYDVR0jBBgwFoAU\n" + "SeiFVAiLUuQQmUdIBKSGixMqCIkwDQYJKoZIhvcNAQELBQADggEBAIAEIodvCDnt\n" + "6R0OthdfOOgP9LNbkrvliitAiN4MO3U5WKvN9WAVreTMoeymYe5gpcZ/eEJHByWX\n" + "ocVN/U/dmMIAuloVknASYTijfcswYdqCHMvaBzXJyM9vZCp+TjLeyg3rpyJiru3E\n" + "Gfwrc9yzdvX0VOx8a4FBWIDr3/hrl829Re096Z8mVuBSyveF39URHuE+WWA+arPK\n" + "S1xt2nbN2Nfn7ZefcanuAmu6+0WnY4JAnyq9A4O4yrQAsRO8+2fTl7lNrOiyT28a\n" + "t1PtYLjhr0WTNDZvHhfwkolIwJJuirsLkZRuG4VAV2tJ3ZBypg6g1sY8zZDz3ZJJ\n" + "Id4Aht1VESg=\n" + "-----END CERTIFICATE-----"; static final String TR34_KRD_CA_PrivateKey_Pem = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEpAIBAAKCAQEAzSvOA0+tJ/h2/6mZQw/s/WckpTEu6dAmi9LqtaAZMdT+0bjc\n" + "PYKpLSFJ8l0p0lLOiv6OsEVdn7kb+N5hCOpsnV1gWW1L57VSpIdBlqdPD6PggUPs\n" + "lu+9gxDDbyCIrvET36W628Q2Q+nGwZV1muRU81SuR6G8Wopk2nruqLlTcR3+cnv6\n" + "83eQdsYvvq4mH0+wL4Sc3Se/wIuhwy3IimZyZLlNKmZ4cXzC/qnZKEwTumTkDX0W\n" + "Qo3dRTGL+D+1CeuwuKIO2HeGKjGCTWvw0xyP3IWDotEh9FJImV+9G0xKphMdfT5G\n" + "Jfj/+ix2J14qqvsZgQbLlHboS/kqwZOGZAwZywIDAQABAoIBAHu3NExu2PzHKApV\n" + "3CLCEadjcIdjtuQqLXQWxIysc0THKLiRfcxhY13hOtO4NaWrZPwPLz8/NItBdYqF\n" + "nYFgygnB6n1CGIkpnyGypWwQiu3lZVTM/natLVtA2nfB6GmE2PT83EX0dLxS1RSZ\n" + "6QZzNH5dy5FKB2eZF+NeSVbYGWaVGD9l7Uy5L87zFOtFUVUPan3ONPbh3sPZA6mL\n" + "4FvaOcuNyJp6L5rFXitEC+6JdZyXid4o8xfG4p8+0JqzuDaTsdzNPPjuFVkpxBLy\n" + "8mWtGwThwvjGzpvBc7P5a5p7IyYWDpCEP4EmtMwgbrySBpgPKx1nX48YRtNIg+GO\n" + "uLTTqbECgYEA9/kOXiO05d9LBJofg6bIF4YI5r+SaddM2uW350AVVBNNhysD9Ixp\n" + "zQb2/9iBIPW0CxW4q16DMUktkIz20VKAHe4KqktbotTXyEkjRM2PPrr2DOssWR+J\n" + "CxjRi7UzdAE4/ICNlo3g6TRWMT35Jv6n+oCbsYyi6Am7qqbE2YH6bAcCgYEA09AN\n" + "OjlmxzKtPqpXLbUyxoghMed8cvyJzxNcZV3jyLSXAcnVAgeH8tCsY5Nc5ecOUq36\n" + "Ety4vBaKVorolKtVLrBtA8floEBhWYpzax7VJ3OKq8GYbafDX+eF/pXmevwDVotB\n" + "Cvo/kQwaX7lwZS4sJ4k4CQ4WRaeTB3hE1Vxl+x0CgYEArawVUAGaFNVK6TI4mDAb\n" + "O754RYQuu0o7XaQ+JQxQ482RIvYRkxk0kJAsNgwghEERlCHmcL+FCuPBsdfIldo+\n" + "OLgbaCHXUDfZ2UDAHtQJW1n+MhYTvWfEx6zeNgb2vmyMyOwQPj2oJCyvoVVSRulc\n" + "JKomYTeqcPFAKskaXWwXQ8kCgYEA0gdWZmqu0E0e3qmX4nnvTE+F4u8wRvDFUbFY\n" + "CCeui8EOj7Zr4iRHmO10UxS3pDyVxkQ/WV7GS7NqH2CEOY8e2zoUDxCzUFEmdtxD\n" + "kG+1WvZGBgPkuq8Em19/Ta+kKEUmpjVVHKaCS7idmlfN7HZ5UAbPqqLuUMlWkKyg\n" + "TJTfhr0CgYAdqiZlltOz9pJ5ZBCtduuohIc9mc5lDRabeKn9SXhPBOYZu2U+e+7a\n" + "L6WIX2bTtVq6B5qVv08/frdrBh5gzDig+mTiQxs3oQqersj5Cab89ruHVSoBYglr\n" + "/Zawxw4blDLa/R507/ipeFF1Tl2fxdN3s79/GVuoRE0LPH7zWnBsmw==\n" + "-----END RSA PRIVATE KEY-----"; public static final String TR34_KDH_1_Cert_Pem = "-----BEGIN CERTIFICATE-----\n" + "MIIDcDCCAligAwIBAgIQEt6WKvHM910o6MgARZ8UyzANBgkqhkiG9w0BAQsFADBT\n" + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xvdmVyMREwDwYDVQQLEwhkZXZpY2Vv\n" + "czEgMB4GA1UEAxMXVEVTVCBDbG92ZXIgVFIzNCBLREggQ0EwHhcNMjMwOTAxMjIw\n" + "MTQ1WhcNMzgwODE0MjIwMDA5WjBSMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xv\n" + "dmVyMREwDwYDVQQLEwhkZXZpY2VvczEfMB0GA1UEAxMWVEVTVCBDbG92ZXIgVFIz\n" + "NCBLREggMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANG3eq/n2Y9N\n" + "W+unTuzDoCT9XrHmLMukpM4qL4NCaJgBS7lXpcMBc7s9I954aw0TUKWBYDtgF6gv\n" + "s8DfMYcULW0/sH0LGVGBQ/dwUWY6vgfNfSDhtjGqEnl/JA0lwioSb7ZbxJ8pTv1H\n" + "F69GaBzkvYAbDJUcgDR5bEhCBxpel/Go2OzG3HknfVy1zaAIe9Z4z3FZ6Gp1e203\n" + "YRJjuaEhei8WsnZeUo1gVH8p3xDs9TrQsJTsS4E3IZukwemXF2dKMKgDGbo89QIc\n" + "wriJRhsDPAjvdkwCryhjCthjT+CcYkeiihSuTkrZbqSB3xU9ZNikI2aOs0suN0HW\n" + "su1+ZQppHz0CAwEAAaNBMD8wDgYDVR0PAQH/BAQDAgeAMAwGA1UdEwEB/wQCMAAw\n" + "HwYDVR0jBBgwFoAUbeIyuJDjaE5J/WjddKCtqKMCQ4wwDQYJKoZIhvcNAQELBQAD\n" + "ggEBADD96Ckbo9UFvCjZb0fMUHBbwpbZVLze/LUwxuQ2NOMDLZsP6TDtMYXMeeWN\n" + "+/VpuAmPt/2TwshUA6xuCtxV0XySsxMAhy77csGmfsA1dr0plYiMfGz0o03a+fcm\n" + "eTSO3GgCf6nJoH7Dxhfb0m4+CYIVlbvXG/C2sak98/orhux9SmjkfJ3ZtY4fYbp+\n" + "QOsMGdM6TZdXwjuG3luEVwUqrxMqLHpgJnf2I8jP9cNRvMXE9npoSq5v1MfWo6LG\n" + "WcbRVOvHwGPSlDzX1wmg+r99viY2LuHvSMmS90fs+XlxKIWJDpd20vY2UQRNBOn/\n" + "x71vA+0//1su6sE0LtPenoz2eFQ=\n" + "-----END CERTIFICATE-----"; static final String TR34_KDH_1_PrivateKey_Pem = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEpAIBAAKCAQEA0bd6r+fZj01b66dO7MOgJP1eseYsy6Skziovg0JomAFLuVel\n" + "wwFzuz0j3nhrDRNQpYFgO2AXqC+zwN8xhxQtbT+wfQsZUYFD93BRZjq+B819IOG2\n" + "MaoSeX8kDSXCKhJvtlvEnylO/UcXr0ZoHOS9gBsMlRyANHlsSEIHGl6X8ajY7Mbc\n" + "eSd9XLXNoAh71njPcVnoanV7bTdhEmO5oSF6Lxaydl5SjWBUfynfEOz1OtCwlOxL\n" + "gTchm6TB6ZcXZ0owqAMZujz1AhzCuIlGGwM8CO92TAKvKGMK2GNP4JxiR6KKFK5O\n" + "StlupIHfFT1k2KQjZo6zSy43Qday7X5lCmkfPQIDAQABAoIBADUWazpISKyb+p7m\n" + "1XXd95YlhWknSUOrxARkbW6eyvdfrJmYdF+u6GsHiSLx/LdsokejPocJRjPPD4PN\n" + "fC4jj3ROYRDmVFxripcCmbh1OlGjVP+T45ki4lZbNvcVDde0nw7coCNiQ5qd+oLm\n" + "IcjeppHdRwwgENw3uI96F243b+M+U1bmeYucL5hYYIh0W4juRpiAQUqYDmNTtGt2\n" + "DUH+ivs5FxuMVs+k/JciVbaMiVr9hs/FFY1p9qdT3jyiIKNUI8ScoX8/cefzW+wL\n" + "wNIuyRvPhIE2mkEIRGt3UHZz3pOqpWz0Yr+eluNPi5kAB0aEFHsDkx7fLVhXTJCY\n" + "SR2KYQkCgYEA9e3Ml9vjm78j3M75OcXWNxTDhbueQ8I+b3jEHilIOwg0w3U6uQDq\n" + "sXu0LA8u7DRqdIxV4JWoQzfX8BE7FXaB6CCGZzk5NbJz9WOGYq7zIQvGvUw6OzYN\n" + "JmcJKFTbyJd7IU7A5S/vLu4S/8+aGVpHWUU4TNpmNEnrFPYShem46zcCgYEA2k4M\n" + "gCVPEMuV8G73bsuB26D25OBiW+DjCSE5QgeLhW2d+HA4RZLR+N6gja5ZdSRKfh6v\n" + "tD2Q18P1OYibQUcXXZirynxPIBKgMYzQkeqqLeXpDK9+dELI3JO8iyQc3Jqf0NiK\n" + "QXKK2MI3NsnDgrJ/jj26ysQSuZ3yo71DqbVTyysCgYEA8fVvyK0YB+ELyLB99kBW\n" + "HUU5hTbtZF8VDJl14vLc1O+i8fdBuklTnyFFR9/8W3rKjjaQO3Ei5ldoBhL93YUG\n" + "FLsDYUWkqtcTTYgI7MiR/p5Wf2IjHKR2VaUkFmE/B+E5zLBuCk+Z9MNZQAQh6fWv\n" + "ov3+gWaTDbj4KFxeJxCn1gsCgYANq6WMwMlau+T/0XMdNRFEt6e+XW7LYiHViIcV\n" + "Y3ORP3QNAroDYVZUx1w2gxyHAWbIzxMhrllLqbHJkIxoYhNMgSsA2xf5YjE16SOG\n" + "f7N4fFVDvhmlHimF5pp//BrylZw8b9L4ljurpz3d6HSd0p+6QJNZ7z1c8k8ngcqi\n" + "7f/5UQKBgQC+/nN7ErSzAY0t3IAbhG8SxKoUrsgU+5WFEDTCuO/qnvXXQIG1VZZv\n" + "SkXt/EdTUsepE9YNHTVFGsGYV+Ctu/lbwVfrssi78dCsCr6+hAA6NznG4f8RoYSJ\n" + "0HuR2t8TorC9akETtuE1AKXoofITZVx+OuSocIn7em+cLzuZ7+38MQ==\n" + "-----END RSA PRIVATE KEY-----"; public static final String TR34_KDH_2_Cert_Pem = "-----BEGIN CERTIFICATE-----\n" + "MIIDcTCCAlmgAwIBAgIRAOlCYfqGO4D4ER57Qy5tGwswDQYJKoZIhvcNAQELBQAw\n" + "UzELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkNsb3ZlcjERMA8GA1UECxMIZGV2aWNl\n" + "b3MxIDAeBgNVBAMTF1RFU1QgQ2xvdmVyIFRSMzQgS0RIIENBMB4XDTIzMDkxODIw\n" + "MzYxNVoXDTM4MDgxNDIyMDAwOVowUjELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkNs\n" + "b3ZlcjERMA8GA1UECxMIZGV2aWNlb3MxHzAdBgNVBAMTFlRFU1QgQ2xvdmVyIFRS\n" + "MzQgS0RIIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCacdeuY7yK\n" + "Z8z33EqrrAxbdQLKvydy281qjLr9Rv5Gcf29m93WftqmDMSZF6buX8CGADRcU++f\n" + "17Ab2hXzkmnBItmnrs0bOtdXVqR3l4SaJM2V5fMYTFGJiBcrwdw3h/vAzU707ftb\n" + "3N04SJKR3xGqjCCqrDDKghiRkbLiOhi/oiDOAgXXZj4MM4x2/70Q6ikMSpLlsdix\n" + "yMnW8hmB5upBmodPV5Z0FAJu4lYwBNKpENz/34UEO9CwRje4lGfidmF7Zhg8G8HA\n" + "2BZIYRJqnoQRlJwIoR1+9/FAgEoKATEJV/x/4XxAnb7EtP29NlEhAUOEJufPGSpV\n" + "urhhRJeTJ4OHAgMBAAGjQTA/MA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAA\n" + "MB8GA1UdIwQYMBaAFG3iMriQ42hOSf1o3XSgraijAkOMMA0GCSqGSIb3DQEBCwUA\n" + "A4IBAQCE2+Bb/FzbnO15AJWoRpkJdLGdz3t+a4Q5eQEvSVTJHGR1lurjafn3RD3w\n" + "cRzfq1Y3iqIjgfwSdV7psM1hw2YD7z5Nm370YTNbox+QTNbyVQBWMh5X2ht2yR9G\n" + "tNU9MWMc75XIbU5dU2MdNmeIOx9Oco0NOfqAwmt3Bin7zlDTy3LMjSAjX8vut4Vm\n" + "G43iGj80kT3TIy4cAY+fA540ThdVl+n3+Ur3JfbcRMytbq+k2JIhBG1ec6o+6sxY\n" + "ZgGgDJhsPz1sQpgpsMfUwkZw80Jr4ZgZgm9KSkmHT5lCl1mbUHyJeXx9hof6Rd88\n" + "ZE5gnJg8yjk6rc2s6DIcTn1tEkTh\n" + "-----END CERTIFICATE-----\n"; public static final String TR34_KDH_2_PrivateKey_Pem = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEowIBAAKCAQEAmnHXrmO8imfM99xKq6wMW3UCyr8nctvNaoy6/Ub+RnH9vZvd\n" + "1n7apgzEmRem7l/AhgA0XFPvn9ewG9oV85JpwSLZp67NGzrXV1akd5eEmiTNleXz\n" + "GExRiYgXK8HcN4f7wM1O9O37W9zdOEiSkd8RqowgqqwwyoIYkZGy4joYv6IgzgIF\n" + "12Y+DDOMdv+9EOopDEqS5bHYscjJ1vIZgebqQZqHT1eWdBQCbuJWMATSqRDc/9+F\n" + "BDvQsEY3uJRn4nZhe2YYPBvBwNgWSGESap6EEZScCKEdfvfxQIBKCgExCVf8f+F8\n" + "QJ2+xLT9vTZRIQFDhCbnzxkqVbq4YUSXkyeDhwIDAQABAoIBAEHscgnIHMRfRkhO\n" + "Sbk5eRTYv1ZXfbkzRV1DsNVHpmXfZlW24FwcTawvKwPF6sU5Le6Ey9TVJyVtZYid\n" + "8FzFlEqSW6GNpZMH7L8lBpLdpAY/y1k+jCNFAFDaPDm7SAqUCsvjVt6Jbo9pmSvb\n" + "HmUReHL52T/AvBrUqTQJoveZoNK68cyq9Uz54oEvyt1WrU7zaNiFGpH90Q1Qhb2J\n" + "Nlpjihpc6syqluVruYND/bJm9DJGqMLdlS6uD6fXp5aCGfixwvndLq1h6TCzEXLf\n" + "HcL8elN60SIZXUKDKPEDIQQa9jzBx6eqThErCvr7lZ6+YNqIx4F+2nkJdoZCrXN5\n" + "9a+f7fECgYEAydySZAEN/bIUlwXvN04x675rJtc4ih++dUrT7QrLouzhMz4wdIwM\n" + "RnV3/i/vkQoec1zjI7VETKlfgRDlicFjgShiyz74KJrUxmgvrfQsgO9wkNKrtAsm\n" + "936Qizh5+3WjuAPf/xtZhk31NVDR8v5IJJEDl5Miv47MAJxiCv5rSvsCgYEAw923\n" + "lJYzgRjjKdBMOFNEliVsmWaPrnwQDKKtJ809dq5THYwK9/Taz5Xx2SQBWxZF06/Z\n" + "efW2IqhNAza4unyNmVTcKiKiy/ziZwLMVl5gBudzrFuVnxSaDd7kCAlL9dTJ17dq\n" + "sf2FadgmqCvIlCgpkodi+HSXfCYdJ4rViyg9g+UCgYA4h4WTbdwuLJ2pgWbxVPuT\n" + "6jp1oRXbUHJ0xGS+4CQQ10dlo0fMi5+wZ5sX2vK66luGsP+G829SDKiLK2Esh7TG\n" + "6blo85RpQprNiUW48EU6QlOCqwycmfbqnk36PvGiItqbYLJs7YrPmqtNp/lzlBQ9\n" + "8UJRQ0oa3PFyRlkKfR8s2wKBgHqmiYH7OI9b1UxmyoPu6KEZGFNLHShHOgmfiMzG\n" + "wflimluDSY8R/j9FhyfRWyP944X2tTmg+wfi2i7sAmuM+WKN+DxOaiFQ3zlgUDK5\n" + "cGqCXzYMN7phPUL4U1UQ9Ucgk7CIg8Cnn/ayyyo+GKFmMPo322r4H7A3ccRENQqq\n" + "DTNdAoGBALKefyenQOTgjdIXlDICTIM4VRAMzrGI43wnIPKE6DEZwxhzt0jE5NYu\n" + "jWpTbaTuduIC6/b0jbiIBDefrOh/Rw4iVicXxC4lJJCoLqrNdLBfqvt9JAvBndan\n" + "KlXNyoIMUktye1+fywLHfmU+k0tWMm2PacdD7V4aUpN3G1qQeIwt\n" + "-----END RSA PRIVATE KEY-----\n"; public static final String TR34_KRD_1_Cert_Pem = "-----BEGIN CERTIFICATE-----\n" + "MIIDcDCCAligAwIBAgIQbCpMOGMtYO46ksi7B0ziSTANBgkqhkiG9w0BAQsFADBT\n" + "MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xvdmVyMREwDwYDVQQLEwhkZXZpY2Vv\n" + "czEgMB4GA1UEAxMXVEVTVCBDbG92ZXIgVFIzNCBLUkQgQ0EwHhcNMjMwOTAxMjIw\n" + "NjUwWhcNMzgwODE0MjIwMDA5WjBSMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQ2xv\n" + "dmVyMREwDwYDVQQLEwhkZXZpY2VvczEfMB0GA1UEAxMWVEVTVCBDbG92ZXIgVFIz\n" + "NCBLUkQgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALhilgrs5YCt\n" + "DSiWa/Z/TX96qztN0dLlyh7rYimeBkEpEU4kJwWogRrt6CGIQ1+guSZLm4QtqWzn\n" + "bR72bDSJHLArnWi+Dx+9AHMK1AaZUrf75eC/yh5yV/sI0YFmnWp4DjV0AtGKgzDm\n" + "cjgQloIR2zrUrPXihXSUcwxJe0q/IqrMEdQ+morvZ2w+8Vlo1WszyvknhrCUWzKg\n" + "zf9DZ+9BG1fKREffS2SUruBHCFkQeXDFdP3d1RtgZznWGXQhwUXa5jkoFkR4jQYK\n" + "R8Lhj8v9YEbWcG8L7lOMkCZfRWeGzuQnjKRS9bx6D67gxvY2XJLbmfov4HNVkdxS\n" + "O68xEd8qI6UCAwEAAaNBMD8wDgYDVR0PAQH/BAQDAgeAMAwGA1UdEwEB/wQCMAAw\n" + "HwYDVR0jBBgwFoAU11VYe+bdyaYUH4MF8MFoJvdaOFkwDQYJKoZIhvcNAQELBQAD\n" + "ggEBAKdiYCU87sxKtldqs+4bNrSIXEwc/6XKCG2nCCToGNYOE2FApDWBZcOUcSEd\n" + "Lp0n7FEa/gLWVr5J/EOUkDp+5gAgmtbyvHptla8ThxVWPFHCXXbo4qlylfFwcXF1\n" + "OG8I+mwggUSh9DFoq27JUJApjaDcVyQ2Ywvdq0EcITYgrrZKZrqD7JYTEYmVXtKq\n" + "B4091HxtSM9vWophBudJDfK308x9fj+PM6AZqWRG7XCMShi3tVERiImTw0Pqn2/P\n" + "K0aEafxpvTRJh0kjsujX4HteBGXzLjjikfyjJKGz6Fyl5A8T9VAEFObqqZQ6Sa92\n" + "wMMs9Ow1xNvbr1cGImewoVhyBJU=\n" + "-----END CERTIFICATE-----"; public static final String TR34_KRD_1_PrivateKey_Pem = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEogIBAAKCAQEAuGKWCuzlgK0NKJZr9n9Nf3qrO03R0uXKHutiKZ4GQSkRTiQn\n" + "BaiBGu3oIYhDX6C5JkubhC2pbOdtHvZsNIkcsCudaL4PH70AcwrUBplSt/vl4L/K\n" + "HnJX+wjRgWadangONXQC0YqDMOZyOBCWghHbOtSs9eKFdJRzDEl7Sr8iqswR1D6a\n" + "iu9nbD7xWWjVazPK+SeGsJRbMqDN/0Nn70EbV8pER99LZJSu4EcIWRB5cMV0/d3V\n" + "G2BnOdYZdCHBRdrmOSgWRHiNBgpHwuGPy/1gRtZwbwvuU4yQJl9FZ4bO5CeMpFL1\n" + "vHoPruDG9jZcktuZ+i/gc1WR3FI7rzER3yojpQIDAQABAoIBADJnKLLl3TrWk2FD\n" + "9VFVrV6qrsIwXKo1DJJ1L8lGnFkVm9hrg4tFa71ryWfZMumiKtqwElwIi2bswGSV\n" + "YjDeRkxWL9phEgtQBB5umFURdo46urU8WEkIYsqJt5OS9HcVSHUOOHMFVSV56UEw\n" + "L6Rwsyga2QkCGg8rQWPbdmuRYi2j0j95IFvszn7kzQZ6hcoEdbhedYX85Ij4mgR7\n" + "ydeli6SAMQ8dRIbsOFhdf07DvA5st59lRTDeC/kyYMN6SZHRl7Vr9cvsTVawJb7v\n" + "v94Q3fRqzq9rB/JdHjVjjx+NM97sc7azZFFFVtrnlOG80k4lMIZLnjH0ZMpXrkY6\n" + "4Vv7p6UCgYEA5uLIa9+vopgpgTR4CUmqAcDh6EAzAOyIRTxag5c0i2Tz+x4ffc2Y\n" + "6s7Rs9x1b8ypr+z8GKmsjhEyxlToFEG0cZTBQzQEMsQ89jJbbLz8pSglS1hM3W4Y\n" + "zDGhiBtiJRpvuA3ZJN0No09cYDbH/y5ZyM6AAgwK1uD0vu5eTvoP83MCgYEAzHDy\n" + "8rVoHfF82pHrmzz8NRhf8SuDI+rwm+ThDnphteMXmJSz9ki8lljaF2T/mMsCHn1B\n" + "o+R5WTg1b/0+YGEH7OAjKNx+6K7BCZ1dA5S+dHtZjCvp2Bp3UL7FtK3dptQEL3t+\n" + "0SnSFBZ9lpXLj8dQNTwISVM8LD7vOBtVAOZftocCgYApFqzSPcGU7v1b6AmApaJi\n" + "o3/QhDRPcsihgaceCfeo4vNkeizih4cyKlI5bv9bQRHlpAgNH4z8z2S41P1kNXk2\n" + "SWHHYudoXXH34mhQxqUzgxx39yPeuCwjkqWLgkwKDFVbbON64vf9Wy82VCltaUND\n" + "MDSpqJj5OplzrRoNdgUGrwKBgEPHrsSJIFvNFHfiqRpuva9cxXJP2sqtudf1qigC\n" + "qyKCh/AuXPvqYZv3GVdoRNWDeNBi9sA/n3vVBuJ6M5QAl4ART5bcg7bhOV7WrV/i\n" + "kMJNowK2DHF5VNWQajvc6P/Gixyy9PijxOKkEj86qqKgkhcUMCsfTXPd6bHQXf5O\n" + "Yq1BAoGAaYsPFFv1uZJSDLb4kd5wW1o2AV2a5PhKqn71dCvYal6Dtm66jQnSvWSN\n" + "Jo7ewgPInB6FGUiHkG0uxCDaWxbqMoX0Gv6qhXP70TNg6PxTFZYQIcMOtjMWtfbo\n" + "JJbzKc5rgdHayNGWor9LWY7Y3gFASuItLuHLyI8n8Xx/zuaLxv8=\n" + "-----END RSA PRIVATE KEY-----"; private final X509Certificate rootCert; private final X509Certificate krdCaCert; private final X509Certificate kdhCaCert; private final X509Certificate kdhCert; private final PrivateKey krdCaPrivateKey; private final PrivateKey kdhCaPrivateKey; private final PrivateKey kdhPrivateKey; private CloverDevTr34KeyStoreData(String kdhCertPem, String kdhPrivateKeyPem) { kdhCert = Tr34CryptoUtils.parseCert(kdhCertPem); kdhPrivateKey = Tr34CryptoUtils.parsePrivateKey(kdhPrivateKeyPem); rootCert = Tr34CryptoUtils.parseCert(TR34_Root_Cert_Pem); kdhCaCert = Tr34CryptoUtils.parseCert(TR34_KDH_CA_Cert_Pem); krdCaCert = Tr34CryptoUtils.parseCert(TR34_KRD_CA_Cert_Pem); kdhCaPrivateKey = Tr34CryptoUtils.parsePrivateKey(TR34_KDH_CA_PrivateKey_Pem); krdCaPrivateKey = Tr34CryptoUtils.parsePrivateKey(TR34_KRD_CA_PrivateKey_Pem); } public static final Tr34KeyStoreData KDH_1 = new CloverDevTr34KeyStoreData(TR34_KDH_1_Cert_Pem, TR34_KDH_1_PrivateKey_Pem); public static final Tr34KeyStoreData KDH_2 = new CloverDevTr34KeyStoreData(TR34_KDH_2_Cert_Pem, TR34_KDH_2_PrivateKey_Pem); @Override public X509Certificate getRootCert() { return rootCert; } @Override public X509Certificate getKdhCaCert() { return kdhCaCert; } @Override public X509Certificate getKdhCert() { return kdhCert; } @Override public X509Certificate getKrdCaCert() { return krdCaCert; } @Override public Tr34ScdKeyStoreData getKdhKeyStoreData() { return new Tr34ScdKeyStoreData(kdhCert, kdhPrivateKey); } @Override public Tr34ScdKeyStoreData getKdhCaKeyStoreData() { return new Tr34ScdKeyStoreData(kdhCaCert, kdhCaPrivateKey); } @Override public Tr34ScdKeyStoreData getKrdCaKeyStoreData() { return new Tr34ScdKeyStoreData(krdCaCert, krdCaPrivateKey); } @Override
public List<Tr34KdhRevocation> getKdhRevocationList() {
1
2023-11-22 06:30:40+00:00
16k
Staffilon/KestraDataOrchestrator
IoT Simulator/src/main/java/net/acesinc/data/json/generator/JsonDataGenerator.java
[ { "identifier": "JSONConfigReader", "path": "IoT Simulator/src/main/java/net/acesinc/data/json/generator/config/JSONConfigReader.java", "snippet": "public class JSONConfigReader {\n private static final Logger log = LogManager.getLogger(JSONConfigReader.class);\n \n public static String getJsonC...
import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.pulsar.client.api.PulsarClientException; import org.eclipse.paho.client.mqttv3.MqttException; import org.json.simple.parser.ParseException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; 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.RestController; import net.acesinc.data.json.generator.config.JSONConfigReader; import net.acesinc.data.json.generator.config.SimulationConfig; import net.acesinc.data.json.generator.log.AzureIoTHubLogger; import net.acesinc.data.json.generator.log.EventLogger; import net.acesinc.data.json.generator.log.FileLogger; import net.acesinc.data.json.generator.log.HttpPostLogger; import net.acesinc.data.json.generator.log.KafkaLogger; import net.acesinc.data.json.generator.log.KinesisLogger; import net.acesinc.data.json.generator.log.Log4JLogger; import net.acesinc.data.json.generator.log.MqttLogger; import net.acesinc.data.json.generator.log.NatsLogger; import net.acesinc.data.json.generator.log.PulsarLogger; import net.acesinc.data.json.generator.log.TranquilityLogger; import net.acesinc.data.json.generator.log.WampLogger;
10,834
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package net.acesinc.data.json.generator; /** * * @author andrewserff */ @RestController public class JsonDataGenerator { @Autowired Environment environment; private static final Logger log = LogManager.getLogger(JsonDataGenerator.class); private SimulationRunner simRunner; private String simConfigFile; public JsonDataGenerator() { } public String getFilePath(String file) { String filePath = getSimulationContentPath() + "/" + file; return filePath; } public String getSimulationContentPath() { String folder = null; if (environment != null) environment.getProperty("myApp.folder", "conf"); else folder = System.getProperty("myApp.folder", "conf"); return folder; } public JsonDataGenerator setUpSimulation(String simConfigString) { simConfigFile = simConfigString; LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(); try { log.debug("Creating Simulation Runner using Simulation Config [ " + simConfigString + " ]"); SimulationConfig simConfig = getSimConfig(); List<EventLogger> loggers = new ArrayList<>(); for (Map<String, Object> elProps : simConfig.getProducers()) { String elType = (String) elProps.get("type"); switch (elType) { case "logger": { log.info("Adding Log4JLogger Producer"); loggers.add(new Log4JLogger()); break; } case "file": { log.info("Adding File Logger with properties: " + elProps); loggers.add(new FileLogger(queue, elProps)); break; } case "kafka": { log.info("Adding Kafka Producer with properties: " + elProps); loggers.add(new KafkaLogger(queue, elProps)); break; } case "tranquility": { log.info("Adding Tranqulity Logger with properties: " + elProps); loggers.add(new TranquilityLogger(queue, elProps)); break; } case "nats": { log.info("Adding NATS Logger with properties: " + elProps); loggers.add(new NatsLogger(queue, elProps)); break; } case "http-post": { log.info("Adding HTTP Post Logger with properties: " + elProps); try { loggers.add(new HttpPostLogger(queue, elProps)); } catch (NoSuchAlgorithmException ex) { log.error("http-post Logger unable to initialize", ex); } break; } case "mqtt": { log.info("Adding MQTT Logger with properties: " + elProps); try { loggers.add(new MqttLogger(queue, elProps)); } catch (MqttException ex) { log.error("mqtt Logger unable to initialize", ex); } break; } case "iothub": { log.info("Adding Azure IoT Hub Logger with properties: " + elProps); try { loggers.add(new AzureIoTHubLogger(queue, elProps)); } catch (URISyntaxException ex) { log.error("Azure IoT Hub Logger unable to initialize", ex); } break; } case "kinesis": { log.info("Adding Kinesis Logger with properties: " + elProps); try { loggers.add(new KinesisLogger(queue, elProps)); } catch (Exception ex) { log.error("Kinesis Logger unable to initialize", ex); } break; } case "pulsar": { log.info("Adding Pulsar Logger with properties: " + elProps); try {
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package net.acesinc.data.json.generator; /** * * @author andrewserff */ @RestController public class JsonDataGenerator { @Autowired Environment environment; private static final Logger log = LogManager.getLogger(JsonDataGenerator.class); private SimulationRunner simRunner; private String simConfigFile; public JsonDataGenerator() { } public String getFilePath(String file) { String filePath = getSimulationContentPath() + "/" + file; return filePath; } public String getSimulationContentPath() { String folder = null; if (environment != null) environment.getProperty("myApp.folder", "conf"); else folder = System.getProperty("myApp.folder", "conf"); return folder; } public JsonDataGenerator setUpSimulation(String simConfigString) { simConfigFile = simConfigString; LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(); try { log.debug("Creating Simulation Runner using Simulation Config [ " + simConfigString + " ]"); SimulationConfig simConfig = getSimConfig(); List<EventLogger> loggers = new ArrayList<>(); for (Map<String, Object> elProps : simConfig.getProducers()) { String elType = (String) elProps.get("type"); switch (elType) { case "logger": { log.info("Adding Log4JLogger Producer"); loggers.add(new Log4JLogger()); break; } case "file": { log.info("Adding File Logger with properties: " + elProps); loggers.add(new FileLogger(queue, elProps)); break; } case "kafka": { log.info("Adding Kafka Producer with properties: " + elProps); loggers.add(new KafkaLogger(queue, elProps)); break; } case "tranquility": { log.info("Adding Tranqulity Logger with properties: " + elProps); loggers.add(new TranquilityLogger(queue, elProps)); break; } case "nats": { log.info("Adding NATS Logger with properties: " + elProps); loggers.add(new NatsLogger(queue, elProps)); break; } case "http-post": { log.info("Adding HTTP Post Logger with properties: " + elProps); try { loggers.add(new HttpPostLogger(queue, elProps)); } catch (NoSuchAlgorithmException ex) { log.error("http-post Logger unable to initialize", ex); } break; } case "mqtt": { log.info("Adding MQTT Logger with properties: " + elProps); try { loggers.add(new MqttLogger(queue, elProps)); } catch (MqttException ex) { log.error("mqtt Logger unable to initialize", ex); } break; } case "iothub": { log.info("Adding Azure IoT Hub Logger with properties: " + elProps); try { loggers.add(new AzureIoTHubLogger(queue, elProps)); } catch (URISyntaxException ex) { log.error("Azure IoT Hub Logger unable to initialize", ex); } break; } case "kinesis": { log.info("Adding Kinesis Logger with properties: " + elProps); try { loggers.add(new KinesisLogger(queue, elProps)); } catch (Exception ex) { log.error("Kinesis Logger unable to initialize", ex); } break; } case "pulsar": { log.info("Adding Pulsar Logger with properties: " + elProps); try {
loggers.add(new PulsarLogger(elProps));
11
2023-11-26 10:57:17+00:00
16k
Invadermonky/JustEnoughMagiculture
src/main/java/com/invadermonky/justenoughmagiculture/integrations/jer/mods/JERAnimaniaExtra.java
[ { "identifier": "JERRenderPeafowlBase", "path": "src/main/java/com/invadermonky/justenoughmagiculture/client/render/entity/mods/animania/peafowl/JERRenderPeafowlBase.java", "snippet": "public class JERRenderPeafowlBase extends RenderPeafowlBase {\n public static final JERRenderPeafowlBase.Factory FAC...
import com.animania.addons.extra.common.entity.amphibians.EntityAmphibian; import com.animania.addons.extra.common.entity.amphibians.EntityDartFrogs; import com.animania.addons.extra.common.entity.amphibians.EntityFrogs; import com.animania.addons.extra.common.entity.amphibians.EntityToad; import com.animania.addons.extra.common.entity.peafowl.EntityAnimaniaPeacock; import com.animania.addons.extra.common.entity.peafowl.EntityPeachickBase; import com.animania.addons.extra.common.entity.peafowl.EntityPeafowlBase; import com.animania.addons.extra.common.entity.peafowl.PeafowlBlue.EntityPeacockBlue; import com.animania.addons.extra.common.entity.peafowl.PeafowlBlue.EntityPeafowlBlue; import com.animania.addons.extra.common.entity.peafowl.PeafowlCharcoal.EntityPeacockCharcoal; import com.animania.addons.extra.common.entity.peafowl.PeafowlCharcoal.EntityPeafowlCharcoal; import com.animania.addons.extra.common.entity.peafowl.PeafowlOpal.EntityPeacockOpal; import com.animania.addons.extra.common.entity.peafowl.PeafowlOpal.EntityPeafowlOpal; import com.animania.addons.extra.common.entity.peafowl.PeafowlPeach.EntityPeacockPeach; import com.animania.addons.extra.common.entity.peafowl.PeafowlPeach.EntityPeafowlPeach; import com.animania.addons.extra.common.entity.peafowl.PeafowlPurple.EntityPeacockPurple; import com.animania.addons.extra.common.entity.peafowl.PeafowlPurple.EntityPeafowlPurple; import com.animania.addons.extra.common.entity.peafowl.PeafowlTaupe.EntityPeacockTaupe; import com.animania.addons.extra.common.entity.peafowl.PeafowlTaupe.EntityPeafowlTaupe; import com.animania.addons.extra.common.entity.peafowl.PeafowlWhite.EntityPeacockWhite; import com.animania.addons.extra.common.entity.peafowl.PeafowlWhite.EntityPeafowlWhite; import com.animania.addons.extra.common.entity.rodents.*; import com.animania.addons.extra.common.entity.rodents.rabbits.EntityAnimaniaRabbit; import com.animania.addons.extra.common.entity.rodents.rabbits.EntityRabbitKitBase; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitChinchilla.EntityRabbitBuckChinchilla; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitChinchilla.EntityRabbitDoeChinchilla; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitCottonail.EntityRabbitBuckCottontail; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitCottonail.EntityRabbitDoeCottontail; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitDutch.EntityRabbitBuckDutch; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitDutch.EntityRabbitDoeDutch; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitHavana.EntityRabbitBuckHavana; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitHavana.EntityRabbitDoeHavana; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitJack.EntityRabbitBuckJack; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitJack.EntityRabbitDoeJack; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitLop.EntityRabbitBuckLop; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitLop.EntityRabbitDoeLop; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitNewZealand.EntityRabbitBuckNewZealand; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitNewZealand.EntityRabbitDoeNewZealand; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitRex.EntityRabbitBuckRex; import com.animania.addons.extra.common.entity.rodents.rabbits.RabbitRex.EntityRabbitDoeRex; import com.animania.addons.extra.config.ExtraConfig; import com.invadermonky.justenoughmagiculture.client.render.entity.mods.animania.peafowl.JERRenderPeafowlBase; import com.invadermonky.justenoughmagiculture.client.render.entity.mods.animania.rabbits.*; import com.invadermonky.justenoughmagiculture.configs.JEMConfig; import com.invadermonky.justenoughmagiculture.configs.mods.JEMConfigAnimaniaExtra; import com.invadermonky.justenoughmagiculture.integrations.jer.IJERIntegration; import com.invadermonky.justenoughmagiculture.integrations.jer.JERBase; import com.invadermonky.justenoughmagiculture.integrations.jer.conditionals.JEMLightLevel; import com.invadermonky.justenoughmagiculture.util.BiomeHelper; import com.invadermonky.justenoughmagiculture.util.ModIds; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.client.registry.RenderingRegistry;
13,857
private void registerRabbits() { if(jerConfig.enableRabbitChinchilla) { if(registerMales) { EntityRabbitBuckChinchilla buckChinchilla = new EntityRabbitBuckChinchilla(world); registerMob(buckChinchilla, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitChinchillaBiomeTypes), getRabbitLootTable(buckChinchilla)); } if(registerFemales) { EntityRabbitDoeChinchilla doeChinchilla = new EntityRabbitDoeChinchilla(world); registerMob(doeChinchilla, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitChinchillaBiomeTypes), getRabbitLootTable(doeChinchilla)); } } if(jerConfig.enableRabbitCottontail) { if(registerMales) { EntityRabbitBuckCottontail buckCottontail = new EntityRabbitBuckCottontail(world); registerMob(buckCottontail, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitCottontailBiomeTypes), getRabbitLootTable(buckCottontail)); } if(registerFemales) { EntityRabbitDoeCottontail doeCottontail = new EntityRabbitDoeCottontail(world); registerMob(doeCottontail, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitCottontailBiomeTypes), getRabbitLootTable(doeCottontail)); } } if(jerConfig.enableRabbitDutch) { if(registerMales) { EntityRabbitBuckDutch buckDutch = new EntityRabbitBuckDutch(world); registerMob(buckDutch, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitDutchBiomeTypes), getRabbitLootTable(buckDutch)); } if(registerFemales) { EntityRabbitDoeDutch doeDutch = new EntityRabbitDoeDutch(world); registerMob(doeDutch, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitDutchBiomeTypes), getRabbitLootTable(doeDutch)); } } if(jerConfig.enableRabbitHavana) { if(registerMales) { EntityRabbitBuckHavana buckHavana = new EntityRabbitBuckHavana(world); registerMob(buckHavana, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitHavanaBiomeTypes), getRabbitLootTable(buckHavana)); } if(registerFemales) { EntityRabbitDoeHavana doeHavana = new EntityRabbitDoeHavana(world); registerMob(doeHavana, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitHavanaBiomeTypes), getRabbitLootTable(doeHavana)); } } if(jerConfig.enableRabbitJack) { if(registerMales) { EntityRabbitBuckJack buckJack = new EntityRabbitBuckJack(world); registerMob(buckJack, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitJackBiomeTypes), getRabbitLootTable(buckJack)); } if(registerFemales) { EntityRabbitDoeJack doeJack = new EntityRabbitDoeJack(world); registerMob(doeJack, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitJackBiomeTypes), getRabbitLootTable(doeJack)); } } if(jerConfig.enableRabbitLop) { if(registerMales) { EntityRabbitBuckLop buckLop = new EntityRabbitBuckLop(world); registerMob(buckLop, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitLopBiomeTypes), getRabbitLootTable(buckLop)); } if(registerFemales) { EntityRabbitDoeLop doeLop = new EntityRabbitDoeLop(world); registerMob(doeLop, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitLopBiomeTypes), getRabbitLootTable(doeLop)); } } if(jerConfig.enableRabbitNewZealand) { if(registerMales) { EntityRabbitBuckNewZealand buckNewZealand = new EntityRabbitBuckNewZealand(world); registerMob(buckNewZealand, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitNewZealandBiomeTypes), getRabbitLootTable(buckNewZealand)); } if(registerFemales) { EntityRabbitDoeNewZealand doeNewZealand = new EntityRabbitDoeNewZealand(world); registerMob(doeNewZealand, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitNewZealandBiomeTypes), getRabbitLootTable(doeNewZealand)); } } if(jerConfig.enableRabbitRex) { if (registerMales) { EntityRabbitBuckRex buckRex = new EntityRabbitBuckRex(world); registerMob(buckRex, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitRexBiomeTypes), getRabbitLootTable(buckRex)); } if (registerFemales) { EntityRabbitDoeRex doeRex = new EntityRabbitDoeRex(world); registerMob(doeRex, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitRexBiomeTypes), getRabbitLootTable(doeRex)); } } } public void registerRenderOverrides() { RenderingRegistry.registerEntityRenderingHandler(EntityPeafowlBlue.class, JERRenderPeafowlBase.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityPeafowlCharcoal.class, JERRenderPeafowlBase.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityPeafowlOpal.class, JERRenderPeafowlBase.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityPeafowlPeach.class, JERRenderPeafowlBase.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityPeafowlPurple.class, JERRenderPeafowlBase.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityPeafowlTaupe.class, JERRenderPeafowlBase.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityPeafowlWhite.class, JERRenderPeafowlBase.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckChinchilla.class, JERRenderBuckChinchilla.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeChinchilla.class, JERRenderDoeChinchilla.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckCottontail.class, JERRenderBuckCottontail.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeCottontail.class, JERRenderDoeCottontail.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckDutch.class, JERRenderBuckDutch.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeDutch.class, JERRenderDoeDutch.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckHavana.class, JERRenderBuckHavana.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeHavana.class, JERRenderDoeHavana.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckJack.class, JERRenderBuckJack.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeJack.class, JERRenderDoeJack.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckNewZealand.class, JERRenderBuckNewZealand.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeNewZealand.class, JERRenderDoeNewZealand.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckRex.class, JERRenderBuckRex.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeRex.class, JERRenderDoeRex.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckLop.class, JERRenderBuckLop.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeLop.class, JERRenderDoeLop.FACTORY); } private ResourceLocation getAmphibianLootTable(EntityAmphibian entity) { if(entity instanceof EntityDartFrogs)
package com.invadermonky.justenoughmagiculture.integrations.jer.mods; public class JERAnimaniaExtra extends JERBase implements IJERIntegration { private static JERAnimaniaExtra instance; private static final JEMConfigAnimaniaExtra.JER.Animals jerConfig = JEMConfig.ANIMANIA_EXTRA.JUST_ENOUGH_RESOURCES.ANIMALS; private static final boolean registerMales = JEMConfig.ANIMANIA_EXTRA.JUST_ENOUGH_RESOURCES.registerMaleAnimals; private static final boolean registerFemales = JEMConfig.ANIMANIA_EXTRA.JUST_ENOUGH_RESOURCES.registerFemaleAnimals; private JERAnimaniaExtra() {} public JERAnimaniaExtra(boolean registerJERMobs) { if(registerJERMobs) registerModEntities(); } public static JERAnimaniaExtra getInstance() { return instance == null ? instance = new JERAnimaniaExtra() : instance; } @Override public void registerModEntities() { registerAmphibians(); registerHamsters(); registerHedgehogs(); registerFerrets(); registerPeafowl(); registerRabbits(); } private void registerAmphibians() { if (jerConfig.enableDartFrog) { EntityDartFrogs dartFrog = new EntityDartFrogs(world); registerMob(dartFrog, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.dartFrogBiomeTypes), getAmphibianLootTable(dartFrog)); registerRenderHook(dartFrog.getClass(), ((renderInfo, e) -> { GlStateManager.scale(2.0,2.0,2.0); GlStateManager.translate(0,-0.05,0); return renderInfo; })); } if (jerConfig.enableFrog) { EntityFrogs frog = new EntityFrogs(world); registerMob(frog, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.frogBiomeTypes), getAmphibianLootTable(frog)); registerRenderHook(frog.getClass(), ((renderInfo, e) -> { GlStateManager.scale(2.0,2.0,2.0); GlStateManager.translate(0,-0.05,0); return renderInfo; })); } if (jerConfig.enableToad) { EntityToad toad = new EntityToad(world); registerMob(toad, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.toadBiomeTypes), getAmphibianLootTable(toad)); registerRenderHook(toad.getClass(), ((renderInfo, e) -> { GlStateManager.scale(2.0,2.0,2.0); GlStateManager.translate(0,-0.05,0); return renderInfo; })); } } private void registerHamsters() { if (jerConfig.enableHamster) { registerMob(new EntityHamster(world), JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.hamsterBiomeTypes), getHamsterLootTable()); } } private void registerHedgehogs() { if(jerConfig.enableHedgehogAlbino) { registerMob(new EntityHedgehogAlbino(world), JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.hedgehogAlbinoBiomeTypes), getHedgehogLootTable()); } if(jerConfig.enableHedgehog) { registerMob(new EntityHedgehog(world), JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.hedgehogBiomeTypes), getHedgehogLootTable()); } } private void registerFerrets() { if(jerConfig.enableFerretGray) { registerMob(new EntityFerretGrey(world), JEMLightLevel.animal, BiomeHelper.getBiomeNamesForBiomes(ExtraConfig.settings.spawning_and_breeding.ferretGrayBiomeTypes), getFerretLootTable()); } if(jerConfig.enableFerretWhite) { registerMob(new EntityFerretWhite(world), JEMLightLevel.animal, BiomeHelper.getBiomeNamesForBiomes(ExtraConfig.settings.spawning_and_breeding.ferretWhiteBiomeTypes), getFerretLootTable()); } } private void registerPeafowl() { if(jerConfig.enablePeafowlBlue) { if(registerMales) { EntityPeacockBlue peacockBlue = new EntityPeacockBlue(world); registerMob(peacockBlue, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.peafowlBlueBiomeTypes), getPeafowlLootTable(peacockBlue)); } if(registerFemales) { EntityPeafowlBlue peafowlBlue = new EntityPeafowlBlue(world); registerMob(peafowlBlue, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.peafowlBlueBiomeTypes), getPeafowlLootTable(peafowlBlue)); } } if(jerConfig.enablePeafowlCharcoal) { if(registerMales) { EntityPeacockCharcoal peacockCharcoal = new EntityPeacockCharcoal(world); registerMob(peacockCharcoal, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.peafowlCharcoalBiomeTypes), getPeafowlLootTable(peacockCharcoal)); } if(registerFemales) { EntityPeafowlCharcoal peafowlCharcoal = new EntityPeafowlCharcoal(world); registerMob(peafowlCharcoal, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.peafowlCharcoalBiomeTypes), getPeafowlLootTable(peafowlCharcoal)); } } if(jerConfig.enablePeafowlOpal) { if(registerMales) { EntityPeacockOpal peacockOpal = new EntityPeacockOpal(world); registerMob(peacockOpal, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.peafowlOpalBiomeTypes), getPeafowlLootTable(peacockOpal)); } if(registerFemales) { EntityPeafowlOpal peafowlOpal = new EntityPeafowlOpal(world); registerMob(peafowlOpal, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.peafowlOpalBiomeTypes), getPeafowlLootTable(peafowlOpal)); } } if(jerConfig.enablePeafowlPeach) { if(registerMales) { EntityPeacockPeach peacockPeach = new EntityPeacockPeach(world); registerMob(peacockPeach, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.peafowlPeachBiomeTypes), getPeafowlLootTable(peacockPeach)); } if(registerFemales) { EntityPeafowlPeach peafowlPeach = new EntityPeafowlPeach(world); registerMob(peafowlPeach, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.peafowlPeachBiomeTypes), getPeafowlLootTable(peafowlPeach)); } } if(jerConfig.enablePeafowlPurple) { if(registerMales) { EntityPeacockPurple peacockPurple = new EntityPeacockPurple(world); registerMob(peacockPurple, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.peafowlPurpleBiomeTypes), getPeafowlLootTable(peacockPurple)); } if(registerFemales) { EntityPeafowlPurple peafowlPurple = new EntityPeafowlPurple(world); registerMob(peafowlPurple, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.peafowlPurpleBiomeTypes), getPeafowlLootTable(peafowlPurple)); } } if(jerConfig.enablePeafowlTaupe) { if(registerMales) { EntityPeacockTaupe peacockTaupe = new EntityPeacockTaupe(world); registerMob(peacockTaupe, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.peafowlTaupeBiomeTypes), getPeafowlLootTable(peacockTaupe)); } if(registerFemales) { EntityPeafowlTaupe peafowlTaupe = new EntityPeafowlTaupe(world); registerMob(peafowlTaupe, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.peafowlTaupeBiomeTypes), getPeafowlLootTable(peafowlTaupe)); } } if(jerConfig.enablePeafowlWhite) { if(registerMales) { EntityPeacockWhite peacockWhite = new EntityPeacockWhite(world); registerMob(peacockWhite, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.peafowlWhiteBiomeTypes), getPeafowlLootTable(peacockWhite)); } if(registerFemales) { EntityPeafowlWhite peafowlWhite = new EntityPeafowlWhite(world); registerMob(peafowlWhite, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.peafowlWhiteBiomeTypes), getPeafowlLootTable(peafowlWhite)); } } if(registerFemales) { registerRenderHook(EntityPeafowlBase.class, ((renderInfo, e) -> { GlStateManager.translate(0.24, 0.4, 0); return renderInfo; })); } } private void registerRabbits() { if(jerConfig.enableRabbitChinchilla) { if(registerMales) { EntityRabbitBuckChinchilla buckChinchilla = new EntityRabbitBuckChinchilla(world); registerMob(buckChinchilla, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitChinchillaBiomeTypes), getRabbitLootTable(buckChinchilla)); } if(registerFemales) { EntityRabbitDoeChinchilla doeChinchilla = new EntityRabbitDoeChinchilla(world); registerMob(doeChinchilla, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitChinchillaBiomeTypes), getRabbitLootTable(doeChinchilla)); } } if(jerConfig.enableRabbitCottontail) { if(registerMales) { EntityRabbitBuckCottontail buckCottontail = new EntityRabbitBuckCottontail(world); registerMob(buckCottontail, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitCottontailBiomeTypes), getRabbitLootTable(buckCottontail)); } if(registerFemales) { EntityRabbitDoeCottontail doeCottontail = new EntityRabbitDoeCottontail(world); registerMob(doeCottontail, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitCottontailBiomeTypes), getRabbitLootTable(doeCottontail)); } } if(jerConfig.enableRabbitDutch) { if(registerMales) { EntityRabbitBuckDutch buckDutch = new EntityRabbitBuckDutch(world); registerMob(buckDutch, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitDutchBiomeTypes), getRabbitLootTable(buckDutch)); } if(registerFemales) { EntityRabbitDoeDutch doeDutch = new EntityRabbitDoeDutch(world); registerMob(doeDutch, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitDutchBiomeTypes), getRabbitLootTable(doeDutch)); } } if(jerConfig.enableRabbitHavana) { if(registerMales) { EntityRabbitBuckHavana buckHavana = new EntityRabbitBuckHavana(world); registerMob(buckHavana, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitHavanaBiomeTypes), getRabbitLootTable(buckHavana)); } if(registerFemales) { EntityRabbitDoeHavana doeHavana = new EntityRabbitDoeHavana(world); registerMob(doeHavana, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitHavanaBiomeTypes), getRabbitLootTable(doeHavana)); } } if(jerConfig.enableRabbitJack) { if(registerMales) { EntityRabbitBuckJack buckJack = new EntityRabbitBuckJack(world); registerMob(buckJack, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitJackBiomeTypes), getRabbitLootTable(buckJack)); } if(registerFemales) { EntityRabbitDoeJack doeJack = new EntityRabbitDoeJack(world); registerMob(doeJack, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitJackBiomeTypes), getRabbitLootTable(doeJack)); } } if(jerConfig.enableRabbitLop) { if(registerMales) { EntityRabbitBuckLop buckLop = new EntityRabbitBuckLop(world); registerMob(buckLop, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitLopBiomeTypes), getRabbitLootTable(buckLop)); } if(registerFemales) { EntityRabbitDoeLop doeLop = new EntityRabbitDoeLop(world); registerMob(doeLop, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitLopBiomeTypes), getRabbitLootTable(doeLop)); } } if(jerConfig.enableRabbitNewZealand) { if(registerMales) { EntityRabbitBuckNewZealand buckNewZealand = new EntityRabbitBuckNewZealand(world); registerMob(buckNewZealand, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitNewZealandBiomeTypes), getRabbitLootTable(buckNewZealand)); } if(registerFemales) { EntityRabbitDoeNewZealand doeNewZealand = new EntityRabbitDoeNewZealand(world); registerMob(doeNewZealand, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitNewZealandBiomeTypes), getRabbitLootTable(doeNewZealand)); } } if(jerConfig.enableRabbitRex) { if (registerMales) { EntityRabbitBuckRex buckRex = new EntityRabbitBuckRex(world); registerMob(buckRex, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitRexBiomeTypes), getRabbitLootTable(buckRex)); } if (registerFemales) { EntityRabbitDoeRex doeRex = new EntityRabbitDoeRex(world); registerMob(doeRex, JEMLightLevel.animal, BiomeHelper.getBiomeNamesForTypes(ExtraConfig.settings.spawning_and_breeding.rabbitRexBiomeTypes), getRabbitLootTable(doeRex)); } } } public void registerRenderOverrides() { RenderingRegistry.registerEntityRenderingHandler(EntityPeafowlBlue.class, JERRenderPeafowlBase.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityPeafowlCharcoal.class, JERRenderPeafowlBase.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityPeafowlOpal.class, JERRenderPeafowlBase.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityPeafowlPeach.class, JERRenderPeafowlBase.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityPeafowlPurple.class, JERRenderPeafowlBase.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityPeafowlTaupe.class, JERRenderPeafowlBase.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityPeafowlWhite.class, JERRenderPeafowlBase.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckChinchilla.class, JERRenderBuckChinchilla.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeChinchilla.class, JERRenderDoeChinchilla.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckCottontail.class, JERRenderBuckCottontail.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeCottontail.class, JERRenderDoeCottontail.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckDutch.class, JERRenderBuckDutch.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeDutch.class, JERRenderDoeDutch.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckHavana.class, JERRenderBuckHavana.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeHavana.class, JERRenderDoeHavana.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckJack.class, JERRenderBuckJack.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeJack.class, JERRenderDoeJack.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckNewZealand.class, JERRenderBuckNewZealand.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeNewZealand.class, JERRenderDoeNewZealand.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckRex.class, JERRenderBuckRex.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeRex.class, JERRenderDoeRex.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitBuckLop.class, JERRenderBuckLop.FACTORY); RenderingRegistry.registerEntityRenderingHandler(EntityRabbitDoeLop.class, JERRenderDoeLop.FACTORY); } private ResourceLocation getAmphibianLootTable(EntityAmphibian entity) { if(entity instanceof EntityDartFrogs)
return new ResourceLocation("extra/" + ModIds.ANIMANIA.MOD_ID, "dart_frog");
7
2023-11-19 23:09:14+00:00
16k
Provismet/ProviHealth
src/main/java/com/provismet/provihealth/mixin/EntityRendererMixin.java
[ { "identifier": "Options", "path": "src/main/java/com/provismet/provihealth/config/Options.java", "snippet": "public class Options {\n public static final Vector3f WHITE = Vec3d.unpackRgb(0xFFFFFF).toVector3f();\n\n public static int maxHealthBarTicks = 40;\n\n public static List<String> blackl...
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 com.provismet.provihealth.config.Options; import com.provismet.provihealth.hud.TargetHealthBar; import com.provismet.provihealth.world.EntityHealthBar; import net.minecraft.client.MinecraftClient; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.render.entity.EntityRenderer; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.text.Text;
11,542
package com.provismet.provihealth.mixin; @Mixin(EntityRenderer.class) public abstract class EntityRendererMixin { @Inject(method="renderLabelIfPresent", at=@At("HEAD"), cancellable=true) private void cancelLabel (Entity entity, Text text, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, CallbackInfo info) {
package com.provismet.provihealth.mixin; @Mixin(EntityRenderer.class) public abstract class EntityRendererMixin { @Inject(method="renderLabelIfPresent", at=@At("HEAD"), cancellable=true) private void cancelLabel (Entity entity, Text text, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, CallbackInfo info) {
if (TargetHealthBar.disabledLabels || (Options.overrideLabels && entity instanceof LivingEntity living && Options.shouldRenderHealthFor(living))) info.cancel();
0
2023-11-26 02:46:37+00:00
16k
3arthqu4ke/phobot
src/main/java/me/earth/phobot/modules/combat/autocrystal/CrystalPlacingModule.java
[ { "identifier": "Phobot", "path": "src/main/java/me/earth/phobot/Phobot.java", "snippet": "@Getter\n@RequiredArgsConstructor\n@SuppressWarnings(\"ClassCanBeRecord\")\npublic class Phobot {\n public static final String NAME = \"Phobot\";\n\n private final PingBypass pingBypass;\n private final E...
import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; import me.earth.phobot.Phobot; import me.earth.phobot.damagecalc.CrystalPosition; import me.earth.phobot.ducks.IEntity; import me.earth.phobot.event.RenderEvent; import me.earth.phobot.modules.BlockPlacingModule; import me.earth.phobot.services.BlockPlacer; import me.earth.phobot.services.SurroundService; import me.earth.phobot.services.inventory.InventoryContext; import me.earth.phobot.util.PositionPool; import me.earth.phobot.util.ResetUtil; import me.earth.phobot.util.render.Renderer; import me.earth.phobot.util.time.StopWatch; import me.earth.phobot.util.time.TimeUtil; import me.earth.pingbypass.api.event.listeners.generic.Listener; import me.earth.pingbypass.api.gui.hud.DisplaysHudInfo; import me.earth.pingbypass.api.input.Bind; import me.earth.pingbypass.api.setting.Setting; import me.earth.pingbypass.api.traits.Nameable; import me.earth.pingbypass.commons.event.SafeListener; import me.earth.pingbypass.commons.event.loop.GameloopEvent; import me.earth.pingbypass.commons.event.network.PacketEvent; import me.earth.pingbypass.commons.event.network.PrePostSubscriber; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.MultiPlayerGameMode; import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; import net.minecraft.network.protocol.game.ClientboundAddEntityPacket; import net.minecraft.server.network.ServerGamePacketListenerImpl; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.boss.enderdragon.EndCrystal; import net.minecraft.world.entity.player.Player; import net.minecraft.world.phys.AABB; import org.apache.commons.lang3.mutable.MutableObject; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
13,443
package me.earth.phobot.modules.combat.autocrystal; // TODO: AntiOutPlace, attempt to schedule crystal placement in a way that we can get crystals in // crystal spawns -> schedule placement to arrive after player around us broke one @Slf4j @Getter @Accessors(fluent = true)
package me.earth.phobot.modules.combat.autocrystal; // TODO: AntiOutPlace, attempt to schedule crystal placement in a way that we can get crystals in // crystal spawns -> schedule placement to arrive after player around us broke one @Slf4j @Getter @Accessors(fluent = true)
public class CrystalPlacingModule extends BlockPlacingModule implements DisplaysHudInfo {
4
2023-12-22 14:32:16+00:00
16k
ArmanKhanDev/FakepixelDungeonHelper
build/sources/main/java/io/github/quantizr/core/Waypoints.java
[ { "identifier": "DungeonRooms", "path": "build/sources/main/java/io/github/quantizr/DungeonRooms.java", "snippet": "@Mod(modid = DungeonRooms.MODID, version = DungeonRooms.VERSION)\npublic class DungeonRooms\n{\n public static final String MODID = \"FDH\";\n public static final String VERSION = \"...
import com.google.gson.JsonArray; import com.google.gson.JsonObject; import io.github.quantizr.DungeonRooms; import io.github.quantizr.events.PacketEvent; import io.github.quantizr.utils.Utils; import io.github.quantizr.utils.WaypointUtils; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; import net.minecraft.network.play.server.S0DPacketCollectItem; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.StringUtils; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import java.awt.*; import java.util.*; import java.util.List;
13,349
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.core; public class Waypoints { public static boolean enabled = true; public static boolean showEntrance = true; public static boolean showSuperboom = true; public static boolean showSecrets = true; public static boolean showFairySouls = true; public static boolean sneakToDisable = true; public static boolean disableWhenAllFound = true; public static boolean allFound = false; public static boolean showWaypointText = true; public static boolean showBoundingBox = true; public static boolean showBeacon = true; public static int secretNum = 0; public static int completedSecrets = 0; public static Map<String, List<Boolean>> allSecretsMap = new HashMap<>(); public static List<Boolean> secretsList = new ArrayList<>(Arrays.asList(new Boolean[9])); static long lastSneakTime = 0; @SubscribeEvent public void onWorldRender(RenderWorldLastEvent event) { if (!enabled) return; String roomName = AutoRoom.lastRoomName; if (AutoRoom.lastRoomJson != null && roomName != null && secretsList != null) { secretNum = AutoRoom.lastRoomJson.get("secrets").getAsInt(); if (DungeonRooms.waypointsJson.get(roomName) != null) { JsonArray secretsArray = DungeonRooms.waypointsJson.get(roomName).getAsJsonArray(); int arraySize = secretsArray.size(); for(int i = 0; i < arraySize; i++) { JsonObject secretsObject = secretsArray.get(i).getAsJsonObject(); boolean display = true; for(int j = 1; j <= secretNum; j++) { if (!secretsList.get(j-1)) { if (secretsObject.get("secretName").getAsString().contains(String.valueOf(j))) { display = false; break; } } } if (!display) continue; if (disableWhenAllFound && allFound && !secretsObject.get("category").getAsString().equals("fairysoul")) continue; Color color; switch (secretsObject.get("category").getAsString()) { case "entrance": if (!showEntrance) continue; color = new Color(0, 255, 0); break; case "superboom": if (!showSuperboom) continue; color = new Color(255, 0, 0); break; case "chest": if (!showSecrets) continue; color = new Color(2, 213, 250); break; case "item": if (!showSecrets) continue; color = new Color(2, 64, 250); break; case "bat": if (!showSecrets) continue; color = new Color(142, 66, 0); break; case "wither": if (!showSecrets) continue; color = new Color(30, 30, 30); break; case "lever": if (!showSecrets) continue; color = new Color(250, 217, 2); break; case "fairysoul": if (!showFairySouls) continue; color = new Color(255, 85, 255); break; default: color = new Color(190, 255, 252); } Entity viewer = Minecraft.getMinecraft().getRenderViewEntity(); double viewerX = viewer.lastTickPosX + (viewer.posX - viewer.lastTickPosX) * event.partialTicks; double viewerY = viewer.lastTickPosY + (viewer.posY - viewer.lastTickPosY) * event.partialTicks; double viewerZ = viewer.lastTickPosZ + (viewer.posZ - viewer.lastTickPosZ) * event.partialTicks;
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.core; public class Waypoints { public static boolean enabled = true; public static boolean showEntrance = true; public static boolean showSuperboom = true; public static boolean showSecrets = true; public static boolean showFairySouls = true; public static boolean sneakToDisable = true; public static boolean disableWhenAllFound = true; public static boolean allFound = false; public static boolean showWaypointText = true; public static boolean showBoundingBox = true; public static boolean showBeacon = true; public static int secretNum = 0; public static int completedSecrets = 0; public static Map<String, List<Boolean>> allSecretsMap = new HashMap<>(); public static List<Boolean> secretsList = new ArrayList<>(Arrays.asList(new Boolean[9])); static long lastSneakTime = 0; @SubscribeEvent public void onWorldRender(RenderWorldLastEvent event) { if (!enabled) return; String roomName = AutoRoom.lastRoomName; if (AutoRoom.lastRoomJson != null && roomName != null && secretsList != null) { secretNum = AutoRoom.lastRoomJson.get("secrets").getAsInt(); if (DungeonRooms.waypointsJson.get(roomName) != null) { JsonArray secretsArray = DungeonRooms.waypointsJson.get(roomName).getAsJsonArray(); int arraySize = secretsArray.size(); for(int i = 0; i < arraySize; i++) { JsonObject secretsObject = secretsArray.get(i).getAsJsonObject(); boolean display = true; for(int j = 1; j <= secretNum; j++) { if (!secretsList.get(j-1)) { if (secretsObject.get("secretName").getAsString().contains(String.valueOf(j))) { display = false; break; } } } if (!display) continue; if (disableWhenAllFound && allFound && !secretsObject.get("category").getAsString().equals("fairysoul")) continue; Color color; switch (secretsObject.get("category").getAsString()) { case "entrance": if (!showEntrance) continue; color = new Color(0, 255, 0); break; case "superboom": if (!showSuperboom) continue; color = new Color(255, 0, 0); break; case "chest": if (!showSecrets) continue; color = new Color(2, 213, 250); break; case "item": if (!showSecrets) continue; color = new Color(2, 64, 250); break; case "bat": if (!showSecrets) continue; color = new Color(142, 66, 0); break; case "wither": if (!showSecrets) continue; color = new Color(30, 30, 30); break; case "lever": if (!showSecrets) continue; color = new Color(250, 217, 2); break; case "fairysoul": if (!showFairySouls) continue; color = new Color(255, 85, 255); break; default: color = new Color(190, 255, 252); } Entity viewer = Minecraft.getMinecraft().getRenderViewEntity(); double viewerX = viewer.lastTickPosX + (viewer.posX - viewer.lastTickPosX) * event.partialTicks; double viewerY = viewer.lastTickPosY + (viewer.posY - viewer.lastTickPosY) * event.partialTicks; double viewerZ = viewer.lastTickPosZ + (viewer.posZ - viewer.lastTickPosZ) * event.partialTicks;
BlockPos pos = Utils.relativeToActual(new BlockPos(secretsObject.get("x").getAsInt(), secretsObject.get("y").getAsInt(), secretsObject.get("z").getAsInt()));
2
2023-12-22 04:44:39+00:00
16k
lonelytransistor/LauncherAndroidTV
app/src/main/java/net/lonelytransistor/launcher/entrypoints/LauncherActivity.java
[ { "identifier": "BadgeCard", "path": "app/src/main/java/net/lonelytransistor/launcher/BadgeCard.java", "snippet": "public class BadgeCard extends Card {\n public String title;\n public Object badgeImage;\n public String badgeText;\n public Object mainImage;\n public Object statusIcon;\n ...
import android.app.AppOpsManager; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.os.PowerManager; import android.provider.Settings; import android.util.Log; import android.view.View; import android.view.ViewTreeObserver; import androidx.annotation.NonNull; import net.lonelytransistor.launcher.BadgeCard; import net.lonelytransistor.launcher.Card; import net.lonelytransistor.launcher.LauncherBar; import net.lonelytransistor.launcher.MovieCard; import net.lonelytransistor.launcher.R; import net.lonelytransistor.launcher.WidgetBar; import net.lonelytransistor.launcher.generics.GenericActivity;
11,632
package net.lonelytransistor.launcher.entrypoints; public class LauncherActivity extends GenericActivity implements ViewTreeObserver.OnGlobalFocusChangeListener { private static final String TAG = "LauncherActivity"; private static final String PERMISSION_READ_TV_LISTINGS = "android.permission.READ_TV_LISTINGS"; @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); for (int res : grantResults) { if (res != PackageManager.PERMISSION_GRANTED) { finish(); return; } } start(); } private boolean isUsageAccessGranted() { try { PackageManager packageManager = getPackageManager(); ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0); AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE); int mode = appOpsManager.unsafeCheckOpRaw(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName); return (mode == AppOpsManager.MODE_ALLOWED); } catch (PackageManager.NameNotFoundException e) { return false; } } private boolean isIgnoringBatteryOptimizations() { PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); return powerManager.isIgnoringBatteryOptimizations(getPackageName()); } private void start() { if (checkCallingOrSelfPermission(PERMISSION_READ_TV_LISTINGS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{PERMISSION_READ_TV_LISTINGS}, 0); } else { if (!isUsageAccessGranted()) { Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); intent.putExtra(Intent.EXTRA_PACKAGE_NAME, getPackageName()); startActivity(intent); } else if (!Settings.canDrawOverlays(this)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } else /*if (!isIgnoringBatteryOptimizations()) { Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS, Uri.parse("package:" + getPackageName())); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } else*/ { BackgroundService.showLauncher(this); finish(); } } } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); widgetBar.onStop(); } WidgetBar widgetBar; @Override public void onGlobalFocusChanged(View oldFocus, View newFocus) { Log.i(TAG, "Focus: " + newFocus); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the global focus change listener //getWindow().getDecorView().getRootView().getViewTreeObserver().addOnGlobalFocusChangeListener(this); if (true) { start(); } else if (true) { setContentView(R.layout.activity_main);
package net.lonelytransistor.launcher.entrypoints; public class LauncherActivity extends GenericActivity implements ViewTreeObserver.OnGlobalFocusChangeListener { private static final String TAG = "LauncherActivity"; private static final String PERMISSION_READ_TV_LISTINGS = "android.permission.READ_TV_LISTINGS"; @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); for (int res : grantResults) { if (res != PackageManager.PERMISSION_GRANTED) { finish(); return; } } start(); } private boolean isUsageAccessGranted() { try { PackageManager packageManager = getPackageManager(); ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0); AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE); int mode = appOpsManager.unsafeCheckOpRaw(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName); return (mode == AppOpsManager.MODE_ALLOWED); } catch (PackageManager.NameNotFoundException e) { return false; } } private boolean isIgnoringBatteryOptimizations() { PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); return powerManager.isIgnoringBatteryOptimizations(getPackageName()); } private void start() { if (checkCallingOrSelfPermission(PERMISSION_READ_TV_LISTINGS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{PERMISSION_READ_TV_LISTINGS}, 0); } else { if (!isUsageAccessGranted()) { Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); intent.putExtra(Intent.EXTRA_PACKAGE_NAME, getPackageName()); startActivity(intent); } else if (!Settings.canDrawOverlays(this)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } else /*if (!isIgnoringBatteryOptimizations()) { Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS, Uri.parse("package:" + getPackageName())); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } else*/ { BackgroundService.showLauncher(this); finish(); } } } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); widgetBar.onStop(); } WidgetBar widgetBar; @Override public void onGlobalFocusChanged(View oldFocus, View newFocus) { Log.i(TAG, "Focus: " + newFocus); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the global focus change listener //getWindow().getDecorView().getRootView().getViewTreeObserver().addOnGlobalFocusChangeListener(this); if (true) { start(); } else if (true) { setContentView(R.layout.activity_main);
LauncherBar bar = findViewById(R.id.launcherBar);
2
2023-12-28 18:24:12+00:00
16k
RoderickQiu/SUSTech_CSE_Projects
CS109_2022_Fall/Chess/view/ChessGameFrame.java
[ { "identifier": "Main", "path": "CS109_2022_Fall/Chess/Main.java", "snippet": "public class Main {\r\n private static ChessGameFrame gameFrame = null;\r\n private static StartFrame startFrame = null;\r\n public static Font titleFont, sansFont, serifFont;\r\n public static String theme = \"像素...
import Chess.Main; import Chess.chessComponent.EatenComponent; import Chess.chessComponent.SquareComponent; import Chess.controller.GameController; import Chess.model.ChessColor; import Chess.model.ChessboardPoint; import Chess.utils.FileUtils; import Chess.utils.GeneralUtils; import Chess.utils.ImageUtils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import static Chess.Main.*; import static Chess.utils.GeneralUtils.log; import static Chess.utils.ImageUtils.changeImageSize;
12,010
while (start + len < longString.length()) { while (true) { len++; if (start + len > longString.length()) break; if (fontMetrics.charsWidth(chars, start, len) > jLabel.getWidth()) { break; } } builder.append(chars, start, len - 1).append("<br/>"); start = start + len - 1; len = 0; } builder.append(chars, start, longString.length() - start); builder.append("</html>"); jLabel.setText(builder.toString()); } private void addScoreLabel() { JLabel jLabel = new JLabel("红 - 黑"); jLabel.setLocation((int) (WIDTH * 11.14 / 15 + 5), (int) (HEIGHT / 13 * 9.3)); jLabel.setSize(200, 60); jLabel.setFont(sansFont.deriveFont(Font.BOLD, 23)); jLabel.setForeground(ChessColor.BLACK.getColor()); add(jLabel); scoreLabel = new JLabel("00 - 00"); scoreLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 9.85)); scoreLabel.setSize(200, 60); scoreLabel.setFont(sansFont.deriveFont(Font.BOLD, 23)); scoreLabel.setForeground(ChessColor.BLACK.getColor()); add(scoreLabel); } public static JLabel getStatusLabel() { return statusLabel; } public static JLabel getScoreLabel() { return scoreLabel; } public static JLabel getBlackEatenLabel() { return blackEatenLabel; } public static JLabel getRedEatenLabel() { return redEatenLabel; } /** * 在游戏窗体中增加一个按钮,如果按下的话就会显示Hello, world! */ private void addBackButton() { JButton button = new JButton("返回"); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); button.addActionListener((e) -> { Main.backStart(); Main.playNotifyMusic("click"); }); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13); button.setSize(80, 40); StartFrame.setButtonBg(button, 80, 40); add(button); } private void addLoadButton() { JButton button = new JButton("存档"); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 45); button.setSize(80, 40); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); StartFrame.setButtonBg(button, 80, 40); add(button); button.addActionListener(e -> { System.out.println("Click load"); Main.playNotifyMusic("click"); int option = JOptionPane.showOptionDialog(this, "选择是要保存存档还是导入存档?", "请选择", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{"保存存档", "导入存档"}, "导入存档"); if (option == 1) { String path = JOptionPane.showInputDialog(this, "在这里输入存档的文件绝对路径"); gameController.loadGSon(path); } else { gameController.toGSon(); } }); } private void addRefreshButton() { JButton button = new JButton("重置"); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 90); button.setSize(80, 40); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); StartFrame.setButtonBg(button, 80, 40); add(button); button.addActionListener(e -> { Main.playNotifyMusic("click"); Main.refreshGame(); }); } private void addThemeButton() { JButton button = new JButton("主题"); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 135); button.setSize(80, 40); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); StartFrame.setButtonBg(button, 80, 40); add(button); button.addActionListener(e -> { System.out.println("Click theme"); Main.playNotifyMusic("click"); String path = JOptionPane.showInputDialog(this, "在下方输入主题的名字以选择主题(可选主题有像素、典雅、激情):"); if (path == null) { JOptionPane.showMessageDialog(this, "不能输入空内容!"); } else if (path.equals(Main.themeList[0]) || path.equals(Main.themeList[1]) || path.equals(Main.themeList[2])) {
package Chess.view; /** * 这个类表示游戏窗体,窗体上包含: * 1 Chessboard: 棋盘 * 2 JLabel: 标签 * 3 JButton: 按钮 */ public class ChessGameFrame extends JFrame { private final int WIDTH; private final int HEIGHT; public final int CHESSBOARD_SIZE; private GameController gameController; private static JLabel statusLabel, scoreLabel, blackEatenLabel, redEatenLabel; private static JPanel eatenPanel; public static String redEatenList, blackEatenList; private Gson gson = new Gson(); private static EatenComponent[][] eatenComponents = new EatenComponent[2][7]; private static String[][] nameList = { {"將", "士", "象", "車", "馬", "卒", "砲"}, {"帥", "仕", "相", "俥", "傌", "兵", "炮"}}; private static int redEaten[] = {0, 0, 0, 0, 0, 0, 0}, blackEaten[] = {0, 0, 0, 0, 0, 0, 0}; public ChessGameFrame(int width, int height, int mode) { setTitle("翻翻棋~"); this.WIDTH = width; this.HEIGHT = height; this.CHESSBOARD_SIZE = HEIGHT * 4 / 5; redEatenList = ""; blackEatenList = ""; setResizable(false); setSize(WIDTH, HEIGHT); setLocationRelativeTo(null); // Center the window. getContentPane().setBackground(Color.WHITE); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(null); addChessboard(mode); addStatusLabel(); addScoreLabel(); addBlackEatenLabel(); addRedEatenLabel(); addEatenList(); addBackButton(); addLoadButton(); addRefreshButton(); addThemeButton(); addBg(); } /** * 在游戏窗体中添加棋盘 */ private void addChessboard(int mode) { Chessboard chessboard = new Chessboard(CHESSBOARD_SIZE / 2 + 100, CHESSBOARD_SIZE, mode); gameController = new GameController(chessboard); chessboard.setLocation(HEIGHT / 13, HEIGHT / 13); add(chessboard); } private void addEatenList() { eatenPanel = new JPanel(); eatenPanel.setBounds(WIDTH * 11 / 15 + 2, (int) (HEIGHT / 13 * 6.04), 75, 185); GridLayout gridLayout = new GridLayout(7, 2); eatenPanel.setLayout(gridLayout); eatenPanel.setBackground(Color.WHITE); eatenPanel.setOpaque(false);//workaround keep opaque after repainted add(eatenPanel); setEatenList(); } private static void setEatenList() { parseEatenLists(); for (int j = 0; j < 7; j++) { for (int i = 0; i < 2; i++) { if (eatenComponents[i][j] != null) eatenPanel.remove(eatenComponents[i][j]); eatenComponents[i][j] = new EatenComponent(nameList[i][j], (i == 0) ? blackEaten[j] : redEaten[j], i, j, (i == 0) ? "b" : "r"); eatenPanel.add(eatenComponents[i][j]); } } } private static void parseEatenLists() { Arrays.fill(redEaten, 0); Arrays.fill(blackEaten, 0); String[] red = redEatenList.split(" "), black = blackEatenList.split(" "); for (String s : red) { switch (s) { case "帥" -> redEaten[0]++; case "仕" -> redEaten[1]++; case "相" -> redEaten[2]++; case "俥" -> redEaten[3]++; case "傌" -> redEaten[4]++; case "兵" -> redEaten[5]++; case "炮" -> redEaten[6]++; } } for (String s : black) { switch (s) { case "將" -> blackEaten[0]++; case "士" -> blackEaten[1]++; case "象" -> blackEaten[2]++; case "車" -> blackEaten[3]++; case "馬" -> blackEaten[4]++; case "卒" -> blackEaten[5]++; case "砲" -> blackEaten[6]++; } } } /** * 在游戏窗体中添加标签 */ private void addStatusLabel() { statusLabel = new JLabel("红走棋"); statusLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 10.65)); statusLabel.setSize(200, 60); statusLabel.setFont(sansFont.deriveFont(Font.BOLD, 23)); statusLabel.setForeground(Main.getThemeColor("indicatorRed")); add(statusLabel); } private void addRedEatenLabel() { redEatenLabel = new JLabel(); redEatenLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 5.05)); redEatenLabel.setSize(100, 200); redEatenLabel.setFont(sansFont.deriveFont(Font.BOLD, 14)); redEatenLabel.setForeground(Main.getThemeColor("indicatorBlack")); JlabelSetText(redEatenLabel, "红被吃:----"); redEatenLabel.setFont(sansFont.deriveFont(Font.BOLD, 14)); //add(redEatenLabel); } private void addBlackEatenLabel() { blackEatenLabel = new JLabel(); blackEatenLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 6.65)); blackEatenLabel.setSize(100, 200); blackEatenLabel.setFont(sansFont.deriveFont(Font.BOLD, 14)); blackEatenLabel.setForeground(Main.getThemeColor("indicatorBlack")); JlabelSetText(blackEatenLabel, "黑被吃:----"); blackEatenLabel.setFont(sansFont.deriveFont(Font.BOLD, 14)); //add(blackEatenLabel); } public static void appendBlackEatenLabel(String str) { blackEatenList += " " + str; setEatenList(); //JlabelSetText(blackEatenLabel, "黑被吃:<br/>" + blackEatenList); } public static void appendRedEatenLabel(String str) { redEatenList += " " + str; setEatenList(); //JlabelSetText(redEatenLabel, "红被吃:<br/>" + redEatenList); } public static void popBlackEatenLabel() { blackEatenList = blackEatenList.substring(0, blackEatenList.lastIndexOf(" ")); setEatenList(); /*if (blackEatenList.strip().length() > 0) JlabelSetText(blackEatenLabel, "黑被吃:<br/>" + blackEatenList); else JlabelSetText(blackEatenLabel, "黑被吃:----");*/ } public static void popRedEatenLabel() { redEatenList = redEatenList.substring(0, redEatenList.lastIndexOf(" ")); setEatenList(); /*if (redEatenList.strip().length() > 0) JlabelSetText(redEatenLabel, "红被吃:<br/>" + redEatenList); else JlabelSetText(redEatenLabel, "红被吃:----");*/ } public static void setBlackEatenLabel(String str) { blackEatenList = str; setEatenList(); //JlabelSetText(blackEatenLabel, "黑被吃:<br/>" + blackEatenList); } public static void setRedEatenLabel(String str) { redEatenList = str; setEatenList(); //JlabelSetText(redEatenLabel, "红被吃:<br/>" + redEatenList); } private static void JlabelSetText(JLabel jLabel, String longString) { StringBuilder builder = new StringBuilder("<html>" + longString.substring(0, 7)); char[] chars = longString.toCharArray(); FontMetrics fontMetrics = jLabel.getFontMetrics(jLabel.getFont()); int start = 8; int len = 0; while (start + len < longString.length()) { while (true) { len++; if (start + len > longString.length()) break; if (fontMetrics.charsWidth(chars, start, len) > jLabel.getWidth()) { break; } } builder.append(chars, start, len - 1).append("<br/>"); start = start + len - 1; len = 0; } builder.append(chars, start, longString.length() - start); builder.append("</html>"); jLabel.setText(builder.toString()); } private void addScoreLabel() { JLabel jLabel = new JLabel("红 - 黑"); jLabel.setLocation((int) (WIDTH * 11.14 / 15 + 5), (int) (HEIGHT / 13 * 9.3)); jLabel.setSize(200, 60); jLabel.setFont(sansFont.deriveFont(Font.BOLD, 23)); jLabel.setForeground(ChessColor.BLACK.getColor()); add(jLabel); scoreLabel = new JLabel("00 - 00"); scoreLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 9.85)); scoreLabel.setSize(200, 60); scoreLabel.setFont(sansFont.deriveFont(Font.BOLD, 23)); scoreLabel.setForeground(ChessColor.BLACK.getColor()); add(scoreLabel); } public static JLabel getStatusLabel() { return statusLabel; } public static JLabel getScoreLabel() { return scoreLabel; } public static JLabel getBlackEatenLabel() { return blackEatenLabel; } public static JLabel getRedEatenLabel() { return redEatenLabel; } /** * 在游戏窗体中增加一个按钮,如果按下的话就会显示Hello, world! */ private void addBackButton() { JButton button = new JButton("返回"); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); button.addActionListener((e) -> { Main.backStart(); Main.playNotifyMusic("click"); }); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13); button.setSize(80, 40); StartFrame.setButtonBg(button, 80, 40); add(button); } private void addLoadButton() { JButton button = new JButton("存档"); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 45); button.setSize(80, 40); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); StartFrame.setButtonBg(button, 80, 40); add(button); button.addActionListener(e -> { System.out.println("Click load"); Main.playNotifyMusic("click"); int option = JOptionPane.showOptionDialog(this, "选择是要保存存档还是导入存档?", "请选择", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{"保存存档", "导入存档"}, "导入存档"); if (option == 1) { String path = JOptionPane.showInputDialog(this, "在这里输入存档的文件绝对路径"); gameController.loadGSon(path); } else { gameController.toGSon(); } }); } private void addRefreshButton() { JButton button = new JButton("重置"); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 90); button.setSize(80, 40); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); StartFrame.setButtonBg(button, 80, 40); add(button); button.addActionListener(e -> { Main.playNotifyMusic("click"); Main.refreshGame(); }); } private void addThemeButton() { JButton button = new JButton("主题"); button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 135); button.setSize(80, 40); button.setFont(sansFont.deriveFont(Font.BOLD, 17)); StartFrame.setButtonBg(button, 80, 40); add(button); button.addActionListener(e -> { System.out.println("Click theme"); Main.playNotifyMusic("click"); String path = JOptionPane.showInputDialog(this, "在下方输入主题的名字以选择主题(可选主题有像素、典雅、激情):"); if (path == null) { JOptionPane.showMessageDialog(this, "不能输入空内容!"); } else if (path.equals(Main.themeList[0]) || path.equals(Main.themeList[1]) || path.equals(Main.themeList[2])) {
log("SELECT " + path);
10
2023-12-31 05:50:13+00:00
16k
psobiech/opengr8on
client/src/main/java/pl/psobiech/opengr8on/client/Main.java
[ { "identifier": "CLUDevice", "path": "lib/src/main/java/pl/psobiech/opengr8on/client/device/CLUDevice.java", "snippet": "public class CLUDevice {\n private final String name;\n\n private final Long serialNumber;\n\n private final String macAddress;\n\n private Inet4Address address;\n\n pr...
import java.io.IOException; import java.net.Inet4Address; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.util.Map; import java.util.Optional; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.psobiech.opengr8on.client.device.CLUDevice; import pl.psobiech.opengr8on.client.device.CLUDeviceConfig; import pl.psobiech.opengr8on.client.device.CipherTypeEnum; import pl.psobiech.opengr8on.exceptions.UnexpectedException; import pl.psobiech.opengr8on.util.FileUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil.NetworkInterfaceDto; import pl.psobiech.opengr8on.util.ObjectMapperFactory; import pl.psobiech.opengr8on.util.RandomUtil; import pl.psobiech.opengr8on.util.Util; import pl.psobiech.opengr8on.xml.interfaces.CLU; import pl.psobiech.opengr8on.xml.interfaces.InterfaceRegistry; import pl.psobiech.opengr8on.xml.omp.OmpReader;
14,086
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client; public class Main { private static final Duration DEFAULT_LONG_TIMEOUT = Duration.ofMillis(30_000); private static final int TIMEOUT = 4_000; private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); private static final Map<Long, byte[]> PRIVATE_KEYS = Map.of( 0x0L, "00000000".getBytes() ); private static final Inet4Address MIN_IP = IPv4AddressUtil.parseIPv4("10.72.144.1"); private Main() { // NOP } public static void main(String[] args) throws Exception { final CommandLine commandLine = new DefaultParser().parse(CLIParameters.OPTIONS, args); if (commandLine.hasOption(CLIParameters.HELP_OPTION)) { new HelpFormatter() .printHelp("java -jar client.jar", CLIParameters.OPTIONS); System.exit(0); } // final NetworkInterfaceDto networkInterface = CLIParameters.getNetworkInterface(commandLine); LOGGER.debug("Using network interface: {}", networkInterface); if (commandLine.hasOption(CLIParameters.DISCOVER_OPTION)) { final InterfaceRegistry interfaceRegistry = CLIParameters.getInterfaceRegistry(commandLine); final CipherKey projectCipherKey = CLIParameters.getProjectCipherKey(commandLine) .orElseGet(() -> { final CipherKey cipherKey = new CipherKey(RandomUtil.bytes(16), RandomUtil.bytes(16)); LOGGER.debug("Generated random project key: {}", cipherKey); return cipherKey; }); final Integer cluLimit = Optional.ofNullable(commandLine.getOptionValue(CLIParameters.CLU_LIMIT_PATH_OPTION)) .map(Integer::parseInt) .orElse(1); discover(networkInterface, projectCipherKey, cluLimit, interfaceRegistry); return; } final Inet4Address ipAddress = CLIParameters.getRemoteIPAddress(commandLine); if (commandLine.hasOption(CLIParameters.FETCH_OPTION)) { final InterfaceRegistry interfaceRegistry = CLIParameters.getInterfaceRegistry(commandLine); final CipherKey projectCipherKey = Optional.ofNullable(commandLine.getOptionValue(CLIParameters.PROJECT_PATH_OPTION)) .map(Paths::get) .map(OmpReader::readProjectCipherKey) .orElseThrow(() -> new UnexpectedException("Provide a project location")); final CLUDevice device = fetchDevice(networkInterface, ipAddress, projectCipherKey, interfaceRegistry); // try (CLUClient client = new CLUClient(networkInterface, device, projectCipherKey)) { // // NOP // } } else if (commandLine.hasOption(CLIParameters.EXECUTE_OPTION)) { final String command = commandLine.getOptionValue(CLIParameters.EXECUTE_OPTION); final CipherKey projectCipherKey = CLIParameters.getProjectCipherKey(commandLine) .orElseThrow(() -> new UnexpectedException("Provide a project location")); try (CLUClient client = new CLUClient(networkInterface.getAddress(), ipAddress, projectCipherKey)) { LOGGER.info(client.execute(command).get()); final Boolean success = client.startTFTPdServer().get(); if (success) { final CLUDevice device = client.getCluDevice(); final Path rootPath = Paths.get(".").resolve("live").resolve(String.valueOf(device.getSerialNumber())); FileUtil.mkdir(rootPath); for (CLUFiles cluLikeFile : CLUFiles.values()) { if (!cluLikeFile.isReadable() || !cluLikeFile.isWritable()) { continue; } final Path target = rootPath.resolve(cluLikeFile.getDevice() + "_" + StringUtils.lowerCase(cluLikeFile.getFileName())); try { client.downloadFile(cluLikeFile.getLocation(), target); } catch (Exception e) { FileUtil.deleteQuietly(target); } } } } } } private static void discover( NetworkInterfaceDto networkInterface, CipherKey projectCipherKey, Integer cluLimit, InterfaceRegistry interfaceRegistry ) { try (Client broadcastClient = new Client(networkInterface.getAddress())) { broadcastClient.discover( projectCipherKey, PRIVATE_KEYS, DEFAULT_LONG_TIMEOUT, cluLimit ) .map(cluDevice -> { LOGGER.debug("Discovered device: {}", cluDevice); return new CLUClient(networkInterface.getAddress(), cluDevice); }) .forEach(client -> { try (client) { final CLUDevice device = client.getCluDevice(); client.updateCipherKey(projectCipherKey) .get(); client.reset(DEFAULT_LONG_TIMEOUT) .get(); Util.repeatUntilTrueOrTimeout( DEFAULT_LONG_TIMEOUT, duration -> client.checkAlive() ) .orElseThrow(() -> new UnexpectedException("CLU did not came up alive")); detect(interfaceRegistry, client, device); } }); } } private static void detect(InterfaceRegistry interfaceRegistry, CLUClient client, CLUDevice device) { client.startTFTPdServer() .get(); final Path temporaryFile = FileUtil.temporaryFile(); try { final Optional<Path> path = client.downloadFile(CLUFiles.CONFIG_JSON.getLocation(), temporaryFile); if (path.isPresent()) { final Path configJsonFile = path.get();
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client; public class Main { private static final Duration DEFAULT_LONG_TIMEOUT = Duration.ofMillis(30_000); private static final int TIMEOUT = 4_000; private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); private static final Map<Long, byte[]> PRIVATE_KEYS = Map.of( 0x0L, "00000000".getBytes() ); private static final Inet4Address MIN_IP = IPv4AddressUtil.parseIPv4("10.72.144.1"); private Main() { // NOP } public static void main(String[] args) throws Exception { final CommandLine commandLine = new DefaultParser().parse(CLIParameters.OPTIONS, args); if (commandLine.hasOption(CLIParameters.HELP_OPTION)) { new HelpFormatter() .printHelp("java -jar client.jar", CLIParameters.OPTIONS); System.exit(0); } // final NetworkInterfaceDto networkInterface = CLIParameters.getNetworkInterface(commandLine); LOGGER.debug("Using network interface: {}", networkInterface); if (commandLine.hasOption(CLIParameters.DISCOVER_OPTION)) { final InterfaceRegistry interfaceRegistry = CLIParameters.getInterfaceRegistry(commandLine); final CipherKey projectCipherKey = CLIParameters.getProjectCipherKey(commandLine) .orElseGet(() -> { final CipherKey cipherKey = new CipherKey(RandomUtil.bytes(16), RandomUtil.bytes(16)); LOGGER.debug("Generated random project key: {}", cipherKey); return cipherKey; }); final Integer cluLimit = Optional.ofNullable(commandLine.getOptionValue(CLIParameters.CLU_LIMIT_PATH_OPTION)) .map(Integer::parseInt) .orElse(1); discover(networkInterface, projectCipherKey, cluLimit, interfaceRegistry); return; } final Inet4Address ipAddress = CLIParameters.getRemoteIPAddress(commandLine); if (commandLine.hasOption(CLIParameters.FETCH_OPTION)) { final InterfaceRegistry interfaceRegistry = CLIParameters.getInterfaceRegistry(commandLine); final CipherKey projectCipherKey = Optional.ofNullable(commandLine.getOptionValue(CLIParameters.PROJECT_PATH_OPTION)) .map(Paths::get) .map(OmpReader::readProjectCipherKey) .orElseThrow(() -> new UnexpectedException("Provide a project location")); final CLUDevice device = fetchDevice(networkInterface, ipAddress, projectCipherKey, interfaceRegistry); // try (CLUClient client = new CLUClient(networkInterface, device, projectCipherKey)) { // // NOP // } } else if (commandLine.hasOption(CLIParameters.EXECUTE_OPTION)) { final String command = commandLine.getOptionValue(CLIParameters.EXECUTE_OPTION); final CipherKey projectCipherKey = CLIParameters.getProjectCipherKey(commandLine) .orElseThrow(() -> new UnexpectedException("Provide a project location")); try (CLUClient client = new CLUClient(networkInterface.getAddress(), ipAddress, projectCipherKey)) { LOGGER.info(client.execute(command).get()); final Boolean success = client.startTFTPdServer().get(); if (success) { final CLUDevice device = client.getCluDevice(); final Path rootPath = Paths.get(".").resolve("live").resolve(String.valueOf(device.getSerialNumber())); FileUtil.mkdir(rootPath); for (CLUFiles cluLikeFile : CLUFiles.values()) { if (!cluLikeFile.isReadable() || !cluLikeFile.isWritable()) { continue; } final Path target = rootPath.resolve(cluLikeFile.getDevice() + "_" + StringUtils.lowerCase(cluLikeFile.getFileName())); try { client.downloadFile(cluLikeFile.getLocation(), target); } catch (Exception e) { FileUtil.deleteQuietly(target); } } } } } } private static void discover( NetworkInterfaceDto networkInterface, CipherKey projectCipherKey, Integer cluLimit, InterfaceRegistry interfaceRegistry ) { try (Client broadcastClient = new Client(networkInterface.getAddress())) { broadcastClient.discover( projectCipherKey, PRIVATE_KEYS, DEFAULT_LONG_TIMEOUT, cluLimit ) .map(cluDevice -> { LOGGER.debug("Discovered device: {}", cluDevice); return new CLUClient(networkInterface.getAddress(), cluDevice); }) .forEach(client -> { try (client) { final CLUDevice device = client.getCluDevice(); client.updateCipherKey(projectCipherKey) .get(); client.reset(DEFAULT_LONG_TIMEOUT) .get(); Util.repeatUntilTrueOrTimeout( DEFAULT_LONG_TIMEOUT, duration -> client.checkAlive() ) .orElseThrow(() -> new UnexpectedException("CLU did not came up alive")); detect(interfaceRegistry, client, device); } }); } } private static void detect(InterfaceRegistry interfaceRegistry, CLUClient client, CLUDevice device) { client.startTFTPdServer() .get(); final Path temporaryFile = FileUtil.temporaryFile(); try { final Optional<Path> path = client.downloadFile(CLUFiles.CONFIG_JSON.getLocation(), temporaryFile); if (path.isPresent()) { final Path configJsonFile = path.get();
final CLUDeviceConfig configJson = ObjectMapperFactory.JSON.readerFor(CLUDeviceConfig.class)
7
2023-12-23 09:56:14+00:00
16k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/tests/org/jfree/chart/labels/StandardXYSeriesLabelGeneratorTest.java
[ { "identifier": "TestUtilities", "path": "lib/jfreechart-1.0.19/tests/org/jfree/chart/TestUtilities.java", "snippet": "public class TestUtilities {\n\n /**\n * Returns <code>true</code> if the collections contains any object that\n * is an instance of the specified class, and <code>false</cod...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.jfree.chart.TestUtilities; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.util.PublicCloneable; import org.junit.Test;
13,870
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------------- * StandardXYSeriesLabelGeneratorTest.java * --------------------------------------- * (C) Copyright 2006-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 24-Nov-2006 : Version 1 (DG); * 23-Apr-2008 : Added testPublicCloneable() (DG) * */ package org.jfree.chart.labels; /** * Tests for the {@link StandardXYSeriesLabelGenerator} class. */ public class StandardXYSeriesLabelGeneratorTest { /** * Some checks for the generalLabel() method. */ @Test public void testGenerateLabel() { StandardXYSeriesLabelGenerator g = new StandardXYSeriesLabelGenerator("Series {0}"); XYSeriesCollection dataset = new XYSeriesCollection();
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------------- * StandardXYSeriesLabelGeneratorTest.java * --------------------------------------- * (C) Copyright 2006-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 24-Nov-2006 : Version 1 (DG); * 23-Apr-2008 : Added testPublicCloneable() (DG) * */ package org.jfree.chart.labels; /** * Tests for the {@link StandardXYSeriesLabelGenerator} class. */ public class StandardXYSeriesLabelGeneratorTest { /** * Some checks for the generalLabel() method. */ @Test public void testGenerateLabel() { StandardXYSeriesLabelGenerator g = new StandardXYSeriesLabelGenerator("Series {0}"); XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(new XYSeries("1"));
1
2023-12-24 12:36:47+00:00
16k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/module/impl/skills/FillChestWithSaplingMacro.java
[ { "identifier": "MayOBeesConfig", "path": "src/main/java/com/github/may2beez/mayobees/config/MayOBeesConfig.java", "snippet": "public class MayOBeesConfig extends Config {\n\n //<editor-fold desc=\"COMBAT\">\n @KeyBind(\n name = \"Shortbow Aura\",\n description = \"Automatica...
import com.github.may2beez.mayobees.config.MayOBeesConfig; import com.github.may2beez.mayobees.module.IModuleActive; import com.github.may2beez.mayobees.util.InventoryUtils; import com.github.may2beez.mayobees.util.KeyBindUtils; import com.github.may2beez.mayobees.util.LogUtils; import com.github.may2beez.mayobees.util.helper.Clock; import net.minecraft.client.Minecraft; import net.minecraft.init.Blocks; import net.minecraft.inventory.Slot; import net.minecraft.util.MovingObjectPosition; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent;
13,225
package com.github.may2beez.mayobees.module.impl.skills; public class FillChestWithSaplingMacro implements IModuleActive { private static FillChestWithSaplingMacro instance; public static FillChestWithSaplingMacro getInstance() { if (instance == null) { instance = new FillChestWithSaplingMacro(); } return instance; } private boolean enabled = false; private static final Minecraft mc = Minecraft.getMinecraft(); @Override public boolean isRunning() { return enabled; } @Override public String getName() { return "Fill Chest With Sapling Macro"; } public enum States { IDLE, ABIPHONE, BUILDER, OPEN_CHEST, FILL_CHEST } private static States state = States.IDLE;
package com.github.may2beez.mayobees.module.impl.skills; public class FillChestWithSaplingMacro implements IModuleActive { private static FillChestWithSaplingMacro instance; public static FillChestWithSaplingMacro getInstance() { if (instance == null) { instance = new FillChestWithSaplingMacro(); } return instance; } private boolean enabled = false; private static final Minecraft mc = Minecraft.getMinecraft(); @Override public boolean isRunning() { return enabled; } @Override public String getName() { return "Fill Chest With Sapling Macro"; } public enum States { IDLE, ABIPHONE, BUILDER, OPEN_CHEST, FILL_CHEST } private static States state = States.IDLE;
private static final Clock waitTimer = new Clock();
5
2023-12-24 15:39:11+00:00
16k
Trodev-IT/ScanHub
app/src/main/java/com/trodev/scanhub/HomeFragment.java
[ { "identifier": "EmailActivity", "path": "app/src/main/java/com/trodev/scanhub/activities/EmailActivity.java", "snippet": "public class EmailActivity extends AppCompatActivity {\n\n public final static int QRCodeWidth = 500;\n Bitmap bitmap;\n private Button make_btn, save_btn, downloadBtn;\n ...
import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.google.android.material.card.MaterialCardView; import com.trodev.scanhub.activities.EmailActivity; import com.trodev.scanhub.activities.LocationActivity; import com.trodev.scanhub.activities.ProductQrActivity; import com.trodev.scanhub.activities.ScanGalleryActivity; import com.trodev.scanhub.activities.ScannerActivity; import com.trodev.scanhub.activities.SmsActivity; import com.trodev.scanhub.activities.URLActivity; import com.trodev.scanhub.activities.WifiQrActivity;
12,433
package com.trodev.scanhub; public class HomeFragment extends Fragment { MaterialCardView product_qr, message, wifi; MaterialCardView email_qr, location_qr, url_qr; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); /*init views*/ product_qr = view.findViewById(R.id.product_qr); message = view.findViewById(R.id.message); wifi = view.findViewById(R.id.wifi); email_qr = view.findViewById(R.id.email_qr); location_qr = view.findViewById(R.id.location_qr); url_qr = view.findViewById(R.id.url_qr); /*set on click listener*/ product_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_product(); } }); message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_message(); } }); wifi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_wifi(); } }); email_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_email(); } }); location_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_location(); } }); url_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_url(); } }); return view; } private void goto_url() { startActivity(new Intent(getContext(), URLActivity.class)); } private void goto_location() { startActivity(new Intent(getContext(), LocationActivity.class)); } private void goto_email() {
package com.trodev.scanhub; public class HomeFragment extends Fragment { MaterialCardView product_qr, message, wifi; MaterialCardView email_qr, location_qr, url_qr; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); /*init views*/ product_qr = view.findViewById(R.id.product_qr); message = view.findViewById(R.id.message); wifi = view.findViewById(R.id.wifi); email_qr = view.findViewById(R.id.email_qr); location_qr = view.findViewById(R.id.location_qr); url_qr = view.findViewById(R.id.url_qr); /*set on click listener*/ product_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_product(); } }); message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_message(); } }); wifi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_wifi(); } }); email_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_email(); } }); location_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_location(); } }); url_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_url(); } }); return view; } private void goto_url() { startActivity(new Intent(getContext(), URLActivity.class)); } private void goto_location() { startActivity(new Intent(getContext(), LocationActivity.class)); } private void goto_email() {
startActivity(new Intent(getContext(), EmailActivity.class));
0
2023-12-26 05:10:38+00:00
16k
piovas-lu/condominio
src/main/java/app/condominio/service/RelatorioServiceImpl.java
[ { "identifier": "Categoria", "path": "src/main/java/app/condominio/domain/Categoria.java", "snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"categorias\")\r\npublic class Categoria implements Serializable, Comparable<Categoria> {\r\n\r\n\tpublic static final int NIVEL_MAX = 4;\r\n\...
import java.math.BigDecimal; import java.time.LocalDate; import java.time.YearMonth; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import app.condominio.domain.Categoria; import app.condominio.domain.Cobranca; import app.condominio.domain.Conta; import app.condominio.domain.Moradia; import app.condominio.domain.Movimento; import app.condominio.domain.Orcamento; import app.condominio.domain.Periodo; import app.condominio.domain.Subcategoria; import app.condominio.domain.enums.TipoCategoria;
10,965
private BigDecimal[] receitaDespesaEntre(Collection<Conta> contas, LocalDate inicio, LocalDate fim) { BigDecimal[] resultado = new BigDecimal[2]; if (!contas.isEmpty()) { resultado[0] = movimentoService.somaLancamentosEntre(contas, inicio, fim, Boolean.FALSE); resultado[1] = movimentoService.somaLancamentosEntre(contas, inicio, fim, Boolean.TRUE); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } private BigDecimal[] receitaDespesaDesde(Collection<Conta> contas, LocalDate inicio) { BigDecimal[] resultado = new BigDecimal[2]; if (!contas.isEmpty()) { resultado[0] = movimentoService.somaLancamentosDesde(contas, inicio, Boolean.FALSE); resultado[1] = movimentoService.somaLancamentosDesde(contas, inicio, Boolean.TRUE); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } @Override public BigDecimal[] receitaDespesaMesAtual() { List<Conta> contas = contaService.listar(); YearMonth mesAtual = YearMonth.from(LocalDate.now()); // mesAtual = mesAtual.minusMonths(1); // Mês anterior para testes return receitaDespesaEntre(contas, mesAtual.atDay(1), mesAtual.atEndOfMonth()); } @Override public BigDecimal[] receitaDespesaEntre(LocalDate inicio, LocalDate fim) { List<Conta> contas = contaService.listar(); return receitaDespesaEntre(contas, inicio, fim); } @Override public BigDecimal[] receitaDespesaRealizadaPeriodoAtual() { List<Conta> contas = contaService.listar(); Periodo periodoAtual = periodoService.ler(LocalDate.now()); if (periodoAtual != null) { return receitaDespesaEntre(contas, periodoAtual.getInicio(), periodoAtual.getFim()); } else { BigDecimal[] resultado = new BigDecimal[2]; resultado[0] = BigDecimal.ZERO.setScale(2); resultado[1] = BigDecimal.ZERO.setScale(2); return resultado; } } @Override public BigDecimal[] receitaDespesaOrcadaPeriodoAtual() { Periodo periodoAtual = periodoService.ler(LocalDate.now()); BigDecimal[] resultado = new BigDecimal[2]; if (periodoAtual != null) { resultado[0] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.R); resultado[1] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.D); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } @Override public List<Movimento> lancamentosEntre(LocalDate inicio, LocalDate fim) { List<Conta> contas = contaService.listar(); if (!contas.isEmpty()) { List<Movimento> lancamentos = new ArrayList<>(); lancamentos.addAll(movimentoService.listarLancamentosEntre(contas, inicio, fim)); return lancamentos; } return new ArrayList<>(); } @Override public BigDecimal[] saldosAposMovimentos(List<Movimento> movimentos, BigDecimal saldoInicial) { if (saldoInicial == null) { saldoInicial = BigDecimal.ZERO.setScale(2); } if (!movimentos.isEmpty()) { BigDecimal[] saldos = new BigDecimal[movimentos.size()]; Movimento movimento = movimentos.get(0); // Preenche o primeiro saldo if (movimento.getReducao()) { saldos[0] = saldoInicial.subtract(movimento.getValor()); } else { saldos[0] = saldoInicial.add(movimento.getValor()); } // Preenche os outros saldos for (int i = 1; i < saldos.length; i++) { movimento = movimentos.get(i); if (movimento.getReducao()) { saldos[i] = saldos[i - 1].subtract(movimento.getValor()); } else { saldos[i] = saldos[i - 1].add(movimento.getValor()); } } return saldos; } else { BigDecimal[] vazio = new BigDecimal[1]; vazio[0] = saldoInicial; return vazio; } } @Override
package app.condominio.service; @Service @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public class RelatorioServiceImpl implements RelatorioService { @Autowired ContaService contaService; @Autowired MovimentoService movimentoService; @Autowired CobrancaService cobrancaService; @Autowired OrcamentoService orcamentoService; @Autowired PeriodoService periodoService; @Autowired SubcategoriaService subcategoriaService; @Autowired CategoriaService categoriaService; @Override public BigDecimal saldoAtualTodasContas() { return contaService.saldoAtual(); } @Override public BigDecimal saldoInicialTodasContasEm(LocalDate data) { BigDecimal saldo = contaService.saldoAtual(); BigDecimal[] lancamentos = receitaDespesaDesde(contaService.listar(), data); return saldo.subtract(lancamentos[0]).add(lancamentos[1]); } @Override public BigDecimal saldoFinalTodasContasEm(LocalDate data) { return saldoInicialTodasContasEm(data.plusDays(1)); } @Override public BigDecimal inadimplenciaAtual() { return cobrancaService.inadimplencia(); } private BigDecimal[] receitaDespesaEntre(Collection<Conta> contas, LocalDate inicio, LocalDate fim) { BigDecimal[] resultado = new BigDecimal[2]; if (!contas.isEmpty()) { resultado[0] = movimentoService.somaLancamentosEntre(contas, inicio, fim, Boolean.FALSE); resultado[1] = movimentoService.somaLancamentosEntre(contas, inicio, fim, Boolean.TRUE); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } private BigDecimal[] receitaDespesaDesde(Collection<Conta> contas, LocalDate inicio) { BigDecimal[] resultado = new BigDecimal[2]; if (!contas.isEmpty()) { resultado[0] = movimentoService.somaLancamentosDesde(contas, inicio, Boolean.FALSE); resultado[1] = movimentoService.somaLancamentosDesde(contas, inicio, Boolean.TRUE); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } @Override public BigDecimal[] receitaDespesaMesAtual() { List<Conta> contas = contaService.listar(); YearMonth mesAtual = YearMonth.from(LocalDate.now()); // mesAtual = mesAtual.minusMonths(1); // Mês anterior para testes return receitaDespesaEntre(contas, mesAtual.atDay(1), mesAtual.atEndOfMonth()); } @Override public BigDecimal[] receitaDespesaEntre(LocalDate inicio, LocalDate fim) { List<Conta> contas = contaService.listar(); return receitaDespesaEntre(contas, inicio, fim); } @Override public BigDecimal[] receitaDespesaRealizadaPeriodoAtual() { List<Conta> contas = contaService.listar(); Periodo periodoAtual = periodoService.ler(LocalDate.now()); if (periodoAtual != null) { return receitaDespesaEntre(contas, periodoAtual.getInicio(), periodoAtual.getFim()); } else { BigDecimal[] resultado = new BigDecimal[2]; resultado[0] = BigDecimal.ZERO.setScale(2); resultado[1] = BigDecimal.ZERO.setScale(2); return resultado; } } @Override public BigDecimal[] receitaDespesaOrcadaPeriodoAtual() { Periodo periodoAtual = periodoService.ler(LocalDate.now()); BigDecimal[] resultado = new BigDecimal[2]; if (periodoAtual != null) { resultado[0] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.R); resultado[1] = orcamentoService.somaOrcamentos(periodoAtual, TipoCategoria.D); } if (resultado[0] == null) { resultado[0] = BigDecimal.ZERO.setScale(2); } if (resultado[1] == null) { resultado[1] = BigDecimal.ZERO.setScale(2); } return resultado; } @Override public List<Movimento> lancamentosEntre(LocalDate inicio, LocalDate fim) { List<Conta> contas = contaService.listar(); if (!contas.isEmpty()) { List<Movimento> lancamentos = new ArrayList<>(); lancamentos.addAll(movimentoService.listarLancamentosEntre(contas, inicio, fim)); return lancamentos; } return new ArrayList<>(); } @Override public BigDecimal[] saldosAposMovimentos(List<Movimento> movimentos, BigDecimal saldoInicial) { if (saldoInicial == null) { saldoInicial = BigDecimal.ZERO.setScale(2); } if (!movimentos.isEmpty()) { BigDecimal[] saldos = new BigDecimal[movimentos.size()]; Movimento movimento = movimentos.get(0); // Preenche o primeiro saldo if (movimento.getReducao()) { saldos[0] = saldoInicial.subtract(movimento.getValor()); } else { saldos[0] = saldoInicial.add(movimento.getValor()); } // Preenche os outros saldos for (int i = 1; i < saldos.length; i++) { movimento = movimentos.get(i); if (movimento.getReducao()) { saldos[i] = saldos[i - 1].subtract(movimento.getValor()); } else { saldos[i] = saldos[i - 1].add(movimento.getValor()); } } return saldos; } else { BigDecimal[] vazio = new BigDecimal[1]; vazio[0] = saldoInicial; return vazio; } } @Override
public SortedMap<Subcategoria, BigDecimal> somasPorTipoEntre(LocalDate inicio, LocalDate fim,
7
2023-12-29 22:19:42+00:00
16k
HuXin0817/shop_api
consumer/src/main/java/cn/lili/event/impl/GoodsSkuExecute.java
[ { "identifier": "Cache", "path": "framework/src/main/java/cn/lili/cache/Cache.java", "snippet": "public interface Cache<T> {\n\n /**\n * Get an item from the cache, nontransactionally\n *\n * @param key 缓存key\n * @return the cached object or <tt>null</tt>\n */\n T get(Object ke...
import cn.lili.cache.Cache; import cn.lili.cache.CachePrefix; import cn.lili.event.GoodsCommentCompleteEvent; import cn.lili.event.StoreSettingChangeEvent; import cn.lili.modules.goods.entity.dos.GoodsSku; import cn.lili.modules.goods.entity.dto.GoodsSearchParams; import cn.lili.modules.goods.service.GoodsService; import cn.lili.modules.goods.service.GoodsSkuService; import cn.lili.modules.member.entity.dos.MemberEvaluation; import cn.lili.modules.store.entity.dos.Store; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List;
13,622
package cn.lili.event.impl; /** * 商品SKU变化 * * @author Chopper * @since 2020-07-03 11:20 */ @Service public class GoodsSkuExecute implements GoodsCommentCompleteEvent, StoreSettingChangeEvent { /** * 商品 */ @Autowired private GoodsSkuService goodsSkuService; @Autowired private GoodsService goodsService; @Autowired
package cn.lili.event.impl; /** * 商品SKU变化 * * @author Chopper * @since 2020-07-03 11:20 */ @Service public class GoodsSkuExecute implements GoodsCommentCompleteEvent, StoreSettingChangeEvent { /** * 商品 */ @Autowired private GoodsSkuService goodsSkuService; @Autowired private GoodsService goodsService; @Autowired
private Cache cache;
0
2023-12-24 19:45:18+00:00
16k
huidongyin/kafka-2.7.2
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/WorkerTaskTest.java
[ { "identifier": "Time", "path": "clients/src/main/java/org/apache/kafka/common/utils/Time.java", "snippet": "public interface Time {\n\n Time SYSTEM = new SystemTime();\n\n /**\n * Returns the current time in milliseconds.\n */\n long milliseconds();\n\n /**\n * Returns the value...
import org.apache.kafka.common.utils.Time; import org.apache.kafka.connect.errors.ConnectException; import org.apache.kafka.connect.runtime.WorkerTask.TaskMetricsGroup; import org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator; import org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperatorTest; import org.apache.kafka.connect.sink.SinkTask; import org.apache.kafka.connect.storage.StatusBackingStore; import org.apache.kafka.connect.util.ConnectorTaskId; import org.apache.kafka.common.utils.MockTime; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.easymock.Mock; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.partialMockBuilder; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals;
11,364
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.connect.runtime; @RunWith(PowerMockRunner.class) @PrepareForTest({WorkerTask.class}) @PowerMockIgnore("javax.management.*") public class WorkerTaskTest { private static final Map<String, String> TASK_PROPS = new HashMap<>(); static { TASK_PROPS.put(TaskConfig.TASK_CLASS_CONFIG, TestSinkTask.class.getName()); } private static final TaskConfig TASK_CONFIG = new TaskConfig(TASK_PROPS); private ConnectMetrics metrics; @Mock private TaskStatus.Listener statusListener; @Mock private ClassLoader loader; RetryWithToleranceOperator retryWithToleranceOperator; @Mock StatusBackingStore statusBackingStore; @Before public void setup() { metrics = new MockConnectMetrics();
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.connect.runtime; @RunWith(PowerMockRunner.class) @PrepareForTest({WorkerTask.class}) @PowerMockIgnore("javax.management.*") public class WorkerTaskTest { private static final Map<String, String> TASK_PROPS = new HashMap<>(); static { TASK_PROPS.put(TaskConfig.TASK_CLASS_CONFIG, TestSinkTask.class.getName()); } private static final TaskConfig TASK_CONFIG = new TaskConfig(TASK_PROPS); private ConnectMetrics metrics; @Mock private TaskStatus.Listener statusListener; @Mock private ClassLoader loader; RetryWithToleranceOperator retryWithToleranceOperator; @Mock StatusBackingStore statusBackingStore; @Before public void setup() { metrics = new MockConnectMetrics();
retryWithToleranceOperator = RetryWithToleranceOperatorTest.NOOP_OPERATOR;
4
2023-12-23 07:12:18+00:00
16k
Yanyutin753/PandoraNext-TokensTool
rearServer/src/main/java/com/tokensTool/pandoraNext/controller/autoTokenController.java
[ { "identifier": "Result", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/Result.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Result {\n\n /**\n * 响应码,1 代表成功; 0 代表失败\n */\n\n private Integer code;\n /**\n * 响应信息 描述字符串\n */\n\n...
import com.tokensTool.pandoraNext.anno.Log; import com.tokensTool.pandoraNext.pojo.Result; import com.tokensTool.pandoraNext.pojo.token; import com.tokensTool.pandoraNext.service.impl.poolServiceImpl; import com.tokensTool.pandoraNext.service.impl.shareServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.bind.annotation.*; import java.util.List;
13,688
package com.tokensTool.pandoraNext.controller; /** * @author Yangyang * @create 2023-11-11 18:19 */ @Slf4j @RestController @RequestMapping("/api") public class autoTokenController { @Autowired private com.tokensTool.pandoraNext.service.apiService apiService; @Autowired private poolServiceImpl poolService; @Autowired
package com.tokensTool.pandoraNext.controller; /** * @author Yangyang * @create 2023-11-11 18:19 */ @Slf4j @RestController @RequestMapping("/api") public class autoTokenController { @Autowired private com.tokensTool.pandoraNext.service.apiService apiService; @Autowired private poolServiceImpl poolService; @Autowired
private shareServiceImpl shareService;
3
2023-11-17 11:37:37+00:00
16k
quarkiverse/quarkus-langchain4j
openai/azure-openai/runtime/src/main/java/io/quarkiverse/langchain4j/azure/openai/runtime/AzureOpenAiRecorder.java
[ { "identifier": "firstOrDefault", "path": "core/runtime/src/main/java/io/quarkiverse/langchain4j/runtime/OptionalUtil.java", "snippet": "@SafeVarargs\npublic static <T> T firstOrDefault(T defaultValue, Optional<T>... values) {\n for (Optional<T> o : values) {\n if (o != null && o.isPresent()) ...
import static io.quarkiverse.langchain4j.runtime.OptionalUtil.firstOrDefault; import java.util.function.Supplier; import io.quarkiverse.langchain4j.azure.openai.AzureOpenAiChatModel; import io.quarkiverse.langchain4j.azure.openai.AzureOpenAiEmbeddingModel; import io.quarkiverse.langchain4j.azure.openai.AzureOpenAiStreamingChatModel; import io.quarkiverse.langchain4j.azure.openai.runtime.config.ChatModelConfig; import io.quarkiverse.langchain4j.azure.openai.runtime.config.EmbeddingModelConfig; import io.quarkiverse.langchain4j.azure.openai.runtime.config.Langchain4jAzureOpenAiConfig; import io.quarkiverse.langchain4j.openai.QuarkusOpenAiClient; import io.quarkus.runtime.ShutdownContext; import io.quarkus.runtime.annotations.Recorder;
11,020
package io.quarkiverse.langchain4j.azure.openai.runtime; @Recorder public class AzureOpenAiRecorder { public Supplier<?> chatModel(Langchain4jAzureOpenAiConfig runtimeConfig) { ChatModelConfig chatModelConfig = runtimeConfig.chatModel();
package io.quarkiverse.langchain4j.azure.openai.runtime; @Recorder public class AzureOpenAiRecorder { public Supplier<?> chatModel(Langchain4jAzureOpenAiConfig runtimeConfig) { ChatModelConfig chatModelConfig = runtimeConfig.chatModel();
var builder = AzureOpenAiChatModel.builder()
1
2023-11-13 09:10:27+00:00
16k
qiusunshine/xiu
clinglibrary/src/main/java/com/qingfeng/clinglibrary/service/manager/ClingManager.java
[ { "identifier": "ClingControlPoint", "path": "clinglibrary/src/main/java/com/qingfeng/clinglibrary/entity/ClingControlPoint.java", "snippet": "public class ClingControlPoint implements IControlPoint<ControlPoint> {\n\n private static ClingControlPoint INSTANCE = null;\n private ControlPoint mContr...
import android.content.Context; import androidx.annotation.Nullable; import com.qingfeng.clinglibrary.entity.ClingControlPoint; import com.qingfeng.clinglibrary.entity.ClingDevice; import com.qingfeng.clinglibrary.entity.IControlPoint; import com.qingfeng.clinglibrary.entity.IDevice; import com.qingfeng.clinglibrary.service.ClingUpnpService; import com.qingfeng.clinglibrary.util.ListUtils; import com.qingfeng.clinglibrary.util.Utils; import org.fourthline.cling.model.meta.Device; import org.fourthline.cling.model.types.DeviceType; import org.fourthline.cling.model.types.ServiceType; import org.fourthline.cling.model.types.UDADeviceType; import org.fourthline.cling.model.types.UDAServiceType; import org.fourthline.cling.registry.Registry; import java.util.ArrayList; import java.util.Collection;
12,245
package com.qingfeng.clinglibrary.service.manager; /** * 说明:所有对服务的操作都通过该类代理执行 * 作者:zhouzhan * 日期:17/6/27 18:12 */ public class ClingManager implements IClingManager { // public static final ServiceType CONTENT_DIRECTORY_SERVICE = new UDAServiceType("ContentDirectory"); public static final ServiceType AV_TRANSPORT_SERVICE = new UDAServiceType("AVTransport"); /** * 控制服务 */ public static final ServiceType RENDERING_CONTROL_SERVICE = new UDAServiceType("RenderingControl"); public static final DeviceType DMR_DEVICE_TYPE = new UDADeviceType("MediaRenderer"); private static ClingManager INSTANCE = null;
package com.qingfeng.clinglibrary.service.manager; /** * 说明:所有对服务的操作都通过该类代理执行 * 作者:zhouzhan * 日期:17/6/27 18:12 */ public class ClingManager implements IClingManager { // public static final ServiceType CONTENT_DIRECTORY_SERVICE = new UDAServiceType("ContentDirectory"); public static final ServiceType AV_TRANSPORT_SERVICE = new UDAServiceType("AVTransport"); /** * 控制服务 */ public static final ServiceType RENDERING_CONTROL_SERVICE = new UDAServiceType("RenderingControl"); public static final DeviceType DMR_DEVICE_TYPE = new UDADeviceType("MediaRenderer"); private static ClingManager INSTANCE = null;
private ClingUpnpService mUpnpService;
4
2023-11-10 14:28:40+00:00
16k
xIdentified/Devotions
src/main/java/me/xidentified/devotions/commandexecutors/DeityCommand.java
[ { "identifier": "Deity", "path": "src/main/java/me/xidentified/devotions/Deity.java", "snippet": "public class Deity {\n private final Devotions plugin;\n // Getter methods below\n @Getter public final String name;\n @Getter private final String lore;\n @Getter private final String alignm...
import de.cubbossa.tinytranslations.GlobalMessages; import me.xidentified.devotions.Deity; import me.xidentified.devotions.Devotions; import me.xidentified.devotions.managers.FavorManager; import me.xidentified.devotions.util.Messages; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.UUID;
12,918
package me.xidentified.devotions.commandexecutors; public class DeityCommand implements CommandExecutor, TabCompleter { private final Devotions plugin; public DeityCommand(Devotions plugin) { this.plugin = plugin; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (!(sender instanceof Player player)) { Devotions.getInstance().sendMessage(sender, GlobalMessages.CMD_PLAYER_ONLY); return true; } if (args.length < 1) { plugin.sendMessage(player, Messages.DEITY_CMD_USAGE); return true; } String subCommand = args[0].toLowerCase(); switch (subCommand) { case "list" -> { return handleList(player); } case "select" -> { return handleSelect(player, args); } case "info" -> { return handleInfo(player, args); } default -> { plugin.sendMessage(player,Messages.DEITY_CMD_USAGE); return true; } } } private boolean handleSelect(Player player, String[] args) { if (args.length < 2) { plugin.sendMessage(player, Messages.DEITY_CMD_SPECIFY_DEITY); return true; } String deityName = args[1]; Deity selectedDeity = plugin.getDevotionManager().getDeityByName(deityName); if (selectedDeity == null) { plugin.sendMessage(player, Messages.DEITY_NOT_FOUND); return false; } // Fetch or create the player's FavorManager UUID playerUniqueId = player.getUniqueId();
package me.xidentified.devotions.commandexecutors; public class DeityCommand implements CommandExecutor, TabCompleter { private final Devotions plugin; public DeityCommand(Devotions plugin) { this.plugin = plugin; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (!(sender instanceof Player player)) { Devotions.getInstance().sendMessage(sender, GlobalMessages.CMD_PLAYER_ONLY); return true; } if (args.length < 1) { plugin.sendMessage(player, Messages.DEITY_CMD_USAGE); return true; } String subCommand = args[0].toLowerCase(); switch (subCommand) { case "list" -> { return handleList(player); } case "select" -> { return handleSelect(player, args); } case "info" -> { return handleInfo(player, args); } default -> { plugin.sendMessage(player,Messages.DEITY_CMD_USAGE); return true; } } } private boolean handleSelect(Player player, String[] args) { if (args.length < 2) { plugin.sendMessage(player, Messages.DEITY_CMD_SPECIFY_DEITY); return true; } String deityName = args[1]; Deity selectedDeity = plugin.getDevotionManager().getDeityByName(deityName); if (selectedDeity == null) { plugin.sendMessage(player, Messages.DEITY_NOT_FOUND); return false; } // Fetch or create the player's FavorManager UUID playerUniqueId = player.getUniqueId();
FavorManager favorManager = plugin.getDevotionManager().getPlayerDevotion(playerUniqueId);
2
2023-11-10 07:03:24+00:00
16k
SplitfireUptown/datalinkx
flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/outputformat/BaseRichOutputFormat.java
[ { "identifier": "ErrorLimitConfig", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/config/ErrorLimitConfig.java", "snippet": "public class ErrorLimitConfig extends AbstractConfig {\n\n public static final String KEY_ERROR_RECORD_LIMIT = \"record\";\n public static final String KEY_ER...
import com.dtstack.flinkx.config.ErrorLimitConfig; import com.dtstack.flinkx.config.RestoreConfig; import com.dtstack.flinkx.constants.Metrics; import com.dtstack.flinkx.exception.WriteRecordException; import com.dtstack.flinkx.latch.BaseLatch; import com.dtstack.flinkx.latch.LocalLatch; import com.dtstack.flinkx.latch.MetricLatch; import com.dtstack.flinkx.log.DtLogger; import com.dtstack.flinkx.metrics.AccumulatorCollector; import com.dtstack.flinkx.metrics.BaseMetric; import com.dtstack.flinkx.metrics.RateCounter; import com.dtstack.flinkx.restore.FormatState; import com.dtstack.flinkx.util.ExceptionUtil; import com.dtstack.flinkx.util.GsonUtil; import com.dtstack.flinkx.util.UrlUtil; import com.dtstack.flinkx.writer.DirtyDataManager; import com.dtstack.flinkx.writer.ErrorLimiter; import com.google.gson.reflect.TypeToken; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.flink.api.common.accumulators.LongCounter; import org.apache.flink.api.common.io.CleanupWhenUnsuccessful; import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.operators.StreamingRuntimeContext; import org.apache.flink.types.Row; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import static com.dtstack.flinkx.writer.WriteErrorTypes.ERR_FORMAT_TRANSFORM; import static com.dtstack.flinkx.writer.WriteErrorTypes.ERR_NULL_POINTER; import static com.dtstack.flinkx.writer.WriteErrorTypes.ERR_PRIMARY_CONFLICT;
12,736
/* * 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 com.dtstack.flinkx.outputformat; /** * Abstract Specification for all the OutputFormat defined in flinkx plugins * * Company: www.dtstack.com * @author huyifan.zju@163.com */ public abstract class BaseRichOutputFormat extends org.apache.flink.api.common.io.RichOutputFormat<Row> implements CleanupWhenUnsuccessful { protected final Logger LOG = LoggerFactory.getLogger(getClass()); protected String formatId; public static final String RUNNING_STATE = "RUNNING"; public static final int LOG_PRINT_INTERNAL = 2000; /** Dirty data manager */ protected DirtyDataManager dirtyDataManager; /** Dirty data storage path */ protected String dirtyPath; /** The hadoop config for dirty data storage */ protected Map<String,Object> dirtyHadoopConfig; /** The source table field names */ protected List<String> srcFieldNames; /** 批量提交条数 */ protected int batchInterval = 1; /** 存储用于批量写入的数据 */ protected List<Row> rows = new ArrayList(); /** 总记录数 */ protected LongCounter numWriteCounter; /** snapshot 中记录的总记录数 */ protected LongCounter snapshotWriteCounter; /** 错误记录数 */ protected LongCounter errCounter; /** Number of null pointer errors */ protected LongCounter nullErrCounter; /** Number of primary key conflict errors */ protected LongCounter duplicateErrCounter; /** Number of type conversion errors */ protected LongCounter conversionErrCounter; /** Number of other errors */ protected LongCounter otherErrCounter; /** 错误限制 */ protected ErrorLimiter errorLimiter; protected LongCounter bytesWriteCounter; protected LongCounter durationCounter; /** 错误阈值 */ protected Integer errors; /** 错误比例阈值 */ protected Double errorRatio; /** 批异常重试机制 */ protected String errorTryPlan; /** 任务名 */ protected String jobName = "defaultJobName"; /** 监控api根路径 */ protected String monitorUrl; /** 子任务编号 */ protected int taskNumber; /** 环境上下文 */ protected StreamingRuntimeContext context; /** 子任务数量 */ protected int numTasks; protected String jobId; protected RestoreConfig restoreConfig; protected FormatState formatState; protected Object initState; protected transient BaseMetric outputMetric; protected AccumulatorCollector accumulatorCollector; private long startTime; protected boolean initAccumulatorAndDirty = true; protected RateCounter rateCounter; protected final static String rateCounterName = "Writer"; public String getDirtyPath() { return dirtyPath; } public void setDirtyPath(String dirtyPath) { this.dirtyPath = dirtyPath; } public Map<String, Object> getDirtyHadoopConfig() { return dirtyHadoopConfig; } public void setDirtyHadoopConfig(Map<String, Object> dirtyHadoopConfig) { this.dirtyHadoopConfig = dirtyHadoopConfig; } public void setDirtyDataManager(DirtyDataManager dirtyDataManager) { this.dirtyDataManager = dirtyDataManager; } public void setErrorLimiter(ErrorLimiter errorLimiter) { this.errorLimiter = errorLimiter; } public void setSrcFieldNames(List<String> srcFieldNames) { this.srcFieldNames = srcFieldNames; } @Override public void configure(Configuration parameters) { // do nothing } /** * 子类实现,打开资源 * * @param taskNumber 通道索引 * @param numTasks 通道数量 * @throws IOException */ protected abstract void openInternal(int taskNumber, int numTasks) throws IOException; /** * 打开资源的前后做一些初始化操作 * * @param taskNumber The number of the parallel instance. * @param numTasks The number of parallel tasks. * @throws IOException */ @Override public void open(int taskNumber, int numTasks) throws IOException { LOG.info("subtask[{}] open start", taskNumber); this.taskNumber = taskNumber; context = (StreamingRuntimeContext) getRuntimeContext(); this.numTasks = numTasks; initStatisticsAccumulator(); initJobInfo(); if (initAccumulatorAndDirty) { initAccumulatorCollector(); openErrorLimiter(); openDirtyDataManager(); } initRestoreInfo(); if(needWaitBeforeOpenInternal()) { beforeOpenInternal(); waitWhile("#1"); } openInternal(taskNumber, numTasks); if(needWaitBeforeWriteRecords()) { beforeWriteRecords(); waitWhile("#2"); } } private void initAccumulatorCollector(){ accumulatorCollector = new AccumulatorCollector(jobId, monitorUrl, getRuntimeContext(), 2,
/* * 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 com.dtstack.flinkx.outputformat; /** * Abstract Specification for all the OutputFormat defined in flinkx plugins * * Company: www.dtstack.com * @author huyifan.zju@163.com */ public abstract class BaseRichOutputFormat extends org.apache.flink.api.common.io.RichOutputFormat<Row> implements CleanupWhenUnsuccessful { protected final Logger LOG = LoggerFactory.getLogger(getClass()); protected String formatId; public static final String RUNNING_STATE = "RUNNING"; public static final int LOG_PRINT_INTERNAL = 2000; /** Dirty data manager */ protected DirtyDataManager dirtyDataManager; /** Dirty data storage path */ protected String dirtyPath; /** The hadoop config for dirty data storage */ protected Map<String,Object> dirtyHadoopConfig; /** The source table field names */ protected List<String> srcFieldNames; /** 批量提交条数 */ protected int batchInterval = 1; /** 存储用于批量写入的数据 */ protected List<Row> rows = new ArrayList(); /** 总记录数 */ protected LongCounter numWriteCounter; /** snapshot 中记录的总记录数 */ protected LongCounter snapshotWriteCounter; /** 错误记录数 */ protected LongCounter errCounter; /** Number of null pointer errors */ protected LongCounter nullErrCounter; /** Number of primary key conflict errors */ protected LongCounter duplicateErrCounter; /** Number of type conversion errors */ protected LongCounter conversionErrCounter; /** Number of other errors */ protected LongCounter otherErrCounter; /** 错误限制 */ protected ErrorLimiter errorLimiter; protected LongCounter bytesWriteCounter; protected LongCounter durationCounter; /** 错误阈值 */ protected Integer errors; /** 错误比例阈值 */ protected Double errorRatio; /** 批异常重试机制 */ protected String errorTryPlan; /** 任务名 */ protected String jobName = "defaultJobName"; /** 监控api根路径 */ protected String monitorUrl; /** 子任务编号 */ protected int taskNumber; /** 环境上下文 */ protected StreamingRuntimeContext context; /** 子任务数量 */ protected int numTasks; protected String jobId; protected RestoreConfig restoreConfig; protected FormatState formatState; protected Object initState; protected transient BaseMetric outputMetric; protected AccumulatorCollector accumulatorCollector; private long startTime; protected boolean initAccumulatorAndDirty = true; protected RateCounter rateCounter; protected final static String rateCounterName = "Writer"; public String getDirtyPath() { return dirtyPath; } public void setDirtyPath(String dirtyPath) { this.dirtyPath = dirtyPath; } public Map<String, Object> getDirtyHadoopConfig() { return dirtyHadoopConfig; } public void setDirtyHadoopConfig(Map<String, Object> dirtyHadoopConfig) { this.dirtyHadoopConfig = dirtyHadoopConfig; } public void setDirtyDataManager(DirtyDataManager dirtyDataManager) { this.dirtyDataManager = dirtyDataManager; } public void setErrorLimiter(ErrorLimiter errorLimiter) { this.errorLimiter = errorLimiter; } public void setSrcFieldNames(List<String> srcFieldNames) { this.srcFieldNames = srcFieldNames; } @Override public void configure(Configuration parameters) { // do nothing } /** * 子类实现,打开资源 * * @param taskNumber 通道索引 * @param numTasks 通道数量 * @throws IOException */ protected abstract void openInternal(int taskNumber, int numTasks) throws IOException; /** * 打开资源的前后做一些初始化操作 * * @param taskNumber The number of the parallel instance. * @param numTasks The number of parallel tasks. * @throws IOException */ @Override public void open(int taskNumber, int numTasks) throws IOException { LOG.info("subtask[{}] open start", taskNumber); this.taskNumber = taskNumber; context = (StreamingRuntimeContext) getRuntimeContext(); this.numTasks = numTasks; initStatisticsAccumulator(); initJobInfo(); if (initAccumulatorAndDirty) { initAccumulatorCollector(); openErrorLimiter(); openDirtyDataManager(); } initRestoreInfo(); if(needWaitBeforeOpenInternal()) { beforeOpenInternal(); waitWhile("#1"); } openInternal(taskNumber, numTasks); if(needWaitBeforeWriteRecords()) { beforeWriteRecords(); waitWhile("#2"); } } private void initAccumulatorCollector(){ accumulatorCollector = new AccumulatorCollector(jobId, monitorUrl, getRuntimeContext(), 2,
Arrays.asList(Metrics.NUM_ERRORS,
2
2023-11-16 02:22:52+00:00
16k
kotmatross28729/EnviroMine-continuation
src/main/java/enviromine/core/commands/QuakeCommand.java
[ { "identifier": "EnumLogVerbosity", "path": "src/main/java/enviromine/core/EM_ConfigHandler.java", "snippet": "public enum EnumLogVerbosity\n{\n\tNONE(0),\n\tLOW(1),\n\tNORMAL(2),\n\tALL(3);\n\n\tprivate final int level;\n\n\tprivate EnumLogVerbosity(int level)\n\t{\n\t\tthis.level = level;\n\t}\n\n\tpu...
import java.util.Iterator; import org.apache.logging.log4j.Level; import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint; import enviromine.core.EM_ConfigHandler.EnumLogVerbosity; import enviromine.core.EM_Settings; import enviromine.core.EnviroMine; import enviromine.network.packet.PacketEnviroMine; import enviromine.world.Earthquake; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChatComponentText; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MathHelper; import net.minecraft.util.StatCollector; import net.minecraft.world.World;
11,080
package enviromine.core.commands; public class QuakeCommand extends CommandBase { private String lengthName = StatCollector.translateToLocal("commands.enviromine.enviroquake.length"); private String widthName = StatCollector.translateToLocal("commands.enviromine.enviroquake.width"); private String rotationName = StatCollector.translateToLocal("commands.enviromine.enviroquake.rotation"); private String modeName = StatCollector.translateToLocal("commands.enviromine.enviroquake.mode"); private String stopName = StatCollector.translateToLocal("commands.enviromine.enviroquake.stop"); private String stoppedAll = StatCollector.translateToLocal("commands.enviromine.enviroquake.stoppedAll"); private String errorMany = StatCollector.translateToLocal("commands.enviromine.enviroquake.error.tooMany"); private String errorBig = StatCollector.translateToLocal("commands.enviromine.enviroquake.error.tooBig"); @Override public String getCommandName() { return "enviroquake"; } @Override public String getCommandUsage(ICommandSender p_71518_1_) { return "/enviroquake ["+stopName+" | <x> <z> [<"+lengthName+"> <"+widthName+"> <"+rotationName+"> <"+modeName+"(0 ~ 4)>]]"; } public void ShowUsage(ICommandSender sender) { sender.addChatMessage(new ChatComponentText(getCommandUsage(sender))); } @Override public int getRequiredPermissionLevel() { return 4; } @Override public void processCommand(ICommandSender sender, String[] astring) { if(astring.length != 0 && astring.length != 1 && astring.length != 2 && astring.length != 6) { this.ShowUsage(sender); return; } if(astring.length == 1) { if(astring[0].equalsIgnoreCase(stopName)) { Iterator<Earthquake> iterator = Earthquake.pendingQuakes.iterator(); while(iterator.hasNext()) { Earthquake quake = iterator.next(); int size = quake.length > quake.width? quake.length/2 : quake.width/2; NBTTagCompound pData = new NBTTagCompound(); pData.setInteger("id", 3); pData.setInteger("dimension", quake.world.provider.dimensionId); pData.setInteger("posX", quake.posX); pData.setInteger("posZ", quake.posZ); pData.setInteger("length", quake.length); pData.setInteger("width", quake.width); pData.setFloat("angle", quake.angle); pData.setFloat("action", 2); pData.setFloat("height", quake.passY);
package enviromine.core.commands; public class QuakeCommand extends CommandBase { private String lengthName = StatCollector.translateToLocal("commands.enviromine.enviroquake.length"); private String widthName = StatCollector.translateToLocal("commands.enviromine.enviroquake.width"); private String rotationName = StatCollector.translateToLocal("commands.enviromine.enviroquake.rotation"); private String modeName = StatCollector.translateToLocal("commands.enviromine.enviroquake.mode"); private String stopName = StatCollector.translateToLocal("commands.enviromine.enviroquake.stop"); private String stoppedAll = StatCollector.translateToLocal("commands.enviromine.enviroquake.stoppedAll"); private String errorMany = StatCollector.translateToLocal("commands.enviromine.enviroquake.error.tooMany"); private String errorBig = StatCollector.translateToLocal("commands.enviromine.enviroquake.error.tooBig"); @Override public String getCommandName() { return "enviroquake"; } @Override public String getCommandUsage(ICommandSender p_71518_1_) { return "/enviroquake ["+stopName+" | <x> <z> [<"+lengthName+"> <"+widthName+"> <"+rotationName+"> <"+modeName+"(0 ~ 4)>]]"; } public void ShowUsage(ICommandSender sender) { sender.addChatMessage(new ChatComponentText(getCommandUsage(sender))); } @Override public int getRequiredPermissionLevel() { return 4; } @Override public void processCommand(ICommandSender sender, String[] astring) { if(astring.length != 0 && astring.length != 1 && astring.length != 2 && astring.length != 6) { this.ShowUsage(sender); return; } if(astring.length == 1) { if(astring[0].equalsIgnoreCase(stopName)) { Iterator<Earthquake> iterator = Earthquake.pendingQuakes.iterator(); while(iterator.hasNext()) { Earthquake quake = iterator.next(); int size = quake.length > quake.width? quake.length/2 : quake.width/2; NBTTagCompound pData = new NBTTagCompound(); pData.setInteger("id", 3); pData.setInteger("dimension", quake.world.provider.dimensionId); pData.setInteger("posX", quake.posX); pData.setInteger("posZ", quake.posZ); pData.setInteger("length", quake.length); pData.setInteger("width", quake.width); pData.setFloat("angle", quake.angle); pData.setFloat("action", 2); pData.setFloat("height", quake.passY);
EnviroMine.instance.network.sendToAllAround(new PacketEnviroMine(pData), new TargetPoint(quake.world.provider.dimensionId, quake.posX, quake.passY, quake.posZ, 128 + size));
3
2023-11-16 18:15:29+00:00
16k
exadel-inc/etoolbox-anydiff
core/src/test/java/com/exadel/etoolbox/anydiff/AllTests.java
[ { "identifier": "DiffBlockXPathTest", "path": "core/src/test/java/com/exadel/etoolbox/anydiff/comparison/DiffBlockXPathTest.java", "snippet": "public class DiffBlockXPathTest {\n\n @Test\n public void shouldReportHtmlPath() throws IOException {\n try (\n InputStream leftInput...
import com.exadel.etoolbox.anydiff.comparison.DiffBlockXPathTest; import com.exadel.etoolbox.anydiff.comparison.DiffCountTest; import com.exadel.etoolbox.anydiff.comparison.DiffTaskTest; import com.exadel.etoolbox.anydiff.comparison.DiffTest; import com.exadel.etoolbox.anydiff.comparison.FragmentTest; import com.exadel.etoolbox.anydiff.comparison.MarkedStringTest; import com.exadel.etoolbox.anydiff.comparison.SpacesHandlingTest; import com.exadel.etoolbox.anydiff.comparison.preprocessor.PreprocessorsTest; import com.exadel.etoolbox.anydiff.runner.DiffRunnerTest; import com.exadel.etoolbox.anydiff.runner.FilterHelperTest; import com.exadel.etoolbox.anydiff.runner.FiltersTest; import org.junit.runner.RunWith; import org.junit.runners.Suite;
14,064
/* * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exadel.etoolbox.anydiff; @RunWith(Suite.class) @Suite.SuiteClasses({
/* * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exadel.etoolbox.anydiff; @RunWith(Suite.class) @Suite.SuiteClasses({
DiffTest.class,
3
2023-11-16 14:29:45+00:00
16k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/capability/CapabilityHandler.java
[ { "identifier": "ClientProxy", "path": "src/main/java/sheridan/gunscraft/ClientProxy.java", "snippet": "public class ClientProxy extends CommonProxy{\n\n public static HashMap<Item, TransformData> transformDataMap = new HashMap<>();\n public static HashMap<Item, IGunModel> gunModelMap = new HashMa...
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.google.common.collect.ImmutableList; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.nbt.ListNBT; import net.minecraft.network.PacketBuffer; import net.minecraft.util.Direction; import net.minecraft.util.ResourceLocation; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.CapabilityManager; import net.minecraftforge.common.capabilities.ICapabilitySerializable; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.network.PacketDistributor; import org.apache.commons.lang3.Validate; import sheridan.gunscraft.ClientProxy; import sheridan.gunscraft.Gunscraft; import sheridan.gunscraft.animation.recoilAnimation.RecoilAnimationHandler; import sheridan.gunscraft.events.RenderEvents; import sheridan.gunscraft.network.LoginPacks; import sheridan.gunscraft.network.PacketHandler; import sheridan.gunscraft.network.packets.SyncPlayerDataPacket;
11,644
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package sheridan.gunscraft.capability; public class CapabilityHandler { @CapabilityInject(PlayerDataManager.class) public static final Capability<PlayerDataManager> CAPABILITY = null; public static CapabilityHandler INSTANCE; private static boolean init = false; public boolean dataChanged = false; private final Map<ResourceLocation, CapabilityKey<?>> keyMap = new HashMap<>(); private final Map<Integer, CapabilityKey<?>> keyIdMap = new HashMap<>(); private int nextKeyId = 0; private CapabilityHandler() {} public static CapabilityHandler getInstance() { if(INSTANCE == null) { INSTANCE = new CapabilityHandler(); } return INSTANCE; } public static void init() { if(!init) { CapabilityManager.INSTANCE.register(PlayerDataManager.class, new Storage(), PlayerDataManager::new); MinecraftForge.EVENT_BUS.register(getInstance()); init = true; } } public void registerKey(CapabilityKey<?> key) { if(!this.keyMap.containsKey(key.getKey())) { int nextId = this.nextKeyId++; key.setId(nextId); this.keyMap.put(key.getKey(), key); this.keyIdMap.put(nextId, key); } } public <T> void set(PlayerEntity player, CapabilityKey<T> key, T value) { if(this.keyMap.containsValue(key)) { PlayerDataManager manager = this.getDataManager(player); if(manager != null && manager.set(player, key, value)) { if(!player.world.isRemote) { this.dataChanged = true; } } } } public <T> T get(PlayerEntity player, CapabilityKey<T> key) { if(this.keyMap.containsValue(key)) { PlayerDataManager manager = this.getDataManager(player); return manager != null ? manager.get(key) : key.getDefaultValueSupplier().get(); } return null; } @OnlyIn(Dist.CLIENT) public <T> void updateClientData(PlayerEntity player, Pair<T> entry) { CapabilityHandler.getInstance().set(player, entry.getKey(), entry.getValue()); } @Nullable public CapabilityKey<?> getKey(int id) { return this.keyIdMap.get(id); } public List<CapabilityKey<?>> getKeys() { return ImmutableList.copyOf(this.keyMap.values()); } @Nullable private PlayerDataManager getDataManager(PlayerEntity player) { return player.getCapability(CAPABILITY, null).orElse(null); } @SubscribeEvent public void attachCapabilities(AttachCapabilitiesEvent<Entity> event) { if(event.getObject() instanceof PlayerEntity) {
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by FernFlower decompiler) // package sheridan.gunscraft.capability; public class CapabilityHandler { @CapabilityInject(PlayerDataManager.class) public static final Capability<PlayerDataManager> CAPABILITY = null; public static CapabilityHandler INSTANCE; private static boolean init = false; public boolean dataChanged = false; private final Map<ResourceLocation, CapabilityKey<?>> keyMap = new HashMap<>(); private final Map<Integer, CapabilityKey<?>> keyIdMap = new HashMap<>(); private int nextKeyId = 0; private CapabilityHandler() {} public static CapabilityHandler getInstance() { if(INSTANCE == null) { INSTANCE = new CapabilityHandler(); } return INSTANCE; } public static void init() { if(!init) { CapabilityManager.INSTANCE.register(PlayerDataManager.class, new Storage(), PlayerDataManager::new); MinecraftForge.EVENT_BUS.register(getInstance()); init = true; } } public void registerKey(CapabilityKey<?> key) { if(!this.keyMap.containsKey(key.getKey())) { int nextId = this.nextKeyId++; key.setId(nextId); this.keyMap.put(key.getKey(), key); this.keyIdMap.put(nextId, key); } } public <T> void set(PlayerEntity player, CapabilityKey<T> key, T value) { if(this.keyMap.containsValue(key)) { PlayerDataManager manager = this.getDataManager(player); if(manager != null && manager.set(player, key, value)) { if(!player.world.isRemote) { this.dataChanged = true; } } } } public <T> T get(PlayerEntity player, CapabilityKey<T> key) { if(this.keyMap.containsValue(key)) { PlayerDataManager manager = this.getDataManager(player); return manager != null ? manager.get(key) : key.getDefaultValueSupplier().get(); } return null; } @OnlyIn(Dist.CLIENT) public <T> void updateClientData(PlayerEntity player, Pair<T> entry) { CapabilityHandler.getInstance().set(player, entry.getKey(), entry.getValue()); } @Nullable public CapabilityKey<?> getKey(int id) { return this.keyIdMap.get(id); } public List<CapabilityKey<?>> getKeys() { return ImmutableList.copyOf(this.keyMap.values()); } @Nullable private PlayerDataManager getDataManager(PlayerEntity player) { return player.getCapability(CAPABILITY, null).orElse(null); } @SubscribeEvent public void attachCapabilities(AttachCapabilitiesEvent<Entity> event) { if(event.getObject() instanceof PlayerEntity) {
event.addCapability(new ResourceLocation(Gunscraft.MOD_ID, "sync_player_data"), new CapabilityProvider());
1
2023-11-14 14:00:55+00:00
16k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/fragments/APKExplorerFragment.java
[ { "identifier": "TextEditorActivity", "path": "app/src/main/java/com/threethan/questpatcher/activities/TextEditorActivity.java", "snippet": "public class TextEditorActivity extends AppCompatActivity {\n\n private static final String find0 = \"android:extractNativeLibs=\\\"false\\\"\";\n private st...
import android.annotation.SuppressLint; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import androidx.activity.OnBackPressedCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.AppCompatImageButton; import androidx.appcompat.widget.LinearLayoutCompat; import androidx.appcompat.widget.PopupMenu; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.threethan.questpatcher.R; import com.threethan.questpatcher.activities.TextEditorActivity; import com.threethan.questpatcher.adapters.APKExplorerAdapter; import com.threethan.questpatcher.utils.APKEditorUtils; import com.threethan.questpatcher.utils.APKExplorer; import com.threethan.questpatcher.utils.Common; import com.threethan.questpatcher.utils.tasks.DeleteFile; import com.threethan.questpatcher.utils.tasks.DeleteProject; import com.threethan.questpatcher.utils.tasks.ExportToStorage; import com.threethan.questpatcher.utils.tasks.SignAPK; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.textview.MaterialTextView; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.util.Objects; import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils; import in.sunilpaulmathew.sCommon.CommonUtils.sExecutor; import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils; import in.sunilpaulmathew.sCommon.PermissionUtils.sPermissionUtils;
11,656
View mRootView = inflater.inflate(R.layout.fragment_apkexplorer, container, false); AppCompatImageButton mBack = mRootView.findViewById(R.id.back); AppCompatImageButton mSave = mRootView.findViewById(R.id.save); // EDITED saveBtn = mSave; AppCompatImageButton mSortButton = mRootView.findViewById(R.id.sort); mTitle = mRootView.findViewById(R.id.title); mProgressLayout = mRootView.findViewById(R.id.progress_layout); mRecyclerView = mRootView.findViewById(R.id.recycler_view); Common.setAppID(new File(Common.getPath()).getName()); mTitle.setText(getString(R.string.root)); mBack.setOnClickListener(v -> retainDialog()); mSave.setOnClickListener(v -> new SignAPK(requireActivity()).execute()); if (APKEditorUtils.isFullVersion(requireActivity())) { mSave.setVisibility(View.VISIBLE); } mRecyclerView.setLayoutManager(new GridLayoutManager(requireActivity(), APKExplorer.getSpanCount(requireActivity()))); // CHANGED: AUTOMATE current = this; Intent amintent; boolean hasOpened = false; amintent = new Intent(requireActivity(), TextEditorActivity.class); for (String file : APKExplorer.getData(getFilesList(), true, requireActivity())) { if (file != null && file.endsWith("AndroidManifest.xml")) { amintent.putExtra(TextEditorActivity.PATH_INTENT, file); startActivity(amintent); hasOpened = true; break; } } // succeed(); if (!hasOpened) failManifest(); mSortButton.setOnClickListener(v -> { PopupMenu popupMenu = new PopupMenu(requireActivity(), mSortButton); Menu menu = popupMenu.getMenu(); menu.add(Menu.NONE, 0, Menu.NONE, getString(R.string.sort_order)).setCheckable(true) .setChecked(sCommonUtils.getBoolean("az_order", true, requireActivity())); if (Common.getFiles() != null && Common.getFiles().size() > 0) { menu.add(Menu.NONE, 1, Menu.NONE, getString(R.string.export_selected_files)); if (APKEditorUtils.isFullVersion(requireActivity())) { menu.add(Menu.NONE, 2, Menu.NONE, getString(R.string.delete_selected_files)); } } if (APKEditorUtils.isFullVersion(requireActivity()) && !Objects.requireNonNull(new File(Common.getPath()).getParentFile()).getPath().equals(requireActivity().getCacheDir().getPath())) { menu.add(Menu.NONE, 3, Menu.NONE, getString(R.string.delete_folder)); } popupMenu.setOnMenuItemClickListener(item -> { if (item.getItemId() == 0) { sCommonUtils.saveBoolean("az_order", !sCommonUtils.getBoolean("az_order", true, requireActivity()), requireActivity()); reload(requireActivity()); } else if (item.getItemId() == 1) { if (Build.VERSION.SDK_INT < 29 && sPermissionUtils.isPermissionDenied(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, v.getContext())) { sPermissionUtils.requestPermission( new String[] { android.Manifest.permission.WRITE_EXTERNAL_STORAGE }, (Activity) v.getContext()); } else { new ExportToStorage(null, Common.getFiles(), Common.getAppID(), requireActivity()).execute(); } } else if (item.getItemId() == 2) { for (File file : Common.getFiles()) { if (file.exists()) { new DeleteFile(file, v.getContext()) { @Override public void onPostExecute() { reload(requireActivity()); } }.execute(); } } } else if (item.getItemId() == 3) { new DeleteFile(new File(Common.getPath()), v.getContext()) { @Override public void onPostExecute() { Common.setPath(Objects.requireNonNull(new File(Common.getPath()).getParentFile()).getPath()); Common.clearFilesList(); reload(requireActivity()); } }.execute(); } return false; }); popupMenu.show(); }); requireActivity().getOnBackPressedDispatcher().addCallback(new OnBackPressedCallback(true) { @Override public void handleOnBackPressed() { if (Objects.requireNonNull(new File(Common.getPath()).getParentFile()).getPath().equals(requireActivity().getCacheDir().getPath())) { retainDialog(); } else { Common.setPath(Objects.requireNonNull(new File(Common.getPath()).getParentFile()).getPath()); Common.clearFilesList(); reload(requireActivity()); } } }); return mRootView; } private void retainDialog() { if (sCommonUtils.getString("projectAction", null, requireActivity()) == null) { new MaterialAlertDialogBuilder(requireActivity()) .setIcon(R.mipmap.ic_launcher) .setTitle(R.string.app_name) .setMessage(R.string.save_projects_question) .setNeutralButton(getString(R.string.cancel), (dialog, id) -> { }) .setNegativeButton(getString(R.string.discard), (dialog, id) -> {
package com.threethan.questpatcher.fragments; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 05, 2021 */ public class APKExplorerFragment extends androidx.fragment.app.Fragment { private MaterialTextView mTitle; private LinearLayoutCompat mProgressLayout; private RecyclerView mRecyclerView; private APKExplorerAdapter mRecycleViewAdapter; private AppCompatImageButton saveBtn; public static APKExplorerFragment current; public void fail() { AlertDialog alertDialog = new MaterialAlertDialogBuilder(requireActivity()) .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) (d, w) -> { requireActivity().finish(); d.dismiss(); }).create(); alertDialog.setTitle(R.string.cancelling); alertDialog.setMessage(getString(R.string.already_patched)); alertDialog.show(); } public void failManifest() { AlertDialog alertDialog = new MaterialAlertDialogBuilder(requireActivity()) .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) (d, w) -> { requireActivity().finish(); d.dismiss(); }).create(); alertDialog.setTitle(R.string.cancelling); alertDialog.setMessage(getString(R.string.no_manifest)); alertDialog.show(); } public void succeed() { saveBtn.callOnClick(); } @SuppressLint("StringFormatInvalid") @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View mRootView = inflater.inflate(R.layout.fragment_apkexplorer, container, false); AppCompatImageButton mBack = mRootView.findViewById(R.id.back); AppCompatImageButton mSave = mRootView.findViewById(R.id.save); // EDITED saveBtn = mSave; AppCompatImageButton mSortButton = mRootView.findViewById(R.id.sort); mTitle = mRootView.findViewById(R.id.title); mProgressLayout = mRootView.findViewById(R.id.progress_layout); mRecyclerView = mRootView.findViewById(R.id.recycler_view); Common.setAppID(new File(Common.getPath()).getName()); mTitle.setText(getString(R.string.root)); mBack.setOnClickListener(v -> retainDialog()); mSave.setOnClickListener(v -> new SignAPK(requireActivity()).execute()); if (APKEditorUtils.isFullVersion(requireActivity())) { mSave.setVisibility(View.VISIBLE); } mRecyclerView.setLayoutManager(new GridLayoutManager(requireActivity(), APKExplorer.getSpanCount(requireActivity()))); // CHANGED: AUTOMATE current = this; Intent amintent; boolean hasOpened = false; amintent = new Intent(requireActivity(), TextEditorActivity.class); for (String file : APKExplorer.getData(getFilesList(), true, requireActivity())) { if (file != null && file.endsWith("AndroidManifest.xml")) { amintent.putExtra(TextEditorActivity.PATH_INTENT, file); startActivity(amintent); hasOpened = true; break; } } // succeed(); if (!hasOpened) failManifest(); mSortButton.setOnClickListener(v -> { PopupMenu popupMenu = new PopupMenu(requireActivity(), mSortButton); Menu menu = popupMenu.getMenu(); menu.add(Menu.NONE, 0, Menu.NONE, getString(R.string.sort_order)).setCheckable(true) .setChecked(sCommonUtils.getBoolean("az_order", true, requireActivity())); if (Common.getFiles() != null && Common.getFiles().size() > 0) { menu.add(Menu.NONE, 1, Menu.NONE, getString(R.string.export_selected_files)); if (APKEditorUtils.isFullVersion(requireActivity())) { menu.add(Menu.NONE, 2, Menu.NONE, getString(R.string.delete_selected_files)); } } if (APKEditorUtils.isFullVersion(requireActivity()) && !Objects.requireNonNull(new File(Common.getPath()).getParentFile()).getPath().equals(requireActivity().getCacheDir().getPath())) { menu.add(Menu.NONE, 3, Menu.NONE, getString(R.string.delete_folder)); } popupMenu.setOnMenuItemClickListener(item -> { if (item.getItemId() == 0) { sCommonUtils.saveBoolean("az_order", !sCommonUtils.getBoolean("az_order", true, requireActivity()), requireActivity()); reload(requireActivity()); } else if (item.getItemId() == 1) { if (Build.VERSION.SDK_INT < 29 && sPermissionUtils.isPermissionDenied(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, v.getContext())) { sPermissionUtils.requestPermission( new String[] { android.Manifest.permission.WRITE_EXTERNAL_STORAGE }, (Activity) v.getContext()); } else { new ExportToStorage(null, Common.getFiles(), Common.getAppID(), requireActivity()).execute(); } } else if (item.getItemId() == 2) { for (File file : Common.getFiles()) { if (file.exists()) { new DeleteFile(file, v.getContext()) { @Override public void onPostExecute() { reload(requireActivity()); } }.execute(); } } } else if (item.getItemId() == 3) { new DeleteFile(new File(Common.getPath()), v.getContext()) { @Override public void onPostExecute() { Common.setPath(Objects.requireNonNull(new File(Common.getPath()).getParentFile()).getPath()); Common.clearFilesList(); reload(requireActivity()); } }.execute(); } return false; }); popupMenu.show(); }); requireActivity().getOnBackPressedDispatcher().addCallback(new OnBackPressedCallback(true) { @Override public void handleOnBackPressed() { if (Objects.requireNonNull(new File(Common.getPath()).getParentFile()).getPath().equals(requireActivity().getCacheDir().getPath())) { retainDialog(); } else { Common.setPath(Objects.requireNonNull(new File(Common.getPath()).getParentFile()).getPath()); Common.clearFilesList(); reload(requireActivity()); } } }); return mRootView; } private void retainDialog() { if (sCommonUtils.getString("projectAction", null, requireActivity()) == null) { new MaterialAlertDialogBuilder(requireActivity()) .setIcon(R.mipmap.ic_launcher) .setTitle(R.string.app_name) .setMessage(R.string.save_projects_question) .setNeutralButton(getString(R.string.cancel), (dialog, id) -> { }) .setNegativeButton(getString(R.string.discard), (dialog, id) -> {
new DeleteProject(new File(requireActivity().getCacheDir(), Common.getAppID()), requireActivity()).execute();
6
2023-11-18 15:13:30+00:00
16k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/security/rest/AuthorizationController.java
[ { "identifier": "RsaProperties", "path": "dimple-common/src/main/java/com/dimple/config/RsaProperties.java", "snippet": "@Data\n@Component\npublic class RsaProperties {\n\n public static String privateKey;\n\n @Value(\"${rsa.private_key}\")\n public void setPrivateKey(String privateKey) {\n ...
import cn.hutool.core.util.IdUtil; import com.dimple.annotation.OLog; import com.dimple.annotation.rest.AnonymousDeleteMapping; import com.dimple.annotation.rest.AnonymousGetMapping; import com.dimple.annotation.rest.AnonymousPostMapping; import com.dimple.config.RsaProperties; import com.dimple.exception.BadRequestException; import com.dimple.modules.security.config.bean.LoginProperties; import com.dimple.modules.security.config.bean.SecurityProperties; import com.dimple.modules.security.security.TokenProvider; import com.dimple.modules.security.service.OnlineUserService; import com.dimple.modules.security.service.dto.AuthUserDTO; import com.dimple.modules.security.service.dto.JwtUserDTO; import com.dimple.service.LoginLogService; import com.dimple.utils.RedisUtils; import com.dimple.utils.RsaUtils; import com.dimple.utils.SecurityUtils; import com.dimple.utils.StringUtils; import com.wf.captcha.base.Captcha; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit;
11,820
package com.dimple.modules.security.rest; /** * @className: AuthorizationController * @description: * @author: Dimple * @date: 06/17/20 */ @Slf4j @RestController @RequestMapping("/auth") @RequiredArgsConstructor @Api(tags = "系统:系统授权接口") public class AuthorizationController { private final SecurityProperties properties; private final RedisUtils redisUtils; private final OnlineUserService onlineUserService; private final TokenProvider tokenProvider; private final AuthenticationManagerBuilder authenticationManagerBuilder; private final LoginLogService loginLogService; @Resource
package com.dimple.modules.security.rest; /** * @className: AuthorizationController * @description: * @author: Dimple * @date: 06/17/20 */ @Slf4j @RestController @RequestMapping("/auth") @RequiredArgsConstructor @Api(tags = "系统:系统授权接口") public class AuthorizationController { private final SecurityProperties properties; private final RedisUtils redisUtils; private final OnlineUserService onlineUserService; private final TokenProvider tokenProvider; private final AuthenticationManagerBuilder authenticationManagerBuilder; private final LoginLogService loginLogService; @Resource
private LoginProperties loginProperties;
2
2023-11-10 03:30:36+00:00
16k
LazyCoder0101/LazyCoder
ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/modulemanagement/editframe/ModuleEditFrame.java
[ { "identifier": "NotNamed", "path": "database/src/main/java/com/lazycoder/database/common/NotNamed.java", "snippet": "public enum NotNamed {\n\n\tnonModule(\"非模块\", \"非模块\", null), // 非模块没有模块名\n\n\tgeneral(\"通用\", \"通用\", \"通用\"), // 通用选项\n\n\tmain(\"必填模板\", \"main\", \"main\"),\n\n\tmainSet(\"必填模板设置\",...
import com.lazycoder.database.common.NotNamed; import com.lazycoder.database.model.Module; import com.lazycoder.service.service.SysService; import com.lazycoder.uidatasourceedit.DataSourceEditHolder; import com.lazycoder.uidatasourceedit.ModuleEditPaneHolder; import com.lazycoder.uiutils.mycomponent.LazyCoderCommonDialog; import com.lazycoder.uiutils.mycomponent.MyButton; import com.lazycoder.uiutils.utils.SysUtil; import com.lazycoder.utils.RealNumberUtil; import com.lazycoder.utils.swing.LazyCoderOptionPane; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.EmptyBorder;
11,212
package com.lazycoder.uidatasourceedit.modulemanagement.editframe; public class ModuleEditFrame extends LazyCoderCommonDialog { /** * */ private static final long serialVersionUID = 8358412199068941740L; private final boolean addType = true; private final boolean updateType = false; private boolean type = addType; private JPanel contentPane; private JTextField moduleNameTextField, ordinalTextField, noteTextField;//classShowTextField = null; private MyButton ok, cancel; private ModuleEditFrameClassCombobox combobox = null; private JLabel clabel; private Module module = null; /** * 更改时用 */ private String oldName; /** * 添加模块 */ public ModuleEditFrame() { this.type = addType; init(); setTitle("添加模块"); combobox = new ModuleEditFrameClassCombobox(); combobox.updateItems(); combobox.setBounds(148, 30, 240, 30); contentPane.add(combobox); ordinalTextField.setText(1 + ""); ok.addActionListener(addListener); cancel.addActionListener(addListener); this.setVisible(true); } /** * 更新模块 * * @param module */ public ModuleEditFrame(Module module) { this.type = updateType; this.module = module; init(); setTitle("修改模块"); // classShowTextField = new JTextField(); // classShowTextField.setEditable(false); // classShowTextField.setBounds(148, 30, 100, 30); // contentPane.add(classShowTextField); combobox = new ModuleEditFrameClassCombobox(); combobox.updateItems(); combobox.setBounds(148, 30, 240, 30); contentPane.add(combobox); oldName = module.getModuleName(); moduleNameTextField.setText(module.getModuleName()); // classShowTextField.setText(module.getClassName()); combobox.setSelectedItem(module.getClassName()); ordinalTextField.setText(module.getIndexParam() + ""); noteTextField.setText(module.getNote()); ok.addActionListener(updateListener); cancel.addActionListener(updateListener); this.setVisible(true); } private ActionListener addListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getSource() == ok) { addModule(); // DatabaseFrameFileMethod.generateOrCheckModuleFileStrucure(databaseName, // className, moduleName); } else if (e.getSource() == cancel) { dispose(); } } }; private ActionListener updateListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getSource() == ok) { updateModule(); } else if (e.getSource() == cancel) { dispose(); } } }; /** * Launch the application. */ // public static void main(String[] args) { // EventQueue.invokeLater(new Runnable() { // public void run() { // try { // ModuleEditFrame frame = new ModuleEditFrame(); // frame.setVisible(true); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } /** * Create the frame. */ public void init() { contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel label = new JLabel("请输入模块名:"); label.setBounds(35, 85, 115, 30); contentPane.add(label); moduleNameTextField = new JTextField(); moduleNameTextField.setBounds(148, 85, 240, 30); contentPane.add(moduleNameTextField); moduleNameTextField.setColumns(10); JLabel plabel = new JLabel("排序:"); plabel.setBounds(35, 128, 72, 30); contentPane.add(plabel); ordinalTextField = new JTextField(); ordinalTextField.setBounds(148, 139, 100, 30); contentPane.add(ordinalTextField); ordinalTextField.setColumns(10); ok = new MyButton("确定"); ok.setBounds(70, 243, 100, 30); contentPane.add(ok); cancel = new MyButton("取消"); cancel.setBounds(260, 243, 100, 30); contentPane.add(cancel); JLabel nlabel = new JLabel("备注:"); nlabel.setBounds(35, 195, 60, 18); contentPane.add(nlabel); noteTextField = new JTextField(); noteTextField.setBounds(100, 189, 300, 30); contentPane.add(noteTextField); clabel = new JLabel("分类名:"); clabel.setBounds(35, 30, 72, 30); contentPane.add(clabel); Dimension dimension = SysUtil.SCREEN_SIZE; setBounds(dimension.width / 2 - 200, dimension.height / 2 - 200, 500, 360); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { ModuleEditFrame.this.dispose(); } }); } private void addModule() { boolean flag = check(); if (flag == true) { String className = (String) combobox.getSelectedItem(), moduleName = moduleNameTextField.getText(), note = noteTextField.getText(); int oridinal = RealNumberUtil.convertedToInteger(ordinalTextField.getText()); SysService.DATABASE_NAME_SERVICE.addModule(className, moduleName, oridinal, note);
package com.lazycoder.uidatasourceedit.modulemanagement.editframe; public class ModuleEditFrame extends LazyCoderCommonDialog { /** * */ private static final long serialVersionUID = 8358412199068941740L; private final boolean addType = true; private final boolean updateType = false; private boolean type = addType; private JPanel contentPane; private JTextField moduleNameTextField, ordinalTextField, noteTextField;//classShowTextField = null; private MyButton ok, cancel; private ModuleEditFrameClassCombobox combobox = null; private JLabel clabel; private Module module = null; /** * 更改时用 */ private String oldName; /** * 添加模块 */ public ModuleEditFrame() { this.type = addType; init(); setTitle("添加模块"); combobox = new ModuleEditFrameClassCombobox(); combobox.updateItems(); combobox.setBounds(148, 30, 240, 30); contentPane.add(combobox); ordinalTextField.setText(1 + ""); ok.addActionListener(addListener); cancel.addActionListener(addListener); this.setVisible(true); } /** * 更新模块 * * @param module */ public ModuleEditFrame(Module module) { this.type = updateType; this.module = module; init(); setTitle("修改模块"); // classShowTextField = new JTextField(); // classShowTextField.setEditable(false); // classShowTextField.setBounds(148, 30, 100, 30); // contentPane.add(classShowTextField); combobox = new ModuleEditFrameClassCombobox(); combobox.updateItems(); combobox.setBounds(148, 30, 240, 30); contentPane.add(combobox); oldName = module.getModuleName(); moduleNameTextField.setText(module.getModuleName()); // classShowTextField.setText(module.getClassName()); combobox.setSelectedItem(module.getClassName()); ordinalTextField.setText(module.getIndexParam() + ""); noteTextField.setText(module.getNote()); ok.addActionListener(updateListener); cancel.addActionListener(updateListener); this.setVisible(true); } private ActionListener addListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getSource() == ok) { addModule(); // DatabaseFrameFileMethod.generateOrCheckModuleFileStrucure(databaseName, // className, moduleName); } else if (e.getSource() == cancel) { dispose(); } } }; private ActionListener updateListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getSource() == ok) { updateModule(); } else if (e.getSource() == cancel) { dispose(); } } }; /** * Launch the application. */ // public static void main(String[] args) { // EventQueue.invokeLater(new Runnable() { // public void run() { // try { // ModuleEditFrame frame = new ModuleEditFrame(); // frame.setVisible(true); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); // } /** * Create the frame. */ public void init() { contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel label = new JLabel("请输入模块名:"); label.setBounds(35, 85, 115, 30); contentPane.add(label); moduleNameTextField = new JTextField(); moduleNameTextField.setBounds(148, 85, 240, 30); contentPane.add(moduleNameTextField); moduleNameTextField.setColumns(10); JLabel plabel = new JLabel("排序:"); plabel.setBounds(35, 128, 72, 30); contentPane.add(plabel); ordinalTextField = new JTextField(); ordinalTextField.setBounds(148, 139, 100, 30); contentPane.add(ordinalTextField); ordinalTextField.setColumns(10); ok = new MyButton("确定"); ok.setBounds(70, 243, 100, 30); contentPane.add(ok); cancel = new MyButton("取消"); cancel.setBounds(260, 243, 100, 30); contentPane.add(cancel); JLabel nlabel = new JLabel("备注:"); nlabel.setBounds(35, 195, 60, 18); contentPane.add(nlabel); noteTextField = new JTextField(); noteTextField.setBounds(100, 189, 300, 30); contentPane.add(noteTextField); clabel = new JLabel("分类名:"); clabel.setBounds(35, 30, 72, 30); contentPane.add(clabel); Dimension dimension = SysUtil.SCREEN_SIZE; setBounds(dimension.width / 2 - 200, dimension.height / 2 - 200, 500, 360); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { ModuleEditFrame.this.dispose(); } }); } private void addModule() { boolean flag = check(); if (flag == true) { String className = (String) combobox.getSelectedItem(), moduleName = moduleNameTextField.getText(), note = noteTextField.getText(); int oridinal = RealNumberUtil.convertedToInteger(ordinalTextField.getText()); SysService.DATABASE_NAME_SERVICE.addModule(className, moduleName, oridinal, note);
LazyCoderOptionPane.showMessageDialog(null, "已添加\"" + moduleName + "\"模块", "系统信息", JOptionPane.PLAIN_MESSAGE);
9
2023-11-16 11:55:06+00:00
16k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/ksx4506/KSMainContext.java
[ { "identifier": "BasicPropertyMap", "path": "app/src/main/java/kr/or/kashi/hde/base/BasicPropertyMap.java", "snippet": "public class BasicPropertyMap extends PropertyMap {\n private final Map<String, PropertyValue> mMap = new ConcurrentHashMap<>();\n\n public BasicPropertyMap() {\n }\n\n pub...
import android.content.Context; import android.os.Handler; import android.util.Log; import kr.or.kashi.hde.base.BasicPropertyMap; import kr.or.kashi.hde.base.PropertyMap; import kr.or.kashi.hde.base.PropertyValue; import kr.or.kashi.hde.DeviceContextBase; import kr.or.kashi.hde.DeviceDiscovery; import kr.or.kashi.hde.HomePacket; import kr.or.kashi.hde.MainContext; import kr.or.kashi.hde.HomeDevice; import kr.or.kashi.hde.device.*; import kr.or.kashi.hde.util.DebugLog; import kr.or.kashi.hde.util.Utils; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
13,997
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.ksx4506; /** * [KS X 4506] The implementation of main context */ public class KSMainContext extends MainContext { private static final String TAG = "KSMainContext"; private static final boolean DBG = true; protected final Map<Integer, Class<?>> mAddressToClassMap = new HashMap<>(); private DeviceDiscovery mDiscovery = null; private final Map<String, HomeDevice> mVirtualDeviceMap = new ConcurrentHashMap<>(); public static int getDeviceIdFromProps(Map props) {
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.ksx4506; /** * [KS X 4506] The implementation of main context */ public class KSMainContext extends MainContext { private static final String TAG = "KSMainContext"; private static final boolean DBG = true; protected final Map<Integer, Class<?>> mAddressToClassMap = new HashMap<>(); private DeviceDiscovery mDiscovery = null; private final Map<String, HomeDevice> mVirtualDeviceMap = new ConcurrentHashMap<>(); public static int getDeviceIdFromProps(Map props) {
PropertyValue propAddr = (PropertyValue) props.get(HomeDevice.PROP_ADDR);
2
2023-11-10 01:19:44+00:00
16k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/client/ui/pluginMenu/MainMenuButton.java
[ { "identifier": "ScreenWidget", "path": "src/main/java/io/xlorey/FluxLoader/client/ui/ScreenWidget.java", "snippet": "public class ScreenWidget implements IWidget {\n /**\n * Flag indicating whether the mouse cursor is inside the widget\n */\n private boolean isWidgetHovered = false;\n\n ...
import imgui.ImGui; import imgui.ImVec2; import imgui.flag.ImGuiCol; import imgui.flag.ImGuiStyleVar; import imgui.flag.ImGuiWindowFlags; import imgui.type.ImBoolean; import io.xlorey.FluxLoader.client.ui.ScreenWidget; import io.xlorey.FluxLoader.utils.Constants; import zombie.GameWindow; import zombie.core.Core; import zombie.gameStates.MainScreenState;
12,862
package io.xlorey.FluxLoader.client.ui.pluginMenu; /** * Implementation of a button to open the plugin control panel */ public class MainMenuButton extends ScreenWidget { /** * Button width */ private final int width = 112; /** * Button height */ private final int height = 26; /** * Horizontal button position */ private int posX = 0; /** * Vertical position of the button */ private int posY = 0; /** * Update button state */ @Override public void update() { super.update(); setVisible(GameWindow.states.current instanceof MainScreenState); posX = Core.getInstance().getScreenWidth() - width - 38; posY = Core.getInstance().getScreenHeight() - height - 70; } /** * Drawing a button in the main menu */ @Override public void render() { ImGui.setNextWindowPos(posX, posY); ImGui.setNextWindowSize(width, height); ImVec2 oldPadding = new ImVec2(); ImGui.getStyle().getWindowPadding(oldPadding); ImGui.getStyle().setWindowPadding(2, 2); ImVec2 oldMinSize = new ImVec2(); ImGui.getStyle().getWindowMinSize(oldMinSize); ImGui.getStyle().setWindowMinSize(5, 5); ImGui.pushStyleColor(ImGuiCol.Border, 0.7f, 0.7f, 0.7f, 1.0f); ImGui.pushStyleVar(ImGuiStyleVar.FrameBorderSize, 1.0f); ImGui.begin("Plugin Menu Button", new ImBoolean(false), ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoBackground); ImGui.pushStyleColor(ImGuiCol.Button, 0.0f, 0.0f, 0.0f, 0.5f); ImGui.pushStyleColor(ImGuiCol.ButtonHovered, 0.5f, 0.5f, 0.5f, 0.5f); ImGui.pushStyleColor(ImGuiCol.ButtonActive, 0.3f, 0.3f, 0.3f, 0.5f); ImGui.pushStyleColor(ImGuiCol.Text, 0.7f, 0.7f, 0.7f, 1.0f);
package io.xlorey.FluxLoader.client.ui.pluginMenu; /** * Implementation of a button to open the plugin control panel */ public class MainMenuButton extends ScreenWidget { /** * Button width */ private final int width = 112; /** * Button height */ private final int height = 26; /** * Horizontal button position */ private int posX = 0; /** * Vertical position of the button */ private int posY = 0; /** * Update button state */ @Override public void update() { super.update(); setVisible(GameWindow.states.current instanceof MainScreenState); posX = Core.getInstance().getScreenWidth() - width - 38; posY = Core.getInstance().getScreenHeight() - height - 70; } /** * Drawing a button in the main menu */ @Override public void render() { ImGui.setNextWindowPos(posX, posY); ImGui.setNextWindowSize(width, height); ImVec2 oldPadding = new ImVec2(); ImGui.getStyle().getWindowPadding(oldPadding); ImGui.getStyle().setWindowPadding(2, 2); ImVec2 oldMinSize = new ImVec2(); ImGui.getStyle().getWindowMinSize(oldMinSize); ImGui.getStyle().setWindowMinSize(5, 5); ImGui.pushStyleColor(ImGuiCol.Border, 0.7f, 0.7f, 0.7f, 1.0f); ImGui.pushStyleVar(ImGuiStyleVar.FrameBorderSize, 1.0f); ImGui.begin("Plugin Menu Button", new ImBoolean(false), ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoBackground); ImGui.pushStyleColor(ImGuiCol.Button, 0.0f, 0.0f, 0.0f, 0.5f); ImGui.pushStyleColor(ImGuiCol.ButtonHovered, 0.5f, 0.5f, 0.5f, 0.5f); ImGui.pushStyleColor(ImGuiCol.ButtonActive, 0.3f, 0.3f, 0.3f, 0.5f); ImGui.pushStyleColor(ImGuiCol.Text, 0.7f, 0.7f, 0.7f, 1.0f);
if (ImGui.button(Constants.FLUX_NAME, -1, -1)) {
1
2023-11-16 09:05:44+00:00
16k
EmonerRobotics/2023Robot
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "IntakeConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class IntakeConstants{\n\n public static final double kEncoderTick2Meter = 1.0 / 4096.0 * 0.1 * Math.PI;\n\n //üst sistem joystick sabitleri\n public static final int Joystick2 = 1; //usb por...
import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab; import edu.wpi.first.wpilibj.smartdashboard.Field2d; import edu.wpi.first.wpilibj.smartdashboard.FieldObject2d; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.RunCommand; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import edu.wpi.first.wpilibj2.command.button.JoystickButton; import frc.robot.Constants.IntakeConstants; import frc.robot.commands.AutoElevator; import frc.robot.commands.AutoIntake; import frc.robot.commands.DriveWithJoysticks; import frc.robot.commands.GetInRange; import frc.robot.commands.IntakeCommand; import frc.robot.commands.LiftCommand; import frc.robot.commands.PneumaticCommand; import frc.robot.commands.AutoElevator.ElevatorPosition; import frc.robot.commands.AutoIntake.IntakePosition; import frc.robot.commands.GetInRange.LimelightPositionCheck; import frc.robot.commands.autonomous.AutoBalance; import frc.robot.commands.autonomous.AutoCommand; import frc.robot.commands.autonomous.OnePieceCharge; import frc.robot.poseestimation.PoseEstimation; import frc.robot.subsystems.IntakeSubsystem; import frc.robot.subsystems.LiftSubsystem; import frc.robot.subsystems.LimelightSubsystem; import frc.robot.subsystems.PneumaticSubsystem; import frc.robot.subsystems.drivetrain.Drivetrain; import frc.robot.utils.AllianceUtils; import com.pathplanner.lib.server.PathPlannerServer;
11,233
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { //Limelight public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem(); //Intake public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); //Pneumatic public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem(); //Lift public static final LiftSubsystem liftSubsystem = new LiftSubsystem(); public static final ShuffleboardTab driveSettingsTab = Shuffleboard.getTab("Drive Settings"); public static final ShuffleboardTab autoTab = Shuffleboard.getTab("Auto"); public static final ShuffleboardTab swerveTab = Shuffleboard.getTab("Swerve"); public static final Joystick joystick1 = new Joystick(0); public static final Joystick joystick2 = new Joystick(IntakeConstants.AngleController); public static final Drivetrain drivetrain = new Drivetrain(); public static final PoseEstimation poseEstimation = new PoseEstimation(); public static final SendableChooser<String> drivePresetsChooser = new SendableChooser<>(); public static Field2d field = new Field2d(); public static Field2d nodeSelector = new Field2d(); private final FieldObject2d startingPosition = field.getObject("Starting Position"); private final FieldObject2d autoBalanceStartingPosition = field.getObject("Auto Balance Starting Position"); private DriveWithJoysticks driveCommand = new DriveWithJoysticks(drivetrain, poseEstimation, joystick1); private AutoBalance autoBalanceCommand = new AutoBalance(drivetrain); public static SendableChooser<String> autoSelector; //private static AutoElevator autoElevator; /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { //autoElevator = new AutoElevator(liftSubsystem, 0); //Intake intakeSubsystem.setDefaultCommand(new IntakeCommand(intakeSubsystem, () -> -joystick2.getRawAxis(IntakeConstants.AngleController))); //Pneumatic //pneumaticSubsystem.setDefaultCommand(new PneumaticCommand(pneumaticSubsystem, false, true)); //Lift liftSubsystem.setDefaultCommand(new LiftCommand(liftSubsystem, () -> -joystick2.getRawAxis(5))); if (!DriverStation.isFMSAttached()) { PathPlannerServer.startServer(5811); } drivetrain.setDefaultCommand(driveCommand); if (autoBalanceStartingPosition.getPoses().isEmpty()) { autoBalanceStartingPosition.setPose(AllianceUtils.allianceToField(new Pose2d(new Translation2d(0,0),new Rotation2d()))); } configureBindings(); autoSelector = new SendableChooser<>(); autoSelector.setDefaultOption("grid1", "grid1"); // 1 kup en yukari kisa taxi //autoSelector.setDefaultOption("grid2", "grid2"); // 1 kup en yukari kisa taxi denge //autoSelector.setDefaultOption("grid3", "grid3"); // 1 kup en yukari ortadan denge //autoSelector.setDefaultOption("grid4", "grid4"); //1 kup en yukari uzun taxi denge //autoSelector.setDefaultOption("grid5", "grid5"); //1 kup en yukari uzun taxi } /** * Use this method to define your trigger->command mappings. Triggers can be created via the * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary * predicate, or via the named factories in {@link * edu.wpi.first.wpilibj2.command.button.CommandGenericHID}'s subclasses for {@link * CommandXboxController Xbox}/{@link edu.wpi.first.wpilibj2.command.button.CommandPS4Controller * PS4} controllers or {@link edu.wpi.first.wpilibj2.command.button.CommandJoystick Flight * joysticks}. */ private void configureBindings() { //setPoint type is inches //limelight sets 111 cm new JoystickButton(joystick1, 2).
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { //Limelight public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem(); //Intake public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); //Pneumatic public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem(); //Lift public static final LiftSubsystem liftSubsystem = new LiftSubsystem(); public static final ShuffleboardTab driveSettingsTab = Shuffleboard.getTab("Drive Settings"); public static final ShuffleboardTab autoTab = Shuffleboard.getTab("Auto"); public static final ShuffleboardTab swerveTab = Shuffleboard.getTab("Swerve"); public static final Joystick joystick1 = new Joystick(0); public static final Joystick joystick2 = new Joystick(IntakeConstants.AngleController); public static final Drivetrain drivetrain = new Drivetrain(); public static final PoseEstimation poseEstimation = new PoseEstimation(); public static final SendableChooser<String> drivePresetsChooser = new SendableChooser<>(); public static Field2d field = new Field2d(); public static Field2d nodeSelector = new Field2d(); private final FieldObject2d startingPosition = field.getObject("Starting Position"); private final FieldObject2d autoBalanceStartingPosition = field.getObject("Auto Balance Starting Position"); private DriveWithJoysticks driveCommand = new DriveWithJoysticks(drivetrain, poseEstimation, joystick1); private AutoBalance autoBalanceCommand = new AutoBalance(drivetrain); public static SendableChooser<String> autoSelector; //private static AutoElevator autoElevator; /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { //autoElevator = new AutoElevator(liftSubsystem, 0); //Intake intakeSubsystem.setDefaultCommand(new IntakeCommand(intakeSubsystem, () -> -joystick2.getRawAxis(IntakeConstants.AngleController))); //Pneumatic //pneumaticSubsystem.setDefaultCommand(new PneumaticCommand(pneumaticSubsystem, false, true)); //Lift liftSubsystem.setDefaultCommand(new LiftCommand(liftSubsystem, () -> -joystick2.getRawAxis(5))); if (!DriverStation.isFMSAttached()) { PathPlannerServer.startServer(5811); } drivetrain.setDefaultCommand(driveCommand); if (autoBalanceStartingPosition.getPoses().isEmpty()) { autoBalanceStartingPosition.setPose(AllianceUtils.allianceToField(new Pose2d(new Translation2d(0,0),new Rotation2d()))); } configureBindings(); autoSelector = new SendableChooser<>(); autoSelector.setDefaultOption("grid1", "grid1"); // 1 kup en yukari kisa taxi //autoSelector.setDefaultOption("grid2", "grid2"); // 1 kup en yukari kisa taxi denge //autoSelector.setDefaultOption("grid3", "grid3"); // 1 kup en yukari ortadan denge //autoSelector.setDefaultOption("grid4", "grid4"); //1 kup en yukari uzun taxi denge //autoSelector.setDefaultOption("grid5", "grid5"); //1 kup en yukari uzun taxi } /** * Use this method to define your trigger->command mappings. Triggers can be created via the * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary * predicate, or via the named factories in {@link * edu.wpi.first.wpilibj2.command.button.CommandGenericHID}'s subclasses for {@link * CommandXboxController Xbox}/{@link edu.wpi.first.wpilibj2.command.button.CommandPS4Controller * PS4} controllers or {@link edu.wpi.first.wpilibj2.command.button.CommandJoystick Flight * joysticks}. */ private void configureBindings() { //setPoint type is inches //limelight sets 111 cm new JoystickButton(joystick1, 2).
whileTrue(new GetInRange(drivetrain, poseEstimation, limelightSubsystem, 44, LimelightPositionCheck.fiftyFive));
4
2023-11-18 14:02:20+00:00
16k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/core/items/types/end/armor/SuperiorChestplate.java
[ { "identifier": "SkyblockPlayerDamageEntityEvent", "path": "src/main/java/com/sweattypalms/skyblock/core/events/def/SkyblockPlayerDamageEntityEvent.java", "snippet": "public class SkyblockPlayerDamageEntityEvent extends SkyblockPlayerEvent implements Cancellable {\n private static final HandlerList H...
import com.sweattypalms.skyblock.core.events.def.SkyblockPlayerDamageEntityEvent; import com.sweattypalms.skyblock.core.items.builder.Rarity; import com.sweattypalms.skyblock.core.items.builder.SkyblockItem; import com.sweattypalms.skyblock.core.items.builder.SkyblockItemType; import com.sweattypalms.skyblock.core.items.builder.abilities.Ability; import com.sweattypalms.skyblock.core.items.builder.abilities.IHasAbility; import com.sweattypalms.skyblock.core.items.builder.abilities.types.FullSetBonus; import com.sweattypalms.skyblock.core.items.builder.abilities.types.PassiveAbility; import com.sweattypalms.skyblock.core.items.builder.armor.IDyedArmor; import com.sweattypalms.skyblock.core.items.types.end.items.AspectOfTheDragons; import com.sweattypalms.skyblock.core.player.SkyblockPlayer; import com.sweattypalms.skyblock.core.player.sub.stats.Stats; import com.sweattypalms.skyblock.core.player.sub.stats.StatsManager; import org.bukkit.Material; import org.bukkit.event.Event; import org.bukkit.inventory.ItemStack; import java.util.*;
11,571
package com.sweattypalms.skyblock.core.items.types.end.armor; public class SuperiorChestplate extends SkyblockItem implements IHasAbility, IDyedArmor { public static final String ID = "superior_dragon_chestplate"; private static final Map<Stats, Double> stats = new HashMap<>(Map.of( Stats.HEALTH, 150d, Stats.DEFENSE, 190d, Stats.SPEED, 3d, Stats.STRENGTH, 10d, Stats.INTELLIGENCE, 25d, Stats.CRIT_CHANCE, 2d, Stats.CRIT_DAMAGE, 10d )); public SuperiorChestplate() { super( ID, "Superior Dragon Chestplate", Material.LEATHER_CHESTPLATE, null, stats, Rarity.LEGENDARY, SkyblockItemType.CHESTPLATE ); } @Override public List<Ability> getAbilities() { return List.of( new SuperiorBlood(), new SuperiorBloodAOTD() ); } @Override public String getHexColor() { return "f2df11"; } public static class SuperiorBlood implements FullSetBonus, PassiveAbility { @Override public String getName() { return "Superior Blood"; } @Override public List<String> getDescription() { return List.of( "$7Most of your stats are increased", "$7by $a5%$7 and $6Aspect of the", "$6Dragons $7ability deals $a50%", "$7more damage." ); } @Override public void onTick(SkyblockPlayer player) {
package com.sweattypalms.skyblock.core.items.types.end.armor; public class SuperiorChestplate extends SkyblockItem implements IHasAbility, IDyedArmor { public static final String ID = "superior_dragon_chestplate"; private static final Map<Stats, Double> stats = new HashMap<>(Map.of( Stats.HEALTH, 150d, Stats.DEFENSE, 190d, Stats.SPEED, 3d, Stats.STRENGTH, 10d, Stats.INTELLIGENCE, 25d, Stats.CRIT_CHANCE, 2d, Stats.CRIT_DAMAGE, 10d )); public SuperiorChestplate() { super( ID, "Superior Dragon Chestplate", Material.LEATHER_CHESTPLATE, null, stats, Rarity.LEGENDARY, SkyblockItemType.CHESTPLATE ); } @Override public List<Ability> getAbilities() { return List.of( new SuperiorBlood(), new SuperiorBloodAOTD() ); } @Override public String getHexColor() { return "f2df11"; } public static class SuperiorBlood implements FullSetBonus, PassiveAbility { @Override public String getName() { return "Superior Blood"; } @Override public List<String> getDescription() { return List.of( "$7Most of your stats are increased", "$7by $a5%$7 and $6Aspect of the", "$6Dragons $7ability deals $a50%", "$7more damage." ); } @Override public void onTick(SkyblockPlayer player) {
StatsManager statsManager = player.getStatsManager();
12
2023-11-15 15:05:58+00:00
16k
HanGyeolee/AndroidPdfWriter
android-pdf-writer/src/androidTest/java/com/hangyeolee/androidpdfwriter/PDFTableTest.java
[ { "identifier": "PDFGridLayout", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/components/PDFGridLayout.java", "snippet": "public class PDFGridLayout extends PDFLayout{\n int rows, columns;\n\n ArrayList<Integer> span;\n\n final int[] gaps;\n final Rect childMargi...
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.hangyeolee.androidpdfwriter.components.PDFGridLayout; import com.hangyeolee.androidpdfwriter.components.PDFH1; import com.hangyeolee.androidpdfwriter.components.PDFH3; import com.hangyeolee.androidpdfwriter.components.PDFImage; import com.hangyeolee.androidpdfwriter.components.PDFLinearLayout; import com.hangyeolee.androidpdfwriter.utils.Anchor; import com.hangyeolee.androidpdfwriter.utils.DPI; import com.hangyeolee.androidpdfwriter.utils.Fit; import com.hangyeolee.androidpdfwriter.utils.Orientation; import com.hangyeolee.androidpdfwriter.utils.Paper; import com.hangyeolee.androidpdfwriter.utils.StandardDirectory; import com.hangyeolee.androidpdfwriter.utils.TextAlign; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.InputStream;
11,089
package com.hangyeolee.androidpdfwriter; @RunWith(AndroidJUnit4.class) public class PDFTableTest { Context context; PDFBuilder<PDFLinearLayout> builder; /** * The first page of the pdf file that is output by executing the code below is as follows: * com.hangyeolee.androidpdfwriter.test.R.drawable.pdftabletest_resultimage */ @Before public void setUp() { context = InstrumentationRegistry.getInstrumentation().getTargetContext(); InputStream stream = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(com.hangyeolee.androidpdfwriter.test.R.drawable.test); Bitmap b = BitmapFactory.decodeStream(stream); builder = new PDFBuilder<>(Paper.A4); builder.setPagePadding(30, 30); { builder.root = PDFLinearLayout.build() .setOrientation(Orientation.Column) .setBackgroundColor(Color.BLUE) .addChild(PDFImage.build(b) .setSize(null, 200f)
package com.hangyeolee.androidpdfwriter; @RunWith(AndroidJUnit4.class) public class PDFTableTest { Context context; PDFBuilder<PDFLinearLayout> builder; /** * The first page of the pdf file that is output by executing the code below is as follows: * com.hangyeolee.androidpdfwriter.test.R.drawable.pdftabletest_resultimage */ @Before public void setUp() { context = InstrumentationRegistry.getInstrumentation().getTargetContext(); InputStream stream = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(com.hangyeolee.androidpdfwriter.test.R.drawable.test); Bitmap b = BitmapFactory.decodeStream(stream); builder = new PDFBuilder<>(Paper.A4); builder.setPagePadding(30, 30); { builder.root = PDFLinearLayout.build() .setOrientation(Orientation.Column) .setBackgroundColor(Color.BLUE) .addChild(PDFImage.build(b) .setSize(null, 200f)
.setFit(Fit.CONTAIN))
7
2023-11-15 08:05:28+00:00
16k
Hikaito/Fox-Engine
src/system/gui/editorPane/GuiFieldControls.java
[ { "identifier": "Program", "path": "src/system/Program.java", "snippet": "public class Program {\n\n //region initialization------------------------------------------\n\n // \"global\" variables\n private static UserSetting userSetting;\n private static MainWindow window;\n private static...
import system.Program; import system.gui.GuiOperations; import system.layerTree.data.LayerManager; import system.layerTree.data.SelectionManager; import system.layerTree.data.Folder; import system.layerTree.data.Layer; import system.layerTree.data.LayerCore; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
14,315
title.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setTitle(title.getText())); layer.setTitle(title.getText()); Program.redrawLayerEditor(); } }); return title; } //endregion- //region clipping------------------------------- //add clipping toggle to field public static JCheckBox makeClippingToggle(LayerCore layer){ //create toggle; set value to existing clipping values JCheckBox clipBox = new JCheckBox("clip", layer.getClipToParent()); //on selection, toggle clipping in layer clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setClipToParent()); layer.setClipToParent(); // Program.redrawAllRegions(); } }); return clipBox; } //generate clipping label public static JLabel makeClippingLabel(LayerCore layer){ if (layer.getClipToParent()) return new JLabel("clipped"); else return null; } //endregion //region visibility ---------------------- //make toggle to visibility public static JCheckBox makeVisibleToggle(LayerCore layer){ //create toggle; set value to existing values JCheckBox clipBox = new JCheckBox("Visible", layer.getVisible()); //on selection, toggle visibility clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setViewAlpha()); layer.setVisible(); //Program.redrawAllRegions(); //layer.signalRedraw(); //redraw canvas } }); return clipBox; } //endregion //region visibilty toggle button------------------------- //add duplicate button public static JButton makeVisibilityToggleButton(LayerCore layer){ // text String text; if (layer.getVisible() == false) text = "-"; else text = "\uD83D\uDC41"; //👁 //add button JButton button = new JButton(text); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ layer.setVisible(); //Program.redrawAllRegions(); } }); return button; } //endregion //region alpha ------------------------- //add alpha edit box public static JPanel makeAlpha(LayerCore layer){ //add alpha box JPanel alphaPanel = new JPanel(); //create field for alpha text entering with a label JFormattedTextField alphaInput = new JFormattedTextField(layer.getAlpha()); //creates field with default alpha JLabel alphaLabel = new JLabel("alpha"); //creates label alphaPanel.add(alphaLabel); alphaPanel.add(alphaInput); //when change is detected, adjust alpha alphaInput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //if input is valid, set input to alpha. Otherwise, set alpha to input. try{ //parse double; if a valid number, establish range Double input = Double.parseDouble(alphaInput.getText()); layer.setAlpha(input); //setAlpha performs validity checking //layer.signalRedraw(); //redraw canvas } catch(Exception ee){ alphaInput.setValue(layer.getAlpha()); } // Program.redrawAllRegions(); } }); alphaInput.setColumns(3); return alphaPanel; } //endregion //endregion //region layer only manipulation ======================================== //region color ------------------------------ //generate color toggle for layer
package system.gui.editorPane; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== // field controls for Layer objects public class GuiFieldControls { //region core unit manipulation ======================================== //region clone and delete-------------------------------------- //add delete button: adds deletion button to field public static JButton makeDelete(LayerCore layer){ //add button JButton button = new JButton("delete"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.deleteTreeUnit(layer, false); } }); return button; } //add delete all button: adds deletion of children button to field public static JButton makeDeleteAll(LayerCore layer){ //add button JButton button = new JButton("delete (deep)"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.deleteTreeUnit(layer, true); } }); return button; } //add duplicate button public static JButton makeDuplicate(LayerCore layer){ //add button JButton button = new JButton("clone"); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ // request action from layer manager [handles redraw] Program.duplicateTreeUnit(layer); } }); return button; } //endregion //region movement control --------------------------- //function for adding location controls to panel [adds buttons to field] public static void addLocationControls(JPanel innerField, LayerCore layer){ //generate panel for holding buttons JPanel buttonBox = new JPanel(); innerField.add(buttonBox); //add buttons for location movement----------- buttonBox.add(makeButtonOut(layer)); //register button buttonBox.add(makeButtonUp(layer)); //label for level //JLabel levelLabel = new JLabel("level " + 0); //fixme 0 was level //buttonBox.add(levelLabel); buttonBox.add(makeButtonDown(layer)); buttonBox.add(makeButtonIn(layer)); } //get button for in public static JButton makeButtonIn(LayerCore layer){ //in: button to signal moving deeper in hierarchy JButton buttonIn = new JButton("->"); buttonIn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.IN); } }); return buttonIn; } //get button for down public static JButton makeButtonDown(LayerCore layer){ //down: button to signal moving down in hierarchy JButton buttonDown = new JButton("v"); buttonDown.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.DOWN); } }); return buttonDown; } //get button for up public static JButton makeButtonUp(LayerCore layer){ //up: button to signal moving up in hierarchy JButton buttonUp = new JButton("^"); buttonUp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.UP); } }); return buttonUp; } ///get button for out public static JButton makeButtonOut(LayerCore layer){ //out: button to signal moving out of the hierarchy JButton buttonOut = new JButton("<-"); //generate button buttonOut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // request action from layer manager [handles redraw] Program.moveLayer(layer, LayerManager.direction.OUT); } }); return buttonOut; } //endregion //region selection --------------------------- // function for selection public static JButton makeSelectionButton(LayerCore layer){ // pick text String text = "Deselect"; // test for selection: selection type is select if not selected if (Program.checkSelection(layer) == SelectionManager.selectionPriority.NONE) text = "Select"; //out: button to signal moving out of the hierarchy JButton buttonOut = new JButton(text); //generate button buttonOut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //check selection value // select if unselected if (Program.checkSelection(layer) == SelectionManager.selectionPriority.NONE) Program.addSelection(layer); //otherwise unselect if selected else Program.removeSelection(layer); //on click, move out in hierarchy Program.redrawLayerEditor(); //redraw layer map //Program.redrawLayerEditor(); //layer.signalRedraw(); //redraw canvas //fixme idk about this } }); return buttonOut; } //endregion //endregion //region common element manipulation ======================================== //region title------------------------ //generate title label public static JLabel makeTitle(LayerCore layer){ return new JLabel(layer.getTitle()); } // generate title text field public static JTextField makeTitleField(LayerCore layer){ JTextField title = new JTextField(10); //generate text field with preferred size title.setText(layer.getTitle()); // action title.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setTitle(title.getText())); layer.setTitle(title.getText()); Program.redrawLayerEditor(); } }); return title; } //endregion- //region clipping------------------------------- //add clipping toggle to field public static JCheckBox makeClippingToggle(LayerCore layer){ //create toggle; set value to existing clipping values JCheckBox clipBox = new JCheckBox("clip", layer.getClipToParent()); //on selection, toggle clipping in layer clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setClipToParent()); layer.setClipToParent(); // Program.redrawAllRegions(); } }); return clipBox; } //generate clipping label public static JLabel makeClippingLabel(LayerCore layer){ if (layer.getClipToParent()) return new JLabel("clipped"); else return null; } //endregion //region visibility ---------------------- //make toggle to visibility public static JCheckBox makeVisibleToggle(LayerCore layer){ //create toggle; set value to existing values JCheckBox clipBox = new JCheckBox("Visible", layer.getVisible()); //on selection, toggle visibility clipBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //Program.addUndo(layer.setViewAlpha()); layer.setVisible(); //Program.redrawAllRegions(); //layer.signalRedraw(); //redraw canvas } }); return clipBox; } //endregion //region visibilty toggle button------------------------- //add duplicate button public static JButton makeVisibilityToggleButton(LayerCore layer){ // text String text; if (layer.getVisible() == false) text = "-"; else text = "\uD83D\uDC41"; //👁 //add button JButton button = new JButton(text); //on button click, deploy action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ layer.setVisible(); //Program.redrawAllRegions(); } }); return button; } //endregion //region alpha ------------------------- //add alpha edit box public static JPanel makeAlpha(LayerCore layer){ //add alpha box JPanel alphaPanel = new JPanel(); //create field for alpha text entering with a label JFormattedTextField alphaInput = new JFormattedTextField(layer.getAlpha()); //creates field with default alpha JLabel alphaLabel = new JLabel("alpha"); //creates label alphaPanel.add(alphaLabel); alphaPanel.add(alphaInput); //when change is detected, adjust alpha alphaInput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //if input is valid, set input to alpha. Otherwise, set alpha to input. try{ //parse double; if a valid number, establish range Double input = Double.parseDouble(alphaInput.getText()); layer.setAlpha(input); //setAlpha performs validity checking //layer.signalRedraw(); //redraw canvas } catch(Exception ee){ alphaInput.setValue(layer.getAlpha()); } // Program.redrawAllRegions(); } }); alphaInput.setColumns(3); return alphaPanel; } //endregion //endregion //region layer only manipulation ======================================== //region color ------------------------------ //generate color toggle for layer
public static JCheckBox makeColorToggle(Layer layer){
5
2023-11-12 21:12:21+00:00
16k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/checks/impl/combat/Reach.java
[ { "identifier": "PacketCheck", "path": "src/main/java/ac/grim/grimac/checks/type/PacketCheck.java", "snippet": "public class PacketCheck extends Check<Object> {\n\n public PacketCheck(final GrimPlayer playerData) {\n super(playerData);\n }\n\n public void onPacketReceive(final PacketPlay...
import ac.grim.grimac.checks.type.PacketCheck; import ac.grim.grimac.player.GrimPlayer; import ac.grim.grimac.utils.collisions.datatypes.SimpleCollisionBox; import ac.grim.grimac.utils.data.packetentity.PacketEntity; import ac.grim.grimac.utils.math.VectorUtils; import ac.grim.grimac.utils.nmsutil.ReachUtils; import io.github.retrooper.packetevents.event.impl.PacketPlayReceiveEvent; import io.github.retrooper.packetevents.packettype.PacketType; import io.github.retrooper.packetevents.packetwrappers.play.in.useentity.WrappedPacketInUseEntity; import io.github.retrooper.packetevents.utils.player.ClientVersion; import io.github.retrooper.packetevents.utils.server.ServerVersion; import io.github.retrooper.packetevents.utils.vector.Vector3d; import org.bukkit.GameMode; import org.bukkit.util.Vector; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue;
12,582
// This file was designed and is an original check for GrimAC // Copyright (C) 2021 DefineOutside // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package ac.grim.grimac.checks.impl.combat; // You may not copy the check unless you are licensed under GPL public class Reach extends PacketCheck { // Concurrent to support weird entity trackers private final ConcurrentLinkedQueue<Integer> playerAttackQueue = new ConcurrentLinkedQueue<>(); private boolean cancelImpossibleHits = true; private double threshold = 0.0005; public Reach(GrimPlayer player) { super(player); } @Override public void onPacketReceive(final PacketPlayReceiveEvent event) { if (event.getPacketId() == PacketType.Play.Client.USE_ENTITY) { WrappedPacketInUseEntity action = new WrappedPacketInUseEntity(event.getNMSPacket()); if (player.gamemode == GameMode.CREATIVE) return; if (player.vehicle != null) return; checkReach(action.getEntityId()); if (cancelImpossibleHits && isKnownInvalid(action.getEntityId())) { event.setCancelled(true); } } if (PacketType.Play.Client.Util.isInstanceOfFlying(event.getPacketId())) { // Teleports don't interpolate, duplicate 1.17 packets don't interpolate if (player.packetStateData.lastPacketWasTeleport || player.packetStateData.lastPacketWasOnePointSeventeenDuplicate) return; tickFlying(); } } public void checkReach(int entityID) { if (player.compensatedEntities.entityMap.containsKey(entityID)) playerAttackQueue.add(entityID); } // This method finds the most optimal point at which the user should be aiming at // and then measures the distance between the player's eyes and this target point // // It will not cancel every invalid attack but should cancel 3.05+ or so in real-time // Let the post look check measure the distance, as it will always return equal or higher // than this method. If this method flags, the other method WILL flag. // // Meaning that the other check should be the only one that flags. private boolean isKnownInvalid(int entityID) {
// This file was designed and is an original check for GrimAC // Copyright (C) 2021 DefineOutside // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package ac.grim.grimac.checks.impl.combat; // You may not copy the check unless you are licensed under GPL public class Reach extends PacketCheck { // Concurrent to support weird entity trackers private final ConcurrentLinkedQueue<Integer> playerAttackQueue = new ConcurrentLinkedQueue<>(); private boolean cancelImpossibleHits = true; private double threshold = 0.0005; public Reach(GrimPlayer player) { super(player); } @Override public void onPacketReceive(final PacketPlayReceiveEvent event) { if (event.getPacketId() == PacketType.Play.Client.USE_ENTITY) { WrappedPacketInUseEntity action = new WrappedPacketInUseEntity(event.getNMSPacket()); if (player.gamemode == GameMode.CREATIVE) return; if (player.vehicle != null) return; checkReach(action.getEntityId()); if (cancelImpossibleHits && isKnownInvalid(action.getEntityId())) { event.setCancelled(true); } } if (PacketType.Play.Client.Util.isInstanceOfFlying(event.getPacketId())) { // Teleports don't interpolate, duplicate 1.17 packets don't interpolate if (player.packetStateData.lastPacketWasTeleport || player.packetStateData.lastPacketWasOnePointSeventeenDuplicate) return; tickFlying(); } } public void checkReach(int entityID) { if (player.compensatedEntities.entityMap.containsKey(entityID)) playerAttackQueue.add(entityID); } // This method finds the most optimal point at which the user should be aiming at // and then measures the distance between the player's eyes and this target point // // It will not cancel every invalid attack but should cancel 3.05+ or so in real-time // Let the post look check measure the distance, as it will always return equal or higher // than this method. If this method flags, the other method WILL flag. // // Meaning that the other check should be the only one that flags. private boolean isKnownInvalid(int entityID) {
PacketEntity reachEntity = player.compensatedEntities.entityMap.get(entityID);
3
2023-11-11 05:14:12+00:00
16k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/app/AppApplication.java
[ { "identifier": "RequestHandler", "path": "app/src/main/java/com/buaa/food/http/model/RequestHandler.java", "snippet": "public final class RequestHandler implements IRequestHandler {\n\n private final Application mApplication;\n private final MMKV mMmkv;\n\n public RequestHandler(Application ap...
import android.app.Activity; import android.app.Application; import android.content.Context; import android.net.ConnectivityManager; import android.net.Network; import android.os.Build; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleOwner; import com.buaa.food.http.glide.GlideApp; import com.buaa.food.http.model.RequestHandler; import com.buaa.food.http.model.RequestServer; import com.buaa.food.manager.ActivityManager; import com.buaa.food.other.AppConfig; import com.buaa.food.other.CrashHandler; import com.buaa.food.other.DebugLoggerTree; import com.buaa.food.other.MaterialHeader; import com.buaa.food.other.SmartBallPulseFooter; import com.buaa.food.other.TitleBarStyle; import com.buaa.food.other.ToastLogInterceptor; import com.buaa.food.other.ToastStyle; import com.hjq.bar.TitleBar; import com.buaa.food.R; import com.buaa.food.aop.Log; import com.hjq.gson.factory.GsonFactory; import com.hjq.http.EasyConfig; import com.hjq.toast.ToastUtils; import com.hjq.umeng.UmengClient; import com.scwang.smart.refresh.layout.SmartRefreshLayout; import com.tencent.bugly.crashreport.CrashReport; import com.tencent.mmkv.MMKV; import okhttp3.OkHttpClient; import timber.log.Timber;
11,454
package com.buaa.food.app; public final class AppApplication extends Application { @Log("启动耗时") @Override public void onCreate() { super.onCreate(); initSdk(this); } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); } @Override public void onLowMemory() { super.onLowMemory(); // 清理所有图片内存缓存 GlideApp.get(this).onLowMemory(); } @Override public void onTrimMemory(int level) { super.onTrimMemory(level); // 根据手机内存剩余情况清理图片内存缓存 GlideApp.get(this).onTrimMemory(level); } /** * 初始化一些第三方框架 */ public static void initSdk(Application application) { // 设置标题栏初始化器 TitleBar.setDefaultStyle(new TitleBarStyle()); // 设置全局的 Header 构建器 SmartRefreshLayout.setDefaultRefreshHeaderCreator((cx, layout) -> new MaterialHeader(application).setColorSchemeColors(ContextCompat.getColor(application, R.color.common_accent_color))); // 设置全局的 Footer 构建器 SmartRefreshLayout.setDefaultRefreshFooterCreator((cx, layout) -> new SmartBallPulseFooter(application)); // 设置全局初始化器 SmartRefreshLayout.setDefaultRefreshInitializer((cx, layout) -> { // 刷新头部是否跟随内容偏移 layout.setEnableHeaderTranslationContent(true) // 刷新尾部是否跟随内容偏移 .setEnableFooterTranslationContent(true) // 加载更多是否跟随内容偏移 .setEnableFooterFollowWhenNoMoreData(true) // 内容不满一页时是否可以上拉加载更多 .setEnableLoadMoreWhenContentNotFull(false) // 仿苹果越界效果开关 .setEnableOverScrollDrag(false); }); // 初始化吐司
package com.buaa.food.app; public final class AppApplication extends Application { @Log("启动耗时") @Override public void onCreate() { super.onCreate(); initSdk(this); } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); } @Override public void onLowMemory() { super.onLowMemory(); // 清理所有图片内存缓存 GlideApp.get(this).onLowMemory(); } @Override public void onTrimMemory(int level) { super.onTrimMemory(level); // 根据手机内存剩余情况清理图片内存缓存 GlideApp.get(this).onTrimMemory(level); } /** * 初始化一些第三方框架 */ public static void initSdk(Application application) { // 设置标题栏初始化器 TitleBar.setDefaultStyle(new TitleBarStyle()); // 设置全局的 Header 构建器 SmartRefreshLayout.setDefaultRefreshHeaderCreator((cx, layout) -> new MaterialHeader(application).setColorSchemeColors(ContextCompat.getColor(application, R.color.common_accent_color))); // 设置全局的 Footer 构建器 SmartRefreshLayout.setDefaultRefreshFooterCreator((cx, layout) -> new SmartBallPulseFooter(application)); // 设置全局初始化器 SmartRefreshLayout.setDefaultRefreshInitializer((cx, layout) -> { // 刷新头部是否跟随内容偏移 layout.setEnableHeaderTranslationContent(true) // 刷新尾部是否跟随内容偏移 .setEnableFooterTranslationContent(true) // 加载更多是否跟随内容偏移 .setEnableFooterFollowWhenNoMoreData(true) // 内容不满一页时是否可以上拉加载更多 .setEnableLoadMoreWhenContentNotFull(false) // 仿苹果越界效果开关 .setEnableOverScrollDrag(false); }); // 初始化吐司
ToastUtils.init(application, new ToastStyle());
10
2023-11-14 10:04:26+00:00
16k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/model/block/BlockModelRenderer.java
[ { "identifier": "DragonFly", "path": "src/main/java/useless/dragonfly/DragonFly.java", "snippet": "public class DragonFly implements GameStartEntrypoint {\n public static final String MOD_ID = \"dragonfly\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\tpublic static fi...
import net.minecraft.client.Minecraft; import net.minecraft.client.render.RenderBlockCache; import net.minecraft.client.render.RenderBlocks; import net.minecraft.client.render.Tessellator; import net.minecraft.client.render.block.color.BlockColorDispatcher; import net.minecraft.client.render.block.model.BlockModelRenderBlocks; import net.minecraft.core.block.Block; import net.minecraft.core.util.helper.Side; import net.minecraft.core.world.WorldSource; import org.lwjgl.opengl.GL11; import useless.dragonfly.DragonFly; import useless.dragonfly.mixins.mixin.accessor.RenderBlocksAccessor; import useless.dragonfly.model.block.data.PositionData; import useless.dragonfly.model.block.processed.BlockCube; import useless.dragonfly.model.block.processed.BlockFace; import useless.dragonfly.model.block.processed.BlockModel; import useless.dragonfly.utilities.vector.Vector3f; import java.awt.*; import java.lang.reflect.Field; import static useless.dragonfly.utilities.vector.Vector3f.origin;
12,778
// Bottom Right tessellator.setColorOpaque_F(colorRedBottomRight * r, colorGreenBottomRight * g, colorBlueBottomRight * b); tessellator.addVertexWithUV(x + vbr.x, y + vbr.y, z + vbr.z, uvBR[0], uvBR[1]); // Top Right tessellator.setColorOpaque_F(colorRedTopRight * r, colorGreenTopRight * g, colorBlueTopRight * b); tessellator.addVertexWithUV(x + vtr.x, y + vtr.y, z + vtr.z, uvTR[0], uvTR[1]); } else { tessellator.setColorOpaque_F(r, g, b); tessellator.addVertexWithUV(x + vtl.x, y + vtl.y, z + vtl.z, uvTL[0], uvTL[1]); // Top Left tessellator.addVertexWithUV(x + vbl.x, y + vbl.y, z + vbl.z, uvBL[0], uvBL[1]); // Bottom Left tessellator.addVertexWithUV(x + vbr.x, y + vbr.y, z + vbr.z, uvBR[0], uvBR[1]); // Bottom Right tessellator.addVertexWithUV(x + vtr.x, y + vtr.y, z + vtr.z, uvTR[0], uvTR[1]); // Top Right } } public static boolean renderStandardModelWithColorMultiplier(BlockModel model, Block block, int x, int y, int z, float r, float g, float b) { enableAO = false; Tessellator tessellator = Tessellator.instance; boolean renderedSomething = false; float cBottom = 0.5f; float cTop = 1.0f; float cNorthSouth = 0.8f; float cEastWest = 0.6f; float rTop = cTop * r; float gTop = cTop * g; float bTop = cTop * b; float rBottom = cBottom; float rNorthSouth = cNorthSouth; float rEastWest = cEastWest; float gBottom = cBottom; float gNorthSouth = cNorthSouth; float gEastWest = cEastWest; float bBottom = cBottom; float bNorthSouth = cNorthSouth; float bEastWest = cEastWest; rBottom *= r; rNorthSouth *= r; rEastWest *= r; gBottom *= g; gNorthSouth *= g; gEastWest *= g; bBottom *= b; bNorthSouth *= b; bEastWest *= b; float blockBrightness = rba().invokeGetBlockBrightness(rba().getBlockAccess(), x, y, z); for (BlockCube cube: model.blockCubes) { for (Side side: DragonFly.sides) { BlockFace face = cube.getFaceFromSide(side, rotationX, rotationY); if (face == null) continue; int _x = x + side.getOffsetX(); int _y = y + side.getOffsetY(); int _z = z + side.getOffsetZ(); if (!renderAllFaces){ if (!renderSide(model, cube, side, x, y, z)) continue; } float sideBrightness; if (!cube.isOuterFace(side, rotationX, rotationY) && !block.blockMaterial.isLiquid()){ sideBrightness = blockBrightness; } else { sideBrightness = rba().invokeGetBlockBrightness(rba().getBlockAccess(), _x, _y, _z); } float red = 1f; float green = 1f; float blue = 1f; if (cube.shade()){ switch (side){ case TOP: red = rTop; green = gTop; blue = bTop; break; case BOTTOM: red = rBottom; green = gBottom; blue = bBottom; break; case NORTH: case SOUTH: red = rNorthSouth; green = gNorthSouth; blue = bNorthSouth; break; case WEST: case EAST: red = rEastWest; green = gEastWest; blue = bEastWest; break; default: throw new RuntimeException("Specified side does not exist on a cube!!!"); } } tessellator.setColorOpaque_F(!face.getFullBright() ? red * sideBrightness : 1f, !face.getFullBright() ? green * sideBrightness : 1f, !face.getFullBright() ? blue * sideBrightness : 1f); renderModelFace(face, x, y, z); renderedSomething = true; } } return renderedSomething; } public static boolean renderSide(BlockModel model, BlockCube cube, Side side, int x, int y, int z){ WorldSource blockAccess = rba().getBlockAccess(); boolean renderOuterSide = blockAccess.getBlock(x, y, z).shouldSideBeRendered(blockAccess, x + side.getOffsetX(), y + side.getOffsetY(), z + side.getOffsetZ(), side.getId(), blockAccess.getBlockMetadata(x + side.getOffsetX(), y + side.getOffsetY(), z + side.getOffsetZ())); return !cube.getFaceFromSide(side, rotationX, rotationY).cullFace(x, y, z, renderOuterSide); } public static RenderBlocks getRenderBlocks(){ try { Field f = BlockModelRenderBlocks.class.getDeclaredField("renderBlocks"); f.setAccessible(true); RenderBlocks rb = (RenderBlocks) f.get(null); f.setAccessible(false); return rb; } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException(e); } }
package useless.dragonfly.model.block; public class BlockModelRenderer { public static Minecraft mc = Minecraft.getMinecraft(Minecraft.class); private static boolean enableAO = false; private static boolean renderAllFaces = false; private static float colorRedTopRight; private static float colorRedBottomRight; private static float colorRedBottomLeft; private static float colorGreenTopRight; private static float colorRedTopLeft; private static float colorGreenBottomRight; private static float colorGreenBottomLeft; private static float colorGreenTopLeft; private static float colorBlueTopRight; private static float colorBlueBottomRight; private static float colorBlueBottomLeft; private static float colorBlueTopLeft; private static int overrideBlockTexture = -1; private static int rotationX = 0; private static int rotationY = 0; public static void renderModelInventory(BlockModelDragonFly modelDragonFly, Block block, int meta, float brightness){ int off = (int) ((System.currentTimeMillis()/20) % 360); float xOffset; float yOffset; float zOffset; float xScale; float yScale; float zScale; float xRot; float yRot; float zRot; PositionData displayData = modelDragonFly.baseModel.getDisplayPosition(DragonFly.renderState); switch (DragonFly.renderState) { case "ground": xScale = (float) displayData.scale[2] * 4; yScale = (float) displayData.scale[1] * 4; zScale = (float) displayData.scale[0] * 4; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[0] / 16f; xRot = (float) displayData.rotation[0]; yRot = (float) displayData.rotation[1]; zRot = (float) displayData.rotation[2]; break; case "head": GL11.glFrontFace(GL11.GL_CW); xScale = (float) displayData.scale[0]; yScale = (float) displayData.scale[1]; zScale = (float) displayData.scale[2]; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[0] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[2] / 16f; xRot = (float) displayData.rotation[0]; yRot = (float) displayData.rotation[1] + 180; zRot = (float) displayData.rotation[2]; break; case "firstperson_righthand": xScale = (float) displayData.scale[2] * 2.5f; yScale = (float) displayData.scale[1] * 2.5f; zScale = (float) displayData.scale[0] * 2.5f; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 8f; yOffset -= (float) displayData.translation[1] / 8f; zOffset -= (float) displayData.translation[0] / 8f; xRot = (float) displayData.rotation[0]; yRot = (float) displayData.rotation[1] + 45; zRot = (float) displayData.rotation[2]; break; case "thirdperson_righthand": GL11.glFrontFace(GL11.GL_CW); float scale = 8f/3; xScale = (float) displayData.scale[2] * scale; yScale = (float) displayData.scale[1] * scale; zScale = (float) displayData.scale[0] * scale; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[0] / 16f; xRot = (float) -displayData.rotation[2] + 180; yRot = (float) displayData.rotation[1] + 45; zRot = (float) -displayData.rotation[0] - 100; break; case "gui": default: xScale = (float) displayData.scale[2] * 1.6f; yScale = (float) displayData.scale[1] * 1.6f; zScale = (float) displayData.scale[0] * 1.6f; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[0] / 16f; xRot = (float) displayData.rotation[0] - 30; yRot = (float) displayData.rotation[1] + 45; zRot = (float) displayData.rotation[2]; } Tessellator tessellator = Tessellator.instance; GL11.glEnable(GL11.GL_CULL_FACE); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glRotatef(yRot, 0, 1, 0); GL11.glRotatef(xRot, 1, 0, 0); GL11.glRotatef(zRot, 0, 0, 1); GL11.glTranslatef(-xOffset, -yOffset, -zOffset); GL11.glScalef(xScale, yScale, zScale); if (modelDragonFly.baseModel.blockCubes != null){ tessellator.startDrawingQuads(); GL11.glColor4f(brightness, brightness, brightness, 1); for (BlockCube cube: modelDragonFly.baseModel.blockCubes) { for (BlockFace face: cube.getFaces().values()) { tessellator.setNormal(face.getSide().getOffsetX(), face.getSide().getOffsetY(), face.getSide().getOffsetZ()); float r = 1; float g = 1; float b = 1; if (face.useTint()){ int color = BlockColorDispatcher.getInstance().getDispatch(block).getFallbackColor(meta); r = (float)(color >> 16 & 0xFF) / 255.0f; g = (float)(color >> 8 & 0xFF) / 255.0f; b = (float)(color & 0xFF) / 255.0f; } renderModelFaceWithColor(face, 0, 0, 0, r * brightness, g * brightness, b * brightness); } } tessellator.draw(); } GL11.glFrontFace(GL11.GL_CCW); // Deleting this breaks rendering for the whole world GL11.glDisable(GL11.GL_CULL_FACE); // Deleting this causes render issues on vanilla transparent blocks GL11.glTranslatef(xOffset, yOffset, zOffset); } public static boolean renderModelNormal(BlockModel model, Block block, int x, int y, int z, int rotationX, int rotationY) { BlockModelRenderer.rotationX = rotationX; BlockModelRenderer.rotationY = rotationY; if (rotationX % 90 != 0 || rotationY % 90 != 0) throw new IllegalArgumentException("Rotation must be a multiple of 90!!"); boolean didRender; if (mc.isAmbientOcclusionEnabled() && model.getAO()) { didRender = renderStandardModelWithAmbientOcclusion(model, block, x, y, z); } else { didRender = renderStandardModelWithColorMultiplier(model, block, x, y, z, 1, 1, 1); } BlockModelRenderer.rotationX = 0; BlockModelRenderer.rotationY = 0; return didRender; } public static boolean renderModelNoCulling(BlockModel model, Block block, int x, int y, int z, int rotationX, int rotationY) { renderAllFaces = true; boolean result = renderModelNormal(model, block, x, y, z, rotationX, rotationY); renderAllFaces = false; return result; } public static boolean renderModelBlockUsingTexture(BlockModel model, Block block, int x, int y, int z, int textureIndex, int rotationX, int rotationY) { overrideBlockTexture = textureIndex; boolean result = renderModelNormal(model, block, x, y, z, rotationX, rotationY); overrideBlockTexture = -1; return result; } public static boolean renderStandardModelWithAmbientOcclusion(BlockModel model, Block block, int x, int y, int z) { enableAO = true; rba().getCache().setupCache(block, rba().getBlockAccess(), x, y, z); boolean somethingRendered = false; for (BlockCube cube: model.blockCubes) { for (Side side: DragonFly.sides) { somethingRendered |= renderModelSide(model, cube, block, x, y, z, side); } } enableAO = false; return somethingRendered; } public static boolean renderModelSide(BlockModel model, BlockCube cube, Block block, int x, int y, int z, Side side) { BlockFace blockFace = cube.getFaceFromSide(side, rotationX, rotationY); if (blockFace == null) return false; if (!renderAllFaces){ if (!renderSide(model, cube, side, x, y, z)) return false; } RenderBlockCache cache = rba().getCache(); int sideOffX = side.getOffsetX(); int sideOffY = side.getOffsetY(); int sideOffZ = side.getOffsetZ(); Vector3f vMin = cube.getMin().rotateAroundX(origin, rotationX).rotateAroundY(origin, rotationY); Vector3f vMax = cube.getMax().rotateAroundX(origin, rotationX).rotateAroundY(origin, rotationY); float minX = vMin.x; float minY = vMin.y; float minZ = vMin.z; float maxX = vMax.x; float maxY = vMax.y; float maxZ = vMax.z; float depth; int topX; int topY; int topZ; float topP; float botP; int lefX; int lefY; int lefZ; float lefP; float rigP; switch (side){ case BOTTOM: depth = minY; topX = 0; topY = 0; topZ = 1; topP = maxZ; botP = minZ; lefX = -1; lefY = 0; lefZ = 0; lefP = 1.0F - minX; rigP = 1.0F - maxX; break; case TOP: depth = 1f - maxY; topX = 0; topY = 0; topZ = 1; topP = maxZ; botP = minZ; lefX = 1; lefY = 0; lefZ = 0; lefP = maxX; rigP = minX; break; case NORTH: depth = minZ; topX = -1; topY = 0; topZ = 0; topP = 1.0F - minX; botP = 1.0F - maxX; lefX = 0; lefY = 1; lefZ = 0; lefP = maxY; rigP = minY; break; case SOUTH: depth = 1f - maxZ; topX = 0; topY = 1; topZ = 0; topP = maxY; botP = minY; lefX = -1; lefY = 0; lefZ = 0; lefP = 1.0F - minX; rigP = 1.0F - maxX; break; case WEST: depth = minX; topX = 0; topY = 0; topZ = 1; topP = maxZ; botP = minZ; lefX = 0; lefY = 1; lefZ = 0; lefP = maxY; rigP = minY; break; case EAST: depth = 1f - maxX; topX = 0; topY = 0; topZ = 1; topP = maxZ; botP = minZ; lefX = 0; lefY = -1; lefZ = 0; lefP = 1.0F - minY; rigP = 1.0F - maxY; break; default: throw new IllegalArgumentException("Side " + side + " is not a valid side to render!"); } float r; float g; float b; if (blockFace.useTint()){ Color color = new Color(BlockColorDispatcher.getInstance().getDispatch(block).getWorldColor(mc.theWorld, x, y, z)); r = color.getRed() / 255.0f; g = color.getGreen() / 255.0f; b = color.getBlue() / 255.0f; } else { r = 1f; g = 1f; b = 1f; } float lightTR; float lightBR; float lightBL; float lightTL; if (rba().getOverbright() || blockFace.getFullBright()){ lightTR = 1.0f; lightBR = 1.0f; lightBL = 1.0f; lightTL = 1.0f; } else if (!cube.shade()) { float brightness = cache.getBrightness(0, 0, 0);; lightTR = brightness; lightBR = brightness; lightBL = brightness; lightTL = brightness; } else { float sideLightMultiplier = rba().getSIDE_LIGHT_MULTIPLIER()[side.getId()]; r *= sideLightMultiplier; g *= sideLightMultiplier; b *= sideLightMultiplier; float directionBrightness = cache.getBrightness(sideOffX, sideOffY, sideOffZ); boolean lefT = cache.getOpacity(sideOffX + lefX, sideOffY + lefY, sideOffZ + lefZ); boolean botT = cache.getOpacity(sideOffX - topX, sideOffY - topY, sideOffZ - topZ); boolean topT = cache.getOpacity(sideOffX + topX, sideOffY + topY, sideOffZ + topZ); boolean rigT = cache.getOpacity(sideOffX - lefX, sideOffY - lefY, sideOffZ - lefZ); float leftBrightness = cache.getBrightness(sideOffX + lefX, sideOffY + lefY, sideOffZ + lefZ); float bottomBrightness = cache.getBrightness(sideOffX - topX, sideOffY - topY, sideOffZ - topZ); float topBrightness = cache.getBrightness(sideOffX + topX, sideOffY + topY, sideOffZ + topZ); float rightBrightness = cache.getBrightness(sideOffX - lefX, sideOffY - lefY, sideOffZ - lefZ); float bottomLeftBrightness = botT && lefT ? leftBrightness : cache.getBrightness(sideOffX + lefX - topX, sideOffY + lefY - topY, sideOffZ + lefZ - topZ); float topLeftBrightness = topT && lefT ? leftBrightness : cache.getBrightness(sideOffX + lefX + topX, sideOffY + lefY + topY, sideOffZ + lefZ + topZ); float bottomRightBrightness = botT && rigT ? rightBrightness : cache.getBrightness(sideOffX - lefX - topX, sideOffY - lefY - topY, sideOffZ - lefZ - topZ); float topRightBrightness = topT && rigT ? rightBrightness : cache.getBrightness(sideOffX - lefX + topX, sideOffY - lefY + topY, sideOffZ - lefZ + topZ); lightTL = (topLeftBrightness + leftBrightness + topBrightness + directionBrightness) / 4.0f; lightTR = (topBrightness + directionBrightness + topRightBrightness + rightBrightness) / 4.0f; lightBR = (directionBrightness + bottomBrightness + rightBrightness + bottomRightBrightness) / 4.0f; lightBL = (leftBrightness + bottomLeftBrightness + directionBrightness + bottomBrightness) / 4.0f; if (depth > 0.01) { // The non-external faces of the block use the central block's brightness directionBrightness = cache.getBrightness(0, 0, 0); lefT = cache.getOpacity(lefX, lefY, lefZ); botT = cache.getOpacity(-topX, -topY, -topZ); topT = cache.getOpacity(topX, topY, topZ); rigT = cache.getOpacity(-lefX, -lefY, -lefZ); leftBrightness = cache.getBrightness(lefX, lefY, lefZ); bottomBrightness = cache.getBrightness(-topX, -topY, -topZ); topBrightness = cache.getBrightness(topX, topY, topZ); rightBrightness = cache.getBrightness(-lefX, -lefY, -lefZ); bottomLeftBrightness = botT && lefT ? leftBrightness : cache.getBrightness(lefX - topX, lefY - topY, lefZ - topZ); topLeftBrightness = topT && lefT ? leftBrightness : cache.getBrightness(lefX + topX, lefY + topY, lefZ + topZ); bottomRightBrightness = botT && rigT ? rightBrightness : cache.getBrightness(-lefX - topX, -lefY - topY, -lefZ - topZ); topRightBrightness = topT && rigT ? rightBrightness : cache.getBrightness(-lefX + topX, -lefY + topY, -lefZ + topZ); lightTL = (topLeftBrightness + leftBrightness + topBrightness + directionBrightness) / 4.0f * depth + lightTL * (1.0f - depth); lightTR = (topBrightness + directionBrightness + topRightBrightness + rightBrightness) / 4.0f * depth + lightTR * (1.0f - depth); lightBR = (directionBrightness + bottomBrightness + rightBrightness + bottomRightBrightness) / 4.0f * depth + lightBR * (1.0f - depth); lightBL = (leftBrightness + bottomLeftBrightness + directionBrightness + bottomBrightness) / 4.0f * depth + lightBL * (1.0f - depth); } } colorRedTopLeft = colorRedBottomLeft = colorRedBottomRight = colorRedTopRight = r; colorGreenTopLeft = colorGreenBottomLeft = colorGreenBottomRight = colorGreenTopRight = g; colorBlueTopLeft = colorBlueBottomLeft = colorBlueBottomRight = colorBlueTopRight = b; float tl = topP * lightTL + (1.0f - topP) * lightBL; float tr = topP * lightTR + (1.0f - topP) * lightBR; float bl = botP * lightTL + (1.0f - botP) * lightBL; float br = botP * lightTR + (1.0f - botP) * lightBR; float brightnessTopRight = lefP * tl + (1.0f - lefP) * tr; float brightnessBottomLeft = lefP * bl + (1.0f - lefP) * br; float bottomRightBrightness = rigP * bl + (1.0f - rigP) * br; float topRightBrightness = rigP * tl + (1.0f - rigP) * tr; colorRedTopLeft *= brightnessTopRight; colorGreenTopLeft *= brightnessTopRight; colorBlueTopLeft *= brightnessTopRight; colorRedBottomLeft *= brightnessBottomLeft; colorGreenBottomLeft *= brightnessBottomLeft; colorBlueBottomLeft *= brightnessBottomLeft; colorRedBottomRight *= bottomRightBrightness; colorGreenBottomRight *= bottomRightBrightness; colorBlueBottomRight *= bottomRightBrightness; colorRedTopRight *= topRightBrightness; colorGreenTopRight *= topRightBrightness; colorBlueTopRight *= topRightBrightness; renderModelFace(blockFace, x, y, z); return true; } public static void renderModelFace(BlockFace face, double x, double y, double z) { Tessellator tessellator = Tessellator.instance; double[] uvTL; double[] uvBL; double[] uvBR; double[] uvTR; if (overrideBlockTexture >= 0) { uvTL = face.generateVertexUV(overrideBlockTexture, 0); uvBL = face.generateVertexUV(overrideBlockTexture, 1); uvBR = face.generateVertexUV(overrideBlockTexture, 2); uvTR = face.generateVertexUV(overrideBlockTexture, 3); } else { uvTL = face.getVertexUV(0); uvBL = face.getVertexUV(1); uvBR = face.getVertexUV(2); uvTR = face.getVertexUV(3); } Vector3f[] faceVertices = new Vector3f[4]; for (int i = 0; i < faceVertices.length; i++) { faceVertices[i] = face.vertices[i].rotateAroundX(origin, rotationX).rotateAroundY(origin, rotationY); } Vector3f vtl = faceVertices[0]; Vector3f vbl = faceVertices[1]; Vector3f vbr = faceVertices[2]; Vector3f vtr = faceVertices[3]; if (enableAO) { // Top Left tessellator.setColorOpaque_F(colorRedTopLeft, colorGreenTopLeft, colorBlueTopLeft); tessellator.addVertexWithUV(x + vtl.x, y + vtl.y, z + vtl.z, uvTL[0], uvTL[1]); // Bottom Left tessellator.setColorOpaque_F(colorRedBottomLeft, colorGreenBottomLeft, colorBlueBottomLeft); tessellator.addVertexWithUV(x + vbl.x, y + vbl.y, z + vbl.z, uvBL[0], uvBL[1]); // Bottom Right tessellator.setColorOpaque_F(colorRedBottomRight, colorGreenBottomRight, colorBlueBottomRight); tessellator.addVertexWithUV(x + vbr.x, y + vbr.y, z + vbr.z, uvBR[0], uvBR[1]); // Top Right tessellator.setColorOpaque_F(colorRedTopRight, colorGreenTopRight, colorBlueTopRight); tessellator.addVertexWithUV(x + vtr.x, y + vtr.y, z + vtr.z, uvTR[0], uvTR[1]); } else { tessellator.addVertexWithUV(x + vtl.x, y + vtl.y, z + vtl.z, uvTL[0], uvTL[1]); // Top Left tessellator.addVertexWithUV(x + vbl.x, y + vbl.y, z + vbl.z, uvBL[0], uvBL[1]); // Bottom Left tessellator.addVertexWithUV(x + vbr.x, y + vbr.y, z + vbr.z, uvBR[0], uvBR[1]); // Bottom Right tessellator.addVertexWithUV(x + vtr.x, y + vtr.y, z + vtr.z, uvTR[0], uvTR[1]); // Top Right } } public static void renderModelFaceWithColor(BlockFace face, double x, double y, double z, float r, float g, float b) { Tessellator tessellator = Tessellator.instance; double[] uvTL; double[] uvBL; double[] uvBR; double[] uvTR; if (overrideBlockTexture >= 0) { uvTL = face.generateVertexUV(overrideBlockTexture, 0); uvBL = face.generateVertexUV(overrideBlockTexture, 1); uvBR = face.generateVertexUV(overrideBlockTexture, 2); uvTR = face.generateVertexUV(overrideBlockTexture, 3); } else { uvTL = face.getVertexUV(0); uvBL = face.getVertexUV(1); uvBR = face.getVertexUV(2); uvTR = face.getVertexUV(3); } Vector3f[] faceVertices = new Vector3f[4]; for (int i = 0; i < faceVertices.length; i++) { faceVertices[i] = face.vertices[i].rotateAroundX(origin, rotationX).rotateAroundY(origin, rotationY); } Vector3f vtl = faceVertices[0]; Vector3f vbl = faceVertices[1]; Vector3f vbr = faceVertices[2]; Vector3f vtr = faceVertices[3]; if (enableAO) { // Top Left tessellator.setColorOpaque_F(colorRedTopLeft * r, colorGreenTopLeft * g, colorBlueTopLeft * b); tessellator.addVertexWithUV(x + vtl.x, y + vtl.y, z + vtl.z, uvTL[0], uvTL[1]); // Bottom Left tessellator.setColorOpaque_F(colorRedBottomLeft * r, colorGreenBottomLeft * g, colorBlueBottomLeft * b); tessellator.addVertexWithUV(x + vbl.x, y + vbl.y, z + vbl.z, uvBL[0], uvBL[1]); // Bottom Right tessellator.setColorOpaque_F(colorRedBottomRight * r, colorGreenBottomRight * g, colorBlueBottomRight * b); tessellator.addVertexWithUV(x + vbr.x, y + vbr.y, z + vbr.z, uvBR[0], uvBR[1]); // Top Right tessellator.setColorOpaque_F(colorRedTopRight * r, colorGreenTopRight * g, colorBlueTopRight * b); tessellator.addVertexWithUV(x + vtr.x, y + vtr.y, z + vtr.z, uvTR[0], uvTR[1]); } else { tessellator.setColorOpaque_F(r, g, b); tessellator.addVertexWithUV(x + vtl.x, y + vtl.y, z + vtl.z, uvTL[0], uvTL[1]); // Top Left tessellator.addVertexWithUV(x + vbl.x, y + vbl.y, z + vbl.z, uvBL[0], uvBL[1]); // Bottom Left tessellator.addVertexWithUV(x + vbr.x, y + vbr.y, z + vbr.z, uvBR[0], uvBR[1]); // Bottom Right tessellator.addVertexWithUV(x + vtr.x, y + vtr.y, z + vtr.z, uvTR[0], uvTR[1]); // Top Right } } public static boolean renderStandardModelWithColorMultiplier(BlockModel model, Block block, int x, int y, int z, float r, float g, float b) { enableAO = false; Tessellator tessellator = Tessellator.instance; boolean renderedSomething = false; float cBottom = 0.5f; float cTop = 1.0f; float cNorthSouth = 0.8f; float cEastWest = 0.6f; float rTop = cTop * r; float gTop = cTop * g; float bTop = cTop * b; float rBottom = cBottom; float rNorthSouth = cNorthSouth; float rEastWest = cEastWest; float gBottom = cBottom; float gNorthSouth = cNorthSouth; float gEastWest = cEastWest; float bBottom = cBottom; float bNorthSouth = cNorthSouth; float bEastWest = cEastWest; rBottom *= r; rNorthSouth *= r; rEastWest *= r; gBottom *= g; gNorthSouth *= g; gEastWest *= g; bBottom *= b; bNorthSouth *= b; bEastWest *= b; float blockBrightness = rba().invokeGetBlockBrightness(rba().getBlockAccess(), x, y, z); for (BlockCube cube: model.blockCubes) { for (Side side: DragonFly.sides) { BlockFace face = cube.getFaceFromSide(side, rotationX, rotationY); if (face == null) continue; int _x = x + side.getOffsetX(); int _y = y + side.getOffsetY(); int _z = z + side.getOffsetZ(); if (!renderAllFaces){ if (!renderSide(model, cube, side, x, y, z)) continue; } float sideBrightness; if (!cube.isOuterFace(side, rotationX, rotationY) && !block.blockMaterial.isLiquid()){ sideBrightness = blockBrightness; } else { sideBrightness = rba().invokeGetBlockBrightness(rba().getBlockAccess(), _x, _y, _z); } float red = 1f; float green = 1f; float blue = 1f; if (cube.shade()){ switch (side){ case TOP: red = rTop; green = gTop; blue = bTop; break; case BOTTOM: red = rBottom; green = gBottom; blue = bBottom; break; case NORTH: case SOUTH: red = rNorthSouth; green = gNorthSouth; blue = bNorthSouth; break; case WEST: case EAST: red = rEastWest; green = gEastWest; blue = bEastWest; break; default: throw new RuntimeException("Specified side does not exist on a cube!!!"); } } tessellator.setColorOpaque_F(!face.getFullBright() ? red * sideBrightness : 1f, !face.getFullBright() ? green * sideBrightness : 1f, !face.getFullBright() ? blue * sideBrightness : 1f); renderModelFace(face, x, y, z); renderedSomething = true; } } return renderedSomething; } public static boolean renderSide(BlockModel model, BlockCube cube, Side side, int x, int y, int z){ WorldSource blockAccess = rba().getBlockAccess(); boolean renderOuterSide = blockAccess.getBlock(x, y, z).shouldSideBeRendered(blockAccess, x + side.getOffsetX(), y + side.getOffsetY(), z + side.getOffsetZ(), side.getId(), blockAccess.getBlockMetadata(x + side.getOffsetX(), y + side.getOffsetY(), z + side.getOffsetZ())); return !cube.getFaceFromSide(side, rotationX, rotationY).cullFace(x, y, z, renderOuterSide); } public static RenderBlocks getRenderBlocks(){ try { Field f = BlockModelRenderBlocks.class.getDeclaredField("renderBlocks"); f.setAccessible(true); RenderBlocks rb = (RenderBlocks) f.get(null); f.setAccessible(false); return rb; } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException(e); } }
public static RenderBlocksAccessor rba(){
1
2023-11-16 01:10:52+00:00
16k
AntonyCheng/ai-bi
src/main/java/top/sharehome/springbootinittemplate/config/captcha/service/impl/CaptchaServiceImpl.java
[ { "identifier": "CaptchaCondition", "path": "src/main/java/top/sharehome/springbootinittemplate/config/captcha/condition/CaptchaCondition.java", "snippet": "public class CaptchaCondition implements Condition {\n\n @Override\n public boolean matches(ConditionContext context, AnnotatedTypeMetadata m...
import cn.hutool.captcha.AbstractCaptcha; import cn.hutool.captcha.generator.CodeGenerator; import cn.hutool.core.util.ReflectUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Conditional; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.stereotype.Service; import top.sharehome.springbootinittemplate.config.captcha.condition.CaptchaCondition; import top.sharehome.springbootinittemplate.config.captcha.model.CaptchaCreate; import top.sharehome.springbootinittemplate.config.captcha.properties.CaptchaProperties; import top.sharehome.springbootinittemplate.config.captcha.properties.enums.CaptchaType; import top.sharehome.springbootinittemplate.config.captcha.service.CaptchaService; import top.sharehome.springbootinittemplate.common.base.ReturnCode; import top.sharehome.springbootinittemplate.config.bean.SpringContextHolder; import top.sharehome.springbootinittemplate.exception.customize.CustomizeReturnException; import top.sharehome.springbootinittemplate.utils.redisson.cache.CacheUtils; import top.sharehome.springbootinittemplate.utils.redisson.KeyPrefixConstants; import javax.annotation.Resource; import java.util.UUID;
14,143
package top.sharehome.springbootinittemplate.config.captcha.service.impl; /** * 验证码服务实现类 * * @author AntonyCheng */ @EnableConfigurationProperties(CaptchaProperties.class) @Service @Conditional(CaptchaCondition.class) public class CaptchaServiceImpl implements CaptchaService { @Resource private CaptchaProperties captchaProperties; @Override public CaptchaCreate createCaptcha() { CaptchaCreate captchaCreateResponse = new CaptchaCreate(); boolean enable = captchaProperties.getEnable(); captchaCreateResponse.setEnableCode(enable); if (!enable) { return captchaCreateResponse; } String uuid = UUID.randomUUID().toString().replace("-", ""); String codeKeyInRedis = KeyPrefixConstants.CAPTCHA_PREFIX + uuid; CaptchaType captchaType = captchaProperties.getType(); boolean isMath = CaptchaType.MATH == captchaType; int length = isMath ? ((captchaProperties.getNumberLength() < 1 || captchaProperties.getNumberLength() > 9) ? 1 : captchaProperties.getNumberLength()) : ((captchaProperties.getCharLength() < 1 || captchaProperties.getCharLength() > 100) ? 4 : captchaProperties.getCharLength()); CodeGenerator codeGenerator = ReflectUtil.newInstance(captchaType.getClazz(), length); AbstractCaptcha captcha = SpringContextHolder.getBean(captchaProperties.getCategory().getClazz()); captcha.setGenerator(codeGenerator); captcha.createCode(); String code = captcha.getCode(); if (isMath) { ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression(StringUtils.remove(code, "=")); code = exp.getValue(String.class); }
package top.sharehome.springbootinittemplate.config.captcha.service.impl; /** * 验证码服务实现类 * * @author AntonyCheng */ @EnableConfigurationProperties(CaptchaProperties.class) @Service @Conditional(CaptchaCondition.class) public class CaptchaServiceImpl implements CaptchaService { @Resource private CaptchaProperties captchaProperties; @Override public CaptchaCreate createCaptcha() { CaptchaCreate captchaCreateResponse = new CaptchaCreate(); boolean enable = captchaProperties.getEnable(); captchaCreateResponse.setEnableCode(enable); if (!enable) { return captchaCreateResponse; } String uuid = UUID.randomUUID().toString().replace("-", ""); String codeKeyInRedis = KeyPrefixConstants.CAPTCHA_PREFIX + uuid; CaptchaType captchaType = captchaProperties.getType(); boolean isMath = CaptchaType.MATH == captchaType; int length = isMath ? ((captchaProperties.getNumberLength() < 1 || captchaProperties.getNumberLength() > 9) ? 1 : captchaProperties.getNumberLength()) : ((captchaProperties.getCharLength() < 1 || captchaProperties.getCharLength() > 100) ? 4 : captchaProperties.getCharLength()); CodeGenerator codeGenerator = ReflectUtil.newInstance(captchaType.getClazz(), length); AbstractCaptcha captcha = SpringContextHolder.getBean(captchaProperties.getCategory().getClazz()); captcha.setGenerator(codeGenerator); captcha.createCode(); String code = captcha.getCode(); if (isMath) { ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression(StringUtils.remove(code, "=")); code = exp.getValue(String.class); }
CacheUtils.put(codeKeyInRedis, code, captchaProperties.getExpired());
8
2023-11-12 07:49:59+00:00
16k
Shushandr/offroad
src/net/osmand/data/MapObject.java
[ { "identifier": "Collator", "path": "src/net/osmand/Collator.java", "snippet": "public interface Collator extends java.util.Comparator<Object>, Cloneable {\n\t\t\n\tpublic boolean equals(String source, String target);\n\t\n\tpublic abstract int compare(String source, String target);\n}" }, { "id...
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.osmand.Collator; import net.osmand.OsmAndCollator; import net.osmand.util.Algorithms; import net.osmand.util.MapUtils; import net.sf.junidecode.Junidecode;
12,327
while(it.hasNext()) { Entry<String, String> e = it.next(); String key = e.getKey(); if(key.startsWith("name:")) { key = key.substring("name:".length()); } if(names == null) { names = new HashMap<String, String>(); } if(Algorithms.isEmpty(names.get(key))) { names.put(key, e.getValue()); } } } } public String getName(String lang) { return getName(lang, false); } public String getName(String lang, boolean transliterate) { if (lang != null) { if (lang.equals("en")) { // ignore transliterate option here for backward compatibility return getEnName(true); } else { // get name if(names != null) { String nm = names.get(lang); if(!Algorithms.isEmpty(nm)) { return nm; } if(transliterate) { return Junidecode.unidecode(getName()); } } } } return getName(); } public String getEnName(boolean transliterate) { if(!Algorithms.isEmpty(enName)){ return this.enName; } else if(!Algorithms.isEmpty(getName()) && transliterate){ return Junidecode.unidecode(getName()); } return ""; //$NON-NLS-1$ } public void setEnName(String enName) { this.enName = enName; } public LatLon getLocation(){ return location; } public void setLocation(double latitude, double longitude){ location = new LatLon(latitude, longitude); } @Override public int compareTo(MapObject o) { return OsmAndCollator.primaryCollator().compare(getName(), o.getName()); } public int getFileOffset() { return fileOffset; } public void setFileOffset(int fileOffset) { this.fileOffset = fileOffset; } @Override public String toString() { return getClass().getSimpleName() + " " + name +"("+id+")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MapObject other = (MapObject) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } public static class MapObjectComparator implements Comparator<MapObject>{ private final String l; Collator collator = OsmAndCollator.primaryCollator(); public MapObjectComparator(String lang){ this.l = lang; } @Override public int compare(MapObject o1, MapObject o2) { return collator.compare(o1.getName(l), o2.getName(l)); } } // new in offroad: public double getDistance(LatLon pCursorPosition) {
package net.osmand.data; public abstract class MapObject implements Comparable<MapObject> { protected String name = null; protected String enName = null; protected Map<String, String> names = null; protected LatLon location = null; protected int fileOffset = 0; protected Long id = null; public void setId(Long id) { this.id = id; } public Long getId() { if(id != null){ return id; } return null; } public String getName() { if (this.name != null) { return this.name; } return ""; //$NON-NLS-1$ } public void setName(String name) { this.name = name; } public void setName(String lang, String name) { if(names == null) { names = new HashMap<String, String>(); } names.put(lang, name); } public Map<String, String> getNamesMap(boolean includeEn) { if (!includeEn || Algorithms.isEmpty(enName)) { if (names == null) { return Collections.emptyMap(); } return names; } Map<String, String> mp = new HashMap<String, String>(); if(names != null) { mp.putAll(names); } mp.put("en", enName); return mp; } public List<String> getAllNames() { List<String> l = new ArrayList<String>(); if(!Algorithms.isEmpty(enName)) { l.add(enName); } if(names != null) { l.addAll(names.values()); } return l; } public void copyNames(MapObject s) { if(Algorithms.isEmpty(name)) { name = s.name; } if(Algorithms.isEmpty(enName)) { enName = s.enName; } copyNames(s.names); } public void copyNames(Map<String, String> snames) { if(snames != null && snames.containsKey("name:en")){ enName = snames.get("name:en"); } if(snames != null && snames.containsKey("en")){ enName = snames.get("en"); } if(snames != null){ Iterator<Entry<String, String>> it = snames.entrySet().iterator(); while(it.hasNext()) { Entry<String, String> e = it.next(); String key = e.getKey(); if(key.startsWith("name:")) { key = key.substring("name:".length()); } if(names == null) { names = new HashMap<String, String>(); } if(Algorithms.isEmpty(names.get(key))) { names.put(key, e.getValue()); } } } } public String getName(String lang) { return getName(lang, false); } public String getName(String lang, boolean transliterate) { if (lang != null) { if (lang.equals("en")) { // ignore transliterate option here for backward compatibility return getEnName(true); } else { // get name if(names != null) { String nm = names.get(lang); if(!Algorithms.isEmpty(nm)) { return nm; } if(transliterate) { return Junidecode.unidecode(getName()); } } } } return getName(); } public String getEnName(boolean transliterate) { if(!Algorithms.isEmpty(enName)){ return this.enName; } else if(!Algorithms.isEmpty(getName()) && transliterate){ return Junidecode.unidecode(getName()); } return ""; //$NON-NLS-1$ } public void setEnName(String enName) { this.enName = enName; } public LatLon getLocation(){ return location; } public void setLocation(double latitude, double longitude){ location = new LatLon(latitude, longitude); } @Override public int compareTo(MapObject o) { return OsmAndCollator.primaryCollator().compare(getName(), o.getName()); } public int getFileOffset() { return fileOffset; } public void setFileOffset(int fileOffset) { this.fileOffset = fileOffset; } @Override public String toString() { return getClass().getSimpleName() + " " + name +"("+id+")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MapObject other = (MapObject) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } public static class MapObjectComparator implements Comparator<MapObject>{ private final String l; Collator collator = OsmAndCollator.primaryCollator(); public MapObjectComparator(String lang){ this.l = lang; } @Override public int compare(MapObject o1, MapObject o2) { return collator.compare(o1.getName(l), o2.getName(l)); } } // new in offroad: public double getDistance(LatLon pCursorPosition) {
return MapUtils.getDistance(getLocation(), pCursorPosition);
3
2023-11-15 05:04:55+00:00
16k
WuKongOpenSource/Wukong_HRM
hrm/hrm-web/src/main/java/com/kakarote/hrm/service/impl/HrmAttendanceGroupServiceImpl.java
[ { "identifier": "OperationLog", "path": "common/common-log/src/main/java/com/kakarote/common/log/entity/OperationLog.java", "snippet": "@Getter\n@Setter\npublic class OperationLog {\n //操作对象\n private Object operationObject;\n //操作详情\n private String operationInfo;\n\n private BehaviorEnu...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.LocalDateTimeUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.kakarote.common.entity.SimpleUser; import com.kakarote.common.entity.UserInfo; import com.kakarote.common.log.entity.OperationLog; import com.kakarote.common.utils.UserUtil; import com.kakarote.core.common.Const; import com.kakarote.core.entity.BasePage; import com.kakarote.core.exception.CrmException; import com.kakarote.core.servlet.BaseServiceImpl; import com.kakarote.core.utils.TagUtil; import com.kakarote.hrm.common.HrmCodeEnum; import com.kakarote.hrm.constant.EmployeeEntryStatus; import com.kakarote.hrm.constant.IsEnum; import com.kakarote.hrm.entity.BO.QueryHrmAttendanceGroupBO; import com.kakarote.hrm.entity.BO.SetAttendanceGroupBO; import com.kakarote.hrm.entity.PO.*; import com.kakarote.hrm.entity.VO.HrmAttendanceGroupVO; import com.kakarote.hrm.entity.VO.HrmAttendanceShiftVO; import com.kakarote.hrm.entity.VO.QueryMyAttendanceGroupVO; import com.kakarote.hrm.mapper.HrmAttendanceGroupMapper; import com.kakarote.hrm.service.*; import com.kakarote.hrm.utils.EmployeeCacheUtil; import com.kakarote.ids.provider.utils.UserCacheUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; import java.util.stream.Collectors;
13,343
package com.kakarote.hrm.service.impl; /** * <p> * 考勤组表 服务实现类 * </p> * * @author guomenghao * @since 2021-08-13 */ @Service public class HrmAttendanceGroupServiceImpl extends BaseServiceImpl<HrmAttendanceGroupMapper, HrmAttendanceGroup> implements IHrmAttendanceGroupService { @Autowired private HrmAttendanceGroupMapper attendanceGroupMapper; @Autowired private IHrmDeptService deptService; @Autowired private IHrmAttendanceWifiService hrmAttendanceWifiService; @Autowired private IHrmAttendancePointService hrmAttendancePointService; @Autowired private IHrmEmployeeService employeeService; @Autowired private IHrmAttendanceShiftService attendanceShiftService; @Autowired private IHrmAttendanceRuleService attendanceRuleService; @Autowired private IHrmAttendanceGroupRelationDeptService attendGroupRelDeptService; @Autowired private IHrmAttendanceGroupRelationEmployeeService attendGroupRelEmpService; @Autowired private IHrmConfigService configService; @Autowired private IHrmAttendanceClockService attendanceClockService; @Autowired private IHrmAttendanceDateShiftService attendanceDateShiftService; private static final int TWO = 2; private static final int ONE = 1; @Override public BasePage<HrmAttendanceGroupVO> queryAttendanceGroupPageList(QueryHrmAttendanceGroupBO queryHrmAttendanceGroupBO) { checkInitAttendData(); QueryWrapper<HrmAttendanceGroup> hrmAttendanceGroupQueryWrapper = new QueryWrapper<>(); hrmAttendanceGroupQueryWrapper.eq("old_setting", IsEnum.NO.getValue()); hrmAttendanceGroupQueryWrapper.like(StrUtil.isNotEmpty(queryHrmAttendanceGroupBO.getName()), "name", queryHrmAttendanceGroupBO.getName()); BasePage<HrmAttendanceGroup> attendanceGroupBasePage = attendanceGroupMapper.selectPage(queryHrmAttendanceGroupBO.parse(), hrmAttendanceGroupQueryWrapper); List<HrmAttendanceGroupVO> attendanceGroupPageListVOList = new ArrayList<>(); attendanceGroupBasePage.getList().forEach(attendanceGroup -> { HrmAttendanceGroupVO attendanceGroupPageListVO = new HrmAttendanceGroupVO(); BeanUtil.copyProperties(attendanceGroup, attendanceGroupPageListVO); Set<Long> deptIds = attendGroupRelDeptService.lambdaQuery().eq(HrmAttendanceGroupRelationDept::getAttendanceGroupId, attendanceGroup.getAttendanceGroupId()).list() .stream().map(HrmAttendanceGroupRelationDept::getDeptId).collect(Collectors.toSet()); Set<Long> deptIdSet = deptService.queryChildDeptId(deptIds); attendanceGroupPageListVO.setDeptList(deptService.querySimpleDeptList(deptIdSet)); Set<Long> employeeIds = attendGroupRelEmpService.lambdaQuery().eq(HrmAttendanceGroupRelationEmployee::getAttendanceGroupId, attendanceGroup.getAttendanceGroupId()).list() .stream().map(HrmAttendanceGroupRelationEmployee::getEmployeeId).collect(Collectors.toSet()); attendanceGroupPageListVO.setEmployeeList(employeeService.querySimpleEmployeeList(employeeIds)); HrmAttendanceRule hrmAttendanceRule = attendanceRuleService.getById(attendanceGroup.getAttendanceRuleId()); if (hrmAttendanceRule != null) { attendanceGroupPageListVO.setAttendanceRuleName(hrmAttendanceRule.getAttendanceRuleName()); } attendanceGroupPageListVO.setShiftSetting(StrUtil.splitTrim(attendanceGroup.getShiftSetting(), Const.SEPARATOR)); Map<Integer, Map<String, Object>> attendanceDate = attendanceShiftService.queryAttendanceDate(attendanceGroup.getShiftSetting()); String specialStr = Optional.ofNullable(attendanceGroup.getSpecialDateSetting()).orElse(""); attendanceGroupPageListVO.setSpecialDateSetting(JSON.parse(specialStr)); attendanceGroupPageListVO.setAttendanceDate(attendanceDate); List<HrmAttendancePoint> pointList = hrmAttendancePointService.lambdaQuery().eq(HrmAttendancePoint::getAttendanceGroupId, attendanceGroup.getAttendanceGroupId()).list(); attendanceGroupPageListVO.setPointList(pointList); List<HrmAttendanceWifi> wifiList = hrmAttendanceWifiService.lambdaQuery().eq(HrmAttendanceWifi::getAttendanceGroupId, attendanceGroup.getAttendanceGroupId()).list(); attendanceGroupPageListVO.setWifiList(wifiList); attendanceGroupPageListVOList.add(attendanceGroupPageListVO); }); BasePage<HrmAttendanceGroupVO> page = new BasePage<>(attendanceGroupBasePage.getCurrent(), attendanceGroupBasePage.getSize(), attendanceGroupBasePage.getTotal()); page.setList(attendanceGroupPageListVOList); return page; } @Override @Transactional(rollbackFor = Exception.class) public void setAttendanceGroup(SetAttendanceGroupBO attendanceGroup) { HrmAttendanceGroup hrmAttendanceGroup = BeanUtil.copyProperties(attendanceGroup, HrmAttendanceGroup.class); //获取考勤分组ID Long attendanceGroupId = hrmAttendanceGroup.getAttendanceGroupId(); List<Long> employeeIdList = attendanceGroup.getEmployeeIds(); List<Long> deptIdsList = attendanceGroup.getDeptIds(); //如果存在员工和部门都选择,判断当前考勤范围与员工唯一 if (CollUtil.isNotEmpty(employeeIdList) && CollUtil.isNotEmpty(deptIdsList)) { Set<Long> deptIds = deptService.queryChildDeptId(deptIdsList); List<Long> empIdList = employeeService.lambdaQuery().in(HrmEmployee::getDeptId, deptIds).list().stream().map(HrmEmployee::getEmployeeId).collect(Collectors.toList()); Collection<Long> empIntersection = CollUtil.intersection(employeeIdList, empIdList); if (!empIntersection.isEmpty()) {
package com.kakarote.hrm.service.impl; /** * <p> * 考勤组表 服务实现类 * </p> * * @author guomenghao * @since 2021-08-13 */ @Service public class HrmAttendanceGroupServiceImpl extends BaseServiceImpl<HrmAttendanceGroupMapper, HrmAttendanceGroup> implements IHrmAttendanceGroupService { @Autowired private HrmAttendanceGroupMapper attendanceGroupMapper; @Autowired private IHrmDeptService deptService; @Autowired private IHrmAttendanceWifiService hrmAttendanceWifiService; @Autowired private IHrmAttendancePointService hrmAttendancePointService; @Autowired private IHrmEmployeeService employeeService; @Autowired private IHrmAttendanceShiftService attendanceShiftService; @Autowired private IHrmAttendanceRuleService attendanceRuleService; @Autowired private IHrmAttendanceGroupRelationDeptService attendGroupRelDeptService; @Autowired private IHrmAttendanceGroupRelationEmployeeService attendGroupRelEmpService; @Autowired private IHrmConfigService configService; @Autowired private IHrmAttendanceClockService attendanceClockService; @Autowired private IHrmAttendanceDateShiftService attendanceDateShiftService; private static final int TWO = 2; private static final int ONE = 1; @Override public BasePage<HrmAttendanceGroupVO> queryAttendanceGroupPageList(QueryHrmAttendanceGroupBO queryHrmAttendanceGroupBO) { checkInitAttendData(); QueryWrapper<HrmAttendanceGroup> hrmAttendanceGroupQueryWrapper = new QueryWrapper<>(); hrmAttendanceGroupQueryWrapper.eq("old_setting", IsEnum.NO.getValue()); hrmAttendanceGroupQueryWrapper.like(StrUtil.isNotEmpty(queryHrmAttendanceGroupBO.getName()), "name", queryHrmAttendanceGroupBO.getName()); BasePage<HrmAttendanceGroup> attendanceGroupBasePage = attendanceGroupMapper.selectPage(queryHrmAttendanceGroupBO.parse(), hrmAttendanceGroupQueryWrapper); List<HrmAttendanceGroupVO> attendanceGroupPageListVOList = new ArrayList<>(); attendanceGroupBasePage.getList().forEach(attendanceGroup -> { HrmAttendanceGroupVO attendanceGroupPageListVO = new HrmAttendanceGroupVO(); BeanUtil.copyProperties(attendanceGroup, attendanceGroupPageListVO); Set<Long> deptIds = attendGroupRelDeptService.lambdaQuery().eq(HrmAttendanceGroupRelationDept::getAttendanceGroupId, attendanceGroup.getAttendanceGroupId()).list() .stream().map(HrmAttendanceGroupRelationDept::getDeptId).collect(Collectors.toSet()); Set<Long> deptIdSet = deptService.queryChildDeptId(deptIds); attendanceGroupPageListVO.setDeptList(deptService.querySimpleDeptList(deptIdSet)); Set<Long> employeeIds = attendGroupRelEmpService.lambdaQuery().eq(HrmAttendanceGroupRelationEmployee::getAttendanceGroupId, attendanceGroup.getAttendanceGroupId()).list() .stream().map(HrmAttendanceGroupRelationEmployee::getEmployeeId).collect(Collectors.toSet()); attendanceGroupPageListVO.setEmployeeList(employeeService.querySimpleEmployeeList(employeeIds)); HrmAttendanceRule hrmAttendanceRule = attendanceRuleService.getById(attendanceGroup.getAttendanceRuleId()); if (hrmAttendanceRule != null) { attendanceGroupPageListVO.setAttendanceRuleName(hrmAttendanceRule.getAttendanceRuleName()); } attendanceGroupPageListVO.setShiftSetting(StrUtil.splitTrim(attendanceGroup.getShiftSetting(), Const.SEPARATOR)); Map<Integer, Map<String, Object>> attendanceDate = attendanceShiftService.queryAttendanceDate(attendanceGroup.getShiftSetting()); String specialStr = Optional.ofNullable(attendanceGroup.getSpecialDateSetting()).orElse(""); attendanceGroupPageListVO.setSpecialDateSetting(JSON.parse(specialStr)); attendanceGroupPageListVO.setAttendanceDate(attendanceDate); List<HrmAttendancePoint> pointList = hrmAttendancePointService.lambdaQuery().eq(HrmAttendancePoint::getAttendanceGroupId, attendanceGroup.getAttendanceGroupId()).list(); attendanceGroupPageListVO.setPointList(pointList); List<HrmAttendanceWifi> wifiList = hrmAttendanceWifiService.lambdaQuery().eq(HrmAttendanceWifi::getAttendanceGroupId, attendanceGroup.getAttendanceGroupId()).list(); attendanceGroupPageListVO.setWifiList(wifiList); attendanceGroupPageListVOList.add(attendanceGroupPageListVO); }); BasePage<HrmAttendanceGroupVO> page = new BasePage<>(attendanceGroupBasePage.getCurrent(), attendanceGroupBasePage.getSize(), attendanceGroupBasePage.getTotal()); page.setList(attendanceGroupPageListVOList); return page; } @Override @Transactional(rollbackFor = Exception.class) public void setAttendanceGroup(SetAttendanceGroupBO attendanceGroup) { HrmAttendanceGroup hrmAttendanceGroup = BeanUtil.copyProperties(attendanceGroup, HrmAttendanceGroup.class); //获取考勤分组ID Long attendanceGroupId = hrmAttendanceGroup.getAttendanceGroupId(); List<Long> employeeIdList = attendanceGroup.getEmployeeIds(); List<Long> deptIdsList = attendanceGroup.getDeptIds(); //如果存在员工和部门都选择,判断当前考勤范围与员工唯一 if (CollUtil.isNotEmpty(employeeIdList) && CollUtil.isNotEmpty(deptIdsList)) { Set<Long> deptIds = deptService.queryChildDeptId(deptIdsList); List<Long> empIdList = employeeService.lambdaQuery().in(HrmEmployee::getDeptId, deptIds).list().stream().map(HrmEmployee::getEmployeeId).collect(Collectors.toList()); Collection<Long> empIntersection = CollUtil.intersection(employeeIdList, empIdList); if (!empIntersection.isEmpty()) {
throw new CrmException(HrmCodeEnum.THE_ATTEND_GROUP_ALREADY_DEPT_EMPLOYEE_ERROR);
6
2023-10-17 05:49:52+00:00
16k
djkcyl/Shamrock
qqinterface/src/main/java/com/tencent/mobileqq/profilecard/processor/AbsProfileBusinessProcessor.java
[ { "identifier": "Card", "path": "qqinterface/src/main/java/com/tencent/mobileqq/data/Card.java", "snippet": "public class Card {\n public static final long BIRTHDAY_INVALID = 0;\n public static final int CONSTELLATION_INVALID = 0;\n public static final short FEMALE = 1;\n public static final...
import android.os.Bundle; import android.util.SparseArray; import com.tencent.mobileqq.data.Card; import com.tencent.mobileqq.profilecard.entity.BusinessReqBuffer; import com.tencent.mobileqq.profilecard.entity.BusinessRespBuffer; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import SummaryCard.RespHead; import SummaryCard.RespSummaryCard; import mqq.app.AppRuntime; import tencent.im.oidb.cmd0x5eb.oidb_0x5eb;
12,423
package com.tencent.mobileqq.profilecard.processor; public abstract class AbsProfileBusinessProcessor implements IRequestProfileCardCallback, IGetProfileDetailCallback { public AbsProfileBusinessProcessor(AppRuntime appRuntime) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailRequestForLogin(List<Short> list) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailResponseBegin(Bundle bundle) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailResponseEnd(Bundle bundle, boolean z, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLV(Bundle bundle, long j2, Card card, short s, short s2, ByteBuffer byteBuffer) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLVBegin(Bundle bundle, long j2, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLVEnd(Bundle bundle, long j2, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback public void onProcessProfile0x5eb(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard, oidb_0x5eb.UdcUinData oidb_0x5eb_udcuindata) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback public void onProcessProfileCard(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback public void onProcessProfileService(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard, SparseArray<BusinessRespBuffer> sparseArray) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback
package com.tencent.mobileqq.profilecard.processor; public abstract class AbsProfileBusinessProcessor implements IRequestProfileCardCallback, IGetProfileDetailCallback { public AbsProfileBusinessProcessor(AppRuntime appRuntime) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailRequestForLogin(List<Short> list) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailResponseBegin(Bundle bundle) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailResponseEnd(Bundle bundle, boolean z, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLV(Bundle bundle, long j2, Card card, short s, short s2, ByteBuffer byteBuffer) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLVBegin(Bundle bundle, long j2, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IGetProfileDetailCallback public void onGetProfileDetailTLVEnd(Bundle bundle, long j2, Card card) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback public void onProcessProfile0x5eb(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard, oidb_0x5eb.UdcUinData oidb_0x5eb_udcuindata) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback public void onProcessProfileCard(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback public void onProcessProfileService(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard, SparseArray<BusinessRespBuffer> sparseArray) { } @Override // com.tencent.mobileqq.profilecard.processor.IRequestProfileCardCallback
public void onRequestProfileCard(Bundle bundle, ArrayList<BusinessReqBuffer> arrayList, ArrayList<Integer> arrayList2) {
1
2023-10-20 10:43:47+00:00
16k
wyjsonGo/GoRouter
GoRouter-Api/src/main/java/com/wyjson/router/core/RouteCenter.java
[ { "identifier": "ROUTER_CURRENT_PATH", "path": "GoRouter-Api/src/main/java/com/wyjson/router/core/Constants.java", "snippet": "static final String ROUTER_CURRENT_PATH = \"go_router_current_path\";" }, { "identifier": "ROUTER_RAW_URI", "path": "GoRouter-Api/src/main/java/com/wyjson/router/cor...
import static com.wyjson.router.core.Constants.ROUTER_CURRENT_PATH; import static com.wyjson.router.core.Constants.ROUTER_RAW_URI; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.wyjson.router.GoRouter; import com.wyjson.router.enums.ParamType; import com.wyjson.router.exception.NoFoundRouteException; import com.wyjson.router.exception.ParamException; import com.wyjson.router.exception.RouterException; import com.wyjson.router.interfaces.IJsonService; import com.wyjson.router.model.Card; import com.wyjson.router.model.CardMeta; import com.wyjson.router.model.ParamMeta; import com.wyjson.router.module.interfaces.IRouteModuleGroup; import com.wyjson.router.utils.MapUtils; import com.wyjson.router.utils.TextUtils; import java.lang.reflect.Field; import java.util.Map;
11,916
package com.wyjson.router.core; public class RouteCenter { private static IJsonService jsonService; public static Map<String, IRouteModuleGroup> getRouteGroups() { return Warehouse.routeGroups; } /** * 动态添加路由分组,按需加载路由 * * @param group * @param routeModuleGroup */ public static void addRouterGroup(String group, IRouteModuleGroup routeModuleGroup) { Warehouse.routeGroups.put(group, routeModuleGroup); GoRouter.logger.info(null, "[addRouterGroup] Add a route group[" + group + "] dynamically"); } /** * 获取路由元数据 * * @param card * @return * @throws NoFoundRouteException */ public static CardMeta getCardMeta(Card card) throws NoFoundRouteException { CardMeta cardMeta = Warehouse.routes.get(card.getPath()); if (cardMeta == null) { if (!Warehouse.routeGroups.containsKey(card.getGroup())) { throw new NoFoundRouteException("There is no route match the path [" + card.getPath() + "], in group [" + card.getGroup() + "]"); } else { try { if (GoRouter.isDebug()) { GoRouter.logger.debug(null, "[getCardMeta] The group [" + card.getGroup() + "] starts loading, trigger by [" + card.getPath() + "]"); } // Load route and cache it into memory, then delete from metas. if (Warehouse.routeGroups.containsKey(card.getGroup())) { Warehouse.routeGroups.get(card.getGroup()).load(); Warehouse.routeGroups.remove(card.getGroup()); } if (GoRouter.isDebug()) { GoRouter.logger.debug(null, "[getCardMeta] The group [" + card.getGroup() + "] has already been loaded, trigger by [" + card.getPath() + "]"); } } catch (Exception e) { throw new RouterException("Fatal exception when loading route group[" + card.getGroup() + "] meta. [" + e.getMessage() + "]"); } return getCardMeta(card);// Reload } } else { GoRouter.logger.info(null, "[getCardMeta] " + cardMeta); } return cardMeta; } /** * 添加路由元数据 * * @param cardMeta */ public static void addCardMeta(CardMeta cardMeta) { Warehouse.routes.put(cardMeta.getPath(), cardMeta); GoRouter.logger.debug(null, "[addCardMeta] size:" + Warehouse.routes.size() + ", commit:" + cardMeta); } /** * 获取原始的URI * * @param target * @param <T> */ public static <T> String getRawURI(T target) { Bundle bundle; try { bundle = getBundle(target, null, null); } catch (Exception e) { throw new RuntimeException("getRawURI() " + e.getMessage()); } return bundle.getString(ROUTER_RAW_URI); } /** * 获取当前页面路径 * * @param target * @param <T> */ public static <T> String getCurrentPath(T target) { Bundle bundle; if (target instanceof Bundle) { bundle = (Bundle) target; } else { try { bundle = getBundle(target, null, null); } catch (Exception e) { throw new RuntimeException("getCurrentPath() " + e.getMessage()); } } return bundle.getString(ROUTER_CURRENT_PATH); } @NonNull private static <T> Bundle getBundle(T target, Intent intent, Bundle bundle) { if (bundle == null) { if (intent != null) { bundle = intent.getExtras(); } else { if (target instanceof Activity) { bundle = ((Activity) target).getIntent().getExtras(); } else if (target instanceof Fragment) { bundle = ((Fragment) target).getArguments(); } } if (bundle == null) { throw new RouterException("method does not get bundle!"); } } return bundle; } /** * 解析参数 * * @param target * @param intent * @param bundle * @param isCheck 是否检查 isRequired * @param <T> * @throws ParamException * @Deprecated Higher performance methods have been available since version 2.3.2 */ @Deprecated(since = "2.3.2") public static <T> void inject(T target, Intent intent, Bundle bundle, boolean isCheck) throws ParamException { GoRouter.logger.debug(null, "[inject] Auto Inject Start!"); try { bundle = getBundle(target, intent, bundle); } catch (Exception e) { throw new RuntimeException("inject() " + e.getMessage()); } String path = getCurrentPath(bundle); if (TextUtils.isEmpty(path)) { GoRouter.logger.error(null, "[inject] The " + ROUTER_CURRENT_PATH + " parameter was not found in the intent"); return; } CardMeta cardMeta = GoRouter.getInstance().build(path).getCardMeta(); if (cardMeta != null) { Map<String, ParamMeta> paramsType = cardMeta.getParamsType(); for (Map.Entry<String, ParamMeta> entry : paramsType.entrySet()) { String paramName = entry.getValue().getName(); Object value = bundle.get(paramName); if (value == null) { if (isCheck && entry.getValue().isRequired()) { throw new ParamException(paramName); } continue; } GoRouter.logger.debug(null, "[inject] " + paramName + ":" + value); try { Field injectField = getDeclaredField(target.getClass(), entry.getKey());
package com.wyjson.router.core; public class RouteCenter { private static IJsonService jsonService; public static Map<String, IRouteModuleGroup> getRouteGroups() { return Warehouse.routeGroups; } /** * 动态添加路由分组,按需加载路由 * * @param group * @param routeModuleGroup */ public static void addRouterGroup(String group, IRouteModuleGroup routeModuleGroup) { Warehouse.routeGroups.put(group, routeModuleGroup); GoRouter.logger.info(null, "[addRouterGroup] Add a route group[" + group + "] dynamically"); } /** * 获取路由元数据 * * @param card * @return * @throws NoFoundRouteException */ public static CardMeta getCardMeta(Card card) throws NoFoundRouteException { CardMeta cardMeta = Warehouse.routes.get(card.getPath()); if (cardMeta == null) { if (!Warehouse.routeGroups.containsKey(card.getGroup())) { throw new NoFoundRouteException("There is no route match the path [" + card.getPath() + "], in group [" + card.getGroup() + "]"); } else { try { if (GoRouter.isDebug()) { GoRouter.logger.debug(null, "[getCardMeta] The group [" + card.getGroup() + "] starts loading, trigger by [" + card.getPath() + "]"); } // Load route and cache it into memory, then delete from metas. if (Warehouse.routeGroups.containsKey(card.getGroup())) { Warehouse.routeGroups.get(card.getGroup()).load(); Warehouse.routeGroups.remove(card.getGroup()); } if (GoRouter.isDebug()) { GoRouter.logger.debug(null, "[getCardMeta] The group [" + card.getGroup() + "] has already been loaded, trigger by [" + card.getPath() + "]"); } } catch (Exception e) { throw new RouterException("Fatal exception when loading route group[" + card.getGroup() + "] meta. [" + e.getMessage() + "]"); } return getCardMeta(card);// Reload } } else { GoRouter.logger.info(null, "[getCardMeta] " + cardMeta); } return cardMeta; } /** * 添加路由元数据 * * @param cardMeta */ public static void addCardMeta(CardMeta cardMeta) { Warehouse.routes.put(cardMeta.getPath(), cardMeta); GoRouter.logger.debug(null, "[addCardMeta] size:" + Warehouse.routes.size() + ", commit:" + cardMeta); } /** * 获取原始的URI * * @param target * @param <T> */ public static <T> String getRawURI(T target) { Bundle bundle; try { bundle = getBundle(target, null, null); } catch (Exception e) { throw new RuntimeException("getRawURI() " + e.getMessage()); } return bundle.getString(ROUTER_RAW_URI); } /** * 获取当前页面路径 * * @param target * @param <T> */ public static <T> String getCurrentPath(T target) { Bundle bundle; if (target instanceof Bundle) { bundle = (Bundle) target; } else { try { bundle = getBundle(target, null, null); } catch (Exception e) { throw new RuntimeException("getCurrentPath() " + e.getMessage()); } } return bundle.getString(ROUTER_CURRENT_PATH); } @NonNull private static <T> Bundle getBundle(T target, Intent intent, Bundle bundle) { if (bundle == null) { if (intent != null) { bundle = intent.getExtras(); } else { if (target instanceof Activity) { bundle = ((Activity) target).getIntent().getExtras(); } else if (target instanceof Fragment) { bundle = ((Fragment) target).getArguments(); } } if (bundle == null) { throw new RouterException("method does not get bundle!"); } } return bundle; } /** * 解析参数 * * @param target * @param intent * @param bundle * @param isCheck 是否检查 isRequired * @param <T> * @throws ParamException * @Deprecated Higher performance methods have been available since version 2.3.2 */ @Deprecated(since = "2.3.2") public static <T> void inject(T target, Intent intent, Bundle bundle, boolean isCheck) throws ParamException { GoRouter.logger.debug(null, "[inject] Auto Inject Start!"); try { bundle = getBundle(target, intent, bundle); } catch (Exception e) { throw new RuntimeException("inject() " + e.getMessage()); } String path = getCurrentPath(bundle); if (TextUtils.isEmpty(path)) { GoRouter.logger.error(null, "[inject] The " + ROUTER_CURRENT_PATH + " parameter was not found in the intent"); return; } CardMeta cardMeta = GoRouter.getInstance().build(path).getCardMeta(); if (cardMeta != null) { Map<String, ParamMeta> paramsType = cardMeta.getParamsType(); for (Map.Entry<String, ParamMeta> entry : paramsType.entrySet()) { String paramName = entry.getValue().getName(); Object value = bundle.get(paramName); if (value == null) { if (isCheck && entry.getValue().isRequired()) { throw new ParamException(paramName); } continue; } GoRouter.logger.debug(null, "[inject] " + paramName + ":" + value); try { Field injectField = getDeclaredField(target.getClass(), entry.getKey());
if (ParamType.Object == entry.getValue().getType() && value instanceof String) {
3
2023-10-18 13:52:07+00:00
16k
trpc-group/trpc-java
trpc-test/trpc-test-integration/src/integration-test/java/com/tencent/trpc/integration/test/transport/CodecIntegrationTest.java
[ { "identifier": "RpcClientContext", "path": "trpc-core/src/main/java/com/tencent/trpc/core/rpc/RpcClientContext.java", "snippet": "public class RpcClientContext extends RpcContext {\n\n /**\n * Remote service name to be called, commonly used for generic calls.\n */\n private String rpcServ...
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import com.tencent.trpc.core.rpc.RpcClientContext; import com.tencent.trpc.core.rpc.TRpcProxy; import com.tencent.trpc.integration.test.TrpcServerApplication; import com.tencent.trpc.integration.test.stub.EchoAPI; import com.tencent.trpc.integration.test.stub.EchoService.EchoRequest; import com.tencent.trpc.integration.test.stub.EchoService.EchoResponse; import com.tencent.trpc.integration.test.stub.JpbEchoAPI; import com.tencent.trpc.integration.test.stub.jpb.EchoRequestPojo; import com.tencent.trpc.integration.test.stub.jpb.EchoResponsePojo; import com.tencent.trpc.spring.annotation.TRpcClient; import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles;
10,834
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.integration.test.transport; /** * Codec related integration tests. Related configuration files: * <ul> * <li>application-codec.yml</li> * <li>application-codec-compressor-error.yml</li> * <li>application-codec-serialization-error.yml</li> * </ul> */ @ActiveProfiles("codec") @SpringBootTest(classes = TrpcServerApplication.class) public class CodecIntegrationTest { @TRpcClient(id = "no-compress-client") private EchoAPI noCompressEchoAPI; @TRpcClient(id = "gzip-client") private EchoAPI gzipEchoAPI; @TRpcClient(id = "snappy-client") private EchoAPI snappyEchoAPI; @TRpcClient(id = "pb-client") private EchoAPI pbEchoAPI; @TRpcClient(id = "jpb-client") private JpbEchoAPI jpbEchoAPI; @TRpcClient(id = "json-client") private EchoAPI jsonEchoAPI; @TRpcClient(id = "pb-json-client") private EchoAPI pbToJsonEchoAPI; @TRpcClient(id = "pb-jpb-client") private EchoAPI pbToJpbEchoAPI; @TRpcClient(id = "jpb-pb-client") private JpbEchoAPI jpbToPbEchoAPI; @TRpcClient(id = "jpb-json-client") private JpbEchoAPI jpbToJsonEchoAPI; @TRpcClient(id = "json-pb-client") private EchoAPI jsonToPbEchoAPI; @TRpcClient(id = "json-jpb-client") private EchoAPI jsonToJpbEchoAPI; /** * Test for 'none' compressor */ @Test public void noCompressTest() { assertResponseOK(noCompressEchoAPI, "1"); // send request size lower than compress_min_bytes assertResponseOK(noCompressEchoAPI, "greater_than_compress_min_bytes"); } /** * Test for 'gzip' compressor */ @Test public void gzipTest() { assertResponseOK(gzipEchoAPI, "1"); assertResponseOK(gzipEchoAPI, "greater_than_compress_min_bytes"); } /** * Test for 'snappy' compressor */ @Test public void snappyTest() { assertResponseOK(snappyEchoAPI, "1"); assertResponseOK(snappyEchoAPI, "greater_than_compress_min_bytes"); } /** * Server-side non-exist compressor test, related configuration file: * <code>application-codec-compressor-error.yml</code> */ @Test public void testNonExistServerSideCompressor() { assertThrows(RuntimeException.class, () -> SpringApplication.run(TrpcServerApplication.class, "--spring.profiles.active=codec-compressor-error")); } /** * Client-side non-exist compressor test */ @Test public void testNonExistClientSideCompressor() { assertThrows(RuntimeException.class, () ->
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.integration.test.transport; /** * Codec related integration tests. Related configuration files: * <ul> * <li>application-codec.yml</li> * <li>application-codec-compressor-error.yml</li> * <li>application-codec-serialization-error.yml</li> * </ul> */ @ActiveProfiles("codec") @SpringBootTest(classes = TrpcServerApplication.class) public class CodecIntegrationTest { @TRpcClient(id = "no-compress-client") private EchoAPI noCompressEchoAPI; @TRpcClient(id = "gzip-client") private EchoAPI gzipEchoAPI; @TRpcClient(id = "snappy-client") private EchoAPI snappyEchoAPI; @TRpcClient(id = "pb-client") private EchoAPI pbEchoAPI; @TRpcClient(id = "jpb-client") private JpbEchoAPI jpbEchoAPI; @TRpcClient(id = "json-client") private EchoAPI jsonEchoAPI; @TRpcClient(id = "pb-json-client") private EchoAPI pbToJsonEchoAPI; @TRpcClient(id = "pb-jpb-client") private EchoAPI pbToJpbEchoAPI; @TRpcClient(id = "jpb-pb-client") private JpbEchoAPI jpbToPbEchoAPI; @TRpcClient(id = "jpb-json-client") private JpbEchoAPI jpbToJsonEchoAPI; @TRpcClient(id = "json-pb-client") private EchoAPI jsonToPbEchoAPI; @TRpcClient(id = "json-jpb-client") private EchoAPI jsonToJpbEchoAPI; /** * Test for 'none' compressor */ @Test public void noCompressTest() { assertResponseOK(noCompressEchoAPI, "1"); // send request size lower than compress_min_bytes assertResponseOK(noCompressEchoAPI, "greater_than_compress_min_bytes"); } /** * Test for 'gzip' compressor */ @Test public void gzipTest() { assertResponseOK(gzipEchoAPI, "1"); assertResponseOK(gzipEchoAPI, "greater_than_compress_min_bytes"); } /** * Test for 'snappy' compressor */ @Test public void snappyTest() { assertResponseOK(snappyEchoAPI, "1"); assertResponseOK(snappyEchoAPI, "greater_than_compress_min_bytes"); } /** * Server-side non-exist compressor test, related configuration file: * <code>application-codec-compressor-error.yml</code> */ @Test public void testNonExistServerSideCompressor() { assertThrows(RuntimeException.class, () -> SpringApplication.run(TrpcServerApplication.class, "--spring.profiles.active=codec-compressor-error")); } /** * Client-side non-exist compressor test */ @Test public void testNonExistClientSideCompressor() { assertThrows(RuntimeException.class, () ->
TRpcProxy.getProxy("illegal-compressor-client", EchoAPI.class));
1
2023-10-19 10:54:11+00:00
16k
eclipse-jgit/jgit
org.eclipse.jgit.ui/src/org/eclipse/jgit/awtui/AwtCredentialsProvider.java
[ { "identifier": "UnsupportedCredentialItem", "path": "org.eclipse.jgit/src/org/eclipse/jgit/errors/UnsupportedCredentialItem.java", "snippet": "public class UnsupportedCredentialItem extends RuntimeException {\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * Constructs an UnsupportedCr...
import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import org.eclipse.jgit.errors.UnsupportedCredentialItem; import org.eclipse.jgit.transport.ChainingCredentialsProvider; import org.eclipse.jgit.transport.CredentialItem; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.NetRCCredentialsProvider; import org.eclipse.jgit.transport.URIish;
10,862
/* * Copyright (C) 2010, Google Inc. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com> * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.awtui; /** * Interacts with the user during authentication by using AWT/Swing dialogs. */ public class AwtCredentialsProvider extends CredentialsProvider { /** * Install this implementation as the default. */ public static void install() { final AwtCredentialsProvider c = new AwtCredentialsProvider(); CredentialsProvider cp = new ChainingCredentialsProvider( new NetRCCredentialsProvider(), c); CredentialsProvider.setDefault(cp); } @Override public boolean isInteractive() { return true; } @Override public boolean supports(CredentialItem... items) { for (CredentialItem i : items) { if (i instanceof CredentialItem.StringType) continue; else if (i instanceof CredentialItem.CharArrayType) continue; else if (i instanceof CredentialItem.YesNoType) continue; else if (i instanceof CredentialItem.InformationalMessage) continue; else return false; } return true; } @Override
/* * Copyright (C) 2010, Google Inc. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com> * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.awtui; /** * Interacts with the user during authentication by using AWT/Swing dialogs. */ public class AwtCredentialsProvider extends CredentialsProvider { /** * Install this implementation as the default. */ public static void install() { final AwtCredentialsProvider c = new AwtCredentialsProvider(); CredentialsProvider cp = new ChainingCredentialsProvider( new NetRCCredentialsProvider(), c); CredentialsProvider.setDefault(cp); } @Override public boolean isInteractive() { return true; } @Override public boolean supports(CredentialItem... items) { for (CredentialItem i : items) { if (i instanceof CredentialItem.StringType) continue; else if (i instanceof CredentialItem.CharArrayType) continue; else if (i instanceof CredentialItem.YesNoType) continue; else if (i instanceof CredentialItem.InformationalMessage) continue; else return false; } return true; } @Override
public boolean get(URIish uri, CredentialItem... items)
5
2023-10-20 15:09:17+00:00
16k
starfish-studios/Naturalist
common/src/main/java/com/starfish_studios/naturalist/common/block/OstrichEggBlock.java
[ { "identifier": "Ostrich", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/Ostrich.java", "snippet": "public class Ostrich extends Animal implements IAnimatable, ItemSteerable, Saddleable, EggLayingAnimal {\n private static final Ingredient FOOD_ITEMS = Ingredient.of(Natur...
import com.starfish_studios.naturalist.common.entity.Ostrich; import com.starfish_studios.naturalist.core.registry.NaturalistEntityTypes; import com.starfish_studios.naturalist.core.registry.NaturalistSoundEvents; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundSource; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.monster.Zombie; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.GameRules; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.TurtleEggBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape;
12,339
package com.starfish_studios.naturalist.common.block; public class OstrichEggBlock extends TurtleEggBlock { private static final VoxelShape EGG_AABB = Block.box(5.0, 0.0, 5.0, 11.0, 8.0, 11.0); public OstrichEggBlock(Properties properties) { super(properties); } @Override public void randomTick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { if (this.shouldUpdateHatchLevel(level)) { int i = state.getValue(HATCH); if (i < 2) { level.playSound(null, pos, NaturalistSoundEvents.OSTRICH_EGG_CRACK.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.setBlock(pos, state.setValue(HATCH, i + 1), 2); } else { level.playSound(null, pos, NaturalistSoundEvents.OSTRICH_EGG_HATCH.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.removeBlock(pos, false); for (int j = 0; j < state.getValue(EGGS); ++j) { level.levelEvent(2001, pos, Block.getId(state));
package com.starfish_studios.naturalist.common.block; public class OstrichEggBlock extends TurtleEggBlock { private static final VoxelShape EGG_AABB = Block.box(5.0, 0.0, 5.0, 11.0, 8.0, 11.0); public OstrichEggBlock(Properties properties) { super(properties); } @Override public void randomTick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { if (this.shouldUpdateHatchLevel(level)) { int i = state.getValue(HATCH); if (i < 2) { level.playSound(null, pos, NaturalistSoundEvents.OSTRICH_EGG_CRACK.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.setBlock(pos, state.setValue(HATCH, i + 1), 2); } else { level.playSound(null, pos, NaturalistSoundEvents.OSTRICH_EGG_HATCH.get(), SoundSource.BLOCKS, 0.7f, 0.9f + random.nextFloat() * 0.2f); level.removeBlock(pos, false); for (int j = 0; j < state.getValue(EGGS); ++j) { level.levelEvent(2001, pos, Block.getId(state));
Ostrich ostrich = NaturalistEntityTypes.OSTRICH.get().create(level);
1
2023-10-16 21:54:32+00:00
16k
wangqi060934/MyAndroidToolsPro
app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/ProcessFragment.java
[ { "identifier": "Utils", "path": "app/src/main/java/cn/wq/myandroidtoolspro/helper/Utils.java", "snippet": "public class Utils {\n private static final String TAG = \"Utils\";\n //\tpublic final static String ACTION_RECEIVER_CHANGED=\"cn.wq.myandroidtoolspro.receiver_changed\";\n//\tprivate final ...
import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.RunningAppProcessInfo; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Debug.MemoryInfo; import android.preference.PreferenceManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.support.v4.view.MenuItemCompat; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import cn.wq.myandroidtoolspro.R; import cn.wq.myandroidtoolspro.helper.Utils; import cn.wq.myandroidtoolspro.model.ProcessEntry; import cn.wq.myandroidtoolspro.recyclerview.toolbar.SearchWithToolbarRecyclerFragment;
12,996
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class ProcessFragment extends SearchWithToolbarRecyclerFragment implements LoaderManager.LoaderCallbacks<List<ProcessEntry>> { private static final String TAG = "ProcessFragment"; private ProcessAdapter adapter; private static boolean isUseRoot; private SharedPreferences sharedPreferences; private final static String PROCESS_KEY = "proceess_root_default"; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); adapter = new ProcessAdapter(getActivity()); setAdapter(adapter); setListShown(false, true); getLoaderManager().initLoader(0, null, this); initActionbar(0, getString(R.string.process)); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext()); isUseRoot = sharedPreferences.getBoolean(PROCESS_KEY, true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); setSearchHint(getString(R.string.hint_process_search)); MenuItem menuItem = menu.add(0, R.id.process_root_default, 1, R.string.process_root_default); MenuItemCompat.setShowAsAction(menuItem, MenuItemCompat.SHOW_AS_ACTION_NEVER); menuItem.setCheckable(true); menuItem.setChecked(isUseRoot); MenuItem refreshItem=menu.add(0,R.id.process_refresh,2,R.string.refresh); MenuItemCompat.setShowAsAction(refreshItem, MenuItemCompat.SHOW_AS_ACTION_IF_ROOM); refreshItem.setIcon(R.drawable.ic_refresh_white); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.process_refresh: scrollToPosition(0); getRecyclerListView().post(new Runnable() { @Override public void run() { setListShown(false, isResumed()); getLoaderManager().restartLoader(0, null, ProcessFragment.this); } }); break; case R.id.process_root_default: isUseRoot = !item.isChecked(); sharedPreferences.edit().putBoolean(PROCESS_KEY, isUseRoot).apply();; item.setChecked(isUseRoot); getRecyclerListView().post(new Runnable() { @Override public void run() { setListShown(false, isResumed()); getLoaderManager().restartLoader(0, null, ProcessFragment.this); } }); break; } return super.onOptionsItemSelected(item); } private class ProcessAdapter extends RecyclerView.Adapter<VHolder> implements Filterable { private Context context; private List<ProcessEntry> data; private List<ProcessEntry> originalData; private final Object mLock = new Object(); private ProcessFilter mFilter; private boolean isLower21; @Override public VHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new VHolder(LayoutInflater.from(context).inflate( R.layout.item_process_list, parent, false)); } @Override public void onBindViewHolder(VHolder holder, int position) { final ProcessEntry entry = data.get(position); holder.pid.setText(context.getString(R.string.pre_pid, entry.pid)); // holder.importance.setText(context.getString(R.string.pre_importance,entry.importance)); if (entry.uid < 0) { holder.uid.setVisibility(View.GONE); } else { holder.uid.setVisibility(View.VISIBLE); holder.uid.setText(context.getString(R.string.pre_uid, entry.uid)); } holder.icon.setImageDrawable(entry.icon); holder.processName.setText(entry.processName); if (isLower21) { holder.memory.setText(context.getString(R.string.pre_pss_memory, (float) entry.memory / 1024)); holder.pkgList.setText(entry.pkgList); } else { if (entry.memory < 0) { holder.memory.setVisibility(View.GONE); } else { holder.memory.setText(context.getString(R.string.pre_rss_memory, (float) entry.memory / 1024)); holder.memory.setVisibility(View.VISIBLE); } } holder.stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... arg0) { // return Utils.runRootCommand3("kill "+entry.pid)!=null;
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class ProcessFragment extends SearchWithToolbarRecyclerFragment implements LoaderManager.LoaderCallbacks<List<ProcessEntry>> { private static final String TAG = "ProcessFragment"; private ProcessAdapter adapter; private static boolean isUseRoot; private SharedPreferences sharedPreferences; private final static String PROCESS_KEY = "proceess_root_default"; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); adapter = new ProcessAdapter(getActivity()); setAdapter(adapter); setListShown(false, true); getLoaderManager().initLoader(0, null, this); initActionbar(0, getString(R.string.process)); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext()); isUseRoot = sharedPreferences.getBoolean(PROCESS_KEY, true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); setSearchHint(getString(R.string.hint_process_search)); MenuItem menuItem = menu.add(0, R.id.process_root_default, 1, R.string.process_root_default); MenuItemCompat.setShowAsAction(menuItem, MenuItemCompat.SHOW_AS_ACTION_NEVER); menuItem.setCheckable(true); menuItem.setChecked(isUseRoot); MenuItem refreshItem=menu.add(0,R.id.process_refresh,2,R.string.refresh); MenuItemCompat.setShowAsAction(refreshItem, MenuItemCompat.SHOW_AS_ACTION_IF_ROOM); refreshItem.setIcon(R.drawable.ic_refresh_white); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.process_refresh: scrollToPosition(0); getRecyclerListView().post(new Runnable() { @Override public void run() { setListShown(false, isResumed()); getLoaderManager().restartLoader(0, null, ProcessFragment.this); } }); break; case R.id.process_root_default: isUseRoot = !item.isChecked(); sharedPreferences.edit().putBoolean(PROCESS_KEY, isUseRoot).apply();; item.setChecked(isUseRoot); getRecyclerListView().post(new Runnable() { @Override public void run() { setListShown(false, isResumed()); getLoaderManager().restartLoader(0, null, ProcessFragment.this); } }); break; } return super.onOptionsItemSelected(item); } private class ProcessAdapter extends RecyclerView.Adapter<VHolder> implements Filterable { private Context context; private List<ProcessEntry> data; private List<ProcessEntry> originalData; private final Object mLock = new Object(); private ProcessFilter mFilter; private boolean isLower21; @Override public VHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new VHolder(LayoutInflater.from(context).inflate( R.layout.item_process_list, parent, false)); } @Override public void onBindViewHolder(VHolder holder, int position) { final ProcessEntry entry = data.get(position); holder.pid.setText(context.getString(R.string.pre_pid, entry.pid)); // holder.importance.setText(context.getString(R.string.pre_importance,entry.importance)); if (entry.uid < 0) { holder.uid.setVisibility(View.GONE); } else { holder.uid.setVisibility(View.VISIBLE); holder.uid.setText(context.getString(R.string.pre_uid, entry.uid)); } holder.icon.setImageDrawable(entry.icon); holder.processName.setText(entry.processName); if (isLower21) { holder.memory.setText(context.getString(R.string.pre_pss_memory, (float) entry.memory / 1024)); holder.pkgList.setText(entry.pkgList); } else { if (entry.memory < 0) { holder.memory.setVisibility(View.GONE); } else { holder.memory.setText(context.getString(R.string.pre_rss_memory, (float) entry.memory / 1024)); holder.memory.setVisibility(View.VISIBLE); } } holder.stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... arg0) { // return Utils.runRootCommand3("kill "+entry.pid)!=null;
return Utils.runRootCommand("kill " + entry.pid);
0
2023-10-18 14:32:49+00:00
16k
instana/otel-dc
rdb/src/main/java/com/instana/dc/rdb/impl/Oceanbase4Dc.java
[ { "identifier": "CalculationMode", "path": "internal/otel-dc/src/main/java/com/instana/dc/CalculationMode.java", "snippet": "public enum CalculationMode {\n DIRECT,\n RATE\n}" }, { "identifier": "DcException", "path": "internal/otel-dc/src/main/java/com/instana/dc/DcException.java", ...
import com.instana.dc.CalculationMode; import com.instana.dc.DcException; import com.instana.dc.DcUtil; import com.instana.dc.rdb.AbstractDbDc; import io.opentelemetry.api.OpenTelemetry; import java.sql.Connection; import java.sql.SQLException; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import static com.instana.agent.sensorsdk.semconv.SemanticAttributes.SQL_TEXT; import static com.instana.dc.rdb.DbDcUtil.*; import static com.instana.dc.rdb.impl.Oceanbase4Util.*;
12,065
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb.impl; public class Oceanbase4Dc extends AbstractDbDc { private static final Logger logger = Logger.getLogger(Oceanbase4Dc.class.getName()); boolean isCluster = false; boolean isTenant = false; public Oceanbase4Dc(Map<String, String> properties, String dbSystem, String dbDriver) throws SQLException, DcException { super(properties, dbSystem, dbDriver); setDbPassword(DcUtil.base64Decode(getDbPassword())); if (getServiceInstanceId() == null) { setServiceInstanceId(getDbAddress() + ":" + getDbPort() + "@" + getDbName()); } try (Connection conn = getConnection()) { setDbVersion(getSimpleStringWithSql(conn, DB_VERSION_SQL)); if (this.getDbEntityType().equals(TYPE_CLUSTER)) { isCluster = true; this.setDbTenantId("1"); this.setDbTenantName("sys"); } else if (getDbEntityType().equals(TYPE_TENANT)) { isTenant = true; String tId = getDbTenantId(); String tName = getDbTenantName(); if (tId == null) { if (tName == null) { throw new DcException(DB_TENANT_ID + " or " + DB_TENANT_NAME + " must be provided!"); } setDbTenantId(getSimpleStringWithSql(conn, DB_TENANT_NAME2ID_SQL.replace(TENANT_HOLDER, tName))); } else if (tName == null) { setDbTenantName(getSimpleStringWithSql(conn, DB_TENANT_ID2NAME_SQL.replace(TENANT_HOLDER, tId))); } } else { throw new DcException("Unsupported entity type of Oceanbase"); } } } @Override public void registerMetrics() { super.registerMetrics();
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb.impl; public class Oceanbase4Dc extends AbstractDbDc { private static final Logger logger = Logger.getLogger(Oceanbase4Dc.class.getName()); boolean isCluster = false; boolean isTenant = false; public Oceanbase4Dc(Map<String, String> properties, String dbSystem, String dbDriver) throws SQLException, DcException { super(properties, dbSystem, dbDriver); setDbPassword(DcUtil.base64Decode(getDbPassword())); if (getServiceInstanceId() == null) { setServiceInstanceId(getDbAddress() + ":" + getDbPort() + "@" + getDbName()); } try (Connection conn = getConnection()) { setDbVersion(getSimpleStringWithSql(conn, DB_VERSION_SQL)); if (this.getDbEntityType().equals(TYPE_CLUSTER)) { isCluster = true; this.setDbTenantId("1"); this.setDbTenantName("sys"); } else if (getDbEntityType().equals(TYPE_TENANT)) { isTenant = true; String tId = getDbTenantId(); String tName = getDbTenantName(); if (tId == null) { if (tName == null) { throw new DcException(DB_TENANT_ID + " or " + DB_TENANT_NAME + " must be provided!"); } setDbTenantId(getSimpleStringWithSql(conn, DB_TENANT_NAME2ID_SQL.replace(TENANT_HOLDER, tName))); } else if (tName == null) { setDbTenantName(getSimpleStringWithSql(conn, DB_TENANT_ID2NAME_SQL.replace(TENANT_HOLDER, tId))); } } else { throw new DcException("Unsupported entity type of Oceanbase"); } } } @Override public void registerMetrics() { super.registerMetrics();
getRawMetric(DB_TRANSACTION_RATE_NAME).setCalculationMode(CalculationMode.RATE);
0
2023-10-23 01:16:38+00:00
16k
histevehu/12306
business/src/main/java/com/steve/train/business/service/DailyTrainService.java
[ { "identifier": "DailyTrain", "path": "business/src/main/java/com/steve/train/business/domain/DailyTrain.java", "snippet": "public class DailyTrain {\n private Long id;\n\n private Date date;\n\n private String code;\n\n private String type;\n\n private String start;\n\n private String...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.steve.train.business.domain.DailyTrain; import com.steve.train.business.domain.DailyTrainExample; import com.steve.train.business.domain.Train; import com.steve.train.business.mapper.DailyTrainMapper; import com.steve.train.business.req.DailyTrainQueryReq; import com.steve.train.business.req.DailyTrainSaveReq; import com.steve.train.business.resp.DailyTrainQueryResp; import com.steve.train.common.resp.PageResp; import com.steve.train.common.util.SnowFlakeUtil; import jakarta.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List;
13,463
package com.steve.train.business.service; /* * @author : Steve Hu * @date : 2023-10-31 11:29:05 * @description: 每日车次服务(FreeMarker生成) */ @Service public class DailyTrainService { private static final Logger LOG = LoggerFactory.getLogger(DailyTrainService.class); @Resource private DailyTrainMapper dailyTrainMapper; @Resource private TrainService trainService; @Resource private DailyTrainStationService dailyTrainStationService; @Resource private DailyTrainCarriageService dailyTrainCarriageService; @Resource private DailyTrainSeatService dailyTrainSeatService; @Resource private DailyTrainTicketService dailyTrainTicketService; @Resource private SkTokenService skTokenService; public void save(DailyTrainSaveReq req) { DateTime now = DateTime.now(); DailyTrain dailyTrain = BeanUtil.copyProperties(req, DailyTrain.class); if (ObjectUtil.isNull(dailyTrain.getId())) { dailyTrain.setId(SnowFlakeUtil.getSnowFlakeNextId()); dailyTrain.setCreateTime(now); dailyTrain.setUpdateTime(now); dailyTrainMapper.insert(dailyTrain); } else { dailyTrain.setUpdateTime(now); dailyTrainMapper.updateByPrimaryKey(dailyTrain); } } public PageResp<DailyTrainQueryResp> queryList(DailyTrainQueryReq req) { DailyTrainExample dailyTrainExample = new DailyTrainExample(); dailyTrainExample.setOrderByClause("date desc, code asc"); DailyTrainExample.Criteria criteria = dailyTrainExample.createCriteria(); if (ObjectUtil.isNotNull(req.getDate())) { criteria.andDateEqualTo(req.getDate()); } if (ObjectUtil.isNotEmpty(req.getCode())) { criteria.andCodeEqualTo(req.getCode()); } LOG.info("查询页码:{}", req.getPage()); LOG.info("每页条数:{}", req.getSize()); PageHelper.startPage(req.getPage(), req.getSize()); List<DailyTrain> dailyTrainList = dailyTrainMapper.selectByExample(dailyTrainExample); PageInfo<DailyTrain> pageInfo = new PageInfo<>(dailyTrainList); LOG.info("总行数:{}", pageInfo.getTotal()); LOG.info("总页数:{}", pageInfo.getPages()); List<DailyTrainQueryResp> list = BeanUtil.copyToList(dailyTrainList, DailyTrainQueryResp.class); PageResp<DailyTrainQueryResp> pageResp = new PageResp<>(); pageResp.setTotal(pageInfo.getTotal()); pageResp.setList(list); return pageResp; } public void delete(Long id) { dailyTrainMapper.deleteByPrimaryKey(id); } /** * 生成某日所有车次信息,包括车次、车站、车厢、座位 * * @param date */ public void genDaily(Date date) {
package com.steve.train.business.service; /* * @author : Steve Hu * @date : 2023-10-31 11:29:05 * @description: 每日车次服务(FreeMarker生成) */ @Service public class DailyTrainService { private static final Logger LOG = LoggerFactory.getLogger(DailyTrainService.class); @Resource private DailyTrainMapper dailyTrainMapper; @Resource private TrainService trainService; @Resource private DailyTrainStationService dailyTrainStationService; @Resource private DailyTrainCarriageService dailyTrainCarriageService; @Resource private DailyTrainSeatService dailyTrainSeatService; @Resource private DailyTrainTicketService dailyTrainTicketService; @Resource private SkTokenService skTokenService; public void save(DailyTrainSaveReq req) { DateTime now = DateTime.now(); DailyTrain dailyTrain = BeanUtil.copyProperties(req, DailyTrain.class); if (ObjectUtil.isNull(dailyTrain.getId())) { dailyTrain.setId(SnowFlakeUtil.getSnowFlakeNextId()); dailyTrain.setCreateTime(now); dailyTrain.setUpdateTime(now); dailyTrainMapper.insert(dailyTrain); } else { dailyTrain.setUpdateTime(now); dailyTrainMapper.updateByPrimaryKey(dailyTrain); } } public PageResp<DailyTrainQueryResp> queryList(DailyTrainQueryReq req) { DailyTrainExample dailyTrainExample = new DailyTrainExample(); dailyTrainExample.setOrderByClause("date desc, code asc"); DailyTrainExample.Criteria criteria = dailyTrainExample.createCriteria(); if (ObjectUtil.isNotNull(req.getDate())) { criteria.andDateEqualTo(req.getDate()); } if (ObjectUtil.isNotEmpty(req.getCode())) { criteria.andCodeEqualTo(req.getCode()); } LOG.info("查询页码:{}", req.getPage()); LOG.info("每页条数:{}", req.getSize()); PageHelper.startPage(req.getPage(), req.getSize()); List<DailyTrain> dailyTrainList = dailyTrainMapper.selectByExample(dailyTrainExample); PageInfo<DailyTrain> pageInfo = new PageInfo<>(dailyTrainList); LOG.info("总行数:{}", pageInfo.getTotal()); LOG.info("总页数:{}", pageInfo.getPages()); List<DailyTrainQueryResp> list = BeanUtil.copyToList(dailyTrainList, DailyTrainQueryResp.class); PageResp<DailyTrainQueryResp> pageResp = new PageResp<>(); pageResp.setTotal(pageInfo.getTotal()); pageResp.setList(list); return pageResp; } public void delete(Long id) { dailyTrainMapper.deleteByPrimaryKey(id); } /** * 生成某日所有车次信息,包括车次、车站、车厢、座位 * * @param date */ public void genDaily(Date date) {
List<Train> trainList = trainService.selectAll();
2
2023-10-23 01:20:56+00:00
16k
team-moabam/moabam-BE
src/test/java/com/moabam/api/application/report/ReportServiceTest.java
[ { "identifier": "ErrorMessage", "path": "src/main/java/com/moabam/global/error/model/ErrorMessage.java", "snippet": "@Getter\n@RequiredArgsConstructor\npublic enum ErrorMessage {\n\n\tFAILED_MOABAM(\"모아밤 서버 실행 중 오류가 발생했습니다.\"),\n\tINVALID_REQUEST_FIELD(\"올바른 요청 정보가 아닙니다.\"),\n\tINVALID_REQUEST_VALUE_TYP...
import static com.moabam.global.error.model.ErrorMessage.*; import static org.assertj.core.api.Assertions.*; import static org.mockito.BDDMockito.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import com.moabam.api.application.member.MemberService; import com.moabam.api.application.room.CertificationService; import com.moabam.api.application.room.RoomService; import com.moabam.api.domain.member.Member; import com.moabam.api.domain.report.repository.ReportRepository; import com.moabam.api.domain.room.Certification; import com.moabam.api.domain.room.Room; import com.moabam.api.domain.room.Routine; import com.moabam.api.dto.report.ReportRequest; import com.moabam.global.auth.model.AuthMember; import com.moabam.global.error.exception.BadRequestException; import com.moabam.support.annotation.WithMember; import com.moabam.support.common.FilterProcessExtension; import com.moabam.support.fixture.MemberFixture; import com.moabam.support.fixture.ReportFixture; import com.moabam.support.fixture.RoomFixture;
12,889
package com.moabam.api.application.report; @ExtendWith({MockitoExtension.class, FilterProcessExtension.class}) class ReportServiceTest { @InjectMocks ReportService reportService; @Mock CertificationService certificationService; @Mock RoomService roomService; @Mock MemberService memberService; @Mock ReportRepository reportRepository; @DisplayName("신고 대상이 없어서 실패") @Test void no_report_subject_fail(@WithMember AuthMember authMember) { // given ReportRequest reportRequest = new ReportRequest(null, null, null, "st"); // When + Then assertThatThrownBy(() -> reportService.report(authMember, reportRequest)) .isInstanceOf(BadRequestException.class) .hasMessage(REPORT_REQUEST_ERROR.getMessage()); } @DisplayName("신고 성공") @ParameterizedTest @CsvSource({"true, false", "false, true"}) void report_success(boolean roomFilter, boolean certificationFilter, @WithMember AuthMember authMember) { // given Room room = RoomFixture.room(); Routine routine = RoomFixture.routine(room, "ets");
package com.moabam.api.application.report; @ExtendWith({MockitoExtension.class, FilterProcessExtension.class}) class ReportServiceTest { @InjectMocks ReportService reportService; @Mock CertificationService certificationService; @Mock RoomService roomService; @Mock MemberService memberService; @Mock ReportRepository reportRepository; @DisplayName("신고 대상이 없어서 실패") @Test void no_report_subject_fail(@WithMember AuthMember authMember) { // given ReportRequest reportRequest = new ReportRequest(null, null, null, "st"); // When + Then assertThatThrownBy(() -> reportService.report(authMember, reportRequest)) .isInstanceOf(BadRequestException.class) .hasMessage(REPORT_REQUEST_ERROR.getMessage()); } @DisplayName("신고 성공") @ParameterizedTest @CsvSource({"true, false", "false, true"}) void report_success(boolean roomFilter, boolean certificationFilter, @WithMember AuthMember authMember) { // given Room room = RoomFixture.room(); Routine routine = RoomFixture.routine(room, "ets");
Certification certification = RoomFixture.certification(routine);
6
2023-10-20 06:15:43+00:00
16k
tuxming/xmfx
BaseUI/src/main/java/com/xm2013/jfx/control/dropdown/DropdownMenuPopup.java
[ { "identifier": "CallBack", "path": "BaseUI/src/main/java/com/xm2013/jfx/common/CallBack.java", "snippet": "public interface CallBack<T> {\n \n /**\n * Call.\n *\n * @param t the t\n */\n public void call(T t);\n}" }, { "identifier": "FxKit", "path": "BaseUI/src/main...
import com.xm2013.jfx.common.CallBack; import com.xm2013.jfx.common.FxKit; import com.xm2013.jfx.container.SimpleVScrollPane; import com.xm2013.jfx.control.base.ColorType; import com.xm2013.jfx.control.base.SizeType; import com.xm2013.jfx.control.icon.XmIcon; import javafx.animation.AnimationTimer; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyBooleanWrapper; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.geometry.*; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.control.ScrollBar; import javafx.scene.effect.BlurType; import javafx.scene.effect.DropShadow; import javafx.scene.input.MouseEvent; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.shape.SVGPath; import javafx.scene.text.Font; import javafx.stage.Popup; import javafx.stage.Screen; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
11,765
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.jfx.control.dropdown; /** * 下拉菜单的下拉部分 */ public class DropdownMenuPopup extends Popup { /** * 动画从上向下渐显 */ public final static int DIRECTION_BOTTOM = 1; /** * 动画从左向右渐显 */ public final static int DIRECTION_RIGHT = 2; //内容容器 private final VBox popupContentPane; //内容容器过高会显示滚动条
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.jfx.control.dropdown; /** * 下拉菜单的下拉部分 */ public class DropdownMenuPopup extends Popup { /** * 动画从上向下渐显 */ public final static int DIRECTION_BOTTOM = 1; /** * 动画从左向右渐显 */ public final static int DIRECTION_RIGHT = 2; //内容容器 private final VBox popupContentPane; //内容容器过高会显示滚动条
private final SimpleVScrollPane scrollPane;
2
2023-10-17 08:57:08+00:00
16k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/PCFGLA/CoarseToFineTwoChartsParser.java
[ { "identifier": "Linearizer", "path": "src/berkeley_parser/edu/berkeley/nlp/discPCFG/Linearizer.java", "snippet": "public interface Linearizer {\n\tpublic double[] getLinearizedGrammar();\n\n\tpublic double[] getLinearizedLexicon();\n\n\tpublic double[] getLinearizedSpanPredictor();\n\n\tpublic double[]...
import java.util.Arrays; import java.util.List; import edu.berkeley.nlp.discPCFG.Linearizer; import edu.berkeley.nlp.syntax.StateSet; import edu.berkeley.nlp.syntax.Tree;
11,622
for (int start = 0; start < length; start++) { for (int end = start + 1; end <= length; end++) { if (firstTime) { viScore[start][end] = new double[numStates]; voScore[start][end] = new double[numStates]; iScorePreU[start][end] = new double[numStates][]; iScorePostU[start][end] = new double[numStates][]; oScorePreU[start][end] = new double[numStates][]; oScorePostU[start][end] = new double[numStates][]; // iScale[start][end] = new int[numStates]; // oScale[start][end] = new int[numStates]; allowedSubStates[start][end] = new boolean[numStates][]; allowedStates[start][end] = grammarTags.clone(); if (level == 1 && (end - start == 1)) Arrays.fill(allowedStates[start][end], true); vAllowedStates[start][end] = true; } for (int state = 0; state < numSubStatesArray.length; state++) { if (allowedSubStates[start][end][state] != null) { if (level < 1) { viScore[start][end][state] = Double.NEGATIVE_INFINITY; voScore[start][end][state] = Double.NEGATIVE_INFINITY; } else { iScorePreU[start][end][state] = new double[numSubStatesArray[state]]; iScorePostU[start][end][state] = new double[numSubStatesArray[state]]; oScorePreU[start][end][state] = new double[numSubStatesArray[state]]; oScorePostU[start][end][state] = new double[numSubStatesArray[state]]; Arrays.fill(iScorePreU[start][end][state], initVal); Arrays.fill(iScorePostU[start][end][state], initVal); Arrays.fill(oScorePreU[start][end][state], initVal); Arrays.fill(oScorePostU[start][end][state], initVal); // Arrays.fill(iScale[start][end], // Integer.MIN_VALUE); // Arrays.fill(oScale[start][end], // Integer.MIN_VALUE); // boolean[] newAllowedSubStates = new // boolean[numSubStatesArray[state]]; // if (allowedSubStates[start][end][state]==null || // level<=1){ // Arrays.fill(newAllowedSubStates,true); // allowedSubStates[start][end][state] = // newAllowedSubStates; // } else{ // if (!justInit){ // // int[][] curLChildMap = lChildMap[level-2]; // // int[][] curRChildMap = rChildMap[level-2]; // // for (int i=0; // i<allowedSubStates[start][end][state].length; // i++){ // // boolean val = // allowedSubStates[start][end][state][i]; // // newAllowedSubStates[curLChildMap[state][i]] = // val; // // newAllowedSubStates[curRChildMap[state][i]] = // val; // // } // // allowedSubStates[start][end][state] = // newAllowedSubStates; // } // } } } else { if (level < 1) { viScore[start][end][state] = Double.NEGATIVE_INFINITY; voScore[start][end][state] = Double.NEGATIVE_INFINITY; } else { iScorePreU[start][end][state] = null; iScorePostU[start][end][state] = null; oScorePreU[start][end][state] = null; oScorePostU[start][end][state] = null; // allowedSubStates[start][end][state] = new // boolean[1]; // allowedSubStates[start][end][state][0] = false; } } } if (level > 0 && start == 0 && end == length) { if (iScorePostU[start][end][0] == null) System.out .println("ROOT does not span the entire tree!"); } } } narrowRExtent = new int[length + 1][numStates]; wideRExtent = new int[length + 1][numStates]; narrowLExtent = new int[length + 1][numStates]; wideLExtent = new int[length + 1][numStates]; for (int loc = 0; loc <= length; loc++) { Arrays.fill(narrowLExtent[loc], -1); // the rightmost left with // state s ending at i that // we can get is the // beginning Arrays.fill(wideLExtent[loc], length + 1); // the leftmost left with // state s ending at i // that we can get is // the end Arrays.fill(narrowRExtent[loc], length + 1); // the leftmost right // with state s // starting at i // that we can get // is the end Arrays.fill(wideRExtent[loc], -1); // the rightmost right with state // s starting at i that we can // get is the beginning } } @Override protected void clearArrays() { iScorePreU = iScorePostU = oScorePreU = oScorePostU = null; viScore = voScore = null; allowedSubStates = null; vAllowedStates = null; // iPossibleByL = iPossibleByR = oFilteredEnd = oFilteredStart = // oPossibleByL = oPossibleByR = tags = null; narrowRExtent = wideRExtent = narrowLExtent = wideLExtent = null; }
/** * */ package edu.berkeley.nlp.PCFGLA; /** * @author petrov * */ public class CoarseToFineTwoChartsParser extends CoarseToFineMaxRuleParser { /** * inside and outside scores; start idx, end idx, state, substate -> * logProb/prob */ /** NEW: we now have two charts one before applying unaries and one after: */ protected double[][][][] iScorePreU, iScorePostU; protected double[][][][] oScorePreU, oScorePostU; /** * @param gr * @param lex * @param unaryPenalty * @param endL * @param viterbi * @param sub * @param score */ public CoarseToFineTwoChartsParser(Grammar gr, Lexicon lex, double unaryPenalty, int endL, boolean viterbi, boolean sub, boolean score, boolean accurate) { super(gr, lex, unaryPenalty, endL, viterbi, sub, score, accurate, false, false, true); } @Override void doConstrainedInsideScores(Grammar grammar, boolean viterbi, boolean logScores) { if (!viterbi && logScores) throw new Error( "This would require logAdds and is slow. Exponentiate the scores instead."); numSubStatesArray = grammar.numSubStates; double initVal = (logScores) ? Double.NEGATIVE_INFINITY : 0; // double[] oldIScores = new double[maxNSubStates]; // int smallestScale = 10, largestScale = -10; for (int diff = 1; diff <= length; diff++) { // smallestScale = 10; largestScale = -10; // System.out.print(diff + " "); for (int start = 0; start < (length - diff + 1); start++) { int end = start + diff; for (int pState = 0; pState < numSubStatesArray.length; pState++) { if (diff == 1) continue; // there are no binary rules that span over 1 // symbol only if (allowedSubStates[start][end][pState] == null) continue; BinaryRule[] parentRules = grammar.splitRulesWithP(pState); int nParentStates = numSubStatesArray[pState]; // we will oftern write to the scoresToAdd array and then // transfer the accumulated values once // to the iScores arrays because writing to large arrays is // slow // scoresToAdd = new double[nParentStates]; Arrays.fill(scoresToAdd, initVal); boolean somethingChanged = false; for (int i = 0; i < parentRules.length; i++) { BinaryRule r = parentRules[i]; int lState = r.leftChildState; int rState = r.rightChildState; int narrowR = narrowRExtent[start][lState]; boolean iPossibleL = (narrowR < end); // can this left // constituent // leave space // for a right // constituent? if (!iPossibleL) { continue; } int narrowL = narrowLExtent[end][rState]; boolean iPossibleR = (narrowL >= narrowR); // can this // right // constituent // fit next // to the // left // constituent? if (!iPossibleR) { continue; } int min1 = narrowR; int min2 = wideLExtent[end][rState]; int min = (min1 > min2 ? min1 : min2); // can this right // constituent // stretch far // enough to // reach the // left // constituent? if (min > narrowL) { continue; } int max1 = wideRExtent[start][lState]; int max2 = narrowL; int max = (max1 < max2 ? max1 : max2); // can this left // constituent // stretch far // enough to // reach the // right // constituent? if (min > max) { continue; } // TODO switch order of loops for efficiency double[][][] scores = r.getScores2(); int nLeftChildStates = numSubStatesArray[lState]; int nRightChildStates = numSubStatesArray[rState]; for (int split = min; split <= max; split++) { if (allowedSubStates[start][split][lState] == null) continue; if (allowedSubStates[split][end][rState] == null) continue; for (int lp = 0; lp < nLeftChildStates; lp++) { // if (iScore[start][split][lState] == null) // continue; // if // (!allowedSubStates[start][split][lState][lp]) // continue; double lS = iScorePostU[start][split][lState][lp]; if (lS == initVal) continue; for (int rp = 0; rp < nRightChildStates; rp++) { if (scores[lp][rp] == null) continue; double rS = iScorePostU[split][end][rState][rp]; if (rS == initVal) continue; for (int np = 0; np < nParentStates; np++) { if (!allowedSubStates[start][end][pState][np]) continue; double pS = scores[lp][rp][np]; if (pS == initVal) continue; // if (iScore[split][end][rState] == // null) continue; // if // (!allowedSubStates[split][end][rState][rp]) // continue; double thisRound = (logScores) ? pS + lS + rS : pS * lS * rS; if (viterbi) scoresToAdd[np] = Math.max( thisRound, scoresToAdd[np]); else scoresToAdd[np] += thisRound; somethingChanged = true; } } } // if (!somethingChanged) continue; // boolean firstTime = false; /* * int parentScale = iScale[start][end][pState]; int * currentScale = * iScale[start][split][lState]+iScale * [split][end][rState]; if * (parentScale==currentScale) { // already had a * way to generate this state and the scales are the * same // -> nothing to do } else { if * (parentScale==Integer.MIN_VALUE){ // first time * we can build this state firstTime = true; * parentScale = * scaleArray(scoresToAdd,currentScale); * iScale[start][end][pState] = parentScale; * //smallestScale = * Math.min(smallestScale,parentScale); * //largestScale = * Math.max(largestScale,parentScale); } else { // * scale the smaller one to the base of the bigger * one int newScale = * Math.max(currentScale,parentScale); * scaleArrayToScale * (scoresToAdd,currentScale,newScale); * scaleArrayToScale * (iScore[start][end][pState],parentScale * ,newScale); iScale[start][end][pState] = * newScale; //smallestScale = * Math.min(smallestScale,newScale); //largestScale * = Math.max(largestScale,newScale); } } */ } } if (!somethingChanged) continue; for (int np = 0; np < nParentStates; np++) { if (scoresToAdd[np] > initVal) { iScorePreU[start][end][pState][np] = scoresToAdd[np]; } } // iScale[start][end][pState] = currentScale; // iScale[start][end][pState] = // scaleArray(iScore[start][end][pState],iScale[start][end][pState]); if (true/* firstTime */) { if (start > narrowLExtent[end][pState]) { narrowLExtent[end][pState] = start; wideLExtent[end][pState] = start; } else { if (start < wideLExtent[end][pState]) { wideLExtent[end][pState] = start; } } if (end < narrowRExtent[start][pState]) { narrowRExtent[start][pState] = end; wideRExtent[start][pState] = end; } else { if (end > wideRExtent[start][pState]) { wideRExtent[start][pState] = end; } } } } // now do the unaries for (int pState = 0; pState < numSubStatesArray.length; pState++) { if (allowedSubStates[start][end][pState] == null) continue; // Should be: Closure under sum-product: UnaryRule[] unaries = grammar .getClosedSumUnaryRulesByParent(pState); // UnaryRule[] unaries = // grammar.getUnaryRulesByParent(pState).toArray(new // UnaryRule[0]); int nParentStates = numSubStatesArray[pState];// scores[0].length; boolean firstTime = true; boolean somethingChanged = false; for (int r = 0; r < unaries.length; r++) { UnaryRule ur = unaries[r]; int cState = ur.childState; if ((pState == cState)) continue; if (iScorePreU[start][end][cState] == null) continue; // if (!allowedStates[start][end][cState]) continue; // new loop over all substates // System.out.println("Rule "+r+" out of "+unaries.length+" "+ur); double[][] scores = ur.getScores2(); int nChildStates = numSubStatesArray[cState];// scores[0].length; for (int cp = 0; cp < nChildStates; cp++) { if (scores[cp] == null) continue; double iS = iScorePreU[start][end][cState][cp]; if (iS == initVal) continue; for (int np = 0; np < nParentStates; np++) { if (!allowedSubStates[start][end][pState][np]) continue; // if // (!allowedSubStates[start][end][cState][cp]) // continue; double pS = scores[cp][np]; if (pS == initVal) continue; if (firstTime) { firstTime = false; Arrays.fill(scoresToAdd, initVal); } double thisRound = (logScores) ? iS + pS : iS * pS; if (viterbi) scoresToAdd[np] = Math.max(thisRound, scoresToAdd[np]); else scoresToAdd[np] += thisRound; somethingChanged = true; } } } /* * boolean firstTime = false; int currentScale = * iScale[start][end][cState]; int parentScale = * iScale[start][end][pState]; if * (parentScale==currentScale) { // already had a way to * generate this state and the scales are the same // -> * nothing to do } else { if * (parentScale==Integer.MIN_VALUE){ // first time we can * build this state firstTime = true; parentScale = * scaleArray(scoresToAdd,currentScale); * iScale[start][end][pState] = parentScale; //smallestScale * = Math.min(smallestScale,parentScale); //largestScale = * Math.max(largestScale,parentScale); } else { // scale the * smaller one to the base of the bigger one int newScale = * Math.max(currentScale,parentScale); * scaleArrayToScale(scoresToAdd,currentScale,newScale); * scaleArrayToScale * (iScore[start][end][pState],parentScale,newScale); * iScale[start][end][pState] = newScale; //smallestScale = * Math.min(smallestScale,newScale); //largestScale = * Math.max(largestScale,newScale); * * } } */ if (!somethingChanged) { iScorePostU[start][end][pState] = iScorePreU[start][end][pState] .clone(); continue; } else { for (int np = 0; np < nParentStates; np++) { if (scoresToAdd[np] > initVal) { if (viterbi) iScorePostU[start][end][pState][np] = Math .max(iScorePreU[start][end][pState][np], scoresToAdd[np]); else iScorePostU[start][end][pState][np] = iScorePreU[start][end][pState][np] + scoresToAdd[np]; } else iScorePostU[start][end][pState][np] = iScorePreU[start][end][pState][np]; } } // iScale[start][end][pState] = currentScale; // iScale[start][end][pState] = // scaleArray(iScore[start][end][pState],iScale[start][end][pState]); if (true) { if (start > narrowLExtent[end][pState]) { narrowLExtent[end][pState] = start; wideLExtent[end][pState] = start; } else { if (start < wideLExtent[end][pState]) { wideLExtent[end][pState] = start; } } if (end < narrowRExtent[start][pState]) { narrowRExtent[start][pState] = end; wideRExtent[start][pState] = end; } else { if (end > wideRExtent[start][pState]) { wideRExtent[start][pState] = end; } } } } } } } @Override void doConstrainedOutsideScores(Grammar grammar, boolean viterbi, boolean logScores) { numSubStatesArray = grammar.numSubStates; double initVal = (logScores) ? Double.NEGATIVE_INFINITY : 0; for (int diff = length; diff >= 1; diff--) { for (int start = 0; start + diff <= length; start++) { int end = start + diff; // do unaries boolean somethingChanged = false; for (int pState = 0; pState < numSubStatesArray.length; pState++) { if (oScorePreU[start][end][pState] == null) { continue; } // if (!allowedStates[start][end][pState]) continue; // Should be: Closure under sum-product: UnaryRule[] rules = grammar .getClosedSumUnaryRulesByParent(pState); // UnaryRule[] rules = // grammar.getClosedViterbiUnaryRulesByParent(pState); // For now: // UnaryRule[] rules = // grammar.getUnaryRulesByParent(pState).toArray(new // UnaryRule[0]); for (int r = 0; r < rules.length; r++) { UnaryRule ur = rules[r]; int cState = ur.childState; if ((pState == cState)) continue; // if (!allowedStates[start][end][cState]) continue; if (oScorePreU[start][end][cState] == null) { continue; } double[][] scores = ur.getScores2(); int nParentStates = numSubStatesArray[pState]; int nChildStates = scores.length; boolean firstTime = true; for (int cp = 0; cp < nChildStates; cp++) { if (scores[cp] == null) continue; if (!allowedSubStates[start][end][cState][cp]) continue; for (int np = 0; np < nParentStates; np++) { // if // (!allowedSubStates[start][end][pState][np]) // continue; double pS = scores[cp][np]; if (pS == initVal) continue; double oS = oScorePreU[start][end][pState][np]; if (oS == initVal) continue; double thisRound = (logScores) ? oS + pS : oS * pS; if (firstTime) { firstTime = false; Arrays.fill(scoresToAdd, initVal); } if (viterbi) scoresToAdd[cp] = Math.max(thisRound, scoresToAdd[cp]); else scoresToAdd[cp] += thisRound; somethingChanged = true; } } // check first whether there was a change at all // boolean firstTime = false; /* * int currentScale = oScale[start][end][pState]; int * childScale = oScale[start][end][cState]; if * (childScale==currentScale) { // already had a way to * generate this state and the scales are the same // -> * nothing to do } else { if * (childScale==Integer.MIN_VALUE){ // first time we can * build this state firstTime = true; childScale = * scaleArray(scoresToAdd,currentScale); * oScale[start][end][cState] = childScale; } else { // * scale the smaller one to the base of the bigger one * int newScale = Math.max(currentScale,childScale); * scaleArrayToScale(scoresToAdd,currentScale,newScale); * scaleArrayToScale * (oScore[start][end][cState],childScale,newScale); * oScale[start][end][cState] = newScale; } } */ if (somethingChanged) { for (int cp = 0; cp < nChildStates; cp++) { // if (true /*firstTime*/) // oScore[start][end][cState][cp] = // scoresToAdd[cp]; // else // if (scoresToAdd[cp] > 0) // oScore[start][end][cState][cp] += // scoresToAdd[cp]; if (scoresToAdd[cp] > initVal) { if (viterbi) oScorePostU[start][end][cState][cp] = Math .max(oScorePostU[start][end][cState][cp], scoresToAdd[cp]); else oScorePostU[start][end][cState][cp] += scoresToAdd[cp]; } } } } } // copy/add the entries where the unaries where not useful for (int cState = 0; cState < numSubStatesArray.length; cState++) { if (oScorePostU[start][end][cState] == null) continue; for (int cp = 0; cp < numSubStatesArray[cState]; cp++) { if (viterbi) oScorePostU[start][end][cState][cp] = Math.max( oScorePostU[start][end][cState][cp], oScorePreU[start][end][cState][cp]); else oScorePostU[start][end][cState][cp] += oScorePreU[start][end][cState][cp]; } } // do binaries for (int pState = 0; pState < numSubStatesArray.length; pState++) { if (oScorePostU[start][end][pState] == null) { continue; } final int nParentChildStates = numSubStatesArray[pState]; // if (!allowedStates[start][end][pState]) continue; BinaryRule[] rules = grammar.splitRulesWithP(pState); // BinaryRule[] rules = grammar.splitRulesWithLC(lState); for (int r = 0; r < rules.length; r++) { BinaryRule br = rules[r]; int lState = br.leftChildState; int min1 = narrowRExtent[start][lState]; if (end < min1) { continue; } int rState = br.rightChildState; int max1 = narrowLExtent[end][rState]; if (max1 < min1) { continue; } int min = min1; int max = max1; if (max - min > 2) { int min2 = wideLExtent[end][rState]; min = (min1 > min2 ? min1 : min2); if (max1 < min) { continue; } int max2 = wideRExtent[start][lState]; max = (max1 < max2 ? max1 : max2); if (max < min) { continue; } } double[][][] scores = br.getScores2(); int nLeftChildStates = numSubStatesArray[lState]; int nRightChildStates = numSubStatesArray[rState]; for (int split = min; split <= max; split++) { if (oScorePreU[start][split][lState] == null) continue; if (oScorePreU[split][end][rState] == null) continue; // if (!allowedStates[start][split][lState]) // continue; // if (!allowedStates[split][end][rState]) continue; double[] rightScores = new double[nRightChildStates]; Arrays.fill(scoresToAdd, initVal); Arrays.fill(rightScores, initVal); somethingChanged = false; for (int lp = 0; lp < nLeftChildStates; lp++) { double lS = iScorePostU[start][split][lState][lp]; if (lS == initVal) { continue; } // if // (!allowedSubStates[start][split][lState][lp]) // continue; for (int rp = 0; rp < nRightChildStates; rp++) { if (scores[lp][rp] == null) continue; double rS = iScorePostU[split][end][rState][rp]; if (rS == initVal) { continue; } // if // (!allowedSubStates[split][end][rState][rp]) // continue; for (int np = 0; np < nParentChildStates; np++) { double pS = scores[lp][rp][np]; if (pS == initVal) continue; double oS = oScorePostU[start][end][pState][np]; if (oS == initVal) continue; // if // (!allowedSubStates[start][end][pState][np]) // continue; double thisRoundL = (logScores) ? pS + rS + oS : pS * rS * oS; double thisRoundR = (logScores) ? pS + lS + oS : pS * lS * oS; if (viterbi) { scoresToAdd[lp] = Math .max(thisRoundL, scoresToAdd[lp]); rightScores[rp] = Math .max(thisRoundR, rightScores[rp]); } else { scoresToAdd[lp] += thisRoundL; rightScores[rp] += thisRoundR; } somethingChanged = true; } } } if (!somethingChanged) continue; /* * boolean firstTime = false; int leftScale = * oScale[start][split][lState]; int rightScale = * oScale[split][end][rState]; int parentScale = * oScale[start][end][pState]; int currentScale = * parentScale+iScale[split][end][rState]; if * (leftScale==currentScale) { // already had a way * to generate this state and the scales are the * same // -> nothing to do } else { if * (leftScale==Integer.MIN_VALUE){ // first time we * can build this state firstTime = true; leftScale * = scaleArray(scoresToAdd,currentScale); * oScale[start][split][lState] = leftScale; } else * { // scale the smaller one to the base of the * bigger one int newScale = * Math.max(currentScale,leftScale); * scaleArrayToScale * (scoresToAdd,currentScale,newScale); * scaleArrayToScale * (oScore[start][split][lState],leftScale * ,newScale); oScale[start][split][lState] = * newScale; } } */ for (int cp = 0; cp < nLeftChildStates; cp++) { // if (true /*firstTime*/) // oScore[start][split][lState][cp] = // scoresToAdd[cp]; if (scoresToAdd[cp] > initVal) { if (viterbi) oScorePreU[start][split][lState][cp] = Math .max(oScorePreU[start][split][lState][cp], scoresToAdd[cp]); else oScorePreU[start][split][lState][cp] += scoresToAdd[cp]; } } // oScale[start][split][lState] = currentScale; // oScale[start][split][lState] = // scaleArray(oScore[start][split][lState],oScale[start][split][lState]); // currentScale = // parentScale+iScale[start][split][lState]; /* * firstTime = false; if (rightScale==currentScale) * { // already had a way to generate this state and * the scales are the same // -> nothing to do } * else { if (rightScale==Integer.MIN_VALUE){ // * first time we can build this state firstTime = * true; rightScale = * scaleArray(rightScores,currentScale); * oScale[split][end][rState] = rightScale; } else { * // scale the smaller one to the base of the * bigger one int newScale = * Math.max(currentScale,rightScale); * scaleArrayToScale * (rightScores,currentScale,newScale); * scaleArrayToScale * (oScore[split][end][rState],rightScale,newScale); * oScale[split][end][rState] = newScale; } } */ for (int cp = 0; cp < nRightChildStates; cp++) { // if (true/*firstTime*/) // oScore[split][end][rState][cp] = // rightScores[cp]; // else if (rightScores[cp] > initVal) { if (viterbi) oScorePreU[split][end][rState][cp] = Math .max(oScorePreU[split][end][rState][cp], rightScores[cp]); else oScorePreU[split][end][rState][cp] += rightScores[cp]; } } // oScale[split][end][rState] = currentScale; // oScale[split][end][rState] = // scaleArray(oScore[split][end][rState],oScale[split][end][rState]); } } } } } } void initializeChart(List<String> sentence, Lexicon lexicon, boolean noSubstates, boolean noSmoothing) { int start = 0; int end = start + 1; for (String word : sentence) { end = start + 1; for (int tag = 0; tag < numSubStatesArray.length; tag++) { if (!noSubstates && allowedSubStates[start][end][tag] == null) continue; if (grammarTags[tag]) continue; // System.out.println("Initializing"); // if (dummy) allowedStates[start][end][tag] = true; narrowRExtent[start][tag] = end; narrowLExtent[end][tag] = start; wideRExtent[start][tag] = end; wideLExtent[end][tag] = start; double[] lexiconScores = lexicon.score(word, (short) tag, start, noSmoothing, false); // if (!logProbs) iScale[start][end][tag] = // scaleArray(lexiconScores,0); for (short n = 0; n < lexiconScores.length; n++) { double prob = lexiconScores[n]; if (noSubstates) viScore[start][end][tag] = prob; else iScorePreU[start][end][tag][n] = prob; } /* * if (start==1){ * System.out.println(word+" +TAG "+(String)tagNumberer * .object(tag)+" "+Arrays.toString(lexiconScores)); } */ } start++; } } @Override protected void createArrays(boolean firstTime, int numStates, short[] numSubStatesArray, int level, double initVal, boolean justInit) { // zero out some stuff first in case we recently ran out of memory and // are reallocating // spanMass = new double[length][length+1]; if (firstTime) { viScore = new double[length][length + 1][]; voScore = new double[length][length + 1][]; iScorePreU = new double[length][length + 1][][]; iScorePostU = new double[length][length + 1][][]; oScorePreU = new double[length][length + 1][][]; oScorePostU = new double[length][length + 1][][]; allowedSubStates = new boolean[length][length + 1][][]; allowedStates = new boolean[length][length + 1][]; vAllowedStates = new boolean[length][length + 1]; } for (int start = 0; start < length; start++) { for (int end = start + 1; end <= length; end++) { if (firstTime) { viScore[start][end] = new double[numStates]; voScore[start][end] = new double[numStates]; iScorePreU[start][end] = new double[numStates][]; iScorePostU[start][end] = new double[numStates][]; oScorePreU[start][end] = new double[numStates][]; oScorePostU[start][end] = new double[numStates][]; // iScale[start][end] = new int[numStates]; // oScale[start][end] = new int[numStates]; allowedSubStates[start][end] = new boolean[numStates][]; allowedStates[start][end] = grammarTags.clone(); if (level == 1 && (end - start == 1)) Arrays.fill(allowedStates[start][end], true); vAllowedStates[start][end] = true; } for (int state = 0; state < numSubStatesArray.length; state++) { if (allowedSubStates[start][end][state] != null) { if (level < 1) { viScore[start][end][state] = Double.NEGATIVE_INFINITY; voScore[start][end][state] = Double.NEGATIVE_INFINITY; } else { iScorePreU[start][end][state] = new double[numSubStatesArray[state]]; iScorePostU[start][end][state] = new double[numSubStatesArray[state]]; oScorePreU[start][end][state] = new double[numSubStatesArray[state]]; oScorePostU[start][end][state] = new double[numSubStatesArray[state]]; Arrays.fill(iScorePreU[start][end][state], initVal); Arrays.fill(iScorePostU[start][end][state], initVal); Arrays.fill(oScorePreU[start][end][state], initVal); Arrays.fill(oScorePostU[start][end][state], initVal); // Arrays.fill(iScale[start][end], // Integer.MIN_VALUE); // Arrays.fill(oScale[start][end], // Integer.MIN_VALUE); // boolean[] newAllowedSubStates = new // boolean[numSubStatesArray[state]]; // if (allowedSubStates[start][end][state]==null || // level<=1){ // Arrays.fill(newAllowedSubStates,true); // allowedSubStates[start][end][state] = // newAllowedSubStates; // } else{ // if (!justInit){ // // int[][] curLChildMap = lChildMap[level-2]; // // int[][] curRChildMap = rChildMap[level-2]; // // for (int i=0; // i<allowedSubStates[start][end][state].length; // i++){ // // boolean val = // allowedSubStates[start][end][state][i]; // // newAllowedSubStates[curLChildMap[state][i]] = // val; // // newAllowedSubStates[curRChildMap[state][i]] = // val; // // } // // allowedSubStates[start][end][state] = // newAllowedSubStates; // } // } } } else { if (level < 1) { viScore[start][end][state] = Double.NEGATIVE_INFINITY; voScore[start][end][state] = Double.NEGATIVE_INFINITY; } else { iScorePreU[start][end][state] = null; iScorePostU[start][end][state] = null; oScorePreU[start][end][state] = null; oScorePostU[start][end][state] = null; // allowedSubStates[start][end][state] = new // boolean[1]; // allowedSubStates[start][end][state][0] = false; } } } if (level > 0 && start == 0 && end == length) { if (iScorePostU[start][end][0] == null) System.out .println("ROOT does not span the entire tree!"); } } } narrowRExtent = new int[length + 1][numStates]; wideRExtent = new int[length + 1][numStates]; narrowLExtent = new int[length + 1][numStates]; wideLExtent = new int[length + 1][numStates]; for (int loc = 0; loc <= length; loc++) { Arrays.fill(narrowLExtent[loc], -1); // the rightmost left with // state s ending at i that // we can get is the // beginning Arrays.fill(wideLExtent[loc], length + 1); // the leftmost left with // state s ending at i // that we can get is // the end Arrays.fill(narrowRExtent[loc], length + 1); // the leftmost right // with state s // starting at i // that we can get // is the end Arrays.fill(wideRExtent[loc], -1); // the rightmost right with state // s starting at i that we can // get is the beginning } } @Override protected void clearArrays() { iScorePreU = iScorePostU = oScorePreU = oScorePostU = null; viScore = voScore = null; allowedSubStates = null; vAllowedStates = null; // iPossibleByL = iPossibleByR = oFilteredEnd = oFilteredStart = // oPossibleByL = oPossibleByR = tags = null; narrowRExtent = wideRExtent = narrowLExtent = wideLExtent = null; }
public void doPreParses(List<String> sentence, Tree<StateSet> tree,
1
2023-10-22 13:13:22+00:00
16k
UnityFoundation-io/Libre311
app/src/main/java/app/service/servicerequest/ServiceRequestService.java
[ { "identifier": "DownloadRequestsArgumentsDTO", "path": "app/src/main/java/app/dto/download/DownloadRequestsArgumentsDTO.java", "snippet": "@Introspected\npublic class DownloadRequestsArgumentsDTO {\n\n @Nullable\n @QueryValue(value = \"jurisdiction_id\")\n private String jurisdictionId;\n\n ...
import app.dto.download.DownloadRequestsArgumentsDTO; import app.dto.download.DownloadServiceRequestDTO; import app.dto.servicerequest.*; import app.model.service.Service; import app.model.service.ServiceRepository; import app.model.service.servicedefinition.AttributeDataType; import app.model.service.servicedefinition.AttributeValue; import app.model.service.servicedefinition.ServiceDefinition; import app.model.service.servicedefinition.ServiceDefinitionAttribute; import app.model.servicerequest.ServiceRequest; import app.model.servicerequest.ServiceRequestRepository; import app.model.servicerequest.ServiceRequestStatus; import app.recaptcha.ReCaptchaService; import app.service.storage.StorageUrlUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.opencsv.bean.StatefulBeanToCsv; import com.opencsv.bean.StatefulBeanToCsvBuilder; import com.opencsv.exceptions.CsvDataTypeMismatchException; import com.opencsv.exceptions.CsvRequiredFieldEmptyException; import io.micronaut.core.util.StringUtils; import io.micronaut.data.model.Page; import io.micronaut.data.model.Pageable; import io.micronaut.data.model.Sort; import io.micronaut.http.HttpRequest; import io.micronaut.http.server.types.files.StreamedFile; import jakarta.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.MalformedURLException; import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream;
10,801
} if (StringUtils.hasText(serviceRequestIds)) { List<Long> requestIds = Arrays.stream(serviceRequestIds.split(",")).map(String::trim).map(Long::valueOf).collect(Collectors.toList()); return serviceRequestRepository.findByIdIn(requestIds, pageable); } if (jurisdictionId == null) { return getServiceRequests(pageable, serviceCode, status, startDate, endDate); } return getJurisdictionServiceRequests(jurisdictionId, pageable, serviceCode, status, startDate, endDate); } private Page<ServiceRequest> getServiceRequests(Pageable pageable, String serviceCode, ServiceRequestStatus status, Instant startDate, Instant endDate) { if (StringUtils.hasText(serviceCode) && status != null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndStatusAndDateCreatedBetween(serviceCode, status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByServiceServiceCodeAndStatusAndDateCreatedAfter(serviceCode, status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndStatusAndDateCreatedBefore(serviceCode, status, endDate, pageable); } return serviceRequestRepository.findByServiceServiceCodeAndStatus(serviceCode, status, pageable); } else if (StringUtils.hasText(serviceCode) && status == null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndDateCreatedBetween(serviceCode, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByServiceServiceCodeAndDateCreatedAfter(serviceCode, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndDateCreatedBefore(serviceCode, endDate, pageable); } return serviceRequestRepository.findByServiceServiceCode(serviceCode, pageable); } else if (status != null && StringUtils.isEmpty(serviceCode)) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByStatusAndDateCreatedBetween(status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByStatusAndDateCreatedAfter(status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByStatusAndDateCreatedBefore(status, endDate, pageable); } return serviceRequestRepository.findByStatus(status, pageable); } if (startDate != null && endDate != null) { return serviceRequestRepository.findByDateCreatedBetween(startDate, endDate, pageable); } else if (startDate != null && endDate == null) { // just start return serviceRequestRepository.findByDateCreatedAfter(startDate, pageable); } else if (startDate == null && endDate != null) { // just end return serviceRequestRepository.findByDateCreatedBefore(endDate, pageable); } return serviceRequestRepository.findAll(pageable); } private Page<ServiceRequest> getJurisdictionServiceRequests(String jurisdictionId, Pageable pageable, String serviceCode, ServiceRequestStatus status, Instant startDate, Instant endDate) { if (StringUtils.hasText(serviceCode) && status != null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBetween(jurisdictionId, serviceCode, status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedAfter(jurisdictionId, serviceCode, status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBefore(jurisdictionId, serviceCode, status, endDate, pageable); } return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatus(jurisdictionId, serviceCode, status, pageable); } else if (StringUtils.hasText(serviceCode) && status == null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBetween(jurisdictionId, serviceCode, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndDateCreatedAfter(jurisdictionId, serviceCode, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBefore(jurisdictionId, serviceCode, endDate, pageable); } return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCode(jurisdictionId, serviceCode, pageable); } else if (status != null && StringUtils.isEmpty(serviceCode)) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndStatusAndDateCreatedBetween(jurisdictionId, status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByJurisdictionIdAndStatusAndDateCreatedAfter(jurisdictionId, status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndStatusAndDateCreatedBefore(jurisdictionId, status, endDate, pageable); } return serviceRequestRepository.findByJurisdictionIdAndStatus(jurisdictionId, status, pageable); } if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndDateCreatedBetween(jurisdictionId, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { // just start return serviceRequestRepository.findByJurisdictionIdAndDateCreatedAfter(jurisdictionId, startDate, pageable); } else if (startDate == null && endDate != null) { // just end return serviceRequestRepository.findByJurisdictionIdAndDateCreatedBefore(jurisdictionId, endDate, pageable); } return serviceRequestRepository.findAllByJurisdictionId(jurisdictionId, pageable); } public ServiceRequestDTO getServiceRequest(Long serviceRequestId, String jurisdictionId) { Optional<ServiceRequest> serviceRequestOptional; if (jurisdictionId == null) { serviceRequestOptional = serviceRequestRepository.findById(serviceRequestId); } else { serviceRequestOptional = serviceRequestRepository.findByIdAndJurisdictionId(serviceRequestId, jurisdictionId); } return serviceRequestOptional.map(ServiceRequestService::convertToDTO).orElse(null); }
// Copyright 2023 Libre311 Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package app.service.servicerequest; @Singleton public class ServiceRequestService { private static final Logger LOG = LoggerFactory.getLogger(ServiceRequestService.class); private final ServiceRequestRepository serviceRequestRepository; private final ServiceRepository serviceRepository; private final ReCaptchaService reCaptchaService; private final StorageUrlUtil storageUrlUtil; public ServiceRequestService(ServiceRequestRepository serviceRequestRepository, ServiceRepository serviceRepository, ReCaptchaService reCaptchaService, StorageUrlUtil storageUrlUtil) { this.serviceRequestRepository = serviceRequestRepository; this.serviceRepository = serviceRepository; this.reCaptchaService = reCaptchaService; this.storageUrlUtil = storageUrlUtil; } private static ServiceRequestDTO convertToDTO(ServiceRequest serviceRequest) { ServiceRequestDTO serviceRequestDTO = new ServiceRequestDTO(serviceRequest); ObjectMapper objectMapper = new ObjectMapper(); String attributesJson = serviceRequest.getAttributesJson(); if (attributesJson != null) { try { ServiceDefinitionAttribute[] serviceDefinitionAttributes = objectMapper.readValue(attributesJson, ServiceDefinitionAttribute[].class); serviceRequestDTO.setSelectedValues(List.of(serviceDefinitionAttributes)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } return serviceRequestDTO; } public PostResponseServiceRequestDTO createServiceRequest(HttpRequest<?> request, PostRequestServiceRequestDTO serviceRequestDTO) { if (!reCaptchaService.verifyReCaptcha(serviceRequestDTO.getgRecaptchaResponse())) { LOG.error("ReCaptcha verification failed."); return null; } if (!validMediaUrl(serviceRequestDTO.getMediaUrl())) { LOG.error("Media URL is invalid."); return null; } Optional<Service> serviceByServiceCodeOptional = serviceRepository.findByServiceCode(serviceRequestDTO.getServiceCode()); if (serviceByServiceCodeOptional.isEmpty()) { LOG.error("Corresponding service not found."); return null; // todo return 'corresponding service not found } if (serviceRequestDTO.getJurisdictionId() != null && !serviceRequestDTO.getJurisdictionId().equals(serviceByServiceCodeOptional.get().getJurisdiction().getId())) { LOG.error("Mismatch between jurisdiction_id provided and Service's associated jurisdiction."); return null; } // validate if a location is provided boolean latLongProvided = StringUtils.hasText(serviceRequestDTO.getLatitude()) && StringUtils.hasText(serviceRequestDTO.getLongitude()); if (!latLongProvided && StringUtils.isEmpty(serviceRequestDTO.getAddressString()) && StringUtils.isEmpty(serviceRequestDTO.getAddressId())) { LOG.error("Address or lat/long not provided."); return null; // todo throw exception } // validate if additional attributes are required List<ServiceDefinitionAttribute> requestAttributes = null; Service service = serviceByServiceCodeOptional.get(); if (service.isMetadata()) { // get service definition String serviceDefinitionJson = service.getServiceDefinitionJson(); if (serviceDefinitionJson == null || serviceDefinitionJson.isBlank()) { LOG.error("Service definition does not exists despite service requiring it."); return null; // should not be in this state and admin needs to be aware. } requestAttributes = buildUserResponseAttributesFromRequest(request, serviceDefinitionJson); if (requestAttributes.isEmpty()) { LOG.error("Submitted Service Request does not contain any attribute values."); return null; // todo throw exception - must provide attributes } if (!requestAttributesHasAllRequiredServiceDefinitionAttributes(serviceDefinitionJson, requestAttributes)) { LOG.error("Submitted Service Request does not contain required attribute values."); return null; // todo throw exception (validation) } } ServiceRequest serviceRequest = transformDtoToServiceRequest(serviceRequestDTO, service); if (requestAttributes != null) { ObjectMapper objectMapper = new ObjectMapper(); try { serviceRequest.setAttributesJson(objectMapper.writeValueAsString(requestAttributes)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } return new PostResponseServiceRequestDTO(serviceRequestRepository.save(serviceRequest)); } private boolean validMediaUrl(String mediaUrl) { if (mediaUrl == null) return true; return mediaUrl.startsWith(storageUrlUtil.getBucketUrlString()); } private boolean requestAttributesHasAllRequiredServiceDefinitionAttributes(String serviceDefinitionJson, List<ServiceDefinitionAttribute> requestAttributes) { // deserialize ObjectMapper objectMapper = new ObjectMapper(); boolean containsAllRequiredAttrs = false; try { // collect all required attributes ServiceDefinition serviceDefinition = objectMapper.readValue(serviceDefinitionJson, ServiceDefinition.class); List<String> requiredCodes = serviceDefinition.getAttributes().stream() .filter(ServiceDefinitionAttribute::isRequired) .map(ServiceDefinitionAttribute::getCode) .collect(Collectors.toList()); // for each attr, check if it exists in requestAttributes List<String> requestCodes = requestAttributes.stream() .map(ServiceDefinitionAttribute::getCode) .collect(Collectors.toList()); containsAllRequiredAttrs = requestCodes.containsAll(requiredCodes); } catch (JsonProcessingException e) { throw new RuntimeException(e); } return containsAllRequiredAttrs; } private List<ServiceDefinitionAttribute> buildUserResponseAttributesFromRequest(HttpRequest<?> request, String serviceDefinitionJson) { ObjectMapper objectMapper = new ObjectMapper(); ServiceDefinition serviceDefinition; try { serviceDefinition = objectMapper.readValue(serviceDefinitionJson, ServiceDefinition.class); } catch (JsonProcessingException e) { throw new RuntimeException(e); } Optional<Map> body = request.getBody(Map.class); List<ServiceDefinitionAttribute> attributes = new ArrayList<>(); if (body.isPresent()) { Map<String, Object> map = body.get(); map.forEach((k, v) -> { if (k.startsWith("attribute[")) { String attributeCode = k.substring(k.indexOf("[") + 1, k.indexOf("]")); // search for attribute by code in serviceDefinition Optional<ServiceDefinitionAttribute> serviceDefinitionAttributeOptional = serviceDefinition.getAttributes().stream() .filter(serviceDefinitionAttribute -> serviceDefinitionAttribute.getCode().equals(attributeCode)) .findFirst(); // if attribute in request does not exist in db, then ignore if (serviceDefinitionAttributeOptional.isEmpty()) { return; } ServiceDefinitionAttribute serviceDefinitionAttribute = serviceDefinitionAttributeOptional.get(); // validate the value if necessary (number and dates) if (v != null && !validValueType(v, serviceDefinitionAttribute.getDatatype())) { String errorMsg = String.format("Provided value for attribute with code %s is invalid", attributeCode); LOG.error(errorMsg); throw new RuntimeException(errorMsg); } ServiceDefinitionAttribute sda = new ServiceDefinitionAttribute(); sda.setCode(attributeCode); sda.setAttributeOrder(serviceDefinitionAttribute.getAttributeOrder()); sda.setRequired(serviceDefinitionAttribute.isRequired()); sda.setVariable(serviceDefinitionAttribute.isVariable()); List<AttributeValue> values = new ArrayList<>(); if (serviceDefinitionAttribute.getDatatype() == AttributeDataType.SINGLEVALUELIST || serviceDefinitionAttribute.getDatatype() == AttributeDataType.MULTIVALUELIST) { List<AttributeValue> attributeValues = serviceDefinitionAttribute.getValues(); if (attributeValues != null) { if (v instanceof ArrayList) { ((ArrayList<?>) v).forEach(s -> { values.add(new AttributeValue((String) s, getAttributeValueName((String) s, attributeValues))); }); } else { values.add(new AttributeValue((String) v, getAttributeValueName((String) v, attributeValues))); } } } else { // we need a way to capture the user's response. We will do so by adding an attribute value where // the key is the code and the value is the user's response. values.add(new AttributeValue(attributeCode, (String) v)); } attributes.add(sda); } }); } return attributes; } private boolean validValueType(Object v, AttributeDataType datatype) { if (datatype == AttributeDataType.NUMBER || datatype == AttributeDataType.DATETIME){ String value = (String) v; if (datatype == AttributeDataType.NUMBER) { try { Integer.parseInt(value); } catch (NumberFormatException nfe) { return false; } } else { try { Instant.parse(value); } catch (DateTimeParseException dtpe) { return false; } } return true; } return true; } private String getAttributeValueName(String valueKey, List<AttributeValue> attributeValues) { String valueName = null; Optional<AttributeValue> attributeValueOptional = attributeValues.stream() .filter(attributeValue -> attributeValue.getKey().equals(valueKey)).findFirst(); if (attributeValueOptional.isPresent()) { valueName = attributeValueOptional.get().getName(); } return valueName; } private ServiceRequest transformDtoToServiceRequest(PostRequestServiceRequestDTO serviceRequestDTO, Service service) { ServiceRequest serviceRequest = new ServiceRequest(); serviceRequest.setService(service); serviceRequest.setJurisdiction(service.getJurisdiction()); serviceRequest.setLatitude(serviceRequestDTO.getLatitude()); serviceRequest.setLongitude(serviceRequestDTO.getLongitude()); serviceRequest.setAddressString(serviceRequestDTO.getAddressString()); serviceRequest.setAddressId(serviceRequestDTO.getAddressId()); serviceRequest.setEmail(serviceRequestDTO.getEmail()); serviceRequest.setDeviceId(serviceRequestDTO.getDeviceId()); serviceRequest.setAccountId(serviceRequestDTO.getAccountId()); serviceRequest.setFirstName(serviceRequestDTO.getFirstName()); serviceRequest.setLastName(serviceRequestDTO.getLastName()); serviceRequest.setPhone(serviceRequestDTO.getPhone()); serviceRequest.setDescription(serviceRequestDTO.getDescription()); serviceRequest.setMediaUrl(serviceRequestDTO.getMediaUrl()); return serviceRequest; } public Page<ServiceRequestDTO> findAll(GetServiceRequestsDTO requestDTO) { return getServiceRequestPage(requestDTO).map(ServiceRequestService::convertToDTO); } private Page<ServiceRequest> getServiceRequestPage(GetServiceRequestsDTO requestDTO) { String serviceRequestIds = requestDTO.getId(); String serviceCode = requestDTO.getServiceCode(); String jurisdictionId = requestDTO.getJurisdictionId(); ServiceRequestStatus status = requestDTO.getStatus(); Instant startDate = requestDTO.getStartDate(); Instant endDate = requestDTO.getEndDate(); Pageable pageable = requestDTO.getPageable(); if(!pageable.isSorted()) { pageable = pageable.order("dateCreated", Sort.Order.Direction.DESC); } if (StringUtils.hasText(serviceRequestIds)) { List<Long> requestIds = Arrays.stream(serviceRequestIds.split(",")).map(String::trim).map(Long::valueOf).collect(Collectors.toList()); return serviceRequestRepository.findByIdIn(requestIds, pageable); } if (jurisdictionId == null) { return getServiceRequests(pageable, serviceCode, status, startDate, endDate); } return getJurisdictionServiceRequests(jurisdictionId, pageable, serviceCode, status, startDate, endDate); } private Page<ServiceRequest> getServiceRequests(Pageable pageable, String serviceCode, ServiceRequestStatus status, Instant startDate, Instant endDate) { if (StringUtils.hasText(serviceCode) && status != null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndStatusAndDateCreatedBetween(serviceCode, status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByServiceServiceCodeAndStatusAndDateCreatedAfter(serviceCode, status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndStatusAndDateCreatedBefore(serviceCode, status, endDate, pageable); } return serviceRequestRepository.findByServiceServiceCodeAndStatus(serviceCode, status, pageable); } else if (StringUtils.hasText(serviceCode) && status == null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndDateCreatedBetween(serviceCode, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByServiceServiceCodeAndDateCreatedAfter(serviceCode, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByServiceServiceCodeAndDateCreatedBefore(serviceCode, endDate, pageable); } return serviceRequestRepository.findByServiceServiceCode(serviceCode, pageable); } else if (status != null && StringUtils.isEmpty(serviceCode)) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByStatusAndDateCreatedBetween(status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByStatusAndDateCreatedAfter(status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByStatusAndDateCreatedBefore(status, endDate, pageable); } return serviceRequestRepository.findByStatus(status, pageable); } if (startDate != null && endDate != null) { return serviceRequestRepository.findByDateCreatedBetween(startDate, endDate, pageable); } else if (startDate != null && endDate == null) { // just start return serviceRequestRepository.findByDateCreatedAfter(startDate, pageable); } else if (startDate == null && endDate != null) { // just end return serviceRequestRepository.findByDateCreatedBefore(endDate, pageable); } return serviceRequestRepository.findAll(pageable); } private Page<ServiceRequest> getJurisdictionServiceRequests(String jurisdictionId, Pageable pageable, String serviceCode, ServiceRequestStatus status, Instant startDate, Instant endDate) { if (StringUtils.hasText(serviceCode) && status != null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBetween(jurisdictionId, serviceCode, status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedAfter(jurisdictionId, serviceCode, status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBefore(jurisdictionId, serviceCode, status, endDate, pageable); } return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndStatus(jurisdictionId, serviceCode, status, pageable); } else if (StringUtils.hasText(serviceCode) && status == null) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBetween(jurisdictionId, serviceCode, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndDateCreatedAfter(jurisdictionId, serviceCode, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBefore(jurisdictionId, serviceCode, endDate, pageable); } return serviceRequestRepository.findByJurisdictionIdAndServiceServiceCode(jurisdictionId, serviceCode, pageable); } else if (status != null && StringUtils.isEmpty(serviceCode)) { if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndStatusAndDateCreatedBetween(jurisdictionId, status, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { return serviceRequestRepository.findByJurisdictionIdAndStatusAndDateCreatedAfter(jurisdictionId, status, startDate, pageable); } else if (startDate == null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndStatusAndDateCreatedBefore(jurisdictionId, status, endDate, pageable); } return serviceRequestRepository.findByJurisdictionIdAndStatus(jurisdictionId, status, pageable); } if (startDate != null && endDate != null) { return serviceRequestRepository.findByJurisdictionIdAndDateCreatedBetween(jurisdictionId, startDate, endDate, pageable); } else if (startDate != null && endDate == null) { // just start return serviceRequestRepository.findByJurisdictionIdAndDateCreatedAfter(jurisdictionId, startDate, pageable); } else if (startDate == null && endDate != null) { // just end return serviceRequestRepository.findByJurisdictionIdAndDateCreatedBefore(jurisdictionId, endDate, pageable); } return serviceRequestRepository.findAllByJurisdictionId(jurisdictionId, pageable); } public ServiceRequestDTO getServiceRequest(Long serviceRequestId, String jurisdictionId) { Optional<ServiceRequest> serviceRequestOptional; if (jurisdictionId == null) { serviceRequestOptional = serviceRequestRepository.findById(serviceRequestId); } else { serviceRequestOptional = serviceRequestRepository.findByIdAndJurisdictionId(serviceRequestId, jurisdictionId); } return serviceRequestOptional.map(ServiceRequestService::convertToDTO).orElse(null); }
public StreamedFile getAllServiceRequests(DownloadRequestsArgumentsDTO downloadRequestsArgumentsDTO) throws MalformedURLException {
0
2023-10-18 15:37:36+00:00
16k
JonnyOnlineYT/xenza
src/minecraft/net/augustus/modules/combat/FastBow.java
[ { "identifier": "EventUpdate", "path": "src/minecraft/net/augustus/events/EventUpdate.java", "snippet": "public class EventUpdate extends Event {\n}" }, { "identifier": "Categorys", "path": "src/minecraft/net/augustus/modules/Categorys.java", "snippet": "public enum Categorys {\n MOVE...
import net.augustus.events.EventUpdate; import net.augustus.modules.Categorys; import net.augustus.modules.Module; import net.lenni0451.eventapi.reflection.EventTarget; import net.minecraft.item.ItemBow; import net.minecraft.network.play.client.C03PacketPlayer; import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import java.awt.*;
11,639
package net.augustus.modules.combat; public class FastBow extends Module { public FastBow() { super("FastBow", Color.ORANGE, Categorys.COMBAT); } @EventTarget public void onUpdate(EventUpdate event) { if ( mc.thePlayer.getHealth() > 0 && (mc.thePlayer.onGround || mc.thePlayer.capabilities.isCreativeMode) && mc.thePlayer.inventory.getCurrentItem() != null && mc.thePlayer.inventory.getCurrentItem().getItem() instanceof ItemBow && mc.gameSettings.keyBindUseItem.pressed ) { mc.playerController.sendUseItem ( mc.thePlayer, mc.theWorld, mc.thePlayer.inventory.getCurrentItem() ); mc.thePlayer.inventory.getCurrentItem().getItem().onItemRightClick ( mc.thePlayer.inventory.getCurrentItem(), mc.theWorld, mc.thePlayer ); for(int i = 0; i < 20; i++) mc.thePlayer.sendQueue.addToSendQueue(new C03PacketPlayer(false));
package net.augustus.modules.combat; public class FastBow extends Module { public FastBow() { super("FastBow", Color.ORANGE, Categorys.COMBAT); } @EventTarget public void onUpdate(EventUpdate event) { if ( mc.thePlayer.getHealth() > 0 && (mc.thePlayer.onGround || mc.thePlayer.capabilities.isCreativeMode) && mc.thePlayer.inventory.getCurrentItem() != null && mc.thePlayer.inventory.getCurrentItem().getItem() instanceof ItemBow && mc.gameSettings.keyBindUseItem.pressed ) { mc.playerController.sendUseItem ( mc.thePlayer, mc.theWorld, mc.thePlayer.inventory.getCurrentItem() ); mc.thePlayer.inventory.getCurrentItem().getItem().onItemRightClick ( mc.thePlayer.inventory.getCurrentItem(), mc.theWorld, mc.thePlayer ); for(int i = 0; i < 20; i++) mc.thePlayer.sendQueue.addToSendQueue(new C03PacketPlayer(false));
mc.getNetHandler().addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN));
6
2023-10-15 00:21:15+00:00
16k
turtleisaac/PokEditor
src/main/java/io/github/turtleisaac/pokeditor/gui/editors/data/formats/scripts/field/FieldScriptEditor.java
[ { "identifier": "PokeditorManager", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/PokeditorManager.java", "snippet": "public class PokeditorManager extends PanelManager\n{\n private static final Dimension dimension = new Dimension(1200, 714);\n\n public static final FlatSVGIcon sheetE...
import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.text.*; import io.github.turtleisaac.nds4j.ui.ThemeUtils; import io.github.turtleisaac.pokeditor.formats.GenericFileData; import io.github.turtleisaac.pokeditor.formats.scripts.GenericScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.ScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.LevelScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.antlr4.ScriptDataProducer; import io.github.turtleisaac.pokeditor.formats.text.TextBankData; import io.github.turtleisaac.pokeditor.gui.*; import io.github.turtleisaac.pokeditor.gui.PokeditorManager; import io.github.turtleisaac.pokeditor.gui.editors.data.DefaultDataEditor; import io.github.turtleisaac.pokeditor.gui.editors.data.DefaultDataEditorPanel; import io.github.turtleisaac.pokeditor.gui.editors.data.EditorDataModel; import io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.*; import io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.ScriptDocument; import io.github.turtleisaac.pokeditor.gui.sheets.tables.FormatModel; import net.miginfocom.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.List;
11,978
/* * Created by JFormDesigner */ package io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.field; /** * @author turtleisaac */ public class FieldScriptEditor extends DefaultDataEditor<GenericScriptData, FieldScriptEditor.FieldScriptContents> { private DefaultListModel<GenericScriptData.ScriptComponent> levelScriptDataListModel = new DefaultListModel<>(); private DefaultListModel<String> labelDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> actionDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> scriptDisplayListModel = new DefaultListModel<>(); private boolean editMode; private GenericScriptData.ScriptComponent selected; public FieldScriptEditor(List<GenericScriptData> data, List<TextBankData> textBankData) { super(new FieldScriptModel(data, textBankData)); editMode = false; initComponents(); // FieldScriptEditorKit editorKit = new FieldScriptEditorKit();
/* * Created by JFormDesigner */ package io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.field; /** * @author turtleisaac */ public class FieldScriptEditor extends DefaultDataEditor<GenericScriptData, FieldScriptEditor.FieldScriptContents> { private DefaultListModel<GenericScriptData.ScriptComponent> levelScriptDataListModel = new DefaultListModel<>(); private DefaultListModel<String> labelDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> actionDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> scriptDisplayListModel = new DefaultListModel<>(); private boolean editMode; private GenericScriptData.ScriptComponent selected; public FieldScriptEditor(List<GenericScriptData> data, List<TextBankData> textBankData) { super(new FieldScriptModel(data, textBankData)); editMode = false; initComponents(); // FieldScriptEditorKit editorKit = new FieldScriptEditorKit();
StyledDocument document = new ScriptDocument(textPane1);
4
2023-10-15 05:00:57+00:00
16k
eclipse-egit/egit
org.eclipse.egit.core/src/org/eclipse/egit/core/op/BranchOperation.java
[ { "identifier": "Activator", "path": "org.eclipse.egit.core/src/org/eclipse/egit/core/Activator.java", "snippet": "public class Activator extends Plugin {\n\n\t/** The plug-in ID for Egit core. */\n\tpublic static final String PLUGIN_ID = \"org.eclipse.egit.core\"; //$NON-NLS-1$\n\n\tprivate static Acti...
import java.io.File; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Stream; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.egit.core.Activator; import org.eclipse.egit.core.EclipseGitProgressTransformer; import org.eclipse.egit.core.internal.CoreText; import org.eclipse.egit.core.internal.job.RuleUtil; import org.eclipse.egit.core.internal.util.ProjectUtil; import org.eclipse.jgit.annotations.NonNull; import org.eclipse.jgit.api.CheckoutCommand; import org.eclipse.jgit.api.CheckoutResult; import org.eclipse.jgit.api.CheckoutResult.Status; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.CheckoutConflictException; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.JGitInternalException; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.treewalk.AbstractTreeIterator; import org.eclipse.jgit.treewalk.FileTreeIterator; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.AndTreeFilter; import org.eclipse.jgit.treewalk.filter.PathSuffixFilter; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.eclipse.jgit.util.FileUtils;
13,245
/******************************************************************************* * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com> * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com> * Copyright (C) 2006, Shawn O. Pearce <spearce@spearce.org> * Copyright (C) 2010, Jens Baumgart <jens.baumgart@sap.com> * Copyright (C) 2010, 2011, Mathias Kinzler <mathias.kinzler@sap.com> * Copyright (C) 2015, Stephan Hackstedt <stephan.hackstedt@googlemail.com> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package org.eclipse.egit.core.op; /** * This class implements checkouts of a specific revision. A check is made that * this can be done without data loss. */ public class BranchOperation implements IEGitOperation { private final String target; private Repository[] repositories; private @NonNull Map<Repository, CheckoutResult> results = new HashMap<>(); private boolean delete; /** * Construct a {@link BranchOperation} object for a {@link Ref}. * * @param repository * @param target * a {@link Ref} name or {@link RevCommit} id */ public BranchOperation(Repository repository, String target) { this(repository, target, true); } /** * Construct a {@link BranchOperation} object for a {@link Ref}. * * @param repository * @param target * a {@link Ref} name or {@link RevCommit} id * @param delete * true to delete missing projects on new branch, false to close * them */ public BranchOperation(Repository repository, String target, boolean delete) { this(new Repository[] { repository }, target, delete); } /** * * @param repositories * @param target * @param delete */ public BranchOperation(Repository[] repositories, String target, boolean delete) { this.repositories = repositories; this.target = target; this.delete = delete; } @Override public void execute(IProgressMonitor m) throws CoreException { IWorkspaceRunnable action = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor pm) throws CoreException { try { pm.setTaskName(MessageFormat.format( CoreText.BranchOperation_performingBranch, target)); int numberOfRepositories = repositories.length; SubMonitor progress = SubMonitor.convert(pm, numberOfRepositories * 2); for (Repository repository : repositories) { CheckoutResult result; if (pm.isCanceled()) { // don't break from the loop, the result map must be // filled result = CheckoutResult.NOT_TRIED_RESULT; } else { result = checkoutRepository(repository, progress.newChild(1), numberOfRepositories > 1); if (result.getStatus() == Status.NONDELETED) { retryDelete(repository, result.getUndeletedList()); } } results.put(repository, result); } refreshAffectedProjects( progress.newChild(numberOfRepositories)); } finally { pm.done(); } } public CheckoutResult checkoutRepository(Repository repo, IProgressMonitor monitor, boolean logErrors) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, 2); closeProjectsMissingAfterCheckout(repo, progress.newChild(1)); try (Git git = new Git(repo)) { CheckoutCommand co = git.checkout().setProgressMonitor(
/******************************************************************************* * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com> * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com> * Copyright (C) 2006, Shawn O. Pearce <spearce@spearce.org> * Copyright (C) 2010, Jens Baumgart <jens.baumgart@sap.com> * Copyright (C) 2010, 2011, Mathias Kinzler <mathias.kinzler@sap.com> * Copyright (C) 2015, Stephan Hackstedt <stephan.hackstedt@googlemail.com> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package org.eclipse.egit.core.op; /** * This class implements checkouts of a specific revision. A check is made that * this can be done without data loss. */ public class BranchOperation implements IEGitOperation { private final String target; private Repository[] repositories; private @NonNull Map<Repository, CheckoutResult> results = new HashMap<>(); private boolean delete; /** * Construct a {@link BranchOperation} object for a {@link Ref}. * * @param repository * @param target * a {@link Ref} name or {@link RevCommit} id */ public BranchOperation(Repository repository, String target) { this(repository, target, true); } /** * Construct a {@link BranchOperation} object for a {@link Ref}. * * @param repository * @param target * a {@link Ref} name or {@link RevCommit} id * @param delete * true to delete missing projects on new branch, false to close * them */ public BranchOperation(Repository repository, String target, boolean delete) { this(new Repository[] { repository }, target, delete); } /** * * @param repositories * @param target * @param delete */ public BranchOperation(Repository[] repositories, String target, boolean delete) { this.repositories = repositories; this.target = target; this.delete = delete; } @Override public void execute(IProgressMonitor m) throws CoreException { IWorkspaceRunnable action = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor pm) throws CoreException { try { pm.setTaskName(MessageFormat.format( CoreText.BranchOperation_performingBranch, target)); int numberOfRepositories = repositories.length; SubMonitor progress = SubMonitor.convert(pm, numberOfRepositories * 2); for (Repository repository : repositories) { CheckoutResult result; if (pm.isCanceled()) { // don't break from the loop, the result map must be // filled result = CheckoutResult.NOT_TRIED_RESULT; } else { result = checkoutRepository(repository, progress.newChild(1), numberOfRepositories > 1); if (result.getStatus() == Status.NONDELETED) { retryDelete(repository, result.getUndeletedList()); } } results.put(repository, result); } refreshAffectedProjects( progress.newChild(numberOfRepositories)); } finally { pm.done(); } } public CheckoutResult checkoutRepository(Repository repo, IProgressMonitor monitor, boolean logErrors) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, 2); closeProjectsMissingAfterCheckout(repo, progress.newChild(1)); try (Git git = new Git(repo)) { CheckoutCommand co = git.checkout().setProgressMonitor(
new EclipseGitProgressTransformer(
1
2023-10-20 15:17:51+00:00
16k