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
quan100/quan
quan-app/quan-app-pm-bff/src/main/java/cn/javaquan/app/pm/bff/file/controller/FileController.java
[ { "identifier": "FileAssembler", "path": "quan-app/quan-app-pm-bff/src/main/java/cn/javaquan/app/pm/bff/file/convert/FileAssembler.java", "snippet": "@Mapper\npublic interface FileAssembler {\n\n FileAssembler INSTANCE = Mappers.getMapper(FileAssembler.class);\n\n @Mapping(target = \"url\", expres...
import cn.javaquan.app.pm.bff.file.convert.FileAssembler; import cn.javaquan.app.common.module.file.FileVO; import cn.javaquan.common.base.message.Result; import cn.javaquan.tools.file.minio.MinioResponse; import cn.javaquan.tools.file.minio.MinioUtil; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse;
3,784
package cn.javaquan.app.pm.bff.file.controller; /** * 文件 * * @author JavaQuan * @version 2.2.0 */ @RequiredArgsConstructor @RestController @RequestMapping("/file") public class FileController { private final MinioUtil minioUtil; /** * 文件上传 * * @param file * @return */ @PostMapping(value = "/upload") public Result<FileVO> upload(@RequestPart MultipartFile file) { MinioResponse response = minioUtil.upload(file);
package cn.javaquan.app.pm.bff.file.controller; /** * 文件 * * @author JavaQuan * @version 2.2.0 */ @RequiredArgsConstructor @RestController @RequestMapping("/file") public class FileController { private final MinioUtil minioUtil; /** * 文件上传 * * @param file * @return */ @PostMapping(value = "/upload") public Result<FileVO> upload(@RequestPart MultipartFile file) { MinioResponse response = minioUtil.upload(file);
return Result.success(FileAssembler.INSTANCE.toFileVO(response));
0
2023-10-08 06:48:41+00:00
8k
Ghost-chu/DoDoSRV
src/main/java/com/ghostchu/plugins/dodosrv/text/TextManager.java
[ { "identifier": "DoDoSRV", "path": "src/main/java/com/ghostchu/plugins/dodosrv/DoDoSRV.java", "snippet": "public final class DoDoSRV extends JavaPlugin {\n\n private DodoBot bot;\n private DatabaseManager databaseManager;\n private UserBindManager userBindManager;\n private TextManager textM...
import com.ghostchu.plugins.dodosrv.DoDoSRV; import com.ghostchu.plugins.dodosrv.util.JsonUtil; import com.ghostchu.plugins.dodosrv.util.Util; import de.themoep.minedown.adventure.MineDown; import net.deechael.dodo.api.Member; import net.deechael.dodo.content.Message; import net.deechael.dodo.content.TextMessage; import net.deechael.dodo.types.MessageType; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.ComponentLike; import net.kyori.adventure.text.TextReplacementConfig; import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import org.apache.commons.lang3.StringUtils; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.CompletableFuture;
3,953
String[] found = StringUtils.substringsBetween(content, "<@!", ">"); if (found != null) { for (int i = 0; i < found.length; i++) { try { String cursor = found[i]; String replaceTo = "{" + i + "}"; String origin = "<@!" + cursor + ">"; replaced = replaced.replace(origin, replaceTo); Member member = plugin.bot().getClient().fetchMember(plugin.getIslandId(), cursor); replacements.put(replaceTo, plugin.dodoManager().getMemberDisplayComponent(plugin.getIslandId(), member)); } catch (Throwable ignored) { } } } Component component = new MineDown(replaced).toComponent(); for (Map.Entry<String, Component> e : replacements.entrySet()) { component = component.replaceText(TextReplacementConfig.builder() .matchLiteral(e.getKey()) .replacement(e.getValue()) .build()); } return component; }); } public Text of(CommandSender sender, String key, Object... args) { return new Text(sender, Util.fillArgs(miniMessage.deserialize(config.getString(key, "Missing no: " + key)), convert(args))); } public Text of(String key, Object... args) { return new Text(null, Util.fillArgs(miniMessage.deserialize(config.getString(key, "Missing no: " + key)), convert(args))); } @NotNull public Component[] convert(@Nullable Object... args) { if (args == null || args.length == 0) { return new Component[0]; } Component[] components = new Component[args.length]; for (int i = 0; i < args.length; i++) { Object obj = args[i]; if (obj == null) { components[i] = Component.text("null"); continue; } Class<?> clazz = obj.getClass(); if (obj instanceof Component) { Component component = (Component) obj; components[i] = component; continue; } if (obj instanceof ComponentLike) { ComponentLike componentLike = (ComponentLike) obj; components[i] = componentLike.asComponent(); continue; } // Check try { if (Character.class.equals(clazz)) { components[i] = Component.text((char) obj); continue; } if (Byte.class.equals(clazz)) { components[i] = Component.text((Byte) obj); continue; } if (Integer.class.equals(clazz)) { components[i] = Component.text((Integer) obj); continue; } if (Long.class.equals(clazz)) { components[i] = Component.text((Long) obj); continue; } if (Float.class.equals(clazz)) { components[i] = Component.text((Float) obj); continue; } if (Double.class.equals(clazz)) { components[i] = Component.text((Double) obj); continue; } if (Boolean.class.equals(clazz)) { components[i] = Component.text((Boolean) obj); continue; } if (String.class.equals(clazz)) { components[i] = LegacyComponentSerializer.legacySection().deserialize((String) obj); continue; } if (Text.class.equals(clazz)) { components[i] = ((Text) obj).component(); } components[i] = LegacyComponentSerializer.legacySection().deserialize(obj.toString()); } catch (Exception exception) { components[i] = LegacyComponentSerializer.legacySection().deserialize(obj.toString()); } // undefined } return components; } public static class Text { private final Component component; private final CommandSender sender; public Text(CommandSender sender, Component component) { this.sender = sender; this.component = component.compact(); } public Message dodoText() { String raw = PlainTextComponentSerializer.plainText().serialize(component); if (StringUtils.isBlank(raw)) { raw = "Missing no: text is null"; } Message message = new TextMessage(raw);
package com.ghostchu.plugins.dodosrv.text; public class TextManager { private final File file; private final DoDoSRV plugin; private YamlConfiguration config; private MiniMessage miniMessage; public TextManager(DoDoSRV plugin, File file) { this.plugin = plugin; this.file = file; init(); } private void init() { this.config = YamlConfiguration.loadConfiguration(file); this.miniMessage = MiniMessage.miniMessage(); } public CompletableFuture<Component> dodoToComponent(String content) { return CompletableFuture.supplyAsync(() -> { String replaced = content; Map<String, Component> replacements = new LinkedHashMap<>(); String[] found = StringUtils.substringsBetween(content, "<@!", ">"); if (found != null) { for (int i = 0; i < found.length; i++) { try { String cursor = found[i]; String replaceTo = "{" + i + "}"; String origin = "<@!" + cursor + ">"; replaced = replaced.replace(origin, replaceTo); Member member = plugin.bot().getClient().fetchMember(plugin.getIslandId(), cursor); replacements.put(replaceTo, plugin.dodoManager().getMemberDisplayComponent(plugin.getIslandId(), member)); } catch (Throwable ignored) { } } } Component component = new MineDown(replaced).toComponent(); for (Map.Entry<String, Component> e : replacements.entrySet()) { component = component.replaceText(TextReplacementConfig.builder() .matchLiteral(e.getKey()) .replacement(e.getValue()) .build()); } return component; }); } public Text of(CommandSender sender, String key, Object... args) { return new Text(sender, Util.fillArgs(miniMessage.deserialize(config.getString(key, "Missing no: " + key)), convert(args))); } public Text of(String key, Object... args) { return new Text(null, Util.fillArgs(miniMessage.deserialize(config.getString(key, "Missing no: " + key)), convert(args))); } @NotNull public Component[] convert(@Nullable Object... args) { if (args == null || args.length == 0) { return new Component[0]; } Component[] components = new Component[args.length]; for (int i = 0; i < args.length; i++) { Object obj = args[i]; if (obj == null) { components[i] = Component.text("null"); continue; } Class<?> clazz = obj.getClass(); if (obj instanceof Component) { Component component = (Component) obj; components[i] = component; continue; } if (obj instanceof ComponentLike) { ComponentLike componentLike = (ComponentLike) obj; components[i] = componentLike.asComponent(); continue; } // Check try { if (Character.class.equals(clazz)) { components[i] = Component.text((char) obj); continue; } if (Byte.class.equals(clazz)) { components[i] = Component.text((Byte) obj); continue; } if (Integer.class.equals(clazz)) { components[i] = Component.text((Integer) obj); continue; } if (Long.class.equals(clazz)) { components[i] = Component.text((Long) obj); continue; } if (Float.class.equals(clazz)) { components[i] = Component.text((Float) obj); continue; } if (Double.class.equals(clazz)) { components[i] = Component.text((Double) obj); continue; } if (Boolean.class.equals(clazz)) { components[i] = Component.text((Boolean) obj); continue; } if (String.class.equals(clazz)) { components[i] = LegacyComponentSerializer.legacySection().deserialize((String) obj); continue; } if (Text.class.equals(clazz)) { components[i] = ((Text) obj).component(); } components[i] = LegacyComponentSerializer.legacySection().deserialize(obj.toString()); } catch (Exception exception) { components[i] = LegacyComponentSerializer.legacySection().deserialize(obj.toString()); } // undefined } return components; } public static class Text { private final Component component; private final CommandSender sender; public Text(CommandSender sender, Component component) { this.sender = sender; this.component = component.compact(); } public Message dodoText() { String raw = PlainTextComponentSerializer.plainText().serialize(component); if (StringUtils.isBlank(raw)) { raw = "Missing no: text is null"; } Message message = new TextMessage(raw);
if (false && JsonUtil.isJson(raw)) {
1
2023-10-11 16:16:54+00:00
8k
Hartie95/AnimeGamesLua
GILua/src/main/java/org/anime_game_servers/gi_lua/script_lib/ScriptLib.java
[ { "identifier": "ExhibitionPlayType", "path": "GILua/src/main/java/org/anime_game_servers/gi_lua/models/constants/ExhibitionPlayType.java", "snippet": "@LuaStatic\npublic enum ExhibitionPlayType {\n Challenge,\n Gallery,\n}" }, { "identifier": "FlowSuiteOperatePolicy", "path": "GILua/s...
import io.github.oshai.kotlinlogging.KLogger; import io.github.oshai.kotlinlogging.KotlinLogging; import lombok.val; import org.anime_game_servers.core.base.annotations.lua.LuaStatic; import org.anime_game_servers.gi_lua.models.constants.*; import org.anime_game_servers.gi_lua.models.constants.ExhibitionPlayType; import org.anime_game_servers.gi_lua.models.constants.FlowSuiteOperatePolicy; import org.anime_game_servers.gi_lua.models.constants.temporary.GalleryProgressScoreType; import org.anime_game_servers.gi_lua.models.constants.temporary.GalleryProgressScoreUIType; import org.anime_game_servers.gi_lua.script_lib.handler.ScriptLibStaticHandler; import org.anime_game_servers.gi_lua.script_lib.handler.parameter.KillByConfigIdParams; import org.anime_game_servers.lua.engine.LuaTable; import static org.anime_game_servers.gi_lua.utils.ScriptUtils.luaToPos; import static org.anime_game_servers.gi_lua.utils.ScriptUtils.posToLua; import static org.anime_game_servers.gi_lua.script_lib.ScriptLibErrors.*;
4,369
public static int ExpeditionChallengeEnterRegion(GroupEventLuaContext context, boolean var1){ return context.getScriptLibHandler().ExpeditionChallengeEnterRegion(context, var1); } public static int StartSealBattle(GroupEventLuaContext context, int gadgetId, Object battleParamsTable) { val battleParams = context.getEngine().getTable(battleParamsTable); val battleType = battleParams.optInt("battle_type", -1); if(battleType < 0 || battleType >= SealBattleType.values().length){ scriptLogger.error(() -> "[StartSealBattle] Invalid battle type " + battleType); return -1; } val battleTypeEnum = SealBattleType.values()[battleType]; val handlerParams = switch (battleTypeEnum){ case NONE -> parseSealBattleNoneParams(battleParams); case KILL_MONSTER -> parseSealBattleMonsterKillParams(battleParams); case ENERGY_CHARGE -> parseEnergySealBattleTimeParams(battleParams); }; return context.getScriptLibHandler().StartSealBattle(context, gadgetId, handlerParams); } private static SealBattleParams parseSealBattleNoneParams(LuaTable battleParams){ val radius = battleParams.optInt("radius", -1); val inAdd = battleParams.optInt("in_add", -1); val outSub = battleParams.optInt("out_sub", -1); val failTime = battleParams.optInt("fail_time", -1); val maxProgress = battleParams.optInt("max_progress", -1); // TODO check params and maybe return error? return new DefaultSealBattleParams(radius, inAdd, outSub, failTime, maxProgress); } private static SealBattleParams parseSealBattleMonsterKillParams(LuaTable battleParams){ val radius = battleParams.optInt("radius", -1); val killTime = battleParams.optInt("kill_time", -1); val monsterGroupId = battleParams.optInt("monster_group_id", -1); val maxProgress = battleParams.optInt("max_progress", -1); // TODO check params and maybe return error? return new MonsterSealBattleParams(radius, killTime, monsterGroupId, maxProgress); } private static SealBattleParams parseEnergySealBattleTimeParams(LuaTable battleParams){ val radius = battleParams.optInt("radius", -1); val battleTime = battleParams.optInt("battle_time", -1); val monsterGroupId = battleParams.optInt("monster_group_id", -1); val defaultKillCharge = battleParams.optInt("default_kill_charge", -1); val autoCharge = battleParams.optInt("auto_charge", -1); val autoDecline = battleParams.optInt("auto_decline", -1); val maxEnergy = battleParams.optInt("max_energy", -1); // TODO check params and maybe return error? return new EnergySealBattleParams(radius, battleTime, monsterGroupId, defaultKillCharge, autoCharge, autoDecline, maxEnergy); } public static int InitTimeAxis(GroupEventLuaContext context, String var1, Object var2Table, boolean var3){ val var2 = context.getEngine().getTable(var2Table); return context.getScriptLibHandler().InitTimeAxis(context, var1, var2, var3); } public static int EndTimeAxis(GroupEventLuaContext context, String var1){ return context.getScriptLibHandler().EndTimeAxis(context, var1); } public static int SetTeamEntityGlobalFloatValue(GroupEventLuaContext context, Object sceneUidListTable, String var2, int var3){ val sceneUidList = context.getEngine().getTable(sceneUidListTable); return context.getScriptLibHandler().SetTeamEntityGlobalFloatValue(context, sceneUidList, var2, var3); } public static int SetTeamServerGlobalValue(GroupEventLuaContext context, int sceneUid, String var2, int var3){ return context.getScriptLibHandler().SetTeamServerGlobalValue(context, sceneUid, var2, var3); } public static int AddTeamServerGlobalValue(GroupEventLuaContext context, int ownerId, String sgvName, int value){ return context.getScriptLibHandler().AddTeamServerGlobalValue(context, ownerId, sgvName, value); } public static int GetTeamServerGlobalValue(GroupEventLuaContext context, int ownerId, String sgvName, int value){ return context.getScriptLibHandler().GetTeamServerGlobalValue(context, ownerId, sgvName, value); } public static int GetLanternRiteValue(GroupEventLuaContext context){ return context.getScriptLibHandler().GetLanternRiteValue(context); } public static int CreateMonsterFaceAvatar(GroupEventLuaContext context, Object rawTable) { val table = context.getEngine().getTable(rawTable); return context.getScriptLibHandler().CreateMonsterFaceAvatar(context, table); } public static int ChangeToTargetLevelTag(GroupEventLuaContext context, int var1){ return context.getScriptLibHandler().ChangeToTargetLevelTag(context, var1); } public static int AddSceneTag(GroupEventLuaContext context, int sceneId, int sceneTagId){ return context.getScriptLibHandler().AddSceneTag(context, sceneId, sceneTagId); } public static int DelSceneTag(GroupEventLuaContext context, int sceneId, int sceneTagId){ return context.getScriptLibHandler().DelSceneTag(context, sceneId, sceneTagId); } public static boolean CheckSceneTag(GroupEventLuaContext context, int sceneId, int sceneTagId){ return context.getScriptLibHandler().CheckSceneTag(context, sceneId, sceneTagId); } public static int StartHomeGallery(GroupEventLuaContext context, int galleryId, int uid){ return context.getScriptLibHandler().StartHomeGallery(context, galleryId, uid); } public static int StartGallery(GroupEventLuaContext context, int galleryId){ return context.getScriptLibHandler().StartGallery(context, galleryId); } public static int StopGallery(GroupEventLuaContext context, int galleryId, boolean var2){ return context.getScriptLibHandler().StopGallery(context, galleryId, var2); } public static int UpdatePlayerGalleryScore(GroupEventLuaContext context, int galleryId, Object var2Table) { val var2 = context.getEngine().getTable(var2Table); return context.getScriptLibHandler().UpdatePlayerGalleryScore(context, galleryId, var2); } public static int InitGalleryProgressScore(GroupEventLuaContext context, String name, int galleryId, Object progressTable, int scoreUiTypeIndex, int scoreTypeIndex) { val progress = context.getEngine().getTable(progressTable);
package org.anime_game_servers.gi_lua.script_lib; @LuaStatic public class ScriptLib { /** * Context free functions */ private static KLogger scriptLogger = KotlinLogging.INSTANCE.logger(ScriptLib.class.getName()); public static ScriptLibStaticHandler staticHandler; public static void PrintLog(String msg) { staticHandler.PrintLog(msg); } public static int GetEntityType(int entityId){ return staticHandler.GetEntityType(entityId); } /** * Context independent functions */ public static void PrintContextLog(LuaContext context, String msg) { staticHandler.PrintContextLog(context, msg); } /** * GroupEventLuaContext functions */ public static void PrintGroupWarning(GroupEventLuaContext context, String msg) { context.getScriptLibHandler().PrintGroupWarning(context, msg); } public static int SetGadgetStateByConfigId(GroupEventLuaContext context, int configId, int gadgetState) { return context.getScriptLibHandler().SetGadgetStateByConfigId(context, configId, gadgetState); } public static int SetGroupGadgetStateByConfigId(GroupEventLuaContext context, int groupId, int configId, int gadgetState) { return context.getScriptLibHandler().SetGroupGadgetStateByConfigId(context, groupId, configId, gadgetState); } public static int SetWorktopOptionsByGroupId(GroupEventLuaContext context, int groupId, int configId, Object optionsTable) { val options = context.getEngine().getTable(optionsTable); return context.getScriptLibHandler().SetWorktopOptionsByGroupId(context, groupId, configId, options); } public static int SetWorktopOptions(GroupEventLuaContext context, Object rawTable){ val table = context.getEngine().getTable(rawTable); return context.getScriptLibHandler().SetWorktopOptions(context, table); } public static int DelWorktopOptionByGroupId(GroupEventLuaContext context, int groupId, int configId, int option) { return context.getScriptLibHandler().DelWorktopOptionByGroupId(context, groupId, configId, option); } public static int DelWorktopOption(GroupEventLuaContext context, int var1){ return context.getScriptLibHandler().DelWorktopOption(context, var1); } // Some fields are guessed public static int AutoMonsterTide(GroupEventLuaContext context, int challengeIndex, int groupId, Integer[] ordersConfigId, int tideCount, int sceneLimit, int param6) { return context.getScriptLibHandler().AutoMonsterTide(context, challengeIndex, groupId, ordersConfigId, tideCount, sceneLimit, param6); } public static int GoToGroupSuite(GroupEventLuaContext context, int groupId, int suite) { return context.getScriptLibHandler().GoToGroupSuite(context, groupId, suite); } public static int AddExtraGroupSuite(GroupEventLuaContext context, int groupId, int suite) { return context.getScriptLibHandler().AddExtraGroupSuite(context, groupId, suite); } public static int RemoveExtraGroupSuite(GroupEventLuaContext context, int groupId, int suite) { return context.getScriptLibHandler().RemoveExtraGroupSuite(context, groupId, suite); } public static int KillExtraGroupSuite(GroupEventLuaContext context, int groupId, int suite) { return context.getScriptLibHandler().KillExtraGroupSuite(context, groupId, suite); } public static int AddExtraFlowSuite(GroupEventLuaContext context, int groupId, int suiteId, int flowSuitePolicy){ if(flowSuitePolicy < 0 || flowSuitePolicy >= FlowSuiteOperatePolicy.values().length){ scriptLogger.error(() -> "[AddExtraFlowSuite] Invalid flow suite policy " + flowSuitePolicy); return 1; } val flowSuitePolicyEnum = FlowSuiteOperatePolicy.values()[flowSuitePolicy]; return context.getScriptLibHandler().AddExtraFlowSuite(context, groupId, suiteId, flowSuitePolicyEnum); } public static int RemoveExtraFlowSuite(GroupEventLuaContext context, int groupId, int suiteId, int flowSuitePolicy){ if(flowSuitePolicy < 0 || flowSuitePolicy >= FlowSuiteOperatePolicy.values().length){ scriptLogger.error(() -> "[RemoveExtraFlowSuite] Invalid flow suite policy " + flowSuitePolicy); return 1; } val flowSuitePolicyEnum = FlowSuiteOperatePolicy.values()[flowSuitePolicy]; return context.getScriptLibHandler().RemoveExtraFlowSuite(context, groupId, suiteId, flowSuitePolicyEnum); } public static int KillExtraFlowSuite(GroupEventLuaContext context, int groupId, int suiteId, int flowSuitePolicy){ if(flowSuitePolicy < 0 || flowSuitePolicy >= FlowSuiteOperatePolicy.values().length){ scriptLogger.error(() -> "[KillExtraFlowSuite] Invalid flow suite policy " + flowSuitePolicy); return 1; } val flowSuitePolicyEnum = FlowSuiteOperatePolicy.values()[flowSuitePolicy]; return context.getScriptLibHandler().KillExtraFlowSuite(context, groupId, suiteId, flowSuitePolicyEnum); } public static int ActiveChallenge(GroupEventLuaContext context, int challengeIndex, int challengeId, int timeLimitOrGroupId, int groupId, int objectiveKills, int param5) { return context.getScriptLibHandler().ActiveChallenge(context, challengeIndex, challengeId, timeLimitOrGroupId, groupId, objectiveKills, param5); } public static int StartChallenge(GroupEventLuaContext context, int challengeIndex, int challengeId, Object challengeParams) { val conditionParamTable = context.getEngine().getTable(challengeParams); return context.getScriptLibHandler().StartChallenge(context, challengeIndex, challengeId, conditionParamTable); } public static int StopChallenge(GroupEventLuaContext context, int challengeIndex, int result) { return context.getScriptLibHandler().StopChallenge(context, challengeIndex, result); } /** * Adds or removed time from the challenge * TODO verify and implement * @param context * @param challengeId The active target challenges id * @param duration The duration to add or remove * @return 0 if success, 1 if no challenge is active, 2 if the challenge id doesn't match the active challenge, * 3 if modifying the duration failed */ public static int AddChallengeDuration(GroupEventLuaContext context, int challengeId, int duration) { return context.getScriptLibHandler().AddChallengeDuration(context, challengeId, duration); } public static int GetGroupMonsterCountByGroupId(GroupEventLuaContext context, int groupId) { return context.getScriptLibHandler().GetGroupMonsterCountByGroupId(context, groupId); } // TODO check existence public static int CreateVariable(GroupEventLuaContext context, String type, Object value) { //TODO implement switch (type){ case "int": default: } return 0; } // TODO check existence public static int SetVariableValue(GroupEventLuaContext context, int var1) { //TODO implement var1 type return 0; } public static int GetVariableValue(GroupEventLuaContext context, int var1) { //TODO implement var1 type return 0; } public static int GetGroupVariableValue(GroupEventLuaContext context, String var) { return context.getScriptLibHandler().GetGroupVariableValue(context, var); } public static int GetGroupVariableValueByGroup(GroupEventLuaContext context, String name, int groupId){ return context.getScriptLibHandler().GetGroupVariableValueByGroup(context, name, groupId); } public static int SetGroupVariableValue(GroupEventLuaContext context, String varName, int value) { return context.getScriptLibHandler().SetGroupVariableValue(context, varName, value); } public static int SetGroupVariableValueByGroup(GroupEventLuaContext context, String key, int value, int groupId){ return context.getScriptLibHandler().SetGroupVariableValueByGroup(context, key, value, groupId); } public static int ChangeGroupVariableValue(GroupEventLuaContext context, String varName, int value) { return context.getScriptLibHandler().ChangeGroupVariableValue(context, varName, value); } public static int ChangeGroupVariableValueByGroup(GroupEventLuaContext context, String name, int value, int groupId){ return context.getScriptLibHandler().ChangeGroupVariableValueByGroup(context, name, value, groupId); } /** * Set the actions and triggers to designated group */ public static int RefreshGroup(GroupEventLuaContext context, Object rawTable) { val table = context.getEngine().getTable(rawTable); return context.getScriptLibHandler().RefreshGroup(context, table); } public static int GetRegionEntityCount(GroupEventLuaContext context, Object rawTable) { val table = context.getEngine().getTable(rawTable); int regionId = table.getInt("region_eid"); int entityType = table.getInt("entity_type"); if(entityType < 0 || entityType >= EntityType.values().length){ scriptLogger.error(() -> "[GetRegionEntityCount] Invalid entity type " + entityType); return 0; } val entityTypeEnum = EntityType.values()[entityType]; return context.getScriptLibHandler().GetRegionEntityCount(context, regionId, entityTypeEnum); } public int GetRegionConfigId(GroupEventLuaContext context, Object rawTable){ val table = context.getEngine().getTable(rawTable); val regionEid = table.getInt("region_eid"); return context.getScriptLibHandler().GetRegionConfigId(context, regionEid); } public static int TowerCountTimeStatus(GroupEventLuaContext context, int isDone, int var2){ return context.getScriptLibHandler().TowerCountTimeStatus(context, isDone, var2); } public static int GetGroupMonsterCount(GroupEventLuaContext context){ return context.getScriptLibHandler().GetGroupMonsterCount(context); } public static int SetMonsterBattleByGroup(GroupEventLuaContext context, int configId, int groupId) { return context.getScriptLibHandler().SetMonsterBattleByGroup(context, configId, groupId); } public static int CauseDungeonFail(GroupEventLuaContext context){ return context.getScriptLibHandler().CauseDungeonFail(context); } public static int CauseDungeonSuccess(GroupEventLuaContext context){ return context.getScriptLibHandler().CauseDungeonSuccess(context); } public static int SetEntityServerGlobalValueByConfigId(GroupEventLuaContext context, int cfgId, String sgvName, int value){ return context.getScriptLibHandler().SetEntityServerGlobalValueByConfigId(context, cfgId, sgvName, value); } public static int SetGroupLogicStateValue(GroupEventLuaContext context, String sgvName, int value){ return context.getScriptLibHandler().SetGroupLogicStateValue(context, sgvName, value); } public static int SetIsAllowUseSkill(GroupEventLuaContext context, int canUse){ return context.getScriptLibHandler().SetIsAllowUseSkill(context, canUse); } public static int KillEntityByConfigId(LuaContext context, Object rawTable) { val table = context.getEngine().getTable(rawTable); val configId = table.optInt("config_id", 0); if (configId == 0){ scriptLogger.error(() -> "[KillEntityByConfigId] Invalid config id " + configId); return INVALID_PARAMETER.getValue(); } val groupId = table.optInt("group_id", 0); val entityTypeValue = table.optInt("entity_type", 0); if(entityTypeValue < 0 || entityTypeValue >= EntityType.values().length){ scriptLogger.error(() -> "[KillEntityByConfigId] Invalid entity type " + entityTypeValue); return INVALID_PARAMETER.getValue(); } val entityType = EntityType.values()[entityTypeValue]; val params = new KillByConfigIdParams(groupId, configId, entityType); if (context instanceof GroupEventLuaContext gContext){ return gContext.getScriptLibHandlerProvider().getScriptLibHandler().KillEntityByConfigId(gContext, params); } else if (context instanceof ControllerLuaContext cContext) { return cContext.getScriptLibHandlerProvider().getGadgetControllerHandler().KillEntityByConfigId(cContext, params); } scriptLogger.error(() -> "[KillEntityByConfigId] unknown context type " + context.getClass().getName()); return NOT_IMPLEMENTED.getValue(); } public static int CreateMonster(GroupEventLuaContext context, Object rawTable){ val table = context.getEngine().getTable(rawTable); return context.getScriptLibHandler().CreateMonster(context, table); } public static int TowerMirrorTeamSetUp(GroupEventLuaContext context, int team, int var1) { return context.getScriptLibHandler().TowerMirrorTeamSetUp(context, team, var1); } public static int CreateGadget(GroupEventLuaContext context, Object rawTable){ val table = context.getEngine().getTable(rawTable); return context.getScriptLibHandler().CreateGadget(context, table); } /** * Spawn a gadget from the caller group at the specified position * @param configId The config id of the gadget in the calling group * @param posTable The position to spawn the gadget at * @param rotTable The rotation of the gadget when spawned */ public static int CreateGadgetByConfigIdByPos(GroupEventLuaContext context, int configId, Object posTable, Object rotTable){ val luaPos = context.getEngine().getTable(posTable); val luaRot = context.getEngine().getTable(rotTable); return context.getScriptLibHandler().CreateGadgetByConfigIdByPos(context, configId, luaToPos(luaPos), luaToPos(luaRot)); } /** * TODO parse the table before passing it to the handler * Spawns a gadget based on the caller groups gadget with cfg id matching the specified id. It also applies additional parameters based on the parameters * @param creationParamsTable parameters to spawn a gadget with */ public static int CreateGadgetByParamTable(GroupEventLuaContext context, Object creationParamsTable){ val table = context.getEngine().getTable(creationParamsTable); return context.getScriptLibHandler().CreateGadget(context, table); } public static int CreateVehicle(GroupEventLuaContext context, int uid, int gadgetId, Object posTable, Object rotTable){ val luaPos = context.getEngine().getTable(posTable); val luaRot = context.getEngine().getTable(rotTable); return context.getScriptLibHandler().CreateVehicle(context, uid, gadgetId, luaToPos(luaPos), luaToPos(luaRot)); } public static int CheckRemainGadgetCountByGroupId(GroupEventLuaContext context, Object rawTable) { val table = context.getEngine().getTable(rawTable); return context.getScriptLibHandler().CheckRemainGadgetCountByGroupId(context, table); } public static int GetGadgetStateByConfigId(GroupEventLuaContext context, int groupId, int configId){ return context.getScriptLibHandler().GetGadgetStateByConfigId(context, groupId, configId); } public static int MarkPlayerAction(GroupEventLuaContext context, int var1, int var2, int var3){ return context.getScriptLibHandler().MarkPlayerAction(context, var1, var2, var3); } public static int AddQuestProgress(GroupEventLuaContext context, String eventNotifyName){ return context.getScriptLibHandler().AddQuestProgress(context, eventNotifyName); } /** * change the state of gadget */ public static int ChangeGroupGadget(GroupEventLuaContext context, Object rawTable) { val table = context.getEngine().getTable(rawTable); return context.getScriptLibHandler().ChangeGroupGadget(context, table); } public static int GetSceneOwnerUid(GroupEventLuaContext context){ return context.getScriptLibHandler().GetSceneOwnerUid(context); } public static int GetHostQuestState(GroupEventLuaContext context, int questId){ return context.getScriptLibHandler().GetHostQuestState(context, questId).getValue(); } public static int GetQuestState(GroupEventLuaContext context, int entityId, int questId){ return context.getScriptLibHandler().GetQuestState(context, entityId, questId).getValue(); } public static int ShowReminder(GroupEventLuaContext context, int reminderId){ return context.getScriptLibHandler().ShowReminder(context, reminderId); } public static int RemoveEntityByConfigId(GroupEventLuaContext context, int groupId, int entityTypeValue, int configId){ val entityType = EntityType.values()[entityTypeValue]; return context.getScriptLibHandler().RemoveEntityByConfigId(context, groupId, entityType, configId); } public static int CreateGroupTimerEvent(GroupEventLuaContext context, int groupID, String source, double time) { return context.getScriptLibHandler().CreateGroupTimerEvent(context, groupID, source, time); } public static int CancelGroupTimerEvent(GroupEventLuaContext context, int groupID, String source) { return context.getScriptLibHandler().CancelGroupTimerEvent(context, groupID, source); } public static int GetGroupSuite(GroupEventLuaContext context, int groupId) { return context.getScriptLibHandler().GetGroupSuite(context, groupId); } public static int SetGroupReplaceable(GroupEventLuaContext context, int groupId, boolean value) { return context.getScriptLibHandler().SetGroupReplaceable(context, groupId, value); } public static Object GetSceneUidList(GroupEventLuaContext context){ val list = context.getScriptLibHandler().GetSceneUidList(context); val result = context.getEngine().createTable(); for(int i = 0; i< list.length; i++){ result.set(Integer.toString(i+1), list[i]); } return result; } public static int GetSeaLampActivityPhase(GroupEventLuaContext context){ return context.getScriptLibHandler().GetSeaLampActivityPhase(context); } public static int GadgetPlayUidOp(GroupEventLuaContext context, int groupId, int gadget_crucible, int var3, int var4, String var5, int var6 ){ return context.getScriptLibHandler().GadgetPlayUidOp(context, groupId, gadget_crucible, var3, var4, var5, var6); } public static long GetServerTime(GroupEventLuaContext context){ return context.getScriptLibHandler().GetServerTime(context); } public static long GetServerTimeByWeek(GroupEventLuaContext context){ return context.getScriptLibHandler().GetServerTimeByWeek(context); } public static int GetCurTriggerCount(GroupEventLuaContext context){ return context.getScriptLibHandler().GetCurTriggerCount(context); } public static int GetChannellerSlabLoopDungeonLimitTime(GroupEventLuaContext context){ return context.getScriptLibHandler().GetChannellerSlabLoopDungeonLimitTime(context); } public static boolean IsPlayerAllAvatarDie(GroupEventLuaContext context, int sceneUid){ return context.getScriptLibHandler().IsPlayerAllAvatarDie(context, sceneUid); } public static int sendShowCommonTipsToClient(GroupEventLuaContext context, String title, String content, int closeTime) { return context.getScriptLibHandler().sendShowCommonTipsToClient(context, title, content, closeTime); } public static int sendCloseCommonTipsToClient(GroupEventLuaContext context){ return context.getScriptLibHandler().sendCloseCommonTipsToClient(context); } public static int updateBundleMarkShowStateByGroupId(GroupEventLuaContext context, int groupId, boolean val2){ return context.getScriptLibHandler().updateBundleMarkShowStateByGroupId(context, groupId, val2); } public static int CreateFatherChallenge(GroupEventLuaContext context, int challengeIndex, int challengeId, int timeLimit, Object conditionTable){ val conditionLuaTable = context.getEngine().getTable(conditionTable); return context.getScriptLibHandler().CreateFatherChallenge(context, challengeIndex, challengeId, timeLimit, conditionLuaTable); } public static int StartFatherChallenge(GroupEventLuaContext context, int challengeIndex){ return context.getScriptLibHandler().StartFatherChallenge(context, challengeIndex); } public static int ModifyFatherChallengeProperty(GroupEventLuaContext context, int challengeId, int propertyTypeIndex, int value){ val propertyType = FatherChallengeProperty.values()[propertyTypeIndex]; return context.getScriptLibHandler().ModifyFatherChallengeProperty(context, challengeId, propertyType, value); } public static int SetChallengeEventMark(GroupEventLuaContext context, int challengeId, int markType){ if(markType < 0 || markType >= ChallengeEventMarkType.values().length){ scriptLogger.error(() -> "[SetChallengeEventMark] Invalid mark type " + markType); return 1; } val markTypeEnum = ChallengeEventMarkType.values()[markType]; return context.getScriptLibHandler().SetChallengeEventMark(context, challengeId, markTypeEnum); } public static int AttachChildChallenge(GroupEventLuaContext context, int fatherChallengeIndex, int childChallengeIndex, int childChallengeId, Object var4Table, Object var5Table, Object var6Table){ val conditionArray = context.getEngine().getTable(var4Table); val var5 = context.getEngine().getTable(var5Table); val conditionTable = context.getEngine().getTable(var6Table); return context.getScriptLibHandler().AttachChildChallenge(context, fatherChallengeIndex, childChallengeIndex, childChallengeId, conditionArray, var5, conditionTable); } public static int CreateEffigyChallengeMonster(GroupEventLuaContext context, int var1, Object var2Table){ val var2 = context.getEngine().getTable(var2Table); return context.getScriptLibHandler().CreateEffigyChallengeMonster(context, var1, var2); } public static int GetEffigyChallengeMonsterLevel(GroupEventLuaContext context){ return context.getScriptLibHandler().GetEffigyChallengeMonsterLevel(context); } public static int AddTeamEntityGlobalFloatValue(GroupEventLuaContext context, Object sceneUidListTable, String var2, int var3){ val sceneUidList = context.getEngine().getTable(sceneUidListTable); return context.getScriptLibHandler().AddTeamEntityGlobalFloatValue(context, sceneUidList, var2, var3); } public static int CreateBlossomChestByGroupId(GroupEventLuaContext context, int groupId, int chestConfigId){ return context.getScriptLibHandler().CreateBlossomChestByGroupId(context, groupId, chestConfigId); } public static int GetBlossomScheduleStateByGroupId(GroupEventLuaContext context, int groupId){ return context.getScriptLibHandler().GetBlossomScheduleStateByGroupId(context, groupId); } public static int SetBlossomScheduleStateByGroupId(GroupEventLuaContext context, int groupId, int state){ return context.getScriptLibHandler().SetBlossomScheduleStateByGroupId(context, groupId, state); } public static int RefreshBlossomGroup(GroupEventLuaContext context, Object rawTable) { val configTable = context.getEngine().getTable(rawTable); return context.getScriptLibHandler().RefreshBlossomGroup(context, configTable); } public static int RefreshBlossomDropRewardByGroupId(GroupEventLuaContext context, int groupId){ return context.getScriptLibHandler().RefreshBlossomDropRewardByGroupId(context, groupId); } public static int AddBlossomScheduleProgressByGroupId(GroupEventLuaContext context, int groupId){ return context.getScriptLibHandler().AddBlossomScheduleProgressByGroupId(context, groupId); } public static int GetBlossomRefreshTypeByGroupId(GroupEventLuaContext context, int groupId){ return context.getScriptLibHandler().GetBlossomRefreshTypeByGroupId(context, groupId); } public static int RefreshHuntingClueGroup(GroupEventLuaContext context){ return context.getScriptLibHandler().RefreshHuntingClueGroup(context); } public static int GetHuntingMonsterExtraSuiteIndexVec(GroupEventLuaContext context){ return context.getScriptLibHandler().GetHuntingMonsterExtraSuiteIndexVec(context); } public static int SetGroupTempValue(GroupEventLuaContext context, String name, int value, Object var3Table) { val var3 = context.getEngine().getTable(var3Table); return context.getScriptLibHandler().SetGroupTempValue(context, name, value, var3); } public static int GetGroupTempValue(GroupEventLuaContext context, String name, Object var2Table) { val var2 = context.getEngine().getTable(var2Table); return context.getScriptLibHandler().GetGroupTempValue(context, name, var2); } public static int FinishExpeditionChallenge(GroupEventLuaContext context){ return context.getScriptLibHandler().FinishExpeditionChallenge(context); } public static int ExpeditionChallengeEnterRegion(GroupEventLuaContext context, boolean var1){ return context.getScriptLibHandler().ExpeditionChallengeEnterRegion(context, var1); } public static int StartSealBattle(GroupEventLuaContext context, int gadgetId, Object battleParamsTable) { val battleParams = context.getEngine().getTable(battleParamsTable); val battleType = battleParams.optInt("battle_type", -1); if(battleType < 0 || battleType >= SealBattleType.values().length){ scriptLogger.error(() -> "[StartSealBattle] Invalid battle type " + battleType); return -1; } val battleTypeEnum = SealBattleType.values()[battleType]; val handlerParams = switch (battleTypeEnum){ case NONE -> parseSealBattleNoneParams(battleParams); case KILL_MONSTER -> parseSealBattleMonsterKillParams(battleParams); case ENERGY_CHARGE -> parseEnergySealBattleTimeParams(battleParams); }; return context.getScriptLibHandler().StartSealBattle(context, gadgetId, handlerParams); } private static SealBattleParams parseSealBattleNoneParams(LuaTable battleParams){ val radius = battleParams.optInt("radius", -1); val inAdd = battleParams.optInt("in_add", -1); val outSub = battleParams.optInt("out_sub", -1); val failTime = battleParams.optInt("fail_time", -1); val maxProgress = battleParams.optInt("max_progress", -1); // TODO check params and maybe return error? return new DefaultSealBattleParams(radius, inAdd, outSub, failTime, maxProgress); } private static SealBattleParams parseSealBattleMonsterKillParams(LuaTable battleParams){ val radius = battleParams.optInt("radius", -1); val killTime = battleParams.optInt("kill_time", -1); val monsterGroupId = battleParams.optInt("monster_group_id", -1); val maxProgress = battleParams.optInt("max_progress", -1); // TODO check params and maybe return error? return new MonsterSealBattleParams(radius, killTime, monsterGroupId, maxProgress); } private static SealBattleParams parseEnergySealBattleTimeParams(LuaTable battleParams){ val radius = battleParams.optInt("radius", -1); val battleTime = battleParams.optInt("battle_time", -1); val monsterGroupId = battleParams.optInt("monster_group_id", -1); val defaultKillCharge = battleParams.optInt("default_kill_charge", -1); val autoCharge = battleParams.optInt("auto_charge", -1); val autoDecline = battleParams.optInt("auto_decline", -1); val maxEnergy = battleParams.optInt("max_energy", -1); // TODO check params and maybe return error? return new EnergySealBattleParams(radius, battleTime, monsterGroupId, defaultKillCharge, autoCharge, autoDecline, maxEnergy); } public static int InitTimeAxis(GroupEventLuaContext context, String var1, Object var2Table, boolean var3){ val var2 = context.getEngine().getTable(var2Table); return context.getScriptLibHandler().InitTimeAxis(context, var1, var2, var3); } public static int EndTimeAxis(GroupEventLuaContext context, String var1){ return context.getScriptLibHandler().EndTimeAxis(context, var1); } public static int SetTeamEntityGlobalFloatValue(GroupEventLuaContext context, Object sceneUidListTable, String var2, int var3){ val sceneUidList = context.getEngine().getTable(sceneUidListTable); return context.getScriptLibHandler().SetTeamEntityGlobalFloatValue(context, sceneUidList, var2, var3); } public static int SetTeamServerGlobalValue(GroupEventLuaContext context, int sceneUid, String var2, int var3){ return context.getScriptLibHandler().SetTeamServerGlobalValue(context, sceneUid, var2, var3); } public static int AddTeamServerGlobalValue(GroupEventLuaContext context, int ownerId, String sgvName, int value){ return context.getScriptLibHandler().AddTeamServerGlobalValue(context, ownerId, sgvName, value); } public static int GetTeamServerGlobalValue(GroupEventLuaContext context, int ownerId, String sgvName, int value){ return context.getScriptLibHandler().GetTeamServerGlobalValue(context, ownerId, sgvName, value); } public static int GetLanternRiteValue(GroupEventLuaContext context){ return context.getScriptLibHandler().GetLanternRiteValue(context); } public static int CreateMonsterFaceAvatar(GroupEventLuaContext context, Object rawTable) { val table = context.getEngine().getTable(rawTable); return context.getScriptLibHandler().CreateMonsterFaceAvatar(context, table); } public static int ChangeToTargetLevelTag(GroupEventLuaContext context, int var1){ return context.getScriptLibHandler().ChangeToTargetLevelTag(context, var1); } public static int AddSceneTag(GroupEventLuaContext context, int sceneId, int sceneTagId){ return context.getScriptLibHandler().AddSceneTag(context, sceneId, sceneTagId); } public static int DelSceneTag(GroupEventLuaContext context, int sceneId, int sceneTagId){ return context.getScriptLibHandler().DelSceneTag(context, sceneId, sceneTagId); } public static boolean CheckSceneTag(GroupEventLuaContext context, int sceneId, int sceneTagId){ return context.getScriptLibHandler().CheckSceneTag(context, sceneId, sceneTagId); } public static int StartHomeGallery(GroupEventLuaContext context, int galleryId, int uid){ return context.getScriptLibHandler().StartHomeGallery(context, galleryId, uid); } public static int StartGallery(GroupEventLuaContext context, int galleryId){ return context.getScriptLibHandler().StartGallery(context, galleryId); } public static int StopGallery(GroupEventLuaContext context, int galleryId, boolean var2){ return context.getScriptLibHandler().StopGallery(context, galleryId, var2); } public static int UpdatePlayerGalleryScore(GroupEventLuaContext context, int galleryId, Object var2Table) { val var2 = context.getEngine().getTable(var2Table); return context.getScriptLibHandler().UpdatePlayerGalleryScore(context, galleryId, var2); } public static int InitGalleryProgressScore(GroupEventLuaContext context, String name, int galleryId, Object progressTable, int scoreUiTypeIndex, int scoreTypeIndex) { val progress = context.getEngine().getTable(progressTable);
if(scoreUiTypeIndex < 0 || scoreUiTypeIndex >= GalleryProgressScoreUIType.values().length){
3
2023-10-07 16:45:54+00:00
8k
PDC2023/project
src/main/java/pdc/project/entity/Coin.java
[ { "identifier": "Universe", "path": "src/main/java/pdc/project/Universe.java", "snippet": "public final class Universe {\r\n\r\n public Player player = new Player(this, 0, 0);\r\n private int score = 0;\r\n public final Main main;\r\n\r\n public Set<Entity> entities = new HashSet<>();\r\n ...
import pdc.project.Universe; import pdc.project.Utils; import pdc.project.Database; import pdc.project.DatabaseDerby;
4,389
package pdc.project.entity; public class Coin extends ImageEntity implements NoPhysicalCollisionEntity { private Database database; public Coin(Universe universe, int x, int y, int width, int height) {
package pdc.project.entity; public class Coin extends ImageEntity implements NoPhysicalCollisionEntity { private Database database; public Coin(Universe universe, int x, int y, int width, int height) {
super(universe, x, y, width, height, Utils.loadImage("/bonus.gif"));
1
2023-10-09 03:01:39+00:00
8k
qmjy/mapbox-offline-server
src/main/java/io/github/qmjy/mapbox/service/AsyncService.java
[ { "identifier": "MapServerDataCenter", "path": "src/main/java/io/github/qmjy/mapbox/MapServerDataCenter.java", "snippet": "@Component\npublic class MapServerDataCenter {\n private static final Logger logger = LoggerFactory.getLogger(MapServerDataCenter.class);\n\n /**\n * 瓦片数据库文件模型\n */\n ...
import io.github.qmjy.mapbox.MapServerDataCenter; import io.github.qmjy.mapbox.config.AppConfig; import io.github.qmjy.mapbox.model.MbtileMergeFile; import io.github.qmjy.mapbox.model.MbtileMergeWrapper; import io.github.qmjy.mapbox.model.MbtilesOfMergeProgress; import io.github.qmjy.mapbox.util.JdbcUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.util.DigestUtils; import org.springframework.util.FileCopyUtils; import org.springframework.util.StringUtils; import java.io.File; import java.io.IOException; import java.sql.PreparedStatement; import java.util.*;
5,809
while (iterator.hasNext()) { Map.Entry<String, MbtileMergeFile> next = iterator.next(); mergeTo(next.getValue(), targetTmpFile); completeCount += next.getValue().getCount(); taskProgress.put(taskId, (int) (completeCount * 100 / totalCount)); iterator.remove(); logger.info("Merged file: {}", next.getValue().getFilePath()); } updateMetadata(wrapper, targetTmpFile); boolean b = targetTmpFile.renameTo(new File(targetFilePath)); System.out.println("重命名文件结果:" + b); taskProgress.put(taskId, 100); } else { taskProgress.put(taskId, -1); } } private void updateMetadata(MbtileMergeWrapper wrapper, File targetTmpFile) { String bounds = wrapper.getMinLon() + "," + wrapper.getMinLat() + "," + wrapper.getMaxLon() + "," + wrapper.getMaxLat(); JdbcTemplate jdbcTemplate = JdbcUtils.getInstance().getJdbcTemplate(appConfig.getDriverClassName(), targetTmpFile.getAbsolutePath()); jdbcTemplate.update("UPDATE metadata SET value = " + wrapper.getMinZoom() + " WHERE name = 'minzoom'"); jdbcTemplate.update("UPDATE metadata SET value = " + wrapper.getMaxZoom() + " WHERE name = 'maxzoom'"); jdbcTemplate.update("UPDATE metadata SET value = '" + bounds + "' WHERE name = 'bounds'"); } private Optional<MbtileMergeWrapper> arrange(List<String> sourceNamePaths) { MbtileMergeWrapper mbtileMergeWrapper = new MbtileMergeWrapper(); for (String item : sourceNamePaths) { if (mbtileMergeWrapper.getLargestFilePath() == null || mbtileMergeWrapper.getLargestFilePath().isBlank() || new File(item).length() > new File(mbtileMergeWrapper.getLargestFilePath()).length()) { mbtileMergeWrapper.setLargestFilePath(item); } MbtileMergeFile value = wrapModel(item); Map<String, String> metadata = value.getMetaMap(); String format = metadata.get("format"); if (mbtileMergeWrapper.getFormat().isBlank()) { mbtileMergeWrapper.setFormat(format); } else { //比较mbtiles文件格式是否一致 if (!mbtileMergeWrapper.getFormat().equals(format)) { logger.error("These Mbtiles files have different formats!"); return Optional.empty(); } } int minZoom = Integer.parseInt(metadata.get("minzoom")); if (mbtileMergeWrapper.getMinZoom() > minZoom) { mbtileMergeWrapper.setMinZoom(minZoom); } int maxZoom = Integer.parseInt(metadata.get("maxzoom")); if (mbtileMergeWrapper.getMaxZoom() < maxZoom) { mbtileMergeWrapper.setMaxZoom(maxZoom); } //Such as: 120.85098267,30.68516394,122.03475952,31.87872381 String[] split = metadata.get("bounds").split(","); if (mbtileMergeWrapper.getMinLat() > Double.parseDouble(split[1])) { mbtileMergeWrapper.setMinLat(Double.parseDouble(split[1])); } if (mbtileMergeWrapper.getMaxLat() < Double.parseDouble(split[3])) { mbtileMergeWrapper.setMaxLat(Double.parseDouble(split[3])); } if (mbtileMergeWrapper.getMinLon() > Double.parseDouble(split[0])) { mbtileMergeWrapper.setMinLon(Double.parseDouble(split[0])); } if (mbtileMergeWrapper.getMaxLon() < Double.parseDouble(split[2])) { mbtileMergeWrapper.setMaxLon(Double.parseDouble(split[2])); } mbtileMergeWrapper.addToTotal(value.getCount()); mbtileMergeWrapper.getNeedMerges().put(item, value); } return Optional.of(mbtileMergeWrapper); } public void mergeTo(MbtileMergeFile mbtile, File targetTmpFile) { JdbcTemplate jdbcTemplate = JdbcUtils.getInstance().getJdbcTemplate(appConfig.getDriverClassName(), targetTmpFile.getAbsolutePath()); int pageSize = 5000; long totalPage = mbtile.getCount() % pageSize == 0 ? mbtile.getCount() / pageSize : mbtile.getCount() / pageSize + 1; for (long currentPage = 0; currentPage < totalPage; currentPage++) { List<Map<String, Object>> dataList = mbtile.getJdbcTemplate().queryForList("SELECT * FROM tiles LIMIT " + pageSize + " OFFSET " + currentPage * pageSize); jdbcTemplate.batchUpdate("INSERT INTO tiles (zoom_level, tile_column, tile_row, tile_data) VALUES (?, ?, ?, ?)", dataList, pageSize, (PreparedStatement ps, Map<String, Object> rowDataMap) -> { ps.setInt(1, (int) rowDataMap.get("zoom_level")); ps.setInt(2, (int) rowDataMap.get("tile_column")); ps.setInt(3, (int) rowDataMap.get("tile_row")); ps.setBytes(4, (byte[]) rowDataMap.get("tile_data")); }); } JdbcUtils.getInstance().releaseJdbcTemplate(jdbcTemplate); } private MbtileMergeFile wrapModel(String item) { JdbcTemplate jdbcTemplate = JdbcUtils.getInstance().getJdbcTemplate(appConfig.getDriverClassName(), item); return new MbtileMergeFile(item, jdbcTemplate); } /** * data format from: <a href="https://osm-boundaries.com/">OSM-Boundaries</a> * * @param dataFolder 行政区划边界数据 */ private void wrapOSMBFile(File dataFolder) { File boundariesFolder = new File(dataFolder, "OSMB"); File[] files = boundariesFolder.listFiles(); if (files != null) { for (File boundary : files) { if (!boundary.isDirectory() && boundary.getName().endsWith(AppConfig.FILE_EXTENSION_NAME_GEOJSON)) { logger.info("Load boundary file: {}", boundary.getName());
/* * Copyright (c) 2023 QMJY. * * 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 io.github.qmjy.mapbox.service; @Service public class AsyncService { private final Logger logger = LoggerFactory.getLogger(AsyncService.class); @Autowired private AppConfig appConfig; /** * taskId:完成百分比 */ private final Map<String, Integer> taskProgress = new HashMap<>(); /** * 每10秒检查一次,数据有更新则刷新 */ @Scheduled(fixedRate = 1000) public void processFixedRate() { //TODO nothing to do yet } /** * 加载数据文件 */ @Async("asyncServiceExecutor") public void asyncTask() { if (StringUtils.hasLength(appConfig.getDataPath())) { File dataFolder = new File(appConfig.getDataPath()); if (dataFolder.isDirectory() && dataFolder.exists()) { wrapTilesFile(dataFolder); wrapFontsFile(dataFolder); wrapOSMBFile(dataFolder); } } } /** * 提交文件合并任务。合并任务失败,则process is -1。 * * @param sourceNamePaths 待合并的文件列表 * @param targetFilePath 目标文件名字 */ @Async("asyncServiceExecutor") public void submit(String taskId, List<String> sourceNamePaths, String targetFilePath) { taskProgress.put(taskId, 0); Optional<MbtileMergeWrapper> wrapperOpt = arrange(sourceNamePaths); if (wrapperOpt.isPresent()) { MbtileMergeWrapper wrapper = wrapperOpt.get(); Map<String, MbtileMergeFile> needMerges = wrapper.getNeedMerges(); long totalCount = wrapper.getTotalCount(); String largestFilePath = wrapper.getLargestFilePath(); long completeCount = 0; //直接拷贝最大的文件,提升合并速度 File targetTmpFile = new File(targetFilePath + ".tmp"); try { FileCopyUtils.copy(new File(largestFilePath), targetTmpFile); completeCount = needMerges.get(largestFilePath).getCount(); taskProgress.put(taskId, (int) (completeCount * 100 / totalCount)); needMerges.remove(largestFilePath); } catch (IOException e) { logger.info("Copy the largest file failed: {}", largestFilePath); taskProgress.put(taskId, -1); return; } Iterator<Map.Entry<String, MbtileMergeFile>> iterator = needMerges.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, MbtileMergeFile> next = iterator.next(); mergeTo(next.getValue(), targetTmpFile); completeCount += next.getValue().getCount(); taskProgress.put(taskId, (int) (completeCount * 100 / totalCount)); iterator.remove(); logger.info("Merged file: {}", next.getValue().getFilePath()); } updateMetadata(wrapper, targetTmpFile); boolean b = targetTmpFile.renameTo(new File(targetFilePath)); System.out.println("重命名文件结果:" + b); taskProgress.put(taskId, 100); } else { taskProgress.put(taskId, -1); } } private void updateMetadata(MbtileMergeWrapper wrapper, File targetTmpFile) { String bounds = wrapper.getMinLon() + "," + wrapper.getMinLat() + "," + wrapper.getMaxLon() + "," + wrapper.getMaxLat(); JdbcTemplate jdbcTemplate = JdbcUtils.getInstance().getJdbcTemplate(appConfig.getDriverClassName(), targetTmpFile.getAbsolutePath()); jdbcTemplate.update("UPDATE metadata SET value = " + wrapper.getMinZoom() + " WHERE name = 'minzoom'"); jdbcTemplate.update("UPDATE metadata SET value = " + wrapper.getMaxZoom() + " WHERE name = 'maxzoom'"); jdbcTemplate.update("UPDATE metadata SET value = '" + bounds + "' WHERE name = 'bounds'"); } private Optional<MbtileMergeWrapper> arrange(List<String> sourceNamePaths) { MbtileMergeWrapper mbtileMergeWrapper = new MbtileMergeWrapper(); for (String item : sourceNamePaths) { if (mbtileMergeWrapper.getLargestFilePath() == null || mbtileMergeWrapper.getLargestFilePath().isBlank() || new File(item).length() > new File(mbtileMergeWrapper.getLargestFilePath()).length()) { mbtileMergeWrapper.setLargestFilePath(item); } MbtileMergeFile value = wrapModel(item); Map<String, String> metadata = value.getMetaMap(); String format = metadata.get("format"); if (mbtileMergeWrapper.getFormat().isBlank()) { mbtileMergeWrapper.setFormat(format); } else { //比较mbtiles文件格式是否一致 if (!mbtileMergeWrapper.getFormat().equals(format)) { logger.error("These Mbtiles files have different formats!"); return Optional.empty(); } } int minZoom = Integer.parseInt(metadata.get("minzoom")); if (mbtileMergeWrapper.getMinZoom() > minZoom) { mbtileMergeWrapper.setMinZoom(minZoom); } int maxZoom = Integer.parseInt(metadata.get("maxzoom")); if (mbtileMergeWrapper.getMaxZoom() < maxZoom) { mbtileMergeWrapper.setMaxZoom(maxZoom); } //Such as: 120.85098267,30.68516394,122.03475952,31.87872381 String[] split = metadata.get("bounds").split(","); if (mbtileMergeWrapper.getMinLat() > Double.parseDouble(split[1])) { mbtileMergeWrapper.setMinLat(Double.parseDouble(split[1])); } if (mbtileMergeWrapper.getMaxLat() < Double.parseDouble(split[3])) { mbtileMergeWrapper.setMaxLat(Double.parseDouble(split[3])); } if (mbtileMergeWrapper.getMinLon() > Double.parseDouble(split[0])) { mbtileMergeWrapper.setMinLon(Double.parseDouble(split[0])); } if (mbtileMergeWrapper.getMaxLon() < Double.parseDouble(split[2])) { mbtileMergeWrapper.setMaxLon(Double.parseDouble(split[2])); } mbtileMergeWrapper.addToTotal(value.getCount()); mbtileMergeWrapper.getNeedMerges().put(item, value); } return Optional.of(mbtileMergeWrapper); } public void mergeTo(MbtileMergeFile mbtile, File targetTmpFile) { JdbcTemplate jdbcTemplate = JdbcUtils.getInstance().getJdbcTemplate(appConfig.getDriverClassName(), targetTmpFile.getAbsolutePath()); int pageSize = 5000; long totalPage = mbtile.getCount() % pageSize == 0 ? mbtile.getCount() / pageSize : mbtile.getCount() / pageSize + 1; for (long currentPage = 0; currentPage < totalPage; currentPage++) { List<Map<String, Object>> dataList = mbtile.getJdbcTemplate().queryForList("SELECT * FROM tiles LIMIT " + pageSize + " OFFSET " + currentPage * pageSize); jdbcTemplate.batchUpdate("INSERT INTO tiles (zoom_level, tile_column, tile_row, tile_data) VALUES (?, ?, ?, ?)", dataList, pageSize, (PreparedStatement ps, Map<String, Object> rowDataMap) -> { ps.setInt(1, (int) rowDataMap.get("zoom_level")); ps.setInt(2, (int) rowDataMap.get("tile_column")); ps.setInt(3, (int) rowDataMap.get("tile_row")); ps.setBytes(4, (byte[]) rowDataMap.get("tile_data")); }); } JdbcUtils.getInstance().releaseJdbcTemplate(jdbcTemplate); } private MbtileMergeFile wrapModel(String item) { JdbcTemplate jdbcTemplate = JdbcUtils.getInstance().getJdbcTemplate(appConfig.getDriverClassName(), item); return new MbtileMergeFile(item, jdbcTemplate); } /** * data format from: <a href="https://osm-boundaries.com/">OSM-Boundaries</a> * * @param dataFolder 行政区划边界数据 */ private void wrapOSMBFile(File dataFolder) { File boundariesFolder = new File(dataFolder, "OSMB"); File[] files = boundariesFolder.listFiles(); if (files != null) { for (File boundary : files) { if (!boundary.isDirectory() && boundary.getName().endsWith(AppConfig.FILE_EXTENSION_NAME_GEOJSON)) { logger.info("Load boundary file: {}", boundary.getName());
MapServerDataCenter.initBoundaryFile(boundary);
0
2023-10-09 03:18:52+00:00
8k
Aywen1/reciteeasily
src/fr/nicolas/main/frames/AFrameMenu.java
[ { "identifier": "ATools", "path": "src/fr/nicolas/main/ATools.java", "snippet": "public class ATools {\n\n\tpublic static String[] matiereList = { \"Histoire\", \"Géographie\", \"Emc\", \"Phys-Chim\", \"Svt\", \"Maths\",\n\t\t\t\"Anglais\", \"Espagnol\" };\n\tpublic static ArrayList<String> elements;\n\...
import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.filechooser.FileNameExtensionFilter; import fr.nicolas.main.ATools; import fr.nicolas.main.components.ABackground; import fr.nicolas.main.components.AButtonImg; import fr.nicolas.main.components.AButtonMatiere; import fr.nicolas.main.components.ALabel; import fr.nicolas.main.components.ATextArea; import fr.nicolas.main.components.ABackground.ABgType; import fr.nicolas.main.panel.APanelTop;
3,757
package fr.nicolas.main.frames; public class AFrameMenu extends JFrame { private JPanel base = new JPanel(); private APanelTop panelTop = new APanelTop(); private ABackground bg = new ABackground(); private AButtonImg buttonOpenFile = new AButtonImg("OpenFile"); private ALabel labelText = new ALabel("Fiches enregistrées", 34); private JFileChooser fileChooser = new JFileChooser(); private JFrame frame = this; private JPanel panel = new JPanel(); private String nameFiche; private String nameFolder; private JPanel fiches = new JPanel(); private CardLayout cardLayout = new CardLayout(); private ArrayList<AButtonMatiere> buttonMatiereList = new ArrayList<AButtonMatiere>(); public AFrameMenu() { this.setTitle("ReciteEasily - Menu"); this.setSize(1050, 600); this.setLocationRelativeTo(null); this.setResizable(false); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setContentPane(base); this.setIconImage(new ImageIcon(getClass().getResource("/img/icone.png")).getImage()); init(); build(); this.setVisible(true); } private void init() { base.setLayout(new BorderLayout()); fiches.setLayout(cardLayout); JScrollPane scrollpanePanel = new JScrollPane(panel); scrollpanePanel.getViewport().setOpaque(false); scrollpanePanel.setOpaque(false); scrollpanePanel.setBorder(null); scrollpanePanel.getVerticalScrollBar().setUnitIncrement(5); FileNameExtensionFilter extensionFileChooser = new FileNameExtensionFilter(".html", "html"); fileChooser.setFileFilter(extensionFileChooser); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setDialogTitle("Charger une fiche"); panel.add(fiches); base.add(bg); bg.add(panelTop); bg.add(buttonOpenFile); bg.add(labelText); bg.add(scrollpanePanel); fiches.setBounds(0, 40, 985, 250); panelTop.setBounds(1, 1, 1200, 90); buttonOpenFile.setBounds(40, 110, 985, 80); labelText.setBounds(40, 210, 400, 40); scrollpanePanel.setBounds(40, 260, 985, 290); buttonOpenFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int fileChooserValue = fileChooser.showOpenDialog(frame); if (fileChooserValue == JFileChooser.APPROVE_OPTION) { new AFrameNewFiche(fileChooser.getSelectedFile(), getLocation()); dispose(); } } }); } private void build() { panel.setLayout(null); panel.setOpaque(false); int locX = 0; File folder = new File("ReciteEasily/Fiches"); String[] listFolders = folder.list(); if (listFolders.length != 0) { for (int i = 0; i < listFolders.length; i++) { nameFolder = listFolders[i]; AButtonMatiere buttonMatiere = new AButtonMatiere(nameFolder); JPanel matierePanel = new JPanel(); matierePanel.setLayout(null); matierePanel.setBackground(new Color(30, 30, 30)); buttonMatiere.setBounds(locX, 0, 110, 30); buttonMatiereList.add(buttonMatiere); if (i == 0) { buttonMatiere.setSelected(true); } panel.add(buttonMatiere); fiches.add(matierePanel, nameFolder); buttonMatiere.addActionListener(new ActionListener() { private String name = nameFolder; public void actionPerformed(ActionEvent e) { setMatiereSelected(buttonMatiere); cardLayout.show(fiches, name); } }); locX += 120; // Charger les fiches int locY = 0; File file = new File("ReciteEasily/Fiches/" + nameFolder); String[] listFiles = file.list(); if (listFiles.length != 0) { for (int i2 = 0; i2 < listFiles.length; i2++) { nameFiche = listFiles[i2].replace(".txt", "");
package fr.nicolas.main.frames; public class AFrameMenu extends JFrame { private JPanel base = new JPanel(); private APanelTop panelTop = new APanelTop(); private ABackground bg = new ABackground(); private AButtonImg buttonOpenFile = new AButtonImg("OpenFile"); private ALabel labelText = new ALabel("Fiches enregistrées", 34); private JFileChooser fileChooser = new JFileChooser(); private JFrame frame = this; private JPanel panel = new JPanel(); private String nameFiche; private String nameFolder; private JPanel fiches = new JPanel(); private CardLayout cardLayout = new CardLayout(); private ArrayList<AButtonMatiere> buttonMatiereList = new ArrayList<AButtonMatiere>(); public AFrameMenu() { this.setTitle("ReciteEasily - Menu"); this.setSize(1050, 600); this.setLocationRelativeTo(null); this.setResizable(false); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setContentPane(base); this.setIconImage(new ImageIcon(getClass().getResource("/img/icone.png")).getImage()); init(); build(); this.setVisible(true); } private void init() { base.setLayout(new BorderLayout()); fiches.setLayout(cardLayout); JScrollPane scrollpanePanel = new JScrollPane(panel); scrollpanePanel.getViewport().setOpaque(false); scrollpanePanel.setOpaque(false); scrollpanePanel.setBorder(null); scrollpanePanel.getVerticalScrollBar().setUnitIncrement(5); FileNameExtensionFilter extensionFileChooser = new FileNameExtensionFilter(".html", "html"); fileChooser.setFileFilter(extensionFileChooser); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setDialogTitle("Charger une fiche"); panel.add(fiches); base.add(bg); bg.add(panelTop); bg.add(buttonOpenFile); bg.add(labelText); bg.add(scrollpanePanel); fiches.setBounds(0, 40, 985, 250); panelTop.setBounds(1, 1, 1200, 90); buttonOpenFile.setBounds(40, 110, 985, 80); labelText.setBounds(40, 210, 400, 40); scrollpanePanel.setBounds(40, 260, 985, 290); buttonOpenFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int fileChooserValue = fileChooser.showOpenDialog(frame); if (fileChooserValue == JFileChooser.APPROVE_OPTION) { new AFrameNewFiche(fileChooser.getSelectedFile(), getLocation()); dispose(); } } }); } private void build() { panel.setLayout(null); panel.setOpaque(false); int locX = 0; File folder = new File("ReciteEasily/Fiches"); String[] listFolders = folder.list(); if (listFolders.length != 0) { for (int i = 0; i < listFolders.length; i++) { nameFolder = listFolders[i]; AButtonMatiere buttonMatiere = new AButtonMatiere(nameFolder); JPanel matierePanel = new JPanel(); matierePanel.setLayout(null); matierePanel.setBackground(new Color(30, 30, 30)); buttonMatiere.setBounds(locX, 0, 110, 30); buttonMatiereList.add(buttonMatiere); if (i == 0) { buttonMatiere.setSelected(true); } panel.add(buttonMatiere); fiches.add(matierePanel, nameFolder); buttonMatiere.addActionListener(new ActionListener() { private String name = nameFolder; public void actionPerformed(ActionEvent e) { setMatiereSelected(buttonMatiere); cardLayout.show(fiches, name); } }); locX += 120; // Charger les fiches int locY = 0; File file = new File("ReciteEasily/Fiches/" + nameFolder); String[] listFiles = file.list(); if (listFiles.length != 0) { for (int i2 = 0; i2 < listFiles.length; i2++) { nameFiche = listFiles[i2].replace(".txt", "");
ATextArea textArea = new ATextArea(getTextFile(ATools.readFile(nameFolder, nameFiche)), 22);
0
2023-10-13 13:17:51+00:00
8k
rgrosa/comes-e-bebes
src/main/java/br/com/project/domain/service/imp/UserServiceImpl.java
[ { "identifier": "CreateUserDTO", "path": "src/main/java/br/com/project/domain/dto/CreateUserDTO.java", "snippet": "public class CreateUserDTO {\n\n private String username;\n private String password;\n private String address;\n private String registrationDocument;\n private RestaurantDTO ...
import br.com.project.domain.dto.CreateUserDTO; import br.com.project.domain.dto.LoggedUserDTO; import br.com.project.domain.dto.LoggedUserDetailsDTO; import br.com.project.domain.dto.UserLoginDTO; import br.com.project.domain.entity.RestaurantEntity; import br.com.project.domain.entity.UserEntity; import br.com.project.domain.repository.RestaurantRepository; import br.com.project.infrasctructure.exception.PasswordException; import br.com.project.infrasctructure.exception.ResourceNotFoundException; import br.com.project.domain.repository.UserRepository; import br.com.project.domain.service.UserService; import br.com.project.infrasctructure.util.auth.CryptPassword; import br.com.project.infrasctructure.util.auth.JwtTokenUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service; import java.util.Optional;
4,303
package br.com.project.domain.service.imp; @Service public class UserServiceImpl implements UserService { @Autowired UserRepository userRepository; @Autowired RestaurantRepository restaurantRepository; @Autowired CryptPassword cryptPassword; @Autowired JwtTokenUtil jwtTokenUtil; private final static int C_CLIENT_ID = 1; private final static int C_OWNER_ID = 2; @Override public LoggedUserDTO postLogin(UserLoginDTO userLoginDto) throws PasswordException { try { return generateUserLogin(userLoginDto); } catch (Exception ex) { throw new PasswordException(ex.getMessage()); } } @Override
package br.com.project.domain.service.imp; @Service public class UserServiceImpl implements UserService { @Autowired UserRepository userRepository; @Autowired RestaurantRepository restaurantRepository; @Autowired CryptPassword cryptPassword; @Autowired JwtTokenUtil jwtTokenUtil; private final static int C_CLIENT_ID = 1; private final static int C_OWNER_ID = 2; @Override public LoggedUserDTO postLogin(UserLoginDTO userLoginDto) throws PasswordException { try { return generateUserLogin(userLoginDto); } catch (Exception ex) { throw new PasswordException(ex.getMessage()); } } @Override
public UserDetails loadUserByUsername(String username) throws ResourceNotFoundException {
8
2023-10-10 23:22:15+00:00
8k
Stachelbeere1248/zombies-utils
src/main/java/com/github/stachelbeere1248/zombiesutils/mixin/MixinNetHandlerPlayClient.java
[ { "identifier": "ZombiesUtils", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/ZombiesUtils.java", "snippet": "@Mod(modid = \"zombiesutils\", useMetadata = true, clientSideOnly = true, guiFactory = \"com.github.stachelbeere1248.zombiesutils.config.GuiFactory\")\npublic class ZombiesUtil...
import com.github.stachelbeere1248.zombiesutils.ZombiesUtils; import com.github.stachelbeere1248.zombiesutils.timer.Timer; import com.github.stachelbeere1248.zombiesutils.utils.LanguageSupport; import com.github.stachelbeere1248.zombiesutils.utils.Scoreboard; import net.minecraft.client.Minecraft; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.network.play.server.S29PacketSoundEffect; import net.minecraft.network.play.server.S45PacketTitle; import net.minecraft.util.ChatComponentText; import org.jetbrains.annotations.NotNull; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
3,623
package com.github.stachelbeere1248.zombiesutils.mixin; @Mixin(NetHandlerPlayClient.class) public class MixinNetHandlerPlayClient { @Unique private boolean zombies_utils$alienUfoOpened; @Inject(method = "handleSoundEffect", at = @At(value = "HEAD")) private void handleSound(S29PacketSoundEffect packetIn, CallbackInfo ci) { zombies_utils$handleSound(packetIn); } @Inject(method = "handleTitle", at = @At(value = "HEAD")) private void handleTitle(S45PacketTitle packetIn, CallbackInfo ci) { zombies_utils$handleTitle(packetIn); } @Unique private void zombies_utils$handleSound(@NotNull S29PacketSoundEffect packet) { if (Scoreboard.isNotZombies()) return; final String soundEffect = packet.getSoundName(); if (!( soundEffect.equals("mob.wither.spawn") || (soundEffect.equals("mob.guardian.curse") && !zombies_utils$alienUfoOpened) )) return; zombies_utils$alienUfoOpened = soundEffect.equals("mob.guardian.curse"); try {
package com.github.stachelbeere1248.zombiesutils.mixin; @Mixin(NetHandlerPlayClient.class) public class MixinNetHandlerPlayClient { @Unique private boolean zombies_utils$alienUfoOpened; @Inject(method = "handleSoundEffect", at = @At(value = "HEAD")) private void handleSound(S29PacketSoundEffect packetIn, CallbackInfo ci) { zombies_utils$handleSound(packetIn); } @Inject(method = "handleTitle", at = @At(value = "HEAD")) private void handleTitle(S45PacketTitle packetIn, CallbackInfo ci) { zombies_utils$handleTitle(packetIn); } @Unique private void zombies_utils$handleSound(@NotNull S29PacketSoundEffect packet) { if (Scoreboard.isNotZombies()) return; final String soundEffect = packet.getSoundName(); if (!( soundEffect.equals("mob.wither.spawn") || (soundEffect.equals("mob.guardian.curse") && !zombies_utils$alienUfoOpened) )) return; zombies_utils$alienUfoOpened = soundEffect.equals("mob.guardian.curse"); try {
if (Timer.getInstance().isPresent()) {
1
2023-10-11 01:30:28+00:00
8k
gustavofg1pontes/Tickets-API
infrastructure/src/main/java/br/com/ifsp/tickets/api/infra/config/usecases/GuestUseCaseConfig.java
[ { "identifier": "CreateGuestUseCase", "path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/create/CreateGuestUseCase.java", "snippet": "public abstract class CreateGuestUseCase extends UseCase<CreateGuestCommand, CreateGuestOutput>{\n}" }, { "identifier": "DefaultCreateGuestUseCa...
import br.com.ifsp.tickets.api.app.guest.create.CreateGuestUseCase; import br.com.ifsp.tickets.api.app.guest.create.DefaultCreateGuestUseCase; import br.com.ifsp.tickets.api.app.guest.delete.event.DefaultDeleteGuestsByEventUseCase; import br.com.ifsp.tickets.api.app.guest.delete.event.DeleteGuestsByEventUseCase; import br.com.ifsp.tickets.api.app.guest.delete.eventIdAndName.DefaultDeleteGuestByEventAndNameUseCase; import br.com.ifsp.tickets.api.app.guest.delete.eventIdAndName.DeleteGuestByEventAndNameUseCase; import br.com.ifsp.tickets.api.app.guest.delete.id.DefaultDeleteGuestUseCase; import br.com.ifsp.tickets.api.app.guest.delete.id.DeleteGuestUseCase; import br.com.ifsp.tickets.api.app.guest.retrieve.get.DefaultGetGuestByIdUseCase; import br.com.ifsp.tickets.api.app.guest.retrieve.get.GetGuestByIdUseCase; import br.com.ifsp.tickets.api.app.guest.retrieve.list.DefaultListGuestsUseCase; import br.com.ifsp.tickets.api.app.guest.retrieve.list.ListGuestsUseCase; import br.com.ifsp.tickets.api.app.guest.toggle.blocked.DefaultToggleBlockedGuestUseCase; import br.com.ifsp.tickets.api.app.guest.toggle.blocked.ToggleBlockedGuestUseCase; import br.com.ifsp.tickets.api.app.guest.toggle.enter.DefaultToggleEnterGuestUseCase; import br.com.ifsp.tickets.api.app.guest.toggle.enter.ToggleEnterGuestUseCase; import br.com.ifsp.tickets.api.app.guest.toggle.left.DefaultToggleLeftGuestUseCase; import br.com.ifsp.tickets.api.app.guest.toggle.left.ToggleLeftGuestUseCase; import br.com.ifsp.tickets.api.app.guest.update.DefaultUpdateGuestUseCase; import br.com.ifsp.tickets.api.app.guest.update.UpdateGuestUseCase; import br.com.ifsp.tickets.api.app.guest.validate.DefaultValidateGuestQRUseCase; import br.com.ifsp.tickets.api.app.guest.validate.ValidateGuestQRUseCase; import br.com.ifsp.tickets.api.domain.event.gateway.EventGateway; import br.com.ifsp.tickets.api.domain.guest.gateway.GuestGateway; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
4,866
package br.com.ifsp.tickets.api.infra.config.usecases; @Configuration @RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class GuestUseCaseConfig { private final GuestGateway guestGateway; private final EventGateway eventGateway; @Bean public CreateGuestUseCase createGuestUseCase() { return new DefaultCreateGuestUseCase(guestGateway, eventGateway); } @Bean public GetGuestByIdUseCase getGuestByIdUseCase() { return new DefaultGetGuestByIdUseCase(guestGateway); } @Bean public UpdateGuestUseCase updateGuestUseCase() { return new DefaultUpdateGuestUseCase(guestGateway); } @Bean public ListGuestsUseCase listGuestsUseCase() { return new DefaultListGuestsUseCase(guestGateway); } @Bean public DeleteGuestUseCase deleteGuestUseCase() { return new DefaultDeleteGuestUseCase(guestGateway, eventGateway); } @Bean
package br.com.ifsp.tickets.api.infra.config.usecases; @Configuration @RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class GuestUseCaseConfig { private final GuestGateway guestGateway; private final EventGateway eventGateway; @Bean public CreateGuestUseCase createGuestUseCase() { return new DefaultCreateGuestUseCase(guestGateway, eventGateway); } @Bean public GetGuestByIdUseCase getGuestByIdUseCase() { return new DefaultGetGuestByIdUseCase(guestGateway); } @Bean public UpdateGuestUseCase updateGuestUseCase() { return new DefaultUpdateGuestUseCase(guestGateway); } @Bean public ListGuestsUseCase listGuestsUseCase() { return new DefaultListGuestsUseCase(guestGateway); } @Bean public DeleteGuestUseCase deleteGuestUseCase() { return new DefaultDeleteGuestUseCase(guestGateway, eventGateway); } @Bean
public DeleteGuestByEventAndNameUseCase deleteGuestByEventAndNameUseCase() {
5
2023-10-11 00:05:05+00:00
8k
DeeChael/dcg
src/main/java/net/deechael/dcg/source/structure/execution/DyExecutable.java
[ { "identifier": "DyTranstringable", "path": "src/main/java/net/deechael/dcg/DyTranstringable.java", "snippet": "public interface DyTranstringable {\n\n String toCompilableString();\n\n}" }, { "identifier": "DyLabel", "path": "src/main/java/net/deechael/dcg/source/structure/DyLabel.java", ...
import net.deechael.dcg.DyTranstringable; import net.deechael.dcg.source.structure.DyLabel; import net.deechael.dcg.source.structure.DyStructure; import net.deechael.dcg.source.structure.invokation.DyInvokable; import net.deechael.dcg.source.structure.invokation.Invokation; import net.deechael.dcg.source.structure.invokation.Invoker; import net.deechael.dcg.source.structure.invokation.internal.*; import net.deechael.dcg.source.structure.selection.IfElseSelection; import net.deechael.dcg.source.structure.selection.SwitchCaseSelection; import net.deechael.dcg.source.structure.selection.TryCatchSelection; import net.deechael.dcg.source.type.DyType; import net.deechael.dcg.source.variable.Variable; import net.deechael.dcg.source.variable.internal.InvokeMethodVariable; import net.deechael.dcg.source.variable.internal.ReferringVariable; import net.deechael.dcg.util.Preconditions; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer;
4,990
package net.deechael.dcg.source.structure.execution; public abstract class DyExecutable implements DyInvokable, DyStructure, DyTranstringable { private final List<Invokation> invokations = new ArrayList<>(); @NotNull public CreateVariableInvokation createVariable(@NotNull DyType type, @NotNull String name, @NotNull Variable variable) { CreateVariableInvokation invokation = new CreateVariableInvokation(type, name, variable, new ReferringVariable(this, type, name)); this.invokations.add(invokation); return invokation; } public void modifyVariable(Variable referring, @Nullable Variable newValue) { Preconditions.domain(this, referring.getDomain()); if (newValue != null) Preconditions.domain(this, newValue.getDomain()); ModifyVariableInvokation invokation = new ModifyVariableInvokation(referring, newValue != null ? newValue : Variable.nullVariable()); this.invokations.add(invokation); } public DyLabel createLabel(String name) { this.invokations.add(new CreateLabelInvokation(name)); return new DyLabel(name); }
package net.deechael.dcg.source.structure.execution; public abstract class DyExecutable implements DyInvokable, DyStructure, DyTranstringable { private final List<Invokation> invokations = new ArrayList<>(); @NotNull public CreateVariableInvokation createVariable(@NotNull DyType type, @NotNull String name, @NotNull Variable variable) { CreateVariableInvokation invokation = new CreateVariableInvokation(type, name, variable, new ReferringVariable(this, type, name)); this.invokations.add(invokation); return invokation; } public void modifyVariable(Variable referring, @Nullable Variable newValue) { Preconditions.domain(this, referring.getDomain()); if (newValue != null) Preconditions.domain(this, newValue.getDomain()); ModifyVariableInvokation invokation = new ModifyVariableInvokation(referring, newValue != null ? newValue : Variable.nullVariable()); this.invokations.add(invokation); } public DyLabel createLabel(String name) { this.invokations.add(new CreateLabelInvokation(name)); return new DyLabel(name); }
public InvokeMethodVariable invoke(@Nullable Invoker invoker, @NotNull String methodName, Variable... parameters) {
5
2023-10-15 13:45:11+00:00
8k
giteecode/supermarket2Public
src/main/java/com/ruoyi/project/system/checkout/controller/CheckOutController.java
[ { "identifier": "ShiroUtils", "path": "src/main/java/com/ruoyi/common/utils/security/ShiroUtils.java", "snippet": "public class ShiroUtils\n{\n public static Subject getSubject()\n {\n return SecurityUtils.getSubject();\n }\n\n public static Session getSession()\n {\n return...
import com.ruoyi.common.utils.security.ShiroUtils; import com.ruoyi.framework.web.controller.BaseController; import com.ruoyi.framework.web.domain.AjaxResult; import com.ruoyi.framework.web.page.TableDataInfo; import com.ruoyi.project.system.checkout.domain.AddTempBillItemDto; import com.ruoyi.project.system.checkout.service.CheckoutService; import com.ruoyi.project.system.user.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody;
5,848
package com.ruoyi.project.system.checkout.controller; @Controller @RequestMapping("/system/checkout") public class CheckOutController extends BaseController { private String prefix = "system/checkout"; @Autowired private CheckoutService checkoutService; // @RequiresPermissions("system:checkout:view") @GetMapping() public String product() { return prefix + "/checkout"; } /** * 新增保存商品分类 */ @PostMapping("/tmp-bill-item/add") @ResponseBody public AjaxResult saveTempBillItem(AddTempBillItemDto addTempBillItemDto) { User currentUser = ShiroUtils.getSysUser(); Long userId = currentUser.getUserId(); boolean success = checkoutService.saveTempBillItem(userId, addTempBillItemDto); if (success) { return AjaxResult.success("添加成功"); } else { return AjaxResult.error("找不到商品,请检查商品编号是否正确"); } } /** * 获取数据集合 */ @PostMapping("/tmp-bill-item") @ResponseBody
package com.ruoyi.project.system.checkout.controller; @Controller @RequestMapping("/system/checkout") public class CheckOutController extends BaseController { private String prefix = "system/checkout"; @Autowired private CheckoutService checkoutService; // @RequiresPermissions("system:checkout:view") @GetMapping() public String product() { return prefix + "/checkout"; } /** * 新增保存商品分类 */ @PostMapping("/tmp-bill-item/add") @ResponseBody public AjaxResult saveTempBillItem(AddTempBillItemDto addTempBillItemDto) { User currentUser = ShiroUtils.getSysUser(); Long userId = currentUser.getUserId(); boolean success = checkoutService.saveTempBillItem(userId, addTempBillItemDto); if (success) { return AjaxResult.success("添加成功"); } else { return AjaxResult.error("找不到商品,请检查商品编号是否正确"); } } /** * 获取数据集合 */ @PostMapping("/tmp-bill-item") @ResponseBody
public TableDataInfo getTempBillItem() {
3
2023-10-14 02:27:47+00:00
8k
davidsaltacc/shadowclient
src/main/java/net/shadowclient/main/module/modules/render/Trajectories.java
[ { "identifier": "Event", "path": "src/main/java/net/shadowclient/main/event/Event.java", "snippet": "public abstract class Event {\n public boolean cancelled = false;\n public void cancel() {\n this.cancelled = true;\n }\n public void uncancel() {\n this.cancelled = false;\n ...
import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.render.*; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.Entity; import net.minecraft.entity.projectile.ProjectileUtil; import net.minecraft.item.*; import net.minecraft.util.Hand; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.hit.EntityHitResult; import net.minecraft.util.hit.HitResult; import net.minecraft.util.math.Box; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.shadowclient.main.annotations.EventListener; import net.shadowclient.main.annotations.SearchTags; import net.shadowclient.main.event.Event; import net.shadowclient.main.event.events.Render3DEvent; import net.shadowclient.main.module.Module; import net.shadowclient.main.module.ModuleCategory; import net.shadowclient.main.util.PlayerUtils; import net.shadowclient.main.util.RenderUtils; import net.shadowclient.main.util.WorldUtils; import org.joml.Matrix4f; import org.lwjgl.opengl.GL11; import java.util.ArrayList; import java.util.function.Predicate;
4,249
package net.shadowclient.main.module.modules.render; @EventListener({Render3DEvent.class}) @SearchTags({"trajectories", "bow aim laser", "aim assist"}) public class Trajectories extends Module { public Trajectories() { super("trajectories", "Trajectories", "Draws a line where projectiles will go.", ModuleCategory.RENDER); } public ArrayList<Vec3d> trajPath; public HitResult.Type trajHit; public final Box endBox = new Box(0, 0, 0, 1, 1, 1); @Override public void onEvent(Event event) { Render3DEvent evt = (Render3DEvent) event; evt.matrices.push(); getTrajectory(evt.tickDelta); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDepthMask(false); drawLine(evt.matrices, trajPath); if (!trajPath.isEmpty()) { drawEnd(evt.matrices, trajPath.get(trajPath.size() - 1)); } RenderSystem.setShaderColor(1, 1, 1, 1); GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glDepthMask(true); evt.matrices.pop(); } public void getTrajectory(float delta) { trajHit = HitResult.Type.MISS; trajPath = new ArrayList<>(); Item item = mc.player.getMainHandStack().getItem(); // todo offhand too if (!(item instanceof RangedWeaponItem || item instanceof SnowballItem || item instanceof EggItem || item instanceof EnderPearlItem || item instanceof ThrowablePotionItem || item instanceof FishingRodItem || item instanceof TridentItem)) { return; } double power; if (!(item instanceof RangedWeaponItem)) { power = 1.5; } else { power = (72000 - mc.player.getItemUseTimeLeft()) / 20F; power = power * power + power * 2F; if (power > 3 || power <= 0.3F) { power = 3; } } double gravity; if (item instanceof RangedWeaponItem) { gravity = 0.05; } else if (item instanceof ThrowablePotionItem) { gravity = 0.4; } else if (item instanceof FishingRodItem) { gravity = 0.15; } else if (item instanceof TridentItem) { gravity = 0.015; } else { gravity = 0.03; } double yaw = Math.toRadians(mc.player.getYaw()); double pitch = Math.toRadians(mc.player.getPitch()); Vec3d arrawPos = new Vec3d(MathHelper.lerp(delta, mc.player.lastRenderX, mc.player.getX()), MathHelper.lerp(delta, mc.player.lastRenderY, mc.player.getY()), MathHelper.lerp(delta, mc.player.lastRenderZ, mc.player.getZ())).add(PlayerUtils.getHandOffset(Hand.MAIN_HAND, yaw)); double cospitch = Math.cos(pitch); Vec3d arrowMotion = new Vec3d(-Math.sin(yaw) * cospitch, -Math.sin(pitch), Math.cos(yaw) * cospitch).normalize().multiply(power); for (int i = 0; i < 1000; i++) { trajPath.add(arrawPos); arrawPos = arrawPos.add(arrowMotion.multiply(0.1)); arrowMotion = arrowMotion.multiply(0.999); arrowMotion = arrowMotion.add(0, -gravity * 0.1, 0); Vec3d lastPos = trajPath.size() > 1 ? trajPath.get(trajPath.size() - 2) : mc.player.getEyePos();
package net.shadowclient.main.module.modules.render; @EventListener({Render3DEvent.class}) @SearchTags({"trajectories", "bow aim laser", "aim assist"}) public class Trajectories extends Module { public Trajectories() { super("trajectories", "Trajectories", "Draws a line where projectiles will go.", ModuleCategory.RENDER); } public ArrayList<Vec3d> trajPath; public HitResult.Type trajHit; public final Box endBox = new Box(0, 0, 0, 1, 1, 1); @Override public void onEvent(Event event) { Render3DEvent evt = (Render3DEvent) event; evt.matrices.push(); getTrajectory(evt.tickDelta); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDepthMask(false); drawLine(evt.matrices, trajPath); if (!trajPath.isEmpty()) { drawEnd(evt.matrices, trajPath.get(trajPath.size() - 1)); } RenderSystem.setShaderColor(1, 1, 1, 1); GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glDepthMask(true); evt.matrices.pop(); } public void getTrajectory(float delta) { trajHit = HitResult.Type.MISS; trajPath = new ArrayList<>(); Item item = mc.player.getMainHandStack().getItem(); // todo offhand too if (!(item instanceof RangedWeaponItem || item instanceof SnowballItem || item instanceof EggItem || item instanceof EnderPearlItem || item instanceof ThrowablePotionItem || item instanceof FishingRodItem || item instanceof TridentItem)) { return; } double power; if (!(item instanceof RangedWeaponItem)) { power = 1.5; } else { power = (72000 - mc.player.getItemUseTimeLeft()) / 20F; power = power * power + power * 2F; if (power > 3 || power <= 0.3F) { power = 3; } } double gravity; if (item instanceof RangedWeaponItem) { gravity = 0.05; } else if (item instanceof ThrowablePotionItem) { gravity = 0.4; } else if (item instanceof FishingRodItem) { gravity = 0.15; } else if (item instanceof TridentItem) { gravity = 0.015; } else { gravity = 0.03; } double yaw = Math.toRadians(mc.player.getYaw()); double pitch = Math.toRadians(mc.player.getPitch()); Vec3d arrawPos = new Vec3d(MathHelper.lerp(delta, mc.player.lastRenderX, mc.player.getX()), MathHelper.lerp(delta, mc.player.lastRenderY, mc.player.getY()), MathHelper.lerp(delta, mc.player.lastRenderZ, mc.player.getZ())).add(PlayerUtils.getHandOffset(Hand.MAIN_HAND, yaw)); double cospitch = Math.cos(pitch); Vec3d arrowMotion = new Vec3d(-Math.sin(yaw) * cospitch, -Math.sin(pitch), Math.cos(yaw) * cospitch).normalize().multiply(power); for (int i = 0; i < 1000; i++) { trajPath.add(arrawPos); arrawPos = arrawPos.add(arrowMotion.multiply(0.1)); arrowMotion = arrowMotion.multiply(0.999); arrowMotion = arrowMotion.add(0, -gravity * 0.1, 0); Vec3d lastPos = trajPath.size() > 1 ? trajPath.get(trajPath.size() - 2) : mc.player.getEyePos();
BlockHitResult result = WorldUtils.raycast(lastPos, arrawPos);
6
2023-10-07 06:55:12+00:00
8k
MRkto/MappetVoice
src/main/java/mrkto/mvoice/client/ClientEventHandler.java
[ { "identifier": "MappetVoice", "path": "src/main/java/mrkto/mvoice/MappetVoice.java", "snippet": "@Mod.EventBusSubscriber\n@Mod(\n modid = MappetVoice.MOD_ID,\n name = MappetVoice.NAME,\n version = MappetVoice.VERSION\n)\npublic class MappetVoice {\n\n public static final String ...
import mrkto.mvoice.MappetVoice; import mrkto.mvoice.api.Events.OnEngineRegistry; import mrkto.mvoice.capability.Profile; import mrkto.mvoice.client.audio.AudioEngineLoader; import mrkto.mvoice.client.audio.better.CoolAudioSystem; import mrkto.mvoice.client.audio.DefaultAudioSystemManager; import mrkto.mvoice.network.Dispatcher; import mrkto.mvoice.utils.other.UnableInitiateEngineException; import mrkto.mvoice.utils.other.mclib.MVIcons; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
4,697
package mrkto.mvoice.client; @SideOnly(Side.CLIENT) public class ClientEventHandler { private static int i = 0; public boolean canSpeak = true; @SubscribeEvent public void onClientTick(TickEvent.ClientTickEvent event) {
package mrkto.mvoice.client; @SideOnly(Side.CLIENT) public class ClientEventHandler { private static int i = 0; public boolean canSpeak = true; @SubscribeEvent public void onClientTick(TickEvent.ClientTickEvent event) {
Profile profile = Profile.get(Minecraft.getMinecraft().player);
2
2023-10-14 19:20:12+00:00
8k
batmatt/cli-rpg-java
src/com/clirpg/locations/Arena.java
[ { "identifier": "Round", "path": "src/com/clirpg/game/Round.java", "snippet": "public class Round {\n private int level;\n private Player player;\n private Soldier roundSoldierArray[];\n private int currentSoldierNumber = 0;\n private Monster roundMonsterArray[];\n private int currentM...
import java.util.InputMismatchException; import java.util.Scanner; import src.com.clirpg.game.Round; import src.com.clirpg.characters.Civillian; import src.com.clirpg.characters.Player; import src.com.utils.ConsoleColors;
5,045
package src.com.clirpg.locations; public class Arena implements Visit{ private Civillian trainer;
package src.com.clirpg.locations; public class Arena implements Visit{ private Civillian trainer;
private Player player;
2
2023-10-14 15:38:50+00:00
8k
lukas-mb/ABAP-SQL-Beautifier
ABAP SQL Beautifier/src/com/abap/sql/beautifier/statement/AbapSql.java
[ { "identifier": "Abap", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/Abap.java", "snippet": "public final class Abap {\n\n\t// class to store keywords and stuff\n\t// --> easier to find use with 'where used list'\n\n\tpublic static final List<String> JOINS = Arrays.asList(\"INNER JOIN\", \"J...
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.abap.sql.beautifier.Abap; import com.abap.sql.beautifier.Activator; import com.abap.sql.beautifier.preferences.PreferenceConstants; import com.abap.sql.beautifier.statement.parts.Into; import com.abap.sql.beautifier.utility.Utility;
3,637
package com.abap.sql.beautifier.statement; public class AbapSql { private Map<String, AbapSqlPart> parts; private List<String> order; private boolean isOldSyntax = true; private List<String> comments = new ArrayList<String>(); private String startWhite = ""; public AbapSql(String sql, int diff) { startWhite = Utility.getWhiteChars(diff); parts = new HashMap<String, AbapSqlPart>(); // get order isOldSyntax = checkIfOldSyntax(sql); if (isOldSyntax) { setOrder(buildOrder(PreferenceConstants.ORDER_OLD_SYNTAX)); } else { setOrder(buildOrder(PreferenceConstants.ORDER_NEW_SYNTAX)); } appendSecWords(); sql = filterComments(sql); sql = Utility.cleanString(sql); setFromString(sql); resetFormat(); } private void appendSecWords() { // append keywords, which are introducing the same part int index; // INTO ~ APPENDING index = order.indexOf(Abap.INTO); if (index != -1) { order.add(index, Abap.APPENDING); } // UPTO ~ OFFSET index = order.indexOf(Abap.UPTO); if (index != -1) { order.add(index, Abap.OFFSET); } // INTO ~ INTO CORRESPONDING FIELDS OF index = order.indexOf(Abap.INTO); if (index != -1) { order.add(index, Abap.INTO_COR_FI_OF); } } private String filterComments(String sql) { String returnSql = ""; String asterisks = "*"; String apostrophes = "\""; if (sql.contains(asterisks) || sql.contains(apostrophes)) { List<String> lines = Arrays.asList(sql.split("\r\n")); for (String line : lines) { if (line.contains(asterisks) || line.contains(apostrophes)) { int pos = line.indexOf(asterisks); // check if asterisks is first char --> full line comment if (pos == 0) { comments.add(line.trim()); continue; } // asterisks was not a comment --> check apostrophes pos = line.indexOf(apostrophes); if (pos == -1) { returnSql = returnSql + line + "\r\n"; } else { comments.add(line.substring(pos).trim()); returnSql = returnSql + line.substring(0, pos) + "\r\n"; } } else { returnSql = returnSql + line + "\r\n"; } } return returnSql; } else { // does not contain any comments, return original return sql; } } private List<String> buildOrder(String syntaxType) { List<String> returnOrder = new ArrayList<>();
package com.abap.sql.beautifier.statement; public class AbapSql { private Map<String, AbapSqlPart> parts; private List<String> order; private boolean isOldSyntax = true; private List<String> comments = new ArrayList<String>(); private String startWhite = ""; public AbapSql(String sql, int diff) { startWhite = Utility.getWhiteChars(diff); parts = new HashMap<String, AbapSqlPart>(); // get order isOldSyntax = checkIfOldSyntax(sql); if (isOldSyntax) { setOrder(buildOrder(PreferenceConstants.ORDER_OLD_SYNTAX)); } else { setOrder(buildOrder(PreferenceConstants.ORDER_NEW_SYNTAX)); } appendSecWords(); sql = filterComments(sql); sql = Utility.cleanString(sql); setFromString(sql); resetFormat(); } private void appendSecWords() { // append keywords, which are introducing the same part int index; // INTO ~ APPENDING index = order.indexOf(Abap.INTO); if (index != -1) { order.add(index, Abap.APPENDING); } // UPTO ~ OFFSET index = order.indexOf(Abap.UPTO); if (index != -1) { order.add(index, Abap.OFFSET); } // INTO ~ INTO CORRESPONDING FIELDS OF index = order.indexOf(Abap.INTO); if (index != -1) { order.add(index, Abap.INTO_COR_FI_OF); } } private String filterComments(String sql) { String returnSql = ""; String asterisks = "*"; String apostrophes = "\""; if (sql.contains(asterisks) || sql.contains(apostrophes)) { List<String> lines = Arrays.asList(sql.split("\r\n")); for (String line : lines) { if (line.contains(asterisks) || line.contains(apostrophes)) { int pos = line.indexOf(asterisks); // check if asterisks is first char --> full line comment if (pos == 0) { comments.add(line.trim()); continue; } // asterisks was not a comment --> check apostrophes pos = line.indexOf(apostrophes); if (pos == -1) { returnSql = returnSql + line + "\r\n"; } else { comments.add(line.substring(pos).trim()); returnSql = returnSql + line.substring(0, pos) + "\r\n"; } } else { returnSql = returnSql + line + "\r\n"; } } return returnSql; } else { // does not contain any comments, return original return sql; } } private List<String> buildOrder(String syntaxType) { List<String> returnOrder = new ArrayList<>();
String curOrderString = Activator.getDefault().getPreferenceStore().getString(syntaxType);
1
2023-10-10 18:56:27+00:00
8k
Spider-Admin/Frost
src/main/java/frost/fileTransfer/NewUploadFilesManager.java
[ { "identifier": "GenerateShaThread", "path": "src/main/java/frost/fileTransfer/upload/GenerateShaThread.java", "snippet": "public class GenerateShaThread extends Thread {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(GenerateShaThread.class);\r\n\r\n private NewUploadFilesMana...
import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import frost.fileTransfer.upload.GenerateShaThread; import frost.storage.ExitSavable; import frost.storage.StorageException; import frost.storage.perst.FrostFilesStorage; import frost.storage.perst.NewUploadFile;
4,417
/* NewUploadFilesManager.java / Frost Copyright (C) 2006 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.fileTransfer; /** * * @author $Author: $ * @version $Revision: $ */ public class NewUploadFilesManager implements ExitSavable { private static final Logger logger = LoggerFactory.getLogger(NewUploadFilesManager.class);
/* NewUploadFilesManager.java / Frost Copyright (C) 2006 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.fileTransfer; /** * * @author $Author: $ * @version $Revision: $ */ public class NewUploadFilesManager implements ExitSavable { private static final Logger logger = LoggerFactory.getLogger(NewUploadFilesManager.class);
private LinkedList<NewUploadFile> newUploadFiles;
4
2023-10-07 22:25:20+00:00
8k
Milosz08/screen-sharing-system
host/src/main/java/pl/polsl/screensharing/host/net/ClientThread.java
[ { "identifier": "SessionDetails", "path": "host/src/main/java/pl/polsl/screensharing/host/model/SessionDetails.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\npublic class SessionDetails {\n @JsonProperty(\"ipAddress\")\n private String ipAddress;\n\n @JsonProperty(\"isMachineIp\")\n ...
import at.favre.lib.crypto.bcrypt.BCrypt; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import pl.polsl.screensharing.host.model.SessionDetails; import pl.polsl.screensharing.host.state.HostState; import pl.polsl.screensharing.host.state.StreamingState; import pl.polsl.screensharing.host.view.HostWindow; import pl.polsl.screensharing.lib.Utils; import pl.polsl.screensharing.lib.net.CryptoAsymmetricHelper; import pl.polsl.screensharing.lib.net.SocketState; import pl.polsl.screensharing.lib.net.StreamingSignalState; import pl.polsl.screensharing.lib.net.payload.AuthPasswordReq; import pl.polsl.screensharing.lib.net.payload.AuthPasswordRes; import pl.polsl.screensharing.lib.net.payload.ConnectionData; import pl.polsl.screensharing.lib.net.payload.VideoFrameDetails; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.SocketException; import java.security.PublicKey; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Consumer; import java.util.function.Function;
5,287
/* * Copyright (c) 2023 by MULTIPLE AUTHORS * Part of the CS study course project. */ package pl.polsl.screensharing.host.net; @Slf4j public class ClientThread extends Thread { @Getter private final Socket socket;
/* * Copyright (c) 2023 by MULTIPLE AUTHORS * Part of the CS study course project. */ package pl.polsl.screensharing.host.net; @Slf4j public class ClientThread extends Thread { @Getter private final Socket socket;
private final HostWindow hostWindow;
3
2023-10-11 16:12:02+00:00
8k
Bawnorton/Potters
src/main/java/com/bawnorton/potters/registry/PottersBlocks.java
[ { "identifier": "Potters", "path": "src/main/java/com/bawnorton/potters/Potters.java", "snippet": "public class Potters implements ModInitializer {\n public static final String MOD_ID = \"potters\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n public static Identif...
import com.bawnorton.potters.Potters; import com.bawnorton.potters.block.BottomlessDecoratedPotBlock; import com.bawnorton.potters.block.FiniteDecoratedPotBlock; import com.bawnorton.potters.block.base.PottersDecoratedPotBlockBase; import com.bawnorton.potters.config.ConfigManager; import net.minecraft.block.Block; import net.minecraft.item.Items; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.stream.Stream;
6,266
package com.bawnorton.potters.registry; public class PottersBlocks { public static final FiniteDecoratedPotBlock REDSTONE_DECORATED_POT; public static final FiniteDecoratedPotBlock COPPER_DECORATED_POT; public static final FiniteDecoratedPotBlock IRON_DECORATED_POT; public static final FiniteDecoratedPotBlock LAPIS_DECORATED_POT; public static final FiniteDecoratedPotBlock GOLD_DECORATED_POT; public static final FiniteDecoratedPotBlock AMETHYST_DECORATED_POT; public static final FiniteDecoratedPotBlock DIAMOND_DECORATED_POT; public static final FiniteDecoratedPotBlock EMERALD_DECORATED_POT; public static final FiniteDecoratedPotBlock NETHERITE_DECORATED_POT; public static final BottomlessDecoratedPotBlock BOTTOMLESS_DECORATED_POT; private static final List<PottersDecoratedPotBlockBase> ALL; private static final List<FiniteDecoratedPotBlock> FINITE_DECORATED_POTS; private static final Map<Block, String> BLOCK_TO_NAME; static { ALL = new ArrayList<>(); FINITE_DECORATED_POTS = new ArrayList<>(); BLOCK_TO_NAME = new HashMap<>(); COPPER_DECORATED_POT = register("copper", new FiniteDecoratedPotBlock(() -> Items.COPPER_INGOT, () -> Items.DECORATED_POT, () -> ConfigManager.getConfig().copperStackCount)); LAPIS_DECORATED_POT = register("lapis", new FiniteDecoratedPotBlock(() -> Items.LAPIS_LAZULI, COPPER_DECORATED_POT::asItem, () -> ConfigManager.getConfig().lapisStackCount)); REDSTONE_DECORATED_POT = register("redstone", new FiniteDecoratedPotBlock(() -> Items.REDSTONE, LAPIS_DECORATED_POT::asItem, () -> ConfigManager.getConfig().redstoneStackCount)); EMERALD_DECORATED_POT = register("emerald", new FiniteDecoratedPotBlock(() -> Items.EMERALD, REDSTONE_DECORATED_POT::asItem, () -> ConfigManager.getConfig().emeraldStackCount)); AMETHYST_DECORATED_POT = register("amethyst", new FiniteDecoratedPotBlock(() -> Items.AMETHYST_SHARD, EMERALD_DECORATED_POT::asItem, () -> ConfigManager.getConfig().amethystStackCount)); IRON_DECORATED_POT = register("iron", new FiniteDecoratedPotBlock(() -> Items.IRON_INGOT, () -> Items.DECORATED_POT, () -> ConfigManager.getConfig().ironStackCount)); GOLD_DECORATED_POT = register("gold", new FiniteDecoratedPotBlock(() -> Items.GOLD_INGOT, IRON_DECORATED_POT::asItem, () -> ConfigManager.getConfig().goldStackCount)); DIAMOND_DECORATED_POT = register("diamond", new FiniteDecoratedPotBlock(() -> Items.DIAMOND, GOLD_DECORATED_POT::asItem, () -> ConfigManager.getConfig().diamondStackCount)); NETHERITE_DECORATED_POT = register("netherite", new FiniteDecoratedPotBlock(() -> Items.NETHERITE_INGOT, DIAMOND_DECORATED_POT::asItem, () -> ConfigManager.getConfig().netheriteStackCount, 1)); BOTTOMLESS_DECORATED_POT = register("bottomless", new BottomlessDecoratedPotBlock(() -> Items.ENDER_PEARL)); /* Progression: * copper => lapis => redstone => emerald => amethyst * iron => gold => diamond => netherite => bottomless * normal + 4 copper => copper * copper + 4 lapis => lapis * lapis + 4 redstone => redstone * redstone + 4 emerald => emerald * emerald + 4 amethyst => amethyst * normal + 4 iron => iron * iron + 4 gold => gold * gold + 4 diamond => diamond * diamond + netherite => netherite * netherite + 2 ender pearl + nether star/dragon egg => bottomless * copper + 2 iron => iron * lapis + 2 gold => gold * redstone + 2 diamond => diamond * emerald + netherite => netherite * amethyst + 4 ender pearl + nether star/dragon egg => bottomless */ /* Costs: * Copper: 4 copper ingot + 4 bricks * Lapis: 4 lapis lazuli + 4 copper ingot + 4 bricks * Redstone: 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * Emerald: 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * Amethyst: 4 amethyst + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * Iron: 4 iron ingot + 4 bricks * 2 iron ingot + 4 copper ingot + 4 bricks * Gold: 4 gold ingot + 4 iron ingot + 4 bricks * 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks * 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks * Diamond: 4 diamond + 4 gold ingot + 4 iron ingot + 4 bricks * 2 diamond + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * 4 diamond + 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks * 4 diamond + 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks * Netherite: netherite ingot + 4 diamond + 4 gold ingot + 4 iron ingot + 4 bricks * nehterite ingot + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * netherite ingot + 2 diamond + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * netherite ingot + 4 diamond + 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks * netherite ingot + 4 diamond + 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks * Bottomless: 2 ender pearl + nether star + netherite ingot + 4 diamond + 4 gold ingot + 4 iron ingot + 4 bricks * 2 ender pearl + nether star + netherite ingot + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * 2 ender pearl + nether star + netherite ingot + 2 diamond + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * 2 ender pearl + nether star + netherite ingot + 4 diamond + 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks * 2 ender pearl + nether star + netherite ingot + 4 diamond + 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks * 4 ender pearl + nether star + 4 amethyst + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks */ } public static void init() { // no-op } public static String getName(Block block) { return BLOCK_TO_NAME.get(block); } public static Stream<PottersDecoratedPotBlockBase> stream() { return ALL.stream(); } public static void forEach(Consumer<PottersDecoratedPotBlockBase> blockConsumer) { ALL.forEach(blockConsumer); } public static void forEachFinite(Consumer<FiniteDecoratedPotBlock> blockConsumer) { FINITE_DECORATED_POTS.forEach(blockConsumer); } private static <T extends PottersDecoratedPotBlockBase> T register(String name, T block) {
package com.bawnorton.potters.registry; public class PottersBlocks { public static final FiniteDecoratedPotBlock REDSTONE_DECORATED_POT; public static final FiniteDecoratedPotBlock COPPER_DECORATED_POT; public static final FiniteDecoratedPotBlock IRON_DECORATED_POT; public static final FiniteDecoratedPotBlock LAPIS_DECORATED_POT; public static final FiniteDecoratedPotBlock GOLD_DECORATED_POT; public static final FiniteDecoratedPotBlock AMETHYST_DECORATED_POT; public static final FiniteDecoratedPotBlock DIAMOND_DECORATED_POT; public static final FiniteDecoratedPotBlock EMERALD_DECORATED_POT; public static final FiniteDecoratedPotBlock NETHERITE_DECORATED_POT; public static final BottomlessDecoratedPotBlock BOTTOMLESS_DECORATED_POT; private static final List<PottersDecoratedPotBlockBase> ALL; private static final List<FiniteDecoratedPotBlock> FINITE_DECORATED_POTS; private static final Map<Block, String> BLOCK_TO_NAME; static { ALL = new ArrayList<>(); FINITE_DECORATED_POTS = new ArrayList<>(); BLOCK_TO_NAME = new HashMap<>(); COPPER_DECORATED_POT = register("copper", new FiniteDecoratedPotBlock(() -> Items.COPPER_INGOT, () -> Items.DECORATED_POT, () -> ConfigManager.getConfig().copperStackCount)); LAPIS_DECORATED_POT = register("lapis", new FiniteDecoratedPotBlock(() -> Items.LAPIS_LAZULI, COPPER_DECORATED_POT::asItem, () -> ConfigManager.getConfig().lapisStackCount)); REDSTONE_DECORATED_POT = register("redstone", new FiniteDecoratedPotBlock(() -> Items.REDSTONE, LAPIS_DECORATED_POT::asItem, () -> ConfigManager.getConfig().redstoneStackCount)); EMERALD_DECORATED_POT = register("emerald", new FiniteDecoratedPotBlock(() -> Items.EMERALD, REDSTONE_DECORATED_POT::asItem, () -> ConfigManager.getConfig().emeraldStackCount)); AMETHYST_DECORATED_POT = register("amethyst", new FiniteDecoratedPotBlock(() -> Items.AMETHYST_SHARD, EMERALD_DECORATED_POT::asItem, () -> ConfigManager.getConfig().amethystStackCount)); IRON_DECORATED_POT = register("iron", new FiniteDecoratedPotBlock(() -> Items.IRON_INGOT, () -> Items.DECORATED_POT, () -> ConfigManager.getConfig().ironStackCount)); GOLD_DECORATED_POT = register("gold", new FiniteDecoratedPotBlock(() -> Items.GOLD_INGOT, IRON_DECORATED_POT::asItem, () -> ConfigManager.getConfig().goldStackCount)); DIAMOND_DECORATED_POT = register("diamond", new FiniteDecoratedPotBlock(() -> Items.DIAMOND, GOLD_DECORATED_POT::asItem, () -> ConfigManager.getConfig().diamondStackCount)); NETHERITE_DECORATED_POT = register("netherite", new FiniteDecoratedPotBlock(() -> Items.NETHERITE_INGOT, DIAMOND_DECORATED_POT::asItem, () -> ConfigManager.getConfig().netheriteStackCount, 1)); BOTTOMLESS_DECORATED_POT = register("bottomless", new BottomlessDecoratedPotBlock(() -> Items.ENDER_PEARL)); /* Progression: * copper => lapis => redstone => emerald => amethyst * iron => gold => diamond => netherite => bottomless * normal + 4 copper => copper * copper + 4 lapis => lapis * lapis + 4 redstone => redstone * redstone + 4 emerald => emerald * emerald + 4 amethyst => amethyst * normal + 4 iron => iron * iron + 4 gold => gold * gold + 4 diamond => diamond * diamond + netherite => netherite * netherite + 2 ender pearl + nether star/dragon egg => bottomless * copper + 2 iron => iron * lapis + 2 gold => gold * redstone + 2 diamond => diamond * emerald + netherite => netherite * amethyst + 4 ender pearl + nether star/dragon egg => bottomless */ /* Costs: * Copper: 4 copper ingot + 4 bricks * Lapis: 4 lapis lazuli + 4 copper ingot + 4 bricks * Redstone: 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * Emerald: 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * Amethyst: 4 amethyst + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * Iron: 4 iron ingot + 4 bricks * 2 iron ingot + 4 copper ingot + 4 bricks * Gold: 4 gold ingot + 4 iron ingot + 4 bricks * 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks * 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks * Diamond: 4 diamond + 4 gold ingot + 4 iron ingot + 4 bricks * 2 diamond + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * 4 diamond + 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks * 4 diamond + 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks * Netherite: netherite ingot + 4 diamond + 4 gold ingot + 4 iron ingot + 4 bricks * nehterite ingot + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * netherite ingot + 2 diamond + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * netherite ingot + 4 diamond + 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks * netherite ingot + 4 diamond + 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks * Bottomless: 2 ender pearl + nether star + netherite ingot + 4 diamond + 4 gold ingot + 4 iron ingot + 4 bricks * 2 ender pearl + nether star + netherite ingot + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * 2 ender pearl + nether star + netherite ingot + 2 diamond + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks * 2 ender pearl + nether star + netherite ingot + 4 diamond + 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks * 2 ender pearl + nether star + netherite ingot + 4 diamond + 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks * 4 ender pearl + nether star + 4 amethyst + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks */ } public static void init() { // no-op } public static String getName(Block block) { return BLOCK_TO_NAME.get(block); } public static Stream<PottersDecoratedPotBlockBase> stream() { return ALL.stream(); } public static void forEach(Consumer<PottersDecoratedPotBlockBase> blockConsumer) { ALL.forEach(blockConsumer); } public static void forEachFinite(Consumer<FiniteDecoratedPotBlock> blockConsumer) { FINITE_DECORATED_POTS.forEach(blockConsumer); } private static <T extends PottersDecoratedPotBlockBase> T register(String name, T block) {
T value = Registry.register(Registries.BLOCK, Potters.id(name + "_decorated_pot"), block);
0
2023-10-13 19:14:56+00:00
8k
YinQin257/mqs-adapter
mqs-starter/src/main/java/org/yinqin/mqs/kafka/consumer/factory/KafkaBatchConsumerFactory.java
[ { "identifier": "Constants", "path": "mqs-starter/src/main/java/org/yinqin/mqs/common/Constants.java", "snippet": "public interface Constants {\n int SUCCESS = 1;\n int ERROR = 0;\n String TRAN = \"TRAN\";\n String BATCH = \"BATCH\";\n String BROADCAST = \"BROADCAST\";\n String TRUE = ...
import org.apache.kafka.clients.consumer.KafkaConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yinqin.mqs.common.Constants; import org.yinqin.mqs.common.config.MqsProperties; import org.yinqin.mqs.common.factory.ConsumerFactory; import org.yinqin.mqs.common.handler.MessageHandler; import org.yinqin.mqs.common.service.MessageConsumer; import org.yinqin.mqs.kafka.PollWorker; import org.yinqin.mqs.kafka.consumer.CustomKafkaConsumer; import java.util.Map; import java.util.Properties;
3,683
package org.yinqin.mqs.kafka.consumer.factory; /** * kafka批量消费者工厂类 * * @author YinQin * @createDate 2023年11月27日 * @since 1.0.6 * @see ConsumerFactory * @version 1.0.6 */ public class KafkaBatchConsumerFactory extends ConsumerFactory implements CreateKafkaConsumer { @Override public MessageConsumer createConsumer(String instanceId, MqsProperties.AdapterProperties properties, Map<String, MessageHandler> messageHandlers) { // 初始化配置 Properties kafkaProperties = new Properties(); init(kafkaProperties, properties); // 设置消费组名称 String groupName = properties.getGroupName() + Constants.BATCH_SUFFIX; // 创建kafka原生消费者 KafkaConsumer<String, byte[]> kafkaConsumer = createKafkaConsumer(groupName, properties, kafkaProperties); // 订阅topic subscribe(kafkaConsumer, instanceId, groupName, messageHandlers); // 创建拉取消息工作线程 PollWorker pollWorker = new PollWorker(kafkaConsumer, messageHandlers, properties.getKafka().getInterval()); // 创建自定义消费者
package org.yinqin.mqs.kafka.consumer.factory; /** * kafka批量消费者工厂类 * * @author YinQin * @createDate 2023年11月27日 * @since 1.0.6 * @see ConsumerFactory * @version 1.0.6 */ public class KafkaBatchConsumerFactory extends ConsumerFactory implements CreateKafkaConsumer { @Override public MessageConsumer createConsumer(String instanceId, MqsProperties.AdapterProperties properties, Map<String, MessageHandler> messageHandlers) { // 初始化配置 Properties kafkaProperties = new Properties(); init(kafkaProperties, properties); // 设置消费组名称 String groupName = properties.getGroupName() + Constants.BATCH_SUFFIX; // 创建kafka原生消费者 KafkaConsumer<String, byte[]> kafkaConsumer = createKafkaConsumer(groupName, properties, kafkaProperties); // 订阅topic subscribe(kafkaConsumer, instanceId, groupName, messageHandlers); // 创建拉取消息工作线程 PollWorker pollWorker = new PollWorker(kafkaConsumer, messageHandlers, properties.getKafka().getInterval()); // 创建自定义消费者
return new CustomKafkaConsumer(instanceId, Constants.BATCH, pollWorker);
6
2023-10-11 03:23:43+00:00
8k
Feniksovich/RxPubSub
src/main/java/io/github/feniksovich/rxpubsub/event/EventBusImpl.java
[ { "identifier": "MessagingService", "path": "src/main/java/io/github/feniksovich/rxpubsub/MessagingService.java", "snippet": "public final class MessagingService {\n\n private MessagingServiceConfig config;\n private RedisClient redisClient;\n private StatefulRedisPubSubConnection<String, Strin...
import io.github.feniksovich.rxpubsub.MessagingService; import io.github.feniksovich.rxpubsub.model.PubSubChannel; import io.github.feniksovich.rxpubsub.model.PubSubMessage; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Consumer; import java.util.function.Function;
4,101
package io.github.feniksovich.rxpubsub.event; public class EventBusImpl implements EventBus { private final MessagingService messagingService; private final ConcurrentHashMap<Class<? extends PubSubMessage>, List<ReceiptListener>> handlers = new ConcurrentHashMap<>(); private final ConcurrentHashMap<Class<? extends PubSubMessage>, List<ReceiptListener>> respondingHandlers = new ConcurrentHashMap<>(); private final ExecutorService listenersExecutor = Executors.newCachedThreadPool(); public EventBusImpl(MessagingService messagingService) { this.messagingService = messagingService; } public <T extends PubSubMessage> EventBus registerReceiptListener(Class<T> messageClass, Consumer<T> handler) { // Create new listener object final var listener = new ReceiptListener() { @Override public void execute(PubSubMessage message) { handler.accept(messageClass.cast(message)); } }; registerListener(messageClass, listener, handlers); return this; } public <T extends PubSubMessage> EventBus registerRespondingListener(
package io.github.feniksovich.rxpubsub.event; public class EventBusImpl implements EventBus { private final MessagingService messagingService; private final ConcurrentHashMap<Class<? extends PubSubMessage>, List<ReceiptListener>> handlers = new ConcurrentHashMap<>(); private final ConcurrentHashMap<Class<? extends PubSubMessage>, List<ReceiptListener>> respondingHandlers = new ConcurrentHashMap<>(); private final ExecutorService listenersExecutor = Executors.newCachedThreadPool(); public EventBusImpl(MessagingService messagingService) { this.messagingService = messagingService; } public <T extends PubSubMessage> EventBus registerReceiptListener(Class<T> messageClass, Consumer<T> handler) { // Create new listener object final var listener = new ReceiptListener() { @Override public void execute(PubSubMessage message) { handler.accept(messageClass.cast(message)); } }; registerListener(messageClass, listener, handlers); return this; } public <T extends PubSubMessage> EventBus registerRespondingListener(
Class<T> messageClass, PubSubChannel channel, Function<T, PubSubMessage> handler
1
2023-10-09 19:05:31+00:00
8k
openpilot-hub/devpilot-intellij
src/main/java/com/zhongan/devpilot/gui/toolwindows/chat/DevPilotChatToolWindowService.java
[ { "identifier": "BasicEditorAction", "path": "src/main/java/com/zhongan/devpilot/actions/editor/popupmenu/BasicEditorAction.java", "snippet": "public abstract class BasicEditorAction extends AnAction {\n\n BasicEditorAction(\n @Nullable @NlsActions.ActionText String text,\n @Nullable @N...
import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.Service; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.zhongan.devpilot.actions.editor.popupmenu.BasicEditorAction; import com.zhongan.devpilot.constant.PromptConst; import com.zhongan.devpilot.enums.EditorActionEnum; import com.zhongan.devpilot.enums.SessionTypeEnum; import com.zhongan.devpilot.integrations.llms.LlmProvider; import com.zhongan.devpilot.integrations.llms.LlmProviderFactory; import com.zhongan.devpilot.integrations.llms.entity.DevPilotChatCompletionRequest; import com.zhongan.devpilot.integrations.llms.entity.DevPilotMessage; import com.zhongan.devpilot.util.DevPilotMessageBundle; import com.zhongan.devpilot.util.JsonUtils; import com.zhongan.devpilot.util.MessageUtil; import com.zhongan.devpilot.webview.model.JavaCallModel; import com.zhongan.devpilot.webview.model.LocaleModel; import com.zhongan.devpilot.webview.model.MessageModel; import com.zhongan.devpilot.webview.model.ThemeModel; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer;
4,958
package com.zhongan.devpilot.gui.toolwindows.chat; @Service public final class DevPilotChatToolWindowService { private final Project project; private final DevPilotChatToolWindow devPilotChatToolWindow; private LlmProvider llmProvider; private final List<MessageModel> historyMessageList = new ArrayList<>();
package com.zhongan.devpilot.gui.toolwindows.chat; @Service public final class DevPilotChatToolWindowService { private final Project project; private final DevPilotChatToolWindow devPilotChatToolWindow; private LlmProvider llmProvider; private final List<MessageModel> historyMessageList = new ArrayList<>();
private final List<DevPilotMessage> historyRequestMessageList = new ArrayList<>();
7
2023-11-29 06:37:51+00:00
8k
Gaia3D/mago-3d-tiler
tiler/src/main/java/com/gaia3d/command/PointCloudProcessModel.java
[ { "identifier": "FormatType", "path": "core/src/main/java/com/gaia3d/basic/types/FormatType.java", "snippet": "@Getter\npublic enum FormatType {\n // 3D Formats\n FBX(\"fbx\", true),\n GLTF(\"gltf\", true),\n GLB(\"glb\", true),\n KML(\"kml\", false),\n COLLADA(\"dae\", false),\n MA...
import com.gaia3d.basic.types.FormatType; import com.gaia3d.converter.PointCloudFileLoader; import com.gaia3d.converter.pointcloud.LasConverter; import com.gaia3d.process.PointCloudProcessFlow; import com.gaia3d.process.ProcessOptions; import com.gaia3d.process.TilerOptions; import com.gaia3d.process.postprocess.PostProcess; import com.gaia3d.process.preprocess.PreProcess; import com.gaia3d.process.tileprocess.TileProcess; import com.gaia3d.process.tileprocess.tile.PointCloudTiler; import lombok.extern.slf4j.Slf4j; import org.apache.commons.cli.CommandLine; import org.apache.commons.io.FileExistsException; import org.locationtech.proj4j.CRSFactory; import org.locationtech.proj4j.CoordinateReferenceSystem; import java.io.File; import java.io.IOException; import java.nio.file.NotDirectoryException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List;
6,091
package com.gaia3d.command; @Slf4j public class PointCloudProcessModel implements ProcessFlowModel{ public void run(CommandLine command) throws IOException { File inputFile = new File(command.getOptionValue(ProcessOptions.INPUT.getArgName())); File outputFile = new File(command.getOptionValue(ProcessOptions.OUTPUT.getArgName())); String crs = command.getOptionValue(ProcessOptions.CRS.getArgName()); String proj = command.getOptionValue(ProcessOptions.PROJ4.getArgName()); String inputExtension = command.getOptionValue(ProcessOptions.INPUT_TYPE.getArgName()); Path inputPath = createPath(inputFile); Path outputPath = createPath(outputFile); if (!validate(outputPath)) { return; } FormatType formatType = FormatType.fromExtension(inputExtension); CRSFactory factory = new CRSFactory(); CoordinateReferenceSystem source = null; if (proj != null && !proj.isEmpty()) { source = factory.createFromParameters("CUSTOM", proj); } else { source = (crs != null && !crs.isEmpty()) ? factory.createFromName("EPSG:" + crs) : null; } LasConverter converter = new LasConverter(command, source); PointCloudFileLoader fileLoader = new PointCloudFileLoader(command, converter); List<PreProcess> preProcessors = new ArrayList<>(); TilerOptions tilerOptions = TilerOptions.builder() .inputPath(inputPath) .outputPath(outputPath) .inputFormatType(formatType) .source(source) .build(); TileProcess tileProcess = new PointCloudTiler(tilerOptions, command);
package com.gaia3d.command; @Slf4j public class PointCloudProcessModel implements ProcessFlowModel{ public void run(CommandLine command) throws IOException { File inputFile = new File(command.getOptionValue(ProcessOptions.INPUT.getArgName())); File outputFile = new File(command.getOptionValue(ProcessOptions.OUTPUT.getArgName())); String crs = command.getOptionValue(ProcessOptions.CRS.getArgName()); String proj = command.getOptionValue(ProcessOptions.PROJ4.getArgName()); String inputExtension = command.getOptionValue(ProcessOptions.INPUT_TYPE.getArgName()); Path inputPath = createPath(inputFile); Path outputPath = createPath(outputFile); if (!validate(outputPath)) { return; } FormatType formatType = FormatType.fromExtension(inputExtension); CRSFactory factory = new CRSFactory(); CoordinateReferenceSystem source = null; if (proj != null && !proj.isEmpty()) { source = factory.createFromParameters("CUSTOM", proj); } else { source = (crs != null && !crs.isEmpty()) ? factory.createFromName("EPSG:" + crs) : null; } LasConverter converter = new LasConverter(command, source); PointCloudFileLoader fileLoader = new PointCloudFileLoader(command, converter); List<PreProcess> preProcessors = new ArrayList<>(); TilerOptions tilerOptions = TilerOptions.builder() .inputPath(inputPath) .outputPath(outputPath) .inputFormatType(formatType) .source(source) .build(); TileProcess tileProcess = new PointCloudTiler(tilerOptions, command);
List<PostProcess> postProcessors = new ArrayList<>();
6
2023-11-30 01:59:44+00:00
8k
xuemingqi/x-cloud
x-config/src/main/java/com/x/config/redis/conf/RedissonConfig.java
[ { "identifier": "RedisCommonConstant", "path": "x-config/src/main/java/com/x/config/redis/constants/RedisCommonConstant.java", "snippet": "public interface RedisCommonConstant {\n\n String CACHE_MANAGER_NAME = \"selfCacheManager\";\n}" }, { "identifier": "RedissonClusterProperty", "path":...
import com.x.config.redis.constants.RedisCommonConstant; import com.x.config.redis.property.RedissonClusterProperty; import com.x.config.redis.property.RedissonMasterSlaveProperty; import com.x.config.redis.property.RedissonSingleProperty; import com.x.config.redis.property.TtlRedisCacheManager; import com.x.config.redis.type.RedissonType; import com.x.config.redis.util.RedisUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.codec.JsonJacksonCodec; import org.redisson.config.Config; import org.redisson.config.ReadMode; import org.redisson.connection.balancer.RoundRobinLoadBalancer; import org.redisson.spring.data.connection.RedissonConnectionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter;
7,064
package com.x.config.redis.conf; /** * @author : xuemingqi * @since : 2023/1/7 16:38 */ @Slf4j @Configuration @ConditionalOnClass(RedissonClient.class) @RequiredArgsConstructor(onConstructor = @__({@Autowired})) public class RedissonConfig { private final RedissonSingleProperty singleProperty; private final RedissonMasterSlaveProperty masterSlaveProperty; private final RedissonClusterProperty clusterProperty; private final RedissonType redissonType; @Bean public RedissonClient redissonClient() { Config config = new Config(); switch (redissonType.getType()) { case SINGLE: createSingleConfig(config); break; case MASTER_SLAVE: createMasterSlaveConfig(config); break; case CLUSTER: createClusterConfig(config); break; } return Redisson.create(config); } /** * redisUtil bean */ @Bean
package com.x.config.redis.conf; /** * @author : xuemingqi * @since : 2023/1/7 16:38 */ @Slf4j @Configuration @ConditionalOnClass(RedissonClient.class) @RequiredArgsConstructor(onConstructor = @__({@Autowired})) public class RedissonConfig { private final RedissonSingleProperty singleProperty; private final RedissonMasterSlaveProperty masterSlaveProperty; private final RedissonClusterProperty clusterProperty; private final RedissonType redissonType; @Bean public RedissonClient redissonClient() { Config config = new Config(); switch (redissonType.getType()) { case SINGLE: createSingleConfig(config); break; case MASTER_SLAVE: createMasterSlaveConfig(config); break; case CLUSTER: createClusterConfig(config); break; } return Redisson.create(config); } /** * redisUtil bean */ @Bean
public RedisUtil redisUtil(RedissonClient redissonClient) {
6
2023-11-27 08:23:38+00:00
8k
okx/OKBund
aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/test/NewTestController.java
[ { "identifier": "AccountUtil", "path": "aa-infra/src/main/java/com/okcoin/dapp/bundler/infra/chain/AccountUtil.java", "snippet": "public class AccountUtil {\n\n @SneakyThrows\n public static BigInteger getNonce(String address, boolean isLatest, IChain chain) {\n EthGetTransactionCount ethGe...
import com.alibaba.fastjson2.JSON; import com.google.common.collect.Lists; import com.okcoin.dapp.bundler.infra.chain.AccountUtil; import com.okcoin.dapp.bundler.infra.chain.constant.Web3Constant; import com.okcoin.dapp.bundler.pool.config.ChainConfig; import com.okcoin.dapp.bundler.pool.config.PoolConfig; 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.rest.account.AccountFactory; import com.okcoin.dapp.bundler.rest.account.AccountSignContext; import com.okcoin.dapp.bundler.rest.account.IAccount; import com.okcoin.dapp.bundler.rest.account.SingleCallDataContext; import com.okcoin.dapp.bundler.rest.api.AAController; import com.okcoin.dapp.bundler.rest.api.req.AAReq; import com.okcoin.dapp.bundler.rest.api.req.UserOperationParam; import com.okcoin.dapp.bundler.rest.api.resp.AAResp; import com.okcoin.dapp.bundler.rest.api.resp.EstimateUserOperationGasVO; import com.okcoin.dapp.bundler.rest.constant.AaMethodConstant; import com.okcoin.dapp.bundler.rest.factory.AccountFactoryFactory; import com.okcoin.dapp.bundler.rest.factory.IAccountFactory; import com.okcoin.dapp.bundler.rest.factory.InitCodeContext; import com.okcoin.dapp.bundler.rest.factory.SenderAddressContext; import com.okcoin.dapp.bundler.rest.util.UopUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.web3j.abi.datatypes.DynamicBytes; import org.web3j.crypto.Credentials; import org.web3j.utils.Numeric; import java.math.BigInteger; import java.util.Arrays; import java.util.List;
6,946
package com.okcoin.dapp.bundler.rest.test; @RestController @RequestMapping @Slf4j public class NewTestController { private static final String FAKE_SIGN_FOR_EVM = "0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a07fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a01b"; @Autowired private AAController aaController; @Autowired private AccountFactory accountFactory; @Autowired
package com.okcoin.dapp.bundler.rest.test; @RestController @RequestMapping @Slf4j public class NewTestController { private static final String FAKE_SIGN_FOR_EVM = "0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a07fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a01b"; @Autowired private AAController aaController; @Autowired private AccountFactory accountFactory; @Autowired
private AccountFactoryFactory accountFactoryFactory;
17
2023-11-27 10:54:49+00:00
8k
lidaofu-hub/j_media_server
src/main/java/com/ldf/media/api/service/impl/ApiServiceImpl.java
[ { "identifier": "MediaInfoResult", "path": "src/main/java/com/ldf/media/api/model/result/MediaInfoResult.java", "snippet": "@Data\n@ApiModel(value = \"GetMediaListParam对象\", description = \"流信息\")\npublic class MediaInfoResult implements Serializable {\n\n private static final long serialVersionUID =...
import cn.hutool.core.lang.Assert; import com.ldf.media.api.model.param.*; import com.ldf.media.api.model.result.MediaInfoResult; import com.ldf.media.api.model.result.Track; import com.ldf.media.api.service.IApiService; import com.ldf.media.callback.MKSourceFindCallBack; import com.ldf.media.constants.MediaServerConstants; import com.ldf.media.context.MediaServerContext; import com.ldf.media.sdk.callback.IMKProxyPlayCloseCallBack; import com.ldf.media.sdk.structure.MK_MEDIA_SOURCE; import com.ldf.media.sdk.structure.MK_PROXY_PLAYER; import com.ldf.media.sdk.structure.MK_TRACK; import com.sun.jna.Pointer; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference;
3,836
package com.ldf.media.api.service.impl; /** * 接口服务 * * @author lidaofu * @since 2023/11/29 **/ @Service public class ApiServiceImpl implements IApiService { @Override public void addStreamProxy(StreamProxyParam param) { //查询流是是否存在 MK_MEDIA_SOURCE mkMediaSource = MediaServerContext.ZLM_API.mk_media_source_find2(param.getEnableRtmp() == 1 ? "rtmp" : "rtsp", MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), 0); Assert.isNull(mkMediaSource, "当前流信息已被使用"); //创建拉流代理 MK_PROXY_PLAYER mk_proxy = MediaServerContext.ZLM_API.mk_proxy_player_create(MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), param.getEnableHls(), param.getEnableMp4(), param.getEnableFmp4(), param.getEnableTs(), param.getEnableRtmp(), param.getEnableRtsp()); //回调关闭时间 IMKProxyPlayCloseCallBack imkProxyPlayCloseCallBack = (pUser, err, what, sys_err) -> { //这里Pointer是ZLM维护的不需要我们释放 遵循谁申请谁释放原则 MediaServerContext.ZLM_API.mk_proxy_player_release(new MK_PROXY_PLAYER(pUser)); }; MediaServerContext.ZLM_API.mk_proxy_player_set_option(mk_proxy, "rtp_type", param.getRtpType().toString()); //开始播放 MediaServerContext.ZLM_API.mk_proxy_player_play(mk_proxy, param.getUrl()); //添加代理关闭回调 并把代理客户端传过去释放 MediaServerContext.ZLM_API.mk_proxy_player_set_on_close(mk_proxy, imkProxyPlayCloseCallBack, mk_proxy.getPointer()); } @Override public Integer closeStream(CloseStreamParam param) { //查询流是是否存在 MK_MEDIA_SOURCE mkMediaSource = MediaServerContext.ZLM_API.mk_media_source_find2(param.getSchema(), MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), 0); Assert.notNull(mkMediaSource, "当前流不在线"); return MediaServerContext.ZLM_API.mk_media_source_close(mkMediaSource, param.getForce()); } @Override public Integer closeStreams(CloseStreamsParam param) { AtomicReference<Integer> count = new AtomicReference<>(0); MediaServerContext.ZLM_API.mk_media_source_for_each(Pointer.NULL, new MKSourceFindCallBack((MK_MEDIA_SOURCE ctx) -> { int status = MediaServerContext.ZLM_API.mk_media_source_close(ctx, param.getForce()); count.set(count.get() + status); }), param.getSchema(), MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream()); try { Thread.sleep(200L); } catch (InterruptedException ignored) { } return count.get(); } @Override public List<MediaInfoResult> getMediaList(GetMediaListParam param) { List<MediaInfoResult> list = new ArrayList<>(); MediaServerContext.ZLM_API.mk_media_source_for_each(Pointer.NULL, new MKSourceFindCallBack((MK_MEDIA_SOURCE ctx) -> { String app = MediaServerContext.ZLM_API.mk_media_source_get_app(ctx); String stream = MediaServerContext.ZLM_API.mk_media_source_get_stream(ctx); String schema = MediaServerContext.ZLM_API.mk_media_source_get_schema(ctx); int readerCount = MediaServerContext.ZLM_API.mk_media_source_get_reader_count(ctx); int totalReaderCount = MediaServerContext.ZLM_API.mk_media_source_get_total_reader_count(ctx); int trackSize = MediaServerContext.ZLM_API.mk_media_source_get_track_count(ctx); MediaInfoResult mediaInfoResult = new MediaInfoResult(); mediaInfoResult.setApp(app); mediaInfoResult.setStream(stream); mediaInfoResult.setSchema(schema); mediaInfoResult.setReaderCount(readerCount); mediaInfoResult.setTotalReaderCount(totalReaderCount); List<Track> tracks = new ArrayList<>(); for (int i = 0; i < trackSize; i++) {
package com.ldf.media.api.service.impl; /** * 接口服务 * * @author lidaofu * @since 2023/11/29 **/ @Service public class ApiServiceImpl implements IApiService { @Override public void addStreamProxy(StreamProxyParam param) { //查询流是是否存在 MK_MEDIA_SOURCE mkMediaSource = MediaServerContext.ZLM_API.mk_media_source_find2(param.getEnableRtmp() == 1 ? "rtmp" : "rtsp", MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), 0); Assert.isNull(mkMediaSource, "当前流信息已被使用"); //创建拉流代理 MK_PROXY_PLAYER mk_proxy = MediaServerContext.ZLM_API.mk_proxy_player_create(MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), param.getEnableHls(), param.getEnableMp4(), param.getEnableFmp4(), param.getEnableTs(), param.getEnableRtmp(), param.getEnableRtsp()); //回调关闭时间 IMKProxyPlayCloseCallBack imkProxyPlayCloseCallBack = (pUser, err, what, sys_err) -> { //这里Pointer是ZLM维护的不需要我们释放 遵循谁申请谁释放原则 MediaServerContext.ZLM_API.mk_proxy_player_release(new MK_PROXY_PLAYER(pUser)); }; MediaServerContext.ZLM_API.mk_proxy_player_set_option(mk_proxy, "rtp_type", param.getRtpType().toString()); //开始播放 MediaServerContext.ZLM_API.mk_proxy_player_play(mk_proxy, param.getUrl()); //添加代理关闭回调 并把代理客户端传过去释放 MediaServerContext.ZLM_API.mk_proxy_player_set_on_close(mk_proxy, imkProxyPlayCloseCallBack, mk_proxy.getPointer()); } @Override public Integer closeStream(CloseStreamParam param) { //查询流是是否存在 MK_MEDIA_SOURCE mkMediaSource = MediaServerContext.ZLM_API.mk_media_source_find2(param.getSchema(), MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), 0); Assert.notNull(mkMediaSource, "当前流不在线"); return MediaServerContext.ZLM_API.mk_media_source_close(mkMediaSource, param.getForce()); } @Override public Integer closeStreams(CloseStreamsParam param) { AtomicReference<Integer> count = new AtomicReference<>(0); MediaServerContext.ZLM_API.mk_media_source_for_each(Pointer.NULL, new MKSourceFindCallBack((MK_MEDIA_SOURCE ctx) -> { int status = MediaServerContext.ZLM_API.mk_media_source_close(ctx, param.getForce()); count.set(count.get() + status); }), param.getSchema(), MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream()); try { Thread.sleep(200L); } catch (InterruptedException ignored) { } return count.get(); } @Override public List<MediaInfoResult> getMediaList(GetMediaListParam param) { List<MediaInfoResult> list = new ArrayList<>(); MediaServerContext.ZLM_API.mk_media_source_for_each(Pointer.NULL, new MKSourceFindCallBack((MK_MEDIA_SOURCE ctx) -> { String app = MediaServerContext.ZLM_API.mk_media_source_get_app(ctx); String stream = MediaServerContext.ZLM_API.mk_media_source_get_stream(ctx); String schema = MediaServerContext.ZLM_API.mk_media_source_get_schema(ctx); int readerCount = MediaServerContext.ZLM_API.mk_media_source_get_reader_count(ctx); int totalReaderCount = MediaServerContext.ZLM_API.mk_media_source_get_total_reader_count(ctx); int trackSize = MediaServerContext.ZLM_API.mk_media_source_get_track_count(ctx); MediaInfoResult mediaInfoResult = new MediaInfoResult(); mediaInfoResult.setApp(app); mediaInfoResult.setStream(stream); mediaInfoResult.setSchema(schema); mediaInfoResult.setReaderCount(readerCount); mediaInfoResult.setTotalReaderCount(totalReaderCount); List<Track> tracks = new ArrayList<>(); for (int i = 0; i < trackSize; i++) {
MK_TRACK mkTrack = MediaServerContext.ZLM_API.mk_media_source_get_track(ctx, i);
9
2023-11-29 07:47:56+00:00
8k
seraxis/lr2oraja-endlessdream
core/src/bms/player/beatoraja/skin/json/JsonSelectSkinObjectLoader.java
[ { "identifier": "MusicSelectSkin", "path": "core/src/bms/player/beatoraja/select/MusicSelectSkin.java", "snippet": "public class MusicSelectSkin extends Skin {\n\n\t/**\n\t * カーソルが合っているBarのindex\n\t */\n\tprivate int centerBar;\n\t/**\n\t * クリック可能なBarのindex\n\t */\n\tprivate int[] clickableBar = new int...
import java.nio.file.Path; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import bms.player.beatoraja.select.MusicSelectSkin; import bms.player.beatoraja.select.SkinBar; import bms.player.beatoraja.select.SkinDistributionGraph; import bms.player.beatoraja.skin.*; import bms.player.beatoraja.skin.property.TimerProperty;
5,475
package bms.player.beatoraja.skin.json; /** * JSONセレクトスキンオブジェクトローダー * * @author exch */ public class JsonSelectSkinObjectLoader extends JsonSkinObjectLoader<MusicSelectSkin> { public JsonSelectSkinObjectLoader(JSONSkinLoader loader) { super(loader); } @Override public MusicSelectSkin getSkin(SkinHeader header) { return new MusicSelectSkin(header); } @Override public SkinObject loadSkinObject(MusicSelectSkin skin, JsonSkin.Skin sk, JsonSkin.Destination dst, Path p) { SkinObject obj =super.loadSkinObject(skin, sk, dst, p); if(obj != null) { return obj; } if (sk.songlist != null && dst.id.equals(sk.songlist.id)) {
package bms.player.beatoraja.skin.json; /** * JSONセレクトスキンオブジェクトローダー * * @author exch */ public class JsonSelectSkinObjectLoader extends JsonSkinObjectLoader<MusicSelectSkin> { public JsonSelectSkinObjectLoader(JSONSkinLoader loader) { super(loader); } @Override public MusicSelectSkin getSkin(SkinHeader header) { return new MusicSelectSkin(header); } @Override public SkinObject loadSkinObject(MusicSelectSkin skin, JsonSkin.Skin sk, JsonSkin.Destination dst, Path p) { SkinObject obj =super.loadSkinObject(skin, sk, dst, p); if(obj != null) { return obj; } if (sk.songlist != null && dst.id.equals(sk.songlist.id)) {
SkinBar barobj = new SkinBar(0);
1
2023-12-02 23:41:17+00:00
8k
Elb1to/FFA
src/main/java/me/elb1to/ffa/command/manager/CommandManager.java
[ { "identifier": "FfaPlugin", "path": "src/main/java/me/elb1to/ffa/FfaPlugin.java", "snippet": "@Getter\npublic class FfaPlugin extends JavaPlugin {\n\n\tprivate MongoSrv mongoSrv;\n\n\tprivate MapManager mapManager;\n\tprivate KitManager kitManager;\n\tprivate FfaManager ffaManager;\n\n\tprivate UserPro...
import co.aikar.commands.PaperCommandManager; import me.elb1to.ffa.FfaPlugin; import me.elb1to.ffa.command.FfaCommand; import me.elb1to.ffa.kit.Kit; import me.elb1to.ffa.kit.command.KitCommand; import me.elb1to.ffa.map.FfaMap; import me.elb1to.ffa.map.command.BuildModeCommand; import me.elb1to.ffa.map.command.MapCommand; import me.elb1to.ffa.user.command.SettingsCommand; import me.elb1to.ffa.user.command.StatsCommand; import me.elb1to.ffa.user.command.UserProfileDebugCommand; import java.util.ArrayList; import java.util.stream.Collectors;
5,393
package me.elb1to.ffa.command.manager; /** * @author Elb1to * @since 11/24/2023 */ public class CommandManager { private final FfaPlugin plugin; private final PaperCommandManager manager; public CommandManager(FfaPlugin plugin) { this.plugin = plugin; this.manager = new PaperCommandManager(plugin); load(); } private void load() { manager.getCommandCompletions().registerCompletion("kits", context -> new ArrayList<>(plugin.getKitManager().getKits().values()) .stream() .map(Kit::getName) .collect(Collectors.toList()) ); manager.getCommandCompletions().registerCompletion("maps", context -> plugin.getMapManager().getMaps() .stream() .map(FfaMap::getName) .collect(Collectors.toList()) ); manager.getCommandContexts().registerContext(Kit.class, context -> plugin.getKitManager().get(context.popFirstArg())); manager.getCommandContexts().registerContext(FfaMap.class, context -> plugin.getMapManager().getByName(context.popFirstArg())); manager.registerCommand(new FfaCommand()); manager.registerCommand(new KitCommand()); manager.registerCommand(new MapCommand()); manager.registerCommand(new StatsCommand()); // Unfinished command //manager.registerCommand(new SettingsCommand()); // Not working currently
package me.elb1to.ffa.command.manager; /** * @author Elb1to * @since 11/24/2023 */ public class CommandManager { private final FfaPlugin plugin; private final PaperCommandManager manager; public CommandManager(FfaPlugin plugin) { this.plugin = plugin; this.manager = new PaperCommandManager(plugin); load(); } private void load() { manager.getCommandCompletions().registerCompletion("kits", context -> new ArrayList<>(plugin.getKitManager().getKits().values()) .stream() .map(Kit::getName) .collect(Collectors.toList()) ); manager.getCommandCompletions().registerCompletion("maps", context -> plugin.getMapManager().getMaps() .stream() .map(FfaMap::getName) .collect(Collectors.toList()) ); manager.getCommandContexts().registerContext(Kit.class, context -> plugin.getKitManager().get(context.popFirstArg())); manager.getCommandContexts().registerContext(FfaMap.class, context -> plugin.getMapManager().getByName(context.popFirstArg())); manager.registerCommand(new FfaCommand()); manager.registerCommand(new KitCommand()); manager.registerCommand(new MapCommand()); manager.registerCommand(new StatsCommand()); // Unfinished command //manager.registerCommand(new SettingsCommand()); // Not working currently
manager.registerCommand(new BuildModeCommand());
5
2023-11-28 16:53:29+00:00
8k
daironpf/SocialSeed
Backend/src/test/java/com/social/seed/service/SocialUserServiceTest.java
[ { "identifier": "SocialUser", "path": "Backend/src/main/java/com/social/seed/model/SocialUser.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Node\npublic class SocialUser {\n\n @Id\n @GeneratedValue(UUIDStringGenerator.class)\n @Property(\"identifier\")\n priva...
import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; import com.social.seed.model.SocialUser; import com.social.seed.repository.SocialUserRepository; import com.social.seed.utils.TestUtils; import com.social.seed.util.ResponseDTO; import com.social.seed.util.ResponseService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import java.util.Optional;
4,474
/* * Copyright 2011-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.social.seed.service; /** * Test class for the {@link SocialUserService}, focusing on testing individual methods and functionalities * for managing { SocialUsers }. * <p> * @author Dairon Pérez Frías * @since 2024-01-08 */ @ExtendWith(MockitoExtension.class) class SocialUserServiceTest { // Class under test @InjectMocks private SocialUserService underTest; // region dependencies @Mock
/* * Copyright 2011-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.social.seed.service; /** * Test class for the {@link SocialUserService}, focusing on testing individual methods and functionalities * for managing { SocialUsers }. * <p> * @author Dairon Pérez Frías * @since 2024-01-08 */ @ExtendWith(MockitoExtension.class) class SocialUserServiceTest { // Class under test @InjectMocks private SocialUserService underTest; // region dependencies @Mock
private SocialUserRepository socialUserRepository;
1
2023-12-04 21:47:54+00:00
8k
lunasaw/zlm-spring-boot-starter
src/main/java/io/github/lunasaw/zlm/hook/service/AbstractZlmHookService.java
[ { "identifier": "ServerNodeConfig", "path": "src/main/java/io/github/lunasaw/zlm/entity/ServerNodeConfig.java", "snippet": "@Data\npublic class ServerNodeConfig {\n /**\n * \n * The maximum size of RTP packets.\n */\n @JsonProperty(\"rtp.rtpMaxSize\")\n private String rtpRtpMaxSize;...
import io.github.lunasaw.zlm.entity.ServerNodeConfig; import io.github.lunasaw.zlm.hook.param.*; import io.github.lunasaw.zlm.hook.service.ZlmHookService; import lombok.extern.slf4j.Slf4j;
6,323
package io.github.lunasaw.zlm.hook.service; /** * @author luna * @version 1.0 * @date 2023/12/3 * @description: 默认的钩子服务实现 */ @Slf4j public abstract class AbstractZlmHookService implements ZlmHookService { @Override public void onServerKeepLive(OnServerKeepaliveHookParam param) { } @Override public HookResult onPlay(OnPlayHookParam param) { return HookResult.SUCCESS(); } @Override public HookResultForOnPublish onPublish(OnPublishHookParam param) { return HookResultForOnPublish.SUCCESS(); } @Override public void onStreamChanged(OnStreamChangedHookParam param) { } @Override public HookResultForStreamNoneReader onStreamNoneReader(OnStreamNoneReaderHookParam param) { return HookResultForStreamNoneReader.SUCCESS(); } @Override public void onStreamNotFound(OnStreamNotFoundHookParam param) { } @Override
package io.github.lunasaw.zlm.hook.service; /** * @author luna * @version 1.0 * @date 2023/12/3 * @description: 默认的钩子服务实现 */ @Slf4j public abstract class AbstractZlmHookService implements ZlmHookService { @Override public void onServerKeepLive(OnServerKeepaliveHookParam param) { } @Override public HookResult onPlay(OnPlayHookParam param) { return HookResult.SUCCESS(); } @Override public HookResultForOnPublish onPublish(OnPublishHookParam param) { return HookResultForOnPublish.SUCCESS(); } @Override public void onStreamChanged(OnStreamChangedHookParam param) { } @Override public HookResultForStreamNoneReader onStreamNoneReader(OnStreamNoneReaderHookParam param) { return HookResultForStreamNoneReader.SUCCESS(); } @Override public void onStreamNotFound(OnStreamNotFoundHookParam param) { } @Override
public void onServerStarted(ServerNodeConfig param) {
0
2023-12-02 08:25:38+00:00
8k
Hoto-Mocha/Re-ARranged-Pixel-Dungeon
SPD-classes/src/main/java/com/watabou/noosa/TextInput.java
[ { "identifier": "Script", "path": "SPD-classes/src/main/java/com/watabou/glscripts/Script.java", "snippet": "public class Script extends Program {\n\n\tprivate static final HashMap<Class<? extends Script>,Script> all =\n\t\t\tnew HashMap<>();\n\t\n\tprivate static Script curScript = null;\n\tprivate sta...
import com.badlogic.gdx.Files; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Container; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.TextArea; import com.badlogic.gdx.scenes.scene2d.ui.TextField; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.viewport.Viewport; import com.watabou.glscripts.Script; import com.watabou.glwrap.Blending; import com.watabou.glwrap.Quad; import com.watabou.glwrap.Texture; import com.watabou.noosa.ui.Component; import com.watabou.utils.DeviceCompat; import com.watabou.utils.FileUtils; import com.watabou.utils.Point;
7,072
@Override public void changed(ChangeEvent event, Actor actor) { BitmapFont f = Game.platform.getFont(size, textField.getText(), false, false); TextField.TextFieldStyle style = textField.getStyle(); if (f != style.font){ style.font = f; textField.setStyle(style); } } }); if (!multiline){ textField.setTextFieldListener(new TextField.TextFieldListener(){ public void keyTyped (TextField textField, char c){ if (c == '\r' || c == '\n'){ enterPressed(); } } }); } textField.setOnscreenKeyboard(new TextField.OnscreenKeyboard() { @Override public void show(boolean visible) { Game.platform.setOnscreenKeyboardVisible(visible); } }); container.setActor(textField); stage.setKeyboardFocus(textField); Game.platform.setOnscreenKeyboardVisible(true); } public void enterPressed(){ //do nothing by default }; public void setText(String text){ textField.setText(text); textField.setCursorPosition(textField.getText().length()); } public void setMaxLength(int maxLength){ textField.setMaxLength(maxLength); } public String getText(){ return textField.getText(); } public void copyToClipboard(){ if (textField.getSelection().isEmpty()) { textField.selectAll(); } textField.copy(); } public void pasteFromClipboard(){ String contents = Gdx.app.getClipboard().getContents(); if (contents == null) return; if (!textField.getSelection().isEmpty()){ //just use cut, but override clipboard textField.cut(); Gdx.app.getClipboard().setContents(contents); } String existing = textField.getText(); int cursorIdx = textField.getCursorPosition(); textField.setText(existing.substring(0, cursorIdx) + contents + existing.substring(cursorIdx)); textField.setCursorPosition(cursorIdx + contents.length()); } @Override protected void layout() { super.layout(); float contX = x; float contY = y; float contW = width; float contH = height; if (bg != null){ bg.x = x; bg.y = y; bg.size(width, height); contX += bg.marginLeft(); contY += bg.marginTop(); contW -= bg.marginHor(); contH -= bg.marginVer(); } float zoom = Camera.main.zoom; Camera c = camera(); if (c != null){ zoom = c.zoom; Point p = c.cameraToScreen(contX, contY); contX = p.x/zoom; contY = p.y/zoom; } container.align(Align.topLeft); container.setPosition(contX*zoom, (Game.height-(contY*zoom))); container.size(contW*zoom, contH*zoom); } @Override public void update() { super.update(); stage.act(Game.elapsed); } @Override public void draw() { super.draw(); Quad.releaseIndices();
/* * 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.watabou.noosa; //essentially contains a libGDX text input field, plus a PD-rendered background public class TextInput extends Component { private Stage stage; private Container container; private TextField textField; private Skin skin; private NinePatch bg; public TextInput( NinePatch bg, boolean multiline, int size ){ super(); this.bg = bg; add(bg); //use a custom viewport here to ensure stage camera matches game camera Viewport viewport = new Viewport() {}; viewport.setWorldSize(Game.width, Game.height); viewport.setScreenBounds(0, Game.bottomInset, Game.width, Game.height); viewport.setCamera(new OrthographicCamera()); stage = new Stage(viewport); Game.inputHandler.addInputProcessor(stage); container = new Container<TextField>(); stage.addActor(container); container.setTransform(true); skin = new Skin(FileUtils.getFileHandle(Files.FileType.Internal, "gdx/textfield.json")); TextField.TextFieldStyle style = skin.get(TextField.TextFieldStyle.class); style.font = Game.platform.getFont(size, "", false, false); style.background = null; textField = multiline ? new TextArea("", style) : new TextField("", style); textField.setProgrammaticChangeEvents(true); if (!multiline) textField.setAlignment(Align.center); textField.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { BitmapFont f = Game.platform.getFont(size, textField.getText(), false, false); TextField.TextFieldStyle style = textField.getStyle(); if (f != style.font){ style.font = f; textField.setStyle(style); } } }); if (!multiline){ textField.setTextFieldListener(new TextField.TextFieldListener(){ public void keyTyped (TextField textField, char c){ if (c == '\r' || c == '\n'){ enterPressed(); } } }); } textField.setOnscreenKeyboard(new TextField.OnscreenKeyboard() { @Override public void show(boolean visible) { Game.platform.setOnscreenKeyboardVisible(visible); } }); container.setActor(textField); stage.setKeyboardFocus(textField); Game.platform.setOnscreenKeyboardVisible(true); } public void enterPressed(){ //do nothing by default }; public void setText(String text){ textField.setText(text); textField.setCursorPosition(textField.getText().length()); } public void setMaxLength(int maxLength){ textField.setMaxLength(maxLength); } public String getText(){ return textField.getText(); } public void copyToClipboard(){ if (textField.getSelection().isEmpty()) { textField.selectAll(); } textField.copy(); } public void pasteFromClipboard(){ String contents = Gdx.app.getClipboard().getContents(); if (contents == null) return; if (!textField.getSelection().isEmpty()){ //just use cut, but override clipboard textField.cut(); Gdx.app.getClipboard().setContents(contents); } String existing = textField.getText(); int cursorIdx = textField.getCursorPosition(); textField.setText(existing.substring(0, cursorIdx) + contents + existing.substring(cursorIdx)); textField.setCursorPosition(cursorIdx + contents.length()); } @Override protected void layout() { super.layout(); float contX = x; float contY = y; float contW = width; float contH = height; if (bg != null){ bg.x = x; bg.y = y; bg.size(width, height); contX += bg.marginLeft(); contY += bg.marginTop(); contW -= bg.marginHor(); contH -= bg.marginVer(); } float zoom = Camera.main.zoom; Camera c = camera(); if (c != null){ zoom = c.zoom; Point p = c.cameraToScreen(contX, contY); contX = p.x/zoom; contY = p.y/zoom; } container.align(Align.topLeft); container.setPosition(contX*zoom, (Game.height-(contY*zoom))); container.size(contW*zoom, contH*zoom); } @Override public void update() { super.update(); stage.act(Game.elapsed); } @Override public void draw() { super.draw(); Quad.releaseIndices();
Script.unuse();
0
2023-11-27 05:56:58+00:00
8k
Tofaa2/EntityLib
src/main/java/me/tofaa/entitylib/meta/Metadata.java
[ { "identifier": "EntityLib", "path": "src/main/java/me/tofaa/entitylib/EntityLib.java", "snippet": "public final class EntityLib {\n\n private EntityLib() {}\n private static final HashMap<Integer, EntityMeta> metadata = new HashMap<>();\n private static final Map<UUID, WrapperEntity> entities ...
import com.github.retrooper.packetevents.protocol.entity.data.EntityData; import com.github.retrooper.packetevents.protocol.entity.data.EntityDataType; import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata; import me.tofaa.entitylib.EntityLib; import me.tofaa.entitylib.entity.WrapperEntity; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
4,730
package me.tofaa.entitylib.meta; @SuppressWarnings("unchecked") public class Metadata { private final Map<Byte, EntityData> metadataMap = new ConcurrentHashMap<>(); private final int entityId; public Metadata(int entityId) { this.entityId = entityId; } public <T> T getIndex(byte index, @Nullable T defaultValue) { EntityData entityData = metadataMap.get(index); if (entityData == null) return defaultValue; if (entityData.getValue() == null) return defaultValue; return (T) entityData.getValue(); } public <T> void setIndex(byte index, @NotNull EntityDataType<T> dataType, T value) { EntityData data = new EntityData(index, dataType, value); this.metadataMap.put(index, data);
package me.tofaa.entitylib.meta; @SuppressWarnings("unchecked") public class Metadata { private final Map<Byte, EntityData> metadataMap = new ConcurrentHashMap<>(); private final int entityId; public Metadata(int entityId) { this.entityId = entityId; } public <T> T getIndex(byte index, @Nullable T defaultValue) { EntityData entityData = metadataMap.get(index); if (entityData == null) return defaultValue; if (entityData.getValue() == null) return defaultValue; return (T) entityData.getValue(); } public <T> void setIndex(byte index, @NotNull EntityDataType<T> dataType, T value) { EntityData data = new EntityData(index, dataType, value); this.metadataMap.put(index, data);
WrapperEntity e = EntityLib.getEntity(entityId);
1
2023-11-27 02:17:41+00:00
8k
minlwin/onestop-batch6
s02-backend/member-api/src/main/java/com/jdc/shop/model/service/CatalogService.java
[ { "identifier": "CatalogDetailsDto", "path": "s02-backend/member-api/src/main/java/com/jdc/shop/api/anonymous/output/CatalogDetailsDto.java", "snippet": "@Data\npublic class CatalogDetailsDto {\n\n\tprivate CatalogDto baseInfo;\n\tprivate List<String> images;\n\t\n\tpublic static CatalogDetailsDto from(...
import java.time.LocalDateTime; import java.util.List; import java.util.function.Function; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import com.jdc.shop.api.anonymous.output.CatalogDetailsDto; import com.jdc.shop.api.anonymous.output.CatalogDto; import com.jdc.shop.api.employee.input.CatalogForm; import com.jdc.shop.api.employee.input.CatalogSearch; import com.jdc.shop.api.owner.output.GoldPriceDto; import com.jdc.shop.model.entity.Catalog; import com.jdc.shop.model.entity.Catalog_; import com.jdc.shop.model.entity.GoldPrice; import com.jdc.shop.model.entity.GoldPrice_; import com.jdc.shop.model.repo.CatalogRepo; import com.jdc.shop.model.repo.CategoryRepo; import com.jdc.shop.model.repo.GoldPriceRepo; import com.jdc.shop.utils.exceptions.ApiBusinessException; import com.jdc.shop.utils.io.DataModificationResult; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery;
3,640
package com.jdc.shop.model.service; @Service @Transactional public class CatalogService { @Autowired private CatalogRepo catalogRepo; @Autowired private CategoryRepo categoryRepo; @Autowired private GoldPriceRepo goldPriceRepo; @Autowired private CatalogPriceChangeService priceChangeService; @Autowired private PhotoUploadService photoUploadService; @Transactional(readOnly = true) public Page<CatalogDto> search(CatalogSearch form, int page, int size) { Function<CriteriaBuilder, CriteriaQuery<Long>> countFunc = cb -> { var cq = cb.createQuery(Long.class); var root = cq.from(Catalog.class); cq.select(cb.count(root.get(Catalog_.id))); cq.where(form.where(cb, root)); return cq; }; Function<CriteriaBuilder, CriteriaQuery<CatalogDto>> queryFunc = cb -> { var cq = cb.createQuery(CatalogDto.class); var root = cq.from(Catalog.class); CatalogDto.select(cq, root); cq.where(form.where(cb, root)); cq.orderBy(cb.asc(root.get(Catalog_.name))); return cq; }; return catalogRepo.search(queryFunc, countFunc, page, size); } @Transactional(readOnly = true) public CatalogDetailsDto findById(int id) { return catalogRepo.findById(id).map(CatalogDetailsDto::from) .orElseThrow(() -> new ApiBusinessException("Invalid catalog id.")); } public DataModificationResult<Integer> create(CatalogForm form) { var goldPrice = findGoldPrice(); var category = categoryRepo.findById(form.getCategoryId()) .orElseThrow(() -> new ApiBusinessException("Invalid category id.")); var entity = form.entity(); entity.setCategory(category); entity = catalogRepo.saveAndFlush(entity); priceChangeService.calculate(entity.getId(), goldPrice); return new DataModificationResult<Integer>(entity.getId(), "Catalog has been created."); } public DataModificationResult<Integer> update(int id, CatalogForm form) { var goldPrice = findGoldPrice(); var entity = catalogRepo.findById(id) .orElseThrow(() -> new ApiBusinessException("Invalid catalog id.")); var category = categoryRepo.findById(form.getCategoryId()) .orElseThrow(() -> new ApiBusinessException("Invalid category id.")); entity.setCategory(category); entity.setName(form.getName()); entity.setDescription(form.getDescription()); entity.setBasedPrice(form.getBasedPrice()); entity.setPurity(form.getPurity()); entity.setWeight(form.getWeight()); entity.setLostWeight(form.getLostWeight()); entity.setGoldSmithFees(form.getGoldSmithFees()); entity = catalogRepo.saveAndFlush(entity); priceChangeService.calculate(entity.getId(), goldPrice); return new DataModificationResult<Integer>(entity.getId(), "Catalog has been updated."); } public DataModificationResult<Integer> uploadPhoto(int id, List<MultipartFile> files) { var entity = catalogRepo.findById(id) .orElseThrow(() -> new ApiBusinessException("Invalid catalog id.")); var images = photoUploadService.saveCatalogImages(id, files); entity.getImages().addAll(images); if(!StringUtils.hasLength(entity.getCoverImage()) && !entity.getImages().isEmpty()) { entity.setCoverImage(entity.getImages().get(0)); } return new DataModificationResult<Integer>(entity.getId(), "Catalog has been updated."); } private GoldPriceDto findGoldPrice() {
package com.jdc.shop.model.service; @Service @Transactional public class CatalogService { @Autowired private CatalogRepo catalogRepo; @Autowired private CategoryRepo categoryRepo; @Autowired private GoldPriceRepo goldPriceRepo; @Autowired private CatalogPriceChangeService priceChangeService; @Autowired private PhotoUploadService photoUploadService; @Transactional(readOnly = true) public Page<CatalogDto> search(CatalogSearch form, int page, int size) { Function<CriteriaBuilder, CriteriaQuery<Long>> countFunc = cb -> { var cq = cb.createQuery(Long.class); var root = cq.from(Catalog.class); cq.select(cb.count(root.get(Catalog_.id))); cq.where(form.where(cb, root)); return cq; }; Function<CriteriaBuilder, CriteriaQuery<CatalogDto>> queryFunc = cb -> { var cq = cb.createQuery(CatalogDto.class); var root = cq.from(Catalog.class); CatalogDto.select(cq, root); cq.where(form.where(cb, root)); cq.orderBy(cb.asc(root.get(Catalog_.name))); return cq; }; return catalogRepo.search(queryFunc, countFunc, page, size); } @Transactional(readOnly = true) public CatalogDetailsDto findById(int id) { return catalogRepo.findById(id).map(CatalogDetailsDto::from) .orElseThrow(() -> new ApiBusinessException("Invalid catalog id.")); } public DataModificationResult<Integer> create(CatalogForm form) { var goldPrice = findGoldPrice(); var category = categoryRepo.findById(form.getCategoryId()) .orElseThrow(() -> new ApiBusinessException("Invalid category id.")); var entity = form.entity(); entity.setCategory(category); entity = catalogRepo.saveAndFlush(entity); priceChangeService.calculate(entity.getId(), goldPrice); return new DataModificationResult<Integer>(entity.getId(), "Catalog has been created."); } public DataModificationResult<Integer> update(int id, CatalogForm form) { var goldPrice = findGoldPrice(); var entity = catalogRepo.findById(id) .orElseThrow(() -> new ApiBusinessException("Invalid catalog id.")); var category = categoryRepo.findById(form.getCategoryId()) .orElseThrow(() -> new ApiBusinessException("Invalid category id.")); entity.setCategory(category); entity.setName(form.getName()); entity.setDescription(form.getDescription()); entity.setBasedPrice(form.getBasedPrice()); entity.setPurity(form.getPurity()); entity.setWeight(form.getWeight()); entity.setLostWeight(form.getLostWeight()); entity.setGoldSmithFees(form.getGoldSmithFees()); entity = catalogRepo.saveAndFlush(entity); priceChangeService.calculate(entity.getId(), goldPrice); return new DataModificationResult<Integer>(entity.getId(), "Catalog has been updated."); } public DataModificationResult<Integer> uploadPhoto(int id, List<MultipartFile> files) { var entity = catalogRepo.findById(id) .orElseThrow(() -> new ApiBusinessException("Invalid catalog id.")); var images = photoUploadService.saveCatalogImages(id, files); entity.getImages().addAll(images); if(!StringUtils.hasLength(entity.getCoverImage()) && !entity.getImages().isEmpty()) { entity.setCoverImage(entity.getImages().get(0)); } return new DataModificationResult<Integer>(entity.getId(), "Catalog has been updated."); } private GoldPriceDto findGoldPrice() {
Function<CriteriaBuilder, CriteriaQuery<GoldPrice>> queryFunc = cb -> {
6
2023-12-04 06:59:55+00:00
8k
WiIIiam278/HuskClaims
common/src/main/java/net/william278/huskclaims/command/TrustableTabCompletable.java
[ { "identifier": "Settings", "path": "common/src/main/java/net/william278/huskclaims/config/Settings.java", "snippet": "@SuppressWarnings(\"FieldMayBeFinal\")\n@Getter\n@Configuration\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class Settings {\n\n static final String CONFIG_HEADER...
import net.william278.huskclaims.config.Settings; import net.william278.huskclaims.user.CommandUser; import net.william278.huskclaims.user.OnlineUser; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.UUID;
4,938
/* * 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.command; public interface TrustableTabCompletable extends UserListTabCompletable { @Nullable @Override default List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) {
/* * 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.command; public interface TrustableTabCompletable extends UserListTabCompletable { @Nullable @Override default List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) {
final OnlineUser onlineUser = (OnlineUser) user;
2
2023-11-28 01:09:43+00:00
8k
realgpp/aem-cdn-cache-invalidator
core/src/main/java/com/baglio/autocdninvalidator/core/listeners/AbstractListener.java
[ { "identifier": "LoggingHelper", "path": "core/src/main/java/com/baglio/autocdninvalidator/core/helpers/LoggingHelper.java", "snippet": "public class LoggingHelper {\n\n private final Logger logger;\n\n /**\n * Construct helper for the given class to log messages to. This will create a Logger named ...
import com.baglio.autocdninvalidator.core.helpers.LoggingHelper; import com.baglio.autocdninvalidator.core.jobs.EditorialAssetInvalidationJobConsumer; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.lang.StringUtils; import org.apache.jackrabbit.vault.util.JcrConstants; import org.apache.sling.event.jobs.Job; import org.apache.sling.event.jobs.JobManager;
4,035
package com.baglio.autocdninvalidator.core.listeners; /** * Abstract base class for listeners that process repository change events. Provides common logic to filter paths, * create jobs, and offload work. */ public abstract class AbstractListener { /** * Gives the Logger. * * @return the Logger */ abstract LoggingHelper getLogger(); /** * Gets the OSGi JobManager service to create jobs. * * @return the JobManager */ abstract JobManager getJobManager(); /** * Processes a set of resource paths when changed in the repository. Applies configured regex filter and offloads work * via job. * * @param paths the resource paths changed * @param filterRegex regex to filter relevant paths * @param jobTopic job topic to use for offloading * @return true if a job was scheduled, false otherwise */ public boolean processEvent(final Set<String> paths, final String filterRegex, final String jobTopic) { Set<String> resourcePaths = filterPaths(paths, filterRegex); if (resourcePaths.isEmpty()) { getLogger().warn("No resources to process for paths={} with filter regex={}", paths, filterRegex); return false; } Map<String, Object> jobprops = new HashMap<>();
package com.baglio.autocdninvalidator.core.listeners; /** * Abstract base class for listeners that process repository change events. Provides common logic to filter paths, * create jobs, and offload work. */ public abstract class AbstractListener { /** * Gives the Logger. * * @return the Logger */ abstract LoggingHelper getLogger(); /** * Gets the OSGi JobManager service to create jobs. * * @return the JobManager */ abstract JobManager getJobManager(); /** * Processes a set of resource paths when changed in the repository. Applies configured regex filter and offloads work * via job. * * @param paths the resource paths changed * @param filterRegex regex to filter relevant paths * @param jobTopic job topic to use for offloading * @return true if a job was scheduled, false otherwise */ public boolean processEvent(final Set<String> paths, final String filterRegex, final String jobTopic) { Set<String> resourcePaths = filterPaths(paths, filterRegex); if (resourcePaths.isEmpty()) { getLogger().warn("No resources to process for paths={} with filter regex={}", paths, filterRegex); return false; } Map<String, Object> jobprops = new HashMap<>();
jobprops.put(EditorialAssetInvalidationJobConsumer.JOB_PROPERTY_PATHS, resourcePaths);
1
2023-11-27 14:47:45+00:00
8k
Manzzx/multi-channel-message-reach
metax-gateway/src/main/java/com/metax/gateway/filter/XssFilter.java
[ { "identifier": "StringUtils", "path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/utils/StringUtils.java", "snippet": "public class StringUtils extends org.apache.commons.lang3.StringUtils\n{\n /** 空字符串 */\n private static final String NULLSTR = \"\";\n\n /** 下划线 */\n ...
import java.nio.charset.StandardCharsets; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.core.io.buffer.DefaultDataBufferFactory; import org.springframework.core.io.buffer.NettyDataBufferFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpRequestDecorator; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import com.metax.common.core.utils.StringUtils; import com.metax.common.core.utils.html.EscapeUtil; import com.metax.gateway.config.properties.XssProperties; import io.netty.buffer.ByteBufAllocator; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono;
6,158
package com.metax.gateway.filter; /** * 跨站脚本过滤器 * * @author ruoyi */ @Component @ConditionalOnProperty(value = "security.xss.enabled", havingValue = "true") public class XssFilter implements GlobalFilter, Ordered { // 跨站脚本的 xss 配置,nacos自行添加 @Autowired private XssProperties xss; @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); // xss开关未开启 或 通过nacos关闭,不过滤 if (!xss.getEnabled()) { return chain.filter(exchange); } // GET DELETE 不过滤 HttpMethod method = request.getMethod(); if (method == null || method == HttpMethod.GET || method == HttpMethod.DELETE) { return chain.filter(exchange); } // 非json类型,不过滤 if (!isJsonRequest(exchange)) { return chain.filter(exchange); } // excludeUrls 不过滤 String url = request.getURI().getPath(); if (StringUtils.matches(url, xss.getExcludeUrls())) { return chain.filter(exchange); } ServerHttpRequestDecorator httpRequestDecorator = requestDecorator(exchange); return chain.filter(exchange.mutate().request(httpRequestDecorator).build()); } private ServerHttpRequestDecorator requestDecorator(ServerWebExchange exchange) { ServerHttpRequestDecorator serverHttpRequestDecorator = new ServerHttpRequestDecorator(exchange.getRequest()) { @Override public Flux<DataBuffer> getBody() { Flux<DataBuffer> body = super.getBody(); return body.buffer().map(dataBuffers -> { DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory(); DataBuffer join = dataBufferFactory.join(dataBuffers); byte[] content = new byte[join.readableByteCount()]; join.read(content); DataBufferUtils.release(join); String bodyStr = new String(content, StandardCharsets.UTF_8); // 防xss攻击过滤
package com.metax.gateway.filter; /** * 跨站脚本过滤器 * * @author ruoyi */ @Component @ConditionalOnProperty(value = "security.xss.enabled", havingValue = "true") public class XssFilter implements GlobalFilter, Ordered { // 跨站脚本的 xss 配置,nacos自行添加 @Autowired private XssProperties xss; @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); // xss开关未开启 或 通过nacos关闭,不过滤 if (!xss.getEnabled()) { return chain.filter(exchange); } // GET DELETE 不过滤 HttpMethod method = request.getMethod(); if (method == null || method == HttpMethod.GET || method == HttpMethod.DELETE) { return chain.filter(exchange); } // 非json类型,不过滤 if (!isJsonRequest(exchange)) { return chain.filter(exchange); } // excludeUrls 不过滤 String url = request.getURI().getPath(); if (StringUtils.matches(url, xss.getExcludeUrls())) { return chain.filter(exchange); } ServerHttpRequestDecorator httpRequestDecorator = requestDecorator(exchange); return chain.filter(exchange.mutate().request(httpRequestDecorator).build()); } private ServerHttpRequestDecorator requestDecorator(ServerWebExchange exchange) { ServerHttpRequestDecorator serverHttpRequestDecorator = new ServerHttpRequestDecorator(exchange.getRequest()) { @Override public Flux<DataBuffer> getBody() { Flux<DataBuffer> body = super.getBody(); return body.buffer().map(dataBuffers -> { DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory(); DataBuffer join = dataBufferFactory.join(dataBuffers); byte[] content = new byte[join.readableByteCount()]; join.read(content); DataBufferUtils.release(join); String bodyStr = new String(content, StandardCharsets.UTF_8); // 防xss攻击过滤
bodyStr = EscapeUtil.clean(bodyStr);
1
2023-12-04 05:10:13+00:00
8k
ydb-platform/yoj-project
repository-ydb-v1/src/main/java/tech/ydb/yoj/repository/ydb/client/YdbSessionManager.java
[ { "identifier": "QueryInterruptedException", "path": "repository/src/main/java/tech/ydb/yoj/repository/db/exception/QueryInterruptedException.java", "snippet": "public class QueryInterruptedException extends RepositoryException {\n public QueryInterruptedException(String message) {\n super(mes...
import com.yandex.ydb.core.Result; import com.yandex.ydb.core.grpc.GrpcTransport; import com.yandex.ydb.table.Session; import com.yandex.ydb.table.TableClient; import com.yandex.ydb.table.rpc.grpc.GrpcTableRpc; import com.yandex.ydb.table.stats.SessionPoolStats; import lombok.Getter; import lombok.NonNull; import tech.ydb.yoj.repository.db.exception.QueryInterruptedException; import tech.ydb.yoj.repository.db.exception.RetryableException; import tech.ydb.yoj.repository.db.exception.UnavailableException; import tech.ydb.yoj.repository.ydb.YdbConfig; import tech.ydb.yoj.repository.ydb.metrics.GaugeSupplierCollector; import java.time.Duration; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; import static tech.ydb.yoj.repository.ydb.client.YdbValidator.checkGrpcContextStatus; import static tech.ydb.yoj.repository.ydb.client.YdbValidator.validate; import static tech.ydb.yoj.util.lang.Interrupts.isThreadInterrupted;
4,230
package tech.ydb.yoj.repository.ydb.client; public class YdbSessionManager implements SessionManager { private static final GaugeSupplierCollector sessionStatCollector = GaugeSupplierCollector.build() .namespace("ydb") .subsystem("session_manager") .name("pool_stats") .help("Session pool statistics") .labelNames("type") .register(); private final YdbConfig config; private final GrpcTableRpc tableRpc; @Getter private TableClient tableClient; public YdbSessionManager(@NonNull YdbConfig config, GrpcTransport transport) { this.config = config; this.tableRpc = GrpcTableRpc.useTransport(transport); this.tableClient = createClient(); sessionStatCollector .labels("pending_acquire_count").supplier(() -> tableClient.getSessionPoolStats().getPendingAcquireCount()) .labels("acquired_count").supplier(() -> tableClient.getSessionPoolStats().getAcquiredCount()) .labels("idle_count").supplier(() -> tableClient.getSessionPoolStats().getIdleCount()) .labels("disconnected_count").supplier(() -> tableClient.getSessionPoolStats().getDisconnectedCount()); } private TableClient createClient() { return TableClient.newClient(tableRpc) .keepQueryText(false) .queryCacheSize(0) .sessionCreationMaxRetries(config.getSessionCreationMaxRetries()) .sessionKeepAliveTime(config.getSessionKeepAliveTime()) .sessionMaxIdleTime(config.getSessionMaxIdleTime()) .sessionPoolSize(config.getSessionPoolMin(), config.getSessionPoolMax()) .build(); } @Override public Session getSession() { CompletableFuture<Result<Session>> future = tableClient.getOrCreateSession(getSessionTimeout()); try { Result<Session> result = future.get(); validate("session create", result.getCode(), result.toString()); return result.expect("Can't get session"); } catch (CancellationException | CompletionException | ExecutionException | InterruptedException e) { // We need to cancel future bacause in other case we can get session leak future.cancel(false); if (isThreadInterrupted(e)) { Thread.currentThread().interrupt(); throw new QueryInterruptedException("get session interrupted", e); } checkGrpcContextStatus(e.getMessage(), e); throw new UnavailableException("DB is unavailable", e); } } private Duration getSessionTimeout() { Duration max = Duration.ofMinutes(5); Duration configTimeout = config.getSessionCreationTimeout(); return Duration.ZERO.equals(configTimeout) || configTimeout.compareTo(max) > 0 ? max : configTimeout; } @Override public void release(Session session) { session.release(); } @Override //todo: client load balancing public void warmup() { Session session = null; int maxRetrySessionCreateCount = 10; for (int i = 0; i < maxRetrySessionCreateCount; i++) { try { session = getSession(); break;
package tech.ydb.yoj.repository.ydb.client; public class YdbSessionManager implements SessionManager { private static final GaugeSupplierCollector sessionStatCollector = GaugeSupplierCollector.build() .namespace("ydb") .subsystem("session_manager") .name("pool_stats") .help("Session pool statistics") .labelNames("type") .register(); private final YdbConfig config; private final GrpcTableRpc tableRpc; @Getter private TableClient tableClient; public YdbSessionManager(@NonNull YdbConfig config, GrpcTransport transport) { this.config = config; this.tableRpc = GrpcTableRpc.useTransport(transport); this.tableClient = createClient(); sessionStatCollector .labels("pending_acquire_count").supplier(() -> tableClient.getSessionPoolStats().getPendingAcquireCount()) .labels("acquired_count").supplier(() -> tableClient.getSessionPoolStats().getAcquiredCount()) .labels("idle_count").supplier(() -> tableClient.getSessionPoolStats().getIdleCount()) .labels("disconnected_count").supplier(() -> tableClient.getSessionPoolStats().getDisconnectedCount()); } private TableClient createClient() { return TableClient.newClient(tableRpc) .keepQueryText(false) .queryCacheSize(0) .sessionCreationMaxRetries(config.getSessionCreationMaxRetries()) .sessionKeepAliveTime(config.getSessionKeepAliveTime()) .sessionMaxIdleTime(config.getSessionMaxIdleTime()) .sessionPoolSize(config.getSessionPoolMin(), config.getSessionPoolMax()) .build(); } @Override public Session getSession() { CompletableFuture<Result<Session>> future = tableClient.getOrCreateSession(getSessionTimeout()); try { Result<Session> result = future.get(); validate("session create", result.getCode(), result.toString()); return result.expect("Can't get session"); } catch (CancellationException | CompletionException | ExecutionException | InterruptedException e) { // We need to cancel future bacause in other case we can get session leak future.cancel(false); if (isThreadInterrupted(e)) { Thread.currentThread().interrupt(); throw new QueryInterruptedException("get session interrupted", e); } checkGrpcContextStatus(e.getMessage(), e); throw new UnavailableException("DB is unavailable", e); } } private Duration getSessionTimeout() { Duration max = Duration.ofMinutes(5); Duration configTimeout = config.getSessionCreationTimeout(); return Duration.ZERO.equals(configTimeout) || configTimeout.compareTo(max) > 0 ? max : configTimeout; } @Override public void release(Session session) { session.release(); } @Override //todo: client load balancing public void warmup() { Session session = null; int maxRetrySessionCreateCount = 10; for (int i = 0; i < maxRetrySessionCreateCount; i++) { try { session = getSession(); break;
} catch (RetryableException ex) {
1
2023-12-05 15:57:58+00:00
8k
Vera-Firefly/PojavLauncher-Experimental-Edition
app_pojavlauncher/src/main/java/com/kdt/mcgui/ProgressLayout.java
[ { "identifier": "ExtraCore", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/extra/ExtraCore.java", "snippet": "@SuppressWarnings({\"rawtypes\", \"unchecked\"})\npublic final class ExtraCore {\n // No unwanted instantiation\n private ExtraCore(){}\n\n // Singleton instance\n pri...
import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.collection.ArrayMap; import androidx.constraintlayout.widget.ConstraintLayout; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.extra.ExtraCore; import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper; import net.kdt.pojavlaunch.progresskeeper.ProgressListener; import net.kdt.pojavlaunch.progresskeeper.TaskCountListener; import net.kdt.pojavlaunch.services.ProgressService; import java.util.ArrayList;
3,866
package com.kdt.mcgui; /** Class staring at specific values and automatically show something if the progress is present * Since progress is posted in a specific way, The packing/unpacking is handheld by the class * * This class relies on ExtraCore for its behavior. */ public class ProgressLayout extends ConstraintLayout implements View.OnClickListener, TaskCountListener{ public static final String UNPACK_RUNTIME = "unpack_runtime"; public static final String DOWNLOAD_MINECRAFT = "download_minecraft"; public static final String DOWNLOAD_VERSION_LIST = "download_verlist"; public static final String AUTHENTICATE_MICROSOFT = "authenticate_microsoft"; public static final String INSTALL_MODPACK = "install_modpack"; public static final String EXTRACT_COMPONENTS = "extract_components"; public static final String EXTRACT_SINGLE_FILES = "extract_single_files"; public ProgressLayout(@NonNull Context context) { super(context); init(); } public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private final ArrayList<LayoutProgressListener> mMap = new ArrayList<>(); private LinearLayout mLinearLayout; private TextView mTaskNumberDisplayer; private ImageView mFlipArrow; public void observe(String progressKey){ mMap.add(new LayoutProgressListener(progressKey)); } public void cleanUpObservers() { for(LayoutProgressListener progressListener : mMap) { ProgressKeeper.removeListener(progressListener.progressKey, progressListener); } } public boolean hasProcesses(){ return ProgressKeeper.getTaskCount() > 0; } private void init(){ inflate(getContext(), R.layout.view_progress, this); mLinearLayout = findViewById(R.id.progress_linear_layout); mTaskNumberDisplayer = findViewById(R.id.progress_textview); mFlipArrow = findViewById(R.id.progress_flip_arrow); setBackgroundColor(getResources().getColor(R.color.background_bottom_bar)); setOnClickListener(this); } /** Update the progress bar content */ public static void setProgress(String progressKey, int progress){ ProgressKeeper.submitProgress(progressKey, progress, -1, (Object)null); } /** Update the text and progress content */ public static void setProgress(String progressKey, int progress, @StringRes int resource, Object... message){ ProgressKeeper.submitProgress(progressKey, progress, resource, message); } /** Update the text and progress content */ public static void setProgress(String progressKey, int progress, String message){ setProgress(progressKey,progress, -1, message); } /** Update the text and progress content */ public static void clearProgress(String progressKey){ setProgress(progressKey, -1, -1); } @Override public void onClick(View v) { mLinearLayout.setVisibility(mLinearLayout.getVisibility() == GONE ? VISIBLE : GONE); mFlipArrow.setRotation(mLinearLayout.getVisibility() == GONE? 0 : 180); } @Override public void onUpdateTaskCount(int tc) { post(()->{ if(tc > 0) { mTaskNumberDisplayer.setText(getContext().getString(R.string.progresslayout_tasks_in_progress, tc)); setVisibility(VISIBLE); }else setVisibility(GONE); }); }
package com.kdt.mcgui; /** Class staring at specific values and automatically show something if the progress is present * Since progress is posted in a specific way, The packing/unpacking is handheld by the class * * This class relies on ExtraCore for its behavior. */ public class ProgressLayout extends ConstraintLayout implements View.OnClickListener, TaskCountListener{ public static final String UNPACK_RUNTIME = "unpack_runtime"; public static final String DOWNLOAD_MINECRAFT = "download_minecraft"; public static final String DOWNLOAD_VERSION_LIST = "download_verlist"; public static final String AUTHENTICATE_MICROSOFT = "authenticate_microsoft"; public static final String INSTALL_MODPACK = "install_modpack"; public static final String EXTRACT_COMPONENTS = "extract_components"; public static final String EXTRACT_SINGLE_FILES = "extract_single_files"; public ProgressLayout(@NonNull Context context) { super(context); init(); } public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private final ArrayList<LayoutProgressListener> mMap = new ArrayList<>(); private LinearLayout mLinearLayout; private TextView mTaskNumberDisplayer; private ImageView mFlipArrow; public void observe(String progressKey){ mMap.add(new LayoutProgressListener(progressKey)); } public void cleanUpObservers() { for(LayoutProgressListener progressListener : mMap) { ProgressKeeper.removeListener(progressListener.progressKey, progressListener); } } public boolean hasProcesses(){ return ProgressKeeper.getTaskCount() > 0; } private void init(){ inflate(getContext(), R.layout.view_progress, this); mLinearLayout = findViewById(R.id.progress_linear_layout); mTaskNumberDisplayer = findViewById(R.id.progress_textview); mFlipArrow = findViewById(R.id.progress_flip_arrow); setBackgroundColor(getResources().getColor(R.color.background_bottom_bar)); setOnClickListener(this); } /** Update the progress bar content */ public static void setProgress(String progressKey, int progress){ ProgressKeeper.submitProgress(progressKey, progress, -1, (Object)null); } /** Update the text and progress content */ public static void setProgress(String progressKey, int progress, @StringRes int resource, Object... message){ ProgressKeeper.submitProgress(progressKey, progress, resource, message); } /** Update the text and progress content */ public static void setProgress(String progressKey, int progress, String message){ setProgress(progressKey,progress, -1, message); } /** Update the text and progress content */ public static void clearProgress(String progressKey){ setProgress(progressKey, -1, -1); } @Override public void onClick(View v) { mLinearLayout.setVisibility(mLinearLayout.getVisibility() == GONE ? VISIBLE : GONE); mFlipArrow.setRotation(mLinearLayout.getVisibility() == GONE? 0 : 180); } @Override public void onUpdateTaskCount(int tc) { post(()->{ if(tc > 0) { mTaskNumberDisplayer.setText(getContext().getString(R.string.progresslayout_tasks_in_progress, tc)); setVisibility(VISIBLE); }else setVisibility(GONE); }); }
class LayoutProgressListener implements ProgressListener {
2
2023-12-01 16:16:12+00:00
8k
kawashirov/distant-horizons
fabric/src/main/java/com/seibel/distanthorizons/fabric/mixins/client/MixinClientPacketListener.java
[ { "identifier": "ClientLevelWrapper", "path": "common/src/main/java/com/seibel/distanthorizons/common/wrappers/world/ClientLevelWrapper.java", "snippet": "public class ClientLevelWrapper implements IClientLevelWrapper\n{\n\tprivate static final Logger LOGGER = DhLoggerBuilder.getLogger(ClientLevelWrappe...
import com.seibel.distanthorizons.common.wrappers.world.ClientLevelWrapper; import com.seibel.distanthorizons.core.api.internal.ClientApi; import com.seibel.distanthorizons.core.api.internal.SharedApi; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.ClientPacketListener; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IClientLevelWrapper; import net.minecraft.world.level.chunk.LevelChunk; import com.seibel.distanthorizons.common.wrappers.chunk.ChunkWrapper;
6,404
package com.seibel.distanthorizons.fabric.mixins.client; #if POST_MC_1_20_1 #endif @Mixin(ClientPacketListener.class) public class MixinClientPacketListener { @Shadow private ClientLevel level; @Inject(method = "handleLogin", at = @At("RETURN")) void onHandleLoginEnd(CallbackInfo ci) { ClientApi.INSTANCE.onClientOnlyConnected(); } @Inject(method = "handleRespawn", at = @At("HEAD"))
package com.seibel.distanthorizons.fabric.mixins.client; #if POST_MC_1_20_1 #endif @Mixin(ClientPacketListener.class) public class MixinClientPacketListener { @Shadow private ClientLevel level; @Inject(method = "handleLogin", at = @At("RETURN")) void onHandleLoginEnd(CallbackInfo ci) { ClientApi.INSTANCE.onClientOnlyConnected(); } @Inject(method = "handleRespawn", at = @At("HEAD"))
void onHandleRespawnStart(CallbackInfo ci) { ClientApi.INSTANCE.clientLevelUnloadEvent(ClientLevelWrapper.getWrapper(this.level)); }
0
2023-12-04 11:41:46+00:00
8k
gaojindeng/netty-spring-boot-starter
netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/DefaultNettyContainer.java
[ { "identifier": "BaseNettyClient", "path": "netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/client/BaseNettyClient.java", "snippet": "public abstract class BaseNettyClient extends AbstractNetty implements NettyClient {\n private static final Logger log = LoggerFactory.getLogger(Bas...
import io.github.gaojindeng.netty.client.BaseNettyClient; import io.github.gaojindeng.netty.client.LongNettyClient; import io.github.gaojindeng.netty.client.NettyClient; import io.github.gaojindeng.netty.client.ShortNettyClient; import io.github.gaojindeng.netty.properties.NettyClientConfig; import io.github.gaojindeng.netty.properties.NettyConfigProperties; import io.github.gaojindeng.netty.properties.NettyServerConfig; import io.github.gaojindeng.netty.server.AbstractNettyServer; import io.github.gaojindeng.netty.server.NettyServer; import org.springframework.beans.factory.DisposableBean; import java.util.HashMap; import java.util.Map;
3,861
package io.github.gaojindeng.netty; /** * @author gjd */ public class DefaultNettyContainer implements DisposableBean { private NettyConfigProperties nettyConfigProperties; private NettyServer defaultNettyServer; private NettyClient defaultNettyClient; private final Map<String, NettyServer> nettyServerMap = new HashMap<>(); private final Map<String, NettyClient> nettyClientMap = new HashMap<>(); public DefaultNettyContainer(NettyConfigProperties nettyConfigProperties) { this.nettyConfigProperties = nettyConfigProperties; initNettyServer(nettyConfigProperties.getServer()); initNettyClient(nettyConfigProperties.getClient()); } private void initNettyClient(NettyConfigProperties.NettyClientProperties client) { if (client == null) { return; } defaultNettyClient = getDefaultNettyClient(client); if (defaultNettyClient != null) { nettyClientMap.put(((AbstractNetty) defaultNettyClient).getName(), defaultNettyClient); } Map<String, NettyClientConfig> configs = client.getConfigs(); if (configs != null) { configs.forEach((name, value) -> { NettyClient nettyClient; if (value.isKeepConn()) { nettyClient = new LongNettyClient(name, value); } else { nettyClient = new ShortNettyClient(name, value); } nettyClientMap.put(((AbstractNetty) nettyClient).getName(), nettyClient); }); } } private void initNettyServer(NettyConfigProperties.NettyServerProperties server) { if (server == null) { return; } defaultNettyServer = getDefaultNettyServer(server); if (defaultNettyServer != null) { nettyServerMap.put(defaultNettyServer.getName(), defaultNettyServer); } Map<String, NettyServerConfig> configs = server.getConfigs(); if (configs != null) { configs.forEach((name, value) -> { NettyServer nettyServer = new NettyServer(name, value); nettyServerMap.put(nettyServer.getName(), nettyServer); }); } } private NettyServer getDefaultNettyServer(NettyServerConfig nettyServerConfig) { Integer port = nettyServerConfig.getPort(); if (port == null) { return null; } return new NettyServer(nettyServerConfig); } private NettyClient getDefaultNettyClient(NettyClientConfig nettyClientConfig) { String host = nettyClientConfig.getHost(); Integer port = nettyClientConfig.getPort(); if (host == null || port == null) { return null; } if (nettyClientConfig.isKeepConn()) { return new LongNettyClient(nettyClientConfig); } else { return new ShortNettyClient(nettyClientConfig); } } public NettyServer getNettyServer(String name) { return nettyServerMap.get(name); } public NettyClient getNettyClient(String name) { return nettyClientMap.get(name); } public Map<String, NettyServer> getNettyServerMap() { return nettyServerMap; } public Map<String, NettyClient> getNettyClientMap() { return nettyClientMap; } @Override public void destroy() {
package io.github.gaojindeng.netty; /** * @author gjd */ public class DefaultNettyContainer implements DisposableBean { private NettyConfigProperties nettyConfigProperties; private NettyServer defaultNettyServer; private NettyClient defaultNettyClient; private final Map<String, NettyServer> nettyServerMap = new HashMap<>(); private final Map<String, NettyClient> nettyClientMap = new HashMap<>(); public DefaultNettyContainer(NettyConfigProperties nettyConfigProperties) { this.nettyConfigProperties = nettyConfigProperties; initNettyServer(nettyConfigProperties.getServer()); initNettyClient(nettyConfigProperties.getClient()); } private void initNettyClient(NettyConfigProperties.NettyClientProperties client) { if (client == null) { return; } defaultNettyClient = getDefaultNettyClient(client); if (defaultNettyClient != null) { nettyClientMap.put(((AbstractNetty) defaultNettyClient).getName(), defaultNettyClient); } Map<String, NettyClientConfig> configs = client.getConfigs(); if (configs != null) { configs.forEach((name, value) -> { NettyClient nettyClient; if (value.isKeepConn()) { nettyClient = new LongNettyClient(name, value); } else { nettyClient = new ShortNettyClient(name, value); } nettyClientMap.put(((AbstractNetty) nettyClient).getName(), nettyClient); }); } } private void initNettyServer(NettyConfigProperties.NettyServerProperties server) { if (server == null) { return; } defaultNettyServer = getDefaultNettyServer(server); if (defaultNettyServer != null) { nettyServerMap.put(defaultNettyServer.getName(), defaultNettyServer); } Map<String, NettyServerConfig> configs = server.getConfigs(); if (configs != null) { configs.forEach((name, value) -> { NettyServer nettyServer = new NettyServer(name, value); nettyServerMap.put(nettyServer.getName(), nettyServer); }); } } private NettyServer getDefaultNettyServer(NettyServerConfig nettyServerConfig) { Integer port = nettyServerConfig.getPort(); if (port == null) { return null; } return new NettyServer(nettyServerConfig); } private NettyClient getDefaultNettyClient(NettyClientConfig nettyClientConfig) { String host = nettyClientConfig.getHost(); Integer port = nettyClientConfig.getPort(); if (host == null || port == null) { return null; } if (nettyClientConfig.isKeepConn()) { return new LongNettyClient(nettyClientConfig); } else { return new ShortNettyClient(nettyClientConfig); } } public NettyServer getNettyServer(String name) { return nettyServerMap.get(name); } public NettyClient getNettyClient(String name) { return nettyClientMap.get(name); } public Map<String, NettyServer> getNettyServerMap() { return nettyServerMap; } public Map<String, NettyClient> getNettyClientMap() { return nettyClientMap; } @Override public void destroy() {
nettyServerMap.values().forEach(AbstractNettyServer::close);
7
2023-12-03 13:11:09+00:00
8k
binance/binance-sbe-java-sample-app
src/main/java/com/binance/sbe/sbesampleapp/SymbolFilters.java
[ { "identifier": "asBool", "path": "src/main/java/com/binance/sbe/sbesampleapp/Util.java", "snippet": "public static boolean asBool(BoolEnum value) {\n switch (value) {\n case True:\n return true;\n case False:\n return false;\n case NULL_VAL: {\n ...
import java.util.Optional; import static com.binance.sbe.sbesampleapp.Util.asBool; import spot_sbe.BoolEnum; import spot_sbe.FilterType; import spot_sbe.TPlusSellFilterDecoder;
4,270
} } public static class NotionalFilter { public final FilterType filterType; public final Decimal minNotional; public final boolean applyMinToMarket; public final Decimal maxNotional; public final boolean applyMaxToMarket; public final int avgPriceMins; NotionalFilter( FilterType filterType, byte exponent, long minNotional, BoolEnum applyMinToMarket, long maxNotional, BoolEnum applyMaxToMarket, int avgPriceMins) { this.filterType = filterType; this.minNotional = new Decimal(minNotional, exponent); this.applyMinToMarket = asBool(applyMinToMarket); this.maxNotional = new Decimal(maxNotional, exponent); this.applyMaxToMarket = asBool(applyMaxToMarket); this.avgPriceMins = avgPriceMins; } } public static class IcebergPartsFilter { public final FilterType filterType; public final long filterLimit; IcebergPartsFilter(FilterType filterType, long filterLimit) { this.filterType = filterType; this.filterLimit = filterLimit; } } public static class MarketLotSizeFilter { public final FilterType filterType; public final Decimal minQty; public final Decimal maxQty; public final Decimal stepSize; MarketLotSizeFilter( FilterType filterType, byte exponent, long minQty, long maxQty, long stepSize) { this.filterType = filterType; this.minQty = new Decimal(minQty, exponent); this.maxQty = new Decimal(maxQty, exponent); this.stepSize = new Decimal(stepSize, exponent); } } public static class MaxNumOrdersFilter { public final FilterType filterType; public final long maxNumOrders; MaxNumOrdersFilter(FilterType filterType, long maxNumOrders) { this.filterType = filterType; this.maxNumOrders = maxNumOrders; } } public static class MaxNumAlgoOrdersFilter { public final FilterType filterType; public final long maxNumAlgoOrders; MaxNumAlgoOrdersFilter(FilterType filterType, long maxNumAlgoOrders) { this.filterType = filterType; this.maxNumAlgoOrders = maxNumAlgoOrders; } } public static class MaxNumIcebergOrdersFilter { public final FilterType filterType; public final long maxNumIcebergOrders; MaxNumIcebergOrdersFilter(FilterType filterType, long maxNumIcebergOrders) { this.filterType = filterType; this.maxNumIcebergOrders = maxNumIcebergOrders; } } public static class MaxPositionFilter { public final FilterType filterType; public final Decimal maxPosition; MaxPositionFilter(FilterType filterType, byte exponent, long maxPosition) { this.filterType = filterType; this.maxPosition = new Decimal(maxPosition, exponent); } } public static class TrailingDeltaFilter { public final FilterType filterType; public final long minTrailingAboveDelta; public final long maxTrailingAboveDelta; public final long minTrailingBelowDelta; public final long maxTrailingBelowDelta; TrailingDeltaFilter( FilterType filterType, long minTrailingAboveDelta, long maxTrailingAboveDelta, long minTrailingBelowDelta, long maxTrailingBelowDelta) { this.filterType = filterType; this.minTrailingAboveDelta = minTrailingAboveDelta; this.maxTrailingAboveDelta = maxTrailingAboveDelta; this.minTrailingBelowDelta = minTrailingBelowDelta; this.maxTrailingBelowDelta = maxTrailingBelowDelta; } } public static class TPlusSellFilter { public final FilterType filterType; public final Optional<Long> endTime; TPlusSellFilter(FilterType filterType, long endTime) { this.filterType = filterType;
package com.binance.sbe.sbesampleapp; public class SymbolFilters { public static class PriceFilter { public final FilterType filterType; public final Decimal minPrice; public final Decimal maxPrice; public final Decimal tickSize; public PriceFilter( FilterType filterType, byte exponent, long minPrice, long maxPrice, long tickSize) { this.filterType = filterType; this.minPrice = new Decimal(minPrice, exponent); this.maxPrice = new Decimal(maxPrice, exponent); this.tickSize = new Decimal(tickSize, exponent); } } public static class PercentPriceFilter { public final FilterType filterType; public final Decimal multiplierUp; public final Decimal multiplierDown; public final int avgPriceMins; PercentPriceFilter( FilterType filterType, byte exponent, long multiplierUp, long multiplierDown, int avgPriceMins) { this.filterType = filterType; this.multiplierUp = new Decimal(multiplierUp, exponent); this.multiplierDown = new Decimal(multiplierDown, exponent); this.avgPriceMins = avgPriceMins; } } public static class PercentPriceBySideFilter { public final FilterType filterType; public final Decimal bidMultiplierUp; public final Decimal bidMultiplierDown; public final Decimal askMultiplierUp; public final Decimal askMultiplierDown; public final int avgPriceMins; PercentPriceBySideFilter( FilterType filterType, byte exponent, long bidMultiplierUp, long bidMultiplierDown, long askMultiplierUp, long askMultiplierDown, int avgPriceMins) { this.filterType = filterType; this.bidMultiplierUp = new Decimal(bidMultiplierUp, exponent); this.bidMultiplierDown = new Decimal(bidMultiplierDown, exponent); this.askMultiplierUp = new Decimal(askMultiplierUp, exponent); this.askMultiplierDown = new Decimal(askMultiplierDown, exponent); this.avgPriceMins = avgPriceMins; } } public static class LotSizeFilter { public final FilterType filterType; public final Decimal minQty; public final Decimal maxQty; public final Decimal stepSize; LotSizeFilter(FilterType filterType, byte exponent, long minQty, long maxQty, long stepSize) { this.filterType = filterType; this.minQty = new Decimal(minQty, exponent); this.maxQty = new Decimal(maxQty, exponent); this.stepSize = new Decimal(stepSize, exponent); } } public static class MinNotionalFilter { public final FilterType filterType; public final Decimal minNotional; public final boolean applyToMarket; public final int avgPriceMins; MinNotionalFilter( FilterType filterType, byte exponent, long minNotional, BoolEnum applyToMarket, int avgPriceMins) { this.filterType = filterType; this.minNotional = new Decimal(minNotional, exponent); this.applyToMarket = asBool(applyToMarket); this.avgPriceMins = avgPriceMins; } } public static class NotionalFilter { public final FilterType filterType; public final Decimal minNotional; public final boolean applyMinToMarket; public final Decimal maxNotional; public final boolean applyMaxToMarket; public final int avgPriceMins; NotionalFilter( FilterType filterType, byte exponent, long minNotional, BoolEnum applyMinToMarket, long maxNotional, BoolEnum applyMaxToMarket, int avgPriceMins) { this.filterType = filterType; this.minNotional = new Decimal(minNotional, exponent); this.applyMinToMarket = asBool(applyMinToMarket); this.maxNotional = new Decimal(maxNotional, exponent); this.applyMaxToMarket = asBool(applyMaxToMarket); this.avgPriceMins = avgPriceMins; } } public static class IcebergPartsFilter { public final FilterType filterType; public final long filterLimit; IcebergPartsFilter(FilterType filterType, long filterLimit) { this.filterType = filterType; this.filterLimit = filterLimit; } } public static class MarketLotSizeFilter { public final FilterType filterType; public final Decimal minQty; public final Decimal maxQty; public final Decimal stepSize; MarketLotSizeFilter( FilterType filterType, byte exponent, long minQty, long maxQty, long stepSize) { this.filterType = filterType; this.minQty = new Decimal(minQty, exponent); this.maxQty = new Decimal(maxQty, exponent); this.stepSize = new Decimal(stepSize, exponent); } } public static class MaxNumOrdersFilter { public final FilterType filterType; public final long maxNumOrders; MaxNumOrdersFilter(FilterType filterType, long maxNumOrders) { this.filterType = filterType; this.maxNumOrders = maxNumOrders; } } public static class MaxNumAlgoOrdersFilter { public final FilterType filterType; public final long maxNumAlgoOrders; MaxNumAlgoOrdersFilter(FilterType filterType, long maxNumAlgoOrders) { this.filterType = filterType; this.maxNumAlgoOrders = maxNumAlgoOrders; } } public static class MaxNumIcebergOrdersFilter { public final FilterType filterType; public final long maxNumIcebergOrders; MaxNumIcebergOrdersFilter(FilterType filterType, long maxNumIcebergOrders) { this.filterType = filterType; this.maxNumIcebergOrders = maxNumIcebergOrders; } } public static class MaxPositionFilter { public final FilterType filterType; public final Decimal maxPosition; MaxPositionFilter(FilterType filterType, byte exponent, long maxPosition) { this.filterType = filterType; this.maxPosition = new Decimal(maxPosition, exponent); } } public static class TrailingDeltaFilter { public final FilterType filterType; public final long minTrailingAboveDelta; public final long maxTrailingAboveDelta; public final long minTrailingBelowDelta; public final long maxTrailingBelowDelta; TrailingDeltaFilter( FilterType filterType, long minTrailingAboveDelta, long maxTrailingAboveDelta, long minTrailingBelowDelta, long maxTrailingBelowDelta) { this.filterType = filterType; this.minTrailingAboveDelta = minTrailingAboveDelta; this.maxTrailingAboveDelta = maxTrailingAboveDelta; this.minTrailingBelowDelta = minTrailingBelowDelta; this.maxTrailingBelowDelta = maxTrailingBelowDelta; } } public static class TPlusSellFilter { public final FilterType filterType; public final Optional<Long> endTime; TPlusSellFilter(FilterType filterType, long endTime) { this.filterType = filterType;
if (endTime == TPlusSellFilterDecoder.endTimeNullValue()) {
3
2023-11-27 09:46:42+00:00
8k
hmcts/juror-sql-support-library
src/main/java/uk/gov/hmcts/juror/support/sql/generators/JurorPoolGeneratorUtil.java
[ { "identifier": "ExcusableCode", "path": "src/main/java/uk/gov/hmcts/juror/support/sql/entity/ExcusableCode.java", "snippet": "@Getter\npublic enum ExcusableCode {\n\n CRIMINAL_RECORD(\"K\"),\n DECEASED(\"D\"),\n OVER_69(\"V\"),\n RECENTLY_SERVED(\"S\"),\n THE_FORCES(\"F\"),\n MEDICAL_...
import uk.gov.hmcts.juror.support.generation.generators.value.FixedValueGeneratorImpl; import uk.gov.hmcts.juror.support.generation.generators.value.LocalDateGeneratorImpl; import uk.gov.hmcts.juror.support.generation.generators.value.NullValueGeneratorImpl; import uk.gov.hmcts.juror.support.generation.generators.value.RandomFromCollectionGeneratorImpl; import uk.gov.hmcts.juror.support.sql.entity.ExcusableCode; import uk.gov.hmcts.juror.support.sql.entity.Juror; 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.service.SqlSupportService; import java.time.LocalDate; import java.util.Arrays;
6,942
package uk.gov.hmcts.juror.support.sql.generators; public class JurorPoolGeneratorUtil { public static JurorPoolGenerator summoned(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.SUMMONED); } public static JurorPoolGenerator responded(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.RESPONDED); } public static JurorPoolGenerator panel(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.PANEL); } public static JurorPoolGenerator juror(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.JUROR); } public static JurorPoolGenerator excused(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.EXCUSED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); return jurorPoolGenerator; } public static JurorPoolGenerator disqualified(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DISQUALIFIED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); return jurorPoolGenerator; } public static JurorPoolGenerator deferred(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DEFERRED); //Next date set to date you are deferred too?? -- check jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); jurorPoolGenerator.setDeferralCode(new RandomFromCollectionGeneratorImpl<>(
package uk.gov.hmcts.juror.support.sql.generators; public class JurorPoolGeneratorUtil { public static JurorPoolGenerator summoned(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.SUMMONED); } public static JurorPoolGenerator responded(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.RESPONDED); } public static JurorPoolGenerator panel(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.PANEL); } public static JurorPoolGenerator juror(boolean isCourtOwned) { return createStandard(isCourtOwned, JurorStatus.JUROR); } public static JurorPoolGenerator excused(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.EXCUSED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); return jurorPoolGenerator; } public static JurorPoolGenerator disqualified(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DISQUALIFIED); jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); return jurorPoolGenerator; } public static JurorPoolGenerator deferred(boolean isCourtOwned) { JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DEFERRED); //Next date set to date you are deferred too?? -- check jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>()); jurorPoolGenerator.setDeferralCode(new RandomFromCollectionGeneratorImpl<>(
Arrays.stream(ExcusableCode.values()).map(ExcusableCode::getCode).toList()));
0
2023-12-01 11:38:42+00:00
8k
vvbbnn00/JavaWeb-CanteenSystem
JavaBackend/src/main/java/cn/vvbbnn00/canteen/service/CanteenAdminService.java
[ { "identifier": "CanteenAdminDao", "path": "JavaBackend/src/main/java/cn/vvbbnn00/canteen/dao/CanteenAdminDao.java", "snippet": "public interface CanteenAdminDao {\n /**\n * 插入一个餐厅管理员对象\n * @param canteenAdmin 餐厅管理员对象\n * @return 是否插入成功\n */\n boolean insert(CanteenAdmin canteenAdm...
import cn.vvbbnn00.canteen.dao.CanteenAdminDao; import cn.vvbbnn00.canteen.dao.impl.CanteenAdminDaoImpl; import cn.vvbbnn00.canteen.dao.impl.CanteenDaoImpl; import cn.vvbbnn00.canteen.dao.impl.UserDaoImpl; import cn.vvbbnn00.canteen.model.Canteen; import cn.vvbbnn00.canteen.model.CanteenAdmin; import cn.vvbbnn00.canteen.model.User; import java.util.List; import java.util.stream.Collectors;
6,816
package cn.vvbbnn00.canteen.service; public class CanteenAdminService { private static final CanteenAdminDao canteenAdminDao = new CanteenAdminDaoImpl(); /** * 检查是否可以添加或移除餐厅管理员 * * @param canteenId 餐厅ID * @param userId 用户ID */ private void checkUpdateAvailable(Integer canteenId, Integer userId) { User user = new UserService().getUserById(userId); if (user == null) { throw new RuntimeException("用户不存在"); } Canteen canteen = new CanteenService().getCanteenById(canteenId); if (canteen == null) { throw new RuntimeException("餐厅不存在"); } } /** * 添加一个餐厅管理员 * * @param canteenId 餐厅ID * @param userId 用户ID * @return 是否添加成功 */ public boolean addCanteenAdmin(Integer canteenId, Integer userId) { checkUpdateAvailable(canteenId, userId); CanteenAdmin canteenAdmin = new CanteenAdmin(); canteenAdmin.setCanteenId(canteenId); canteenAdmin.setUserId(userId); List<CanteenAdmin> list = canteenAdminDao.query(canteenId, userId); if (!list.isEmpty()) { throw new RuntimeException("餐厅管理员已存在"); } boolean result = canteenAdminDao.insert(canteenAdmin); if (!result) { throw new RuntimeException("添加失败"); } return true; } /** * 移除一个餐厅管理员 * * @param canteenId 餐厅ID * @param userId 用户ID * @return 是否移除成功 */ public boolean removeCanteenAdmin(Integer canteenId, Integer userId) { checkUpdateAvailable(canteenId, userId); CanteenAdmin canteenAdmin = new CanteenAdmin(); canteenAdmin.setCanteenId(canteenId); canteenAdmin.setUserId(userId); boolean result = canteenAdminDao.delete(canteenAdmin); if (!result) { throw new RuntimeException("移除失败"); } return true; } /** * 查询用户是否为餐厅管理员 * * @param canteenId 餐厅ID * @param userId 用户ID * @return 是否为餐厅管理员 */ public boolean checkHasCanteenAdmin(Integer canteenId, Integer userId) { User user = new UserService().getUserById(userId); if (user == null) { return false; } Canteen canteen = new CanteenService().getCanteenById(canteenId); if (canteen == null) { return false; } if (user.getRole() == User.Role.admin) { return true; } List<CanteenAdmin> list = canteenAdminDao.query(canteenId, userId); if (list == null) { throw new RuntimeException("查询失败"); } return !list.isEmpty(); } /** * 查询餐厅管理员列表 * * @param canteenId 餐厅ID * @return 餐厅管理员列表 */ public List<User> getCanteenAdminList(Integer canteenId) { Canteen canteen = new CanteenService().getCanteenById(canteenId); if (canteen == null) { throw new RuntimeException("餐厅不存在"); } List<CanteenAdmin> canteenAdminList = canteenAdminDao.queryByCanteenId(canteenId); if (canteenAdminList == null) { throw new RuntimeException("查询失败"); } List<Integer> userIdList = canteenAdminList.stream().map(CanteenAdmin::getUserId).collect(Collectors.toList());
package cn.vvbbnn00.canteen.service; public class CanteenAdminService { private static final CanteenAdminDao canteenAdminDao = new CanteenAdminDaoImpl(); /** * 检查是否可以添加或移除餐厅管理员 * * @param canteenId 餐厅ID * @param userId 用户ID */ private void checkUpdateAvailable(Integer canteenId, Integer userId) { User user = new UserService().getUserById(userId); if (user == null) { throw new RuntimeException("用户不存在"); } Canteen canteen = new CanteenService().getCanteenById(canteenId); if (canteen == null) { throw new RuntimeException("餐厅不存在"); } } /** * 添加一个餐厅管理员 * * @param canteenId 餐厅ID * @param userId 用户ID * @return 是否添加成功 */ public boolean addCanteenAdmin(Integer canteenId, Integer userId) { checkUpdateAvailable(canteenId, userId); CanteenAdmin canteenAdmin = new CanteenAdmin(); canteenAdmin.setCanteenId(canteenId); canteenAdmin.setUserId(userId); List<CanteenAdmin> list = canteenAdminDao.query(canteenId, userId); if (!list.isEmpty()) { throw new RuntimeException("餐厅管理员已存在"); } boolean result = canteenAdminDao.insert(canteenAdmin); if (!result) { throw new RuntimeException("添加失败"); } return true; } /** * 移除一个餐厅管理员 * * @param canteenId 餐厅ID * @param userId 用户ID * @return 是否移除成功 */ public boolean removeCanteenAdmin(Integer canteenId, Integer userId) { checkUpdateAvailable(canteenId, userId); CanteenAdmin canteenAdmin = new CanteenAdmin(); canteenAdmin.setCanteenId(canteenId); canteenAdmin.setUserId(userId); boolean result = canteenAdminDao.delete(canteenAdmin); if (!result) { throw new RuntimeException("移除失败"); } return true; } /** * 查询用户是否为餐厅管理员 * * @param canteenId 餐厅ID * @param userId 用户ID * @return 是否为餐厅管理员 */ public boolean checkHasCanteenAdmin(Integer canteenId, Integer userId) { User user = new UserService().getUserById(userId); if (user == null) { return false; } Canteen canteen = new CanteenService().getCanteenById(canteenId); if (canteen == null) { return false; } if (user.getRole() == User.Role.admin) { return true; } List<CanteenAdmin> list = canteenAdminDao.query(canteenId, userId); if (list == null) { throw new RuntimeException("查询失败"); } return !list.isEmpty(); } /** * 查询餐厅管理员列表 * * @param canteenId 餐厅ID * @return 餐厅管理员列表 */ public List<User> getCanteenAdminList(Integer canteenId) { Canteen canteen = new CanteenService().getCanteenById(canteenId); if (canteen == null) { throw new RuntimeException("餐厅不存在"); } List<CanteenAdmin> canteenAdminList = canteenAdminDao.queryByCanteenId(canteenId); if (canteenAdminList == null) { throw new RuntimeException("查询失败"); } List<Integer> userIdList = canteenAdminList.stream().map(CanteenAdmin::getUserId).collect(Collectors.toList());
return new UserDaoImpl().batchQueryUsers(userIdList);
3
2023-12-01 04:55:12+00:00
8k
SuperRicky14/TpaPlusPlus
src/main/java/net/superricky/tpaplusplus/command/TPAAcceptCommand.java
[ { "identifier": "Config", "path": "src/main/java/net/superricky/tpaplusplus/util/configuration/Config.java", "snippet": "public class Config {\n public static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();\n public static final ForgeConfigSpec SPEC;\n\n public static fin...
import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.arguments.EntityArgument; import net.minecraft.server.level.ServerPlayer; import net.minecraftforge.event.RegisterCommandsEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.superricky.tpaplusplus.util.configuration.Config; import net.superricky.tpaplusplus.util.manager.RequestManager; import org.apache.commons.lang3.NotImplementedException; import static net.minecraft.commands.Commands.argument; import static net.minecraft.commands.Commands.literal;
5,053
package net.superricky.tpaplusplus.command; @Mod.EventBusSubscriber public class TPAAcceptCommand { @SubscribeEvent() public static void onRegisterCommandEvent(RegisterCommandsEvent event) {
package net.superricky.tpaplusplus.command; @Mod.EventBusSubscriber public class TPAAcceptCommand { @SubscribeEvent() public static void onRegisterCommandEvent(RegisterCommandsEvent event) {
event.getDispatcher().register(literal(Config.TPAACCEPT_COMMAND_NAME.get())
0
2023-12-02 05:41:24+00:00
8k
aosolorzano/city-tasks-aws-fullstack
apis/city-tasks-api/src/test/java/com/hiperium/city/tasks/api/controllers/TaskControllerValidationsTest.java
[ { "identifier": "AbstractContainerBaseTest", "path": "apis/city-tasks-api/src/test/java/com/hiperium/city/tasks/api/common/AbstractContainerBaseTest.java", "snippet": "public abstract class AbstractContainerBaseTest {\n\n protected static final String AUTHORIZATION = \"Authorization\";\n\n private...
import com.hiperium.city.tasks.api.common.AbstractContainerBaseTest; import com.hiperium.city.tasks.api.dto.ErrorDetailsDTO; import com.hiperium.city.tasks.api.dto.TaskDTO; import com.hiperium.city.tasks.api.utils.TasksUtil; import com.hiperium.city.tasks.api.utils.enums.EnumLanguageCode; import com.hiperium.city.tasks.api.utils.enums.EnumValidationError; import org.assertj.core.api.Assertions; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.reactive.server.WebTestClient; import java.time.ZonedDateTime; import static com.hiperium.city.tasks.api.utils.PathsUtil.TASK_V1_PATH; import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
4,385
Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("El minuto de la tarea debe ser mayor o igual a 0."); }); } @Test @DisplayName("Create Task without executions days") void givenTaskWithoutExecutionDays_whenCreate_thenReturnError404() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setExecutionDays(null); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("Task execution days cannot be empty."); }); } @Test @DisplayName("Create Task without executions days - Spanish") void givenTaskWithoutExecutionDays_whenCreate_thenReturnError404InSpanish() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setExecutionDays(null); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("Los días de ejecución de la tarea no pueden estar vacíos."); }); } @Test @DisplayName("Create Task with past execute until date") void givenTaskWithPastExecuteUntil_whenCreate_thenReturnError404() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setExecuteUntil(ZonedDateTime.now().minusDays(1)); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("Task execute until must be in the future."); }); } @Test @DisplayName("Create Task with past execute until date - Spanish") void givenTaskWithPastExecuteUntil_whenCreate_thenReturnError404InSpanish() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setExecuteUntil(ZonedDateTime.now().minusDays(1)); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("La fecha final de ejecución de la tarea debe ser posterior a la fecha actual."); }); } @Test @DisplayName("Create Task without Device ID") void givenTaskWithoutDeviceId_whenCreate_thenReturnError404() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setDeviceId(null); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("Device ID cannot be empty."); }); } @Test @DisplayName("Create Task without Device ID - Spanish") void givenTaskWithoutDeviceId_whenCreate_thenReturnError404inSpanish() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setDeviceId(null); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("El ID del dispositivo no puede estar vacío."); }); } @Test @DisplayName("Create Task without Device Action") void givenTaskWithoutDeviceAction_whenCreate_thenReturnError404() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setDeviceOperation(null); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("Device action cannot be empty."); }); } @Test @DisplayName("Create Task without Device Action - Spanish") void givenTaskWithoutDeviceAction_whenCreate_thenReturnError404InSpanish() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setDeviceOperation(null); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("La acción del dispositivo no puede estar vacía."); }); } @NotNull
package com.hiperium.city.tasks.api.controllers; @ActiveProfiles("test") @TestInstance(PER_CLASS) @AutoConfigureWebTestClient @TestPropertySource(locations = "classpath:application-test.properties") @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class TaskControllerValidationsTest extends AbstractContainerBaseTest { @Autowired private WebTestClient webTestClient; private static TaskDTO taskDTO; @Test @DisplayName("Create Task without name") void givenTaskWithoutName_whenCreate_thenReturnError404() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setName(null); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("Task name cannot be empty."); }); } @Test @DisplayName("Create Task without name - Spanish") void givenTaskWithoutName_whenCreate_thenReturnError404InSpanish() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setName(null); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("El nombre de la tarea no puede estar vacío."); }); } @Test @DisplayName("Create Task with wrong hour") void givenTaskWithWrongHour_whenCreate_thenReturnError404() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setHour(25); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("Task hour must be less than or equal to 23."); }); } @Test @DisplayName("Create Task with wrong hour - Spanish") void givenTaskWithWrongHour_whenCreate_thenReturnError404InSpanish() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setHour(25); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("La hora de la tarea debe ser menor o igual a 23."); }); } @Test @DisplayName("Create Task with wrong minute") void givenTaskWithWrongMinute_whenCreate_thenReturnError404() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setMinute(-20); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("Task minute must be greater than or equal to 0."); }); } @Test @DisplayName("Create Task with wrong minute - Spanish") void givenTaskWithWrongMinute_whenCreate_thenReturnError404InSpanish() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setMinute(-20); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("El minuto de la tarea debe ser mayor o igual a 0."); }); } @Test @DisplayName("Create Task without executions days") void givenTaskWithoutExecutionDays_whenCreate_thenReturnError404() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setExecutionDays(null); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("Task execution days cannot be empty."); }); } @Test @DisplayName("Create Task without executions days - Spanish") void givenTaskWithoutExecutionDays_whenCreate_thenReturnError404InSpanish() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setExecutionDays(null); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("Los días de ejecución de la tarea no pueden estar vacíos."); }); } @Test @DisplayName("Create Task with past execute until date") void givenTaskWithPastExecuteUntil_whenCreate_thenReturnError404() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setExecuteUntil(ZonedDateTime.now().minusDays(1)); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("Task execute until must be in the future."); }); } @Test @DisplayName("Create Task with past execute until date - Spanish") void givenTaskWithPastExecuteUntil_whenCreate_thenReturnError404InSpanish() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setExecuteUntil(ZonedDateTime.now().minusDays(1)); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("La fecha final de ejecución de la tarea debe ser posterior a la fecha actual."); }); } @Test @DisplayName("Create Task without Device ID") void givenTaskWithoutDeviceId_whenCreate_thenReturnError404() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setDeviceId(null); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("Device ID cannot be empty."); }); } @Test @DisplayName("Create Task without Device ID - Spanish") void givenTaskWithoutDeviceId_whenCreate_thenReturnError404inSpanish() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setDeviceId(null); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("El ID del dispositivo no puede estar vacío."); }); } @Test @DisplayName("Create Task without Device Action") void givenTaskWithoutDeviceAction_whenCreate_thenReturnError404() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setDeviceOperation(null); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("Device action cannot be empty."); }); } @Test @DisplayName("Create Task without Device Action - Spanish") void givenTaskWithoutDeviceAction_whenCreate_thenReturnError404InSpanish() { taskDTO = TasksUtil.getTaskDtoTemplate(); taskDTO.setDeviceOperation(null); this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES) .value(errorDetailsDTO -> { Assertions.assertThat(errorDetailsDTO.getErrorCode()) .isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode()); Assertions.assertThat(errorDetailsDTO.getErrorMessage()) .isEqualTo("La acción del dispositivo no puede estar vacía."); }); } @NotNull
private WebTestClient.BodySpec<ErrorDetailsDTO, ?> getValidationErrorResponse(TaskDTO taskOperationDto,
1
2023-11-28 16:35:22+00:00
8k
shawn-sheep/Activity_Diary
app/src/main/java/de/rampro/activitydiary/helpers/TimeSpanFormatter.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 android.content.res.Resources; import androidx.preference.PreferenceManager; import java.text.DecimalFormat; import java.util.Date; import de.rampro.activitydiary.ActivityDiaryApplication; import de.rampro.activitydiary.R; import de.rampro.activitydiary.ui.settings.SettingsActivity;
5,870
/* * ActivityDiary * * Copyright (C) 2017-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.helpers; public class TimeSpanFormatter { public static String fuzzyFormat(Date start, Date end) {
/* * ActivityDiary * * Copyright (C) 2017-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.helpers; public class TimeSpanFormatter { public static String fuzzyFormat(Date start, Date end) {
Resources res = ActivityDiaryApplication.getAppContext().getResources();
0
2023-12-02 12:36:40+00:00
8k
RabbitHareLu/K-Tools
frontend/src/main/java/com/ktools/frontend/action/NewFolderAction.java
[ { "identifier": "KToolsContext", "path": "warehouse/src/main/java/com/ktools/warehouse/KToolsContext.java", "snippet": "@Getter\npublic class KToolsContext {\n\n private static volatile KToolsContext INSTANCE;\n\n private final MybatisContext mybatisContext;\n\n private final Properties propert...
import com.ktools.warehouse.KToolsContext; import com.ktools.frontend.Main; import com.ktools.warehouse.api.SystemApi; import com.ktools.frontend.common.model.TreeNodeType; import com.ktools.frontend.common.utils.DialogUtil; import com.ktools.warehouse.common.utils.StringUtil; import com.ktools.frontend.component.Tree; import com.ktools.frontend.component.TreeNode; import com.ktools.warehouse.exception.KToolException; import com.ktools.warehouse.manager.uid.UidKey; import com.ktools.warehouse.mybatis.entity.TreeEntity; import lombok.extern.slf4j.Slf4j; import javax.swing.*; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List;
4,118
package com.ktools.frontend.action; /** * @author lsl * @version 1.0 * @date 2023年12月01日 10:50 */ @Slf4j public class NewFolderAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { Tree instance = Tree.getInstance(); TreePath selectionPath = instance.getCurrentTreePath(); TreeNode currentTreeNode = instance.getCurrentTreeNode(selectionPath); String result = JOptionPane.showInputDialog( Main.kToolsRootJFrame, "目录名称", "新建文件夹", JOptionPane.INFORMATION_MESSAGE ); if (StringUtil.isNotBlank(result)) { log.info("新建文件夹: {}", result); TreeEntity treeEntity = new TreeEntity();
package com.ktools.frontend.action; /** * @author lsl * @version 1.0 * @date 2023年12月01日 10:50 */ @Slf4j public class NewFolderAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { Tree instance = Tree.getInstance(); TreePath selectionPath = instance.getCurrentTreePath(); TreeNode currentTreeNode = instance.getCurrentTreeNode(selectionPath); String result = JOptionPane.showInputDialog( Main.kToolsRootJFrame, "目录名称", "新建文件夹", JOptionPane.INFORMATION_MESSAGE ); if (StringUtil.isNotBlank(result)) { log.info("新建文件夹: {}", result); TreeEntity treeEntity = new TreeEntity();
treeEntity.setId(KToolsContext.getInstance().getIdGenerator().getId(UidKey.TREE));
0
2023-11-30 03:26:25+00:00
8k
ChrisGenti/VPL
velocity/src/main/java/com/github/chrisgenti/vpl/velocity/commands/admin/VPLCommand.java
[ { "identifier": "VPLPlugin", "path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/VPLPlugin.java", "snippet": "@Plugin(\n id = \"vpl\",\n name = \"VPL\",\n version = \"1.0.0\",\n description = \"\",\n authors = {\"ChrisGenti\"}\n) @Getter\npublic class VP...
import com.github.chrisgenti.vpl.velocity.VPLPlugin; import com.github.chrisgenti.vpl.velocity.commands.PluginCommand; import com.github.chrisgenti.vpl.velocity.commands.admin.subs.PluginSubCommand; import com.github.chrisgenti.vpl.velocity.commands.admin.subs.accounts.AccountsSubCommand; import com.github.chrisgenti.vpl.velocity.commands.admin.subs.check.CheckSubCommand; import com.github.chrisgenti.vpl.velocity.commands.admin.subs.disable.DisableSubCommand; import com.github.chrisgenti.vpl.velocity.commands.admin.subs.stats.StatsSubCommand; import com.github.chrisgenti.vpl.velocity.configurations.language.LanguageFile; import com.velocitypowered.api.command.CommandSource; import java.util.Set; import java.util.concurrent.ConcurrentHashMap;
3,870
package com.github.chrisgenti.vpl.velocity.commands.admin; public class VPLCommand implements PluginCommand { private final Set<PluginSubCommand> subCommands = ConcurrentHashMap.newKeySet(); private final VPLPlugin plugin; private final LanguageFile languageFile; public VPLCommand(VPLPlugin plugin) { this.plugin = plugin; this.languageFile = plugin.getLanguageFile(); this.subCommands.add(new StatsSubCommand(plugin));
package com.github.chrisgenti.vpl.velocity.commands.admin; public class VPLCommand implements PluginCommand { private final Set<PluginSubCommand> subCommands = ConcurrentHashMap.newKeySet(); private final VPLPlugin plugin; private final LanguageFile languageFile; public VPLCommand(VPLPlugin plugin) { this.plugin = plugin; this.languageFile = plugin.getLanguageFile(); this.subCommands.add(new StatsSubCommand(plugin));
this.subCommands.add(new CheckSubCommand(plugin));
4
2023-11-28 10:12:04+00:00
8k
Ethylene9160/Chess
src/chess/recorder/Saver.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 chess.pieces.Chess; import chess.util.Constants; import chess.util.Locker; import javax.swing.*; import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import java.util.List;
4,218
package chess.recorder; public class Saver { private static String getListInfo(List<Record> recordList) { StringBuilder sb = new StringBuilder(); for (Record r : recordList) sb.append(r); // for (Record r : recordList) sb.append(r).append("\n"); return sb.toString(); }
package chess.recorder; public class Saver { private static String getListInfo(List<Record> recordList) { StringBuilder sb = new StringBuilder(); for (Record r : recordList) sb.append(r); // for (Record r : recordList) sb.append(r).append("\n"); return sb.toString(); }
public static void saveC(int currentMax, List<Record> recordList, ArrayList<Chess> chessList) {
0
2023-12-01 02:33:32+00:00
8k
dnslin/cloud189
src/main/java/in/dnsl/logic/FileDirectory.java
[ { "identifier": "AppFileListParam", "path": "src/main/java/in/dnsl/domain/req/AppFileListParam.java", "snippet": "@Data\n@Builder\npublic class AppFileListParam {\n\n @Builder.Default\n private int familyId = 0;\n\n private String fileId;\n\n private int orderBy;\n\n @Builder.Default\n ...
import in.dnsl.domain.req.AppFileListParam; import in.dnsl.domain.req.AppGetFileInfoParam; import in.dnsl.domain.result.AppFileEntity; import in.dnsl.domain.xml.AppErrorXmlResp; import in.dnsl.domain.xml.AppGetFileInfoResult; import in.dnsl.domain.xml.FileSystemEntity; import in.dnsl.domain.xml.ListFiles; import in.dnsl.enums.OrderEnums; import in.dnsl.utils.XmlUtils; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import me.kuku.utils.OkHttpUtils; import okhttp3.Headers; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static in.dnsl.constant.ApiConstant.API_URL; import static in.dnsl.constant.ApiConstant.rootNode; import static in.dnsl.logic.CloudLogin.getSession; import static in.dnsl.utils.ApiUtils.*; import static in.dnsl.utils.SignatureUtils.signatureOfHmac;
3,907
package in.dnsl.logic; @Slf4j public class FileDirectory { //根据文件ID或者文件绝对路径获取文件信息,支持文件和文件夹 public static AppGetFileInfoResult appGetBasicFileInfo(AppGetFileInfoParam build) { if (build.getFamilyId() > 0 && "-11".equals(build.getFileId())) build.setFileId(""); if (build.getFilePath().isBlank() && build.getFileId().isBlank()) build.setFilePath("/"); var session = getSession(); String sessionKey, sessionSecret, fullUrlPattern; Object[] formatArgs; if (build.getFamilyId() >= 0) { // 个人云逻辑 sessionKey = session.getSessionKey(); sessionSecret = session.getSessionSecret(); fullUrlPattern = "%s/getFolderInfo.action?folderId=%s&folderPath=%s&pathList=0&dt=3&%s"; formatArgs = new Object[]{API_URL, build.getFileId(), urlEncode(build.getFilePath()), PcClientInfoSuffixParam()}; } else { // 家庭云逻辑 sessionKey = session.getFamilySessionKey(); sessionSecret = session.getFamilySessionSecret(); if (build.getFileId().isEmpty()) throw new RuntimeException("FileId为空"); fullUrlPattern = "%s/family/file/getFolderInfo.action?familyId=%d&folderId=%s&folderPath=%s&pathList=0&%s"; formatArgs = new Object[]{API_URL, build.getFamilyId(), build.getFileId(), urlEncode(build.getFilePath()), PcClientInfoSuffixParam()}; } var xmlData = send(fullUrlPattern, formatArgs, sessionKey, sessionSecret); if (xmlData.contains("error")) { var appErrorXmlResp = XmlUtils.xmlToObject(xmlData, AppErrorXmlResp.class); throw new RuntimeException("请求失败:" + appErrorXmlResp.getCode()); } return XmlUtils.xmlToObject(xmlData, AppGetFileInfoResult.class); } // 获取指定目录下的所有文件列表 @SneakyThrows public static ListFiles appGetAllFileList(AppFileListParam param) { // 参数校验 if (param.getPageSize() <= 0) param.setPageSize(200); if (param.getFamilyId() > 0 && "-11".equals(param.getFileId())) param.setFileId(""); // 获取初始文件列表 var files = appFileList(param); if (files == null) throw new RuntimeException("文件列表为空"); var fileList = files.getFileList(); int totalFilesCount = fileList.getCount(); // 检查是否需要分页 if (totalFilesCount > param.getPageSize()) { int pageNum = (int) Math.ceil((double) totalFilesCount / param.getPageSize()); for (int i = 2; i <= pageNum; i++) { param.setPageNum(i); var additionalFiles = appFileList(param).getFileList(); if (additionalFiles != null) { if (additionalFiles.getFile() != null) fileList.getFile().addAll(additionalFiles.getFile()); if (additionalFiles.getFolder() != null) fileList.getFolder().addAll(additionalFiles.getFolder()); } TimeUnit.MILLISECONDS.sleep(100); } } return files; } //获取文件列表 public static ListFiles appFileList(AppFileListParam param) { Object[] formatArgs; var session = getSession(); String sessionKey, sessionSecret, fullUrlPattern; if (param.getFamilyId() <= 0) { sessionKey = session.getSessionKey(); sessionSecret = session.getSessionSecret(); fullUrlPattern = "%s/listFiles.action?folderId=%s&recursive=0&fileType=0&iconOption=10&mediaAttr=0&orderBy=%s&descending=%s&pageNum=%s&pageSize=%s&%s"; formatArgs = new Object[]{API_URL, param.getFileId(), OrderEnums.getByCode(param.getOrderBy()), false, param.getPageNum(), param.getPageSize(), PcClientInfoSuffixParam()}; } else { // 家庭云 if (rootNode.equals(param.getFileId())) param.setFileId(""); sessionKey = session.getFamilySessionKey(); sessionSecret = session.getFamilySessionSecret(); fullUrlPattern = "%s/family/file/listFiles.action?folderId=%s&familyId=%s&fileType=0&iconOption=0&mediaAttr=0&orderBy=%s&descending=%s&pageNum=%d&pageSize=%d&%s"; formatArgs = new Object[]{API_URL, param.getFileId(), param.getFamilyId(), OrderEnums.getByCode(param.getOrderBy()), false, param.getPageNum(), param.getPageSize(), PcClientInfoSuffixParam()}; } var send = send(fullUrlPattern, formatArgs, sessionKey, sessionSecret); return XmlUtils.xmlToObject(send, ListFiles.class); } // 通过FileId获取文件的绝对路径 @SneakyThrows public static String appFilePathById(Integer familyId, String fileId) { var fullPath = ""; var param = AppGetFileInfoParam.builder() .familyId(familyId) .fileId(fileId).build(); while (true) { var fi = appGetBasicFileInfo(param); if (fi == null) throw new RuntimeException("FileInfo is null"); if (!fi.getPath().isEmpty()) return fi.getPath(); if (fi.getId().startsWith("-") || fi.getParentFolderId().startsWith("-")) { fullPath = "/" + fullPath; break; } fullPath = fullPath.isEmpty() ? fi.getName() : fi.getName() + "/" + fullPath; param = AppGetFileInfoParam.builder() .fileId(fi.getParentFolderId()).build(); TimeUnit.MILLISECONDS.sleep(100); } return fullPath; } // 通过FileId获取文件详情 public static AppFileEntity appFileInfoById(Integer familyId, String fileId) { var param = AppGetFileInfoParam.builder() .familyId(familyId) .fileId(fileId).build(); var result = appGetBasicFileInfo(param); var build = AppFileListParam.builder() .fileId(result.getParentFolderId()) .familyId(familyId).build(); var files = appGetAllFileList(build); var file = files.getFileList().getFile(); if (file == null) throw new RuntimeException("文件列表为空"); var collect = convert(file, result.getPath(), result.getParentFolderId()).stream().filter(e -> e.getFileId().equals(fileId)).toList(); if (collect.isEmpty()) throw new RuntimeException("文件不存在"); return collect.getFirst(); } // 递归获取文件夹下的所有文件 包括子文件夹
package in.dnsl.logic; @Slf4j public class FileDirectory { //根据文件ID或者文件绝对路径获取文件信息,支持文件和文件夹 public static AppGetFileInfoResult appGetBasicFileInfo(AppGetFileInfoParam build) { if (build.getFamilyId() > 0 && "-11".equals(build.getFileId())) build.setFileId(""); if (build.getFilePath().isBlank() && build.getFileId().isBlank()) build.setFilePath("/"); var session = getSession(); String sessionKey, sessionSecret, fullUrlPattern; Object[] formatArgs; if (build.getFamilyId() >= 0) { // 个人云逻辑 sessionKey = session.getSessionKey(); sessionSecret = session.getSessionSecret(); fullUrlPattern = "%s/getFolderInfo.action?folderId=%s&folderPath=%s&pathList=0&dt=3&%s"; formatArgs = new Object[]{API_URL, build.getFileId(), urlEncode(build.getFilePath()), PcClientInfoSuffixParam()}; } else { // 家庭云逻辑 sessionKey = session.getFamilySessionKey(); sessionSecret = session.getFamilySessionSecret(); if (build.getFileId().isEmpty()) throw new RuntimeException("FileId为空"); fullUrlPattern = "%s/family/file/getFolderInfo.action?familyId=%d&folderId=%s&folderPath=%s&pathList=0&%s"; formatArgs = new Object[]{API_URL, build.getFamilyId(), build.getFileId(), urlEncode(build.getFilePath()), PcClientInfoSuffixParam()}; } var xmlData = send(fullUrlPattern, formatArgs, sessionKey, sessionSecret); if (xmlData.contains("error")) { var appErrorXmlResp = XmlUtils.xmlToObject(xmlData, AppErrorXmlResp.class); throw new RuntimeException("请求失败:" + appErrorXmlResp.getCode()); } return XmlUtils.xmlToObject(xmlData, AppGetFileInfoResult.class); } // 获取指定目录下的所有文件列表 @SneakyThrows public static ListFiles appGetAllFileList(AppFileListParam param) { // 参数校验 if (param.getPageSize() <= 0) param.setPageSize(200); if (param.getFamilyId() > 0 && "-11".equals(param.getFileId())) param.setFileId(""); // 获取初始文件列表 var files = appFileList(param); if (files == null) throw new RuntimeException("文件列表为空"); var fileList = files.getFileList(); int totalFilesCount = fileList.getCount(); // 检查是否需要分页 if (totalFilesCount > param.getPageSize()) { int pageNum = (int) Math.ceil((double) totalFilesCount / param.getPageSize()); for (int i = 2; i <= pageNum; i++) { param.setPageNum(i); var additionalFiles = appFileList(param).getFileList(); if (additionalFiles != null) { if (additionalFiles.getFile() != null) fileList.getFile().addAll(additionalFiles.getFile()); if (additionalFiles.getFolder() != null) fileList.getFolder().addAll(additionalFiles.getFolder()); } TimeUnit.MILLISECONDS.sleep(100); } } return files; } //获取文件列表 public static ListFiles appFileList(AppFileListParam param) { Object[] formatArgs; var session = getSession(); String sessionKey, sessionSecret, fullUrlPattern; if (param.getFamilyId() <= 0) { sessionKey = session.getSessionKey(); sessionSecret = session.getSessionSecret(); fullUrlPattern = "%s/listFiles.action?folderId=%s&recursive=0&fileType=0&iconOption=10&mediaAttr=0&orderBy=%s&descending=%s&pageNum=%s&pageSize=%s&%s"; formatArgs = new Object[]{API_URL, param.getFileId(), OrderEnums.getByCode(param.getOrderBy()), false, param.getPageNum(), param.getPageSize(), PcClientInfoSuffixParam()}; } else { // 家庭云 if (rootNode.equals(param.getFileId())) param.setFileId(""); sessionKey = session.getFamilySessionKey(); sessionSecret = session.getFamilySessionSecret(); fullUrlPattern = "%s/family/file/listFiles.action?folderId=%s&familyId=%s&fileType=0&iconOption=0&mediaAttr=0&orderBy=%s&descending=%s&pageNum=%d&pageSize=%d&%s"; formatArgs = new Object[]{API_URL, param.getFileId(), param.getFamilyId(), OrderEnums.getByCode(param.getOrderBy()), false, param.getPageNum(), param.getPageSize(), PcClientInfoSuffixParam()}; } var send = send(fullUrlPattern, formatArgs, sessionKey, sessionSecret); return XmlUtils.xmlToObject(send, ListFiles.class); } // 通过FileId获取文件的绝对路径 @SneakyThrows public static String appFilePathById(Integer familyId, String fileId) { var fullPath = ""; var param = AppGetFileInfoParam.builder() .familyId(familyId) .fileId(fileId).build(); while (true) { var fi = appGetBasicFileInfo(param); if (fi == null) throw new RuntimeException("FileInfo is null"); if (!fi.getPath().isEmpty()) return fi.getPath(); if (fi.getId().startsWith("-") || fi.getParentFolderId().startsWith("-")) { fullPath = "/" + fullPath; break; } fullPath = fullPath.isEmpty() ? fi.getName() : fi.getName() + "/" + fullPath; param = AppGetFileInfoParam.builder() .fileId(fi.getParentFolderId()).build(); TimeUnit.MILLISECONDS.sleep(100); } return fullPath; } // 通过FileId获取文件详情 public static AppFileEntity appFileInfoById(Integer familyId, String fileId) { var param = AppGetFileInfoParam.builder() .familyId(familyId) .fileId(fileId).build(); var result = appGetBasicFileInfo(param); var build = AppFileListParam.builder() .fileId(result.getParentFolderId()) .familyId(familyId).build(); var files = appGetAllFileList(build); var file = files.getFileList().getFile(); if (file == null) throw new RuntimeException("文件列表为空"); var collect = convert(file, result.getPath(), result.getParentFolderId()).stream().filter(e -> e.getFileId().equals(fileId)).toList(); if (collect.isEmpty()) throw new RuntimeException("文件不存在"); return collect.getFirst(); } // 递归获取文件夹下的所有文件 包括子文件夹
public static FileSystemEntity appFileListByPath(Integer familyId, String path) {
5
2023-12-02 17:02:16+00:00
8k
ynewmark/vector-lang
compiler/src/main/java/org/vectorlang/compiler/compiler/Typer.java
[ { "identifier": "AssignStatement", "path": "compiler/src/main/java/org/vectorlang/compiler/ast/AssignStatement.java", "snippet": "public class AssignStatement extends Statement {\n\n private final String leftHand;\n private final Expression rightHand;\n\n public AssignStatement(String leftHand,...
import java.util.ArrayList; import java.util.List; import org.vectorlang.compiler.ast.AssignStatement; import org.vectorlang.compiler.ast.BinaryExpression; import org.vectorlang.compiler.ast.BinaryOperator; import org.vectorlang.compiler.ast.BlockStatement; import org.vectorlang.compiler.ast.CallExpression; import org.vectorlang.compiler.ast.CodeBase; import org.vectorlang.compiler.ast.DeclareStatement; import org.vectorlang.compiler.ast.Expression; import org.vectorlang.compiler.ast.ForStatement; import org.vectorlang.compiler.ast.FunctionStatement; import org.vectorlang.compiler.ast.GroupingExpression; import org.vectorlang.compiler.ast.IdentifierExpression; import org.vectorlang.compiler.ast.IfStatement; import org.vectorlang.compiler.ast.IndexExpression; import org.vectorlang.compiler.ast.LiteralExpression; import org.vectorlang.compiler.ast.Node; import org.vectorlang.compiler.ast.PrintStatement; import org.vectorlang.compiler.ast.ReturnStatement; import org.vectorlang.compiler.ast.Statement; import org.vectorlang.compiler.ast.StaticExpression; import org.vectorlang.compiler.ast.UnaryExpression; import org.vectorlang.compiler.ast.UnaryOperator; import org.vectorlang.compiler.ast.VectorExpression; import org.vectorlang.compiler.ast.Visitor; import org.vectorlang.compiler.ast.WhileStatement;
6,059
unaryTable.put(BaseType.BOOL, UnaryOperator.NEGATE, BaseType.BOOL); unaryTable.put(BaseType.INT, UnaryOperator.INVERSE, BaseType.INT); unaryTable.put(BaseType.FLOAT, UnaryOperator.INVERSE, BaseType.FLOAT); binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.AND, BaseType.BOOL); binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.OR, BaseType.BOOL); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.ADD, BaseType.INT); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.SUBTRACT, BaseType.INT); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.MULTIPLY, BaseType.INT); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.DIVIDE, BaseType.INT); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.ADD, BaseType.FLOAT); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.SUBTRACT, BaseType.FLOAT); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.MULTIPLY, BaseType.FLOAT); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.DIVIDE, BaseType.FLOAT); binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.EQUAL, BaseType.BOOL); binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.NOT_EQUAL, BaseType.BOOL); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.EQUAL, BaseType.BOOL); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.NOT_EQUAL, BaseType.BOOL); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.EQUAL, BaseType.BOOL); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.NOT_EQUAL, BaseType.BOOL); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.LESS_THAN, BaseType.BOOL); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.EQUAL_LESS_THAN, BaseType.BOOL); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.GREATER_THAN, BaseType.BOOL); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.EQUAL_GREATER_THAN, BaseType.BOOL); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.LESS_THAN, BaseType.BOOL); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.EQUAL_LESS_THAN, BaseType.BOOL); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.GREATER_THAN, BaseType.BOOL); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.EQUAL_GREATER_THAN, BaseType.BOOL); } public List<TypeFailure> getFailures() { return failures; } public CodeBase type(CodeBase codeBase) { TyperState state = new TyperState(); for (FunctionStatement statement : codeBase.getFunctions()) { state.putFunc(statement.getName(), statement.getParameterTypes(), statement.getReturnType()); } FunctionStatement[] functions = new FunctionStatement[codeBase.getFunctions().length]; for (int i = 0; i < functions.length; i++) { functions[i] = (FunctionStatement) codeBase.getFunctions()[i].accept(this, state); } return new CodeBase(functions); } @Override public Node visitBinaryExpr(BinaryExpression expression, TyperState arg) { Expression left = (Expression) expression.getLeft().visitExpression(this, arg); Expression right = (Expression) expression.getRight().visitExpression(this, arg); if (expression.getOperator() == BinaryOperator.CONCAT) { if (left.getType().indexed().equals(right.getType().indexed())) { return new BinaryExpression(left, right, expression.getOperator(), left.getType().concat(right.getType())); } else { failures.add(new TypeFailure(left.getType(), right.getType(), "cannot concat")); return new BinaryExpression(left, right, expression.getOperator()); } } BaseType result = binaryTable.get( left.getType().getBaseType(), right.getType().getBaseType(), expression.getOperator() ); if (result == null) { failures.add(new TypeFailure(left.getType(), right.getType(), "operator " + expression.getOperator())); return new BinaryExpression(left, right, expression.getOperator()); } Type type = new Type(result, left.getType().getShape(), true); return new BinaryExpression(left, right, expression.getOperator(), type); } @Override public Node visitGroupingExpr(GroupingExpression expression, TyperState arg) { Expression newExpression = (Expression) expression.getExpression().visitExpression(this, arg); return new GroupingExpression(newExpression, newExpression.getType()); } @Override public Node visitIdentifierExpr(IdentifierExpression expression, TyperState arg) { Type type = arg.get(expression.getName()); if (type == null) { failures.add(new TypeFailure(null, null, expression.getName() + " not found")); return expression; } return new IdentifierExpression(expression.getName(), type); } @Override public Node visitLiteralExpr(LiteralExpression expression, TyperState arg) { return expression; } @Override public Node visitUnaryExpr(UnaryExpression expression, TyperState arg) { Expression expr = (Expression) expression.getExpression().visitExpression(this, arg); BaseType result = unaryTable.get(expr.getType().getBaseType(), expression.getOperator()); if (result == null) { failures.add(new TypeFailure(expr.getType(), null, "operator " + expression.getOperator())); return new UnaryExpression(expr, expression.getOperator()); } Type type = new Type(result, expr.getType().getShape(), true); return new UnaryExpression(expr, expression.getOperator(), type); } @Override public Node visitVectorExpr(VectorExpression expression, TyperState arg) { if (expression.getExpressions().length == 0) { failures.add(new TypeFailure(null, null, "length of 0")); return expression; } Expression[] expressions = new Expression[expression.getExpressions().length]; expressions[0] = (Expression) expression.getExpressions()[0].visitExpression(this, arg); for (int i = 1; i < expressions.length; i++) { expressions[i] = (Expression) expression.getExpressions()[i].visitExpression(this, arg); if (!expressions[i].getType().equals(expressions[0].getType())) { failures.add(new TypeFailure(expressions[0].getType(), expressions[i].getType(), "mismatched vector")); } } return new VectorExpression(expressions, expressions[0].getType().vectorize(expressions.length).constant()); } @Override
package org.vectorlang.compiler.compiler; public class Typer implements Visitor<TyperState, Node> { private static UnaryTable<BaseType> unaryTable; private static BinaryTable<BaseType> binaryTable; private List<TypeFailure> failures; public Typer() { this.failures = new ArrayList<>(); } static { unaryTable = new UnaryTable<>(); binaryTable = new BinaryTable<>(); unaryTable.put(BaseType.BOOL, UnaryOperator.NEGATE, BaseType.BOOL); unaryTable.put(BaseType.INT, UnaryOperator.INVERSE, BaseType.INT); unaryTable.put(BaseType.FLOAT, UnaryOperator.INVERSE, BaseType.FLOAT); binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.AND, BaseType.BOOL); binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.OR, BaseType.BOOL); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.ADD, BaseType.INT); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.SUBTRACT, BaseType.INT); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.MULTIPLY, BaseType.INT); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.DIVIDE, BaseType.INT); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.ADD, BaseType.FLOAT); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.SUBTRACT, BaseType.FLOAT); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.MULTIPLY, BaseType.FLOAT); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.DIVIDE, BaseType.FLOAT); binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.EQUAL, BaseType.BOOL); binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.NOT_EQUAL, BaseType.BOOL); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.EQUAL, BaseType.BOOL); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.NOT_EQUAL, BaseType.BOOL); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.EQUAL, BaseType.BOOL); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.NOT_EQUAL, BaseType.BOOL); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.LESS_THAN, BaseType.BOOL); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.EQUAL_LESS_THAN, BaseType.BOOL); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.GREATER_THAN, BaseType.BOOL); binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.EQUAL_GREATER_THAN, BaseType.BOOL); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.LESS_THAN, BaseType.BOOL); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.EQUAL_LESS_THAN, BaseType.BOOL); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.GREATER_THAN, BaseType.BOOL); binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.EQUAL_GREATER_THAN, BaseType.BOOL); } public List<TypeFailure> getFailures() { return failures; } public CodeBase type(CodeBase codeBase) { TyperState state = new TyperState(); for (FunctionStatement statement : codeBase.getFunctions()) { state.putFunc(statement.getName(), statement.getParameterTypes(), statement.getReturnType()); } FunctionStatement[] functions = new FunctionStatement[codeBase.getFunctions().length]; for (int i = 0; i < functions.length; i++) { functions[i] = (FunctionStatement) codeBase.getFunctions()[i].accept(this, state); } return new CodeBase(functions); } @Override public Node visitBinaryExpr(BinaryExpression expression, TyperState arg) { Expression left = (Expression) expression.getLeft().visitExpression(this, arg); Expression right = (Expression) expression.getRight().visitExpression(this, arg); if (expression.getOperator() == BinaryOperator.CONCAT) { if (left.getType().indexed().equals(right.getType().indexed())) { return new BinaryExpression(left, right, expression.getOperator(), left.getType().concat(right.getType())); } else { failures.add(new TypeFailure(left.getType(), right.getType(), "cannot concat")); return new BinaryExpression(left, right, expression.getOperator()); } } BaseType result = binaryTable.get( left.getType().getBaseType(), right.getType().getBaseType(), expression.getOperator() ); if (result == null) { failures.add(new TypeFailure(left.getType(), right.getType(), "operator " + expression.getOperator())); return new BinaryExpression(left, right, expression.getOperator()); } Type type = new Type(result, left.getType().getShape(), true); return new BinaryExpression(left, right, expression.getOperator(), type); } @Override public Node visitGroupingExpr(GroupingExpression expression, TyperState arg) { Expression newExpression = (Expression) expression.getExpression().visitExpression(this, arg); return new GroupingExpression(newExpression, newExpression.getType()); } @Override public Node visitIdentifierExpr(IdentifierExpression expression, TyperState arg) { Type type = arg.get(expression.getName()); if (type == null) { failures.add(new TypeFailure(null, null, expression.getName() + " not found")); return expression; } return new IdentifierExpression(expression.getName(), type); } @Override public Node visitLiteralExpr(LiteralExpression expression, TyperState arg) { return expression; } @Override public Node visitUnaryExpr(UnaryExpression expression, TyperState arg) { Expression expr = (Expression) expression.getExpression().visitExpression(this, arg); BaseType result = unaryTable.get(expr.getType().getBaseType(), expression.getOperator()); if (result == null) { failures.add(new TypeFailure(expr.getType(), null, "operator " + expression.getOperator())); return new UnaryExpression(expr, expression.getOperator()); } Type type = new Type(result, expr.getType().getShape(), true); return new UnaryExpression(expr, expression.getOperator(), type); } @Override public Node visitVectorExpr(VectorExpression expression, TyperState arg) { if (expression.getExpressions().length == 0) { failures.add(new TypeFailure(null, null, "length of 0")); return expression; } Expression[] expressions = new Expression[expression.getExpressions().length]; expressions[0] = (Expression) expression.getExpressions()[0].visitExpression(this, arg); for (int i = 1; i < expressions.length; i++) { expressions[i] = (Expression) expression.getExpressions()[i].visitExpression(this, arg); if (!expressions[i].getType().equals(expressions[0].getType())) { failures.add(new TypeFailure(expressions[0].getType(), expressions[i].getType(), "mismatched vector")); } } return new VectorExpression(expressions, expressions[0].getType().vectorize(expressions.length).constant()); } @Override
public Node visitIndexExpr(IndexExpression expression, TyperState arg) {
13
2023-11-30 04:22:36+00:00
8k
ExternalService/sft
src/main/java/com/nbnw/sft/network/client/SleepFeatureToggleHandler.java
[ { "identifier": "LangManager", "path": "src/main/java/com/nbnw/sft/common/LangManager.java", "snippet": "public class LangManager {\n public static final String keyCategories = \"sft.key.categories\";\n public static final String sleepToggle = \"sft.key.toggleSleepKey\";\n // 功能开启、关闭时的公共前缀信息\n ...
import com.nbnw.sft.common.LangManager; import cpw.mods.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.common.config.Configuration; import com.nbnw.sft.config.ModConfig; import com.nbnw.sft.handler.ScreenMessageHandler; import com.nbnw.sft.network.CommonMessagePacket; import com.nbnw.sft.network.CommonMessagePacket.MessageType;
4,627
package com.nbnw.sft.network.client; public class SleepFeatureToggleHandler { private static final int rgbColor = 0xE367E9; public void showServerResultMessage(CommonMessagePacket message, MessageContext ctx) { if (ctx.side.isClient()) { if (!message.getType().equals(MessageType.SERVER_SCREEN_MESSAGE)) { return; } // 同步服务端信息 boolean newSetting = message.getSleepToggle();
package com.nbnw.sft.network.client; public class SleepFeatureToggleHandler { private static final int rgbColor = 0xE367E9; public void showServerResultMessage(CommonMessagePacket message, MessageContext ctx) { if (ctx.side.isClient()) { if (!message.getType().equals(MessageType.SERVER_SCREEN_MESSAGE)) { return; } // 同步服务端信息 boolean newSetting = message.getSleepToggle();
ModConfig.getInstance().getConfig().get(Configuration.CATEGORY_GENERAL, "several_player_sleep", true).set(newSetting);
1
2023-11-29 15:20:07+00:00
8k
id681ilyg316/jsp_medicine_jxc
源码/jsp_medicine_jxc/src/com/medicine/action/StaffAction.java
[ { "identifier": "StaffDao", "path": "源码/jsp_medicine_jxc/src/com/medicine/dao/StaffDao.java", "snippet": "public class StaffDao {\r\n\r\n\tpublic List<Staff> getStaffList(Connection con,Staff s_staff,PageBean pageBean) throws Exception{\r\n\t\tList<Staff> staffList=new ArrayList<Staff>();\r\n\t\tStringB...
import java.sql.Connection; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.ServletRequestAware; import com.medicine.dao.StaffDao; import com.medicine.model.PageBean; import com.medicine.model.Staff; import com.medicine.util.DbUtil; import com.medicine.util.NavUtil; import com.medicine.util.PageUtil; import com.medicine.util.PropertiesUtil; import com.medicine.util.ResponseUtil; import com.medicine.util.StringUtil; import com.opensymphony.xwork2.ActionSupport; import net.sf.json.JSONObject;
3,834
package com.medicine.action; public class StaffAction extends ActionSupport implements ServletRequestAware{ /** * */ private static final long serialVersionUID = 1L; private HttpServletRequest request; private DbUtil dbUtil=new DbUtil(); private StaffDao staffDao = new StaffDao(); private String page; private int total; private String staffName; public String getStaffName() { return staffName; } public void setStaffName(String staffName) { this.staffName = staffName; } public Staff getS_staff() { return s_staff; } public void setS_staff(Staff s_staff) { this.s_staff = s_staff; } public void setStaffId(String staffId) { this.staffId = staffId; } private String pageCode; private Staff s_staff; private Staff staff; private String staffId; public String getStaffId() { return staffId; } public Staff getStaff() { return staff; } public void setStaff(Staff staff) { this.staff = staff; } public String getPage() { return page; } public void setPage(String page) { this.page = page; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public String getPageCode() { return pageCode; } public void setPageCode(String pageCode) { this.pageCode = pageCode; } private String mainPage; private String navCode; private List<Staff> staffList=new ArrayList<Staff>(); private List<Staff> s_staffList_n; private List<Staff> s_staffList_a; private List<Staff> s_staffList_p; public List<Staff> getS_staffList_n() { return s_staffList_n; } public void setS_staffList_n(List<Staff> s_staffList_n) { this.s_staffList_n = s_staffList_n; } public List<Staff> getS_staffList_a() { return s_staffList_a; } public void setS_staffList_a(List<Staff> s_staffList_a) { this.s_staffList_a = s_staffList_a; } public List<Staff> getS_staffList_p() { return s_staffList_p; } public void setS_staffList_p(List<Staff> s_staffList_p) { this.s_staffList_p = s_staffList_p; } public String getMainPage() { return mainPage; } public void setMainPage(String mainPage) { this.mainPage = mainPage; } public String getNavCode() { return navCode; } public void setNavCode(String navCode) { this.navCode = navCode; } public List<Staff> getStaffList() { return staffList; } public void setStaffList(List<Staff> staffList) { this.staffList = staffList; } public String list(){ HttpSession session=request.getSession(); if(StringUtil.isEmpty(page)){ page="1"; } if(s_staff!=null){ session.setAttribute("s_staff", s_staff); }else{ Object o=session.getAttribute("s_staff"); if(o!=null){ s_staff=(Staff)o; }else{ s_staff=new Staff(); } } Connection con=null; try{ con=dbUtil.getCon(); PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(PropertiesUtil.getValue("pageSize"))); staffList=staffDao.getStaffList(con,s_staff,pageBean); navCode=NavUtil.getNavgation("员工信息管理", "员工修改"); total=staffDao.staffCount(con, s_staff);
package com.medicine.action; public class StaffAction extends ActionSupport implements ServletRequestAware{ /** * */ private static final long serialVersionUID = 1L; private HttpServletRequest request; private DbUtil dbUtil=new DbUtil(); private StaffDao staffDao = new StaffDao(); private String page; private int total; private String staffName; public String getStaffName() { return staffName; } public void setStaffName(String staffName) { this.staffName = staffName; } public Staff getS_staff() { return s_staff; } public void setS_staff(Staff s_staff) { this.s_staff = s_staff; } public void setStaffId(String staffId) { this.staffId = staffId; } private String pageCode; private Staff s_staff; private Staff staff; private String staffId; public String getStaffId() { return staffId; } public Staff getStaff() { return staff; } public void setStaff(Staff staff) { this.staff = staff; } public String getPage() { return page; } public void setPage(String page) { this.page = page; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public String getPageCode() { return pageCode; } public void setPageCode(String pageCode) { this.pageCode = pageCode; } private String mainPage; private String navCode; private List<Staff> staffList=new ArrayList<Staff>(); private List<Staff> s_staffList_n; private List<Staff> s_staffList_a; private List<Staff> s_staffList_p; public List<Staff> getS_staffList_n() { return s_staffList_n; } public void setS_staffList_n(List<Staff> s_staffList_n) { this.s_staffList_n = s_staffList_n; } public List<Staff> getS_staffList_a() { return s_staffList_a; } public void setS_staffList_a(List<Staff> s_staffList_a) { this.s_staffList_a = s_staffList_a; } public List<Staff> getS_staffList_p() { return s_staffList_p; } public void setS_staffList_p(List<Staff> s_staffList_p) { this.s_staffList_p = s_staffList_p; } public String getMainPage() { return mainPage; } public void setMainPage(String mainPage) { this.mainPage = mainPage; } public String getNavCode() { return navCode; } public void setNavCode(String navCode) { this.navCode = navCode; } public List<Staff> getStaffList() { return staffList; } public void setStaffList(List<Staff> staffList) { this.staffList = staffList; } public String list(){ HttpSession session=request.getSession(); if(StringUtil.isEmpty(page)){ page="1"; } if(s_staff!=null){ session.setAttribute("s_staff", s_staff); }else{ Object o=session.getAttribute("s_staff"); if(o!=null){ s_staff=(Staff)o; }else{ s_staff=new Staff(); } } Connection con=null; try{ con=dbUtil.getCon(); PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(PropertiesUtil.getValue("pageSize"))); staffList=staffDao.getStaffList(con,s_staff,pageBean); navCode=NavUtil.getNavgation("员工信息管理", "员工修改"); total=staffDao.staffCount(con, s_staff);
pageCode=PageUtil.genPagation(request.getContextPath()+"/staff!list", total, Integer.parseInt(page), Integer.parseInt(PropertiesUtil.getValue("pageSize")));
5
2023-11-29 14:18:23+00:00
8k
tuxiaobei-scu/Draw-and-guess
entry/src/main/java/com/tuxiaobei/drawandguess/provider/AnswerItemProvider.java
[ { "identifier": "ResourceTable", "path": "entry/build/generated/source/r/debug/com/tuxiaobei/drawandguess/ResourceTable.java", "snippet": "public final class ResourceTable {\n public static final int Graphic_background_ability_main = 0x1000017;\n public static final int Graphic_background_answer =...
import com.tuxiaobei.drawandguess.ResourceTable; import com.tuxiaobei.drawandguess.slice.MainAbilitySlice; import com.tuxiaobei.drawandguess.util.Tools; import ohos.aafwk.ability.AbilitySlice; import ohos.agp.components.*; import com.tuxiaobei.drawandguess.bean.AnswerItem; import ohos.agp.components.element.Element; import java.util.List;
5,898
package com.tuxiaobei.drawandguess.provider; public class AnswerItemProvider extends BaseItemProvider{ private List<AnswerItem> list;
package com.tuxiaobei.drawandguess.provider; public class AnswerItemProvider extends BaseItemProvider{ private List<AnswerItem> list;
private MainAbilitySlice slice;
1
2023-12-03 13:36:00+00:00
8k
godheaven/klib-data-jdbc
src/test/java/cl/kanopus/jdbc/example/AbstractBaseDAO.java
[ { "identifier": "Mapping", "path": "src/main/java/cl/kanopus/jdbc/entity/Mapping.java", "snippet": "public abstract class Mapping implements Serializable {\r\n\r\n private static final Logger LOGGER = LoggerFactory.getLogger(Mapping.class);\r\n\r\n @Override\r\n public String toString() {\r\n\r...
import cl.kanopus.jdbc.entity.Mapping; import cl.kanopus.jdbc.impl.AbstractDAO; import cl.kanopus.jdbc.impl.engine.Engine; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
6,879
package cl.kanopus.jdbc.example; /** * 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. * * @author Pablo Diaz Saavedra * @param <T> * @param <ID> * @email pabloandres.diazsaavedra@gmail.com */ public abstract class AbstractBaseDAO<T extends Mapping, ID> extends AbstractDAO<T, ID> { @Autowired private NamedParameterJdbcTemplate jdbcTemplate; @Override protected NamedParameterJdbcTemplate getJdbcTemplate() { return jdbcTemplate; } @Override
package cl.kanopus.jdbc.example; /** * 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. * * @author Pablo Diaz Saavedra * @param <T> * @param <ID> * @email pabloandres.diazsaavedra@gmail.com */ public abstract class AbstractBaseDAO<T extends Mapping, ID> extends AbstractDAO<T, ID> { @Autowired private NamedParameterJdbcTemplate jdbcTemplate; @Override protected NamedParameterJdbcTemplate getJdbcTemplate() { return jdbcTemplate; } @Override
protected Engine getEngine() {
2
2023-11-27 18:25:00+00:00
8k
andre111/voxedit
src/client/java/me/andre111/voxedit/client/gui/screen/EditBlockPaletteScreen.java
[ { "identifier": "BlockStateWidget", "path": "src/client/java/me/andre111/voxedit/client/gui/widget/BlockStateWidget.java", "snippet": "@Environment(value=EnvType.CLIENT)\npublic class BlockStateWidget extends TextFieldWidget {\n\tpublic static final MatrixStack.Entry BLOCK_POSE;\n\tstatic {\n\t\tMatrixS...
import net.minecraft.client.gui.widget.ButtonWidget; import net.minecraft.screen.ScreenTexts; import net.minecraft.text.Text; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import me.andre111.voxedit.client.gui.widget.BlockStateWidget; import me.andre111.voxedit.client.gui.widget.IntSliderWidget; import me.andre111.voxedit.client.gui.widget.ModListWidget; import me.andre111.voxedit.tool.data.BlockPalette; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.block.Blocks; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.Element; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder;
6,277
/* * 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.gui.screen; @Environment(value=EnvType.CLIENT) public class EditBlockPaletteScreen extends Screen { private final Screen parent; private final int minSize; private final boolean includeProperties; private final boolean showWeights;
/* * 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.gui.screen; @Environment(value=EnvType.CLIENT) public class EditBlockPaletteScreen extends Screen { private final Screen parent; private final int minSize; private final boolean includeProperties; private final boolean showWeights;
private final Consumer<BlockPalette> callback;
3
2023-12-01 15:12:26+00:00
8k
victor-vilar/coleta
backend/src/main/java/com/victorvilar/projetoempresa/controllers/AddressController.java
[ { "identifier": "AddressCreateDto", "path": "backend/src/main/java/com/victorvilar/projetoempresa/dto/adress/AddressCreateDto.java", "snippet": "public class AddressCreateDto {\n\n\n private String addressName;\n private String addressNumber;\n private String complement;\n private String zip...
import com.victorvilar.projetoempresa.dto.adress.AddressCreateDto; import com.victorvilar.projetoempresa.dto.adress.AddressResponseDto; import com.victorvilar.projetoempresa.dto.adress.AddressUpdateDto; import com.victorvilar.projetoempresa.services.AddressService; import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List;
4,084
package com.victorvilar.projetoempresa.controllers; /** * Address controller * @author Victor Vilar * @since 05/01/2023 */ @RestController @RequestMapping("/address") public class AddressController { private final AddressService addressService; @Autowired public AddressController(AddressService service){ this.addressService = service; } /** * get all address * @return list of address */ @GetMapping() public ResponseEntity<List<AddressResponseDto>> getAll(){ return ResponseEntity.status(HttpStatus.OK).body(this.addressService.getAll()); } /** * get all address of a client * @param clientId id of a client * @return a list of address of a client */ @GetMapping("by-customer/{clientId}") public ResponseEntity<List<AddressResponseDto>> getAllByCustomerId(@PathVariable String clientId){ return ResponseEntity.status(HttpStatus.OK).body(this.addressService.getAllByCustomerId(clientId)); } /** * get an address by id * @param id * @return address */ @GetMapping("/{id}") public ResponseEntity<AddressResponseDto> getById(@PathVariable Long id){ return ResponseEntity.status(HttpStatus.OK).body(this.addressService.getById(id)); } /** * create a new addresss * @param addressCreateDto address body to save * @return saved address */ @PostMapping() public ResponseEntity<AddressResponseDto> save(@Valid @RequestBody AddressCreateDto addressCreateDto){ return ResponseEntity.status(HttpStatus.OK).body(this.addressService.save(addressCreateDto)); } /** * delete an address * @param id of an address * @return */ @DeleteMapping("/{id}") public ResponseEntity<?> delete(@PathVariable Long id){ this.addressService.delete(id); return new ResponseEntity<>(HttpStatus.OK); } /** * update an address * @return */ @PutMapping()
package com.victorvilar.projetoempresa.controllers; /** * Address controller * @author Victor Vilar * @since 05/01/2023 */ @RestController @RequestMapping("/address") public class AddressController { private final AddressService addressService; @Autowired public AddressController(AddressService service){ this.addressService = service; } /** * get all address * @return list of address */ @GetMapping() public ResponseEntity<List<AddressResponseDto>> getAll(){ return ResponseEntity.status(HttpStatus.OK).body(this.addressService.getAll()); } /** * get all address of a client * @param clientId id of a client * @return a list of address of a client */ @GetMapping("by-customer/{clientId}") public ResponseEntity<List<AddressResponseDto>> getAllByCustomerId(@PathVariable String clientId){ return ResponseEntity.status(HttpStatus.OK).body(this.addressService.getAllByCustomerId(clientId)); } /** * get an address by id * @param id * @return address */ @GetMapping("/{id}") public ResponseEntity<AddressResponseDto> getById(@PathVariable Long id){ return ResponseEntity.status(HttpStatus.OK).body(this.addressService.getById(id)); } /** * create a new addresss * @param addressCreateDto address body to save * @return saved address */ @PostMapping() public ResponseEntity<AddressResponseDto> save(@Valid @RequestBody AddressCreateDto addressCreateDto){ return ResponseEntity.status(HttpStatus.OK).body(this.addressService.save(addressCreateDto)); } /** * delete an address * @param id of an address * @return */ @DeleteMapping("/{id}") public ResponseEntity<?> delete(@PathVariable Long id){ this.addressService.delete(id); return new ResponseEntity<>(HttpStatus.OK); } /** * update an address * @return */ @PutMapping()
public ResponseEntity<AddressResponseDto> update(@RequestBody AddressUpdateDto addressUpdateDto){
2
2023-12-02 21:29:33+00:00
8k
aliyun/aliyun-pairec-config-java-sdk
src/main/java/com/aliyun/openservices/pairec/api/ExperimentRoomApi.java
[ { "identifier": "Constants", "path": "src/main/java/com/aliyun/openservices/pairec/common/Constants.java", "snippet": "public class Constants {\n public static final String CODE_OK = \"OK\";\n public static final String Environment_Daily_Desc = \"daily\";\n public static final String Environmen...
import com.aliyun.openservices.pairec.common.Constants; import com.aliyun.openservices.pairec.model.ExperimentRoom; import com.aliyun.pairecservice20221213.models.ListLaboratoriesRequest; import com.aliyun.pairecservice20221213.models.ListLaboratoriesResponse; import com.aliyun.pairecservice20221213.models.ListLaboratoriesResponseBody; import com.aliyun.tea.utils.StringUtils; import java.util.ArrayList; import java.util.List;
3,655
package com.aliyun.openservices.pairec.api; public class ExperimentRoomApi extends BaseApi { public ExperimentRoomApi(ApiClient apiClient) { super(apiClient); }
package com.aliyun.openservices.pairec.api; public class ExperimentRoomApi extends BaseApi { public ExperimentRoomApi(ApiClient apiClient) { super(apiClient); }
public List<ExperimentRoom> listExperimentRooms(String environment, Long sceneId, Integer status) throws Exception {
1
2023-11-29 06:27:36+00:00
8k
bioastroiner/Minetweaker-Gregtech6-Addon
src/main/java/mods/bio/gttweaker/mods/minetweaker/CTIOreDictExpansion.java
[ { "identifier": "IMaterialData", "path": "src/main/java/mods/bio/gttweaker/api/mods/gregtech/oredict/IMaterialData.java", "snippet": "@ZenClass(\"mods.gregtech.oredict.IMaterialData\")\npublic interface IMaterialData {\n\t@ZenMethod\n\tpublic static IMaterialData association(IItemStack item) {\n\t\tOreD...
import gregapi.oredict.OreDictManager; import minetweaker.api.item.IItemStack; import minetweaker.api.oredict.IOreDictEntry; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialData; import mods.bio.gttweaker.api.mods.gregtech.oredict.IPrefix; import mods.bio.gttweaker.mods.gregtech.oredict.CTMaterial; import mods.bio.gttweaker.mods.gregtech.oredict.CTMaterialData; import mods.bio.gttweaker.mods.gregtech.oredict.CTPrefix; import mods.bio.gttweaker.mods.gregtech.oredict.CTUnifier; import stanhebben.zenscript.annotations.ZenExpansion; import stanhebben.zenscript.annotations.ZenGetter;
3,761
package mods.bio.gttweaker.mods.minetweaker; @ZenExpansion("minetweaker.oredict.IOreDictEntry") public class CTIOreDictExpansion { @ZenGetter public static IItemStack unified(IOreDictEntry oreDictEntry){ return CTUnifier.unifyItem(oreDictEntry); } @ZenGetter public static CTMaterial material(IOreDictEntry oreDictEntry){ return new CTMaterial(OreDictManager.INSTANCE.getAutomaticItemData(oreDictEntry.getName()).mMaterial.mMaterial); } @ZenGetter public static IPrefix prefix(IOreDictEntry oreDictEntry){
package mods.bio.gttweaker.mods.minetweaker; @ZenExpansion("minetweaker.oredict.IOreDictEntry") public class CTIOreDictExpansion { @ZenGetter public static IItemStack unified(IOreDictEntry oreDictEntry){ return CTUnifier.unifyItem(oreDictEntry); } @ZenGetter public static CTMaterial material(IOreDictEntry oreDictEntry){ return new CTMaterial(OreDictManager.INSTANCE.getAutomaticItemData(oreDictEntry.getName()).mMaterial.mMaterial); } @ZenGetter public static IPrefix prefix(IOreDictEntry oreDictEntry){
return new CTPrefix(OreDictManager.INSTANCE.getAutomaticItemData(oreDictEntry.getName()).mPrefix);
4
2023-12-03 11:55:49+00:00
8k
ariel-mitchell/404-found
server/src/main/java/org/launchcode/fourohfourfound/finalproject/controllers/ApiController.java
[ { "identifier": "CharacterDTO", "path": "server/src/main/java/org/launchcode/fourohfourfound/finalproject/dtos/CharacterDTO.java", "snippet": "@Valid\npublic class CharacterDTO {\n\n @NotNull(message = \"Owner ID cannot be null\")\n private int ownerId;\n\n @NotNull(message = \"Choose a name fo...
import ch.qos.logback.core.net.SyslogOutputStream; import jakarta.servlet.ServletOutputStream; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import jakarta.validation.Valid; import org.launchcode.fourohfourfound.finalproject.dtos.CharacterDTO; import org.launchcode.fourohfourfound.finalproject.dtos.LoginFormDTO; import org.launchcode.fourohfourfound.finalproject.dtos.RegisterFormDTO; import org.launchcode.fourohfourfound.finalproject.repositories.CharacterRepository; import org.launchcode.fourohfourfound.finalproject.repositories.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.launchcode.fourohfourfound.finalproject.models.User; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.*; import org.launchcode.fourohfourfound.finalproject.models.Character; import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; import java.util.Optional;
4,021
package org.launchcode.fourohfourfound.finalproject.controllers; @RestController @CrossOrigin(origins = "http://localhost:5173") @RequestMapping("/api") public class ApiController { private final CharacterRepository characterRepository; private final UserRepository userRepository; private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); @Autowired public ApiController(CharacterRepository characterRepository, UserRepository userRepository) { this.characterRepository = characterRepository; this.userRepository = userRepository; } private static final String userSessionKey = "user"; public User getUserFromSession(HttpSession session) { Integer userId = (Integer) session.getAttribute(userSessionKey); if (userId == null) { return null; } Optional<User> user = userRepository.findById(userId); if (user.isEmpty()) { return null; } return user.get(); } private static void setUserInSession(HttpSession session, User user) { session.setAttribute(userSessionKey, user.getId()); } public ResponseEntity<User> getCurrentUser(HttpSession session) { User user = getUserFromSession(session); if (user == null) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } return new ResponseEntity<>(user, HttpStatus.OK); } @GetMapping("/currentUserId") public ResponseEntity<Integer> getCurrentUserId (HttpSession session) { User user = getUserFromSession(session); if (user == null) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } return new ResponseEntity<>(user.getId(),HttpStatus.OK); } @PostMapping("/register") public ResponseEntity<?> registerUser(@RequestBody @Valid RegisterFormDTO registerFormDTO, Errors errors, HttpServletRequest request) { if (errors.hasErrors()) { System.out.println(errors.getAllErrors()); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } User existingUser = userRepository.findByUsernameIgnoreCase(registerFormDTO.getUsername()); if (existingUser != null) { return new ResponseEntity<String>("Username already exists", HttpStatus.CONFLICT); } String password = registerFormDTO.getPassword(); String verifyPassword = registerFormDTO.getVerifyPassword(); if (!password.equals(verifyPassword)) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } User newUser = new User(registerFormDTO.getUsername(), registerFormDTO.getEmail(),passwordEncoder.encode(password)); userRepository.save(newUser); setUserInSession(request.getSession(), newUser); return new ResponseEntity<>(newUser, HttpStatus.CREATED); } @GetMapping("/login") public ResponseEntity<String> displayLoginForm() { return new ResponseEntity<>("Please log in", HttpStatus.OK); } @PostMapping("/login")
package org.launchcode.fourohfourfound.finalproject.controllers; @RestController @CrossOrigin(origins = "http://localhost:5173") @RequestMapping("/api") public class ApiController { private final CharacterRepository characterRepository; private final UserRepository userRepository; private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); @Autowired public ApiController(CharacterRepository characterRepository, UserRepository userRepository) { this.characterRepository = characterRepository; this.userRepository = userRepository; } private static final String userSessionKey = "user"; public User getUserFromSession(HttpSession session) { Integer userId = (Integer) session.getAttribute(userSessionKey); if (userId == null) { return null; } Optional<User> user = userRepository.findById(userId); if (user.isEmpty()) { return null; } return user.get(); } private static void setUserInSession(HttpSession session, User user) { session.setAttribute(userSessionKey, user.getId()); } public ResponseEntity<User> getCurrentUser(HttpSession session) { User user = getUserFromSession(session); if (user == null) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } return new ResponseEntity<>(user, HttpStatus.OK); } @GetMapping("/currentUserId") public ResponseEntity<Integer> getCurrentUserId (HttpSession session) { User user = getUserFromSession(session); if (user == null) { return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } return new ResponseEntity<>(user.getId(),HttpStatus.OK); } @PostMapping("/register") public ResponseEntity<?> registerUser(@RequestBody @Valid RegisterFormDTO registerFormDTO, Errors errors, HttpServletRequest request) { if (errors.hasErrors()) { System.out.println(errors.getAllErrors()); return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } User existingUser = userRepository.findByUsernameIgnoreCase(registerFormDTO.getUsername()); if (existingUser != null) { return new ResponseEntity<String>("Username already exists", HttpStatus.CONFLICT); } String password = registerFormDTO.getPassword(); String verifyPassword = registerFormDTO.getVerifyPassword(); if (!password.equals(verifyPassword)) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } User newUser = new User(registerFormDTO.getUsername(), registerFormDTO.getEmail(),passwordEncoder.encode(password)); userRepository.save(newUser); setUserInSession(request.getSession(), newUser); return new ResponseEntity<>(newUser, HttpStatus.CREATED); } @GetMapping("/login") public ResponseEntity<String> displayLoginForm() { return new ResponseEntity<>("Please log in", HttpStatus.OK); } @PostMapping("/login")
public ResponseEntity<User> processLoginForm(@RequestBody @Valid LoginFormDTO loginFormDTO, Errors errors, HttpServletRequest request) {
1
2023-11-28 01:32:31+00:00
8k
perfree/perfree-cms
perfree-system/perfree-system-biz/src/main/java/com/perfree/system/service/user/UserServiceImpl.java
[ { "identifier": "CaptchaCacheService", "path": "perfree-core/src/main/java/com/perfree/cache/CaptchaCacheService.java", "snippet": "@Service\npublic class CaptchaCacheService {\n private final Cache<String, String> verificationCodeCache;\n\n public CaptchaCacheService() {\n verificationCode...
import cn.hutool.crypto.digest.DigestUtil; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.perfree.cache.CaptchaCacheService; import com.perfree.enums.ErrorCode; import com.perfree.commons.exception.ServiceException; import com.perfree.security.SecurityFrameworkUtils; import com.perfree.security.util.JwtUtil; import com.perfree.security.vo.LoginUserVO; import com.perfree.system.convert.user.UserConvert; import com.perfree.system.mapper.RoleMapper; import com.perfree.system.mapper.UserMapper; import com.perfree.system.model.Role; import com.perfree.system.model.User; import com.perfree.system.vo.system.LoginUserInfoRespVO; import com.perfree.system.vo.system.LoginUserReqVO; import com.perfree.system.vo.system.LoginUserRespVO; import com.perfree.security.SecurityConstants; import jakarta.annotation.Resource; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import java.time.ZoneId; import java.util.Date;
4,316
package com.perfree.system.service.user; /** * <p> * 服务实现类 * </p> * * @author perfree * @since 2023-09-27 */ @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Resource private UserMapper userMapper; @Resource private RoleMapper roleMapper; @Resource private CaptchaCacheService captchaCacheService; @Override
package com.perfree.system.service.user; /** * <p> * 服务实现类 * </p> * * @author perfree * @since 2023-09-27 */ @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Resource private UserMapper userMapper; @Resource private RoleMapper roleMapper; @Resource private CaptchaCacheService captchaCacheService; @Override
public LoginUserRespVO login(LoginUserReqVO loginUserVO) {
12
2023-12-01 23:37:25+00:00
8k
tuxiaobei-scu/SCU-CCSOJ-Backend
JudgeServer/src/main/java/top/hcode/hoj/dao/impl/JudgeServerEntityServiceImpl.java
[ { "identifier": "SandboxRun", "path": "JudgeServer/src/main/java/top/hcode/hoj/judge/SandboxRun.java", "snippet": "@Slf4j(topic = \"hoj\")\npublic class SandboxRun {\n\n private static final RestTemplate restTemplate;\n\n // 单例模式\n private static final SandboxRun instance = new SandboxRun();\n\...
import cn.hutool.core.map.MapUtil; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Service; import top.hcode.hoj.judge.SandboxRun; import top.hcode.hoj.mapper.JudgeServerMapper; import top.hcode.hoj.pojo.entity.judge.JudgeServer; import top.hcode.hoj.dao.JudgeServerEntityService; import java.util.Arrays; import java.util.Date; import java.util.HashMap;
6,782
package top.hcode.hoj.dao.impl; /** * @Author: Himit_ZH * @Date: 2021/4/15 11:27 * @Description: */ @Service @Slf4j(topic = "hoj") @RefreshScope
package top.hcode.hoj.dao.impl; /** * @Author: Himit_ZH * @Date: 2021/4/15 11:27 * @Description: */ @Service @Slf4j(topic = "hoj") @RefreshScope
public class JudgeServerEntityServiceImpl extends ServiceImpl<JudgeServerMapper, JudgeServer> implements JudgeServerEntityService {
2
2023-12-03 14:15:51+00:00
8k
FIREBOTICS/SwerveBot
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "ControllerConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static final class ControllerConstants {\n\n public static final int driverGamepadPort = 0;\n\n public static final double joystickDeadband = 0.15;\n\n public static final double triggerP...
import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.button.JoystickButton; import edu.wpi.first.wpilibj2.command.button.Trigger; import frc.robot.Constants.ControllerConstants; import frc.robot.commands.drivetrain.IncreaseSpdCmd; import frc.robot.commands.drivetrain.DecreaseSpdCmd; import frc.robot.commands.drivetrain.LockCmd; import frc.robot.commands.drivetrain.ResetHeadingCmd; import frc.robot.commands.drivetrain.SwerveDriveCmd; import frc.robot.subsystems.SwerveSys;
5,661
package frc.robot; public class RobotContainer { // Initialize subsystems. private final SwerveSys swerveSys = new SwerveSys(); // Initialize joysticks. private final XboxController driverController = new XboxController(ControllerConstants.driverGamepadPort); private final JoystickButton driverMenuBtn = new JoystickButton(driverController, 8); private final Trigger driverLeftTriggerBtn = new Trigger(() -> driverController.getLeftTriggerAxis() > ControllerConstants.triggerPressedThreshhold); private final Trigger driverSpeedUpButton = new Trigger(() -> driverController.getXButtonPressed()); private final Trigger driverSlowDownButton = new Trigger(() -> driverController.getAButtonPressed()); // Initialize auto selector. SendableChooser<Command> autoSelector = new SendableChooser<Command>(); public RobotContainer() { SmartDashboard.putData("auto selector", autoSelector); configDriverBindings(); } public void configDriverBindings() { swerveSys.setDefaultCommand( new SwerveDriveCmd( () -> deadband(driverController.getLeftY()), () -> deadband(driverController.getLeftX()), () -> deadband(driverController.getRightX()), true, //Switch to False for Chairbot Mode swerveSys ) );
package frc.robot; public class RobotContainer { // Initialize subsystems. private final SwerveSys swerveSys = new SwerveSys(); // Initialize joysticks. private final XboxController driverController = new XboxController(ControllerConstants.driverGamepadPort); private final JoystickButton driverMenuBtn = new JoystickButton(driverController, 8); private final Trigger driverLeftTriggerBtn = new Trigger(() -> driverController.getLeftTriggerAxis() > ControllerConstants.triggerPressedThreshhold); private final Trigger driverSpeedUpButton = new Trigger(() -> driverController.getXButtonPressed()); private final Trigger driverSlowDownButton = new Trigger(() -> driverController.getAButtonPressed()); // Initialize auto selector. SendableChooser<Command> autoSelector = new SendableChooser<Command>(); public RobotContainer() { SmartDashboard.putData("auto selector", autoSelector); configDriverBindings(); } public void configDriverBindings() { swerveSys.setDefaultCommand( new SwerveDriveCmd( () -> deadband(driverController.getLeftY()), () -> deadband(driverController.getLeftX()), () -> deadband(driverController.getRightX()), true, //Switch to False for Chairbot Mode swerveSys ) );
driverMenuBtn.onTrue(new ResetHeadingCmd(swerveSys));
4
2023-11-30 00:00:43+00:00
8k
yichenhsiaonz/EscAIpe-room-final
src/main/java/nz/ac/auckland/se206/TextToSpeechManager.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 javafx.concurrent.Task; import nz.ac.auckland.se206.controllers.SharedElements; import nz.ac.auckland.se206.speech.TextToSpeech;
7,143
package nz.ac.auckland.se206; /** This class manages the text to speech that plays for the user. */ public class TextToSpeechManager { private static TextToSpeech textToSpeech = new TextToSpeech(); private static Task<Void> task; public static boolean hideOnComplete = false; /** * Speaks the given sentences, and hides the chat bubble when complete. * * @param sentences sentences to speak */ public static void speak(String... sentences) { hideOnComplete = false; cutOff(); hideOnComplete = true; // Run in a separate thread to avoid blocking the UI thread task = new Task<Void>() { @Override protected Void call() throws InterruptedException { textToSpeech.speak(sentences); if (hideOnComplete) {
package nz.ac.auckland.se206; /** This class manages the text to speech that plays for the user. */ public class TextToSpeechManager { private static TextToSpeech textToSpeech = new TextToSpeech(); private static Task<Void> task; public static boolean hideOnComplete = false; /** * Speaks the given sentences, and hides the chat bubble when complete. * * @param sentences sentences to speak */ public static void speak(String... sentences) { hideOnComplete = false; cutOff(); hideOnComplete = true; // Run in a separate thread to avoid blocking the UI thread task = new Task<Void>() { @Override protected Void call() throws InterruptedException { textToSpeech.speak(sentences); if (hideOnComplete) {
SharedElements.hideChatBubble();
0
2023-12-02 04:57:43+00:00
8k
SverreNystad/board-master
backend/src/test/java/board/master/service/GameServiceTest.java
[ { "identifier": "GameResponse", "path": "backend/src/main/java/board/master/model/communication/GameResponse.java", "snippet": "public class GameResponse {\n private final String gameId;\n private final String status;\n private final Board board;\n\n public GameResponse(String gameId, String...
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import board.master.model.communication.GameResponse; import board.master.model.communication.GameStartRequest; import board.master.model.communication.MoveRequest; import board.master.model.games.Board; import board.master.model.games.chess.Chess; import board.master.model.games.tictactoe.TicTacToe;
5,659
package board.master.service; public class GameServiceTest { private GameService gameService; private String gameIdOfGameInService; private Board boardOfGameInService; private final String nonUsedGameId = "nonUsedGameId"; @BeforeEach void GameServiceSetup() { gameService = new GameService(); // Make a game to be used in tests String gameType = "tic-tac-toe"; String botType = "random"; GameStartRequest request = new GameStartRequest(botType, gameType); GameResponse response = gameService.startGame(request); gameIdOfGameInService = response.getGameId(); } @Nested @DisplayName("Test of startGame") class CreationOfGames { @Test @DisplayName("Test of startGame with chess") void testStartGameChess() { String gameType = "chess"; String botType = "random";
package board.master.service; public class GameServiceTest { private GameService gameService; private String gameIdOfGameInService; private Board boardOfGameInService; private final String nonUsedGameId = "nonUsedGameId"; @BeforeEach void GameServiceSetup() { gameService = new GameService(); // Make a game to be used in tests String gameType = "tic-tac-toe"; String botType = "random"; GameStartRequest request = new GameStartRequest(botType, gameType); GameResponse response = gameService.startGame(request); gameIdOfGameInService = response.getGameId(); } @Nested @DisplayName("Test of startGame") class CreationOfGames { @Test @DisplayName("Test of startGame with chess") void testStartGameChess() { String gameType = "chess"; String botType = "random";
Board expectedBoard = new Chess().getBoard();
4
2023-11-30 21:27:22+00:00
8k
nageoffer/shortlink
admin/src/main/java/com/nageoffer/shortlink/admin/controller/RecycleBinController.java
[ { "identifier": "Result", "path": "admin/src/main/java/com/nageoffer/shortlink/admin/common/convention/result/Result.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class Result<T> implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 5679018624309023727L;...
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.baomidou.mybatisplus.core.metadata.IPage; import com.nageoffer.shortlink.admin.common.convention.result.Result; import com.nageoffer.shortlink.admin.common.convention.result.Results; import com.nageoffer.shortlink.admin.dto.req.RecycleBinRecoverReqDTO; import com.nageoffer.shortlink.admin.dto.req.RecycleBinRemoveReqDTO; import com.nageoffer.shortlink.admin.dto.req.RecycleBinSaveReqDTO; import com.nageoffer.shortlink.admin.remote.ShortLinkRemoteService; import com.nageoffer.shortlink.admin.remote.dto.req.ShortLinkRecycleBinPageReqDTO; import com.nageoffer.shortlink.admin.remote.dto.resp.ShortLinkPageRespDTO; import com.nageoffer.shortlink.admin.service.RecycleBinService; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping;
4,192
/* * 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.admin.controller; /** * 回收站管理控制层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @RestController @RequiredArgsConstructor public class RecycleBinController { private final RecycleBinService recycleBinService; /** * 后续重构为 SpringCloud Feign 调用 */ ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() { }; /** * 保存回收站 */ @PostMapping("/api/short-link/admin/v1/recycle-bin/save")
/* * 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.admin.controller; /** * 回收站管理控制层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @RestController @RequiredArgsConstructor public class RecycleBinController { private final RecycleBinService recycleBinService; /** * 后续重构为 SpringCloud Feign 调用 */ ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() { }; /** * 保存回收站 */ @PostMapping("/api/short-link/admin/v1/recycle-bin/save")
public Result<Void> saveRecycleBin(@RequestBody RecycleBinSaveReqDTO requestParam) {
0
2023-11-19 16:04:32+00:00
8k
NEWCIH2023/galois
src/main/java/io/liuguangsheng/galois/service/MethodAdapter.java
[ { "identifier": "GlobalConfiguration", "path": "src/main/java/io/liuguangsheng/galois/conf/GlobalConfiguration.java", "snippet": "public class GlobalConfiguration {\n\n private static final String GALOIS_PROPERTIES = \"galois.properties\";\n private static final Properties configuration = new Prop...
import java.io.File; import java.io.FileOutputStream; import java.util.Arrays; import java.util.Optional; import static io.liuguangsheng.galois.constants.ConfConstant.PRINT_ASM_CODE_ENABLE; import static io.liuguangsheng.galois.constants.Constant.DOT; import static io.liuguangsheng.galois.constants.Constant.USER_DIR; import static io.liuguangsheng.galois.constants.FileType.CLASS_FILE; import static jdk.internal.org.objectweb.asm.Opcodes.ASM5; import io.liuguangsheng.galois.conf.GlobalConfiguration; import io.liuguangsheng.galois.utils.GaloisLog; import jdk.internal.org.objectweb.asm.ClassReader; import jdk.internal.org.objectweb.asm.ClassVisitor; import jdk.internal.org.objectweb.asm.ClassWriter; import org.slf4j.Logger;
3,899
/* * MIT License * * Copyright (c) [2023] [liuguangsheng] * * 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 io.liuguangsheng.galois.service; /** * method adapter * * @author liuguangsheng * @since 1.0.0 */ public abstract class MethodAdapter extends ClassVisitor { private static final Logger logger = new GaloisLog(MethodAdapter.class);
/* * MIT License * * Copyright (c) [2023] [liuguangsheng] * * 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 io.liuguangsheng.galois.service; /** * method adapter * * @author liuguangsheng * @since 1.0.0 */ public abstract class MethodAdapter extends ClassVisitor { private static final Logger logger = new GaloisLog(MethodAdapter.class);
private static final GlobalConfiguration config = GlobalConfiguration.getInstance();
0
2023-11-22 04:51:35+00:00
8k
TongchengOpenSource/ckibana
src/main/java/com/ly/ckibana/parser/MsearchQueryTask.java
[ { "identifier": "CKNotSupportException", "path": "src/main/java/com/ly/ckibana/model/exception/CKNotSupportException.java", "snippet": "public class CKNotSupportException extends UiException {\n\n public CKNotSupportException(String message) {\n super(\"ckNotSupport \" + message);\n }\n}" ...
import com.alibaba.fastjson2.JSONObject; import com.ly.ckibana.model.exception.CKNotSupportException; import com.ly.ckibana.model.exception.UiException; import com.ly.ckibana.model.request.CkRequestContext; import com.ly.ckibana.model.response.Response; import com.ly.ckibana.util.ProxyUtils; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.Callable;
5,213
/* * 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.parser; @Slf4j public class MsearchQueryTask implements Callable<Response> { private CkRequestContext ckRequestContext; private AggResultParser aggsParser; private JSONObject searchQuery; public MsearchQueryTask(CkRequestContext ckRequestContext, AggResultParser aggResultParser, JSONObject searchQuery) { this.ckRequestContext = ckRequestContext; this.aggsParser = aggResultParser; this.searchQuery = searchQuery; } @Override public Response call() { try { return invoke(ckRequestContext); } catch (CKNotSupportException ex) { log.error("call error ", ex); throw new CKNotSupportException(ex.getMessage()); } catch (Exception ex) {
/* * 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.parser; @Slf4j public class MsearchQueryTask implements Callable<Response> { private CkRequestContext ckRequestContext; private AggResultParser aggsParser; private JSONObject searchQuery; public MsearchQueryTask(CkRequestContext ckRequestContext, AggResultParser aggResultParser, JSONObject searchQuery) { this.ckRequestContext = ckRequestContext; this.aggsParser = aggResultParser; this.searchQuery = searchQuery; } @Override public Response call() { try { return invoke(ckRequestContext); } catch (CKNotSupportException ex) { log.error("call error ", ex); throw new CKNotSupportException(ex.getMessage()); } catch (Exception ex) {
if (ex instanceof UiException e) {
1
2023-11-21 09:12:07+00:00
8k
libgdx/gdx-particle-editor
core/src/main/java/com/ray3k/stripe/DraggableList.java
[ { "identifier": "DragAndDrop", "path": "core/src/main/java/com/badlogic/gdx/scenes/scene2d/utils/DragAndDrop.java", "snippet": "public class DragAndDrop {\n static final Vector2 tmpVector = new Vector2();\n\n Source dragSource;\n Payload payload;\n Actor dragActor;\n boolean removeDragAct...
import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.scenes.scene2d.*; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop; import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Payload; import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Source; import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Target; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectMap;
4,754
package com.ray3k.stripe; public class DraggableList extends WidgetGroup { private DraggableListStyle style; private final Table table; protected Array<Actor> actors; private final ObjectMap<Actor, Actor> dragActors; private final ObjectMap<Actor, Actor> validDragActors; private final ObjectMap<Actor, Actor> invalidDragActors;
package com.ray3k.stripe; public class DraggableList extends WidgetGroup { private DraggableListStyle style; private final Table table; protected Array<Actor> actors; private final ObjectMap<Actor, Actor> dragActors; private final ObjectMap<Actor, Actor> validDragActors; private final ObjectMap<Actor, Actor> invalidDragActors;
private final DragAndDrop dragAndDrop;
0
2023-11-24 15:58:20+00:00
8k
373675032/love-charity
src/main/java/com/charity/controller/ArticleController.java
[ { "identifier": "CheckStatus", "path": "src/main/java/com/charity/constant/CheckStatus.java", "snippet": "public class CheckStatus {\n\n /**\n * 等待审核\n */\n public static final int WAIT = 0;\n\n /**\n * 审核通过\n */\n public static final int PASS = 1;\n\n /**\n * 审核未通过\n ...
import com.alibaba.fastjson.JSONObject; import com.charity.constant.CheckStatus; import com.charity.constant.CommentType; import com.charity.constant.TrashStatus; import com.charity.constant.TypeStatus; import com.charity.dto.ResponseResult; import com.charity.entity.Article; import com.charity.entity.Message; import com.charity.utils.OssUtils; import com.charity.utils.LogUtils; import com.charity.utils.MessageUtils; import org.slf4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Date;
4,651
package com.charity.controller; /** * 文章控制器 * <p> * ========================================================================== * 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。 * ========================================================================== * B站账号:薛伟同学 * 微信公众号:薛伟同学 * 作者博客:http://xuewei.world * ========================================================================== * 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。 * 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。 * 希望各位朋友擦亮慧眼,谨防上当受骗! * ========================================================================== * * @author <a href="http://xuewei.world/about">XUEW</a> */ @Controller public class ArticleController extends BaseController { private final Logger logger = LogUtils.getInstance(ArticleController.class); /** * 发布求助文章 */ @PostMapping("/publishArticle") @ResponseBody public String publishArticle(String title, String content, String imgPath, Integer activityId) { // 生成文章对象 Article article = Article.builder() .title(title).content(content).userId(loginUser.getId()) .type(TypeStatus.ARTICLE).readCount(0).status(TrashStatus.NOT_IN).isChecked(CheckStatus.WAIT) .gmtCreate(new Date()).gmtModified(new Date()) .build(); // 为文章设置封面,如果为空就生成随机封面 article.setImg(StringUtils.isEmpty(imgPath) ? OssUtils.getRandomFace() : imgPath); if (articleService.insert(article)) { if (activityId != -1) { articleService.insertArticleActivity(article.getId(), activityId); logger.info("【成功】:添加文章活动"); } result.setCode(200); logger.info("【成功】:添加文章"); } else { result.setCode(500); logger.info("【失败】:添加文章"); } return JSONObject.toJSONString(result); } /** * 更新文章 */ @PostMapping("/updateArticle") @ResponseBody public String updateArticle(Integer id, String title, String content, String imgPath, int activityId) { // 生成文章对象 Article article = Article.builder() .id(id).title(title).content(content).status(TrashStatus.NOT_IN).isChecked(CheckStatus.WAIT) .gmtModified(new Date()) .build(); // 为文章设置封面,如果为空就生成随机封面 article.setImg(StringUtils.isEmpty(imgPath) ? OssUtils.getRandomFace() : imgPath); if (articleService.update(article)) { if (activityId != -1) { // 获取原来参加的活动 Article activity = articleService.getActivityByArticleId(id); if (activity == null || activity.getId() != activityId) { // 删除参与的活动 articleService.deleteArticleActivity(id); // 添加新的活动 articleService.insertArticleActivity(article.getId(), activityId); logger.info("【成功】:更新文章活动"); } } result.setCode(200); logger.info("【成功】:更新文章"); } else { result.setCode(500); logger.info("【失败】:更新文章"); } return JSONObject.toJSONString(result); } /** * 将文章移到回收站 */ @GetMapping("/putIntoTrash") public String putIntoTrash(@RequestParam("id") Integer id, @RequestParam("checked") Integer checked) { // 获取文章 Article article = articleService.getById(id); if (article.getType() == TypeStatus.ACTIVITY) { logger.info("【失败】:将文章移到回收站,类型错误"); return "error/400"; } if (article.getUserId() != loginUser.getId()) { logger.info("【失败】:将文章移到回收站,无权限"); return "error/401"; } article.setStatus(TrashStatus.IS_IN); if (articleService.update(article)) { logger.info("【成功】:将文字移到回收站"); } else { logger.info("【失败】:将文字移到回收站"); } return "redirect:/my-articles?checked=" + checked; } /** * 删除文章 */ @GetMapping("/deleteArticle") public String deleteArticle(@RequestParam("id") Integer id) { Article article = articleService.getById(id); if (article.getType() == TypeStatus.ACTIVITY) { logger.info("【失败】:删除文章,类型错误"); return "error/400"; } if (article.getUserId() != loginUser.getId()) { logger.info("【失败】:删除文章,无权限"); return "error/401"; } // 删除文章 if (articleService.deleteById(id)) { logger.info("【成功】:删除文章"); // 删除文章参加的活动 articleService.deleteArticleActivity(id); // 删除评论 commentService.deleteByTargetIdAndType(id, CommentType.ARTICLE); } else { logger.info("【失败】:删除文章"); } return "redirect:/trash-article"; } /** * 更新文章审核状态 */ @PostMapping("/updateArticleIsCheck") @ResponseBody public ResponseResult updateArticleIsCheck(String isChecked, String info, Integer id) { Article article = articleService.getById(id); article.setIsChecked(Integer.parseInt(isChecked)); article.setInfo(info); if (articleService.update(article)) { //储存消息
package com.charity.controller; /** * 文章控制器 * <p> * ========================================================================== * 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。 * ========================================================================== * B站账号:薛伟同学 * 微信公众号:薛伟同学 * 作者博客:http://xuewei.world * ========================================================================== * 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。 * 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。 * 希望各位朋友擦亮慧眼,谨防上当受骗! * ========================================================================== * * @author <a href="http://xuewei.world/about">XUEW</a> */ @Controller public class ArticleController extends BaseController { private final Logger logger = LogUtils.getInstance(ArticleController.class); /** * 发布求助文章 */ @PostMapping("/publishArticle") @ResponseBody public String publishArticle(String title, String content, String imgPath, Integer activityId) { // 生成文章对象 Article article = Article.builder() .title(title).content(content).userId(loginUser.getId()) .type(TypeStatus.ARTICLE).readCount(0).status(TrashStatus.NOT_IN).isChecked(CheckStatus.WAIT) .gmtCreate(new Date()).gmtModified(new Date()) .build(); // 为文章设置封面,如果为空就生成随机封面 article.setImg(StringUtils.isEmpty(imgPath) ? OssUtils.getRandomFace() : imgPath); if (articleService.insert(article)) { if (activityId != -1) { articleService.insertArticleActivity(article.getId(), activityId); logger.info("【成功】:添加文章活动"); } result.setCode(200); logger.info("【成功】:添加文章"); } else { result.setCode(500); logger.info("【失败】:添加文章"); } return JSONObject.toJSONString(result); } /** * 更新文章 */ @PostMapping("/updateArticle") @ResponseBody public String updateArticle(Integer id, String title, String content, String imgPath, int activityId) { // 生成文章对象 Article article = Article.builder() .id(id).title(title).content(content).status(TrashStatus.NOT_IN).isChecked(CheckStatus.WAIT) .gmtModified(new Date()) .build(); // 为文章设置封面,如果为空就生成随机封面 article.setImg(StringUtils.isEmpty(imgPath) ? OssUtils.getRandomFace() : imgPath); if (articleService.update(article)) { if (activityId != -1) { // 获取原来参加的活动 Article activity = articleService.getActivityByArticleId(id); if (activity == null || activity.getId() != activityId) { // 删除参与的活动 articleService.deleteArticleActivity(id); // 添加新的活动 articleService.insertArticleActivity(article.getId(), activityId); logger.info("【成功】:更新文章活动"); } } result.setCode(200); logger.info("【成功】:更新文章"); } else { result.setCode(500); logger.info("【失败】:更新文章"); } return JSONObject.toJSONString(result); } /** * 将文章移到回收站 */ @GetMapping("/putIntoTrash") public String putIntoTrash(@RequestParam("id") Integer id, @RequestParam("checked") Integer checked) { // 获取文章 Article article = articleService.getById(id); if (article.getType() == TypeStatus.ACTIVITY) { logger.info("【失败】:将文章移到回收站,类型错误"); return "error/400"; } if (article.getUserId() != loginUser.getId()) { logger.info("【失败】:将文章移到回收站,无权限"); return "error/401"; } article.setStatus(TrashStatus.IS_IN); if (articleService.update(article)) { logger.info("【成功】:将文字移到回收站"); } else { logger.info("【失败】:将文字移到回收站"); } return "redirect:/my-articles?checked=" + checked; } /** * 删除文章 */ @GetMapping("/deleteArticle") public String deleteArticle(@RequestParam("id") Integer id) { Article article = articleService.getById(id); if (article.getType() == TypeStatus.ACTIVITY) { logger.info("【失败】:删除文章,类型错误"); return "error/400"; } if (article.getUserId() != loginUser.getId()) { logger.info("【失败】:删除文章,无权限"); return "error/401"; } // 删除文章 if (articleService.deleteById(id)) { logger.info("【成功】:删除文章"); // 删除文章参加的活动 articleService.deleteArticleActivity(id); // 删除评论 commentService.deleteByTargetIdAndType(id, CommentType.ARTICLE); } else { logger.info("【失败】:删除文章"); } return "redirect:/trash-article"; } /** * 更新文章审核状态 */ @PostMapping("/updateArticleIsCheck") @ResponseBody public ResponseResult updateArticleIsCheck(String isChecked, String info, Integer id) { Article article = articleService.getById(id); article.setIsChecked(Integer.parseInt(isChecked)); article.setInfo(info); if (articleService.update(article)) { //储存消息
String content = MessageUtils.articleCheckHandle(article.getTitle(), Integer.parseInt(isChecked), info);
9
2023-11-26 17:33:02+00:00
8k
siam1026/siam-server
siam-system/system-provider/src/main/java/com/siam/system/modular/package_goods/controller/admin/internal/AdminVipRechargeRecordController.java
[ { "identifier": "BasicResultCode", "path": "siam-common/src/main/java/com/siam/package_common/constant/BasicResultCode.java", "snippet": "public class BasicResultCode {\n public static final int ERR = 0;\n\n public static final int SUCCESS = 1;\n\n public static final int TOKEN_ERR = 2;\n}" }...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.package_common.constant.BasicResultCode; import com.siam.package_common.constant.Quantity; import com.siam.package_common.entity.BasicData; import com.siam.package_common.entity.BasicResult; import com.siam.system.modular.package_goods.entity.internal.VipRechargeRecord; import com.siam.system.modular.package_goods.service.internal.VipRechargeRecordService; import com.siam.system.modular.package_user.entity.Member; import com.siam.system.modular.package_user.service.MemberService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.time.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.util.Date; import java.util.Map;
5,838
package com.siam.system.modular.package_goods.controller.admin.internal; @Slf4j @RestController @RequestMapping(value = "/rest/admin/vipRechargeRecord") @Transactional(rollbackFor = Exception.class) @Api(tags = "后台会员充值记录模块相关接口", description = "AdminVipRechargeRecordController") public class AdminVipRechargeRecordController { @Autowired private VipRechargeRecordService vipRechargeRecordService; @Autowired private MemberService memberService; @ApiOperation(value = "会员充值记录列表") @PostMapping(value = "/list") public BasicResult list(@RequestBody @Validated(value = {}) VipRechargeRecord vipRechargeRecord){ BasicData basicResult = new BasicData(); vipRechargeRecord.setStatus(Quantity.INT_2); Page<VipRechargeRecord> page = vipRechargeRecordService.getListByPageJoinMember(vipRechargeRecord.getPageNo(), vipRechargeRecord.getPageSize(), vipRechargeRecord); return BasicResult.success(page); } @ApiOperation(value = "会员充值记录-统计金额") @PostMapping(value = "/statisticalAmount") public BasicResult statisticalAmount(@RequestBody @Validated(value = {}) VipRechargeRecord vipRechargeRecord, HttpServletRequest request){ BasicData basicResult = new BasicData(); Map<String, Object> map = vipRechargeRecordService.statisticalAmount(vipRechargeRecord); basicResult.setData(map); basicResult.setSuccess(true);
package com.siam.system.modular.package_goods.controller.admin.internal; @Slf4j @RestController @RequestMapping(value = "/rest/admin/vipRechargeRecord") @Transactional(rollbackFor = Exception.class) @Api(tags = "后台会员充值记录模块相关接口", description = "AdminVipRechargeRecordController") public class AdminVipRechargeRecordController { @Autowired private VipRechargeRecordService vipRechargeRecordService; @Autowired private MemberService memberService; @ApiOperation(value = "会员充值记录列表") @PostMapping(value = "/list") public BasicResult list(@RequestBody @Validated(value = {}) VipRechargeRecord vipRechargeRecord){ BasicData basicResult = new BasicData(); vipRechargeRecord.setStatus(Quantity.INT_2); Page<VipRechargeRecord> page = vipRechargeRecordService.getListByPageJoinMember(vipRechargeRecord.getPageNo(), vipRechargeRecord.getPageSize(), vipRechargeRecord); return BasicResult.success(page); } @ApiOperation(value = "会员充值记录-统计金额") @PostMapping(value = "/statisticalAmount") public BasicResult statisticalAmount(@RequestBody @Validated(value = {}) VipRechargeRecord vipRechargeRecord, HttpServletRequest request){ BasicData basicResult = new BasicData(); Map<String, Object> map = vipRechargeRecordService.statisticalAmount(vipRechargeRecord); basicResult.setData(map); basicResult.setSuccess(true);
basicResult.setCode(BasicResultCode.SUCCESS);
0
2023-11-26 12:41:06+00:00
8k
junyharang-coding-study/GraphQL-Study
자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/api/people/service/PeopleServiceImpl.java
[ { "identifier": "DefaultResponse", "path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/common/constant/DefaultResponse.java", "snippet": "@Data\n@AllArgsConstructor\n@Builder\npublic class DefaultResponse<T> {\n\tprivate Integer statusCode;\n\tprivate String message;\n\tprivate Pagination pagin...
import java.util.List; import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.junyss.graphqltest.common.constant.DefaultResponse; import com.junyss.graphqltest.common.constant.Pagination; import com.junyss.graphqltest.common.enumtype.BloodType; import com.junyss.graphqltest.common.enumtype.Role; import com.junyss.graphqltest.common.enumtype.Sex; import com.junyss.graphqltest.common.util.GraphQLSupportUtil; import com.junyss.graphqltest.common.util.ObjectUtil; import com.junyss.graphqltest.common.util.PagingProcessUtil; import com.junyss.graphqltest.api.people.model.dto.request.PeopleRequestDto; import com.junyss.graphqltest.api.people.model.dto.request.PeopleSearchRequestDto; import com.junyss.graphqltest.api.people.model.dto.request.PeopleUpdateRequestDto; import com.junyss.graphqltest.api.people.model.dto.response.PeopleResponseDto; import com.junyss.graphqltest.api.people.model.entity.People; import com.junyss.graphqltest.api.people.repository.PeopleQueryDslRepository; import com.junyss.graphqltest.api.people.repository.PeopleRepository; import com.junyss.graphqltest.api.team.model.entity.Team; import com.junyss.graphqltest.api.team.repository.TeamRepository; import lombok.RequiredArgsConstructor;
4,466
package com.junyss.graphqltest.api.people.service; @RequiredArgsConstructor @Service public class PeopleServiceImpl implements PeopleService { private final PeopleRepository peopleRepository; private final PeopleQueryDslRepository peopleQueryDslRepository; private final TeamRepository teamRepository; @Transactional @Override
package com.junyss.graphqltest.api.people.service; @RequiredArgsConstructor @Service public class PeopleServiceImpl implements PeopleService { private final PeopleRepository peopleRepository; private final PeopleQueryDslRepository peopleQueryDslRepository; private final TeamRepository teamRepository; @Transactional @Override
public DefaultResponse<Long> saveForPeople(PeopleRequestDto peopleRequestDtoDto) {
0
2023-11-22 12:26:00+00:00
8k
windsbell/shardingkey-autofill
src/main/java/com/windsbell/shardingkey/autofill/handler/ShardingKeyCooker.java
[ { "identifier": "CourseExplain", "path": "src/main/java/com/windsbell/shardingkey/autofill/jsqlparser/CourseExplain.java", "snippet": "@Data\npublic class CourseExplain {\n\n private Long cost; // 消耗时间\n\n private String initialSQL; // 初始的SQL\n\n private Statement finalSQL; // 填充分片键的SQL\n\n ...
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; import com.windsbell.shardingkey.autofill.jsqlparser.CourseExplain; import com.windsbell.shardingkey.autofill.jsqlparser.ShardingKeyFillerAgent; import com.windsbell.shardingkey.autofill.jsqlparser.ShardingKeyHitFinder; import com.windsbell.shardingkey.autofill.jsqlparser.TableAliasSetter; import com.windsbell.shardingkey.autofill.strategy.*; import net.sf.jsqlparser.statement.Statement; import org.springframework.util.Assert; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.stream.Collectors;
3,869
package com.windsbell.shardingkey.autofill.handler; /** * SQL分片键锅炉房(核心调用链) * * @author windbell */ public class ShardingKeyCooker { private final Long start; // 开始时间 private final Statement statement; // sql private final List<?> parameterList; // 占位符内容值列表 private final List<TableShardingKeyStrategy> tableShardingKeyStrategyList; // 表分片键映射策略列表 private final Map<String, Map<String, String>> fillShardingKeyMap; // 【表名 分片键,分片键值】目标要填充的片键值对内容 private List<BusinessKeyStrategy> businessKeyStrategyList; // 业务分片键字段映射策略列表 private Map<String, TableShardingKeyStrategy> shardingKeyStrategyMap; // 【表名 ,表分片键映射策略】 业务分片键字段映射策略列表 private Map<String, Map<String, Boolean>> firstShardingKeyHitFlagMap; // 【表名 分片键,是否设置 】原始检测收集的结果 private CourseExplain courseExplain; // 分片键填充过程说明 public static ShardingKeyCooker builder(Statement statement, List<TableShardingKeyStrategy> tableShardingKeyStrategyList, List<?> parameterList) { return new ShardingKeyCooker(statement, tableShardingKeyStrategyList, parameterList); } private ShardingKeyCooker(Statement statement, List<TableShardingKeyStrategy> tableShardingKeyStrategyList, List<?> parameterList) { this.start = System.currentTimeMillis(); this.statement = statement; this.tableShardingKeyStrategyList = tableShardingKeyStrategyList; this.parameterList = parameterList; this.fillShardingKeyMap = new LinkedHashMap<>(); } // 设置表字段别名 public ShardingKeyCooker setTableAlias() {
package com.windsbell.shardingkey.autofill.handler; /** * SQL分片键锅炉房(核心调用链) * * @author windbell */ public class ShardingKeyCooker { private final Long start; // 开始时间 private final Statement statement; // sql private final List<?> parameterList; // 占位符内容值列表 private final List<TableShardingKeyStrategy> tableShardingKeyStrategyList; // 表分片键映射策略列表 private final Map<String, Map<String, String>> fillShardingKeyMap; // 【表名 分片键,分片键值】目标要填充的片键值对内容 private List<BusinessKeyStrategy> businessKeyStrategyList; // 业务分片键字段映射策略列表 private Map<String, TableShardingKeyStrategy> shardingKeyStrategyMap; // 【表名 ,表分片键映射策略】 业务分片键字段映射策略列表 private Map<String, Map<String, Boolean>> firstShardingKeyHitFlagMap; // 【表名 分片键,是否设置 】原始检测收集的结果 private CourseExplain courseExplain; // 分片键填充过程说明 public static ShardingKeyCooker builder(Statement statement, List<TableShardingKeyStrategy> tableShardingKeyStrategyList, List<?> parameterList) { return new ShardingKeyCooker(statement, tableShardingKeyStrategyList, parameterList); } private ShardingKeyCooker(Statement statement, List<TableShardingKeyStrategy> tableShardingKeyStrategyList, List<?> parameterList) { this.start = System.currentTimeMillis(); this.statement = statement; this.tableShardingKeyStrategyList = tableShardingKeyStrategyList; this.parameterList = parameterList; this.fillShardingKeyMap = new LinkedHashMap<>(); } // 设置表字段别名 public ShardingKeyCooker setTableAlias() {
TableAliasSetter tableAliasSetter = new TableAliasSetter(statement);
3
2023-11-23 09:05:56+00:00
8k
oxcened/opendialer
feature/settings/src/main/java/dev/alenajam/opendialer/feature/settings/SettingsActivity.java
[ { "identifier": "KEY_SETTING_BLOCKED_NUMBERS", "path": "core/common/src/main/java/dev/alenajam/opendialer/core/common/SharedPreferenceHelper.java", "snippet": "public static final String KEY_SETTING_BLOCKED_NUMBERS = \"blockedNumbers\";" }, { "identifier": "KEY_SETTING_DEFAULT", "path": "cor...
import static dev.alenajam.opendialer.core.common.SharedPreferenceHelper.KEY_SETTING_BLOCKED_NUMBERS; import static dev.alenajam.opendialer.core.common.SharedPreferenceHelper.KEY_SETTING_DEFAULT; import static dev.alenajam.opendialer.core.common.SharedPreferenceHelper.KEY_SETTING_NOTIFICATION_SETTINGS; import static dev.alenajam.opendialer.core.common.SharedPreferenceHelper.KEY_SETTING_QUICK_RESPONSES; import static dev.alenajam.opendialer.core.common.SharedPreferenceHelper.KEY_SETTING_SOUND_VIBRATION; import static dev.alenajam.opendialer.core.common.SharedPreferenceHelper.KEY_SETTING_THEME; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.provider.BlockedNumberContract; import android.provider.Settings; import android.telecom.TelecomManager; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.preference.ListPreference; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import dev.alenajam.opendialer.core.common.CommonUtils; import dev.alenajam.opendialer.core.common.DefaultPhoneUtils;
3,783
package dev.alenajam.opendialer.feature.settings; public class SettingsActivity extends AppCompatActivity { private static final int REQUEST_ID_DEFAULT = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); getSupportFragmentManager() .beginTransaction() .replace(R.id.settings, new SettingsFragment()) .commit(); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back); } } public static class SettingsFragment extends PreferenceFragmentCompat implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener { Preference defaultPreference; private TelecomManager telecomManager; @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { if (getContext() != null) { telecomManager = (TelecomManager) getContext().getSystemService(TELECOM_SERVICE); } setPreferencesFromResource(R.xml.root_preferences, rootKey); ListPreference themePreference = getPreferenceManager().findPreference(KEY_SETTING_THEME); if (themePreference != null) themePreference.setOnPreferenceChangeListener(this); defaultPreference = getPreferenceManager().findPreference(KEY_SETTING_DEFAULT); if (defaultPreference != null) defaultPreference.setOnPreferenceClickListener(this); Preference soundPreference = getPreferenceManager().findPreference(KEY_SETTING_SOUND_VIBRATION); if (soundPreference != null) soundPreference.setOnPreferenceClickListener(this); Preference quickResponsesPreference = getPreferenceManager().findPreference(KEY_SETTING_QUICK_RESPONSES); if (quickResponsesPreference != null) quickResponsesPreference.setOnPreferenceClickListener(this); Preference blockedNumbers = getPreferenceManager().findPreference(KEY_SETTING_BLOCKED_NUMBERS); if (blockedNumbers != null) { blockedNumbers.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && BlockedNumberContract.canCurrentUserBlockNumbers(getContext())); blockedNumbers.setOnPreferenceClickListener(this); } Preference notificationSettings = getPreferenceManager().findPreference(KEY_SETTING_NOTIFICATION_SETTINGS); if (notificationSettings != null) { notificationSettings.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O); notificationSettings.setOnPreferenceClickListener(this); } } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { switch (preference.getKey()) { case KEY_SETTING_THEME: CommonUtils.setTheme(Integer.parseInt(newValue.toString())); break; } return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_ID_DEFAULT) { for (int g : grantResults) { if (g != PackageManager.PERMISSION_GRANTED) return; } if (defaultPreference != null) defaultPreference.setEnabled(false); } } @Override public void onResume() { super.onResume(); if (defaultPreference != null) {
package dev.alenajam.opendialer.feature.settings; public class SettingsActivity extends AppCompatActivity { private static final int REQUEST_ID_DEFAULT = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); getSupportFragmentManager() .beginTransaction() .replace(R.id.settings, new SettingsFragment()) .commit(); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back); } } public static class SettingsFragment extends PreferenceFragmentCompat implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener { Preference defaultPreference; private TelecomManager telecomManager; @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { if (getContext() != null) { telecomManager = (TelecomManager) getContext().getSystemService(TELECOM_SERVICE); } setPreferencesFromResource(R.xml.root_preferences, rootKey); ListPreference themePreference = getPreferenceManager().findPreference(KEY_SETTING_THEME); if (themePreference != null) themePreference.setOnPreferenceChangeListener(this); defaultPreference = getPreferenceManager().findPreference(KEY_SETTING_DEFAULT); if (defaultPreference != null) defaultPreference.setOnPreferenceClickListener(this); Preference soundPreference = getPreferenceManager().findPreference(KEY_SETTING_SOUND_VIBRATION); if (soundPreference != null) soundPreference.setOnPreferenceClickListener(this); Preference quickResponsesPreference = getPreferenceManager().findPreference(KEY_SETTING_QUICK_RESPONSES); if (quickResponsesPreference != null) quickResponsesPreference.setOnPreferenceClickListener(this); Preference blockedNumbers = getPreferenceManager().findPreference(KEY_SETTING_BLOCKED_NUMBERS); if (blockedNumbers != null) { blockedNumbers.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && BlockedNumberContract.canCurrentUserBlockNumbers(getContext())); blockedNumbers.setOnPreferenceClickListener(this); } Preference notificationSettings = getPreferenceManager().findPreference(KEY_SETTING_NOTIFICATION_SETTINGS); if (notificationSettings != null) { notificationSettings.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O); notificationSettings.setOnPreferenceClickListener(this); } } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { switch (preference.getKey()) { case KEY_SETTING_THEME: CommonUtils.setTheme(Integer.parseInt(newValue.toString())); break; } return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_ID_DEFAULT) { for (int g : grantResults) { if (g != PackageManager.PERMISSION_GRANTED) return; } if (defaultPreference != null) defaultPreference.setEnabled(false); } } @Override public void onResume() { super.onResume(); if (defaultPreference != null) {
boolean hasDefault = DefaultPhoneUtils.hasDefault(getContext());
7
2023-11-21 21:24:39+00:00
8k
pewaru-333/HomeMedkit-App
app/src/main/java/ru/application/homemedkit/activities/MedicineActivity.java
[ { "identifier": "ADD", "path": "app/src/main/java/ru/application/homemedkit/helpers/ConstantsHelper.java", "snippet": "public static final String ADD = \"add\";" }, { "identifier": "ADDING", "path": "app/src/main/java/ru/application/homemedkit/helpers/ConstantsHelper.java", "snippet": "p...
import static android.view.View.GONE; import static android.view.View.OnClickListener; import static android.view.View.VISIBLE; import static java.lang.String.valueOf; import static ru.application.homemedkit.helpers.ConstantsHelper.ADD; import static ru.application.homemedkit.helpers.ConstantsHelper.ADDING; import static ru.application.homemedkit.helpers.ConstantsHelper.BLANK; import static ru.application.homemedkit.helpers.ConstantsHelper.CIS; import static ru.application.homemedkit.helpers.ConstantsHelper.DUPLICATE; import static ru.application.homemedkit.helpers.ConstantsHelper.ID; import static ru.application.homemedkit.helpers.ConstantsHelper.MEDICINE_ID; import static ru.application.homemedkit.helpers.ConstantsHelper.NEW_MEDICINE; import static ru.application.homemedkit.helpers.DateHelper.toExpDate; import static ru.application.homemedkit.helpers.ImageHelper.getIconType; import static ru.application.homemedkit.helpers.StringHelper.decimalFormat; import static ru.application.homemedkit.helpers.StringHelper.fromHTML; import static ru.application.homemedkit.helpers.StringHelper.parseAmount; import android.animation.LayoutTransition; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.Toolbar.OnMenuItemClickListener; import androidx.activity.OnBackPressedCallback; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.PopupMenu; import com.google.android.material.appbar.MaterialToolbar; import com.google.android.material.button.MaterialButton; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputLayout; import java.util.Arrays; import ru.application.homemedkit.R; import ru.application.homemedkit.connectionController.RequestAPI; import ru.application.homemedkit.databaseController.Medicine; import ru.application.homemedkit.databaseController.MedicineDatabase; import ru.application.homemedkit.databaseController.Technical; import ru.application.homemedkit.dialogs.ExpDateDialog; import ru.application.homemedkit.graphics.ExpandAnimation; import ru.application.homemedkit.graphics.Snackbars;
5,598
private void setFieldsClickable(boolean flag) { Arrays.asList(productName, prodFormNormName, prodDNormName, phKinetics) .forEach(item -> { if (flag) { item.addTextChangedListener(this); item.setRawInputType(InputType.TYPE_CLASS_TEXT); } else { item.addTextChangedListener(null); item.setRawInputType(InputType.TYPE_NULL); } item.setFocusableInTouchMode(flag); item.setFocusable(flag); item.setCursorVisible(flag); }); Arrays.asList(prodNormAmount, comment).forEach(item -> { item.addTextChangedListener(this); if (item != prodNormAmount) item.setRawInputType(InputType.TYPE_CLASS_TEXT); item.setFocusableInTouchMode(true); item.setFocusable(true); item.setCursorVisible(true); }); expDate.addTextChangedListener(flag ? this : null); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { buttonSave.setVisibility(VISIBLE); } @Override public void afterTextChanged(Editable s) { } @Override public boolean onMenuItemClick(MenuItem item) { PopupMenu popupMenu = new PopupMenu(this, toolbar.findViewById(R.id.top_app_bar_more)); popupMenu.inflate(R.menu.menu_top_app_bar_more); popupMenu.setOnMenuItemClickListener(menuItem -> { database.medicineDAO().delete(new Medicine(primaryKey)); backClick(); return true; }); popupMenu.show(); return true; } private class BackButtonPressed extends OnBackPressedCallback { public BackButtonPressed() { super(true); } @Override public void handleOnBackPressed() { backClick(); } } private class SaveChanges implements OnClickListener { @Override public void onClick(View v) { String cis = medicine.cis; String name = valueOf(productName.getText()); long date = timestamp; String formNormName = valueOf(prodFormNormName.getText()); String normName = valueOf(prodDNormName.getText()); double prodAmount = parseAmount(valueOf(prodNormAmount.getText())); String kinetics = valueOf(phKinetics.getText()); String textComment = valueOf(comment.getText()); database.medicineDAO().update( new Medicine(primaryKey, cis, name, date, formNormName, normName, prodAmount, kinetics, textComment, new Technical(scanned, verified))); buttonSave.setVisibility(GONE); finish(); startActivity(new Intent(getIntent())); } } private class AddMedicine implements OnClickListener { @Override public void onClick(View v) { String name = valueOf(productName.getText()); long date = timestamp; String formNormName = valueOf(prodFormNormName.getText()); String normName = valueOf(prodDNormName.getText()); double prodAmount = parseAmount(valueOf(prodNormAmount.getText())); String kinetics = valueOf(phKinetics.getText()); String textComment = valueOf(comment.getText()); boolean scanned = cis != null; boolean verified = false; long id = database.medicineDAO().add( new Medicine(cis, name, date, formNormName, normName, prodAmount, kinetics, textComment, new Technical(scanned, verified))); buttonSave.setVisibility(GONE); finish(); Intent intent = new Intent(getIntent()); intent.putExtra(ID, id); startActivity(intent); } } private class AddIntake implements OnClickListener { @Override public void onClick(View v) { Intent intent = new Intent(MedicineActivity.this, IntakeActivity.class); intent.putExtra(MEDICINE_ID, primaryKey);
package ru.application.homemedkit.activities; public class MedicineActivity extends AppCompatActivity implements TextWatcher, OnMenuItemClickListener { public static long timestamp = -1; private MedicineDatabase database; private Medicine medicine; private MaterialToolbar toolbar; private ImageView image; private TextInputEditText productName, expDate, prodFormNormName, prodDNormName, prodNormAmount, phKinetics, comment; private FloatingActionButton buttonFetch, buttonAddIntake; private MaterialButton buttonSave; private String cis; private long primaryKey; private boolean duplicate, scanned, verified; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_medicine); toolbar = findViewById(R.id.scanned_medicine_top_app_bar_toolbar); image = findViewById(R.id.image_medicine_scanned_type); productName = findViewById(R.id.medicine_scanned_product_name); expDate = findViewById(R.id.medicine_scanned_exp_date); prodFormNormName = findViewById(R.id.medicine_scanned_prod_form_norm_name); prodDNormName = findViewById(R.id.medicine_scanned_prod_d_norm_name); prodNormAmount = findViewById(R.id.medicine_scanned_amount); phKinetics = findViewById(R.id.medicine_scanned_ph_kinetics); comment = findViewById(R.id.medicine_scanned_comment); buttonSave = findViewById(R.id.medicine_card_save_changes); buttonFetch = findViewById(R.id.button_fetch_data); buttonAddIntake = findViewById(R.id.button_add_intake); database = MedicineDatabase.getInstance(this); primaryKey = getIntent().getLongExtra(ID, 0); duplicate = getIntent().getBooleanExtra(DUPLICATE, false); cis = getIntent().getStringExtra(CIS); if (primaryKey == 0) { setAddingLayout(); } else { medicine = database.medicineDAO().getByPK(primaryKey); scanned = medicine.technical.scanned; verified = medicine.technical.verified; if (scanned && verified) setScannedLayout(); else setAddedLayout(); } toolbar.setOnMenuItemClickListener(this::onMenuItemClick); toolbar.setNavigationOnClickListener(v -> backClick()); buttonAddIntake.setOnClickListener(new AddIntake()); getOnBackPressedDispatcher().addCallback(new BackButtonPressed()); } private void setAddingLayout() { setFieldsClickable(true); findViewById(R.id.top_app_bar_more).setVisibility(GONE); buttonAddIntake.setVisibility(View.INVISIBLE); expDate.setOnClickListener(v -> new ExpDateDialog(this)); buttonSave.setOnClickListener(new AddMedicine()); } private void setScannedLayout() { String form = medicine.prodFormNormName; timestamp = medicine.expDate; image.setImageDrawable(getIconType(this, form)); productName.setText(medicine.productName); expDate.setText(getString(R.string.exp_date_until, toExpDate(timestamp))); prodFormNormName.setText(form); prodDNormName.setText(medicine.prodDNormName); prodNormAmount.setText(decimalFormat(medicine.prodAmount)); phKinetics.setText(fromHTML(medicine.phKinetics)); comment.setText(medicine.comment); setFieldsClickable(false); buttonSave.setOnClickListener(new SaveChanges()); TextInputLayout layout = findViewById(R.id.medicine_scanned_layout_ph_kinetics); layout.setClickable(true); layout.getLayoutTransition().enableTransitionType(LayoutTransition.CHANGING); layout.setEndIconOnClickListener(new ExpandAnimation(this, layout)); duplicateCheck(); } private void setAddedLayout() { String form = medicine.prodFormNormName; image.setImageDrawable(getIconType(this, form)); productName.setText(medicine.productName); expDate.setText(medicine.expDate != -1 ? getString(R.string.exp_date_until, toExpDate(medicine.expDate)) : BLANK); prodFormNormName.setText(form); prodDNormName.setText(medicine.prodDNormName); prodNormAmount.setText(decimalFormat(medicine.prodAmount)); phKinetics.setText(medicine.phKinetics); comment.setText(medicine.comment); setFieldsClickable(true); expDate.setOnClickListener(v -> new ExpDateDialog(this)); buttonFetch.setVisibility(medicine.cis != null ? VISIBLE : View.INVISIBLE); buttonFetch.setOnClickListener(v -> new RequestAPI(this) .onDecoded(primaryKey, medicine.cis)); buttonSave.setOnClickListener(new SaveChanges()); duplicateCheck(); } private void backClick() { Intent intent = new Intent(this, MainActivity.class); if (!getIntent().getBooleanExtra(ADDING, false)) intent.putExtra(NEW_MEDICINE, true); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } private void duplicateCheck() { if (duplicate) new Snackbars(this).duplicateMedicine(); } private void setFieldsClickable(boolean flag) { Arrays.asList(productName, prodFormNormName, prodDNormName, phKinetics) .forEach(item -> { if (flag) { item.addTextChangedListener(this); item.setRawInputType(InputType.TYPE_CLASS_TEXT); } else { item.addTextChangedListener(null); item.setRawInputType(InputType.TYPE_NULL); } item.setFocusableInTouchMode(flag); item.setFocusable(flag); item.setCursorVisible(flag); }); Arrays.asList(prodNormAmount, comment).forEach(item -> { item.addTextChangedListener(this); if (item != prodNormAmount) item.setRawInputType(InputType.TYPE_CLASS_TEXT); item.setFocusableInTouchMode(true); item.setFocusable(true); item.setCursorVisible(true); }); expDate.addTextChangedListener(flag ? this : null); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { buttonSave.setVisibility(VISIBLE); } @Override public void afterTextChanged(Editable s) { } @Override public boolean onMenuItemClick(MenuItem item) { PopupMenu popupMenu = new PopupMenu(this, toolbar.findViewById(R.id.top_app_bar_more)); popupMenu.inflate(R.menu.menu_top_app_bar_more); popupMenu.setOnMenuItemClickListener(menuItem -> { database.medicineDAO().delete(new Medicine(primaryKey)); backClick(); return true; }); popupMenu.show(); return true; } private class BackButtonPressed extends OnBackPressedCallback { public BackButtonPressed() { super(true); } @Override public void handleOnBackPressed() { backClick(); } } private class SaveChanges implements OnClickListener { @Override public void onClick(View v) { String cis = medicine.cis; String name = valueOf(productName.getText()); long date = timestamp; String formNormName = valueOf(prodFormNormName.getText()); String normName = valueOf(prodDNormName.getText()); double prodAmount = parseAmount(valueOf(prodNormAmount.getText())); String kinetics = valueOf(phKinetics.getText()); String textComment = valueOf(comment.getText()); database.medicineDAO().update( new Medicine(primaryKey, cis, name, date, formNormName, normName, prodAmount, kinetics, textComment, new Technical(scanned, verified))); buttonSave.setVisibility(GONE); finish(); startActivity(new Intent(getIntent())); } } private class AddMedicine implements OnClickListener { @Override public void onClick(View v) { String name = valueOf(productName.getText()); long date = timestamp; String formNormName = valueOf(prodFormNormName.getText()); String normName = valueOf(prodDNormName.getText()); double prodAmount = parseAmount(valueOf(prodNormAmount.getText())); String kinetics = valueOf(phKinetics.getText()); String textComment = valueOf(comment.getText()); boolean scanned = cis != null; boolean verified = false; long id = database.medicineDAO().add( new Medicine(cis, name, date, formNormName, normName, prodAmount, kinetics, textComment, new Technical(scanned, verified))); buttonSave.setVisibility(GONE); finish(); Intent intent = new Intent(getIntent()); intent.putExtra(ID, id); startActivity(intent); } } private class AddIntake implements OnClickListener { @Override public void onClick(View v) { Intent intent = new Intent(MedicineActivity.this, IntakeActivity.class); intent.putExtra(MEDICINE_ID, primaryKey);
intent.putExtra(ADD, true);
0
2023-11-19 10:26:15+00:00
8k
3dcitydb/citydb-tool
citydb-operation/src/main/java/org/citydb/operation/exporter/feature/FeatureExporter.java
[ { "identifier": "FeatureType", "path": "citydb-database/src/main/java/org/citydb/database/schema/FeatureType.java", "snippet": "public class FeatureType {\n public static final FeatureType UNDEFINED = new FeatureType(1, Name.of(\"Undefined\", Namespaces.CORE),\n Table.FEATURE, false, null,...
import java.sql.SQLException; import java.time.OffsetDateTime; import org.citydb.database.schema.FeatureType; import org.citydb.model.feature.Feature; import org.citydb.model.feature.FeatureDescriptor; import org.citydb.operation.exporter.ExportException; import org.citydb.operation.exporter.ExportHelper; import org.citydb.operation.exporter.common.DatabaseExporter; import org.citydb.operation.exporter.hierarchy.HierarchyBuilder; import java.sql.ResultSet;
6,592
/* * 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.operation.exporter.feature; public class FeatureExporter extends DatabaseExporter { public FeatureExporter(ExportHelper helper) throws SQLException { super(helper); stmt = helper.getConnection().prepareStatement(adapter.getSchemaAdapter().getFeatureHierarchyQuery()); } public Feature doExport(long id) throws ExportException, SQLException { stmt.setLong(1, id); try (ResultSet rs = stmt.executeQuery()) { return HierarchyBuilder.newInstance(id, helper) .initialize(rs) .build() .getFeature(id); } } public Feature doExport(long id, ResultSet rs) throws ExportException, SQLException {
/* * 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.operation.exporter.feature; public class FeatureExporter extends DatabaseExporter { public FeatureExporter(ExportHelper helper) throws SQLException { super(helper); stmt = helper.getConnection().prepareStatement(adapter.getSchemaAdapter().getFeatureHierarchyQuery()); } public Feature doExport(long id) throws ExportException, SQLException { stmt.setLong(1, id); try (ResultSet rs = stmt.executeQuery()) { return HierarchyBuilder.newInstance(id, helper) .initialize(rs) .build() .getFeature(id); } } public Feature doExport(long id, ResultSet rs) throws ExportException, SQLException {
FeatureType featureType = schemaMapping.getFeatureType(rs.getInt("objectclass_id"));
0
2023-11-19 12:29:54+00:00
8k
magmamaintained/Magma-1.12.2
src/main/java/org/magmafoundation/magma/configuration/MagmaConfig.java
[ { "identifier": "YamlConfiguration", "path": "src/main/java/org/bukkit/configuration/file/YamlConfiguration.java", "snippet": "public class YamlConfiguration extends FileConfiguration {\n protected static final String COMMENT_PREFIX = \"# \";\n protected static final String BLANK_CONFIG = \"{}\\n\...
import org.magmafoundation.magma.commands.MagmaCommand; import org.magmafoundation.magma.commands.TPSCommand; import org.magmafoundation.magma.commands.VersionCommand; import org.magmafoundation.magma.configuration.value.Value; import org.magmafoundation.magma.configuration.value.values.BooleanValue; import org.magmafoundation.magma.configuration.value.values.IntValue; import org.magmafoundation.magma.configuration.value.values.StringArrayValue; import org.magmafoundation.magma.configuration.value.values.StringValue; import com.google.common.collect.Lists; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.List; import java.util.logging.Level; import net.minecraft.server.MinecraftServer; import org.apache.commons.io.FileUtils; import org.bukkit.configuration.file.YamlConfiguration;
6,980
/* * 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.configuration; /** * MagmaConfig * * @author Hexeption admin@hexeption.co.uk * @since 19/08/2019 - 05:14 am */ public class MagmaConfig extends ConfigBase { public static MagmaConfig instance = new MagmaConfig(); //============================Debug====================================== public final BooleanValue debugPrintBukkitMatterials = new BooleanValue(this, "debug.debugPrintBukkitMatterials", false, "Prints the Forge Bukkit Materials"); public final BooleanValue debugPrintBukkitBannerPatterns = new BooleanValue(this, "debug.debugPrintBukkitBannerPatterns", false, "Prints the Forge Bukkit Banner Patterns"); public final BooleanValue debugPrintCommandNode = new BooleanValue(this, "debug.debugPrintCommandNode", false, "Prints out all Command Nodes for permissions"); public final BooleanValue debugPrintBiomes = new BooleanValue(this, "debug.debugPrintBiomes", false, "Prints out all registered biomes"); public final BooleanValue debugPrintSounds = new BooleanValue(this, "debug.debugPrintSounds", false, "Prints out all registered sounds"); //============================Console====================================== public final StringValue highlightLevelError = new StringValue(this, "console.colour.level.error", "c", "The colour for the error level"); public final StringValue highlightLevelWarning = new StringValue(this, "console.colour.level.warning", "e", "The colour for the warning level"); public final StringValue highlightLevelInfo = new StringValue(this, "console.colour.level.info", "2", "The colour for the info level"); public final StringValue highlightLevelFatal = new StringValue(this, "console.colour.level.fatal", "e", "The colour for the fatal level"); public final StringValue highlightLevelTrace = new StringValue(this, "console.colour.level.trace", "e", "The colour for the trace level"); public final StringValue highlightMessageError = new StringValue(this, "console.colour.message.error", "c", "The colour for the error message"); public final StringValue highlightMessageWarning = new StringValue(this, "console.colour.message.warning", "e", "The colour for the warning message"); public final StringValue highlightMessageInfo = new StringValue(this, "console.colour.message.info", "2", "The colour for the info message"); public final StringValue highlightMessageFatal = new StringValue(this, "console.colour.message.fatal", "e", "The colour for the fatal message"); public final StringValue highlightMessageTrace = new StringValue(this, "console.colour.message.trace", "e", "The colour for the trace message"); public final StringValue highlightTimeError = new StringValue(this, "console.colour.time.error", "c", "The colour for the error time"); public final StringValue highlightTimeWarning = new StringValue(this, "console.colour.time.warning", "e", "The colour for the warning time"); public final StringValue highlightTimeInfo = new StringValue(this, "console.colour.time.info", "2", "The colour for the info time"); public final StringValue highlightTimeFatal = new StringValue(this, "console.colour.time.fatal", "e", "The colour for the fatal time"); public final StringValue highlightTimeTrace = new StringValue(this, "console.colour.time.trace", "e", "The colour for the trace time"); //============================Black List Mods============================= public final BooleanValue blacklistedModsEnable = new BooleanValue(this, "forge.blacklistedmods.enabled", false, "Enable blacklisting of mods"); public final StringArrayValue blacklistedMods = new StringArrayValue(this, "forge.blacklistedmods.list", "", "A list of mods to blacklist"); public final StringValue blacklistedModsKickMessage = new StringValue(this, "forge.blacklistedmods.kickmessage", "Please Remove Blacklisted Mods", "Mod Blacklist kick message"); //=============================WORLD SETTINGS=============================
/* * 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.configuration; /** * MagmaConfig * * @author Hexeption admin@hexeption.co.uk * @since 19/08/2019 - 05:14 am */ public class MagmaConfig extends ConfigBase { public static MagmaConfig instance = new MagmaConfig(); //============================Debug====================================== public final BooleanValue debugPrintBukkitMatterials = new BooleanValue(this, "debug.debugPrintBukkitMatterials", false, "Prints the Forge Bukkit Materials"); public final BooleanValue debugPrintBukkitBannerPatterns = new BooleanValue(this, "debug.debugPrintBukkitBannerPatterns", false, "Prints the Forge Bukkit Banner Patterns"); public final BooleanValue debugPrintCommandNode = new BooleanValue(this, "debug.debugPrintCommandNode", false, "Prints out all Command Nodes for permissions"); public final BooleanValue debugPrintBiomes = new BooleanValue(this, "debug.debugPrintBiomes", false, "Prints out all registered biomes"); public final BooleanValue debugPrintSounds = new BooleanValue(this, "debug.debugPrintSounds", false, "Prints out all registered sounds"); //============================Console====================================== public final StringValue highlightLevelError = new StringValue(this, "console.colour.level.error", "c", "The colour for the error level"); public final StringValue highlightLevelWarning = new StringValue(this, "console.colour.level.warning", "e", "The colour for the warning level"); public final StringValue highlightLevelInfo = new StringValue(this, "console.colour.level.info", "2", "The colour for the info level"); public final StringValue highlightLevelFatal = new StringValue(this, "console.colour.level.fatal", "e", "The colour for the fatal level"); public final StringValue highlightLevelTrace = new StringValue(this, "console.colour.level.trace", "e", "The colour for the trace level"); public final StringValue highlightMessageError = new StringValue(this, "console.colour.message.error", "c", "The colour for the error message"); public final StringValue highlightMessageWarning = new StringValue(this, "console.colour.message.warning", "e", "The colour for the warning message"); public final StringValue highlightMessageInfo = new StringValue(this, "console.colour.message.info", "2", "The colour for the info message"); public final StringValue highlightMessageFatal = new StringValue(this, "console.colour.message.fatal", "e", "The colour for the fatal message"); public final StringValue highlightMessageTrace = new StringValue(this, "console.colour.message.trace", "e", "The colour for the trace message"); public final StringValue highlightTimeError = new StringValue(this, "console.colour.time.error", "c", "The colour for the error time"); public final StringValue highlightTimeWarning = new StringValue(this, "console.colour.time.warning", "e", "The colour for the warning time"); public final StringValue highlightTimeInfo = new StringValue(this, "console.colour.time.info", "2", "The colour for the info time"); public final StringValue highlightTimeFatal = new StringValue(this, "console.colour.time.fatal", "e", "The colour for the fatal time"); public final StringValue highlightTimeTrace = new StringValue(this, "console.colour.time.trace", "e", "The colour for the trace time"); //============================Black List Mods============================= public final BooleanValue blacklistedModsEnable = new BooleanValue(this, "forge.blacklistedmods.enabled", false, "Enable blacklisting of mods"); public final StringArrayValue blacklistedMods = new StringArrayValue(this, "forge.blacklistedmods.list", "", "A list of mods to blacklist"); public final StringValue blacklistedModsKickMessage = new StringValue(this, "forge.blacklistedmods.kickmessage", "Please Remove Blacklisted Mods", "Mod Blacklist kick message"); //=============================WORLD SETTINGS=============================
public final IntValue expMergeMaxValue = new IntValue(this, "experience-merge-max-value", -1,
6
2023-11-22 11:25:51+00:00
8k
Barsanti5BI/flight-simulator
src/Aereoporto/ZonaPartenze/ZonaPartenze.java
[ { "identifier": "ImpiegatoControlliStiva", "path": "src/Persona/ImpiegatoControlliStiva.java", "snippet": "public class ImpiegatoControlliStiva extends Thread{\n private Scanner s;\n private ArrayList<String> oggettiProibiti;\n private ArrayList<Turista> turistiPericolosi;\n private ArrayLis...
import Persona.ImpiegatoControlliStiva; import Persona.Turista; import Aereo.Gate; import Aereoporto.Common.ZonaAeroporto; import TorreDiControllo.Viaggio; import Utils.Coda; import java.util.ArrayList; import java.util.List;
6,349
package Aereoporto.ZonaPartenze; public class ZonaPartenze extends ZonaAeroporto { ArrayList<Gate> listaGate;
package Aereoporto.ZonaPartenze; public class ZonaPartenze extends ZonaAeroporto { ArrayList<Gate> listaGate;
public ZonaPartenze(ArrayList<Viaggio> viaggi, ImpiegatoControlliStiva impiegatoControlliStiva)
0
2023-11-18 07:13:43+00:00
8k
Youkehai/openai_assistants_java
assistants-front/src/main/java/com/kh/assistants/front/controller/AssistantsApiController.java
[ { "identifier": "CommonPathReq", "path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/req/CommonPathReq.java", "snippet": "@Data\n@Accessors(chain = true)\n@AllArgsConstructor\n@NoArgsConstructor\npublic class CommonPathReq {\n private fin...
import io.github.youkehai.assistant.core.req.CommonPathReq; import io.github.youkehai.assistant.core.req.PageReq; import io.github.youkehai.assistant.core.req.assistants.CreateAssistantFileReq; import io.github.youkehai.assistant.core.req.message.CreateAndRunReq; import io.github.youkehai.assistant.core.req.message.CreateMessageReq; import io.github.youkehai.assistant.core.req.run.CreateRunReq; import io.github.youkehai.assistant.core.resp.BasePageResp; import io.github.youkehai.assistant.core.resp.assistants.AssistantFile; import io.github.youkehai.assistant.core.resp.assistants.Assistants; import io.github.youkehai.assistant.core.resp.file.File; import io.github.youkehai.assistant.core.resp.message.Message; import io.github.youkehai.assistant.core.resp.run.Run; import io.github.youkehai.assistant.core.resp.run.RunStep; import io.github.youkehai.assistant.core.resp.thread.Thread; import io.github.youkehai.assistant.core.service.AssistantsMessageApiService; import io.github.youkehai.assistant.core.service.AssistantsRunApiService; import io.github.youkehai.assistant.core.service.AssistantsService; import io.github.youkehai.assistant.core.service.AssistantsThreadApiService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile;
6,961
package com.kh.assistants.front.controller; /** * assistants api */ @AllArgsConstructor @Tag(name = "assistantsAPI") @RestController @RequestMapping("/assistant") @Slf4j public class AssistantsApiController { private final AssistantsMessageApiService assistantsMessageApiService; private final AssistantsRunApiService assistantsRunApiService; private final AssistantsService assistantsService; private final AssistantsThreadApiService assistantsThreadApiService; @Operation(summary = "获取消息列表") @GetMapping("/message/{threadId}")
package com.kh.assistants.front.controller; /** * assistants api */ @AllArgsConstructor @Tag(name = "assistantsAPI") @RestController @RequestMapping("/assistant") @Slf4j public class AssistantsApiController { private final AssistantsMessageApiService assistantsMessageApiService; private final AssistantsRunApiService assistantsRunApiService; private final AssistantsService assistantsService; private final AssistantsThreadApiService assistantsThreadApiService; @Operation(summary = "获取消息列表") @GetMapping("/message/{threadId}")
public BasePageResp<Message> messageList(@PathVariable("threadId") String threadId, PageReq pageReqVO) {
10
2023-11-25 13:19:47+00:00
8k
confluentinc/flink-cookbook
pattern-matching-cep/src/test/java/io/confluent/developer/cookbook/flink/PatternMatchingCEPTest.java
[ { "identifier": "TOPIC", "path": "pattern-matching-cep/src/main/java/io/confluent/developer/cookbook/flink/PatternMatchingCEP.java", "snippet": "static final String TOPIC = \"input\";" }, { "identifier": "HOT", "path": "pattern-matching-cep/src/main/java/io/confluent/developer/cookbook/flink...
import static io.confluent.developer.cookbook.flink.PatternMatchingCEP.TOPIC; import static io.confluent.developer.cookbook.flink.records.SensorReading.HOT; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertThrows; import io.confluent.developer.cookbook.flink.extensions.MiniClusterExtensionFactory; import io.confluent.developer.cookbook.flink.patterns.MatcherV1; import io.confluent.developer.cookbook.flink.patterns.MatcherV2; import io.confluent.developer.cookbook.flink.patterns.MatcherV3; import io.confluent.developer.cookbook.flink.patterns.PatternMatcher; import io.confluent.developer.cookbook.flink.records.OscillatingSensorReadingSupplier; import io.confluent.developer.cookbook.flink.records.RisingSensorReadingSupplier; import io.confluent.developer.cookbook.flink.records.SensorReading; import io.confluent.developer.cookbook.flink.records.SensorReadingDeserializationSchema; import io.confluent.developer.cookbook.flink.utils.CookbookKafkaCluster; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import org.apache.flink.connector.kafka.source.KafkaSource; import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.test.junit5.MiniClusterExtension; import org.apache.flink.types.PojoTestUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension;
4,277
package io.confluent.developer.cookbook.flink; class PatternMatchingCEPTest { @RegisterExtension static final MiniClusterExtension FLINK = MiniClusterExtensionFactory.withDefaultConfiguration(); private static final int EVENTS_PER_SECOND = 10; /** * Verify that Flink recognizes the SensorReading type as a POJO that it can serialize * efficiently. */ @Test void sensorReadingsAreAPOJOs() { PojoTestUtils.assertSerializedAsPojo(SensorReading.class); } @Test void matcherV2FindsMoreThanOneRisingHotStreak() throws Exception { Duration limitOfHeatTolerance = Duration.ofSeconds(1); long secondsOfData = 3; PatternMatcher<SensorReading, SensorReading> matcherV2 = new MatcherV2(); assertThat(risingHotStreaks(HOT - 1, secondsOfData, matcherV2, limitOfHeatTolerance)) .hasSizeGreaterThan(1); } @Test void matcherV3FindsOneRisingHotStreak() throws Exception { Duration limitOfHeatTolerance = Duration.ofSeconds(1); long secondsOfData = 3; PatternMatcher<SensorReading, SensorReading> matcherV3 = new MatcherV3(); assertThat(risingHotStreaks(HOT - 1, secondsOfData, matcherV3, limitOfHeatTolerance)) .hasSize(1); } @Test void matcherV2FindsAnOscillatingHotStreak() throws Exception { long secondsOfHeat = 3; Duration limitOfHeatTolerance = Duration.ofSeconds(2); PatternMatcher<SensorReading, SensorReading> matcherV2 = new MatcherV2(); assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV2, limitOfHeatTolerance)) .isNotEmpty(); } @Test void matcherV3FindsAnOscillatingHotStreak() throws Exception { long secondsOfHeat = 3; Duration limitOfHeatTolerance = Duration.ofSeconds(2); PatternMatcher<SensorReading, SensorReading> matcherV3 = new MatcherV3(); assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV3, limitOfHeatTolerance)) .isNotEmpty(); } @Test void matcherV1ErroneouslyFindsOscillatingHotStreaks() { long secondsOfHeat = 1; Duration limitOfHeatTolerance = Duration.ofSeconds(2); PatternMatcher<SensorReading, SensorReading> matcherV1 = new MatcherV1(); assertThrows( AssertionError.class, () -> assertThat( oscillatingHotStreaks( secondsOfHeat, matcherV1, limitOfHeatTolerance)) .isEmpty()); } @Test void matcherV2FindsNoOscillatingHotStreaks() throws Exception { long secondsOfHeat = 1; Duration limitOfHeatTolerance = Duration.ofSeconds(2); PatternMatcher<SensorReading, SensorReading> matcherV2 = new MatcherV2(); assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV2, limitOfHeatTolerance)).isEmpty(); } @Test void matcherV3FindsNoOscillatingHotStreaks() throws Exception { long secondsOfHeat = 1; Duration limitOfHeatTolerance = Duration.ofSeconds(2); PatternMatcher<SensorReading, SensorReading> matcherV3 = new MatcherV3(); assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV3, limitOfHeatTolerance)).isEmpty(); } private List<SensorReading> risingHotStreaks( long initialTemp, long secondsOfData, PatternMatcher<SensorReading, SensorReading> matcher, Duration limitOfHeatTolerance) throws Exception { Stream<SensorReading> readings = Stream.generate(new RisingSensorReadingSupplier(initialTemp)) .limit(secondsOfData * EVENTS_PER_SECOND); return runTestJob(readings, matcher, limitOfHeatTolerance); } private List<SensorReading> oscillatingHotStreaks( long secondsOfHeat, PatternMatcher<SensorReading, SensorReading> matcher, Duration limitOfHeatTolerance) throws Exception { Stream<SensorReading> readings = Stream.generate(new OscillatingSensorReadingSupplier(secondsOfHeat)) .limit(3 * secondsOfHeat * EVENTS_PER_SECOND); return runTestJob(readings, matcher, limitOfHeatTolerance); } private List<SensorReading> runTestJob( Stream<SensorReading> stream, PatternMatcher<SensorReading, SensorReading> patternMatcher, Duration limitOfHeatTolerance) throws Exception {
package io.confluent.developer.cookbook.flink; class PatternMatchingCEPTest { @RegisterExtension static final MiniClusterExtension FLINK = MiniClusterExtensionFactory.withDefaultConfiguration(); private static final int EVENTS_PER_SECOND = 10; /** * Verify that Flink recognizes the SensorReading type as a POJO that it can serialize * efficiently. */ @Test void sensorReadingsAreAPOJOs() { PojoTestUtils.assertSerializedAsPojo(SensorReading.class); } @Test void matcherV2FindsMoreThanOneRisingHotStreak() throws Exception { Duration limitOfHeatTolerance = Duration.ofSeconds(1); long secondsOfData = 3; PatternMatcher<SensorReading, SensorReading> matcherV2 = new MatcherV2(); assertThat(risingHotStreaks(HOT - 1, secondsOfData, matcherV2, limitOfHeatTolerance)) .hasSizeGreaterThan(1); } @Test void matcherV3FindsOneRisingHotStreak() throws Exception { Duration limitOfHeatTolerance = Duration.ofSeconds(1); long secondsOfData = 3; PatternMatcher<SensorReading, SensorReading> matcherV3 = new MatcherV3(); assertThat(risingHotStreaks(HOT - 1, secondsOfData, matcherV3, limitOfHeatTolerance)) .hasSize(1); } @Test void matcherV2FindsAnOscillatingHotStreak() throws Exception { long secondsOfHeat = 3; Duration limitOfHeatTolerance = Duration.ofSeconds(2); PatternMatcher<SensorReading, SensorReading> matcherV2 = new MatcherV2(); assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV2, limitOfHeatTolerance)) .isNotEmpty(); } @Test void matcherV3FindsAnOscillatingHotStreak() throws Exception { long secondsOfHeat = 3; Duration limitOfHeatTolerance = Duration.ofSeconds(2); PatternMatcher<SensorReading, SensorReading> matcherV3 = new MatcherV3(); assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV3, limitOfHeatTolerance)) .isNotEmpty(); } @Test void matcherV1ErroneouslyFindsOscillatingHotStreaks() { long secondsOfHeat = 1; Duration limitOfHeatTolerance = Duration.ofSeconds(2); PatternMatcher<SensorReading, SensorReading> matcherV1 = new MatcherV1(); assertThrows( AssertionError.class, () -> assertThat( oscillatingHotStreaks( secondsOfHeat, matcherV1, limitOfHeatTolerance)) .isEmpty()); } @Test void matcherV2FindsNoOscillatingHotStreaks() throws Exception { long secondsOfHeat = 1; Duration limitOfHeatTolerance = Duration.ofSeconds(2); PatternMatcher<SensorReading, SensorReading> matcherV2 = new MatcherV2(); assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV2, limitOfHeatTolerance)).isEmpty(); } @Test void matcherV3FindsNoOscillatingHotStreaks() throws Exception { long secondsOfHeat = 1; Duration limitOfHeatTolerance = Duration.ofSeconds(2); PatternMatcher<SensorReading, SensorReading> matcherV3 = new MatcherV3(); assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV3, limitOfHeatTolerance)).isEmpty(); } private List<SensorReading> risingHotStreaks( long initialTemp, long secondsOfData, PatternMatcher<SensorReading, SensorReading> matcher, Duration limitOfHeatTolerance) throws Exception { Stream<SensorReading> readings = Stream.generate(new RisingSensorReadingSupplier(initialTemp)) .limit(secondsOfData * EVENTS_PER_SECOND); return runTestJob(readings, matcher, limitOfHeatTolerance); } private List<SensorReading> oscillatingHotStreaks( long secondsOfHeat, PatternMatcher<SensorReading, SensorReading> matcher, Duration limitOfHeatTolerance) throws Exception { Stream<SensorReading> readings = Stream.generate(new OscillatingSensorReadingSupplier(secondsOfHeat)) .limit(3 * secondsOfHeat * EVENTS_PER_SECOND); return runTestJob(readings, matcher, limitOfHeatTolerance); } private List<SensorReading> runTestJob( Stream<SensorReading> stream, PatternMatcher<SensorReading, SensorReading> patternMatcher, Duration limitOfHeatTolerance) throws Exception {
try (final CookbookKafkaCluster kafka = new CookbookKafkaCluster(EVENTS_PER_SECOND)) {
11
2023-11-20 16:31:54+00:00
8k
objectionary/opeo-maven-plugin
src/main/java/org/eolang/opeo/jeo/JeoDecompiler.java
[ { "identifier": "DecompilerMachine", "path": "src/main/java/org/eolang/opeo/decompilation/DecompilerMachine.java", "snippet": "public final class DecompilerMachine {\n\n /**\n * Output Stack.\n */\n private final Deque<AstNode> stack;\n\n /**\n * Local variables.\n */\n priva...
import org.eolang.opeo.decompilation.DecompilerMachine; import org.eolang.opeo.decompilation.LocalVariables; import org.w3c.dom.Node; import org.xembly.Transformers; import org.xembly.Xembler; import com.jcabi.xml.XML; import com.jcabi.xml.XMLDocument; import java.util.Map; import java.util.stream.Collectors; import org.eolang.jeo.representation.xmir.XmlMethod; import org.eolang.jeo.representation.xmir.XmlNode; import org.eolang.jeo.representation.xmir.XmlProgram;
4,671
/* * The MIT License (MIT) * * Copyright (c) 2016-2023 Objectionary.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.eolang.opeo.jeo; /** * Decompiler that gets jeo instructions and decompiles them into high-level EO constructs. * @since 0.1 */ public final class JeoDecompiler { /** * Program in XMIR format received from jeo maven plugin. */ private final XML prog; /** * Constructor. * @param prog Program in XMIR format received from jeo maven plugin. */ public JeoDecompiler(final XML prog) { this.prog = prog; } /** * Decompile program. * @return EO program. */ public XML decompile() { final Node node = this.prog.node(); new XmlProgram(node).top() .methods() .forEach(JeoDecompiler::decompile); return new XMLDocument(node); } /** * Decompile method. * @param method Method. */ private static void decompile(final XmlMethod method) { if (!method.instructions().isEmpty()) { method.replaceInstructions( new XmlNode( new Xembler( new DecompilerMachine(
/* * The MIT License (MIT) * * Copyright (c) 2016-2023 Objectionary.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.eolang.opeo.jeo; /** * Decompiler that gets jeo instructions and decompiles them into high-level EO constructs. * @since 0.1 */ public final class JeoDecompiler { /** * Program in XMIR format received from jeo maven plugin. */ private final XML prog; /** * Constructor. * @param prog Program in XMIR format received from jeo maven plugin. */ public JeoDecompiler(final XML prog) { this.prog = prog; } /** * Decompile program. * @return EO program. */ public XML decompile() { final Node node = this.prog.node(); new XmlProgram(node).top() .methods() .forEach(JeoDecompiler::decompile); return new XMLDocument(node); } /** * Decompile method. * @param method Method. */ private static void decompile(final XmlMethod method) { if (!method.instructions().isEmpty()) { method.replaceInstructions( new XmlNode( new Xembler( new DecompilerMachine(
new LocalVariables(method.access()),
1
2023-11-20 13:01:13+00:00
8k
GregTech-Chinese-Community/EPCore
src/main/java/cn/gtcommunity/epimorphism/api/capability/impl/OreProcessingLogic.java
[ { "identifier": "EPUniverUtil", "path": "src/main/java/cn/gtcommunity/epimorphism/api/utils/EPUniverUtil.java", "snippet": "public class EPUniverUtil {\n\n // Utils\n public static int getOrDefault(NBTTagCompound tag, String key, int defaultValue){\n if(tag.hasKey(key)){\n retur...
import cn.gtcommunity.epimorphism.api.utils.EPUniverUtil; import cn.gtcommunity.epimorphism.common.metatileentities.multiblock.EPMetaTileEntityIntegratedOreFactory; import gregtech.api.GTValues; import gregtech.api.capability.*; import gregtech.api.capability.impl.EnergyContainerList; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.recipes.Recipe; import gregtech.api.recipes.RecipeMaps; import gregtech.api.unification.OreDictUnifier; import gregtech.api.unification.material.Materials; import gregtech.api.unification.ore.OrePrefix; import gregtech.api.util.GTTransferUtils; import gregtech.api.util.GTUtility; import gregtech.common.ConfigHolder; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.network.PacketBuffer; import net.minecraft.util.NonNullList; import net.minecraft.world.World; import net.minecraftforge.common.util.Constants; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.oredict.OreDictionary; import javax.annotation.Nonnull; import java.util.*; import java.util.stream.Collectors;
6,116
package cn.gtcommunity.epimorphism.api.capability.impl; /* * Referenced some code from GT5 Unofficial * * https://github.com/GTNewHorizons/GT5-Unofficial/ * */ //TODO 重写配方逻辑以添加满箱检测和更好的配方检测 public class OreProcessingLogic implements IWorkable{ private static final int MAX_PARA = 1024; private static final HashSet<Integer> isCrushedOre = new HashSet<>(); private static final HashSet<Integer> isCrushedPureOre = new HashSet<>(); private static final HashSet<Integer> isPureDust = new HashSet<>(); private static final HashSet<Integer> isImpureDust = new HashSet<>(); private static final HashSet<Integer> isThermal = new HashSet<>(); private static final HashSet<Integer> isOre = new HashSet<>(); private ItemStack[] midProduct; protected int[] overclockResults; private int progressTime = 0; protected int maxProgressTime; private boolean isActive; protected boolean canRecipeProgress = true; protected int recipeEUt; protected List<FluidStack> fluidOutputs; protected NonNullList<ItemStack> itemOutputs; protected boolean workingEnabled = true; protected boolean hasNotEnoughEnergy; protected boolean wasActiveAndNeedsUpdate; protected boolean isOutputsFull; private int mode = 0; private static boolean init = false; private boolean isVoidStone = false;
package cn.gtcommunity.epimorphism.api.capability.impl; /* * Referenced some code from GT5 Unofficial * * https://github.com/GTNewHorizons/GT5-Unofficial/ * */ //TODO 重写配方逻辑以添加满箱检测和更好的配方检测 public class OreProcessingLogic implements IWorkable{ private static final int MAX_PARA = 1024; private static final HashSet<Integer> isCrushedOre = new HashSet<>(); private static final HashSet<Integer> isCrushedPureOre = new HashSet<>(); private static final HashSet<Integer> isPureDust = new HashSet<>(); private static final HashSet<Integer> isImpureDust = new HashSet<>(); private static final HashSet<Integer> isThermal = new HashSet<>(); private static final HashSet<Integer> isOre = new HashSet<>(); private ItemStack[] midProduct; protected int[] overclockResults; private int progressTime = 0; protected int maxProgressTime; private boolean isActive; protected boolean canRecipeProgress = true; protected int recipeEUt; protected List<FluidStack> fluidOutputs; protected NonNullList<ItemStack> itemOutputs; protected boolean workingEnabled = true; protected boolean hasNotEnoughEnergy; protected boolean wasActiveAndNeedsUpdate; protected boolean isOutputsFull; private int mode = 0; private static boolean init = false; private boolean isVoidStone = false;
private final EPMetaTileEntityIntegratedOreFactory metaTileEntity;
1
2023-11-26 01:56:35+00:00
8k
LaughingMuffin/laughing-logger
app/src/main/java/org/laughing/logger/util/ThemeWrapper.java
[ { "identifier": "App", "path": "app/src/main/java/org/laughing/logger/App.java", "snippet": "public class App extends Application {\n public static final String MUFFIN_ADS = \"MUFFIN-ADS\";\n private static App instance;\n private SharedPreferences preferences;\n\n public App() {\n in...
import android.app.Activity; import android.content.Context; import android.os.Build; import androidx.annotation.StyleRes; import org.laughing.logger.App; import org.laughing.logger.R; import org.laughing.logger.data.ColorScheme; import org.laughing.logger.helper.PreferenceHelper;
5,066
package org.laughing.logger.util; /** * Created by Snow Volf on 16.07.2019, 20:40 */ public abstract class ThemeWrapper { /** * Apply theme to an Activity */ public static void applyTheme(Activity ctx) { int theme; switch (Theme.values()[getThemeIndex()]) { case LIGHT: theme = R.style.Theme_LaughingLogger_Light; if (isDarkScheme(ctx)){ PreferenceHelper.setColorScheme(ctx, ColorScheme.Light); } break; case DARK: theme = R.style.Theme_LaughingLogger; if (isLightScheme(ctx)) { PreferenceHelper.setColorScheme(ctx, ColorScheme.Dark); } break; case AMOLED: theme = R.style.Theme_LaughingLogger_Amoled; if (isLightScheme(ctx)) { PreferenceHelper.setColorScheme(ctx, ColorScheme.Amoled); } break; default: // Force use the light theme theme = R.style.Theme_LaughingLogger_Light; break; } ctx.setTheme(theme); applyAccent(ctx); } private static void applyAccent(Context ctx){ int accent; switch (Accent.values()[getAccentIndex()]){ case RED: accent = R.style.AccentRed; break; case PINK: accent = R.style.AccentPink; break; case PURPLE: accent = R.style.AccentPurple; break; case INDIGO: accent = R.style.AccentIndigo; break; case BLUE: accent = R.style.AccentBlue; break; case LBLUE: accent = R.style.AccentLBlue; break; case CYAN: accent = R.style.AccentCyan; break; case TEAL: accent = R.style.AccentTeal; break; case GREEN: accent = R.style.AccentGreen; break; case LGREEN: accent = R.style.AccentLGreen; break; case LIME: accent = R.style.AccentLime; break; case YELLOW: accent = R.style.AccentYellow; break; case AMBER: accent = R.style.AccentAmber; break; case ORANGE: accent = R.style.AccentOrange; break; case DORANGE: accent = R.style.AccentDOrange; break; case BROWN: accent = R.style.AccentBrown; break; case GREY: accent = R.style.AccentGrey; break; case BGREY: accent = R.style.AccentBGrey; break; default: accent = R.style.AccentBlue; break; } ctx.getTheme().applyStyle(accent, true); } @StyleRes public static int getDialogTheme(){ int theme; switch (Theme.values()[getThemeIndex()]){ case LIGHT: theme = R.style.Theme_MaterialComponents_Light_Dialog_Alert; break; case DARK: theme = R.style.DarkAppTheme_Dialog; break; case AMOLED: theme = R.style.AmoledAppTheme_Dialog; break; default: theme = R.style.Theme_MaterialComponents_Light_Dialog_Alert; } return theme; } /** * Get a saved theme number */ private static int getThemeIndex() {
package org.laughing.logger.util; /** * Created by Snow Volf on 16.07.2019, 20:40 */ public abstract class ThemeWrapper { /** * Apply theme to an Activity */ public static void applyTheme(Activity ctx) { int theme; switch (Theme.values()[getThemeIndex()]) { case LIGHT: theme = R.style.Theme_LaughingLogger_Light; if (isDarkScheme(ctx)){ PreferenceHelper.setColorScheme(ctx, ColorScheme.Light); } break; case DARK: theme = R.style.Theme_LaughingLogger; if (isLightScheme(ctx)) { PreferenceHelper.setColorScheme(ctx, ColorScheme.Dark); } break; case AMOLED: theme = R.style.Theme_LaughingLogger_Amoled; if (isLightScheme(ctx)) { PreferenceHelper.setColorScheme(ctx, ColorScheme.Amoled); } break; default: // Force use the light theme theme = R.style.Theme_LaughingLogger_Light; break; } ctx.setTheme(theme); applyAccent(ctx); } private static void applyAccent(Context ctx){ int accent; switch (Accent.values()[getAccentIndex()]){ case RED: accent = R.style.AccentRed; break; case PINK: accent = R.style.AccentPink; break; case PURPLE: accent = R.style.AccentPurple; break; case INDIGO: accent = R.style.AccentIndigo; break; case BLUE: accent = R.style.AccentBlue; break; case LBLUE: accent = R.style.AccentLBlue; break; case CYAN: accent = R.style.AccentCyan; break; case TEAL: accent = R.style.AccentTeal; break; case GREEN: accent = R.style.AccentGreen; break; case LGREEN: accent = R.style.AccentLGreen; break; case LIME: accent = R.style.AccentLime; break; case YELLOW: accent = R.style.AccentYellow; break; case AMBER: accent = R.style.AccentAmber; break; case ORANGE: accent = R.style.AccentOrange; break; case DORANGE: accent = R.style.AccentDOrange; break; case BROWN: accent = R.style.AccentBrown; break; case GREY: accent = R.style.AccentGrey; break; case BGREY: accent = R.style.AccentBGrey; break; default: accent = R.style.AccentBlue; break; } ctx.getTheme().applyStyle(accent, true); } @StyleRes public static int getDialogTheme(){ int theme; switch (Theme.values()[getThemeIndex()]){ case LIGHT: theme = R.style.Theme_MaterialComponents_Light_Dialog_Alert; break; case DARK: theme = R.style.DarkAppTheme_Dialog; break; case AMOLED: theme = R.style.AmoledAppTheme_Dialog; break; default: theme = R.style.Theme_MaterialComponents_Light_Dialog_Alert; } return theme; } /** * Get a saved theme number */ private static int getThemeIndex() {
return Integer.parseInt(App.get().getPreferences().getString("ui.theme", String.valueOf(Theme.LIGHT.ordinal())));
0
2023-11-19 15:31:51+00:00
8k
GT-ARC/opaca-core
opaca-platform/src/test/java/de/gtarc/opaca/platform/tests/ContainerTests.java
[ { "identifier": "AgentContainerApi", "path": "opaca-model/src/main/java/de/gtarc/opaca/api/AgentContainerApi.java", "snippet": "public interface AgentContainerApi extends CommonApi{\n\n String ENV_CONTAINER_ID = \"CONTAINER_ID\";\n\n String ENV_PLATFORM_URL = \"PLATFORM_URL\";\n\n String ENV_TO...
import de.gtarc.opaca.api.AgentContainerApi; import de.gtarc.opaca.model.AgentContainer; import de.gtarc.opaca.model.AgentDescription; import de.gtarc.opaca.model.RuntimePlatform; import de.gtarc.opaca.platform.Application; import de.gtarc.opaca.util.RestHelper; import org.junit.*; import org.springframework.boot.SpringApplication; import org.springframework.context.ConfigurableApplicationContext; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import java.util.stream.Stream; import static de.gtarc.opaca.platform.tests.TestUtils.*;
5,647
var message = Map.of("payload", "testMessage", "replyTo", "doesnotmatter"); var con = request(PLATFORM_URL, "POST", "/send/unknownagent", message); Assert.assertEquals(404, con.getResponseCode()); } /** * call broadcast, check that it arrived via another invoke */ @Test public void testBroadcast() throws Exception { var message = Map.of("payload", "testBroadcast", "replyTo", "doesnotmatter"); var con = request(PLATFORM_URL, "POST", "/broadcast/topic", message); Assert.assertEquals(200, con.getResponseCode()); con = request(PLATFORM_URL, "POST", "/invoke/GetInfo/sample1", Map.of()); Assert.assertEquals(200, con.getResponseCode()); var res = result(con, Map.class); Assert.assertEquals("testBroadcast", res.get("lastBroadcast")); } /** * test that container's /info route can be accessed via that port */ @Test public void testApiPort() throws Exception { var con = request(PLATFORM_URL, "GET", "/containers/" + containerId, null); var res = result(con, AgentContainer.class).getConnectivity(); // access /info route through exposed port var url = String.format("%s:%s", res.getPublicUrl(), res.getApiPortMapping()); System.out.println(url); con = request(url, "GET", "/info", null); Assert.assertEquals(200, con.getResponseCode()); } /** * test exposed extra port (has to be provided in sample image) */ @Test public void testExtraPortTCP() throws Exception { var con = request(PLATFORM_URL, "GET", "/containers/" + containerId, null); var res = result(con, AgentContainer.class).getConnectivity(); var url = String.format("%s:%s", res.getPublicUrl(), "8888"); con = request(url, "GET", "/", null); Assert.assertEquals(200, con.getResponseCode()); Assert.assertEquals("It Works!", result(con)); } @Test public void testExtraPortUDP() throws Exception { var addr = InetAddress.getByName("localhost"); DatagramSocket clientSocket = new DatagramSocket(); byte[] sendData = "Test".getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, addr, 8889); clientSocket.send(sendPacket); byte[] receiveData = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength()); Assert.assertEquals("TestTest", receivedMessage); clientSocket.close(); } /** * TODO check somehow that notify worked */ @Test public void testContainerNotify() throws Exception { var con1 = request(PLATFORM_URL, "POST", "/containers/notify", containerId); Assert.assertEquals(200, con1.getResponseCode()); } /** * tries to notify about non-existing container */ @Test public void testInvalidContainerNotify() throws Exception { var con1 = request(PLATFORM_URL, "POST", "/containers/notify", "container-does-not-exist"); Assert.assertEquals(404, con1.getResponseCode()); } /** * test that connectivity info is still there after /notify */ @Test public void testNotifyConnectivity() throws Exception { request(PLATFORM_URL, "POST", "/containers/notify", containerId); var con = request(PLATFORM_URL, "GET", "/containers/" + containerId, null); var res = result(con, AgentContainer.class); Assert.assertNotNull(res.getConnectivity()); } /** * Deploy an additional sample-container on the same platform, so there are two of the same. * Then /send and /broadcast messages to one particular container, then /invoke the GetInfo * action of the respective containers to check that the messages were delivered correctly. */ @Test public void testSendWithContainerId() throws Exception { // deploy a second sample container image on platform A var image = getSampleContainerImage(); var con = request(PLATFORM_URL, "POST", "/containers", image); var newContainerId = result(con); try { // directed /send and /broadcast to both containers var msg1 = Map.of("payload", "\"Message to First Container\"", "replyTo", ""); var msg2 = Map.of("payload", "\"Message to Second Container\"", "replyTo", ""); request(PLATFORM_URL, "POST", "/broadcast/topic?containerId=" + containerId, msg1); request(PLATFORM_URL, "POST", "/send/sample1?containerId=" + newContainerId, msg2); Thread.sleep(500); // directed /invoke of GetInfo to check last messages of first container con = request(PLATFORM_URL, "POST", "/invoke/GetInfo/sample1?containerId=" + containerId, Map.of()); var res1 = result(con, Map.class); System.out.println(res1);
package de.gtarc.opaca.platform.tests; /** * This module is for tests that require the sample agent container to be deployed for e.g. testing invoking actions. * The tests should not deploy other container, or if so, those should be removed after the test. In general, all the * tests should be (and remain) independent of each other, able to run individually or in any order. * At the start, a single runtime platform is started and a sample-agent-container is deployed. That state should be * maintained after each test. */ public class ContainerTests { private static final int PLATFORM_PORT = 8003; private static final String PLATFORM_URL = "http://localhost:" + PLATFORM_PORT; private static ConfigurableApplicationContext platform = null; private static String containerId = null; @BeforeClass public static void setupPlatform() throws IOException { platform = SpringApplication.run(Application.class, "--server.port=" + PLATFORM_PORT); containerId = postSampleContainer(PLATFORM_URL); } @AfterClass public static void stopPlatform() { platform.close(); } @After public void checkInvariant() throws Exception { var con1 = request(PLATFORM_URL, "GET", "/info", null); var res1 = result(con1, RuntimePlatform.class); Assert.assertEquals(1, res1.getContainers().size()); var agents = res1.getContainers().get(0).getAgents(); Assert.assertEquals(2, agents.size()); } /** * get container info */ @Test public void testGetContainerInfo() throws Exception { var con = request(PLATFORM_URL, "GET", "/containers/" + containerId, null); Assert.assertEquals(200, con.getResponseCode()); var res = result(con, AgentContainer.class); Assert.assertEquals(containerId, res.getContainerId()); } @Test public void testGetAgents() throws Exception { var con = request(PLATFORM_URL, "GET", "/agents", null); Assert.assertEquals(200, con.getResponseCode()); var res = result(con, List.class); Assert.assertEquals(2, res.size()); } @Test public void testGetAgent() throws Exception { var con = request(PLATFORM_URL, "GET", "/agents/sample1", null); Assert.assertEquals(200, con.getResponseCode()); var res = result(con, AgentDescription.class); Assert.assertEquals("sample1", res.getAgentId()); } @Test public void testGetUnknownAgent() throws Exception { var con = request(PLATFORM_URL, "GET", "/agents/unknown", null); Assert.assertEquals(200, con.getResponseCode()); var res = result(con); Assert.assertTrue(res.isEmpty()); } /** * call invoke, check result */ @Test public void testInvokeAction() throws Exception { var params = Map.of("x", 23, "y", 42); var con = request(PLATFORM_URL, "POST", "/invoke/Add", params); Assert.assertEquals(200, con.getResponseCode()); var res = result(con, Integer.class); Assert.assertEquals(65L, res.longValue()); } @Test public void testStream() throws Exception { var con = request(PLATFORM_URL, "GET", "/stream/GetStream", null); Assert.assertEquals(200, con.getResponseCode()); var inputStream = con.getInputStream(); var bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); var response = bufferedReader.readLine(); Assert.assertEquals("{\"key\":\"value\"}", response); } /** * call invoke with agent, check result */ @Test public void testInvokeAgentAction() throws Exception { for (String name : List.of("sample1", "sample2")) { var con = request(PLATFORM_URL, "POST", "/invoke/GetInfo/" + name, Map.of()); var res = result(con, Map.class); Assert.assertEquals(name, res.get("name")); } } @Test public void testInvokeFail() throws Exception { var con = request(PLATFORM_URL, "POST", "/invoke/Fail", Map.of()); Assert.assertEquals(502, con.getResponseCode()); var msg = error(con); Assert.assertTrue(msg.contains("Action Failed (as expected)")); } /** * test that action invocation fails if it does not respond within the specified time * TODO this is not ideal yet... the original error may contain a descriptive message that is lost */ @Test public void testInvokeTimeout() throws Exception { var params = Map.of("message", "timeout-test", "sleep_seconds", 5); var con = request(PLATFORM_URL, "POST", "/invoke/DoThis?timeout=2", params); Assert.assertEquals(502, con.getResponseCode()); } /** * invoke action with mismatched/missing parameters * TODO case of missing parameter could also be handled by platform, resulting in 422 error */ @Test public void testInvokeParamMismatch() throws Exception { var con = request(PLATFORM_URL, "POST", "/invoke/DoThis", Map.of("message", "missing 'sleep_seconds' parameter!")); Assert.assertEquals(502, con.getResponseCode()); } /** * try to invoke unknown action * -> 404 (not found) */ @Test public void testUnknownAction() throws Exception { var con = request(PLATFORM_URL, "POST", "/invoke/UnknownAction", Map.of()); Assert.assertEquals(404, con.getResponseCode()); con = request(PLATFORM_URL, "POST", "/invoke/Add/unknownagent", Map.of()); Assert.assertEquals(404, con.getResponseCode()); } /** * call send, check that it arrived via another invoke */ @Test public void testSend() throws Exception { var message = Map.of("payload", "testMessage", "replyTo", "doesnotmatter"); var con = request(PLATFORM_URL, "POST", "/send/sample1", message); Assert.assertEquals(200, con.getResponseCode()); con = request(PLATFORM_URL, "POST", "/invoke/GetInfo/sample1", Map.of()); Assert.assertEquals(200, con.getResponseCode()); var res = result(con, Map.class); Assert.assertEquals("testMessage", res.get("lastMessage")); } /** * try to send message to unknown agent * -> 404 (not found) */ @Test public void testUnknownSend() throws Exception { var message = Map.of("payload", "testMessage", "replyTo", "doesnotmatter"); var con = request(PLATFORM_URL, "POST", "/send/unknownagent", message); Assert.assertEquals(404, con.getResponseCode()); } /** * call broadcast, check that it arrived via another invoke */ @Test public void testBroadcast() throws Exception { var message = Map.of("payload", "testBroadcast", "replyTo", "doesnotmatter"); var con = request(PLATFORM_URL, "POST", "/broadcast/topic", message); Assert.assertEquals(200, con.getResponseCode()); con = request(PLATFORM_URL, "POST", "/invoke/GetInfo/sample1", Map.of()); Assert.assertEquals(200, con.getResponseCode()); var res = result(con, Map.class); Assert.assertEquals("testBroadcast", res.get("lastBroadcast")); } /** * test that container's /info route can be accessed via that port */ @Test public void testApiPort() throws Exception { var con = request(PLATFORM_URL, "GET", "/containers/" + containerId, null); var res = result(con, AgentContainer.class).getConnectivity(); // access /info route through exposed port var url = String.format("%s:%s", res.getPublicUrl(), res.getApiPortMapping()); System.out.println(url); con = request(url, "GET", "/info", null); Assert.assertEquals(200, con.getResponseCode()); } /** * test exposed extra port (has to be provided in sample image) */ @Test public void testExtraPortTCP() throws Exception { var con = request(PLATFORM_URL, "GET", "/containers/" + containerId, null); var res = result(con, AgentContainer.class).getConnectivity(); var url = String.format("%s:%s", res.getPublicUrl(), "8888"); con = request(url, "GET", "/", null); Assert.assertEquals(200, con.getResponseCode()); Assert.assertEquals("It Works!", result(con)); } @Test public void testExtraPortUDP() throws Exception { var addr = InetAddress.getByName("localhost"); DatagramSocket clientSocket = new DatagramSocket(); byte[] sendData = "Test".getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, addr, 8889); clientSocket.send(sendPacket); byte[] receiveData = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength()); Assert.assertEquals("TestTest", receivedMessage); clientSocket.close(); } /** * TODO check somehow that notify worked */ @Test public void testContainerNotify() throws Exception { var con1 = request(PLATFORM_URL, "POST", "/containers/notify", containerId); Assert.assertEquals(200, con1.getResponseCode()); } /** * tries to notify about non-existing container */ @Test public void testInvalidContainerNotify() throws Exception { var con1 = request(PLATFORM_URL, "POST", "/containers/notify", "container-does-not-exist"); Assert.assertEquals(404, con1.getResponseCode()); } /** * test that connectivity info is still there after /notify */ @Test public void testNotifyConnectivity() throws Exception { request(PLATFORM_URL, "POST", "/containers/notify", containerId); var con = request(PLATFORM_URL, "GET", "/containers/" + containerId, null); var res = result(con, AgentContainer.class); Assert.assertNotNull(res.getConnectivity()); } /** * Deploy an additional sample-container on the same platform, so there are two of the same. * Then /send and /broadcast messages to one particular container, then /invoke the GetInfo * action of the respective containers to check that the messages were delivered correctly. */ @Test public void testSendWithContainerId() throws Exception { // deploy a second sample container image on platform A var image = getSampleContainerImage(); var con = request(PLATFORM_URL, "POST", "/containers", image); var newContainerId = result(con); try { // directed /send and /broadcast to both containers var msg1 = Map.of("payload", "\"Message to First Container\"", "replyTo", ""); var msg2 = Map.of("payload", "\"Message to Second Container\"", "replyTo", ""); request(PLATFORM_URL, "POST", "/broadcast/topic?containerId=" + containerId, msg1); request(PLATFORM_URL, "POST", "/send/sample1?containerId=" + newContainerId, msg2); Thread.sleep(500); // directed /invoke of GetInfo to check last messages of first container con = request(PLATFORM_URL, "POST", "/invoke/GetInfo/sample1?containerId=" + containerId, Map.of()); var res1 = result(con, Map.class); System.out.println(res1);
Assert.assertEquals(containerId, res1.get(AgentContainerApi.ENV_CONTAINER_ID));
0
2023-11-23 11:06:10+00:00
8k
lushangkan/AutoStreamingAssistant
src/main/java/cn/cutemc/autostreamingassistant/AutoStreamingAssistant.java
[ { "identifier": "WorldStatus", "path": "src/main/java/cn/cutemc/autostreamingassistant/beans/WorldStatus.java", "snippet": "@Getter\n@Setter\npublic class WorldStatus {\n private boolean loading;\n}" }, { "identifier": "Camera", "path": "src/main/java/cn/cutemc/autostreamingassistant/came...
import cn.cutemc.autostreamingassistant.beans.WorldStatus; import cn.cutemc.autostreamingassistant.camera.Camera; import cn.cutemc.autostreamingassistant.commands.ModCommands; import cn.cutemc.autostreamingassistant.config.ModConfig; import cn.cutemc.autostreamingassistant.keybindings.ModKeyBinding; import cn.cutemc.autostreamingassistant.listeners.ConfigListener; import cn.cutemc.autostreamingassistant.listeners.KeyListener; import cn.cutemc.autostreamingassistant.network.packets.ClientBindCameraHandler; import cn.cutemc.autostreamingassistant.network.packets.ClientRequestBindStatusHandle; import cn.cutemc.autostreamingassistant.network.packets.ClientRequestStatusHandler; import cn.cutemc.autostreamingassistant.network.packets.ClientUnbindCameraHandler; import cn.cutemc.autostreamingassistant.utils.SystemUtils; import lombok.extern.log4j.Log4j2; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.loader.api.FabricLoader;
5,033
package cn.cutemc.autostreamingassistant; @Log4j2 public class AutoStreamingAssistant implements ClientModInitializer { public static String VERSION; public static ModConfig CONFIG; public static ModKeyBinding KEYBINDING; public static Camera CAMERA; public static boolean isLinuxMint = false;
package cn.cutemc.autostreamingassistant; @Log4j2 public class AutoStreamingAssistant implements ClientModInitializer { public static String VERSION; public static ModConfig CONFIG; public static ModKeyBinding KEYBINDING; public static Camera CAMERA; public static boolean isLinuxMint = false;
public static WorldStatus worldStatus = new WorldStatus();
0
2023-11-20 14:02:38+00:00
8k
myzticbean/QSFindItemAddOn
src/main/java/io/myzticbean/finditemaddon/Handlers/GUIHandler/PaginatedMenu.java
[ { "identifier": "FindItemAddOn", "path": "src/main/java/io/myzticbean/finditemaddon/FindItemAddOn.java", "snippet": "public final class FindItemAddOn extends JavaPlugin {\n\n private static Plugin plugin;\n public FindItemAddOn() { plugin = this; }\n public static Plugin getInstance() { return ...
import io.myzticbean.finditemaddon.FindItemAddOn; import io.myzticbean.finditemaddon.Models.FoundShopItemModel; import io.myzticbean.finditemaddon.Utils.LoggerUtils; import me.kodysimpson.simpapi.colors.ColorTranslator; import org.apache.commons.lang3.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.List; import java.util.UUID;
4,136
package io.myzticbean.finditemaddon.Handlers.GUIHandler; public abstract class PaginatedMenu extends Menu { protected int page = 0; protected int maxItemsPerPage = 45; protected int index = 0; protected ItemStack backButton; protected ItemStack nextButton; protected ItemStack closeInvButton; private final String BACK_BUTTON_SKIN_ID = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjZkYWI3MjcxZjRmZjA0ZDU0NDAyMTkwNjdhMTA5YjVjMGMxZDFlMDFlYzYwMmMwMDIwNDc2ZjdlYjYxMjE4MCJ9fX0="; private final String NEXT_BUTTON_SKIN_ID = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOGFhMTg3ZmVkZTg4ZGUwMDJjYmQ5MzA1NzVlYjdiYTQ4ZDNiMWEwNmQ5NjFiZGM1MzU4MDA3NTBhZjc2NDkyNiJ9fX0="; public PaginatedMenu(PlayerMenuUtility playerMenuUtility) { super(playerMenuUtility); initMaterialsForBottomBar(); } public PaginatedMenu(PlayerMenuUtility playerMenuUtility, List<FoundShopItemModel> searchResult) { super(playerMenuUtility); initMaterialsForBottomBar(); super.playerMenuUtility.setPlayerShopSearchResult(searchResult); } private void initMaterialsForBottomBar() { createGUIBackButton(); createGUINextButton(); createGUICloseInvButton(); } public void addMenuBottomBar() { inventory.setItem(45, backButton); inventory.setItem(53, nextButton); inventory.setItem(49, closeInvButton); inventory.setItem(46, super.GUI_FILLER_ITEM); inventory.setItem(47, super.GUI_FILLER_ITEM); inventory.setItem(48, super.GUI_FILLER_ITEM); inventory.setItem(50, super.GUI_FILLER_ITEM); inventory.setItem(51, super.GUI_FILLER_ITEM); inventory.setItem(52, super.GUI_FILLER_ITEM); } private void createGUIBackButton() {
package io.myzticbean.finditemaddon.Handlers.GUIHandler; public abstract class PaginatedMenu extends Menu { protected int page = 0; protected int maxItemsPerPage = 45; protected int index = 0; protected ItemStack backButton; protected ItemStack nextButton; protected ItemStack closeInvButton; private final String BACK_BUTTON_SKIN_ID = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjZkYWI3MjcxZjRmZjA0ZDU0NDAyMTkwNjdhMTA5YjVjMGMxZDFlMDFlYzYwMmMwMDIwNDc2ZjdlYjYxMjE4MCJ9fX0="; private final String NEXT_BUTTON_SKIN_ID = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOGFhMTg3ZmVkZTg4ZGUwMDJjYmQ5MzA1NzVlYjdiYTQ4ZDNiMWEwNmQ5NjFiZGM1MzU4MDA3NTBhZjc2NDkyNiJ9fX0="; public PaginatedMenu(PlayerMenuUtility playerMenuUtility) { super(playerMenuUtility); initMaterialsForBottomBar(); } public PaginatedMenu(PlayerMenuUtility playerMenuUtility, List<FoundShopItemModel> searchResult) { super(playerMenuUtility); initMaterialsForBottomBar(); super.playerMenuUtility.setPlayerShopSearchResult(searchResult); } private void initMaterialsForBottomBar() { createGUIBackButton(); createGUINextButton(); createGUICloseInvButton(); } public void addMenuBottomBar() { inventory.setItem(45, backButton); inventory.setItem(53, nextButton); inventory.setItem(49, closeInvButton); inventory.setItem(46, super.GUI_FILLER_ITEM); inventory.setItem(47, super.GUI_FILLER_ITEM); inventory.setItem(48, super.GUI_FILLER_ITEM); inventory.setItem(50, super.GUI_FILLER_ITEM); inventory.setItem(51, super.GUI_FILLER_ITEM); inventory.setItem(52, super.GUI_FILLER_ITEM); } private void createGUIBackButton() {
Material backButtonMaterial = Material.getMaterial(FindItemAddOn.getConfigProvider().SHOP_GUI_BACK_BUTTON_MATERIAL);
0
2023-11-22 11:36:01+00:00
8k
DIDA-lJ/qiyao-12306
services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/service/handler/ticket/TrainSecondClassPurchaseTicketHandler.java
[ { "identifier": "VehicleSeatTypeEnum", "path": "services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/common/enums/VehicleSeatTypeEnum.java", "snippet": "@RequiredArgsConstructor\npublic enum VehicleSeatTypeEnum {\n\n /**\n * 商务座\n */\n BUSINESS_CLASS(0, \"BUSINE...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.ListUtil; import cn.hutool.core.lang.Pair; import com.google.common.collect.Lists; import lombok.RequiredArgsConstructor; import org.opengoofy.index12306.biz.ticketservice.common.enums.VehicleSeatTypeEnum; import org.opengoofy.index12306.biz.ticketservice.common.enums.VehicleTypeEnum; import org.opengoofy.index12306.biz.ticketservice.dto.domain.PurchaseTicketPassengerDetailDTO; import org.opengoofy.index12306.biz.ticketservice.dto.domain.TrainSeatBaseDTO; import org.opengoofy.index12306.biz.ticketservice.service.SeatService; import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.base.AbstractTrainPurchaseTicketTemplate; import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.dto.SelectSeatDTO; import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.dto.TrainPurchaseTicketRespDTO; import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.select.SeatSelection; import org.opengoofy.index12306.biz.ticketservice.toolkit.SeatNumberUtil; import org.opengoofy.index12306.framework.starter.convention.exception.ServiceException; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger;
6,047
/* * 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.ticketservice.service.handler.ticket; /** * 高铁二等座购票组件 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @Component @RequiredArgsConstructor public class TrainSecondClassPurchaseTicketHandler extends AbstractTrainPurchaseTicketTemplate { private final SeatService seatService; private static final Map<Character, Integer> SEAT_Y_INT = Map.of('A', 0, 'B', 1, 'C', 2, 'D', 3, 'F', 4); @Override public String mark() { return VehicleTypeEnum.HIGH_SPEED_RAIN.getName() + VehicleSeatTypeEnum.SECOND_CLASS.getName(); } @Override protected List<TrainPurchaseTicketRespDTO> selectSeats(SelectSeatDTO requestParam) { String trainId = requestParam.getRequestParam().getTrainId(); String departure = requestParam.getRequestParam().getDeparture(); String arrival = requestParam.getRequestParam().getArrival(); List<PurchaseTicketPassengerDetailDTO> passengerSeatDetails = requestParam.getPassengerSeatDetails(); List<String> trainCarriageList = seatService.listUsableCarriageNumber(trainId, requestParam.getSeatType(), departure, arrival); List<Integer> trainStationCarriageRemainingTicket = seatService.listSeatRemainingTicket(trainId, departure, arrival, trainCarriageList); int remainingTicketSum = trainStationCarriageRemainingTicket.stream().mapToInt(Integer::intValue).sum(); if (remainingTicketSum < passengerSeatDetails.size()) {
/* * 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.ticketservice.service.handler.ticket; /** * 高铁二等座购票组件 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @Component @RequiredArgsConstructor public class TrainSecondClassPurchaseTicketHandler extends AbstractTrainPurchaseTicketTemplate { private final SeatService seatService; private static final Map<Character, Integer> SEAT_Y_INT = Map.of('A', 0, 'B', 1, 'C', 2, 'D', 3, 'F', 4); @Override public String mark() { return VehicleTypeEnum.HIGH_SPEED_RAIN.getName() + VehicleSeatTypeEnum.SECOND_CLASS.getName(); } @Override protected List<TrainPurchaseTicketRespDTO> selectSeats(SelectSeatDTO requestParam) { String trainId = requestParam.getRequestParam().getTrainId(); String departure = requestParam.getRequestParam().getDeparture(); String arrival = requestParam.getRequestParam().getArrival(); List<PurchaseTicketPassengerDetailDTO> passengerSeatDetails = requestParam.getPassengerSeatDetails(); List<String> trainCarriageList = seatService.listUsableCarriageNumber(trainId, requestParam.getSeatType(), departure, arrival); List<Integer> trainStationCarriageRemainingTicket = seatService.listSeatRemainingTicket(trainId, departure, arrival, trainCarriageList); int remainingTicketSum = trainStationCarriageRemainingTicket.stream().mapToInt(Integer::intValue).sum(); if (remainingTicketSum < passengerSeatDetails.size()) {
throw new ServiceException("站点余票不足,请尝试更换座位类型或选择其它站点");
10
2023-11-23 07:59:11+00:00
8k
estkme-group/infineon-lpa-mirror
app/src/main/java/com/infineon/esim/lpa/lpa/task/ProfileActionTask.java
[ { "identifier": "ProfileActionType", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/enums/ProfileActionType.java", "snippet": "public enum ProfileActionType {\n PROFILE_ACTION_ENABLE,\n PROFILE_ACTION_DELETE,\n PROFILE_ACTION_DISABLE,\n PROFILE_ACTION_SET_NICKNAME,\n}" }, { ...
import java.util.concurrent.Callable; import com.infineon.esim.lpa.core.dtos.enums.ProfileActionType; import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata; import com.infineon.esim.lpa.core.dtos.result.local.EnableResult; import com.infineon.esim.lpa.core.dtos.result.local.OperationResult; import com.infineon.esim.lpa.core.dtos.result.remote.HandleNotificationsResult; import com.infineon.esim.lpa.lpa.LocalProfileAssistant; import com.infineon.esim.util.Log;
5,301
/* * 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.lpa.task; public class ProfileActionTask implements Callable<Void> { private static final String TAG = ProfileActionTask.class.getName(); private final LocalProfileAssistant lpa;
/* * 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.lpa.task; public class ProfileActionTask implements Callable<Void> { private static final String TAG = ProfileActionTask.class.getName(); private final LocalProfileAssistant lpa;
private final ProfileActionType profileActionType;
0
2023-11-22 07:46:30+00:00
8k
idaoyu/iot-project-java
iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/product/service/ProductInfoManageService.java
[ { "identifier": "BizException", "path": "iotp-dependency/iotp-dependency-web/src/main/java/com/bbkk/project/exception/BizException.java", "snippet": "public class BizException extends RuntimeException {\n\n public BizException(String message) {\n super(message);\n }\n}" }, { "identi...
import com.baomidou.mybatisplus.core.metadata.IPage; import com.bbkk.project.exception.BizException; import com.bbkk.project.module.device.service.IDeviceEvidencePoolService; import com.bbkk.project.module.product.constant.ProductAuthType; import com.bbkk.project.module.product.constant.TslTypeConstant; import com.bbkk.project.module.product.convert.ProductInfoConvert; import com.bbkk.project.module.product.data.OperationProductInfoParams; import com.bbkk.project.module.product.data.PageGetProductInfoParams; import com.bbkk.project.module.product.data.PageGetProductInfoVO; import com.bbkk.project.module.product.data.ProductInfoAndTslDTO; import com.bbkk.project.module.product.entity.ProductInfo; import com.bbkk.project.module.product.entity.ProductInfoTsl; import com.bbkk.project.module.product.entity.ProductType; import com.bbkk.project.module.tsl.service.ITslEventService; import com.bbkk.project.module.tsl.service.ITslMethodService; import com.bbkk.project.module.tsl.service.ITslPropertyService; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date;
4,021
package com.bbkk.project.module.product.service; /** * 产品信息管理接口 业务逻辑 * * @author 一条秋刀鱼zz qchenzexuan@vip.qq.com * @since 2023-12-12 19:27 **/ @Service @RequiredArgsConstructor public class ProductInfoManageService { private final IProductInfoService productInfoService; private final IProductTypeService productTypeService; private final IProductInfoTslService productInfoTslService; private final ITslPropertyService tslPropertyService; private final ITslMethodService tslMethodService; private final ITslEventService tslEventService; private final IDeviceEvidencePoolService deviceEvidencePoolService; private final ProductInfoConvert productInfoConvert; public IPage<PageGetProductInfoVO> pageGetProductInfo(PageGetProductInfoParams params) { // todo 待重构 需要考虑物模型、认证方式等数据的展示方法 IPage<ProductInfo> page = productInfoService.pageGetProductInfo(params); return page.convert(v -> { PageGetProductInfoVO.PageGetProductInfoVOBuilder builder = PageGetProductInfoVO.builder(); builder.id(v.getId()); builder.name(v.getName()); builder.description(v.getDescription()); builder.imageUrl(v.getImageUrl()); builder.needSaveProperty(v.getNeedSaveProperty()); builder.createTime(v.getCreateTime()); builder.updateTime(v.getUpdateTime()); if (v.getType() != null) { ProductType productType = productTypeService.getById(v.getType()); builder.type(productType != null ? productType.getName() : "其他"); } else { builder.type("其他"); } return builder.build(); }); } @Transactional(rollbackFor = Exception.class) public String createProductInfo(OperationProductInfoParams params) { ProductInfo productInfo = productInfoConvert.operationProductInfoParams2ProductInfo(params); // 如果未指定是否需要保存设备上报的属性 则 默认为不保存 if (params.getNeedSaveProperty() == null) { productInfo.setNeedSaveProperty(false); } else { productInfo.setNeedSaveProperty(params.getNeedSaveProperty()); } if (params.getType() != null) { ProductType productType = productTypeService.getOptById(params.getType()).orElseThrow(() -> new BizException("产品类目错误")); productInfo.setType(productType.getId()); } // 默认的状态就是开发中,除非用户手动指定状态 if (StringUtils.isNotBlank(params.getStatus())) { productInfo.setStatus(params.getStatus()); } else { // todo 懒得写枚举了,如果后续状态有业务逻辑意义再写吧 productInfo.setStatus("dev"); } boolean save = productInfoService.save(productInfo); if (!save) { throw new BizException("创建产品失败,请稍后重试"); } // 需要认证,并且认证类型为一个产品一个密钥时,在创建产品时生成密钥 if (productInfo.getNeedAuth() && productInfo.getAuthType().equals(ProductAuthType.BIND_PRODUCT.getType())) { deviceEvidencePoolService.generateAuthKeyAndBind(productInfo.getId(), null); } for (ProductInfoAndTslDTO productInfoAndTslDTO : params.getTslList()) { String type = productInfoAndTslDTO.getType(); String tslId = productInfoAndTslDTO.getTslId();
package com.bbkk.project.module.product.service; /** * 产品信息管理接口 业务逻辑 * * @author 一条秋刀鱼zz qchenzexuan@vip.qq.com * @since 2023-12-12 19:27 **/ @Service @RequiredArgsConstructor public class ProductInfoManageService { private final IProductInfoService productInfoService; private final IProductTypeService productTypeService; private final IProductInfoTslService productInfoTslService; private final ITslPropertyService tslPropertyService; private final ITslMethodService tslMethodService; private final ITslEventService tslEventService; private final IDeviceEvidencePoolService deviceEvidencePoolService; private final ProductInfoConvert productInfoConvert; public IPage<PageGetProductInfoVO> pageGetProductInfo(PageGetProductInfoParams params) { // todo 待重构 需要考虑物模型、认证方式等数据的展示方法 IPage<ProductInfo> page = productInfoService.pageGetProductInfo(params); return page.convert(v -> { PageGetProductInfoVO.PageGetProductInfoVOBuilder builder = PageGetProductInfoVO.builder(); builder.id(v.getId()); builder.name(v.getName()); builder.description(v.getDescription()); builder.imageUrl(v.getImageUrl()); builder.needSaveProperty(v.getNeedSaveProperty()); builder.createTime(v.getCreateTime()); builder.updateTime(v.getUpdateTime()); if (v.getType() != null) { ProductType productType = productTypeService.getById(v.getType()); builder.type(productType != null ? productType.getName() : "其他"); } else { builder.type("其他"); } return builder.build(); }); } @Transactional(rollbackFor = Exception.class) public String createProductInfo(OperationProductInfoParams params) { ProductInfo productInfo = productInfoConvert.operationProductInfoParams2ProductInfo(params); // 如果未指定是否需要保存设备上报的属性 则 默认为不保存 if (params.getNeedSaveProperty() == null) { productInfo.setNeedSaveProperty(false); } else { productInfo.setNeedSaveProperty(params.getNeedSaveProperty()); } if (params.getType() != null) { ProductType productType = productTypeService.getOptById(params.getType()).orElseThrow(() -> new BizException("产品类目错误")); productInfo.setType(productType.getId()); } // 默认的状态就是开发中,除非用户手动指定状态 if (StringUtils.isNotBlank(params.getStatus())) { productInfo.setStatus(params.getStatus()); } else { // todo 懒得写枚举了,如果后续状态有业务逻辑意义再写吧 productInfo.setStatus("dev"); } boolean save = productInfoService.save(productInfo); if (!save) { throw new BizException("创建产品失败,请稍后重试"); } // 需要认证,并且认证类型为一个产品一个密钥时,在创建产品时生成密钥 if (productInfo.getNeedAuth() && productInfo.getAuthType().equals(ProductAuthType.BIND_PRODUCT.getType())) { deviceEvidencePoolService.generateAuthKeyAndBind(productInfo.getId(), null); } for (ProductInfoAndTslDTO productInfoAndTslDTO : params.getTslList()) { String type = productInfoAndTslDTO.getType(); String tslId = productInfoAndTslDTO.getTslId();
if (type.equals(TslTypeConstant.PROPERTY.getValue())) {
3
2023-11-25 06:59:20+00:00
8k
MattiDragon/JsonPatcherLang
src/test/java/io/github/mattidragon/jsonpatcher/lang/test/TestUtils.java
[ { "identifier": "Value", "path": "src/main/java/io/github/mattidragon/jsonpatcher/lang/runtime/Value.java", "snippet": "public sealed interface Value {\n ThreadLocal<Set<Value>> TO_STRING_RECURSION_TRACKER = ThreadLocal.withInitial(HashSet::new);\n\n boolean asBoolean();\n\n @NotNull\n stati...
import io.github.mattidragon.jsonpatcher.lang.parse.*; import io.github.mattidragon.jsonpatcher.lang.runtime.EvaluationContext; import io.github.mattidragon.jsonpatcher.lang.runtime.Value; import io.github.mattidragon.jsonpatcher.lang.runtime.expression.Expression; import io.github.mattidragon.jsonpatcher.lang.runtime.expression.ValueExpression; import io.github.mattidragon.jsonpatcher.lang.runtime.function.PatchFunction; import io.github.mattidragon.jsonpatcher.lang.runtime.statement.BlockStatement; import io.github.mattidragon.jsonpatcher.lang.runtime.statement.Statement; import io.github.mattidragon.jsonpatcher.lang.runtime.statement.UnnecessarySemicolonStatement; import io.github.mattidragon.jsonpatcher.lang.runtime.stdlib.LibraryBuilder; import org.junit.jupiter.api.AssertionFailureBuilder; import org.junit.jupiter.api.Assertions; import java.util.List; import java.util.function.Consumer; import static io.github.mattidragon.jsonpatcher.lang.parse.Parser.parseExpression; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertNotNull;
4,473
package io.github.mattidragon.jsonpatcher.lang.test; public class TestUtils { public static final SourceFile FILE = new SourceFile("test file", "00"); public static final SourceSpan POS = new SourceSpan(new SourcePos(FILE, 1, 1), new SourcePos(FILE, 1, 2)); public static final Consumer<Value> EMPTY_DEBUG_CONSUMER = (value) -> {}; public static EvaluationContext createTestContext() { return EvaluationContext.builder().debugConsumer(EMPTY_DEBUG_CONSUMER).build(); } public static LibraryBuilder.FunctionContext createTestFunctionContext() { return new LibraryBuilder.FunctionContext(createTestContext(), POS); } public static void testCode(String code, Value expected) { var result = Parser.parse(Lexer.lex(code, "test file").tokens()); if (!(result instanceof Parser.Result.Success success)) { var error = new RuntimeException("Expected successful parse"); ((Parser.Result.Fail) result).errors().forEach(error::addSuppressed); AssertionFailureBuilder.assertionFailure() .message("Expected successful parse") .cause(error) .buildAndThrow(); return; } var program = success.program(); var output = new Value[1]; var context = EvaluationContext.builder() .debugConsumer(EMPTY_DEBUG_CONSUMER) .variable("testResult", new Value.FunctionValue((PatchFunction.BuiltInPatchFunction) (ctx, args, pos) -> { output[0] = args.get(0); return Value.NullValue.NULL; })) .build(); program.execute(context); Assertions.assertNotEquals(null, output[0], "testResult should be called"); assertEquals(expected, output[0]); } public static void testExpression(String code, Value expected) {
package io.github.mattidragon.jsonpatcher.lang.test; public class TestUtils { public static final SourceFile FILE = new SourceFile("test file", "00"); public static final SourceSpan POS = new SourceSpan(new SourcePos(FILE, 1, 1), new SourcePos(FILE, 1, 2)); public static final Consumer<Value> EMPTY_DEBUG_CONSUMER = (value) -> {}; public static EvaluationContext createTestContext() { return EvaluationContext.builder().debugConsumer(EMPTY_DEBUG_CONSUMER).build(); } public static LibraryBuilder.FunctionContext createTestFunctionContext() { return new LibraryBuilder.FunctionContext(createTestContext(), POS); } public static void testCode(String code, Value expected) { var result = Parser.parse(Lexer.lex(code, "test file").tokens()); if (!(result instanceof Parser.Result.Success success)) { var error = new RuntimeException("Expected successful parse"); ((Parser.Result.Fail) result).errors().forEach(error::addSuppressed); AssertionFailureBuilder.assertionFailure() .message("Expected successful parse") .cause(error) .buildAndThrow(); return; } var program = success.program(); var output = new Value[1]; var context = EvaluationContext.builder() .debugConsumer(EMPTY_DEBUG_CONSUMER) .variable("testResult", new Value.FunctionValue((PatchFunction.BuiltInPatchFunction) (ctx, args, pos) -> { output[0] = args.get(0); return Value.NullValue.NULL; })) .build(); program.execute(context); Assertions.assertNotEquals(null, output[0], "testResult should be called"); assertEquals(expected, output[0]); } public static void testExpression(String code, Value expected) {
var expression = new Expression[1];
1
2023-11-23 14:17:00+00:00
8k
quarkusio/conversational-release-action
src/main/java/io/quarkus/bot/release/step/SyncCoreRelease.java
[ { "identifier": "ReleaseInformation", "path": "src/main/java/io/quarkus/bot/release/ReleaseInformation.java", "snippet": "public class ReleaseInformation {\n\n private final String branch;\n private final String qualifier;\n private final boolean major;\n\n private String version;\n priva...
import java.io.IOException; import java.util.HashMap; import java.util.Map; import jakarta.inject.Singleton; import org.kohsuke.github.GHIssue; import org.kohsuke.github.GHIssueComment; import org.kohsuke.github.GitHub; import io.quarkiverse.githubaction.Commands; import io.quarkiverse.githubaction.Context; import io.quarkus.arc.Unremovable; import io.quarkus.bot.release.ReleaseInformation; import io.quarkus.bot.release.ReleaseStatus; import io.quarkus.bot.release.util.Branches; import io.quarkus.bot.release.util.Command; import io.quarkus.bot.release.util.MonitorArtifactPublicationInputKeys; import io.quarkus.bot.release.util.Outputs; import io.quarkus.bot.release.util.Progress; import io.quarkus.bot.release.util.UpdatedIssueBody; import io.quarkus.bot.release.util.Versions;
4,132
package io.quarkus.bot.release.step; @Singleton @Unremovable public class SyncCoreRelease implements StepHandler { @Override public boolean shouldPause(Context context, Commands commands, GitHub quarkusBotGitHub, ReleaseInformation releaseInformation, ReleaseStatus releaseStatus, GHIssue issue, GHIssueComment issueComment) { StringBuilder comment = new StringBuilder(); comment.append("The core artifacts have been pushed to `s01.oss.sonatype.org`.\n\n"); comment.append( "**IMPORTANT** You need to wait for them to be synced to Maven Central before continuing with the release:\n\n"); try { Map<String, Object> inputs = new HashMap<>(); inputs.put(MonitorArtifactPublicationInputKeys.GROUP_ID, "io.quarkus"); inputs.put(MonitorArtifactPublicationInputKeys.ARTIFACT_ID, "quarkus-bom"); inputs.put(MonitorArtifactPublicationInputKeys.VERSION, releaseInformation.getVersion()); inputs.put(MonitorArtifactPublicationInputKeys.ISSUE_NUMBER, String.valueOf(issue.getNumber())); inputs.put(MonitorArtifactPublicationInputKeys.MESSAGE_IF_PUBLISHED, Command.CONTINUE.getFullCommand() + "\n\nWe have detected that the core artifacts have been synced to Maven Central."); inputs.put(MonitorArtifactPublicationInputKeys.MESSAGE_IF_NOT_PUBLISHED, "The core artifacts don't seem to have been synced to Maven Central.\n\n" + "Please check the situation by yourself:\n\n" + "* Check that https://repo1.maven.org/maven2/io/quarkus/quarkus-bom/" + releaseInformation.getVersion() + "/" + " does not return a 404\n" + "* Wait some more if it still returns a 404.\n\n" + "Once the artifact is available, wait for an additional 20 minutes then you can continue with the release by adding a `" + Command.CONTINUE.getFullCommand() + "` comment."); inputs.put(MonitorArtifactPublicationInputKeys.INITIAL_DELAY, "30"); inputs.put(MonitorArtifactPublicationInputKeys.POLL_ITERATIONS, "3"); inputs.put(MonitorArtifactPublicationInputKeys.POLL_DELAY, "10"); inputs.put(MonitorArtifactPublicationInputKeys.POST_DELAY, "20"); issue.getRepository().getWorkflow("monitor-artifact-publication.yml").dispatch(Branches.MAIN, inputs); comment.append("The publication of the core artifacts will take 60-80 minutes.\n\n" + "**We started a separate workflow to monitor the situation for you. It will automatically continue the release process once it detects the artifacts have been synced to Maven Central.**\n\n"); comment.append("---\n\n"); comment.append("<details><summary>If things go south</summary>\n\n"); comment.append("If things go south, you can monitor the situation manually:\n\n"); comment.append("* Wait for 1 hour (starting from the time of this comment)\n"); comment.append("* Check that https://repo1.maven.org/maven2/io/quarkus/quarkus-bom/" + releaseInformation.getVersion() + "/" + " does not return a 404\n\n"); comment.append( "Once these two conditions are met, you can continue with the release by adding a `" + Command.CONTINUE.getFullCommand() + "` comment.\n\n"); comment.append("</details>"); } catch (Exception e) { comment.append("We were unable to start the core artifacts monitoring workflow, so please monitor the situation manually:\n\n"); comment.append("* Wait for 1 hour (starting from the time of this comment)\n"); comment.append("* Check that https://repo1.maven.org/maven2/io/quarkus/quarkus-bom/" + releaseInformation.getVersion() + "/" + " does not return a 404\n\n"); comment.append( "Once these two conditions are met, you can continue with the release by adding a `" + Command.CONTINUE.getFullCommand() + "` comment."); }
package io.quarkus.bot.release.step; @Singleton @Unremovable public class SyncCoreRelease implements StepHandler { @Override public boolean shouldPause(Context context, Commands commands, GitHub quarkusBotGitHub, ReleaseInformation releaseInformation, ReleaseStatus releaseStatus, GHIssue issue, GHIssueComment issueComment) { StringBuilder comment = new StringBuilder(); comment.append("The core artifacts have been pushed to `s01.oss.sonatype.org`.\n\n"); comment.append( "**IMPORTANT** You need to wait for them to be synced to Maven Central before continuing with the release:\n\n"); try { Map<String, Object> inputs = new HashMap<>(); inputs.put(MonitorArtifactPublicationInputKeys.GROUP_ID, "io.quarkus"); inputs.put(MonitorArtifactPublicationInputKeys.ARTIFACT_ID, "quarkus-bom"); inputs.put(MonitorArtifactPublicationInputKeys.VERSION, releaseInformation.getVersion()); inputs.put(MonitorArtifactPublicationInputKeys.ISSUE_NUMBER, String.valueOf(issue.getNumber())); inputs.put(MonitorArtifactPublicationInputKeys.MESSAGE_IF_PUBLISHED, Command.CONTINUE.getFullCommand() + "\n\nWe have detected that the core artifacts have been synced to Maven Central."); inputs.put(MonitorArtifactPublicationInputKeys.MESSAGE_IF_NOT_PUBLISHED, "The core artifacts don't seem to have been synced to Maven Central.\n\n" + "Please check the situation by yourself:\n\n" + "* Check that https://repo1.maven.org/maven2/io/quarkus/quarkus-bom/" + releaseInformation.getVersion() + "/" + " does not return a 404\n" + "* Wait some more if it still returns a 404.\n\n" + "Once the artifact is available, wait for an additional 20 minutes then you can continue with the release by adding a `" + Command.CONTINUE.getFullCommand() + "` comment."); inputs.put(MonitorArtifactPublicationInputKeys.INITIAL_DELAY, "30"); inputs.put(MonitorArtifactPublicationInputKeys.POLL_ITERATIONS, "3"); inputs.put(MonitorArtifactPublicationInputKeys.POLL_DELAY, "10"); inputs.put(MonitorArtifactPublicationInputKeys.POST_DELAY, "20"); issue.getRepository().getWorkflow("monitor-artifact-publication.yml").dispatch(Branches.MAIN, inputs); comment.append("The publication of the core artifacts will take 60-80 minutes.\n\n" + "**We started a separate workflow to monitor the situation for you. It will automatically continue the release process once it detects the artifacts have been synced to Maven Central.**\n\n"); comment.append("---\n\n"); comment.append("<details><summary>If things go south</summary>\n\n"); comment.append("If things go south, you can monitor the situation manually:\n\n"); comment.append("* Wait for 1 hour (starting from the time of this comment)\n"); comment.append("* Check that https://repo1.maven.org/maven2/io/quarkus/quarkus-bom/" + releaseInformation.getVersion() + "/" + " does not return a 404\n\n"); comment.append( "Once these two conditions are met, you can continue with the release by adding a `" + Command.CONTINUE.getFullCommand() + "` comment.\n\n"); comment.append("</details>"); } catch (Exception e) { comment.append("We were unable to start the core artifacts monitoring workflow, so please monitor the situation manually:\n\n"); comment.append("* Wait for 1 hour (starting from the time of this comment)\n"); comment.append("* Check that https://repo1.maven.org/maven2/io/quarkus/quarkus-bom/" + releaseInformation.getVersion() + "/" + " does not return a 404\n\n"); comment.append( "Once these two conditions are met, you can continue with the release by adding a `" + Command.CONTINUE.getFullCommand() + "` comment."); }
comment.append("\n\n" + Progress.youAreHere(releaseInformation, releaseStatus));
6
2023-11-20 10:33:48+00:00
8k
wssun/AST4PLU
data-process/process/src/main/java/process/SplitAST_for_csn.java
[ { "identifier": "GenerateAST", "path": "data-process/process/src/main/java/JDT/GenerateAST.java", "snippet": "public class GenerateAST {\n\tprivate static String ast;\n\tprivate static String masked_ast;\n\t\n\tpublic static class astVisitor extends ASTVisitor{\n\t\tpublic void preVisit(ASTNode node) {\...
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.List; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import JDT.GenerateAST; import tree.Tree; import utils.TreeToJSON; import utils.TreeTools;
6,480
package process; public class SplitAST_for_csn { private static String AST_FILE_PATH="D:\\ast_dataset\\csn\\split_ast\\train_ast.jsonl"; private static String JSON_FILE_PATH="D:\\ast_dataset\\csn\\split_ast\\train.jsonl"; // use Tree-sitter public static void main(String[] args) throws IOException { FileReader fr = null; BufferedReader br = null; File jsonFile = null; FileWriter fileWriter = null; BufferedWriter bw = null; try { fr = new FileReader(AST_FILE_PATH); br = new BufferedReader(fr); jsonFile = new File(JSON_FILE_PATH); if (!jsonFile.exists()) { jsonFile.createNewFile(); } fileWriter = new FileWriter(jsonFile.getAbsoluteFile()); bw = new BufferedWriter(fileWriter); String line = ""; //读取每一行的数据 int cnt=1; while ( (line = br.readLine()) != null) { JSONObject lineJson = JSONObject.parseObject(line); String repo=lineJson.getString("repo"); String path=lineJson.getString("path"); String func_name=lineJson.getString("func_name"); String original_string=lineJson.getString("original_string"); String language=lineJson.getString("language"); String original_code=lineJson.getString("code"); JSONArray code_tokens=lineJson.getJSONArray("code_tokens"); String docstring=lineJson.getString("docstring"); JSONArray docstring_tokens=lineJson.getJSONArray("docstring_tokens"); JSONArray asts=lineJson.getJSONArray("asts"); List<String> ast_seqs = JSONObject.parseArray(asts.toJSONString(),String.class); int sz=ast_seqs.size(); JSONArray new_asts=new JSONArray(); for(int i=0;i<sz;++i) { Tree ast=TreeTools.stringToTree(ast_seqs.get(i));
package process; public class SplitAST_for_csn { private static String AST_FILE_PATH="D:\\ast_dataset\\csn\\split_ast\\train_ast.jsonl"; private static String JSON_FILE_PATH="D:\\ast_dataset\\csn\\split_ast\\train.jsonl"; // use Tree-sitter public static void main(String[] args) throws IOException { FileReader fr = null; BufferedReader br = null; File jsonFile = null; FileWriter fileWriter = null; BufferedWriter bw = null; try { fr = new FileReader(AST_FILE_PATH); br = new BufferedReader(fr); jsonFile = new File(JSON_FILE_PATH); if (!jsonFile.exists()) { jsonFile.createNewFile(); } fileWriter = new FileWriter(jsonFile.getAbsoluteFile()); bw = new BufferedWriter(fileWriter); String line = ""; //读取每一行的数据 int cnt=1; while ( (line = br.readLine()) != null) { JSONObject lineJson = JSONObject.parseObject(line); String repo=lineJson.getString("repo"); String path=lineJson.getString("path"); String func_name=lineJson.getString("func_name"); String original_string=lineJson.getString("original_string"); String language=lineJson.getString("language"); String original_code=lineJson.getString("code"); JSONArray code_tokens=lineJson.getJSONArray("code_tokens"); String docstring=lineJson.getString("docstring"); JSONArray docstring_tokens=lineJson.getJSONArray("docstring_tokens"); JSONArray asts=lineJson.getJSONArray("asts"); List<String> ast_seqs = JSONObject.parseArray(asts.toJSONString(),String.class); int sz=ast_seqs.size(); JSONArray new_asts=new JSONArray(); for(int i=0;i<sz;++i) { Tree ast=TreeTools.stringToTree(ast_seqs.get(i));
TreeToJSON.toJSON(ast,0);
2
2023-11-23 06:08:43+00:00
8k
CaoBaoQi/homework-android
work-course-table-v2/src/main/java/jz/cbq/work_course_table_v2/ui/slideshow/SlideshowFragment.java
[ { "identifier": "MainActivity", "path": "work-course-table-v2/src/main/java/jz/cbq/work_course_table_v2/MainActivity.java", "snippet": "public class MainActivity extends AppCompatActivity {\n\n private AppBarConfiguration mAppBarConfiguration;\n public static int courseflag = 0;\n public static...
import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import java.util.ArrayList; import java.util.Calendar; import jz.cbq.work_course_table_v2.MainActivity; import jz.cbq.work_course_table_v2.R; import jz.cbq.work_course_table_v2.addexam; import jz.cbq.work_course_table_v2.databasehelper; import jz.cbq.work_course_table_v2.examcardadapter; import jz.cbq.work_course_table_v2.examcarditem; import jz.cbq.work_course_table_v2.examcalendarremind;
5,149
package jz.cbq.work_course_table_v2.ui.slideshow; @SuppressLint("Range") public class SlideshowFragment extends Fragment { private SlideshowViewModel slideshowViewModel; private databasehelper examtimedbhelper; ArrayList<examcarditem> examlist = new ArrayList<>(); public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { slideshowViewModel = ViewModelProviders.of(this).get(SlideshowViewModel.class); View root = inflater.inflate(R.layout.fragment_slideshow, container, false); examtimedbhelper = new databasehelper(getActivity(),"database.db",null,1); final SQLiteDatabase examdatabase = examtimedbhelper.getWritableDatabase(); initexamitemcard();//初始化考试LISTVIEW
package jz.cbq.work_course_table_v2.ui.slideshow; @SuppressLint("Range") public class SlideshowFragment extends Fragment { private SlideshowViewModel slideshowViewModel; private databasehelper examtimedbhelper; ArrayList<examcarditem> examlist = new ArrayList<>(); public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { slideshowViewModel = ViewModelProviders.of(this).get(SlideshowViewModel.class); View root = inflater.inflate(R.layout.fragment_slideshow, container, false); examtimedbhelper = new databasehelper(getActivity(),"database.db",null,1); final SQLiteDatabase examdatabase = examtimedbhelper.getWritableDatabase(); initexamitemcard();//初始化考试LISTVIEW
examcardadapter examcardadapter = new examcardadapter(getActivity(), R.layout.examitem, examlist);
3
2023-11-20 17:30:01+00:00
8k
tommyskeff/futur4j
futur-api/src/main/java/dev/tommyjs/futur/impl/SimplePromiseFactory.java
[ { "identifier": "AbstractPromise", "path": "futur-api/src/main/java/dev/tommyjs/futur/promise/AbstractPromise.java", "snippet": "public abstract class AbstractPromise<T> implements Promise<T> {\n\n private final Collection<PromiseListener<T>> listeners;\n\n private @Nullable PromiseCompletion<T> c...
import dev.tommyjs.futur.promise.AbstractPromise; import dev.tommyjs.futur.promise.Promise; import dev.tommyjs.futur.promise.PromiseFactory; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import java.util.concurrent.ScheduledExecutorService;
3,732
package dev.tommyjs.futur.impl; public class SimplePromiseFactory implements PromiseFactory { private final ScheduledExecutorService executor; private final Logger logger; public SimplePromiseFactory(ScheduledExecutorService executor, Logger logger) { this.executor = executor; this.logger = logger; } @Override public @NotNull <T> Promise<T> resolve(T value) {
package dev.tommyjs.futur.impl; public class SimplePromiseFactory implements PromiseFactory { private final ScheduledExecutorService executor; private final Logger logger; public SimplePromiseFactory(ScheduledExecutorService executor, Logger logger) { this.executor = executor; this.logger = logger; } @Override public @NotNull <T> Promise<T> resolve(T value) {
AbstractPromise<T> promise = new SimplePromise<>(executor, logger, this);
0
2023-11-19 20:56:51+00:00
8k
phamdung2209/FAP
src/main/java/com/persons/Administrator.java
[ { "identifier": "Course", "path": "src/main/java/com/course/Course.java", "snippet": "public class Course {\n private String id;\n private String courseName;\n private String description;\n private long cost;\n private Student student;\n private Lecturer lecturer;\n private List<Sch...
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.course.Course; import com.date.DateOfBirth; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.func.Grade; import com.func.ClassroomHandler.Classroom; import com.persons.personType.PersonType;
4,095
// Print the lecture data System.out.format("%-10s %-25s %-25s %-10s\n", "ID", "Course Name", "Description", "Cost"/* * , "Student", "Lecturer", "Start Date", "End Date", * "Status" */); for (Map<String, String> course : courses) { System.out.format("%-10s %-25s %-25s %-10s\n", course.get("id"), course.get("name"), course.get("description"), course.get("cost") /* * ,course.getStudent().getFullName(), course.getLecturer().getFullName(), * course.getStartDate().getDay() + "/" + course.getStartDate().getMonth() + "/" * + course.getStartDate().getYear(), * course.getEndDate().getDay() + "/" + course.getEndDate().getMonth() + "/" * + course.getEndDate().getYear(), * course.getStatus() */ + "\n"); } } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); e.printStackTrace(); } } // update course public boolean updateCourse(String id, Course... courses) { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); List<Map<String, String>> courseList = (List<Map<String, String>>) data.get("courses"); for (Course course : courses) { for (Map<String, String> courseMap : courseList) { if (id.equals(courseMap.get("id"))) { courseMap.put("name", course.getCourseName()); courseMap.put("description", course.getDescription()); courseMap.put("cost", Long.toString(course.getCost())); break; } } } // Update the "courses" key in the data map data.put("courses", courseList); objectMapper.writeValue(file, data); System.out.println("Course with ID " + id + " updated successfully."); return true; } catch (IOException e) { System.err.println("Error reading/writing file: " + e.getMessage()); e.printStackTrace(); } return false; } // delete course public boolean deleteCourse(String id) { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); List<Map<String, String>> courses = (List<Map<String, String>>) data.get("courses"); List<Map<String, String>> grades = (List<Map<String, String>>) data.get("grades"); grades.removeIf(grade -> id.equals(grade.get("courseId"))); courses.removeIf(course -> id.equals(course.get("id"))); data.put("grades", grades); data.put("courses", courses); objectMapper.writeValue(file, data); return true; } catch (IOException e) { System.err.println("Error reading/writing file: " + e.getMessage()); e.printStackTrace(); } return false; } // check course public boolean checkCourse(String courseId) { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); // Extract data from the "courses" key List<Map<String, String>> courses = (List<Map<String, String>>) data.get("courses"); for (Map<String, String> course : courses) { if (course.get("id").equals(courseId)) { return true; } } } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); e.printStackTrace(); } return false; } // ==================== Grade ==================== // add grade
package com.persons; // Component interface interface getNotify { void display(); } class AdministratorGroup implements getNotify { private List<getNotify> administrators = new ArrayList<>(); public AdministratorGroup() { } public void addAdministrator(getNotify administrator) { administrators.add(administrator); } @Override public void display() { System.out.println("Administrator Group"); administrators.forEach(getNotify::display); } } public class Administrator extends User implements getNotify { // Composite pattern - Structural Pattern @Override public void display() { System.out.println("Administrator" + getFullName() + "has been added"); } public static final String filePath = "C:\\Users\\ACER\\Documents\\Course\\Advance Programming\\Assignment 2\\Project\\FAP\\src\\main\\java\\service\\data.json"; // ThreadSafe Singleton Pattern - Creational Pattern private Administrator() { } private static Administrator admin; public static synchronized Administrator getAdministrator() { if (admin == null) { admin = new Administrator(); } return admin; } // iterator pattern - Behavioral Pattern public void viewStudents(){ Student student1 = new Student("Dung Pham"); Student student2 = new Student("John Wick"); Student student3 = new Student("Tony Stark"); List<Student> students = new ArrayList<>(); students.add(student1); students.add(student2); students.add(student3); Iterator student = students.iterator(); while(student.hasNext()){ Student std = (Student) student.next(); System.out.println(std.getFullName()); } } // person type public PersonType getPersonType() { return PersonType.ADMINISTRATOR; } // ==================== Student ==================== // save student to file json.data public boolean addStudent(Student student) { try { // Read existing data from file ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); // Deserialize JSON file into a Map TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() { }; HashMap<String, Object> data = objectMapper.readValue(file, typeRef); // Extract the "students" key and add a new student List<Map<String, String>> students = (List<Map<String, String>>) data.get("students"); if (students == null) { students = new ArrayList<>(); } Map<String, String> newStudent = new HashMap<>(); newStudent.put("id", student.getId()); newStudent.put("name", student.getFullName()); newStudent.put("address", student.getAddress()); newStudent.put("gender", String.valueOf(student.getGender())); newStudent.put("day", String.valueOf(student.getDateOfBirth().getDay())); newStudent.put("month", String.valueOf(student.getDateOfBirth().getMonth())); newStudent.put("year", String.valueOf(student.getDateOfBirth().getYear())); newStudent.put("years", String.valueOf(student.getYear())); newStudent.put("major", student.getMajor()); newStudent.put("phone", student.getPhoneNumber()); newStudent.put("email", student.getEmail()); students.add(newStudent); data.put("students", students); // Write the updated data back to the file objectMapper.writeValue(file, data); System.out.println("Student added successfully."); return true; } catch (IOException e) { System.err.println("Error reading/writing to file: " + e.getMessage()); e.printStackTrace(); } return false; } // view student public void viewStudent() { try { // Read JSON file into a Map ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); // Deserialize JSON file into a Map TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); // Extract data from the "students" key List<Map<String, String>> students = (List<Map<String, String>>) data.get("students"); // Print the student data System.out.format("%-10s %-15s %-15s %-10s %-10s %-15s %-20s %-15s %-5s\n", "ID", "Name", "Date of birth", "Gender", "Address", "Phone number", "Email", "Major", "Year"); for (Map<String, String> student : students) { System.out.format("%-10s %-15s %-15s %-10s %-10s %-15s %-20s %-15s %-5s\n", student.get("id"), student.get("name"), student.get("day") + "/" + student.get("month") + "/" + student.get("year"), student.get("gender"), student.get("address"), student.get("phone"), student.get("email"), student.get("major"), student.get("years") + "\n"); } } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); e.printStackTrace(); } } // delete student public boolean deleteStudent(String studentId) { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); List<Map<String, String>> students = (List<Map<String, String>>) data.get("students"); // List<Map<String, String>> grades = (List<Map<String, String>>) data.get("grades"); grades.removeIf(grade -> studentId.equals(grade.get("studentId"))); data.put("grades", grades); List<Map<String, String>> classList = (List<Map<String, String>>) data.get("classList"); classList.removeIf(std -> studentId.equals(std.get("studentId"))); data.put("classList", classList); // students.removeIf(student -> studentId.equals(student.get("id"))); data.put("students", students); objectMapper.writeValue(file, data); return true; } catch (IOException e) { System.err.println("Error reading/writing file: " + e.getMessage()); e.printStackTrace(); } return false; } public boolean checkStudent(String studentId) { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); // Extract data from the "students" key List<Map<String, String>> students = (List<Map<String, String>>) data.get("students"); for (Map<String, String> student : students) { if (student.get("id").equals(studentId)) { return true; } } } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); e.printStackTrace(); } return false; } // Update information of student by id and save to file json.data public boolean updateStudent(String id, Student... students) { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); List<Map<String, String>> studentList = (List<Map<String, String>>) data.get("students"); for (Student student : students) { for (Map<String, String> studentMap : studentList) { if (id.equals(studentMap.get("id"))) { studentMap.put("name", student.getFullName()); studentMap.put("address", student.getAddress()); studentMap.put("gender", String.valueOf(student.getGender())); studentMap.put("day", String.valueOf(student.getDateOfBirth().getDay())); studentMap.put("month", String.valueOf(student.getDateOfBirth().getMonth())); studentMap.put("year", String.valueOf(student.getDateOfBirth().getYear())); studentMap.put("years", String.valueOf(student.getYear())); studentMap.put("major", student.getMajor()); studentMap.put("phone", student.getPhoneNumber()); studentMap.put("email", student.getEmail()); break; } } } // Update the "students" key in the data map data.put("students", studentList); objectMapper.writeValue(file, data); System.out.println("Student with ID " + id + " updated successfully."); return true; } catch (IOException e) { System.err.println("Error reading/writing file: " + e.getMessage()); e.printStackTrace(); } return false; } // ==================== Lecturer ==================== public boolean addLecturer(Lecturer lecturer) { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() { }; HashMap<String, Object> data = objectMapper.readValue(file, typeRef); List<Map<String, String>> lectures = (List<Map<String, String>>) data.get("lectures"); if (lectures == null) { lectures = new ArrayList<>(); } Map<String, String> newLecture = new HashMap<>(); newLecture.put("id", lecturer.getId()); newLecture.put("name", lecturer.getFullName()); newLecture.put("address", lecturer.getAddress()); newLecture.put("gender", String.valueOf(lecturer.getGender())); newLecture.put("day", String.valueOf(lecturer.getDateOfBirth().getDay())); newLecture.put("month", String.valueOf(lecturer.getDateOfBirth().getMonth())); newLecture.put("year", String.valueOf(lecturer.getDateOfBirth().getYear())); newLecture.put("phone", lecturer.getPhoneNumber()); newLecture.put("email", lecturer.getEmail()); newLecture.put("department", lecturer.getDepartment()); lectures.add(newLecture); data.put("lectures", lectures); objectMapper.writeValue(file, data); System.out.println("Lecture added successfully."); return true; } catch (IOException e) { System.err.println("Error reading/writing to file: " + e.getMessage()); e.printStackTrace(); } return false; } // view lecturer public void viewLecture() { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); List<Map<String, String>> lectures = (List<Map<String, String>>) data.get("lectures"); // Print the lecture data System.out.format("%-10s %-15s %-15s %-10s %-10s %-15s %-20s %-15s\n", "ID", "Full Name", "Date Of Birth", "Gender", "Address", "Phone Number", "Email", "Department"); for (Map<String, String> lecture : lectures) { System.out.format("%-10s %-15s %-15s %-10s %-10s %-15s %-20s %-15s\n", lecture.get("id"), lecture.get("name"), lecture.get("day") + "/" + lecture.get("month") + "/" + lecture.get("year"), lecture.get("gender"), lecture.get("address"), lecture.get("phone"), lecture.get("email"), lecture.get("department") + "\n"); } } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); e.printStackTrace(); } } public boolean updateLecturer(String id, Lecturer... lectures) { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); List<Map<String, String>> lectureList = (List<Map<String, String>>) data.get("lectures"); for (Lecturer lecture : lectures) { for (Map<String, String> lectureMap : lectureList) { if (id.equals(lectureMap.get("id"))) { lectureMap.put("name", lecture.getFullName()); lectureMap.put("address", lecture.getAddress()); lectureMap.put("gender", String.valueOf(lecture.getGender())); lectureMap.put("day", String.valueOf(lecture.getDateOfBirth().getDay())); lectureMap.put("month", String.valueOf(lecture.getDateOfBirth().getMonth())); lectureMap.put("year", String.valueOf(lecture.getDateOfBirth().getYear())); lectureMap.put("phone", lecture.getPhoneNumber()); lectureMap.put("email", lecture.getEmail()); lectureMap.put("department", lecture.getDepartment()); break; } } } // Update the "lectures" key in the data map data.put("lectures", lectureList); objectMapper.writeValue(file, data); System.out.println("Lecture with ID " + id + " updated successfully."); return true; } catch (IOException e) { System.err.println("Error reading/writing file: " + e.getMessage()); e.printStackTrace(); } return false; } // delete Lecture public boolean deleteLecture(String lectureId) { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); List<Map<String, String>> lectures = (List<Map<String, String>>) data.get("lectures"); // List<Map<String, String>> grades = (List<Map<String, String>>) data.get("grades"); grades.removeIf(grade -> lectureId.equals(grade.get("lecturerId"))); data.put("grades", grades); // lectures.removeIf(lecture -> lectureId.equals(lecture.get("id"))); data.put("lectures", lectures); objectMapper.writeValue(file, data); return true; } catch (IOException e) { System.err.println("Error reading/writing file: " + e.getMessage()); e.printStackTrace(); } return false; } public boolean checkLecture(String lectureId) { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); // Extract data from the "lectures" key List<Map<String, String>> lectures = (List<Map<String, String>>) data.get("lectures"); for (Map<String, String> lecture : lectures) { if (lecture.get("id").equals(lectureId)) { return true; } } } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); e.printStackTrace(); } return false; } // ==================== Course ==================== // add course public boolean addCourse(Course course) { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() { }; HashMap<String, Object> data = objectMapper.readValue(file, typeRef); List<Map<String, String>> courses = (List<Map<String, String>>) data.get("courses"); if (courses == null) { courses = new ArrayList<>(); } Map<String, String> newCourse = new HashMap<>(); newCourse.put("id", course.getId()); newCourse.put("name", course.getCourseName()); newCourse.put("description", course.getDescription()); newCourse.put("cost", Long.toString(course.getCost())); courses.add(newCourse); data.put("courses", courses); objectMapper.writeValue(file, data); System.out.println("Course added successfully."); return true; } catch (IOException e) { System.err.println("Error reading/writing to file: " + e.getMessage()); e.printStackTrace(); } return false; } // view course public void viewCourse() { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); List<Map<String, String>> courses = (List<Map<String, String>>) data.get("courses"); // Print the lecture data System.out.format("%-10s %-25s %-25s %-10s\n", "ID", "Course Name", "Description", "Cost"/* * , "Student", "Lecturer", "Start Date", "End Date", * "Status" */); for (Map<String, String> course : courses) { System.out.format("%-10s %-25s %-25s %-10s\n", course.get("id"), course.get("name"), course.get("description"), course.get("cost") /* * ,course.getStudent().getFullName(), course.getLecturer().getFullName(), * course.getStartDate().getDay() + "/" + course.getStartDate().getMonth() + "/" * + course.getStartDate().getYear(), * course.getEndDate().getDay() + "/" + course.getEndDate().getMonth() + "/" * + course.getEndDate().getYear(), * course.getStatus() */ + "\n"); } } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); e.printStackTrace(); } } // update course public boolean updateCourse(String id, Course... courses) { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); List<Map<String, String>> courseList = (List<Map<String, String>>) data.get("courses"); for (Course course : courses) { for (Map<String, String> courseMap : courseList) { if (id.equals(courseMap.get("id"))) { courseMap.put("name", course.getCourseName()); courseMap.put("description", course.getDescription()); courseMap.put("cost", Long.toString(course.getCost())); break; } } } // Update the "courses" key in the data map data.put("courses", courseList); objectMapper.writeValue(file, data); System.out.println("Course with ID " + id + " updated successfully."); return true; } catch (IOException e) { System.err.println("Error reading/writing file: " + e.getMessage()); e.printStackTrace(); } return false; } // delete course public boolean deleteCourse(String id) { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); List<Map<String, String>> courses = (List<Map<String, String>>) data.get("courses"); List<Map<String, String>> grades = (List<Map<String, String>>) data.get("grades"); grades.removeIf(grade -> id.equals(grade.get("courseId"))); courses.removeIf(course -> id.equals(course.get("id"))); data.put("grades", grades); data.put("courses", courses); objectMapper.writeValue(file, data); return true; } catch (IOException e) { System.err.println("Error reading/writing file: " + e.getMessage()); e.printStackTrace(); } return false; } // check course public boolean checkCourse(String courseId) { try { ObjectMapper objectMapper = new ObjectMapper(); File file = new File(filePath); TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() { }; Map<String, Object> data = objectMapper.readValue(file, typeRef); // Extract data from the "courses" key List<Map<String, String>> courses = (List<Map<String, String>>) data.get("courses"); for (Map<String, String> course : courses) { if (course.get("id").equals(courseId)) { return true; } } } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); e.printStackTrace(); } return false; } // ==================== Grade ==================== // add grade
public boolean addGrade(Student student, Lecturer lecturer, Course course, Grade grade) {
2
2023-11-23 18:42:19+00:00
8k
morihofi/acmeserver
src/main/java/de/morihofi/acmeserver/certificate/acme/api/Provisioner.java
[ { "identifier": "Main", "path": "src/main/java/de/morihofi/acmeserver/Main.java", "snippet": "public class Main {\n\n /**\n * Logger\n */\n public static final Logger log = LogManager.getLogger(Main.class);\n\n /**\n * `serverdata` directory as an absolute path\n */\n public ...
import de.morihofi.acmeserver.Main; import de.morihofi.acmeserver.config.CertificateExpiration; import de.morihofi.acmeserver.config.DomainNameRestrictionConfig; import de.morihofi.acmeserver.config.MetadataConfig; import de.morihofi.acmeserver.tools.certificate.cryptoops.CryptoStoreManager; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.security.*; import java.security.cert.X509Certificate;
5,069
package de.morihofi.acmeserver.certificate.acme.api; /** * Represents a Provisioner in a certificate management system. * This class encapsulates all the necessary configurations and behaviors associated with a provisioner. * It includes details such as the provisioner's name, ACME metadata configuration, certificate expiration settings, * domain name restrictions, wildcard allowance, and manages cryptographic store operations. * <p> * The Provisioner class is responsible for handling various aspects of certificate provisioning and management, * ensuring adherence to specified security and operational policies. */ public class Provisioner { /** * Get the ACME Server URL, reachable from other Hosts * * @return Full url (including HTTPS prefix) and port to this server */ public String getApiURL() {
package de.morihofi.acmeserver.certificate.acme.api; /** * Represents a Provisioner in a certificate management system. * This class encapsulates all the necessary configurations and behaviors associated with a provisioner. * It includes details such as the provisioner's name, ACME metadata configuration, certificate expiration settings, * domain name restrictions, wildcard allowance, and manages cryptographic store operations. * <p> * The Provisioner class is responsible for handling various aspects of certificate provisioning and management, * ensuring adherence to specified security and operational policies. */ public class Provisioner { /** * Get the ACME Server URL, reachable from other Hosts * * @return Full url (including HTTPS prefix) and port to this server */ public String getApiURL() {
return "https://" + Main.appConfig.getServer().getDnsName() + ":" + Main.appConfig.getServer().getPorts().getHttps() + "/" + provisionerName;
0
2023-11-22 15:54:36+00:00
8k
sakura-ryoko/afkplus
src/main/java/io/github/sakuraryoko/afkplus/AfkPlusMod.java
[ { "identifier": "CommandManager", "path": "src/main/java/io/github/sakuraryoko/afkplus/commands/CommandManager.java", "snippet": "public class CommandManager {\n public static void register() {\n if (CONFIG.afkPlusOptions.enableAfkCommand) {\n AfkCommand.register();\n }\n ...
import io.github.sakuraryoko.afkplus.commands.CommandManager; import io.github.sakuraryoko.afkplus.config.ConfigManager; import io.github.sakuraryoko.afkplus.events.ServerEvents; import io.github.sakuraryoko.afkplus.nodes.NodeManager; import io.github.sakuraryoko.afkplus.placeholders.PlaceholderManager; import io.github.sakuraryoko.afkplus.util.AfkPlusConflicts; import io.github.sakuraryoko.afkplus.util.AfkPlusInfo; import io.github.sakuraryoko.afkplus.util.AfkPlusLogger; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
5,894
package io.github.sakuraryoko.afkplus; public class AfkPlusMod { // Generic Mod init public static void init() { AfkPlusLogger.initLogger(); AfkPlusLogger.debug("Initializing Mod."); AfkPlusInfo.initModInfo(); AfkPlusInfo.displayModInfo(); if (AfkPlusInfo.isClient()) { AfkPlusLogger.info("MOD is running in a CLIENT Environment."); } if (!AfkPlusConflicts.checkMods()) AfkPlusLogger.warn("Mod conflicts check has FAILED."); AfkPlusLogger.debug("Config Initializing."); ConfigManager.initConfig(); AfkPlusLogger.debug("Loading Config."); ConfigManager.loadConfig(); AfkPlusLogger.debug("Initializing nodes.");
package io.github.sakuraryoko.afkplus; public class AfkPlusMod { // Generic Mod init public static void init() { AfkPlusLogger.initLogger(); AfkPlusLogger.debug("Initializing Mod."); AfkPlusInfo.initModInfo(); AfkPlusInfo.displayModInfo(); if (AfkPlusInfo.isClient()) { AfkPlusLogger.info("MOD is running in a CLIENT Environment."); } if (!AfkPlusConflicts.checkMods()) AfkPlusLogger.warn("Mod conflicts check has FAILED."); AfkPlusLogger.debug("Config Initializing."); ConfigManager.initConfig(); AfkPlusLogger.debug("Loading Config."); ConfigManager.loadConfig(); AfkPlusLogger.debug("Initializing nodes.");
NodeManager.initNodes();
3
2023-11-22 00:21:36+00:00
8k
AzFyXi/slotMachine
SlotMachine/src/main/java/Main.java
[ { "identifier": "User", "path": "SlotMachine/src/main/java/User/User.java", "snippet": "public class User {\n private String name;\n private int money;\n private int moneyBet;\n private int totalEarn;\n List<FreeAttempt> freeAttempts;\n\n //Constructor\n public User(String name, int...
import SlotMachine.*; import User.User; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import static SlotMachine.SlotMachine.*;
4,324
public class Main { public static void main(String[] args) { Collection<Symbol> symbols = getSymbolsCollection(); Collection<Column> columns = createColumnsCollection(3, symbols);
public class Main { public static void main(String[] args) { Collection<Symbol> symbols = getSymbolsCollection(); Collection<Column> columns = createColumnsCollection(3, symbols);
User mainUser = new User("First User", 250000);
0
2023-11-22 09:39:59+00:00
8k
clover/clover-tr34-host
src/test/java/com/clover/tr34/Tr34AscX9Test.java
[ { "identifier": "AscSampleTr34KeyStoreData", "path": "src/test/java/com/clover/tr34/samples/AscSampleTr34KeyStoreData.java", "snippet": "public class AscSampleTr34KeyStoreData extends Tr34KeyStoreData {\n\n public static final String SAMPLE_ROOT_CERT_PEM = \"-----BEGIN CERTIFICATE-----\\n\" +\n ...
import com.clover.tr34.samples.AscSampleTr34KeyStoreData; import com.clover.tr34.samples.AscSampleTr34Messages; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.DLSet; import org.bouncycastle.asn1.cms.CMSAttributes; import org.bouncycastle.asn1.pkcs.Attribute; import org.bouncycastle.cert.X509CRLHolder; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cms.CMSSignedData; import org.bouncycastle.util.Properties; import org.bouncycastle.util.Selector; import org.bouncycastle.util.encoders.Hex; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.security.MessageDigest; import java.security.PublicKey; import java.security.Signature; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.assertArrayEquals;
7,156
package com.clover.tr34; @Ignore("Enable after populating redacted ASC X9 TR-34 sample messages") public class Tr34AscX9Test { @Before public void setup() { // ASC X9 TR 34 sample certs sometimes include repeated extensions Properties.setThreadOverride("org.bouncycastle.x509.ignore_repeated_extensions", true); } @Test public void ascSampleRandomTokenParse() {
package com.clover.tr34; @Ignore("Enable after populating redacted ASC X9 TR-34 sample messages") public class Tr34AscX9Test { @Before public void setup() { // ASC X9 TR 34 sample certs sometimes include repeated extensions Properties.setThreadOverride("org.bouncycastle.x509.ignore_repeated_extensions", true); } @Test public void ascSampleRandomTokenParse() {
byte[] rand = Tr34RandomToken.create(AscSampleTr34Messages.RKRD_PEM).getRandomNumber().getOctets();
1
2023-11-22 06:30:40+00:00
8k
trgpnt/java-class-jacksonizer
src/main/java/com/aggregated/inline_tests/intricate_tests/existing_ctor_test/hierarchical_test/BaseClass.java
[ { "identifier": "StringUtils", "path": "src/main/java/com/aggregated/StringUtils.java", "snippet": "public class StringUtils {\n private static final Logger LOG = LoggerFactory.getLogger(StringUtils.class);\n\n private static final String OPEN_PAREN = \"(\";\n private static final String CLOSE_...
import com.aggregated.StringUtils; import com.aggregated.inline_tests.intricate_tests.existing_ctor_test.fuzzy_class.DummyObject; import com.aggregated.inline_tests.intricate_tests.existing_ctor_test.fuzzy_class.DummyObject01; import com.aggregated.inline_tests.intricate_tests.existing_ctor_test.fuzzy_class.DummyObject02; import com.aggregated.inline_tests.intricate_tests.existing_ctor_test.fuzzy_class.HelloIImAnotherDummy; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.SortedSet;
6,447
package com.aggregated.inline_tests.intricate_tests.existing_ctor_test.hierarchical_test; public abstract class BaseClass<T> { protected Integer x; protected String text; protected boolean y; protected Map<String, Map<String, Map<SortedSet<Integer>, String>>> amIScary; protected Map<String, Map<String, Map<SortedSet<Integer>, DummyObject02>>> amIScary02;
package com.aggregated.inline_tests.intricate_tests.existing_ctor_test.hierarchical_test; public abstract class BaseClass<T> { protected Integer x; protected String text; protected boolean y; protected Map<String, Map<String, Map<SortedSet<Integer>, String>>> amIScary; protected Map<String, Map<String, Map<SortedSet<Integer>, DummyObject02>>> amIScary02;
private DummyObject01 dummyObject01;
2
2023-11-23 10:59:01+00:00
8k
DewmithMihisara/car-rental-hibernate
src/main/java/lk/ijse/controller/RentFormController.java
[ { "identifier": "BOFactory", "path": "src/main/java/lk/ijse/bo/BOFactory.java", "snippet": "public class BOFactory {\n private static BOFactory factory;\n private BOFactory(){}\n public static BOFactory getInstance(){\n return factory == null ? new BOFactory() : factory;\n }\n publ...
import animatefx.animation.Shake; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.paint.Color; import javafx.scene.shape.Line; import javafx.util.Callback; import lk.ijse.bo.BOFactory; import lk.ijse.bo.custom.CarBO; import lk.ijse.bo.custom.CustomerBO; import lk.ijse.bo.custom.RentBO; import lk.ijse.controller.util.AlertTypes; import lk.ijse.controller.util.PopUpAlerts; import lk.ijse.controller.util.Validation; import lk.ijse.dto.CarDto; import lk.ijse.dto.CustomerDto; import lk.ijse.dto.RentDto; import lk.ijse.dto.tm.RentTM; import java.time.LocalDate; import java.util.List;
4,248
stDt, endDt, Double.parseDouble(advance), Double.parseDouble(depo), cus, car.getCatId(), car.getNumber(), car.getRate(), car.getRate()*(stDt.toEpochDay()-endDt.toEpochDay()), true ))){ PopUpAlerts.popUps(AlertTypes.CONFORMATION, "Rent", "CRent Placed Successfully!"); initUi(); setNull(); }else { PopUpAlerts.popUps(AlertTypes.ERROR, "Rent", "Rent Not Placed!"); setNull(); } } void setNull(){ id=null; advance=null; depo=null; cus=null; carCmb=null; stDt=null; endDt=null; } @FXML void stDateDatePickerOnAction(ActionEvent event) { endDateDatePicker.setDisable(false); setEndDate(); } @FXML void initialize(){ initUi(); setStartDate(); setValueFactory(); } private void setStartDate() { Callback<DatePicker, DateCell> callB = new Callback<DatePicker, DateCell>() { @Override public DateCell call(final DatePicker param) { return new DateCell() { @Override public void updateItem(LocalDate item, boolean empty) { super.updateItem(item, empty); LocalDate today = LocalDate.now(); setDisable(empty || item.compareTo(today) < 0); } }; } }; stDateDatePicker.setDayCellFactory(callB); } private void setEndDate() { LocalDate startDate = stDateDatePicker.getValue(); if (startDate != null) { endDateDatePicker.setDayCellFactory(picker -> new DateCell() { @Override public void updateItem(LocalDate item, boolean empty) { super.updateItem(item, empty); setDisable(item.isBefore(startDate) || item.isAfter(startDate.plusDays(29))); } }); } } private void loadCarIds() { ObservableList<String> categories = FXCollections.observableArrayList(); categories.addAll(carBO.getIds()); carIdCmb.setItems(categories); } private void loadCusIds() { ObservableList<String> categories = FXCollections.observableArrayList(); categories.addAll(customerBO.getIds()); CusIdCmb.setItems(categories); } private void initUi() { stDateDatePicker.getEditor().clear(); endDateDatePicker.getEditor().clear(); AdvancedTxt.setText(""); carNoTxt1.setText(""); cusNameLbl.setText(""); availableLbl.setText(""); aligibleLbl.setText(""); loadCusIds(); loadCarIds(); carIdCmb.getSelectionModel().clearSelection(); CusIdCmb.getSelectionModel().clearSelection(); cusNameLbl.setVisible(false); availableLbl.setVisible(false); rentBtn.setDisable(true); aligibleLbl.setVisible(false); carNoTxt1.setDisable(true); endDateDatePicker.setDisable(true); addBtn.setDisable(false); clearTable(); } private void clearTable() { try { ObservableList<RentTM> dataList = newRentTbl.getItems(); dataList.clear(); } catch (Exception e) { throw e; } } private boolean validation() { stDate=false; endDate=false; cusId=false; carId=false; advanced=false;
package lk.ijse.controller; public class RentFormController { @FXML private TextField AdvancedTxt; @FXML private ComboBox<String> CusIdCmb; @FXML private Line DepoLine; @FXML private Button addBtn; @FXML private TableColumn<?, ?> advancedClm; @FXML private Line advancedLine; @FXML private Label aligibleLbl; @FXML private Label availableLbl; @FXML private TableColumn<?, ?> balanceClm; @FXML private ComboBox<String> carIdCmb; @FXML private TableColumn<?, ?> carNoClm; @FXML private TextField carNoTxt1; @FXML private Label cusNameLbl; @FXML private TableColumn<?, ?> cusNameClm; @FXML private TableColumn<?, ?> depoClm; @FXML private DatePicker endDateDatePicker; @FXML private TableView<RentTM> newRentTbl; @FXML private TableColumn<?, ?> nosDaysClm; @FXML private TableColumn<?, ?> rateClm; @FXML private Button rentBtn; @FXML private DatePicker stDateDatePicker; @FXML private TableColumn<?, ?> ttlClm; private final CarBO carBO = BOFactory.getInstance().getBO(BOFactory.BOTypes.CAR); private final CustomerBO customerBO = BOFactory.getInstance().getBO(BOFactory.BOTypes.CUSTOMER); private final RentBO rentBO = BOFactory.getInstance().getBO(BOFactory.BOTypes.RENT); boolean stDate, endDate, cusId, carId, advanced; String id, advance, depo, cus, carCmb; LocalDate stDt, endDt; { id=null; advance=null; depo=null; cus=null; carCmb=null; stDt=null; endDt=null; } @FXML void AdvancedTxtOnAction(ActionEvent event) { addBtn.requestFocus(); } @FXML void CusIdCmbOnAction(ActionEvent event) { CustomerDto customer=customerBO.getCustomer(CusIdCmb.getSelectionModel().getSelectedItem()); if (customer!=null){ cusNameLbl.setVisible(true); cusNameLbl.setText(customer.getFirstName()+" "+customer.getLastName()); if (customer.getToReturn()==null){ aligibleLbl.setVisible(true); aligibleLbl.setText("Yes"); }else { aligibleLbl.setVisible(true); aligibleLbl.setText("No"); } } } @FXML void addNewBtnOnAction(ActionEvent event) { if (validation()){ if (isCanCus()){ if (isCanCar()){ if(advanceMatch()){ CarDto car=carBO.getCar(carIdCmb.getSelectionModel().getSelectedItem()); CustomerDto customer=customerBO.getCustomer(CusIdCmb.getSelectionModel().getSelectedItem()); long nosDates=endDateDatePicker.getValue().toEpochDay()-stDateDatePicker.getValue().toEpochDay(); double total=car.getRate()*nosDates; id=rentBO.getNewCarId(); stDt=stDateDatePicker.getValue(); endDt=endDateDatePicker.getValue(); advance=AdvancedTxt.getText(); depo = carNoTxt1.getText(); cus = CusIdCmb.getSelectionModel().getSelectedItem(); carCmb = carIdCmb.getSelectionModel().getSelectedItem(); ObservableList<RentTM>observableList= FXCollections.observableArrayList(); observableList.add(new RentTM( id, customer.getFirstName() + " " + customer.getLastName(), car.getNumber(), String.valueOf(car.getRate()), String.valueOf(nosDates), AdvancedTxt.getText(), carNoTxt1.getText(), String.valueOf(total), String .valueOf(total-Double.parseDouble(AdvancedTxt.getText())) )); newRentTbl.setItems(observableList); // initUi(); if (newRentTbl.getItems() != null && !newRentTbl.getItems().isEmpty()) { rentBtn.setDisable(false); addBtn.setDisable(true); } } } } } } @FXML void carIdCmbOnAction(ActionEvent event) { CarDto car=carBO.getCar(carIdCmb.getSelectionModel().getSelectedItem()); if (car!=null){ if (car.getIsRentable()){ availableLbl.setVisible(true); availableLbl.setText("Yes"); rentBtn.setDisable(false); carNoTxt1.setText(car.getDepositAmount().toString()); }else { availableLbl.setVisible(true); availableLbl.setText("No"); rentBtn.setDisable(true); } } } @FXML void endDateDatePickerOnAction(ActionEvent event) { AdvancedTxt.requestFocus(); } @FXML void rentBtnOnAction(ActionEvent event) { CarDto car=carBO.getCar(carCmb); if (rentBO.placeRent(new RentDto( id, LocalDate.now(), stDt, endDt, Double.parseDouble(advance), Double.parseDouble(depo), cus, car.getCatId(), car.getNumber(), car.getRate(), car.getRate()*(stDt.toEpochDay()-endDt.toEpochDay()), true ))){ PopUpAlerts.popUps(AlertTypes.CONFORMATION, "Rent", "CRent Placed Successfully!"); initUi(); setNull(); }else { PopUpAlerts.popUps(AlertTypes.ERROR, "Rent", "Rent Not Placed!"); setNull(); } } void setNull(){ id=null; advance=null; depo=null; cus=null; carCmb=null; stDt=null; endDt=null; } @FXML void stDateDatePickerOnAction(ActionEvent event) { endDateDatePicker.setDisable(false); setEndDate(); } @FXML void initialize(){ initUi(); setStartDate(); setValueFactory(); } private void setStartDate() { Callback<DatePicker, DateCell> callB = new Callback<DatePicker, DateCell>() { @Override public DateCell call(final DatePicker param) { return new DateCell() { @Override public void updateItem(LocalDate item, boolean empty) { super.updateItem(item, empty); LocalDate today = LocalDate.now(); setDisable(empty || item.compareTo(today) < 0); } }; } }; stDateDatePicker.setDayCellFactory(callB); } private void setEndDate() { LocalDate startDate = stDateDatePicker.getValue(); if (startDate != null) { endDateDatePicker.setDayCellFactory(picker -> new DateCell() { @Override public void updateItem(LocalDate item, boolean empty) { super.updateItem(item, empty); setDisable(item.isBefore(startDate) || item.isAfter(startDate.plusDays(29))); } }); } } private void loadCarIds() { ObservableList<String> categories = FXCollections.observableArrayList(); categories.addAll(carBO.getIds()); carIdCmb.setItems(categories); } private void loadCusIds() { ObservableList<String> categories = FXCollections.observableArrayList(); categories.addAll(customerBO.getIds()); CusIdCmb.setItems(categories); } private void initUi() { stDateDatePicker.getEditor().clear(); endDateDatePicker.getEditor().clear(); AdvancedTxt.setText(""); carNoTxt1.setText(""); cusNameLbl.setText(""); availableLbl.setText(""); aligibleLbl.setText(""); loadCusIds(); loadCarIds(); carIdCmb.getSelectionModel().clearSelection(); CusIdCmb.getSelectionModel().clearSelection(); cusNameLbl.setVisible(false); availableLbl.setVisible(false); rentBtn.setDisable(true); aligibleLbl.setVisible(false); carNoTxt1.setDisable(true); endDateDatePicker.setDisable(true); addBtn.setDisable(false); clearTable(); } private void clearTable() { try { ObservableList<RentTM> dataList = newRentTbl.getItems(); dataList.clear(); } catch (Exception e) { throw e; } } private boolean validation() { stDate=false; endDate=false; cusId=false; carId=false; advanced=false;
stDate= Validation.dateValidation(stDateDatePicker);
6
2023-11-27 17:28:48+00:00
8k