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 |
---|---|---|---|---|---|---|---|---|---|---|
EnigmaGuest/fnk-server | service-core/service-core-system/src/main/java/fun/isite/service/core/system/mapper/UserRoleMapper.java | [
{
"identifier": "SystemMenu",
"path": "service-core/service-core-system/src/main/java/fun/isite/service/core/system/entity/SystemMenu.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@TableName(\"system_menu\")\n@Schema(name = \"SystemMenu\", description = \"系统菜单\")\npublic class SystemMenu extends BaseEntity<SystemMenu> {\n\n /**\n * 上级ID\n */\n @Schema(description=\"上级ID\")\n private String rootId;\n\n /**\n * 菜单名称\n */\n @Schema(description=\"菜单名称\")\n private String name;\n\n /**\n * 路由key全局唯一\n */\n @Schema(description=\"路由key全局唯一\")\n private String routeKey;\n\n /**\n * 显示顺序\n */\n @Schema(description=\"显示顺序\")\n private Integer orderSort;\n\n /**\n * 是否为网页\n */\n @Schema(description=\"是否为网页\")\n private Boolean isIframe;\n\n /**\n * 请求路径\n */\n @Schema(description=\"请求路径\")\n private String path;\n\n /**\n * icones\n */\n @Schema(description=\"icones\")\n private String icon;\n\n /**\n * 本地icon\n */\n @Schema(description=\"本地icon\")\n private String localIcon;\n\n /**\n * 是否显示\n */\n @Schema(description=\"是否显示\")\n private Boolean visible;\n\n /**\n * 权限标识\n */\n @Schema(description=\"权限标识\")\n private String permission;\n\n /**\n * 菜单类型(table目录 menu菜单 button按钮)\n */\n @Schema(description=\"菜单类型(table目录 menu菜单 button按钮)\")\n private MenuTypeEnum type;\n\n /**\n * 备注\n */\n @Schema(description=\"备注\")\n private String remark;\n\n\n}"
},
{
"identifier": "UserRole",
"path": "service-core/service-core-system/src/main/java/fun/isite/service/core/system/entity/UserRole.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@TableName(\"user_role\")\n@Schema(name = \"UserRole\", description = \"用户和角色关联\")\npublic class UserRole extends BaseEntity<UserRole> {\n\n /**\n * 系统用户ID\n */\n @Schema(description=\"系统用户ID\")\n private String userId;\n\n /**\n * 角色ID\n */\n @Schema(description=\"角色ID\")\n private String roleId;\n\n\n}"
}
] | import fun.isite.service.core.system.entity.SystemMenu;
import fun.isite.service.core.system.entity.UserRole;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List; | 852 | package fun.isite.service.core.system.mapper;
/**
* <p>
* 用户和角色关联 Mapper 接口
* </p>
*
* @author Enigma
* @since 2023-12-18
*/
@Mapper
public interface UserRoleMapper extends BaseMapper<UserRole> {
@Delete("delete from user_role where user_id = #{userId}")
int deleteByUserId(String userId);
@Select("select role_id from user_role where user_id = #{userId}")
List<String> queryRoleIdsByUserId(String userId);
| package fun.isite.service.core.system.mapper;
/**
* <p>
* 用户和角色关联 Mapper 接口
* </p>
*
* @author Enigma
* @since 2023-12-18
*/
@Mapper
public interface UserRoleMapper extends BaseMapper<UserRole> {
@Delete("delete from user_role where user_id = #{userId}")
int deleteByUserId(String userId);
@Select("select role_id from user_role where user_id = #{userId}")
List<String> queryRoleIdsByUserId(String userId);
| List<SystemMenu> queryMenusByUserId(String userId); | 0 | 2023-12-26 01:55:01+00:00 | 2k |
yutianqaq/BypassAV-Online | BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/service/impl/CompileServiceImpl.java | [
{
"identifier": "CompilationResult",
"path": "BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/controller/domain/CompilationResult.java",
"snippet": "@Getter\n@Setter\npublic class CompilationResult {\n private byte[] fileBytes;\n private String fileName;\n\n public CompilationResult(byte[] fileBytes, String fileName) {\n this.fileBytes = fileBytes;\n this.fileName = fileName;\n }\n\n\n}"
},
{
"identifier": "CompilationResponseDTO",
"path": "BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/dto/CompilationResponseDTO.java",
"snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@ToString\npublic class CompilationResponseDTO {\n private String downloadLink;\n}"
},
{
"identifier": "CompileRequestDTO",
"path": "BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/dto/CompileRequestDTO.java",
"snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@ToString\npublic class CompileRequestDTO {\n private String code;\n private String templateName;\n\n}"
},
{
"identifier": "CompileService",
"path": "BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/service/CompileService.java",
"snippet": "public interface CompileService {\n CompilationResponseDTO compileCodeC(CompileRequestDTO request) throws IOException;\n CompilationResponseDTO compileCodeNIM(CompileRequestDTO request) throws IOException;\n}"
},
{
"identifier": "CodeCompilationUtils",
"path": "BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/utils/CodeCompilationUtils.java",
"snippet": "@Component\npublic class CodeCompilationUtils {\n\n private static ApplicationProperties applicationProperties;\n\n @Autowired\n public void setApplicationProperties(ApplicationProperties applicationProperties) {\n CodeCompilationUtils.applicationProperties = applicationProperties;\n }\n public static CompilationResult compileCCode(String code, String templateFileName) throws IOException {\n\n String processedCode = TextFileProcessor.processTemplate(code, templateFileName); // 处理模板\n // 将处理后的代码保存到临时文件\n // 生成临时文件名\n String tempFileName = UUID.randomUUID().toString() + \".c\";\n String compiledFileName = UUID.randomUUID().toString() + \".exe\";\n File tempFile = new File(tempFileName);\n\n // 保存处理后的代码到临时文件\n try (FileWriter writer = new FileWriter(tempFile)) {\n writer.write(processedCode);\n }\n\n // 编译代码为EXE文件\n ProcessBuilder processBuilder = new ProcessBuilder(applicationProperties.getCompilerC(), tempFile.getAbsolutePath(), \"-o\", compiledFileName);\n Process process = processBuilder.start();\n try {\n process.waitFor();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n\n // 读取编译后的EXE文件\n File outputFile = new File(compiledFileName);\n byte[] fileBytes = Files.readAllBytes(outputFile.toPath());\n\n // 删除临时文件和输出文件\n tempFile.delete();\n outputFile.delete();\n\n return new CompilationResult(fileBytes, compiledFileName);\n }\n public static CompilationResult compileNimCode(String code, String templateFileName) throws IOException {\n\n String processedCode = TextFileProcessor.processTemplate(code, templateFileName); // 处理模板\n\n // 将处理后的代码保存到临时文件\n // 生成临时文件名\n String randomLetters = TextFileProcessor.generateRandomFileName();\n\n String uniqueId = UUID.randomUUID().toString().replace(\"-\", \"\");\n String tempFileName = randomLetters + uniqueId + \".nim\";\n String compiledFileName = randomLetters + uniqueId + \".exe\";\n File tempFile = new File(tempFileName);\n\n // 保存处理后的代码到临时文件\n try (FileWriter writer = new FileWriter(tempFile)) {\n writer.write(processedCode);\n }\n System.out.println(compiledFileName);\n System.out.println(tempFile.getAbsolutePath());\n\n // nim c -d=release --cc:gcc --app=gui --cpu=amd64 -o:x1.exe x1Ldr.nim\n try {\n ProcessBuilder processBuilder = new ProcessBuilder(applicationProperties.getCompilerNIM(), \"c\", \"-d=release\", \"-d=mingw\", \"--app=gui\", \"-d:strip\", \"--opt:size\",\n \"--cpu=amd64\", \"-o:\" + compiledFileName, tempFile.getAbsolutePath());\n List<String> command = processBuilder.command();\n\n Process process = processBuilder.start();\n\n // 等待进程执行完成\n int exitCode = process.waitFor();\n\n } catch (IOException e) {\n // 处理进程启动的IO异常\n e.printStackTrace();\n } catch (InterruptedException e) {\n // 处理进程等待过程中的中断异常\n e.printStackTrace();\n }\n\n // 读取编译后的EXE文件\n File outputFile = new File(compiledFileName);\n byte[] fileBytes = Files.readAllBytes(outputFile.toPath());\n\n // 删除临时文件和输出文件\n tempFile.delete();\n outputFile.delete();\n\n return new CompilationResult(fileBytes, compiledFileName);\n }\n\n}"
},
{
"identifier": "saveFile",
"path": "BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/utils/FileProcessor.java",
"snippet": "public static String saveFile(byte[] fileBytes, String fileName) throws IOException {\n File storageDirectory = new File(applicationProperties.getStorageDirector());\n if (!storageDirectory.exists()) {\n storageDirectory.mkdirs();\n }\n\n Path filePath = storageDirectory.toPath().resolve(fileName);\n\n Files.write(filePath, fileBytes);\n String modifiedFileName = fileName.substring(0, fileName.length() - 4);\n String filename = storageDirectory + File.separator + modifiedFileName + \".zip\";\n ZipFile zipFile = new ZipFile( filename, \"yutian\".toCharArray());\n\n ZipParameters zipParameters = new ZipParameters();\n zipParameters.setEncryptFiles(true);\n\n zipParameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD);\n\n zipFile.addFile(filePath.toFile(), zipParameters);\n Files.deleteIfExists(filePath);\n\n return modifiedFileName + \".zip\";\n}"
}
] | import com.yutian4090.bypass.controller.domain.CompilationResult;
import com.yutian4090.bypass.dto.CompilationResponseDTO;
import com.yutian4090.bypass.dto.CompileRequestDTO;
import com.yutian4090.bypass.service.CompileService;
import com.yutian4090.bypass.utils.CodeCompilationUtils;
import org.springframework.stereotype.Service;
import java.io.IOException;
import static com.yutian4090.bypass.utils.FileProcessor.saveFile; | 1,588 | package com.yutian4090.bypass.service.impl;
@Service
public class CompileServiceImpl implements CompileService {
@Override | package com.yutian4090.bypass.service.impl;
@Service
public class CompileServiceImpl implements CompileService {
@Override | public CompilationResponseDTO compileCodeC(CompileRequestDTO request) throws IOException { | 1 | 2023-12-28 06:22:12+00:00 | 2k |
codingmiao/hppt | ss/src/main/java/org/wowtools/hppt/ss/StartSs.java | [
{
"identifier": "Constant",
"path": "common/src/main/java/org/wowtools/hppt/common/util/Constant.java",
"snippet": "public class Constant {\n public static final ObjectMapper jsonObjectMapper = new ObjectMapper();\n\n public static final ObjectMapper ymlMapper = new ObjectMapper(new YAMLFactory());\n\n public static final String sessionIdJoinFlag = \",\";\n\n //ss端执行的命令代码\n public static final class SsCommands {\n //关闭Session 0逗号连接需要的SessionId\n public static final char CloseSession = '0';\n\n //保持Session活跃 1逗号连接需要的SessionId\n public static final char ActiveSession = '1';\n }\n\n //Sc端执行的命令代码\n public static final class ScCommands {\n //检查客户端的Session是否还活跃 0逗号连接需要的SessionId\n public static final char CheckSessionActive = '0';\n\n //关闭客户端连接 1逗号连接需要的SessionId\n public static final char CloseSession = '1';\n }\n\n //Cs端执行的命令代码\n public static final class CsCommands {\n //检查客户端的Session是否还活跃 0逗号连接需要的SessionId\n public static final char CheckSessionActive = '0';\n\n //关闭客户端连接 1逗号连接需要的SessionId\n public static final char CloseSession = '1';\n }\n\n //cc端执行的命令代码\n public static final class CcCommands {\n //关闭Session 0逗号连接需要的SessionId\n public static final char CloseSession = '0';\n\n //保持Session活跃 1逗号连接需要的SessionId\n public static final char ActiveSession = '1';\n\n //新建会话 2sessionId host port\n public static final char CreateSession = '2';\n }\n\n}"
},
{
"identifier": "SsConfig",
"path": "ss/src/main/java/org/wowtools/hppt/ss/pojo/SsConfig.java",
"snippet": "public class SsConfig {\n public int port;\n\n /**\n * 超过sessionTimeout,给客户端发送存活确认命令,若下一个sessionTimeout内未收到确认,则强制关闭服务\n */\n public long sessionTimeout = 120000;\n\n /**\n * 接收到客户端/真实端口的数据时,数据被暂存在一个队列里,队列满后强制关闭会话\n */\n public int messageQueueSize = 2048;\n\n /**\n * 上传/下载文件用的目录\n */\n public String fileDir;\n\n /**\n * 是否启用压缩,默认启用\n */\n public boolean enableCompress = true;\n\n /**\n * 是否启用内容加密,默认启用\n */\n public boolean enableEncrypt = true;\n\n /**\n * 允许的客户端\n */\n public ArrayList<String> clientIds;\n}"
}
] | import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.core.config.Configurator;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.wowtools.common.utils.ResourcesReader;
import org.wowtools.hppt.common.util.Constant;
import org.wowtools.hppt.ss.pojo.SsConfig;
import org.wowtools.hppt.ss.servlet.*;
import java.io.File; | 916 | package org.wowtools.hppt.ss;
/**
* @author liuyu
* @date 2023/11/25
*/
@Slf4j
public class StartSs { | package org.wowtools.hppt.ss;
/**
* @author liuyu
* @date 2023/11/25
*/
@Slf4j
public class StartSs { | public static final SsConfig config; | 1 | 2023-12-22 14:14:27+00:00 | 2k |
3arthqu4ke/phobot | src/main/java/me/earth/phobot/pathfinder/Path.java | [
{
"identifier": "CanBeInvalidated",
"path": "src/main/java/me/earth/phobot/invalidation/CanBeInvalidated.java",
"snippet": "public interface CanBeInvalidated {\n boolean isValid();\n\n void invalidate();\n\n}"
},
{
"identifier": "PathfindingNode",
"path": "src/main/java/me/earth/phobot/pathfinder/algorithm/PathfindingNode.java",
"snippet": "public interface PathfindingNode<N extends PathfindingNode<N>> extends Comparable<N> {\n N[] getAdjacent();\n\n double getRenderX();\n\n double getRenderY();\n\n double getRenderZ();\n\n int getChunkX();\n\n int getChunkZ();\n\n double distanceSq(N node);\n\n default double distance(N node) {\n return Math.sqrt(distanceSq(node));\n }\n\n default boolean isValid() {\n return true;\n }\n\n}"
},
{
"identifier": "MeshNode",
"path": "src/main/java/me/earth/phobot/pathfinder/mesh/MeshNode.java",
"snippet": "@Getter\n@Setter\npublic class MeshNode extends Abstract3iNode<MeshNode> implements CanBeInvalidated {\n public static final int[] OPPOSITE_INDEX = {1, 0, 3, 2};\n public static final Vec3i[] OFFSETS = new Vec3i[] {\n new Vec3i(1, 0, 0),\n new Vec3i(-1, 0, 0),\n new Vec3i(0, 0, 1),\n new Vec3i(0, 0, -1)\n };\n\n // TODO: also track how \"safe\" (how many blocks around) a node are, and prefer strafing between bedrock blocks before strafing above\n\n private final MeshNode[] adjacent = new MeshNode[4];\n private final ChunkWorker chunk;\n private final int version;\n\n private boolean headSpace = false;\n private boolean valid = true;\n\n public MeshNode(ChunkWorker chunk, int x, int y, int z) {\n this(chunk, chunk.getVersion(), x, y, z);\n }\n\n public MeshNode(ChunkWorker chunk, int version, int x, int y, int z) {\n super(x, y, z);\n this.chunk = chunk;\n this.version = version;\n }\n\n @Override\n public boolean isValid() {\n return valid && getChunk().getVersion() == this.getVersion();\n }\n\n @Override\n public void invalidate() {\n setValid(false);\n }\n\n}"
}
] | import lombok.Data;
import me.earth.phobot.invalidation.CanBeInvalidated;
import me.earth.phobot.pathfinder.algorithm.PathfindingNode;
import me.earth.phobot.pathfinder.mesh.MeshNode;
import net.minecraft.core.BlockPos;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable;
import java.util.List;
import java.util.Set;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet; | 719 | package me.earth.phobot.pathfinder;
@Data
public class Path<T extends PathfindingNode<T>> implements CanBeInvalidated { | package me.earth.phobot.pathfinder;
@Data
public class Path<T extends PathfindingNode<T>> implements CanBeInvalidated { | private static final Path<?> INVALID = new Path<>(Vec3.ZERO, Vec3.ZERO, BlockPos.ZERO, BlockPos.ZERO, emptySet(), emptyList(), MeshNode.class) { | 2 | 2023-12-22 14:32:16+00:00 | 2k |
Video-Hub-Org/video-hub | backend/src/main/java/org/videohub/service/RedBookService.java | [
{
"identifier": "VideoHubConstants",
"path": "backend/src/main/java/org/videohub/constant/VideoHubConstants.java",
"snippet": "public class VideoHubConstants {\n // 文件下载路径,默认为项目同级目录下\n public static final String VIDEOHUB_FILEPATH = \"videoHubDownload/\";\n\n public static final String USER_AGENT = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\";\n\n // 小红书笔记匹配正则\n public static final String REDBOOK_NODE_REGEX_01 = \"http://xhslink\\\\.com/\\\\w+\";\n public static final String REDBOOK_NODE_REGEX_02 = \"https://www.xiaohongshu.com/explore/([a-zA-Z0-9]+)\";\n public static final String REDBOOK_NODE_REGEX_03 = \"https://www.xiaohongshu.com/discovery/item/([a-zA-Z0-9]+)\";\n\n // 小红书用户匹配正则\n public static final String REDBOOK_USER_REGEX_01 = \"https://www.xiaohongshu.com/user/profile/([a-zA-Z0-9]+)\";\n\n public static final String REDBOOK_NODE_REGEX_EXPLORE = \"https://www.xiaohongshu.com/explore/\";\n\n public static final String IMAGE_PREFIX = \"https://sns-img-qc.xhscdn.com/\";\n public static final String VIDEO_PREFIX = \"http://sns-video-qc.xhscdn.com/\";\n\n}"
},
{
"identifier": "VideoHubUtils",
"path": "backend/src/main/java/org/videohub/utils/VideoHubUtils.java",
"snippet": "@Slf4j\npublic final class VideoHubUtils {\n // 以#开头的行将被忽略,如果你不想下载或某些链接已被下载过,可以在开头添加#\n public static String readLinkFromFile(String fileName) {\n try {\n Path filePath = Paths.get(ClassLoader.getSystemResource(fileName).toURI());\n List<String> lines = Files.readAllLines(filePath);\n\n // 过滤以\"#\"开头的行,然后将每行用空格分隔并拼接成一个字符串\n return lines.stream().filter(line -> !line.trim().startsWith(\"#\")).collect(Collectors.joining(\" \"));\n } catch (IOException | URISyntaxException e) {\n log.error(\"读取{}文件失败\", fileName, e);\n return \"\"; // 处理文件读取失败的情况\n }\n }\n\n public static List<String> matchURL(String text, String... regexArray) {\n List<String> matchedValues = new ArrayList<>();\n\n for (String regex : regexArray) {\n // 使用正则表达式匹配\n Pattern pattern = Pattern.compile(regex);\n Matcher matcher = pattern.matcher(text);\n\n // 查找匹配项\n while (matcher.find()) {\n String match = matcher.group();\n matchedValues.add(match);\n log.info(\"匹配到URL:{}\", match);\n }\n }\n\n return matchedValues;\n }\n\n public static void mkdir4download(String folderPath) throws IOException {\n try {\n // 获取项目运行的上级目录\n Path parentDirectory = Paths.get(\"..\").toAbsolutePath().normalize();\n // 创建文件夹路径\n Path fullPath = parentDirectory.resolve(folderPath);\n // 创建文件夹\n Files.createDirectories(fullPath);\n log.info(\"文件夹创建成功 ---\");\n } catch (FileAlreadyExistsException e) {\n log.info(\"文件夹已经存在 ---\");\n } catch (IOException e) {\n log.error(\"创建文件夹失败\", e);\n throw e;\n }\n }\n}"
}
] | import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.videohub.constant.VideoHubConstants;
import org.videohub.utils.VideoHubUtils;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 1,583 | package org.videohub.service;
/**
* 小红书笔记下载实现类
*
* @author @fmz200
* @date 2023-12-18
*/
@Slf4j
public class RedBookService {
// 下载视频超时时间,默认60秒
@Value("${videoDownloadTimeout}")
private static int videoDownloadTimeout;
// 下载文件的保存位置
@Value("${fileSavePath}")
private static String fileSavePath;
private static final ExecutorService executorService = Executors.newCachedThreadPool();
public static void downloadNodeBatch(String url) {
try {
if (videoDownloadTimeout < 1)
videoDownloadTimeout = 180;
if (!StringUtils.hasText(fileSavePath))
fileSavePath = VideoHubConstants.VIDEOHUB_FILEPATH;
Document doc = Jsoup.connect(url).userAgent(VideoHubConstants.USER_AGENT).get();
String match = "window.__INITIAL_STATE__";
for (Element script : doc.select("script")) {
String scriptData = script.data();
if (!scriptData.contains(match)) {
continue;
}
String jsonString = scriptData.substring(scriptData.indexOf("=") + 1);
log.info("发现笔记信息~~~~");
JSONObject jsonObject = JSON.parseObject(jsonString);
JSONObject object = jsonObject.getJSONObject("note");
String firstNoteId = object.getString("firstNoteId");
JSONObject note = object.getJSONObject("noteDetailMap").getJSONObject(firstNoteId).getJSONObject("note");
String ipLocation = Optional.ofNullable(note.getString("ipLocation")).orElse("偶买噶,居然不知道TA在哪");
JSONObject user = note.getJSONObject("user");
String userId = user.getString("userId");
String nickname = user.getString("nickname");
// String avatar = user.getString("avatar");
log.info("用户信息-->用户ID:{},昵称:{},IP位置:{}", userId, nickname, ipLocation);
String noteId = note.getString("noteId");
String title = note.getString("title");
log.info("笔记信息-->笔记ID:{},标题:{}", noteId, title);
// 创建文件夹
String folder = fileSavePath + "redBook/" + userId + "/" + noteId; | package org.videohub.service;
/**
* 小红书笔记下载实现类
*
* @author @fmz200
* @date 2023-12-18
*/
@Slf4j
public class RedBookService {
// 下载视频超时时间,默认60秒
@Value("${videoDownloadTimeout}")
private static int videoDownloadTimeout;
// 下载文件的保存位置
@Value("${fileSavePath}")
private static String fileSavePath;
private static final ExecutorService executorService = Executors.newCachedThreadPool();
public static void downloadNodeBatch(String url) {
try {
if (videoDownloadTimeout < 1)
videoDownloadTimeout = 180;
if (!StringUtils.hasText(fileSavePath))
fileSavePath = VideoHubConstants.VIDEOHUB_FILEPATH;
Document doc = Jsoup.connect(url).userAgent(VideoHubConstants.USER_AGENT).get();
String match = "window.__INITIAL_STATE__";
for (Element script : doc.select("script")) {
String scriptData = script.data();
if (!scriptData.contains(match)) {
continue;
}
String jsonString = scriptData.substring(scriptData.indexOf("=") + 1);
log.info("发现笔记信息~~~~");
JSONObject jsonObject = JSON.parseObject(jsonString);
JSONObject object = jsonObject.getJSONObject("note");
String firstNoteId = object.getString("firstNoteId");
JSONObject note = object.getJSONObject("noteDetailMap").getJSONObject(firstNoteId).getJSONObject("note");
String ipLocation = Optional.ofNullable(note.getString("ipLocation")).orElse("偶买噶,居然不知道TA在哪");
JSONObject user = note.getJSONObject("user");
String userId = user.getString("userId");
String nickname = user.getString("nickname");
// String avatar = user.getString("avatar");
log.info("用户信息-->用户ID:{},昵称:{},IP位置:{}", userId, nickname, ipLocation);
String noteId = note.getString("noteId");
String title = note.getString("title");
log.info("笔记信息-->笔记ID:{},标题:{}", noteId, title);
// 创建文件夹
String folder = fileSavePath + "redBook/" + userId + "/" + noteId; | VideoHubUtils.mkdir4download(folder); | 1 | 2023-12-23 03:43:13+00:00 | 2k |
PENEKhun/baekjoon-java-starter | src/main/java/kr/huni/BojStarter.java | [
{
"identifier": "CodeGenerator",
"path": "src/main/java/kr/huni/code_generator/CodeGenerator.java",
"snippet": "public interface CodeGenerator {\n\n GeneratedCode generate(Problem problem);\n}"
},
{
"identifier": "CodeOpenManager",
"path": "src/main/java/kr/huni/code_runner/CodeOpenManager.java",
"snippet": "public interface CodeOpenManager {\n\n /**\n * @param codePath 소스코드의 경로\n * @throws IOException 실행 실패\n * @implSpec 주어진 codePath를 IDE로 열어준다\n */\n void run(String codePath, OperatingSystem operatingSystem) throws IOException;\n\n}"
},
{
"identifier": "JavaSourceCodeFile",
"path": "src/main/java/kr/huni/file_generator/JavaSourceCodeFile.java",
"snippet": "@Slf4j\npublic class JavaSourceCodeFile implements SourceCodeFile {\n\n @Override\n public void write(String sourceRootDirectory, String sourceCode, String testCode)\n throws IOException {\n File srcDir = new File(sourceRootDirectory, \"src\");\n\n log.info(\"srcDir : {}\", srcDir.getAbsolutePath());\n srcDir.mkdirs();\n\n log.info(\"소스코드 디렉토리 생성 완료\");\n writeToFile(srcDir, \"Main.java\", sourceCode);\n writeToFile(srcDir, \"TestHelper.java\", testCode);\n }\n\n}"
},
{
"identifier": "OperatingSystem",
"path": "src/main/java/kr/huni/os/OperatingSystem.java",
"snippet": "public enum OperatingSystem {\n WINDOWS,\n LINUX,\n MAC;\n\n public static OperatingSystem getOperatingSystem() {\n String osName = System.getProperty(\"os.name\").toLowerCase();\n if (osName.contains(\"win\")) {\n return WINDOWS;\n } else if (osName.contains(\"nix\") || osName.contains(\"nux\") || osName.contains(\"aix\")) {\n return LINUX;\n } else if (osName.contains(\"mac\")) {\n return MAC;\n } else {\n throw new RuntimeException(\"지원하지 않는 운영체제입니다. (현재 운영체제: \" + osName + \")\");\n }\n }\n}"
},
{
"identifier": "BaekjoonProblemParser",
"path": "src/main/java/kr/huni/problem_parser/BaekjoonProblemParser.java",
"snippet": "public class BaekjoonProblemParser {\n\n static final String PROBLEM_URL = \"https://www.acmicpc.net/problem/\";\n static final String USER_AGENT = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) \"\n + \"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\";\n static final String PROBLEM_TITLE_SELECTOR = \"span#problem_title\";\n static final String PROBLEM_INPUT_SELECTOR = \"pre[id^=sample-input]\";\n static final String PROBLEM_OUTPUT_SELECTOR = \"pre[id^=sample-output]\";\n private final WebParser webParser;\n\n /**\n * 생성자\n *\n * @param webParser 파싱에 사용할 WebParser\n */\n public BaekjoonProblemParser(WebParser webParser) {\n this.webParser = webParser;\n }\n\n /**\n * 문제 번호를 받아 해당 문제를 파싱합니다.\n *\n * @param problemNumber 백준 문제 번호\n * @return Problem 객체\n */\n public Problem parse(int problemNumber) {\n String title = webParser.parse(PROBLEM_TITLE_SELECTOR)[0];\n final ArrayList<TestCase> testCases = new ArrayList<>();\n\n String[] inputs = webParser.parse(PROBLEM_INPUT_SELECTOR);\n String[] outputs = webParser.parse(PROBLEM_OUTPUT_SELECTOR);\n\n assert inputs.length == outputs.length;\n for (int i = 0; i < inputs.length; i++) {\n testCases.add(new TestCase(inputs[i], outputs[i]));\n }\n\n return new Problem(problemNumber, title, testCases);\n }\n\n}"
},
{
"identifier": "Problem",
"path": "src/main/java/kr/huni/problem_parser/Problem.java",
"snippet": "@Getter\npublic class Problem {\n\n private final int number;\n private final String title;\n private final String sourceRootDirectory;\n private final List<TestCase> testCases;\n\n public Problem(int number, String title, List<TestCase> testCases) {\n UserConfiguration configuration = UserConfigurationLoader.getInstance();\n\n this.number = number;\n this.title = title;\n this.sourceRootDirectory = configuration.srcDirPrefix.getValue() + number;\n this.testCases = testCases;\n }\n\n}"
}
] | import java.io.IOException;
import kr.huni.code_generator.CodeGenerator;
import kr.huni.code_generator.GeneratedCode;
import kr.huni.code_runner.CodeOpenManager;
import kr.huni.file_generator.JavaSourceCodeFile;
import kr.huni.os.OperatingSystem;
import kr.huni.problem_parser.BaekjoonProblemParser;
import kr.huni.problem_parser.Problem;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; | 1,168 | package kr.huni;
@Slf4j
@RequiredArgsConstructor
public class BojStarter {
| package kr.huni;
@Slf4j
@RequiredArgsConstructor
public class BojStarter {
| private final CodeOpenManager codeOpenManager; | 1 | 2023-12-22 09:23:38+00:00 | 2k |
ydb-platform/ydb-java-dialects | hibernate-dialect-v5/src/test/java/tech/ydb/hibernate/BaseTest.java | [
{
"identifier": "YdbDialect",
"path": "hibernate-dialect-v5/src/main/java/tech/ydb/hibernate/dialect/YdbDialect.java",
"snippet": "public class YdbDialect extends Dialect {\n private static final int IN_EXPRESSION_COUNT_LIMIT = 10_000;\n\n private static final Exporter<ForeignKey> FOREIGN_KEY_EMPTY_EXPORTER = new EmptyExporter<>();\n\n public YdbDialect() {\n registerColumnType(Types.BIT, \"Bool\");\n registerColumnType(Types.BOOLEAN, \"Bool\");\n registerColumnType(Types.TINYINT, \"Int8\");\n registerColumnType(Types.SMALLINT, \"Int16\");\n registerColumnType(Types.INTEGER, \"Int32\");\n registerColumnType(Types.BIGINT, \"Int64\");\n registerColumnType(Types.FLOAT, \"Float\");\n registerColumnType(Types.DOUBLE, \"Double\");\n registerColumnType(Types.NUMERIC, \"Decimal (22,9)\");\n registerColumnType(Types.DECIMAL, \"Decimal (22,9)\");\n registerColumnType(Types.REAL, \"Float\");\n\n registerColumnType(Types.DATE, \"Date\");\n registerColumnType(Types.TIME, \"Datetime\");\n registerColumnType(Types.TIMESTAMP, \"Timestamp\");\n\n registerColumnType(Types.VARBINARY, \"Bytes\");\n registerColumnType(Types.LONGVARBINARY, \"Bytes\");\n registerColumnType(Types.BLOB, \"Bytes\");\n registerColumnType(Types.BINARY, \"Bytes\");\n\n registerColumnType(Types.CHAR, \"Text\");\n registerColumnType(Types.VARCHAR, \"Text\");\n registerColumnType(Types.LONGVARCHAR, \"Text\");\n registerColumnType(Types.CLOB, \"Text\");\n\n registerColumnType(Types.NCHAR, \"Text\");\n registerColumnType(Types.NVARCHAR, \"Text\");\n registerColumnType(Types.LONGNVARCHAR, \"Text\");\n registerColumnType(Types.NCLOB, \"Text\");\n\n registerColumnType(Types.TIME_WITH_TIMEZONE, \"TzDateTime\");\n registerColumnType(Types.TIMESTAMP_WITH_TIMEZONE, \"TzTimestamp\");\n }\n\n @Override\n public LimitHandler getLimitHandler() {\n return LimitOffsetLimitHandler.INSTANCE;\n }\n\n @Override\n public Exporter<ForeignKey> getForeignKeyExporter() {\n return FOREIGN_KEY_EMPTY_EXPORTER;\n }\n\n @Override\n public boolean supportsLockTimeouts() {\n return false;\n }\n\n @Override\n public boolean supportsOuterJoinForUpdate() {\n return false;\n }\n\n @Override\n public boolean supportsUnionAll() {\n return true;\n }\n\n @Override\n public boolean supportsCaseInsensitiveLike() {\n return true;\n }\n\n @Override\n public String getCaseInsensitiveLike() {\n return \"ilike\";\n }\n\n @Override\n public String toBooleanValueString(boolean bool) {\n return String.valueOf(bool);\n }\n\n @Override\n public NameQualifierSupport getNameQualifierSupport() {\n return NameQualifierSupport.NONE;\n }\n\n @Override\n public char openQuote() {\n return '`';\n }\n\n @Override\n public char closeQuote() {\n return '`';\n }\n\n @Override\n public String getAddColumnString() {\n return \"add column\";\n }\n\n @Override\n public boolean supportsSelectAliasInGroupByClause() {\n return true;\n }\n\n @Override\n public boolean supportsPartitionBy() {\n return true;\n }\n\n @Override\n public boolean supportsValuesList() {\n return true;\n }\n\n @Override\n public boolean supportsExistsInSelect() {\n return false;\n }\n\n @Override\n public int getInExpressionCountLimit() {\n return IN_EXPRESSION_COUNT_LIMIT;\n }\n}"
},
{
"identifier": "Group",
"path": "hibernate-dialect-v5/src/test/java/tech/ydb/hibernate/entity/Group.java",
"snippet": "@Entity\n@Getter\n@Setter\n@NoArgsConstructor\n@Table(name = \"Groups\")\npublic class Group {\n\n @Id\n private int groupId;\n\n @Column(name = \"name\", unique = true)\n private String name;\n}"
},
{
"identifier": "Student",
"path": "hibernate-dialect-v5/src/test/java/tech/ydb/hibernate/entity/Student.java",
"snippet": "@Entity\n@Getter\n@Setter\n@NoArgsConstructor\n@EqualsAndHashCode\n@Table(name = \"Students\")\npublic class Student {\n\n @Id\n private int studentId;\n\n @Column(name = \"name\")\n private String name;\n\n @Column(name = \"groupId\")\n private int groupId;\n}"
}
] | import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.extension.RegisterExtension;
import tech.ydb.hibernate.dialect.YdbDialect;
import tech.ydb.hibernate.entity.Group;
import tech.ydb.hibernate.entity.Student;
import tech.ydb.jdbc.YdbDriver;
import tech.ydb.test.junit5.YdbHelperExtension;
import javax.persistence.EntityManager;
import java.util.Properties;
import java.util.function.Consumer;
import java.util.stream.Stream; | 1,476 | package tech.ydb.hibernate;
/**
* @author Kirill Kurdyukov
*/
public abstract class BaseTest {
@RegisterExtension
public static final YdbHelperExtension YDB_HELPER_EXTENSION = new YdbHelperExtension();
protected static SessionFactory SESSION_FACTORY;
@BeforeAll
static void beforeAll() {
StringBuilder jdbc = new StringBuilder("jdbc:ydb:")
.append(YDB_HELPER_EXTENSION.useTls() ? "grpcs://" : "grpc://")
.append(YDB_HELPER_EXTENSION.endpoint())
.append(YDB_HELPER_EXTENSION.database());
if (YDB_HELPER_EXTENSION.authToken() != null) {
jdbc.append("?").append("token=").append(YDB_HELPER_EXTENSION.authToken());
}
Properties properties = new Properties();
properties.put(Environment.DRIVER, YdbDriver.class.getName());
properties.put(Environment.URL, jdbc.toString());
properties.put(Environment.DIALECT, YdbDialect.class.getName());
properties.put(Environment.HBM2DDL_AUTO, "create");
properties.put(Environment.SHOW_SQL, true);
SESSION_FACTORY = new Configuration().addProperties(properties) | package tech.ydb.hibernate;
/**
* @author Kirill Kurdyukov
*/
public abstract class BaseTest {
@RegisterExtension
public static final YdbHelperExtension YDB_HELPER_EXTENSION = new YdbHelperExtension();
protected static SessionFactory SESSION_FACTORY;
@BeforeAll
static void beforeAll() {
StringBuilder jdbc = new StringBuilder("jdbc:ydb:")
.append(YDB_HELPER_EXTENSION.useTls() ? "grpcs://" : "grpc://")
.append(YDB_HELPER_EXTENSION.endpoint())
.append(YDB_HELPER_EXTENSION.database());
if (YDB_HELPER_EXTENSION.authToken() != null) {
jdbc.append("?").append("token=").append(YDB_HELPER_EXTENSION.authToken());
}
Properties properties = new Properties();
properties.put(Environment.DRIVER, YdbDriver.class.getName());
properties.put(Environment.URL, jdbc.toString());
properties.put(Environment.DIALECT, YdbDialect.class.getName());
properties.put(Environment.HBM2DDL_AUTO, "create");
properties.put(Environment.SHOW_SQL, true);
SESSION_FACTORY = new Configuration().addProperties(properties) | .addAnnotatedClass(Student.class) | 2 | 2023-12-25 18:31:13+00:00 | 2k |
Patbox/GlideAway | src/main/java/eu/pb4/glideaway/datagen/ItemTagsProvider.java | [
{
"identifier": "GlideItemTags",
"path": "src/main/java/eu/pb4/glideaway/item/GlideItemTags.java",
"snippet": "public class GlideItemTags {\n public static final TagKey<Item> HANG_GLIDERS = of(\"hand_gliders\");\n public static final TagKey<Item> SPECIAL_HANG_GLIDERS = of(\"special_hand_gliders\");\n private static TagKey<Item> of(String path) {\n return TagKey.of(RegistryKeys.ITEM, ModInit.id(path));\n }\n}"
},
{
"identifier": "GlideItems",
"path": "src/main/java/eu/pb4/glideaway/item/GlideItems.java",
"snippet": "public class GlideItems {\n\n public static final WindInABottleItem WIND_IN_A_BOTTLE = register(\"wind_in_a_bottle\", new WindInABottleItem(new Item.Settings().maxCount(2), true));\n public static final WindInABottleItem INFINITE_WIND_IN_A_BOTTLE = register(\"infinite_wind_in_a_bottle\", new WindInABottleItem(new Item.Settings().maxCount(1), false));\n public static final DyeableHangGliderItem HANG_GLIDER = register(\"hang_glider\", new DyeableHangGliderItem(new Item.Settings().maxDamage(250)));\n public static final ParticleHangGliderItem CHERRY_HANG_GLIDER = register(\"cherry_hang_glider\", new ParticleHangGliderItem(new Item.Settings().maxDamage(350), ParticleTypes.CHERRY_LEAVES));\n public static final ParticleHangGliderItem SCULK_HANG_GLIDER = register(\"sculk_hang_glider\", new ParticleHangGliderItem(new Item.Settings().maxDamage(350), ParticleTypes.SCULK_CHARGE_POP));\n public static final ParticleHangGliderItem AZALEA_HANG_GLIDER = register(\"azalea_hang_glider\", new ParticleHangGliderItem(new Item.Settings().maxDamage(350), ParticleTypes.SPORE_BLOSSOM_AIR));\n\n public static void register() {\n PolymerItemGroupUtils.registerPolymerItemGroup(new Identifier(ModInit.ID, \"a_group\"), ItemGroup.create(ItemGroup.Row.BOTTOM, -1)\n .icon(HANG_GLIDER::getDefaultStack)\n .displayName(Text.translatable(\"itemgroup.\" + ModInit.ID))\n .entries(((context, entries) -> {\n entries.add(HANG_GLIDER);\n for (var color : DyeColor.values()) {\n if (color != DyeColor.WHITE) {\n var glider = HANG_GLIDER.getDefaultStack();\n var c = color.getColorComponents();\n HANG_GLIDER.setColor(glider, MathHelper.packRgb(c[0], c[1], c[2]));\n entries.add(glider);\n }\n }\n entries.add(CHERRY_HANG_GLIDER);\n entries.add(SCULK_HANG_GLIDER);\n entries.add(AZALEA_HANG_GLIDER);\n\n entries.add(WIND_IN_A_BOTTLE);\n entries.add(INFINITE_WIND_IN_A_BOTTLE);\n })).build()\n );\n\n UseEntityCallback.EVENT.register(WIND_IN_A_BOTTLE::useOnEntityEvent);\n\n TradeOfferHelper.registerWanderingTraderOffers(2, (b) -> {\n b.add(new TradeOffers.SellItemFactory(GlideItems.AZALEA_HANG_GLIDER, 16, 1, 1, 5));\n b.add(new TradeOffers.SellItemFactory(GlideItems.CHERRY_HANG_GLIDER, 16, 1, 1, 5));\n b.add(new TradeOffers.SellItemFactory(GlideItems.SCULK_HANG_GLIDER, 16, 1, 1, 5));\n });\n\n TradeOfferHelper.registerRebalancedWanderingTraderOffers((b) -> {\n b.pool(id(\"hang_gliders\"), 1,\n new TradeOffers.SellItemFactory(GlideItems.AZALEA_HANG_GLIDER, 16, 1, 1, 5),\n new TradeOffers.SellItemFactory(GlideItems.CHERRY_HANG_GLIDER, 16, 1, 1, 5),\n new TradeOffers.SellItemFactory(GlideItems.SCULK_HANG_GLIDER, 16, 1, 1, 5)\n );\n });\n }\n\n public static <T extends Item> T register(String path, T item) {\n Registry.register(Registries.ITEM, new Identifier(ModInit.ID, path), item);\n return item;\n }\n\n public static <E extends Block & PolymerBlock> BlockItem register(E block) {\n var id = Registries.BLOCK.getId(block);\n BlockItem item;\n if (block instanceof MultiBlock multiBlock) {\n item = new MultiBlockItem(multiBlock, new Item.Settings());\n } else {\n item = new FactoryBlockItem(block, new Item.Settings());\n }\n\n Registry.register(Registries.ITEM, id, item);\n return item;\n }\n}"
}
] | import eu.pb4.glideaway.item.GlideItemTags;
import eu.pb4.glideaway.item.GlideItems;
import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput;
import net.fabricmc.fabric.api.datagen.v1.provider.FabricTagProvider;
import net.minecraft.registry.RegistryWrapper;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.CompletableFuture; | 1,296 | package eu.pb4.glideaway.datagen;
class ItemTagsProvider extends FabricTagProvider.ItemTagProvider {
public ItemTagsProvider(FabricDataOutput output, CompletableFuture<RegistryWrapper.WrapperLookup> registriesFuture, @Nullable FabricTagProvider.BlockTagProvider blockTagProvider) {
super(output, registriesFuture, blockTagProvider);
}
@Override
protected void configure(RegistryWrapper.WrapperLookup arg) { | package eu.pb4.glideaway.datagen;
class ItemTagsProvider extends FabricTagProvider.ItemTagProvider {
public ItemTagsProvider(FabricDataOutput output, CompletableFuture<RegistryWrapper.WrapperLookup> registriesFuture, @Nullable FabricTagProvider.BlockTagProvider blockTagProvider) {
super(output, registriesFuture, blockTagProvider);
}
@Override
protected void configure(RegistryWrapper.WrapperLookup arg) { | this.getOrCreateTagBuilder(GlideItemTags.HANG_GLIDERS) | 0 | 2023-12-22 11:00:52+00:00 | 2k |
danielfeitopin/MUNICS-SAPP-P1 | src/main/java/es/storeapp/business/utils/ExceptionGenerationUtils.java | [
{
"identifier": "AuthenticationException",
"path": "src/main/java/es/storeapp/business/exceptions/AuthenticationException.java",
"snippet": "public class AuthenticationException extends Exception {\n \n private static final long serialVersionUID = 9047626511480506926L;\n\n public AuthenticationException(String message) {\n super(message);\n }\n \n}"
},
{
"identifier": "DuplicatedResourceException",
"path": "src/main/java/es/storeapp/business/exceptions/DuplicatedResourceException.java",
"snippet": "public class DuplicatedResourceException extends Exception {\n \n private static final long serialVersionUID = 6896927410877749980L;\n\n private final String resource;\n private final String value;\n\n public DuplicatedResourceException(String resource, String value, String message) {\n super(message);\n this.resource = resource;\n this.value = value;\n }\n\n public Object getResource() {\n return resource;\n }\n\n public Object getValue() {\n return value;\n }\n \n}"
},
{
"identifier": "InstanceNotFoundException",
"path": "src/main/java/es/storeapp/business/exceptions/InstanceNotFoundException.java",
"snippet": "public class InstanceNotFoundException extends Exception {\n\n private static final long serialVersionUID = -4208426212843868046L;\n\n private final Long id;\n private final String type;\n\n public InstanceNotFoundException(Long id, String type, String message) {\n super(message);\n this.id = id;\n this.type = type;\n }\n\n public Object getId() {\n return id;\n }\n\n public String getType() {\n return type;\n }\n \n}"
},
{
"identifier": "InvalidStateException",
"path": "src/main/java/es/storeapp/business/exceptions/InvalidStateException.java",
"snippet": "public class InvalidStateException extends Exception {\n\n private static final long serialVersionUID = 3026551774263871416L;\n\n public InvalidStateException(String message) {\n super(message);\n }\n \n}"
}
] | import es.storeapp.business.exceptions.AuthenticationException;
import es.storeapp.business.exceptions.DuplicatedResourceException;
import es.storeapp.business.exceptions.InstanceNotFoundException;
import es.storeapp.business.exceptions.InvalidStateException;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component; | 729 | package es.storeapp.business.utils;
@Component
public class ExceptionGenerationUtils {
@Autowired
private MessageSource messageSource;
public InstanceNotFoundException toInstanceNotFoundException(Long id, String type, String messageKey)
throws InstanceNotFoundException {
Locale locale = LocaleContextHolder.getLocale();
String message = messageSource.getMessage(messageKey, new Object[]{type, id}, locale);
return new InstanceNotFoundException(id, type, message);
}
public DuplicatedResourceException toDuplicatedResourceException(String resource, String value, String messageKey)
throws DuplicatedResourceException {
Locale locale = LocaleContextHolder.getLocale();
String message = messageSource.getMessage(messageKey, new Object[]{value, resource}, locale);
return new DuplicatedResourceException(resource, value, message);
}
public AuthenticationException toAuthenticationException(String messageKey, String user)
throws AuthenticationException {
Locale locale = LocaleContextHolder.getLocale();
String message = messageSource.getMessage(messageKey, new Object[] {user}, locale);
return new AuthenticationException(message);
}
| package es.storeapp.business.utils;
@Component
public class ExceptionGenerationUtils {
@Autowired
private MessageSource messageSource;
public InstanceNotFoundException toInstanceNotFoundException(Long id, String type, String messageKey)
throws InstanceNotFoundException {
Locale locale = LocaleContextHolder.getLocale();
String message = messageSource.getMessage(messageKey, new Object[]{type, id}, locale);
return new InstanceNotFoundException(id, type, message);
}
public DuplicatedResourceException toDuplicatedResourceException(String resource, String value, String messageKey)
throws DuplicatedResourceException {
Locale locale = LocaleContextHolder.getLocale();
String message = messageSource.getMessage(messageKey, new Object[]{value, resource}, locale);
return new DuplicatedResourceException(resource, value, message);
}
public AuthenticationException toAuthenticationException(String messageKey, String user)
throws AuthenticationException {
Locale locale = LocaleContextHolder.getLocale();
String message = messageSource.getMessage(messageKey, new Object[] {user}, locale);
return new AuthenticationException(message);
}
| public InvalidStateException toInvalidStateException(String messageKey) throws InvalidStateException { | 3 | 2023-12-24 19:24:49+00:00 | 2k |
Brath1024/SensiCheck | src/main/java/cn/brath/sensicheck/strategy/SensiCheckContext.java | [
{
"identifier": "SensiCheckType",
"path": "src/main/java/cn/brath/sensicheck/constants/SensiCheckType.java",
"snippet": "public enum SensiCheckType {\n\n /**\n * 替换\n */\n REPLACE,\n\n /**\n * 抛异常\n */\n ERROR,\n\n /**\n * 不做动作\n */\n NON,\n\n}"
},
{
"identifier": "SenFilterErrorImpl",
"path": "src/main/java/cn/brath/sensicheck/strategy/impl/SenFilterErrorImpl.java",
"snippet": "public class SenFilterErrorImpl extends SenFilterImpl {\n\n @Override\n public SensiCheckType type() {\n return SensiCheckType.ERROR;\n }\n\n /**\n * 处理字符串类型值\n *\n * @param value\n * @return\n */\n @Override\n protected String handleString(String value) {\n String sens = super.sensiHolder.existsStr(value);\n if (sens != null) throw new SenException(errorText + \" 可能涉及到的敏感词:[\" + sens + \"]\", value);\n return value;\n }\n\n}"
},
{
"identifier": "SenFilterNonImpl",
"path": "src/main/java/cn/brath/sensicheck/strategy/impl/SenFilterNonImpl.java",
"snippet": "public class SenFilterNonImpl extends SenFilterImpl {\n\n @Override\n public SensiCheckType type() {\n return SensiCheckType.NON;\n }\n\n /**\n * 处理字符串类型值\n *\n * @param value\n * @return\n */\n @Override\n protected String handleString(String value) {\n return value;\n }\n\n}"
},
{
"identifier": "SenFilterReplaceImpl",
"path": "src/main/java/cn/brath/sensicheck/strategy/impl/SenFilterReplaceImpl.java",
"snippet": "public class SenFilterReplaceImpl extends SenFilterImpl {\n\n @Override\n public SensiCheckType type() {\n return SensiCheckType.REPLACE;\n }\n\n /**\n * 处理字符串类型值\n *\n * @param value\n * @return\n */\n @Override\n protected String handleString(String value) {\n return super.sensiHolder.replace(value, this.replaceValue);\n }\n}"
}
] | import cn.brath.sensicheck.constants.SensiCheckType;
import cn.brath.sensicheck.strategy.impl.SenFilterErrorImpl;
import cn.brath.sensicheck.strategy.impl.SenFilterNonImpl;
import cn.brath.sensicheck.strategy.impl.SenFilterReplaceImpl;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | 770 | package cn.brath.sensicheck.strategy;
/**
* 策略器上下文处理
*
* @author Brath
* @since 2023/7/28 15:44
*/
public class SensiCheckContext {
private final Map<SensiCheckType, SensiCheckStrategy> strategyMap;
private static SensiCheckContext instance = null;
private SensiCheckContext() {
this.strategyMap = new HashMap<>();
this.strategyMap.put(SensiCheckType.REPLACE, new SenFilterReplaceImpl());
this.strategyMap.put(SensiCheckType.ERROR, new SenFilterErrorImpl()); | package cn.brath.sensicheck.strategy;
/**
* 策略器上下文处理
*
* @author Brath
* @since 2023/7/28 15:44
*/
public class SensiCheckContext {
private final Map<SensiCheckType, SensiCheckStrategy> strategyMap;
private static SensiCheckContext instance = null;
private SensiCheckContext() {
this.strategyMap = new HashMap<>();
this.strategyMap.put(SensiCheckType.REPLACE, new SenFilterReplaceImpl());
this.strategyMap.put(SensiCheckType.ERROR, new SenFilterErrorImpl()); | this.strategyMap.put(SensiCheckType.NON, new SenFilterNonImpl()); | 2 | 2023-12-28 04:50:04+00:00 | 2k |
RoderickQiu/SUSTech_CSE_Projects | CS109_2022_Fall/Chess/chessComponent/SquareComponent.java | [
{
"identifier": "ClickController",
"path": "CS109_2022_Fall/Chess/controller/ClickController.java",
"snippet": "public class ClickController {\r\n private final Chessboard chessboard;\r\n private SquareComponent first;\r\n\r\n public ClickController(Chessboard chessboard) {\r\n this.chessboard = chessboard;\r\n }\r\n\r\n private int count = 0;\r\n\r\n public void onClick(SquareComponent squareComponent) {\r\n Main.playNotifyMusic(\"click\");\r\n\r\n //判断第一次点击\r\n if (first == null) {\r\n if (handleFirst(squareComponent)) {\r\n squareComponent.setSelected(true);\r\n first = squareComponent;\r\n first.repaint();//还没有实现显示可以当前棋子可以移动的坐标\r\n }\r\n } else {\r\n if (first == squareComponent) { // 再次点击取消选取\r\n squareComponent.setSelected(false);\r\n SquareComponent recordFirst = first;\r\n first = null;\r\n recordFirst.repaint();\r\n } else if (handleSecond(squareComponent)) {\r\n //repaint in swap chess method.\r\n chessboard.swapChessComponents(first, squareComponent);\r\n chessboard.clickController.swapPlayer();\r\n\r\n first.setSelected(false);\r\n first = null;\r\n }\r\n }\r\n }\r\n\r\n\r\n /**\r\n * @param squareComponent 目标选取的棋子\r\n * @return 目标选取的棋子是否与棋盘记录的当前行棋方颜色相同\r\n */\r\n\r\n private boolean handleFirst(SquareComponent squareComponent) {\r\n if (!squareComponent.isReversal()) {\r\n squareComponent.setReversal(true);\r\n squareComponent.setCheating(false);\r\n System.out.printf(\"onClick to reverse a chess [%d,%d]\\n\", squareComponent.getChessboardPoint().getX(), squareComponent.getChessboardPoint().getY());\r\n chessboard.isPlayerDo = true;\r\n Chessboard.isComReverse = true;\r\n Chessboard.Now.push(squareComponent);\r\n squareComponent.repaint();\r\n if (count == 0) {\r\n count++;\r\n chessboard.setCurrentColor(squareComponent.getChessColor());\r\n chessboard.setPlayerColor(squareComponent.getChessColor());\r\n if (squareComponent.getChessColor() == ChessColor.BLACK) {\r\n JOptionPane.showMessageDialog(null, \"你是黑色,开始博弈吧!\");\r\n chessboard.setEnemyColor(ChessColor.RED);\r\n } else {\r\n chessboard.setEnemyColor(ChessColor.BLACK);\r\n JOptionPane.showMessageDialog(null, \"你是红色,开始博弈吧!\");\r\n }\r\n }\r\n chessboard.clickController.swapPlayer();\r\n try {\r\n Thread.currentThread().sleep(1000);\r\n } catch (Exception e) {\r\n }\r\n return false;\r\n }\r\n return squareComponent.getChessColor() == chessboard.getCurrentColor();\r\n }\r\n\r\n /**\r\n * @param squareComponent first棋子目标移动到的棋子second\r\n * @return first棋子是否能够移动到second棋子位置\r\n */\r\n\r\n /*\r\n *\r\n * 对局主逻辑填充在这里\r\n */\r\n private boolean handleSecond(SquareComponent squareComponent) {\r\n\r\n return first.canMoveTo(chessboard.getChessComponents(), squareComponent.getChessboardPoint(), first.getChessboardPoint(), chessboard.getPlayerColor());\r\n }\r\n\r\n public void swapPlayer() {\r\n chessboard.setCurrentColor(chessboard.getCurrentColor() == ChessColor.BLACK ? ChessColor.RED : ChessColor.BLACK);\r\n ChessGameFrame.getStatusLabel().setText(String.format(\"%s走棋\", (chessboard.getCurrentColor().getName().equals(\"BLACK\")) ? \"黑\" : \"红\"));\r\n ChessGameFrame.getStatusLabel().setForeground((chessboard.getCurrentColor() == ChessColor.BLACK) ? Main.getThemeColor(\"indicatorBlack\") : ChessColor.RED.getColor());\r\n if (chessboard.getCurrentColor() == chessboard.getEnemyColor() && (chessboard.ModeChoice == 1 || chessboard.ModeChoice == 2)) {\r\n chessboard.Comround();\r\n swapPlayer();\r\n }\r\n }\r\n}\r"
},
{
"identifier": "ChessColor",
"path": "CS109_2022_Fall/Chess/model/ChessColor.java",
"snippet": "public enum ChessColor {\r\n BLACK(\"BLACK\", Color.decode(\"#251f1e\")), RED(\"RED\", Color.decode(\"#e83505\")), NONE(\"No Player\", Color.WHITE);\r\n\r\n private final String name;\r\n private final Color color;\r\n\r\n ChessColor(String name, Color color) {\r\n this.name = name;\r\n this.color = color;\r\n }\r\n\r\n public String getName() {\r\n return name;\r\n }\r\n\r\n public Color getColor() {\r\n return color;\r\n }\r\n}\r"
},
{
"identifier": "ChessboardPoint",
"path": "CS109_2022_Fall/Chess/model/ChessboardPoint.java",
"snippet": "public class ChessboardPoint {\r\n private int x, y;\r\n\r\n /**\r\n * @param x: row\r\n * @param y: col\r\n */\r\n public ChessboardPoint(int x, int y) {\r\n this.x = x;\r\n this.y = y;\r\n }\r\n\r\n public int getX() {\r\n return x;\r\n }\r\n\r\n public int getY() {\r\n return y;\r\n }\r\n\r\n\r\n @Override\r\n public String toString() {\r\n return \"(\" + x + \",\" + y + \") \" + \"on the chessboard is clicked!\";\r\n }\r\n}\r"
},
{
"identifier": "serifFont",
"path": "CS109_2022_Fall/Chess/Main.java",
"snippet": "public static Font titleFont, sansFont, serifFont;\r"
}
] | import Chess.controller.ClickController;
import Chess.model.ChessColor;
import Chess.model.ChessboardPoint;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import static Chess.Main.serifFont;
| 1,481 | package Chess.chessComponent;
/**
* 这个类是一个抽象类,主要表示8*4棋盘上每个格子的棋子情况。
* 有两个子类:
* 1. EmptySlotComponent: 空棋子
* 2. ChessComponent: 表示非空棋子
*/
public abstract class SquareComponent extends JComponent {
private static final Color squareColor = new Color(250, 220, 190, 0);
protected static int spacingLength;
| package Chess.chessComponent;
/**
* 这个类是一个抽象类,主要表示8*4棋盘上每个格子的棋子情况。
* 有两个子类:
* 1. EmptySlotComponent: 空棋子
* 2. ChessComponent: 表示非空棋子
*/
public abstract class SquareComponent extends JComponent {
private static final Color squareColor = new Color(250, 220, 190, 0);
protected static int spacingLength;
| protected static final Font CHESS_FONT = serifFont.deriveFont(Font.BOLD, 30);
| 3 | 2023-12-31 05:50:13+00:00 | 2k |
Ertinox45/ImmersiveAddon | src/main/java/fr/dynamx/addons/immersive/common/network/ImmersiveAddonPacketHandler.java | [
{
"identifier": "ImmersiveAddon",
"path": "src/main/java/fr/dynamx/addons/immersive/ImmersiveAddon.java",
"snippet": "@Mod(modid = ImmersiveAddon.ID, name = ImmersiveAddon.NAME, version = \"1.0\", dependencies = \"before: dynamxmod\")\n@DynamXAddon(modid = ImmersiveAddon.ID, name = ImmersiveAddon.NAME, version = \"1.0\")\npublic class ImmersiveAddon {\n public static final String ID = \"dynamx_immersive\";\n public static final String NAME = \"ImmersiveAddon\";\n\n public static RadioPlayer radioPlayer = new RadioPlayer();\n\n @DynamXAddon.AddonEventSubscriber\n public static void initAddon() {\n //if (FMLCommonHandler.instance().getSide().isClient()) {}\n }\n\n @Mod.EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n ModSyncedDataKeys.initKeys();\n MinecraftForge.EVENT_BUS.register(new HandAnimationEventHandler());\n if (event.getSide().isClient()) {\n MinecraftForge.EVENT_BUS.register(new HandAnimClientEventHandler());\n //MinecraftForge.EVENT_BUS.register(new Common());\n if (event.getSide().isClient()) {\n // MinecraftForge.EVENT_BUS.register(new Client());\n KeyBindings.register();\n }\n\n ImmersiveAddonConfig.init(event.getSuggestedConfigurationFile());\n ImmersiveAddonPacketHandler.getInstance().registerPackets();\n\n //network = NetworkRegistry.INSTANCE.newSimpleChannel(ImmersiveAddon.ID);\n //network.registerMessage(PacketAttachTrailer.Handler.class, PacketAttachTrailer.class, 0, Side.SERVER);\n }\n }\n\n @Mod.EventHandler\n public void serverStarting(FMLServerStartingEvent event) {\n }\n}"
},
{
"identifier": "SendRadioFreqConfig",
"path": "src/main/java/fr/dynamx/addons/immersive/common/network/packets/SendRadioFreqConfig.java",
"snippet": "public class SendRadioFreqConfig implements IMessage {\n\n private String json;\n\n public SendRadioFreqConfig() {\n }\n\n public SendRadioFreqConfig(String json) {\n this.json = json;\n }\n\n @Override\n public void fromBytes(ByteBuf buf) {\n json = ByteBufUtils.readUTF8String(buf);\n }\n\n @Override\n public void toBytes(ByteBuf buf) {\n ByteBufUtils.writeUTF8String(buf, json);\n }\n\n public static class Handler implements IMessageHandler<SendRadioFreqConfig, IMessage> {\n\n @Override\n public IMessage onMessage(SendRadioFreqConfig message, MessageContext ctx) {\n try\n {\n ConfigReader.writeToFileString(message.json);\n ConfigReader.readFromFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n }\n}"
}
] | import fr.dynamx.addons.immersive.ImmersiveAddon;
import fr.dynamx.addons.immersive.common.network.packets.SendRadioFreqConfig;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import net.minecraftforge.fml.relauncher.Side; | 879 | package fr.dynamx.addons.immersive.common.network;
public class ImmersiveAddonPacketHandler {
private static ImmersiveAddonPacketHandler instance;
private SimpleNetworkWrapper network;
private int nextID = 0;
public static ImmersiveAddonPacketHandler getInstance() {
if (instance == null) instance = new ImmersiveAddonPacketHandler();
return instance;
}
public SimpleNetworkWrapper getNetwork() {
return network;
}
public void registerPackets() {
this.network = NetworkRegistry.INSTANCE.newSimpleChannel(ImmersiveAddon.ID.toUpperCase());
| package fr.dynamx.addons.immersive.common.network;
public class ImmersiveAddonPacketHandler {
private static ImmersiveAddonPacketHandler instance;
private SimpleNetworkWrapper network;
private int nextID = 0;
public static ImmersiveAddonPacketHandler getInstance() {
if (instance == null) instance = new ImmersiveAddonPacketHandler();
return instance;
}
public SimpleNetworkWrapper getNetwork() {
return network;
}
public void registerPackets() {
this.network = NetworkRegistry.INSTANCE.newSimpleChannel(ImmersiveAddon.ID.toUpperCase());
| this.registerPacket(SendRadioFreqConfig.Handler.class, SendRadioFreqConfig.class, Side.CLIENT); | 1 | 2023-12-30 08:33:54+00:00 | 2k |
Patbox/serveruifix | src/main/java/eu/pb4/serveruifix/polydex/PolydexCompatImpl.java | [
{
"identifier": "GuiTextures",
"path": "src/main/java/eu/pb4/serveruifix/util/GuiTextures.java",
"snippet": "public class GuiTextures {\n public static final GuiElement EMPTY = icon16(\"empty\").get().build();\n public static final Function<Text, Text> STONECUTTER = background(\"stonecutter\");\n\n public static final Supplier<GuiElementBuilder> POLYDEX_BUTTON = icon32(\"polydex\");\n public static final Supplier<GuiElementBuilder> LEFT_BUTTON = icon16(\"left\");\n public static final Supplier<GuiElementBuilder> RIGHT_BUTTON = icon16(\"right\");\n\n public static void register() {\n }\n\n\n public record Progress(GuiElement[] elements) {\n\n public GuiElement get(float progress) {\n return elements[Math.min((int) (progress * elements.length), elements.length - 1)];\n }\n\n public static Progress createVertical(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = verticalProgress16(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress16(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal32(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress32(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n\n public static Progress createHorizontal32Right(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = horizontalProgress32Right(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n public static Progress createVertical32Right(String path, int start, int stop, boolean reverse) {\n var size = stop - start;\n var elements = new GuiElement[size + 1];\n var function = verticalProgress32Right(path, start, stop, reverse);\n\n elements[0] = EMPTY;\n\n for (var i = 1; i <= size; i++) {\n elements[i] = function.apply(i - 1).build();\n }\n return new Progress(elements);\n }\n }\n\n}"
},
{
"identifier": "GuiUtils",
"path": "src/main/java/eu/pb4/serveruifix/util/GuiUtils.java",
"snippet": "public class GuiUtils {\n public static final GuiElement EMPTY = GuiElement.EMPTY;\n\n public static final void playClickSound(ServerPlayerEntity player) {\n player.playSound(SoundEvents.UI_BUTTON_CLICK.value(), SoundCategory.MASTER, 0.5f, 1);\n }\n}"
}
] | import eu.pb4.polydex.api.v1.recipe.*;
import eu.pb4.serveruifix.util.GuiTextures;
import eu.pb4.serveruifix.util.GuiUtils;
import eu.pb4.sgui.api.elements.GuiElement;
import net.minecraft.recipe.RecipeType;
import net.minecraft.text.Text; | 1,076 | package eu.pb4.serveruifix.polydex;
public class PolydexCompatImpl {
public static void register() {
}
public static GuiElement getButton(RecipeType<?> type) {
var category = PolydexCategory.of(type);
return GuiTextures.POLYDEX_BUTTON.get()
.setName(Text.translatable("text.serveruifix.recipes"))
.setCallback((index, type1, action, gui) -> {
PolydexPageUtils.openCategoryUi(gui.getPlayer(), category, gui::open); | package eu.pb4.serveruifix.polydex;
public class PolydexCompatImpl {
public static void register() {
}
public static GuiElement getButton(RecipeType<?> type) {
var category = PolydexCategory.of(type);
return GuiTextures.POLYDEX_BUTTON.get()
.setName(Text.translatable("text.serveruifix.recipes"))
.setCallback((index, type1, action, gui) -> {
PolydexPageUtils.openCategoryUi(gui.getPlayer(), category, gui::open); | GuiUtils.playClickSound(gui.getPlayer()); | 1 | 2023-12-28 23:01:30+00:00 | 2k |
psobiech/opengr8on | tftp/src/main/java/pl/psobiech/opengr8on/tftp/packets/TFTPDataPacket.java | [
{
"identifier": "TFTPPacketType",
"path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/TFTPPacketType.java",
"snippet": "public enum TFTPPacketType {\n UNKNOWN(\n 0,\n payload -> {\n throw new TFTPPacketException(\"Bad packet. Invalid TFTP operator code.\");\n }\n ),\n READ_REQUEST(1, TFTPReadRequestPacket::new),\n WRITE_REQUEST(2, TFTPWriteRequestPacket::new),\n DATA(3, TFTPDataPacket::new),\n ACKNOWLEDGEMENT(4, TFTPAckPacket::new),\n ERROR(5, TFTPErrorPacket::new),\n //\n ;\n\n private final byte packetType;\n\n private final Parser parser;\n\n TFTPPacketType(int packetType, Parser parser) {\n if (packetType < 0 || packetType > 0xFF) {\n throw new IllegalArgumentException();\n }\n\n this.packetType = (byte) (packetType & 0xFF);\n this.parser = parser;\n }\n\n public byte packetType() {\n return packetType;\n }\n\n public TFTPPacket parse(Payload payload) throws TFTPPacketException {\n return parser.parse(payload);\n }\n\n public static TFTPPacketType ofPacketType(byte packetType) {\n for (TFTPPacketType value : values()) {\n if (value.packetType() == packetType) {\n return value;\n }\n }\n\n return UNKNOWN;\n }\n\n @FunctionalInterface\n private interface Parser {\n TFTPPacket parse(Payload payload) throws TFTPPacketException;\n }\n}"
},
{
"identifier": "TFTPPacketException",
"path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/exceptions/TFTPPacketException.java",
"snippet": "public class TFTPPacketException extends Exception {\n private final TFTPErrorType error;\n\n public TFTPPacketException(TFTPErrorPacket errorPacket) {\n this(errorPacket.getError(), errorPacket.getMessage());\n }\n\n public TFTPPacketException(TFTPErrorType error, IOException exception) {\n super(exception);\n\n this.error = error;\n }\n\n public TFTPPacketException(TFTPErrorType error, String message) {\n super(message);\n\n this.error = error;\n }\n\n public TFTPPacketException(TFTPErrorType error, String message, Throwable throwable) {\n super(message, throwable);\n\n this.error = error;\n }\n\n public TFTPPacketException(String message) {\n super(message);\n\n this.error = TFTPErrorType.UNDEFINED;\n }\n\n public TFTPErrorPacket asError(InetAddress address, int port) {\n final String message;\n final Throwable cause = getCause();\n if (cause == null) {\n message = getMessage();\n } else {\n message = cause.getClass().getSimpleName() + \": \" + getMessage();\n }\n\n return new TFTPErrorPacket(\n address, port,\n getError(), message\n );\n }\n\n public TFTPErrorType getError() {\n return error;\n }\n}"
}
] | import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import pl.psobiech.opengr8on.tftp.TFTPPacketType;
import pl.psobiech.opengr8on.tftp.exceptions.TFTPPacketException;
import pl.psobiech.opengr8on.util.SocketUtil.Payload; | 1,107 | /*
* OpenGr8on, open source extensions to systems based on Grenton devices
* Copyright (C) 2023 Piotr Sobiech
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package pl.psobiech.opengr8on.tftp.packets;
public class TFTPDataPacket extends TFTPBlockPacket {
public static final int MAX_DATA_LENGTH = 512;
private final int length;
private final int offset;
private final byte[] buffer;
public TFTPDataPacket(Payload payload) throws TFTPPacketException { | /*
* OpenGr8on, open source extensions to systems based on Grenton devices
* Copyright (C) 2023 Piotr Sobiech
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package pl.psobiech.opengr8on.tftp.packets;
public class TFTPDataPacket extends TFTPBlockPacket {
public static final int MAX_DATA_LENGTH = 512;
private final int length;
private final int offset;
private final byte[] buffer;
public TFTPDataPacket(Payload payload) throws TFTPPacketException { | super(TFTPPacketType.DATA, payload.address(), payload.port(), getBlockNumber(payload)); | 0 | 2023-12-23 09:56:14+00:00 | 2k |
Daniil-Tsiunchyk/DatsBlack-Hackathon | Gold/src/main/java/org/example/scripts/ScriptCommand.java | [
{
"identifier": "ScanResult",
"path": "Gold/src/main/java/org/example/models/ScanResult.java",
"snippet": "@Data\npublic class ScanResult {\n private ScanData scan;\n private boolean success;\n private Error[] errors;\n\n @Data\n public static class ScanData {\n private Ship[] myShips;\n private Ship[] enemyShips;\n private Zone zone;\n }\n\n @Data\n public static class Ship {\n private int id;\n private int x;\n private int y;\n private int size;\n private int hp;\n private String direction;\n private int speed;\n private int cannonCooldown;\n private int cannonCooldownLeft;\n private int cannonShootSuccessCount;\n private int numberTarget = 0;\n\n public void move() {\n switch (direction.toLowerCase()) {\n case NORTH:\n y -= speed;\n break;\n case SOUTH:\n y += speed;\n break;\n case WEST:\n x -= speed;\n break;\n case EAST:\n x += speed;\n break;\n default:\n System.out.println(\"Неправильное направление: \" + direction);\n break;\n }\n }\n }\n\n @Data\n public static class Zone {\n private int x;\n private int y;\n private int radius;\n }\n\n @Data\n public static class Error {\n private String message;\n }\n}"
},
{
"identifier": "parseResponse",
"path": "Gold/src/main/java/org/example/CommonScripts.java",
"snippet": "public static String parseResponse(String responseBody) {\n Response response = gson.fromJson(responseBody, Response.class);\n return response.toString();\n}"
},
{
"identifier": "Const",
"path": "Gold/src/main/java/org/example/Const.java",
"snippet": "public class Const {\n public static final HttpClient httpClient = HttpClient.newHttpClient();\n public static final String apiKey = \"a7e670d0-c3ff-4467-96ca-3ffcd79dca89\";\n public static final Gson gson = new Gson();\n public static final String baseUrl = \"https://datsblack.datsteam.dev/api/\";\n public static final String mapUrl = \"https://datsblack.datsteam.dev/json/map/6586b267d01324.88322035.json\";\n public final static int DISTANCE_SCAN = 25;\n public static final String NORTH = \"north\";\n public static final String SOUTH = \"south\";\n public static final String EAST = \"east\";\n public static final String WEST = \"west\";\n public static final int THIS_TICK = 75;\n}"
},
{
"identifier": "fetchScanResult",
"path": "Gold/src/main/java/org/example/scripts/ScriptMap.java",
"snippet": "static ScanResult fetchScanResult() throws IOException, InterruptedException {\n HttpRequest request = HttpRequest.newBuilder()\n .uri(URI.create(baseUrl + \"scan\"))\n .header(\"X-API-Key\", apiKey)\n .build();\n\n HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());\n\n Gson gson = new Gson();\n return gson.fromJson(response.body(), ScanResult.class);\n}"
}
] | import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.example.models.ScanResult;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import static org.example.CommonScripts.parseResponse;
import static org.example.Const.*;
import static org.example.scripts.ScriptMap.fetchScanResult; | 1,216 | package org.example.scripts;
public class ScriptCommand {
public static final Integer CHANGE_SPEED = null; // Изменяемая скорость
public static final Integer ROTATE_ANGLE = null; // Угол поворота
public static void main(String[] args) {
try {
System.out.println("Запуск команды контроля кораблей");
ScanResult scanResult = fetchScanResult();
ScanResult.Ship[] myShips = scanResult.getScan().getMyShips();
// Gson gson = new GsonBuilder().setPrettyPrinting().create();
// String prettyJson = gson.toJson(scanResult);
// System.out.println("Обработанный результат сканирования: \n" + prettyJson);
sendShipCommands(myShips);
} catch (IOException | InterruptedException e) {
System.err.println("Ошибка: " + e.getMessage());
}
}
@Data
@AllArgsConstructor
static class ShipsWrapper {
private List<ShipCommand> ships;
}
public static void sendShipCommands(ScanResult.Ship[] myShips) throws IOException, InterruptedException {
List<ShipCommand> commands = new ArrayList<>();
for (ScanResult.Ship ship : myShips) {
ShipCommand command = new ShipCommand(ship.getId(), CHANGE_SPEED, ROTATE_ANGLE);
commands.add(command);
}
ShipsWrapper shipsWrapper = new ShipsWrapper(commands);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(shipsWrapper);
System.out.println("Отправляемые команды: " + requestBody);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "shipCommand"))
.header("X-API-Key", apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); | package org.example.scripts;
public class ScriptCommand {
public static final Integer CHANGE_SPEED = null; // Изменяемая скорость
public static final Integer ROTATE_ANGLE = null; // Угол поворота
public static void main(String[] args) {
try {
System.out.println("Запуск команды контроля кораблей");
ScanResult scanResult = fetchScanResult();
ScanResult.Ship[] myShips = scanResult.getScan().getMyShips();
// Gson gson = new GsonBuilder().setPrettyPrinting().create();
// String prettyJson = gson.toJson(scanResult);
// System.out.println("Обработанный результат сканирования: \n" + prettyJson);
sendShipCommands(myShips);
} catch (IOException | InterruptedException e) {
System.err.println("Ошибка: " + e.getMessage());
}
}
@Data
@AllArgsConstructor
static class ShipsWrapper {
private List<ShipCommand> ships;
}
public static void sendShipCommands(ScanResult.Ship[] myShips) throws IOException, InterruptedException {
List<ShipCommand> commands = new ArrayList<>();
for (ScanResult.Ship ship : myShips) {
ShipCommand command = new ShipCommand(ship.getId(), CHANGE_SPEED, ROTATE_ANGLE);
commands.add(command);
}
ShipsWrapper shipsWrapper = new ShipsWrapper(commands);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(shipsWrapper);
System.out.println("Отправляемые команды: " + requestBody);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "shipCommand"))
.header("X-API-Key", apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); | System.out.println("Результат: " + parseResponse(response.body())); | 1 | 2023-12-23 11:29:47+00:00 | 2k |
Pigmice2733/frc-2024 | src/main/java/frc/robot/commands/actions/HandoffToShooter.java | [
{
"identifier": "AutoConfig",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public static class AutoConfig {\n public final static double INTAKE_MOVE_TIME = 3;\n public final static double INTAKE_FEED_TIME = 1;\n public final static double FLYWHEEL_SPINUP_TIME = 3;\n\n}"
},
{
"identifier": "IntakeState",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public static enum IntakeState {\n UP(45),\n DOWN(0);\n\n private double position;\n\n IntakeState(double position) {\n this.position = position;\n }\n\n public double getPosition() {\n return position;\n }\n}"
},
{
"identifier": "Intake",
"path": "src/main/java/frc/robot/subsystems/Intake.java",
"snippet": "public class Intake extends PIDSubsystemBase {\n private final CANSparkMax wheelsMotor = new CANSparkMax(CANConfig.INTAKE_WHEELS, MotorType.kBrushless);\n\n public Intake() {\n super(new CANSparkMax(CANConfig.INTAKE_PIVOT, MotorType.kBrushless), IntakeConfig.P, IntakeConfig.I,\n IntakeConfig.D, new Constraints(IntakeConfig.MAX_VELOCITY, IntakeConfig.MAX_ACCELERATION), false,\n IntakeConfig.MOTOR_POSITION_CONVERSION, 50, Constants.INTAKE_TAB, true);\n\n wheelsMotor.restoreFactoryDefaults();\n wheelsMotor.setInverted(false);\n\n ShuffleboardHelper.addOutput(\"Motor Output\", Constants.INTAKE_TAB, () -> wheelsMotor.get());\n }\n\n /** Sets the intake motor to a percent output (0.0 - 1.0) */\n public void outputToMotor(double percent) {\n wheelsMotor.set(percent);\n }\n\n /** Spins intake wheels to intake balls. */\n public Command runWheelsForward() {\n return Commands.runOnce(() -> outputToMotor(IntakeConfig.WHEELS_SPEED));\n }\n\n /** Spins intake wheels to eject balls. */\n public Command runWheelsBackward() {\n return Commands.runOnce(() -> outputToMotor(-IntakeConfig.WHEELS_SPEED));\n }\n\n /** Sets intake wheels to zero output. */\n public Command stopWheels() {\n return Commands.runOnce(() -> outputToMotor(0));\n }\n\n /** Sets the rotation state of the intake */\n public Command setTargetState(IntakeState state) {\n return Commands.runOnce(() -> setTargetRotation(state.getPosition()));\n }\n}"
},
{
"identifier": "Shooter",
"path": "src/main/java/frc/robot/subsystems/Shooter.java",
"snippet": "public class Shooter extends SubsystemBase {\n private final CANSparkMax flywheelsMotor = new CANSparkMax(CANConfig.SHOOTER_MOTOR, MotorType.kBrushless);\n private final CANSparkMax feederMotor = new CANSparkMax(CANConfig.FEEDER_MOTOR, MotorType.kBrushless);\n\n public Shooter() {\n flywheelsMotor.restoreFactoryDefaults();\n flywheelsMotor.setInverted(false);\n\n ShuffleboardHelper.addOutput(\"Motor Output\", Constants.SHOOTER_TAB, () -> flywheelsMotor.get());\n }\n\n private void outputToFlywheels(double output) {\n flywheelsMotor.set(output);\n }\n\n public Command spinFlywheelsForward() {\n return Commands.runOnce(() -> outputToFlywheels(ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command spinFlywheelsBackward() {\n return Commands.runOnce(() -> outputToFlywheels(-ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command stopFlywheels() {\n return Commands.runOnce(() -> outputToFlywheels(0));\n }\n\n private void outputToFeeder(double output) {\n feederMotor.set(output);\n }\n\n public Command spinFeederForward() {\n return Commands.runOnce(() -> outputToFeeder(ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command spinFeederBackward() {\n return Commands.runOnce(() -> outputToFeeder(-ShooterConfig.DEFAULT_FLYWHEEL_SPEED));\n }\n\n public Command stopFeeder() {\n return Commands.runOnce(() -> outputToFeeder(0));\n }\n}"
}
] | import com.pigmice.frc.lib.controller_rumbler.ControllerRumbler;
import edu.wpi.first.wpilibj.GenericHID.RumbleType;
import edu.wpi.first.wpilibj2.command.Commands;
import edu.wpi.first.wpilibj2.command.SequentialCommandGroup;
import frc.robot.Constants.AutoConfig;
import frc.robot.Constants.IntakeConfig.IntakeState;
import frc.robot.subsystems.Intake;
import frc.robot.subsystems.Shooter; | 1,181 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands.actions;
public class HandoffToShooter extends SequentialCommandGroup {
public HandoffToShooter(Intake intake, Shooter shooter) { | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands.actions;
public class HandoffToShooter extends SequentialCommandGroup {
public HandoffToShooter(Intake intake, Shooter shooter) { | addCommands(intake.setTargetState(IntakeState.UP), | 1 | 2023-12-30 06:06:45+00:00 | 2k |
NeckitWin/Medallions | src/main/java/net/neckitwin/medallions/common/block/BlockMegaChest.java | [
{
"identifier": "Medallions",
"path": "src/main/java/net/neckitwin/medallions/Medallions.java",
"snippet": "@Mod(modid = MOD_ID, version = VERSION, name = MOD_NAME)\npublic class Medallions {\n public static final String MOD_ID = \"medallions\";\n public static final String MOD_NAME = \"Medallions\";\n public static final String VERSION = \"1.0\";\n\n @SidedProxy(\n clientSide = \"net.neckitwin.medallions.common.ClientProxy\",\n serverSide = \"net.neckitwin.medallions.common.CommonProxy\"\n )\n public static CommonProxy proxy;\n\n @Mod.EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n proxy.preInit(event);\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n proxy.init(event);\n }\n\n @Mod.EventHandler\n public void postInit(FMLPostInitializationEvent event) {\n proxy.postInit(event);\n }\n}"
},
{
"identifier": "ModTab",
"path": "src/main/java/net/neckitwin/medallions/common/handler/ModTab.java",
"snippet": "public class ModTab extends CreativeTabs {\n public static final ModTab INSTANCE = new ModTab();\n\n private ModTab() {\n super(Medallions.MOD_ID);\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public Item getTabIconItem() {\n return ModItems.SHADOWY_MEDALLION;\n }\n}"
},
{
"identifier": "TileMegaChest",
"path": "src/main/java/net/neckitwin/medallions/common/tile/TileMegaChest.java",
"snippet": "public class TileMegaChest extends TileEntity {\n private ItemStack stack;\n private static final String INV_TAG = \"inventory\";\n\n @Override\n public void writeToNBT(NBTTagCompound nbt) {\n super.writeToNBT(nbt);\n\n if (stack != null) {\n NBTTagCompound inventoryTag = new NBTTagCompound();\n stack.writeToNBT(inventoryTag);\n nbt.setTag(INV_TAG, inventoryTag);\n }\n }\n\n @Override\n public void readFromNBT(NBTTagCompound nbt) {\n super.readFromNBT(nbt);\n\n if (nbt.hasKey(INV_TAG, Constants.NBT.TAG_COMPOUND)) {\n NBTTagCompound inventoryTag = nbt.getCompoundTag(INV_TAG);\n stack = ItemStack.loadItemStackFromNBT(inventoryTag);\n }\n }\n\n @Override\n public boolean canUpdate() {\n return false;\n }\n\n public boolean hasStack() {\n return stack != null;\n }\n\n public void handleInputStack(EntityPlayer player, ItemStack stack) {\n // Если в StorageTile есть стек, то выполнится действия со взятием предмета из StorageTile\n if (hasStack()) {\n // Если инвентарь заполнен, то предмет будет выброшен, в ином случае будет добавлен игроку в инвентарь.\n if (!player.inventory.addItemStackToInventory(this.stack)) {\n player.dropPlayerItemWithRandomChoice(this.stack, false);\n } else {\n // Иногда бывает, что предмет не отображается в инвентаре после активации блока, данный код исправляет это.\n player.inventoryContainer.detectAndSendChanges();\n }\n // Очищаем стек из StorageTile\n this.stack = null;\n }\n // Если стек в руке не равен null, то он будет положен в кол-ве 1 шт., в StorageTile\n else if (stack != null) {\n // Создаём копию стека и устанавливаем ей размер в 1 шт.\n ItemStack copy = stack.copy();\n copy.stackSize = 1;\n this.stack = copy;\n // Убираем один предмет из инвентаря игрока.\n --stack.stackSize;\n }\n // Не забываем пометить Tile Entity как \"грязный\", чтобы игра сохранила наши данные.\n markDirty();\n }\n}"
}
] | import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.neckitwin.medallions.Medallions;
import net.neckitwin.medallions.common.handler.ModTab;
import net.neckitwin.medallions.common.tile.TileMegaChest; | 1,205 | package net.neckitwin.medallions.common.block;
public class BlockMegaChest extends BlockContainer {
public BlockMegaChest() {
super(Material.wood);
setBlockName("megachest");
setBlockTextureName(Medallions.MOD_ID + ":megachest");
setCreativeTab(ModTab.INSTANCE);
}
@Override
public TileEntity createNewTileEntity(World world, int metadata) { | package net.neckitwin.medallions.common.block;
public class BlockMegaChest extends BlockContainer {
public BlockMegaChest() {
super(Material.wood);
setBlockName("megachest");
setBlockTextureName(Medallions.MOD_ID + ":megachest");
setCreativeTab(ModTab.INSTANCE);
}
@Override
public TileEntity createNewTileEntity(World world, int metadata) { | return new TileMegaChest(); | 2 | 2023-12-29 23:19:12+00:00 | 2k |
373675032/kaka-shop | src/main/java/world/xuewei/service/impl/CollectionServiceImpl.java | [
{
"identifier": "Collection",
"path": "src/main/java/world/xuewei/entity/Collection.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class Collection implements Serializable {\n\n private static final long serialVersionUID = -94320018064732696L;\n\n /**\n * 主键ID\n */\n private Integer id;\n\n /**\n * 用户ID\n */\n private Integer userId;\n\n /**\n * 商品ID\n */\n private Integer commodityId;\n\n /**\n * 收藏时间\n */\n private Date addTime;\n\n}"
},
{
"identifier": "BaseService",
"path": "src/main/java/world/xuewei/service/BaseService.java",
"snippet": "public class BaseService {\n\n @Resource\n protected AddressMapper addressMapper;\n\n @Resource\n protected CartMapper cartMapper;\n\n @Resource\n protected ClassifyMapper classifyMapper;\n\n @Resource\n protected CollectionMapper collectionMapper;\n\n @Resource\n protected CommodityCommentMapper commodityCommentMapper;\n\n @Resource\n protected CommodityMapper commodityMapper;\n\n @Resource\n protected OrderMapper orderMapper;\n\n @Resource\n protected UserMapper userMapper;\n\n}"
},
{
"identifier": "CollectionService",
"path": "src/main/java/world/xuewei/service/CollectionService.java",
"snippet": "public interface CollectionService {\n\n /**\n * @param collection 实例对象\n * @return 是否成功\n * 添加Collection\n */\n boolean insert(Collection collection);\n\n /**\n * @param id 主键\n * @return 是否成功\n * 删除Collection\n */\n boolean deleteById(Integer id);\n\n /**\n * @param id 主键\n * @return 实例对象\n * 查询单条数据\n */\n Collection getById(Integer id);\n\n /**\n * @return 对象列表\n * 查询全部数据\n * 分页使用MyBatis的插件实现\n */\n List<Collection> listCollections();\n\n /**\n * @param collection 实例对象\n * @return 对象列表\n * 实体作为筛选条件查询数据\n */\n List<Collection> listCollections(Collection collection);\n\n /**\n * @param collection 实例对象\n * @return 结果数量\n * 实体作为筛选条件获取结果数量\n */\n int countCollections(Collection collection);\n\n /**\n * @param collection 实例对象\n * @return 是否成功\n * 修改数据,哪个属性不为空就修改哪个属性\n */\n boolean update(Collection collection);\n\n}"
}
] | import org.springframework.stereotype.Service;
import world.xuewei.entity.Collection;
import world.xuewei.service.BaseService;
import world.xuewei.service.CollectionService;
import java.util.List; | 780 | package world.xuewei.service.impl;
/**
* @author XUEW
* @ClassName CollectionServiceImpl
* 收藏表(Collection)表业务接口实现类
* @date 2021-02-28 21:07:19
* @Version 1.0
**/
@Service("collectionService")
public class CollectionServiceImpl extends BaseService implements CollectionService {
@Override | package world.xuewei.service.impl;
/**
* @author XUEW
* @ClassName CollectionServiceImpl
* 收藏表(Collection)表业务接口实现类
* @date 2021-02-28 21:07:19
* @Version 1.0
**/
@Service("collectionService")
public class CollectionServiceImpl extends BaseService implements CollectionService {
@Override | public boolean insert(Collection collection) { | 0 | 2023-12-27 15:17:13+00:00 | 2k |
fatorius/DUCO-Android-Miner | DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/threads/MiningThread.java | [
{
"identifier": "DUCOS1Hasher",
"path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/algorithms/DUCOS1Hasher.java",
"snippet": "public class DUCOS1Hasher {\n private int lastNonce;\n private float hashingTimeDeltaSeconds;\n\n public DUCOS1Hasher(){\n }\n\n public int mine(String lastHash, String expectedHash, int difficulty, float efficiency){\n float hashingStartTimeSeconds = SystemClock.elapsedRealtime() / 1000.0f;\n\n lastNonce = findNonce(lastHash, expectedHash, difficulty, efficiency);\n float hashingEndTimeSeconds = SystemClock.elapsedRealtime() / 1000.0f;\n\n hashingTimeDeltaSeconds = hashingEndTimeSeconds - hashingStartTimeSeconds;\n\n return lastNonce;\n }\n\n public native int findNonce(String lastHash, String expectedHash, int difficulty, float efficiency);\n\n public float getTimeElapsed(){\n return hashingTimeDeltaSeconds;\n }\n\n public float getHashrate(){\n return lastNonce / (hashingTimeDeltaSeconds);\n }\n}"
},
{
"identifier": "MinerInfo",
"path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/infos/MinerInfo.java",
"snippet": "public class MinerInfo {\n public static String MINER_NAME = \"Fatorius' Android Miner\";\n}"
},
{
"identifier": "Client",
"path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/tcp/Client.java",
"snippet": "public class Client {\n String ip;\n int port;\n\n Socket socket;\n PrintWriter socketSender;\n BufferedReader socketReader;\n\n public Client(String ip, int port) throws IOException {\n this.ip = ip;\n this.port = port;\n\n socket = new Socket(ip, port);\n\n socketSender = new PrintWriter(socket.getOutputStream(), true);\n socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n\n Log.d(\"Socket connection\", \"TCP connection started to \" + ip + \":\" + port);\n\n send(\"PING\");\n socketReader.readLine();\n }\n\n public void send(String msg){\n Log.d(\"Sending to socket\", msg);\n socketSender.println(msg);\n }\n\n public String readLine() throws IOException {\n String receivedMsg = socketReader.readLine();\n\n if (receivedMsg == null){\n this.restartConnection();\n receivedMsg = \"Connection restarted\";\n }\n\n Log.d(\"Received from socket\", receivedMsg);\n\n return receivedMsg;\n }\n\n public void closeConnection() throws IOException {\n socket.close();\n socketSender.close();\n socketReader.close();\n\n Log.d(\"Socket connection ended\", \"Connection exit\");\n }\n\n public void restartConnection() throws IOException {\n Log.d(\"Socket connection restarted\", \"Connection restarting\");\n\n socket.close();\n socketSender.close();\n socketReader.close();\n\n socket = new Socket(ip, port);\n\n socketSender = new PrintWriter(socket.getOutputStream(), true);\n socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n\n send(\"PING\");\n socketReader.readLine();\n }\n}"
}
] | import android.os.Build;
import android.util.Log;
import com.fatorius.duinocoinminer.algorithms.DUCOS1Hasher;
import com.fatorius.duinocoinminer.infos.MinerInfo;
import com.fatorius.duinocoinminer.tcp.Client;
import java.io.IOException; | 892 | package com.fatorius.duinocoinminer.threads;
public class MiningThread implements Runnable{
static{
System.loadLibrary("ducohasher");
}
public final static String MINING_THREAD_NAME_ID = "duinocoin_mining_thread";
String ip;
int port;
int threadNo;
| package com.fatorius.duinocoinminer.threads;
public class MiningThread implements Runnable{
static{
System.loadLibrary("ducohasher");
}
public final static String MINING_THREAD_NAME_ID = "duinocoin_mining_thread";
String ip;
int port;
int threadNo;
| Client tcpClient; | 2 | 2023-12-27 06:00:05+00:00 | 2k |
tommyskeff/JObserve | src/main/java/dev/tommyjs/jobserve/observer/ObserverEmitter.java | [
{
"identifier": "ObserverEmitterImpl",
"path": "src/main/java/dev/tommyjs/jobserve/observer/impl/ObserverEmitterImpl.java",
"snippet": "public class ObserverEmitterImpl implements ObserverEmitter {\n\n private final Random random;\n private final @NotNull Map<ObserverKey, AtomicReference<Set<ObserverSubscription>>> observers;\n\n public ObserverEmitterImpl() {\n this.random = new SecureRandom();\n this.observers = new ConcurrentHashMap<>();\n }\n\n protected @NotNull ObserverSubscription observe0(@NotNull ObserverKey key, @NotNull Consumer<Object> consumer) {\n ObserverSubscription subscription = new ObserverSubscriptionImpl(this, random.nextInt(), key, consumer);\n\n observers.compute(key, (_k, ref) -> {\n if (ref == null) {\n ref = new AtomicReference<>(new HashSet<>());\n }\n\n ref.get().add(subscription);\n return ref;\n });\n\n return subscription;\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public <T> @NotNull ObserverSubscription observe(@NotNull MonoKey<T> key, @NotNull Consumer<T> consumer) {\n return observe0(key, o -> consumer.accept((T) o));\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public <K, V> @NotNull ObserverSubscription observe(@NotNull DuplexKey<K, V> key, @NotNull BiConsumer<K, V> consumer) {\n return observe0(key, o -> {\n Object[] objects = (Object[]) o;\n consumer.accept((K) objects[0], (V) objects[1]);\n });\n }\n\n protected void emit0(@NotNull ObserverKey key, @Nullable Object value) {\n observers.compute(key, (_k, ref) -> {\n if (ref == null) {\n return null;\n }\n\n for (ObserverSubscription subscription : ref.get()) {\n subscription.getConsumer().accept(value);\n }\n\n return ref;\n });\n }\n\n @Override\n public <T> void emit(@NotNull MonoKey<T> key, @Nullable T value) {\n emit0(key, value);\n }\n\n @Override\n public <K, V> void emit(@NotNull DuplexKey<K, V> key, @Nullable K value1, @Nullable V value2) {\n emit0(key, new Object[]{value1, value2});\n }\n\n @Override\n public void cancel(@NotNull ObserverSubscription subscription) {\n observers.compute(subscription.getKey(), (key, ref) -> {\n if (ref != null) {\n ref.get().remove(subscription);\n }\n\n return ref;\n });\n }\n\n}"
},
{
"identifier": "DuplexKey",
"path": "src/main/java/dev/tommyjs/jobserve/observer/key/DuplexKey.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic final class DuplexKey<K, V> extends ObserverKey {\n\n private final @NotNull Class<K> type1;\n private final @NotNull Class<V> type2;\n\n private DuplexKey(int keyId, @NotNull Class<K> type1, @NotNull Class<V> type2) {\n super(keyId);\n this.type1 = type1;\n this.type2 = type2;\n }\n\n public @NotNull Class<K> getType1() {\n return type1;\n }\n\n public @NotNull Class<V> getType2() {\n return type2;\n }\n\n public static <K, V> DuplexKey<K, V> register(@NotNull Class<K> type1, @NotNull Class<V> type2) {\n return new DuplexKey<>(RANDOM.nextInt(), type1, type2);\n }\n\n}"
},
{
"identifier": "MonoKey",
"path": "src/main/java/dev/tommyjs/jobserve/observer/key/MonoKey.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic final class MonoKey<T> extends ObserverKey {\n\n private final @NotNull Class<T> type;\n\n private MonoKey(int keyId, @NotNull Class<T> type) {\n super(keyId);\n this.type = type;\n }\n\n public @NotNull Class<T> getType() {\n return type;\n }\n\n public static <T> @NotNull MonoKey<T> register(@NotNull Class<T> type) {\n return new MonoKey<>(RANDOM.nextInt(), type);\n }\n\n}"
}
] | import dev.tommyjs.jobserve.observer.impl.ObserverEmitterImpl;
import dev.tommyjs.jobserve.observer.key.DuplexKey;
import dev.tommyjs.jobserve.observer.key.MonoKey;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.function.BiConsumer;
import java.util.function.Consumer; | 1,130 | package dev.tommyjs.jobserve.observer;
public interface ObserverEmitter {
<T> @NotNull ObserverSubscription observe(@NotNull MonoKey<T> key, @NotNull Consumer<T> consumer);
| package dev.tommyjs.jobserve.observer;
public interface ObserverEmitter {
<T> @NotNull ObserverSubscription observe(@NotNull MonoKey<T> key, @NotNull Consumer<T> consumer);
| <K, V> @NotNull ObserverSubscription observe(@NotNull DuplexKey<K, V> key, @NotNull BiConsumer<K, V> consumer); | 1 | 2023-12-26 17:02:45+00:00 | 2k |
fanxiaoning/framifykit | framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/domain/res/KD100QueryTrackRes.java | [
{
"identifier": "BaseRes",
"path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/domain/res/BaseRes.java",
"snippet": "@Data\npublic class BaseRes {\n\n}"
},
{
"identifier": "KD100QueryTrackDataDetail",
"path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/domain/res/dto/KD100QueryTrackDataDetail.java",
"snippet": "@Data\n@Builder\n@AllArgsConstructor\npublic class KD100QueryTrackDataDetail {\n /**\n * 时间,原始格式\n */\n private String time;\n /**\n * 物流轨迹节点内容\n */\n private String context;\n /**\n * 标题\n */\n private String title;\n /**\n * 格式化后时间\n */\n private String ftime;\n /**\n * 行政区域的编码\n */\n private String areaCode;\n /**\n * 行政区域的名称\n */\n private String areaName;\n /**\n * 签收状态 (0在途,1揽收,2疑难,3签收,4退签,5派件,6退回,7转投)\n */\n private String status;\n\n public KD100QueryTrackDataDetail() {\n }\n\n public KD100QueryTrackDataDetail(KD100QueryTraceData traceDTO) {\n this.time = traceDTO.getOpeTime();\n this.context = traceDTO.getOpeRemark();\n this.ftime = DateUtil.format(DateUtil.parse(time, \"yyyy/MM/dd HH:mm:ss\"), \"yyyy-MM-dd HH:mm:ss\");\n this.title = traceDTO.getOpeTitle();\n }\n}"
},
{
"identifier": "KD100QueryTrackRouteInfo",
"path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/domain/res/dto/KD100QueryTrackRouteInfo.java",
"snippet": "@Data\n@Builder\n@AllArgsConstructor\npublic class KD100QueryTrackRouteInfo {\n /**\n * 出发位置\n */\n private KD100QueryTrackPosition from;\n /**\n * 当前位置\n */\n private KD100QueryTrackPosition cur;\n /**\n * 收货地\n */\n private KD100QueryTrackPosition to;\n}"
}
] | import com.framifykit.starter.logistics.executor.domain.res.BaseRes;
import com.framifykit.starter.logistics.platform.kd100.domain.res.dto.KD100QueryTrackDataDetail;
import com.framifykit.starter.logistics.platform.kd100.domain.res.dto.KD100QueryTrackRouteInfo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List; | 1,020 | package com.framifykit.starter.logistics.platform.kd100.domain.res;
/**
* <p>
* 快递100 查询物流信息res
* </p>
*
* @author fxn
* @since 1.0.0
**/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class KD100QueryTrackRes extends BaseRes {
/**
* 消息体,请忽略
*/
private String message;
/**
* 快递单号
*/
private String nu;
/**
* 是否签收标记
*/
private String ischeck;
/**
* 快递公司编码,一律用小写字母
*/
private String com;
/**
* 通讯状态
*/
private String status;
/**
* 轨迹详情数组
*/
private List<KD100QueryTrackDataDetail> data = new ArrayList<>();
/**
* 快递单当前状态,包括0在途,1揽收,2疑难,3签收,4退签,5派件,6退回,7转投,10待清关,11清关中,12已清关,13清关异常,14拒签 等13个状态
*/
private String state;
/**
* 快递单明细状态标记
*/
private String condition;
| package com.framifykit.starter.logistics.platform.kd100.domain.res;
/**
* <p>
* 快递100 查询物流信息res
* </p>
*
* @author fxn
* @since 1.0.0
**/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class KD100QueryTrackRes extends BaseRes {
/**
* 消息体,请忽略
*/
private String message;
/**
* 快递单号
*/
private String nu;
/**
* 是否签收标记
*/
private String ischeck;
/**
* 快递公司编码,一律用小写字母
*/
private String com;
/**
* 通讯状态
*/
private String status;
/**
* 轨迹详情数组
*/
private List<KD100QueryTrackDataDetail> data = new ArrayList<>();
/**
* 快递单当前状态,包括0在途,1揽收,2疑难,3签收,4退签,5派件,6退回,7转投,10待清关,11清关中,12已清关,13清关异常,14拒签 等13个状态
*/
private String state;
/**
* 快递单明细状态标记
*/
private String condition;
| private KD100QueryTrackRouteInfo routeInfo; | 2 | 2023-12-31 03:48:33+00:00 | 2k |
yangpluseven/Simulate-Something | simulation/src/simulator/GridMap.java | [
{
"identifier": "Constants",
"path": "simulation/src/constants/Constants.java",
"snippet": "public class Constants {\n\n\tpublic static final Size INIT_GRID_SIZE = new Size(10, 10);\n\tpublic static final Size NUM_OF_COL_ROW = new Size(50, 30);\n\tpublic static final int BACKGROUND_Z_ORDER = 0;\n\tpublic static final int TERRAIN_BOTTOM_Z_ORDER = 1;\n\tpublic static final int CREATURE_BOTTOM_Z_ORDER = 6;\n\tpublic static final boolean ZOOM_IN = true;\n\tpublic static final boolean ZOOM_OUT = false;\n\t\n}"
},
{
"identifier": "Location",
"path": "simulation/src/entities/Location.java",
"snippet": "public class Location extends Pair<Integer, Integer> implements Comparable<Pair<Integer, Integer>> {\n\n\t/**\n\t * Default constructor.\n\t */\n\tpublic Location() {\n\t\tleft = 0;\n\t\tright = 0;\n\t}\n\n\t/**\n\t * Represent a row and column.\n\t * \n\t * @param row The row.\n\t * @param col The column.\n\t */\n\tpublic Location(int col, int row) {\n\t\tleft = col;\n\t\tright = row;\n\t}\n\n\t/**\n\t * Update the location.\n\t * \n\t * @param row\n\t * @param col\n\t */\n\tpublic void update(int col, int row) {\n\t\tleft = col;\n\t\tright = row;\n\t}\n\n\t/**\n\t * @return The column.\n\t */\n\tpublic int getCol() {\n\t\treturn left;\n\t}\n\n\t/**\n\t * @return The row.\n\t */\n\tpublic int getRow() {\n\t\treturn right;\n\t}\n\n\t@Override\n\tpublic int compareTo(Pair<Integer, Integer> o) {\n\t\treturn this.left == o.left ? this.right - o.right : this.left - o.left;\n\t}\n\n}"
},
{
"identifier": "Pair",
"path": "simulation/src/entities/Pair.java",
"snippet": "public class Pair<L, R> implements Entry<L, R> {\n\n\tprotected L left;\n\tprotected R right;\n\n\tpublic Pair() {\n\t}\n\n\tpublic Pair(L left, R right) {\n\t\tthis.left = left;\n\t\tthis.right = right;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn (left == null ? 0 : left.hashCode()) ^ (right == null ? 0 : right.hashCode());\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj instanceof Pair) {\n\t\t\tPair<?, ?> other = (Pair<?, ?>) obj;\n\t\t\treturn left == other.getLeft() && right == other.getRight();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"(\" + left.toString() + right.toString() + \")\";\n\t}\n\n\t@Override\n\tpublic L getKey() {\n\t\treturn left;\n\t}\n\n\t@Override\n\tpublic R getValue() {\n\t\treturn right;\n\t}\n\n\t@Override\n\tpublic R setValue(R value) {\n\t\tR former = right;\n\t\tright = value;\n\t\treturn former;\n\t}\n\n\tpublic L getLeft() {\n\t\treturn left;\n\t}\n\n\tpublic void setLeft(L left) {\n\t\tthis.left = left;\n\t}\n\n\tpublic R getRight() {\n\t\treturn right;\n\t}\n\n\tpublic void setRight(R right) {\n\t\tthis.right = right;\n\t}\n\n}"
},
{
"identifier": "SimuObject",
"path": "simulation/src/entities/SimuObject.java",
"snippet": "public abstract class SimuObject {\n\t\n\tprotected Painter painter;\n\tprotected GridMap gridMap;\n\tprotected Location location;\n\tprotected Color color;\n\t\n\tpublic SimuObject() {\n\t\t// TODO SimuObject constructor\n\t}\n\t\n\tpublic void moveTo(Location location) {\n\t\tgridMap.remove(this.location);\n\t\tthis.location = location;\n\t\tgridMap.addObjectAt(this, location);\n\t}\n\t\n\tpublic Color getColor() {\n\t\treturn color;\n\t}\n\n\tpublic Painter getPainter() {\n\t\treturn painter;\n\t}\n\n\tpublic Location getLocation() {\n\t\treturn location;\n\t}\n\t\n\tpublic abstract void forward();\n\n}"
},
{
"identifier": "Size",
"path": "simulation/src/entities/Size.java",
"snippet": "public class Size extends Pair<Integer, Integer> implements Comparable<Pair<Integer, Integer>> {\n\n\t/**\n\t * Default constructor.\n\t */\n\tpublic Size() {\n\t\tleft = 0;\n\t\tright = 0;\n\t}\n\n\t/**\n\t * Represent a width and height.\n\t * \n\t * @param width\n\t * @param height\n\t */\n\tpublic Size(int width, int height) {\n\t\tleft = width;\n\t\tright = height;\n\t}\n\n\t/**\n\t * Update the size.\n\t * \n\t * @param width\n\t * @param height\n\t */\n\tpublic void update(int width, int height) {\n\t\tleft = width;\n\t\tright = height;\n\t}\n\n\t/**\n\t * @return width\n\t */\n\tpublic int getWidth() {\n\t\treturn left;\n\t}\n\n\t/**\n\t * @return height\n\t */\n\tpublic int getHeight() {\n\t\treturn right;\n\t}\n\n\t@Override\n\tpublic int compareTo(Pair<Integer, Integer> o) {\n\t\treturn this.left == o.left ? this.right - o.right : this.left - o.left;\n\t}\n\n}"
}
] | import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import constants.Constants;
import entities.Location;
import entities.Pair;
import entities.SimuObject;
import entities.Size; | 1,464 | package simulator;
/**
* GridMap takes up all the SimuObjects in the simulation.
*
* @author pluseven
*/
public class GridMap implements Map<Location, simulator.GridMap.Grid> {
private Grid[][] grids;
private Size numCR;
private int numOfObjs;
/**
* Default constructor.
*/
public GridMap() { | package simulator;
/**
* GridMap takes up all the SimuObjects in the simulation.
*
* @author pluseven
*/
public class GridMap implements Map<Location, simulator.GridMap.Grid> {
private Grid[][] grids;
private Size numCR;
private int numOfObjs;
/**
* Default constructor.
*/
public GridMap() { | numCR = Constants.NUM_OF_COL_ROW; | 0 | 2023-12-23 13:51:12+00:00 | 2k |
zxx1119/best-adrules | src/main/java/org/fordes/adg/rule/AdgRuleApplication.java | [
{
"identifier": "OutputConfig",
"path": "src/main/java/org/fordes/adg/rule/config/OutputConfig.java",
"snippet": "@Data\n@Component\n@ConfigurationProperties(prefix = \"application.output\")\npublic class OutputConfig {\n\n /**\n * 输出文件路径\n */\n private String path;\n\n /**\n * 输出文件列表\n */\n private Map<String, List<RuleType>> files;\n}"
},
{
"identifier": "RuleConfig",
"path": "src/main/java/org/fordes/adg/rule/config/RuleConfig.java",
"snippet": "@Data\n@Component\n@ConfigurationProperties(prefix = \"application.rule\")\npublic class RuleConfig {\n\n /**\n * 远程规则,http或https\n */\n private List<String> remote;\n\n /**\n * 本地规则\n */\n private List<String> local;\n}"
},
{
"identifier": "RuleType",
"path": "src/main/java/org/fordes/adg/rule/enums/RuleType.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic enum RuleType {\n\n /**\n * 域名规则,形如 xxx.com、xx.oo.com\n */\n DOMAIN(\"域名规则\", true, null, new String[]{\"^([\\\\w,\\\\d,-]+\\\\.)+[\\\\w,\\\\d,-]+(\\\\^$)?$\"}, null),\n\n /**\n * Hosts规则\n */\n HOSTS(\"Hosts规则\", true, null, new String[]{\"^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\s+.*$\"}, null),\n\n /**\n * 正则规则,包含修饰规则\n */\n REGEX(\"正则规则\", true, null, new String[]{},\n new String[]{\"[/,#,&,=,:]\", \"^[\\\\*,@,\\\\-,_,\\\\.,&,\\\\?]\",\"[\\\\$][^\\\\s]\", \"[\\\\^][^\\\\s]\"}),\n\n\n /**\n * 修饰规则,不被adGuardHome支持\n */\n MODIFY(\"修饰规则\", false, null, null, null)\n ;\n\n\n /**\n * 描述\n */\n private final String desc;\n\n /**\n * 支持性,true则adGuardHome支持\n */\n private final boolean usually;\n\n /**\n * 识别标识,包含即通过\n */\n private final String[] identify;\n\n /**\n * 正向 正则,匹配一个即为通过\n */\n private final String[] match;\n\n /**\n * 排除 正则,全部不匹配即为通过\n */\n private final String[] exclude;\n}"
},
{
"identifier": "LocalRuleThread",
"path": "src/main/java/org/fordes/adg/rule/thread/LocalRuleThread.java",
"snippet": "public class LocalRuleThread extends AbstractRuleThread {\n\n\n public LocalRuleThread(String ruleUrl, Map<RuleType, Set<File>> typeFileMap, BloomFilter<String> filter) {\n super(ruleUrl, typeFileMap, filter);\n }\n\n @Override\n InputStream getContentStream() {\n return FileUtil.getInputStream(getRuleUrl());\n }\n}"
},
{
"identifier": "RemoteRuleThread",
"path": "src/main/java/org/fordes/adg/rule/thread/RemoteRuleThread.java",
"snippet": "@Slf4j\npublic class RemoteRuleThread extends AbstractRuleThread {\n\n\n public RemoteRuleThread(String ruleUrl, Map<RuleType, Set<File>> typeFileMap, BloomFilter<String> filter) {\n super(ruleUrl, typeFileMap, filter);\n }\n\n @Override\n InputStream getContentStream() {\n try {\n HttpResponse response = HttpRequest.get(getRuleUrl())\n .setFollowRedirects(true)\n .timeout(20000)\n .execute();\n if (response.isOk()) {\n setCharset(Charset.forName(response.charset()));\n return response.bodyStream();\n }\n }catch (Exception e) {\n log.error(getRuleUrl());\n log.error(ExceptionUtil.stacktraceToString(e));\n }\n return IoUtil.toStream(new byte[0]);\n }\n\n}"
}
] | import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.thread.ExecutorBuilder;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.fordes.adg.rule.config.OutputConfig;
import org.fordes.adg.rule.config.RuleConfig;
import org.fordes.adg.rule.enums.RuleType;
import org.fordes.adg.rule.thread.LocalRuleThread;
import org.fordes.adg.rule.thread.RemoteRuleThread;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import java.io.File;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor; | 1,530 | package org.fordes.adg.rule;
@Slf4j
@Component
@AllArgsConstructor
@SpringBootApplication
public class AdgRuleApplication implements ApplicationRunner {
private final static int N = Runtime.getRuntime().availableProcessors();
private final RuleConfig ruleConfig;
private final OutputConfig outputConfig;
private final ThreadPoolExecutor executor = ExecutorBuilder.create()
.setCorePoolSize(2 * N)
.setMaxPoolSize(2 * N)
.setHandler(new ThreadPoolExecutor.CallerRunsPolicy())
.build();
@Override
public void run(ApplicationArguments args) throws Exception {
TimeInterval interval = DateUtil.timer();
// 初始化,根据配置建立文件
final Map<RuleType, Set<File>> typeFileMap = MapUtil.newHashMap();
if (!outputConfig.getFiles().isEmpty()) {
outputConfig.getFiles().forEach((fileName, types) -> {
File file = Util.createFile(outputConfig.getPath() + File.separator + fileName);
types.forEach(type -> Util.safePut(typeFileMap, type, Util.createFile(file)));
});
}
//使用布隆过滤器实现去重
BloomFilter<String> filter = BloomFilter
.create(Funnels.stringFunnel(Charset.defaultCharset()), 1000000);
//远程规则
ruleConfig.getRemote().stream()
.filter(StrUtil::isNotBlank)
.map(URLUtil::normalize) | package org.fordes.adg.rule;
@Slf4j
@Component
@AllArgsConstructor
@SpringBootApplication
public class AdgRuleApplication implements ApplicationRunner {
private final static int N = Runtime.getRuntime().availableProcessors();
private final RuleConfig ruleConfig;
private final OutputConfig outputConfig;
private final ThreadPoolExecutor executor = ExecutorBuilder.create()
.setCorePoolSize(2 * N)
.setMaxPoolSize(2 * N)
.setHandler(new ThreadPoolExecutor.CallerRunsPolicy())
.build();
@Override
public void run(ApplicationArguments args) throws Exception {
TimeInterval interval = DateUtil.timer();
// 初始化,根据配置建立文件
final Map<RuleType, Set<File>> typeFileMap = MapUtil.newHashMap();
if (!outputConfig.getFiles().isEmpty()) {
outputConfig.getFiles().forEach((fileName, types) -> {
File file = Util.createFile(outputConfig.getPath() + File.separator + fileName);
types.forEach(type -> Util.safePut(typeFileMap, type, Util.createFile(file)));
});
}
//使用布隆过滤器实现去重
BloomFilter<String> filter = BloomFilter
.create(Funnels.stringFunnel(Charset.defaultCharset()), 1000000);
//远程规则
ruleConfig.getRemote().stream()
.filter(StrUtil::isNotBlank)
.map(URLUtil::normalize) | .forEach(e -> executor.execute(new RemoteRuleThread(e, typeFileMap, filter))); | 4 | 2023-12-30 04:47:07+00:00 | 2k |
bmarwell/sipper | impl/src/main/java/io/github/bmarwell/sipper/impl/SocketInConnectionReader.java | [
{
"identifier": "QueueingSipIncomingMessageHandler",
"path": "impl/src/main/java/io/github/bmarwell/sipper/impl/proto/QueueingSipIncomingMessageHandler.java",
"snippet": "public class QueueingSipIncomingMessageHandler implements SipIncomingMessageHandler {\n\n private static final Logger LOG = LoggerFactory.getLogger(QueueingSipIncomingMessageHandler.class);\n\n private final ArrayList<RawSipMessage> messages = new ArrayList<>();\n\n @Override\n public void accept(RawSipMessage sipMessage) {\n LOG.trace(\"Incoming message:\\n[{}]\", sipMessage);\n\n switch (sipMessage.method()) {\n case \"REGISTER\":\n this.messages.add(sipMessage);\n break;\n case \"INVITE\":\n default:\n throw new UnsupportedOperationException(\n \"not yet implemented: [io.github.bmarwell.sipper.impl.proto.QueueingSipIncomingMessageHandler::accept].\");\n }\n }\n\n public List<RawSipMessage> getMessages() {\n return List.copyOf(this.messages);\n }\n\n public void remove(RawSipMessage message) {\n this.messages.remove(message);\n }\n}"
},
{
"identifier": "LangUtil",
"path": "impl/src/main/java/io/github/bmarwell/sipper/impl/util/LangUtil.java",
"snippet": "public final class LangUtil {\n\n public static OptionalInt isIntegerOrEmpty(String maybeNumber) {\n try {\n final var parsedLong = Integer.parseInt(maybeNumber);\n return OptionalInt.of(parsedLong);\n } catch (NumberFormatException nfe) {\n return OptionalInt.empty();\n }\n }\n}"
}
] | import io.github.bmarwell.sipper.impl.proto.QueueingSipIncomingMessageHandler;
import io.github.bmarwell.sipper.impl.proto.RawSipMessage;
import io.github.bmarwell.sipper.impl.util.LangUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 1,221 | /*
* Copyright (C) 2023-2024 The SIPper project team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.bmarwell.sipper.impl;
public class SocketInConnectionReader implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(SocketInConnectionReader.class);
private ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();
private final BufferedReader socketReader;
private final QueueingSipIncomingMessageHandler msgHandler;
private boolean interrupted = false;
public SocketInConnectionReader(InputStream socketInput, QueueingSipIncomingMessageHandler msgHandler) {
this.socketReader = new BufferedReader(new InputStreamReader(socketInput));
this.msgHandler = msgHandler;
}
@Override
public void run() {
StringBuilder currentMessage = new StringBuilder();
String readLine;
try {
checkInterrupted();
LOG.trace("Now listening for incoming messages");
while (!this.interrupted && (readLine = this.socketReader.readLine()) != null) {
checkInterrupted();
if (this.interrupted) {
return;
}
currentMessage.append(readLine);
currentMessage.append('\n');
final var currentMessageString = currentMessage.toString();
if (currentMessageString.endsWith("\n\n")) {
checkInterrupted();
LOG.trace("Received message:\n[{}]", currentMessage);
final RawSipMessage rawSipMessage;
// probably end of message, UNLESS it is a header with a following body.
if (isMessageWithBody(currentMessageString)) {
LOG.trace("Message with body");
rawSipMessage = processMessageWithBody(currentMessageString);
} else {
rawSipMessage = new RawSipMessage(currentMessageString);
}
try {
CompletableFuture.runAsync(() -> this.msgHandler.accept(rawSipMessage), executorService);
} catch (Exception e) {
LOG.trace("Unable to process message.", e);
}
currentMessage = new StringBuilder();
}
}
} catch (SocketException se) {
// probably OK...
Thread.currentThread().interrupt();
} catch (IOException ioException) {
LOG.error("Problem while reading input from socket.", ioException);
} catch (InterruptedException interruptedException) {
// all ok, nothing to clean up.
Thread.currentThread().interrupt();
}
}
private static boolean isMessageWithBody(String currentMessageString) {
return currentMessageString.startsWith("INVITE")
&& currentMessageString.contains("\nContent-Length: ")
&& !currentMessageString.contains("\nContent-Length: 0\n");
}
private RawSipMessage processMessageWithBody(String currentMessageString) throws IOException {
final String bodyLengthString = currentMessageString
.lines()
.filter(line -> line.startsWith("Content-Length: "))
.findFirst()
.orElseThrow();
final var bodyLengthNumber = bodyLengthString.split(":", 2)[1].trim(); | /*
* Copyright (C) 2023-2024 The SIPper project team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.bmarwell.sipper.impl;
public class SocketInConnectionReader implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(SocketInConnectionReader.class);
private ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();
private final BufferedReader socketReader;
private final QueueingSipIncomingMessageHandler msgHandler;
private boolean interrupted = false;
public SocketInConnectionReader(InputStream socketInput, QueueingSipIncomingMessageHandler msgHandler) {
this.socketReader = new BufferedReader(new InputStreamReader(socketInput));
this.msgHandler = msgHandler;
}
@Override
public void run() {
StringBuilder currentMessage = new StringBuilder();
String readLine;
try {
checkInterrupted();
LOG.trace("Now listening for incoming messages");
while (!this.interrupted && (readLine = this.socketReader.readLine()) != null) {
checkInterrupted();
if (this.interrupted) {
return;
}
currentMessage.append(readLine);
currentMessage.append('\n');
final var currentMessageString = currentMessage.toString();
if (currentMessageString.endsWith("\n\n")) {
checkInterrupted();
LOG.trace("Received message:\n[{}]", currentMessage);
final RawSipMessage rawSipMessage;
// probably end of message, UNLESS it is a header with a following body.
if (isMessageWithBody(currentMessageString)) {
LOG.trace("Message with body");
rawSipMessage = processMessageWithBody(currentMessageString);
} else {
rawSipMessage = new RawSipMessage(currentMessageString);
}
try {
CompletableFuture.runAsync(() -> this.msgHandler.accept(rawSipMessage), executorService);
} catch (Exception e) {
LOG.trace("Unable to process message.", e);
}
currentMessage = new StringBuilder();
}
}
} catch (SocketException se) {
// probably OK...
Thread.currentThread().interrupt();
} catch (IOException ioException) {
LOG.error("Problem while reading input from socket.", ioException);
} catch (InterruptedException interruptedException) {
// all ok, nothing to clean up.
Thread.currentThread().interrupt();
}
}
private static boolean isMessageWithBody(String currentMessageString) {
return currentMessageString.startsWith("INVITE")
&& currentMessageString.contains("\nContent-Length: ")
&& !currentMessageString.contains("\nContent-Length: 0\n");
}
private RawSipMessage processMessageWithBody(String currentMessageString) throws IOException {
final String bodyLengthString = currentMessageString
.lines()
.filter(line -> line.startsWith("Content-Length: "))
.findFirst()
.orElseThrow();
final var bodyLengthNumber = bodyLengthString.split(":", 2)[1].trim(); | final var bodyLengthOpt = LangUtil.isIntegerOrEmpty(bodyLengthNumber); | 1 | 2023-12-28 13:13:07+00:00 | 2k |
Deenu143/GradleParser | app/src/main/java/org/deenu/gradle/parser/Main.java | [
{
"identifier": "ParserFailedException",
"path": "app/src/main/java/org/deenu/gradle/parser/exception/ParserFailedException.java",
"snippet": "public class ParserFailedException extends Exception {\n\n public ParserFailedException(String message, Throwable t) {\n super(message, t);\n }\n\n public ParserFailedException(Exception exception) {\n super(exception);\n }\n\n public ParserFailedException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "GradleScript",
"path": "app/src/main/java/org/deenu/gradle/script/GradleScript.java",
"snippet": "public class GradleScript {\n\n private File gradleFile;\n private AstBuilder astBuilder;\n private List<ASTNode> aSTNodes;\n private String scriptContents;\n private GradleScriptVisitor gradleScriptVisitor;\n\n public GradleScript(File gradleFile) throws Exception, FileNotFoundException {\n this.gradleFile = gradleFile;\n if (gradleFile == null || !gradleFile.exists()) {\n throw new FileNotFoundException(\"Failed to get '.gradle' or '.gradle.kts' file.\");\n } else if (gradleFile != null) {\n String fileName = gradleFile.getName();\n String[] fileExtensions = new String[] {\".gradle\", \".gradle.kts\"};\n\n if (fileName != null) {\n if (!fileName.endsWith(fileExtensions[0]) && !fileName.endsWith(fileExtensions[1])) {\n throw new UnsupportedFileException(\"Unsupported file: \" + gradleFile.getAbsolutePath());\n }\n }\n }\n\n this.scriptContents = new String(Files.readAllBytes(this.gradleFile.toPath()));\n init(scriptContents, gradleFile);\n }\n\n private void init(String script, File gradleFile) throws Exception {\n if (script == null || script.isEmpty()) {\n throw new Exception(\"Failed to get gradle script from file: \" + gradleFile.getAbsolutePath());\n }\n this.astBuilder = new AstBuilder();\n this.aSTNodes = getASTNodes();\n }\n\n public File getGradleFile() {\n return this.gradleFile;\n }\n\n public String getGradleFileName() {\n return this.gradleFile.getName();\n }\n\n public boolean isGradleBuildFile() {\n return getGradleFileName().startsWith(\"build.gradle\");\n }\n\n public boolean isGradleSettingsFile() {\n return getGradleFileName().startsWith(\"settings.gradle\");\n }\n\n private List<ASTNode> getASTNodes() throws Exception {\n return this.astBuilder.buildFromString(scriptContents);\n }\n\n public List<Plugin> getPlugins() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getPlugins();\n }\n\n public List<Repository> getRepositories() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getRepositories();\n }\n\n public List<Repository> getBuildScriptRepositories() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getBuildScriptRepositories();\n }\n\n public List<Repository> getAllProjectsRepositories() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getAllProjectsRepositories();\n }\n\n public List<FlatDir> getAllProjectsRepositoriesFlatDirDirs() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getAllProjectsRepositoriesFlatDirDirs();\n }\n\n public List<Repository> getPluginManagementRepositories() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getPluginManagementRepositories();\n }\n\n public List<Repository> getDependencyResolutionManagementRepositories() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getDependencyResolutionManagementRepositories();\n }\n\n public List<FlatDir> getDependencyResolutionManagementRepositoriesFlatDirDirs() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getDependencyResolutionManagementRepositoriesFlatDirDirs();\n }\n\n public List<Dependency> getDependencies() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getDependencies();\n }\n\n public List<Dependency> getBuildScriptDependencies() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getBuildScriptDependencies();\n }\n\n public String getRootProjectName() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getRootProjectName();\n }\n\n public List<Include> getIncludes() {\n this.gradleScriptVisitor = new GradleScriptVisitor();\n walkScript(gradleScriptVisitor);\n return this.gradleScriptVisitor.getIncludes();\n }\n\n private void walkScript(GroovyCodeVisitor visitor) {\n for (ASTNode astNode : aSTNodes) {\n astNode.visit(visitor);\n }\n }\n\n public GradleScriptVisitor getGradleScriptVisitor() {\n return this.gradleScriptVisitor;\n }\n}"
}
] | import java.io.File;
import org.deenu.gradle.parser.exception.ParserFailedException;
import org.deenu.gradle.script.GradleScript; | 1,367 | package org.deenu.gradle.parser;
public class Main {
public static void main(String[] args) {
try {
File buildGradle = new File("/storage/emulated/0/test/build.gradle"); | package org.deenu.gradle.parser;
public class Main {
public static void main(String[] args) {
try {
File buildGradle = new File("/storage/emulated/0/test/build.gradle"); | GradleScript gradleScript = new GradleScript(buildGradle); | 1 | 2023-12-27 10:10:31+00:00 | 2k |
refutix/flink-sql-template-jar | flink-sql-runner-common/src/main/java/org/refutix/flink/sql/template/SqlRunner.java | [
{
"identifier": "SqlParseUtil",
"path": "flink-sql-runner-common/src/main/java/org/refutix/flink/sql/template/common/SqlParseUtil.java",
"snippet": "public class SqlParseUtil {\n\n private static final String STATEMENT_DELIMITER = \";\";\n\n private static final String MASK = \"--.*$\";\n\n private static final String BEGINNING_MASK = \"^(\\\\s)*--.*$\";\n\n private SqlParseUtil() {\n\n }\n\n public static Operation parseSingleStatement(Parser parser, String statement) {\n List<Operation> operations;\n try {\n operations = parser.parse(statement);\n } catch (Exception e) {\n throw new SqlParseException(\"Failed to parse sql statement: \" + statement, e);\n }\n if (operations.isEmpty()) {\n throw new SqlParseException(\"Failed to parse sql statement: \" + statement);\n }\n return operations.get(0);\n }\n\n public static String formatSql(String sql) {\n if (sql == null) {\n return \"\";\n }\n String trimmed = sql.trim();\n StringBuilder formatted = new StringBuilder();\n formatted.append(trimmed);\n if (!trimmed.endsWith(STATEMENT_DELIMITER)) {\n formatted.append(\";\");\n }\n return formatted.toString();\n }\n\n public static List<String> splitContent(String content) {\n List<String> statements = new ArrayList<>();\n List<String> buffer = new ArrayList<>();\n for (String line : content.split(\"\\n\")) {\n if (isEndOfStatement(line)) {\n buffer.add(line);\n statements.add(normalize(buffer));\n buffer.clear();\n } else {\n buffer.add(line);\n }\n\n }\n return statements;\n }\n\n private static String normalize(List<String> buffer) {\n return buffer.stream().map(line -> line.replaceAll(BEGINNING_MASK, \"\"))\n .collect(Collectors.joining(\"\\n\"));\n }\n\n private static boolean isEndOfStatement(String line) {\n return line.replaceAll(MASK, \"\").trim().endsWith(\";\");\n }\n}"
},
{
"identifier": "FlinkSqlProvider",
"path": "flink-sql-runner-common/src/main/java/org/refutix/flink/sql/template/provider/sql/FlinkSqlProvider.java",
"snippet": "public interface FlinkSqlProvider {\n String getSql(Properties properties);\n}"
},
{
"identifier": "FlinkSqlProviderFactory",
"path": "flink-sql-runner-common/src/main/java/org/refutix/flink/sql/template/provider/sql/FlinkSqlProviderFactory.java",
"snippet": "public class FlinkSqlProviderFactory {\n\n public static FlinkSqlProvider getProvider(Properties properties) {\n if (\"file\".equals(properties.get(\"sqlProvider\"))) {\n return new FileFlinkSqlProvider();\n }\n throw new SqlProviderNotFoundException();\n }\n}"
}
] | import java.util.Properties;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.internal.TableEnvironmentInternal;
import org.apache.flink.table.delegation.Parser;
import org.apache.flink.table.operations.Operation;
import org.refutix.flink.sql.template.common.SqlParseUtil;
import org.refutix.flink.sql.template.provider.sql.FlinkSqlProvider;
import org.refutix.flink.sql.template.provider.sql.FlinkSqlProviderFactory;
import java.time.ZoneId;
import java.util.List; | 987 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.refutix.flink.sql.template;
/**
* Main class for executing SQL scripts.
*/
public class SqlRunner {
public static void main(String[] args) {
ParameterTool parameterTool = ParameterTool.fromArgs(args);
Properties properties = parameterTool.getProperties(); | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.refutix.flink.sql.template;
/**
* Main class for executing SQL scripts.
*/
public class SqlRunner {
public static void main(String[] args) {
ParameterTool parameterTool = ParameterTool.fromArgs(args);
Properties properties = parameterTool.getProperties(); | FlinkSqlProvider provider = FlinkSqlProviderFactory.getProvider(properties); | 2 | 2023-12-25 16:29:40+00:00 | 2k |
NickReset/JavaNPM | src/main/java/social/nickrest/npm/module/InstalledNPMPackage.java | [
{
"identifier": "NPM",
"path": "src/main/java/social/nickrest/npm/NPM.java",
"snippet": "@Getter @Setter\npublic class NPM {\n\n public static final String BASE_URL = \"https://registry.npmjs.org\";\n\n private final File nodeModulesDir;\n private NPMLogger logger;\n\n public NPM(File nodeModulesDir) {\n this.nodeModulesDir = nodeModulesDir;\n this.logger = new DefualtNPMLogger();\n }\n\n public NPMPackage getPackage(String name) {\n return new NPMPackage(this, name);\n }\n\n public InstalledNPMPackage getInstalledPackage(String name) {\n File dir = new File(nodeModulesDir, name);\n\n if(!dir.exists()) return null;\n\n return new InstalledNPMPackage(this, dir);\n }\n\n public boolean isOutdated(String name) {\n InstalledNPMPackage installed = getInstalledPackage(name);\n\n if(installed == null) return false;\n\n return installed.getPackageJson() == null || !installed.getVersion().equals(getPackage(name).getVersion());\n }\n\n public boolean isInstalled(String name) {\n InstalledNPMPackage installed = getInstalledPackage(name);\n\n if(installed == null) return false;\n\n return installed.getPackageJson() != null;\n }\n\n}"
},
{
"identifier": "IOUtils",
"path": "src/main/java/social/nickrest/npm/util/IOUtils.java",
"snippet": "@UtilityClass\npublic class IOUtils {\n\n public static String readConnection(@NonNull URLConnection connection) {\n try {\n BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));\n String line;\n StringBuilder response = new StringBuilder();\n\n while ((line = reader.readLine()) != null) {\n response.append(line);\n }\n\n return response.toString();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n public static void downloadConnection(HttpURLConnection connection, File directory) {\n try {\n FileUtils.copyInputStreamToFile(connection.getInputStream(), directory);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public static InputStream getFileStream(File file) {\n try {\n URL url = file.toURI().toURL();\n URLConnection connection = url.openConnection();\n connection.setRequestProperty(\"Accept\", \"application/octet-stream\");\n\n return connection.getInputStream();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n public static void deleteDirectoryAndContents(File file) {\n try {\n FileUtils.deleteDirectory(file);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}"
}
] | import lombok.Getter;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import social.nickrest.npm.NPM;
import social.nickrest.npm.util.IOUtils;
import java.io.File;
import java.io.FileReader;
import java.util.function.Consumer; | 921 | package social.nickrest.npm.module;
@Getter
public class InstalledNPMPackage {
private final NPM parent;
private final File dir;
private JSONObject packageJson;
private NPMPackageData data;
public InstalledNPMPackage(NPM parent, File dir) {
this.parent = parent;
this.dir = dir;
StringBuilder builder = new StringBuilder();
File packageJson = new File(dir, "package.json");
if(!packageJson.exists()) return;
try(FileReader reader = new FileReader(packageJson)) {
int i;
while((i = reader.read()) != -1) {
builder.append((char) i);
}
this.packageJson = (JSONObject) new JSONParser().parse(builder.toString());
this.data = new NPMPackageData((String) this.packageJson.get("version"), (String) this.packageJson.get("name"));
} catch (Exception e) {
e.printStackTrace();
}
}
public void uninstall(Consumer<InstalledNPMPackage> callback) { | package social.nickrest.npm.module;
@Getter
public class InstalledNPMPackage {
private final NPM parent;
private final File dir;
private JSONObject packageJson;
private NPMPackageData data;
public InstalledNPMPackage(NPM parent, File dir) {
this.parent = parent;
this.dir = dir;
StringBuilder builder = new StringBuilder();
File packageJson = new File(dir, "package.json");
if(!packageJson.exists()) return;
try(FileReader reader = new FileReader(packageJson)) {
int i;
while((i = reader.read()) != -1) {
builder.append((char) i);
}
this.packageJson = (JSONObject) new JSONParser().parse(builder.toString());
this.data = new NPMPackageData((String) this.packageJson.get("version"), (String) this.packageJson.get("name"));
} catch (Exception e) {
e.printStackTrace();
}
}
public void uninstall(Consumer<InstalledNPMPackage> callback) { | IOUtils.deleteDirectoryAndContents(dir); | 1 | 2023-12-22 20:46:10+00:00 | 2k |
Renzythedev/Chat-Program-With-Netty | Server/Server.java | [
{
"identifier": "ChannelManager",
"path": "Server/Managers/ChannelManager.java",
"snippet": "public class ChannelManager {\r\n\r\n private HashMap<String,Channel> channels;\r\n\r\n public ChannelManager() {\r\n channels = new HashMap<String, Channel>();\r\n }\r\n\r\n public void addChannel(Channel channel) {\r\n channels.put(Channels.getIP(channel),channel);\r\n }\r\n\r\n public void removeChannel(Channel channel) {\r\n channels.remove(Channels.getIP(channel), channel);\r\n }\r\n\r\n public boolean isActive(Channel channel) {\r\n return channels.containsKey(Channels.getIP(channel));\r\n }\r\n\r\n public Channel getChannel(String ip) {\r\n Channel channel = channels.get(ip);\r\n return channel;\r\n }\r\n\r\n public void sendMessage(Channel channel,String msg) {\r\n String ip = Channels.getIP(channel);\r\n Channel toChannel = channels.get(ip);\r\n toChannel.writeAndFlush(msg);\r\n }\r\n\r\n public void sendMessageToAllChannels(String msg) {\r\n for(Map.Entry<String, Channel> ctx : channels.entrySet()) {\r\n Channel toChannel = ctx.getValue();\r\n toChannel.writeAndFlush(msg);\r\n }\r\n }\r\n\r\n public void sendMessageToAllChannels(Channel channel, String msg) {\r\n for(Map.Entry<String, Channel> ctx : channels.entrySet()) {\r\n Channel toChannel = ctx.getValue();\r\n if(!(toChannel == channel)) {\r\n toChannel.writeAndFlush(msg);\r\n }\r\n\r\n }\r\n }\r\n\r\n}\r"
},
{
"identifier": "Group",
"path": "Server/Utils/Group.java",
"snippet": "public class Group {\r\n\r\n public static void stop(EventLoopGroup patern, EventLoopGroup child) {\r\n patern.shutdownGracefully();\r\n child.shutdownGracefully();\r\n }\r\n}\r"
}
] | import Server.Managers.ChannelManager;
import Server.Utils.Group;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
| 722 | package Server;
public class Server {
public static ChannelManager channels;
public static void main(String[] args) {
channels = new ChannelManager();
run();
}
public static void run(){
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap server = new ServerBootstrap().group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringDecoder(), new StringEncoder(), new ServerHandler());
}
});
Channel channel = server.bind(8000).sync().channel();
System.out.println("Server started on 8000 port");
channel.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
| package Server;
public class Server {
public static ChannelManager channels;
public static void main(String[] args) {
channels = new ChannelManager();
run();
}
public static void run(){
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap server = new ServerBootstrap().group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringDecoder(), new StringEncoder(), new ServerHandler());
}
});
Channel channel = server.bind(8000).sync().channel();
System.out.println("Server started on 8000 port");
channel.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
| Group.stop(bossGroup, workerGroup);
| 1 | 2023-12-30 15:54:33+00:00 | 2k |
Prototik/TheConfigLib | common/src/main/java/dev/tcl/config/api/autogen/CustomImage.java | [
{
"identifier": "EmptyCustomImageFactory",
"path": "common/src/main/java/dev/tcl/config/impl/autogen/EmptyCustomImageFactory.java",
"snippet": "public class EmptyCustomImageFactory implements CustomImage.CustomImageFactory<Object> {\n\n @Override\n public CompletableFuture<ImageRenderer> createImage(Object value, ConfigField<Object> field, OptionAccess access) {\n throw new IllegalStateException();\n }\n}"
},
{
"identifier": "ConfigField",
"path": "common/src/main/java/dev/tcl/config/api/ConfigField.java",
"snippet": "public interface ConfigField<T> {\n /**\n * Gets the accessor for the field on the main instance.\n * (Accessed through {@link ConfigClassHandler#instance()})\n */\n FieldAccess<T> access();\n\n /**\n * Gets the accessor for the field on the default instance.\n */\n ReadOnlyFieldAccess<T> defaultAccess();\n\n /**\n * @return the parent config class handler that manages this field.\n */\n ConfigClassHandler<?> parent();\n\n /**\n * The serial entry metadata for this field, if it exists.\n */\n Optional<SerialField> serial();\n\n /**\n * The auto-gen metadata for this field, if it exists.\n */\n Optional<AutoGenField> autoGen();\n}"
},
{
"identifier": "ImageRenderer",
"path": "common/src/main/java/dev/tcl/gui/image/ImageRenderer.java",
"snippet": "@Environment(EnvType.CLIENT)\npublic interface ImageRenderer {\n int render(GuiGraphics graphics, int x, int y, int renderWidth, float tickDelta);\n\n void close();\n\n default void tick() {}\n}"
}
] | import dev.tcl.config.impl.autogen.EmptyCustomImageFactory;
import dev.tcl.config.api.ConfigField;
import dev.tcl.gui.image.ImageRenderer;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.CompletableFuture; | 875 | package dev.tcl.config.api.autogen;
/**
* Defines a custom image for an option.
* Without this annotation, the option factory will look
* for the resource {@code modid:textures/tcl/$config_id_path/$fieldName.webp}.
* WEBP was chosen as the default format because file sizes are greatly reduced,
* which is important to keep your JAR size down, if you're so bothered.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CustomImage {
/**
* The resource path to the image, a {@link net.minecraft.resources.ResourceLocation}
* is constructed with the namespace being the modid of the config, and the path being
* this value.
* <p>
* The following file formats are supported:
* <ul>
* <li>{@code .png}</li>
* <li>{@code .webp}</li>
* <li>{@code .jpg}, {@code .jpeg}</li>
* </ul>
* <p>
* If left blank, then {@link CustomImage#factory()} is used.
*/
String value() default "";
/**
* The width of the image, in pixels.
* <strong>This is only required when using a PNG with {@link CustomImage#value()}</strong>
*/
int width() default 0;
/**
* The width of the image, in pixels.
* <strong>This is only required when using a PNG with {@link CustomImage#value()}</strong>
*/
int height() default 0;
/**
* The factory to create the image with.
* For the average user, this should not be used as it breaks out of the
* API-safe environment where things could change at any time, but required
* when creating anything advanced with the {@link ImageRenderer}.
* <p>
* The factory should contain a public, no-args constructor that will be
* invoked via reflection.
*
* @return the class of the factory
*/ | package dev.tcl.config.api.autogen;
/**
* Defines a custom image for an option.
* Without this annotation, the option factory will look
* for the resource {@code modid:textures/tcl/$config_id_path/$fieldName.webp}.
* WEBP was chosen as the default format because file sizes are greatly reduced,
* which is important to keep your JAR size down, if you're so bothered.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CustomImage {
/**
* The resource path to the image, a {@link net.minecraft.resources.ResourceLocation}
* is constructed with the namespace being the modid of the config, and the path being
* this value.
* <p>
* The following file formats are supported:
* <ul>
* <li>{@code .png}</li>
* <li>{@code .webp}</li>
* <li>{@code .jpg}, {@code .jpeg}</li>
* </ul>
* <p>
* If left blank, then {@link CustomImage#factory()} is used.
*/
String value() default "";
/**
* The width of the image, in pixels.
* <strong>This is only required when using a PNG with {@link CustomImage#value()}</strong>
*/
int width() default 0;
/**
* The width of the image, in pixels.
* <strong>This is only required when using a PNG with {@link CustomImage#value()}</strong>
*/
int height() default 0;
/**
* The factory to create the image with.
* For the average user, this should not be used as it breaks out of the
* API-safe environment where things could change at any time, but required
* when creating anything advanced with the {@link ImageRenderer}.
* <p>
* The factory should contain a public, no-args constructor that will be
* invoked via reflection.
*
* @return the class of the factory
*/ | Class<? extends CustomImageFactory<?>> factory() default EmptyCustomImageFactory.class; | 0 | 2023-12-25 14:48:27+00:00 | 2k |
flyingpig2016/itheima_web_project | tlias-web-management/src/main/java/com/itheima/filter/LoginCheckFilter.java | [
{
"identifier": "Result",
"path": "springboot-web-config2/src/main/java/com/itheima/pojo/Result.java",
"snippet": "@Data\r\n@NoArgsConstructor\r\n@AllArgsConstructor\r\npublic class Result {\r\n private Integer code;//响应码,1 代表成功; 0 代表失败\r\n private String msg; //响应码 描述字符串\r\n private Object data; //返回的数据\r\n\r\n //增删改 成功响应\r\n public static Result success(){\r\n return new Result(1,\"success\",null);\r\n }\r\n //查询 成功响应\r\n public static Result success(Object data){\r\n return new Result(1,\"success\",data);\r\n }\r\n //失败响应\r\n public static Result error(String msg){\r\n return new Result(0,msg,null);\r\n }\r\n}\r"
},
{
"identifier": "JwtUtils",
"path": "tlias-web-management/src/main/java/com/itheima/utils/JwtUtils.java",
"snippet": "public class JwtUtils {\r\n\r\n private static String signKey = \"itheima\";\r\n private static Long expire = 43200000L;\r\n\r\n /**\r\n * 生成JWT令牌\r\n * @param claims JWT第二部分负载 payload 中存储的内容\r\n * @return\r\n */\r\n public static String generateJwt(Map<String, Object> claims){\r\n String jwt = Jwts.builder()\r\n .addClaims(claims)\r\n .signWith(SignatureAlgorithm.HS256, signKey)\r\n .setExpiration(new Date(System.currentTimeMillis() + expire))\r\n .compact();\r\n return jwt;\r\n }\r\n\r\n /**\r\n * 解析JWT令牌\r\n * @param jwt JWT令牌\r\n * @return JWT第二部分负载 payload 中存储的内容\r\n */\r\n public static Claims parseJWT(String jwt){\r\n Claims claims = Jwts.parser()\r\n .setSigningKey(signKey)\r\n .parseClaimsJws(jwt)\r\n .getBody();\r\n return claims;\r\n }\r\n}\r"
}
] | import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException; | 864 | package com.itheima.filter;
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
// 1. 获取请求url
String url = req.getRequestURI().toString();
System.out.println("请求的url是:" + url);
// 2. 判断url是否包含Login,如果包含,放行
if (url.contains("/login")) {
filterChain.doFilter(req, resp);
return;
}
// 3. 获取请求头里面的token
String token = req.getHeader("token");
// 4. 判断token是否为空,如果不存在,返回错误结果(未登录)
if (StringUtils.isEmpty(token)) {
log.info("请求头token为空,返回未登录的信息");
Result error = Result.error("NOT_LOGIN");
//手动转换对象 --json ------>阿里巴巴fastJSON
String notLogin = JSONObject.toJSONString(error);
resp.getWriter().write(notLogin);
return;
}
// 5. 判断token是否有效,如果解析失败,返回错误结果未登录
try { | package com.itheima.filter;
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
// 1. 获取请求url
String url = req.getRequestURI().toString();
System.out.println("请求的url是:" + url);
// 2. 判断url是否包含Login,如果包含,放行
if (url.contains("/login")) {
filterChain.doFilter(req, resp);
return;
}
// 3. 获取请求头里面的token
String token = req.getHeader("token");
// 4. 判断token是否为空,如果不存在,返回错误结果(未登录)
if (StringUtils.isEmpty(token)) {
log.info("请求头token为空,返回未登录的信息");
Result error = Result.error("NOT_LOGIN");
//手动转换对象 --json ------>阿里巴巴fastJSON
String notLogin = JSONObject.toJSONString(error);
resp.getWriter().write(notLogin);
return;
}
// 5. 判断token是否有效,如果解析失败,返回错误结果未登录
try { | Claims claims = JwtUtils.parseJWT(token); | 1 | 2023-12-25 08:52:04+00:00 | 2k |
vadage/rs4j | src/main/java/space/provided/rs/result/Result.java | [
{
"identifier": "ValueAccessError",
"path": "src/main/java/space/provided/rs/error/ValueAccessError.java",
"snippet": "public final class ValueAccessError extends Error {\n\n public ValueAccessError(String message) {\n super(message);\n }\n}"
},
{
"identifier": "ArgInvokable",
"path": "src/main/java/space/provided/rs/ops/ArgInvokable.java",
"snippet": "@FunctionalInterface\npublic interface ArgInvokable<Value, ReturnType> {\n\n ReturnType invoke(Value value);\n}"
},
{
"identifier": "ArgVoidInvokable",
"path": "src/main/java/space/provided/rs/ops/ArgVoidInvokable.java",
"snippet": "@FunctionalInterface\npublic interface ArgVoidInvokable<Value> {\n\n void invoke(Value value);\n}"
}
] | import space.provided.rs.error.ValueAccessError;
import space.provided.rs.ops.ArgInvokable;
import space.provided.rs.ops.ArgVoidInvokable; | 850 | package space.provided.rs.result;
public final class Result<Ok, Error> {
private final Ok ok;
private final Error error;
private final ResultType type;
private Result(ResultType type, Ok ok, Error error) {
this.type = type;
this.ok = ok;
this.error = error;
}
public static <Ok, Err> Result<Ok, Err> ok() {
return ok(null);
}
public static <Ok, Err> Result<Ok, Err> ok(Ok value) {
return new Result<>(ResultType.OK, value, null);
}
public static <Ok, Err> Result<Ok, Err> error() {
return error(null);
}
public static <Ok, Err> Result<Ok, Err> error(Err value) {
return new Result<>(ResultType.ERROR, null, value);
}
public Ok unwrap() throws ValueAccessError {
if (!isOk()) {
throw new ValueAccessError("Called `unwrap` on %1$s Result.".formatted(type));
}
return ok;
}
public Error unwrapError() throws ValueAccessError {
if (!isError()) {
throw new ValueAccessError("Called `unwrapError` on %1$s Result.".formatted(type));
}
return error;
}
public boolean isOk() {
return type.equals(ResultType.OK);
}
public boolean isOkAnd(ArgInvokable<Ok, Boolean> invokable) {
return switch (type) {
case ERROR -> false;
case OK -> invokable.invoke(ok);
};
}
public boolean isError() {
return !isOk();
}
public boolean isErrorAnd(ArgInvokable<Error, Boolean> invokable) {
return switch (type) {
case OK -> false;
case ERROR -> invokable.invoke(error);
};
}
public <Mapped> Result<Mapped, Error> map(ArgInvokable<Ok, Mapped> invokable) {
return switch (type) {
case OK -> Result.ok(invokable.invoke(ok));
case ERROR -> Result.error(error);
};
}
public <Mapped> Mapped mapOr(Mapped fallback, ArgInvokable<Ok, Mapped> invokable) {
return switch (type) {
case OK -> invokable.invoke(ok);
case ERROR -> fallback;
};
}
public <Mapped> Mapped mapOrElse(ArgInvokable<Error, Mapped> fallback, ArgInvokable<Ok, Mapped> invokable) {
return switch (type) {
case OK -> invokable.invoke(ok);
case ERROR -> fallback.invoke(error);
};
}
public Result<Ok, Error> and(Result<Ok, Error> result) {
return switch (type) {
case OK -> result;
case ERROR -> Result.error(error);
};
}
public Result<Ok, Error> andThen(ArgInvokable<Ok, Result<Ok, Error>> invokable) {
return switch (type) {
case OK -> invokable.invoke(ok);
case ERROR -> Result.error(error);
};
}
| package space.provided.rs.result;
public final class Result<Ok, Error> {
private final Ok ok;
private final Error error;
private final ResultType type;
private Result(ResultType type, Ok ok, Error error) {
this.type = type;
this.ok = ok;
this.error = error;
}
public static <Ok, Err> Result<Ok, Err> ok() {
return ok(null);
}
public static <Ok, Err> Result<Ok, Err> ok(Ok value) {
return new Result<>(ResultType.OK, value, null);
}
public static <Ok, Err> Result<Ok, Err> error() {
return error(null);
}
public static <Ok, Err> Result<Ok, Err> error(Err value) {
return new Result<>(ResultType.ERROR, null, value);
}
public Ok unwrap() throws ValueAccessError {
if (!isOk()) {
throw new ValueAccessError("Called `unwrap` on %1$s Result.".formatted(type));
}
return ok;
}
public Error unwrapError() throws ValueAccessError {
if (!isError()) {
throw new ValueAccessError("Called `unwrapError` on %1$s Result.".formatted(type));
}
return error;
}
public boolean isOk() {
return type.equals(ResultType.OK);
}
public boolean isOkAnd(ArgInvokable<Ok, Boolean> invokable) {
return switch (type) {
case ERROR -> false;
case OK -> invokable.invoke(ok);
};
}
public boolean isError() {
return !isOk();
}
public boolean isErrorAnd(ArgInvokable<Error, Boolean> invokable) {
return switch (type) {
case OK -> false;
case ERROR -> invokable.invoke(error);
};
}
public <Mapped> Result<Mapped, Error> map(ArgInvokable<Ok, Mapped> invokable) {
return switch (type) {
case OK -> Result.ok(invokable.invoke(ok));
case ERROR -> Result.error(error);
};
}
public <Mapped> Mapped mapOr(Mapped fallback, ArgInvokable<Ok, Mapped> invokable) {
return switch (type) {
case OK -> invokable.invoke(ok);
case ERROR -> fallback;
};
}
public <Mapped> Mapped mapOrElse(ArgInvokable<Error, Mapped> fallback, ArgInvokable<Ok, Mapped> invokable) {
return switch (type) {
case OK -> invokable.invoke(ok);
case ERROR -> fallback.invoke(error);
};
}
public Result<Ok, Error> and(Result<Ok, Error> result) {
return switch (type) {
case OK -> result;
case ERROR -> Result.error(error);
};
}
public Result<Ok, Error> andThen(ArgInvokable<Ok, Result<Ok, Error>> invokable) {
return switch (type) {
case OK -> invokable.invoke(ok);
case ERROR -> Result.error(error);
};
}
| public Result<Ok, Error> andThenContinue(ArgVoidInvokable<Ok> invokable) { | 2 | 2023-12-27 15:33:17+00:00 | 2k |
wicksonZhang/Spring-Cloud | 03-spring-cloud-cluster-eureka-payment-3700/src/main/java/cn/wickson/cloud/cluster/eureka/payment2/service/impl/PaymentServiceImpl.java | [
{
"identifier": "PaymentConvert",
"path": "03-spring-cloud-cluster-eureka-payment-3700/src/main/java/cn/wickson/cloud/cluster/eureka/payment2/convert/PaymentConvert.java",
"snippet": "@Mapper\npublic interface PaymentConvert {\n\n PaymentConvert INSTANCE = Mappers.getMapper(PaymentConvert.class);\n\n /**\n * 转实体\n *\n * @param paymentVO\n * @return Payment\n */\n Payment toEntity(PaymentCreateReqVO paymentVO);\n\n /**\n * 转DTO\n *\n * @param payment\n * @return PaymentRespDTO\n */\n PaymentRespDTO toDTO(Payment payment);\n}"
},
{
"identifier": "IPaymentService",
"path": "03-spring-cloud-cluster-eureka-payment-3700/src/main/java/cn/wickson/cloud/cluster/eureka/payment2/service/IPaymentService.java",
"snippet": "public interface IPaymentService {\n\n /**\n * 创建支付订单信息\n *\n * @param paymentVO 支付info\n */\n void create(PaymentCreateReqVO paymentVO);\n\n /**\n * 返回指定信息\n *\n * @param id 订单id\n * @return PaymentRespDTO\n */\n PaymentRespDTO getById(Long id);\n}"
},
{
"identifier": "PaymentRespDTO",
"path": "01-spring-cloud-common/src/main/java/cn/wickson/cloud/common/model/dto/PaymentRespDTO.java",
"snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class PaymentRespDTO implements ResultUnpacked, Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 支付ID\n */\n private Long id;\n\n /**\n * 支付金额\n */\n private String amount;\n\n /**\n * 请求端口\n */\n private int port;\n\n /**\n * 获取类实例\n *\n * @return\n */\n public static PaymentRespDTO getInstance() {\n return new PaymentRespDTO();\n }\n\n}"
},
{
"identifier": "Payment",
"path": "01-spring-cloud-common/src/main/java/cn/wickson/cloud/common/model/entity/Payment.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Payment implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 支付ID\n */\n private Long id;\n\n /**\n * 支付金额\n */\n private String amount;\n\n}"
},
{
"identifier": "PaymentCreateReqVO",
"path": "01-spring-cloud-common/src/main/java/cn/wickson/cloud/common/model/vo/PaymentCreateReqVO.java",
"snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\npublic class PaymentCreateReqVO {\n\n /**\n * 支付ID\n */\n @NotNull(message = \"支付ID不为空\")\n private Long id;\n\n /**\n * 支付金额\n */\n @NotNull(message = \"支付金额不为空\")\n private BigDecimal amount;\n\n}"
}
] | import cn.hutool.core.collection.CollUtil;
import cn.wickson.cloud.cluster.eureka.payment2.convert.PaymentConvert;
import cn.wickson.cloud.cluster.eureka.payment2.service.IPaymentService;
import cn.wickson.cloud.common.model.dto.PaymentRespDTO;
import cn.wickson.cloud.common.model.entity.Payment;
import cn.wickson.cloud.common.model.vo.PaymentCreateReqVO;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List; | 918 | package cn.wickson.cloud.cluster.eureka.payment2.service.impl;
/**
* 支付服务-应用服务实现类
*
* @author ZhangZiHeng
* @date 2023-12-27
*/
@Service
public class PaymentServiceImpl implements IPaymentService {
| package cn.wickson.cloud.cluster.eureka.payment2.service.impl;
/**
* 支付服务-应用服务实现类
*
* @author ZhangZiHeng
* @date 2023-12-27
*/
@Service
public class PaymentServiceImpl implements IPaymentService {
| private static final List<Payment> LIST = new ArrayList<>(); | 3 | 2023-12-27 09:42:02+00:00 | 2k |
behnamnasehi/playsho | app/src/main/java/com/playsho/android/db/SessionStorage.java | [
{
"identifier": "ApplicationLoader",
"path": "app/src/main/java/com/playsho/android/base/ApplicationLoader.java",
"snippet": "public class ApplicationLoader extends Application {\n private static final String TAG = \"ApplicationLoader\";\n @SuppressLint(\"StaticFieldLeak\")\n private static Context context;\n\n private static Gson gson;\n private static SessionStorage sessionStorage;\n\n /**\n * Gets the name of the ApplicationLoader class.\n *\n * @return The name of the ApplicationLoader class.\n */\n @NonNull\n public static String getOriginName() {\n return ApplicationLoader.class.getSimpleName();\n }\n\n /**\n * Called when the application is first created. Initializes the application context, Gson, and SessionStorage.\n */\n public void onCreate() {\n super.onCreate();\n context = getApplicationContext();\n AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);\n gson = new Gson();\n ApplicationLoader.sessionStorage = new SessionStorage();\n try {\n DimensionUtils.checkDisplaySize(context, null);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n /**\n * Gets the application context.\n *\n * @return The application context.\n */\n public static Context getAppContext() {\n return ApplicationLoader.context;\n }\n\n /**\n * Called when the configuration of the device changes.\n *\n * @param newConfig The new configuration.\n */\n @Override\n public void onConfigurationChanged(@NonNull Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n try {\n DimensionUtils.checkDisplaySize(context, newConfig);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n /**\n * Gets the SessionStorage instance for managing session storage.\n *\n * @return The SessionStorage instance.\n */\n public static SessionStorage getSessionStorage() {\n return ApplicationLoader.sessionStorage;\n }\n\n /**\n * Gets the Gson instance for JSON serialization and deserialization.\n *\n * @return The Gson instance.\n */\n public static Gson getGson() {\n return ApplicationLoader.gson;\n }\n\n}"
},
{
"identifier": "Validator",
"path": "app/src/main/java/com/playsho/android/utils/Validator.java",
"snippet": "public class Validator {\n\n /**\n * Checks if a string is null or empty.\n *\n * @param string The string to check.\n * @return {@code true} if the string is null or empty, {@code false} otherwise.\n */\n public static boolean isNullOrEmpty(String string) {\n return TextUtils.isEmpty(string);\n }\n\n /**\n * Checks if a reference is null.\n *\n * @param reference The reference to check.\n * @param <T> The type of the reference.\n * @return {@code true} if the reference is null, {@code false} otherwise.\n */\n public static <T> boolean isNull(T reference) {\n return reference == null;\n }\n\n /**\n * Checks if a string is a valid Iran phone number.\n *\n * @param phone The phone number to check.\n * @return {@code true} if the phone number is a valid Iran phone number, {@code false} otherwise.\n */\n public static boolean isIranPhoneNumber(String phone) {\n if (isNullOrEmpty(phone)) return false;\n boolean starter = phone.startsWith(\"09\") || phone.startsWith(\"+98\");\n return starter && phone.length() >= 11;\n }\n\n /**\n * Checks if a string has a specific length.\n *\n * @param content The string to check.\n * @param length The expected length.\n * @return {@code true} if the string has the specified length, {@code false} otherwise.\n */\n public static boolean hasLength(String content, int length) {\n return !isNullOrEmpty(content) && content.length() == length;\n }\n\n /**\n * Checks if the length of a string is greater than a specified value.\n *\n * @param content The string to check.\n * @param length The minimum length.\n * @return {@code true} if the string length is greater than the specified value, {@code false} otherwise.\n */\n public static boolean isGreaterThan(String content, int length) {\n return !isNullOrEmpty(content) && content.length() > length;\n }\n\n /**\n * Gets the string value or a default if it is null or empty.\n *\n * @param s The string to check.\n * @param def The default value.\n * @return The original string if not null or empty, otherwise the default value.\n */\n public static String getDefaultIfNullOrEmpty(String s, String def) {\n return isNullOrEmpty(s) ? def : s;\n }\n\n /**\n * Checks if the length of a string is smaller than a specified value.\n *\n * @param content The string to check.\n * @param length The maximum length.\n * @return {@code true} if the string length is smaller than the specified value, {@code false} otherwise.\n */\n public static boolean isSmallerThan(String content, int length) {\n return !isNullOrEmpty(content) && content.length() < length;\n }\n\n /**\n * Checks if two integers are equal.\n *\n * @param a The first integer.\n * @param b The second integer.\n * @return {@code true} if the integers are equal, {@code false} otherwise.\n */\n public static boolean isEqual(int a, int b) {\n return a == b;\n }\n\n /**\n * Checks if two strings are equal (handling null values).\n *\n * @param a The first string.\n * @param b The second string.\n * @return {@code true} if the strings are equal, {@code false} otherwise.\n */\n public static boolean isEqual(String a, String b) {\n return Objects.equals(a, b);\n }\n}"
}
] | import android.content.Context;
import android.content.SharedPreferences;
import com.playsho.android.base.ApplicationLoader;
import com.playsho.android.utils.Validator; | 1,547 | package com.playsho.android.db;
/**
* A class for managing session storage using SharedPreferences.
*/
public class SessionStorage {
private final SharedPreferences pref;
private final SharedPreferences.Editor editor;
// Name of the shared preference file
private final String SHARED_PREFERENCE_NAME = "main_sp";
/**
* Constructs a SessionStorage instance and initializes SharedPreferences and its editor.
*/
public SessionStorage() { | package com.playsho.android.db;
/**
* A class for managing session storage using SharedPreferences.
*/
public class SessionStorage {
private final SharedPreferences pref;
private final SharedPreferences.Editor editor;
// Name of the shared preference file
private final String SHARED_PREFERENCE_NAME = "main_sp";
/**
* Constructs a SessionStorage instance and initializes SharedPreferences and its editor.
*/
public SessionStorage() { | this.pref = ApplicationLoader.getAppContext().getSharedPreferences( | 0 | 2023-12-26 08:14:29+00:00 | 2k |
lunasaw/voglander | voglander-integration/src/main/java/io/github/lunasaw/voglander/intergration/wrapper/gb28181/server/message/DefaultMessageProcessorServer.java | [
{
"identifier": "DeviceChannelReq",
"path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/domain/qo/DeviceChannelReq.java",
"snippet": "@Data\npublic class DeviceChannelReq {\n\n /**\n * 设备Id\n */\n private String deviceId;\n\n /**\n * 通道Id\n */\n private String channelId;\n\n /**\n * 通道信息\n */\n private String channelInfo;\n\n /**\n * 通道名称\n */\n private String channelName;\n}"
},
{
"identifier": "DeviceInfoReq",
"path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/domain/qo/DeviceInfoReq.java",
"snippet": "@Data\npublic class DeviceInfoReq {\n\n private String deviceId;\n\n private String deviceInfo;\n}"
},
{
"identifier": "DeviceRegisterService",
"path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/service/DeviceRegisterService.java",
"snippet": "public interface DeviceRegisterService {\n\n /**\n * 注册登陆\n *\n * @param device\n */\n void login(DeviceReq device);\n\n /**\n * 保持活跃\n * @param deviceId\n */\n void keepalive(String deviceId);\n\n /**\n * 更新设备地址\n * @param deviceId\n * @param ip\n * @param port\n */\n void updateRemoteAddress(String deviceId, String ip, Integer port);\n\n /**\n * 设备离线\n * @param userId\n */\n void offline(String userId);\n\n /**\n * 添加设备通道\n *\n * @param req\n */\n void addChannel(DeviceChannelReq req);\n\n /**\n * 更新设备信息\n *\n * @param req\n */\n void updateDeviceInfo(DeviceInfoReq req);\n}"
}
] | import com.alibaba.fastjson.JSON;
import io.github.lunasaw.gb28181.common.entity.notify.DeviceAlarmNotify;
import io.github.lunasaw.gb28181.common.entity.notify.DeviceKeepLiveNotify;
import io.github.lunasaw.gb28181.common.entity.notify.MediaStatusNotify;
import io.github.lunasaw.gb28181.common.entity.notify.MobilePositionNotify;
import io.github.lunasaw.gb28181.common.entity.response.DeviceInfo;
import io.github.lunasaw.gb28181.common.entity.response.DeviceItem;
import io.github.lunasaw.gb28181.common.entity.response.DeviceRecord;
import io.github.lunasaw.gb28181.common.entity.response.DeviceResponse;
import io.github.lunasaw.gbproxy.server.transimit.request.message.MessageProcessorServer;
import io.github.lunasaw.sip.common.entity.RemoteAddressInfo;
import io.github.lunasaw.voglander.client.domain.qo.DeviceChannelReq;
import io.github.lunasaw.voglander.client.domain.qo.DeviceInfoReq;
import io.github.lunasaw.voglander.client.service.DeviceRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; | 951 | package io.github.lunasaw.voglander.intergration.wrapper.gb28181.server.message;
/**
* @author luna
* @date 2023/10/17
*/
@Slf4j
@Component
public class DefaultMessageProcessorServer implements MessageProcessorServer {
@Autowired
private DeviceRegisterService deviceRegisterService;
@Override
public void updateDeviceResponse(String userId, DeviceResponse deviceResponse) {
log.info("接收到设备通道信息 updateDeviceResponse::userId = {}, deviceResponse = {}", userId, JSON.toJSONString(deviceResponse));
DeviceChannelReq req = new DeviceChannelReq();
req.setDeviceId(userId);
for (DeviceItem deviceItem : deviceResponse.getDeviceItemList()) {
req.setChannelId(deviceItem.getDeviceId());
req.setChannelInfo(JSON.toJSONString(deviceItem));
req.setChannelName(deviceItem.getName());
deviceRegisterService.addChannel(req);
}
}
@Override
public void updateDeviceInfo(String userId, DeviceInfo deviceInfo) {
log.info("接收到设备信息 updateDeviceInfo::userId = {}, deviceInfo = {}", userId, JSON.toJSONString(deviceInfo));
| package io.github.lunasaw.voglander.intergration.wrapper.gb28181.server.message;
/**
* @author luna
* @date 2023/10/17
*/
@Slf4j
@Component
public class DefaultMessageProcessorServer implements MessageProcessorServer {
@Autowired
private DeviceRegisterService deviceRegisterService;
@Override
public void updateDeviceResponse(String userId, DeviceResponse deviceResponse) {
log.info("接收到设备通道信息 updateDeviceResponse::userId = {}, deviceResponse = {}", userId, JSON.toJSONString(deviceResponse));
DeviceChannelReq req = new DeviceChannelReq();
req.setDeviceId(userId);
for (DeviceItem deviceItem : deviceResponse.getDeviceItemList()) {
req.setChannelId(deviceItem.getDeviceId());
req.setChannelInfo(JSON.toJSONString(deviceItem));
req.setChannelName(deviceItem.getName());
deviceRegisterService.addChannel(req);
}
}
@Override
public void updateDeviceInfo(String userId, DeviceInfo deviceInfo) {
log.info("接收到设备信息 updateDeviceInfo::userId = {}, deviceInfo = {}", userId, JSON.toJSONString(deviceInfo));
| DeviceInfoReq deviceInfoReq = new DeviceInfoReq(); | 1 | 2023-12-27 07:28:18+00:00 | 2k |
GrailStack/grail-codegen | src/main/java/com/itgrail/grail/codegen/service/impl/DbServiceImpl.java | [
{
"identifier": "DBProperties",
"path": "src/main/java/com/itgrail/grail/codegen/components/db/database/DBProperties.java",
"snippet": "@Data\n@Accessors(chain = true)\npublic class DBProperties {\n\n private String dbType;\n private String dbUrl;\n private String dbUserName;\n private String dbPassword;\n\n}"
},
{
"identifier": "Database",
"path": "src/main/java/com/itgrail/grail/codegen/components/db/database/Database.java",
"snippet": "public interface Database extends Closeable {\n\n String getDbUrl();\n\n String getDbName();\n\n String getDbUserName();\n\n String getDbPassword();\n\n String getDriverClassName();\n\n Connection getConnection();\n\n DbTypeEnum getDbType();\n\n /**\n * 获取表名称列表\n *\n * @param tableNamePattern 获取表名时使用的表达式\n * @return 表名列表\n */\n List<String> getTableNames(String tableNamePattern);\n\n /**\n * 获取数据库所有表名称\n *\n * @return 所有表名称\n */\n List<String> getAllTableNames();\n\n /**\n * 查询表所有列\n *\n * @param tableName 表名\n * @return 所有列\n */\n List<Column> getColumns(String tableName);\n\n /**\n * 查询表主键列\n *\n * @param tableName 表名\n * @return 主键列\n */\n List<PrimaryKeyColumn> getPrimaryColumns(String tableName);\n\n\n /**\n * 查询数据库中所有表\n *\n * @return 数据表列表\n */\n List<Table> getAllTables();\n\n /**\n * 查询表\n *\n * @param tableNamePattern 表名称表达式过滤,如:sys_%,则仅仅查询出【sys_】开头的所有表\n * @return 数据表列表\n */\n List<Table> getTables(String tableNamePattern);\n\n /**\n * 查询表\n *\n * @param tableNames 表名称列表\n * @return 数据表列表\n */\n List<Table> getTables(List<String> tableNames);\n\n /**\n * 查询表\n *\n * @param tableName 表名\n * @return 表对象实例\n */\n Table getTable(String tableName);\n\n\n /**\n * 是否为主键列\n *\n * @param tableName 表名\n * @param columnName 列名\n * @return 是否为主键,true:主键,false:非主键\n */\n boolean isPrimaryKey(String tableName, String columnName);\n\n /**\n * 获取表备注信息\n *\n * @param tableName 表名\n * @return 表备注信息\n */\n String getTableComment(String tableName);\n\n}"
},
{
"identifier": "DatabaseFactory",
"path": "src/main/java/com/itgrail/grail/codegen/components/db/database/DatabaseFactory.java",
"snippet": "@Slf4j\npublic class DatabaseFactory {\n\n private DatabaseFactory() {\n }\n\n public static Database create(DBProperties dbProperties) throws DbException {\n DbTypeEnum dbTypeEnum = DbTypeEnum.get(dbProperties.getDbType());\n if (dbTypeEnum == null) {\n throw new DbException(String.format(\"暂不支持该数据库类型, dbType=%s\", dbProperties.getDbType()));\n }\n try {\n Constructor<? extends Database> constructor = dbTypeEnum.getDataBaseImplClass().getConstructor(DBProperties.class);\n return constructor.newInstance(dbProperties);\n } catch (InvocationTargetException ex) {\n log.error(\"创建database对象失败\", ex);\n throw new DbException(ex.getCause().getMessage());\n } catch (Exception ex) {\n log.error(\"创建database对象失败\", ex);\n throw new DbException(ex.getMessage());\n }\n }\n\n}"
},
{
"identifier": "DbService",
"path": "src/main/java/com/itgrail/grail/codegen/service/DbService.java",
"snippet": "public interface DbService {\n\n public DbTablesRespDTO getDbTables(DbTablesReqDTO reqDTO);\n\n}"
},
{
"identifier": "DbTablesReqDTO",
"path": "src/main/java/com/itgrail/grail/codegen/service/dto/DbTablesReqDTO.java",
"snippet": "@Data\n@Accessors(chain = true)\npublic class DbTablesReqDTO implements Serializable {\n\n private String dbType;\n private String dbUrl;\n private String dbUserName;\n private String dbPassword;\n\n}"
},
{
"identifier": "DbTablesRespDTO",
"path": "src/main/java/com/itgrail/grail/codegen/service/dto/DbTablesRespDTO.java",
"snippet": "@Data\npublic class DbTablesRespDTO implements Serializable {\n\n private String dbName;\n\n private List<String> tables;\n\n}"
},
{
"identifier": "CommonUtil",
"path": "src/main/java/com/itgrail/grail/codegen/utils/CommonUtil.java",
"snippet": "public class CommonUtil {\n\n public static void closeClosable(Closeable closeable) {\n try {\n if (closeable != null) {\n closeable.close();\n }\n } catch (Exception ex) {\n }\n }\n\n public static UUID genUUID() {\n ThreadLocalRandom random = ThreadLocalRandom.current();\n return new UUID(random.nextLong(), random.nextLong());\n }\n\n}"
}
] | import com.google.common.base.Preconditions;
import com.itgrail.grail.codegen.components.db.database.DBProperties;
import com.itgrail.grail.codegen.components.db.database.Database;
import com.itgrail.grail.codegen.components.db.database.DatabaseFactory;
import com.itgrail.grail.codegen.service.DbService;
import com.itgrail.grail.codegen.service.dto.DbTablesReqDTO;
import com.itgrail.grail.codegen.service.dto.DbTablesRespDTO;
import com.itgrail.grail.codegen.utils.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects; | 1,459 | package com.itgrail.grail.codegen.service.impl;
/**
* @author xujin
* created at 2019/6/6 18:13
**/
@Service
public class DbServiceImpl implements DbService {
@Override | package com.itgrail.grail.codegen.service.impl;
/**
* @author xujin
* created at 2019/6/6 18:13
**/
@Service
public class DbServiceImpl implements DbService {
@Override | public DbTablesRespDTO getDbTables(DbTablesReqDTO reqDTO) { | 4 | 2023-12-30 15:32:55+00:00 | 2k |
SkyDynamic/FakeDebugHud | src/main/java/dev/skydynamic/fakedebug/mixin/GlDebugMixin.java | [
{
"identifier": "FpsRandom",
"path": "src/main/java/dev/skydynamic/fakedebug/FpsRandom.java",
"snippet": "public class FpsRandom {\n public static int currentFps = 0;\n}"
},
{
"identifier": "Config",
"path": "src/main/java/dev/skydynamic/fakedebug/config/Config.java",
"snippet": "public class Config {\n public static FakeDebugConfig INSTANCE = new FakeDebugConfig();\n}"
}
] | import dev.skydynamic.fakedebug.FpsRandom;
import java.util.List;
import java.util.Locale;
import dev.skydynamic.fakedebug.config.Config;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.hud.DebugHud;
import net.minecraft.client.option.CloudRenderMode;
import net.minecraft.util.Formatting;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
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.ModifyVariable;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; | 665 | package dev.skydynamic.fakedebug.mixin;
@Environment(EnvType.CLIENT)
@Mixin({DebugHud.class})
public class GlDebugMixin
{
@Shadow
@Final
private MinecraftClient client;
@Unique
private String getFpsDebug() {
int k = this.client.getFramerateLimit();
Object string = (this.client.getGpuUtilizationPercentage() > 0.0D) ? (" GPU: " + ((this.client.getGpuUtilizationPercentage() > 100.0D) ? ("" + Formatting.RED + "100%") : ("" + Math.round(this.client.getGpuUtilizationPercentage()) + "%"))) : "";
return String.format(Locale.ROOT, "%d fps T: %s%s%s%s B: %d%s", new Object[] { Integer.valueOf(FpsRandom.currentFps), (k == 260) ? "inf" : Integer.valueOf(k), ((Boolean)this.client.options.getEnableVsync().getValue()).booleanValue() ? " vsync" : "", this.client.options.getGraphicsMode().getValue(), (this.client.options.getCloudRenderMode().getValue() == CloudRenderMode.OFF) ? "" : ((this.client.options.getCloudRenderMode().getValue() == CloudRenderMode.FAST) ? " fast-clouds" : " fancy-clouds"), this.client.options.getBiomeBlendRadius().getValue(), string });
}
@Inject(method = "getLeftText", at = @At("RETURN"), cancellable = true)
private void modifyFps(CallbackInfoReturnable<List<String>> cir) {
List<String> value = cir.getReturnValue();
value.set(1, getFpsDebug());
cir.setReturnValue(value);
}
@ModifyVariable(method = "getRightText", at = @At("STORE"), ordinal = 0)
private long modifyMaxMemories(long l) { | package dev.skydynamic.fakedebug.mixin;
@Environment(EnvType.CLIENT)
@Mixin({DebugHud.class})
public class GlDebugMixin
{
@Shadow
@Final
private MinecraftClient client;
@Unique
private String getFpsDebug() {
int k = this.client.getFramerateLimit();
Object string = (this.client.getGpuUtilizationPercentage() > 0.0D) ? (" GPU: " + ((this.client.getGpuUtilizationPercentage() > 100.0D) ? ("" + Formatting.RED + "100%") : ("" + Math.round(this.client.getGpuUtilizationPercentage()) + "%"))) : "";
return String.format(Locale.ROOT, "%d fps T: %s%s%s%s B: %d%s", new Object[] { Integer.valueOf(FpsRandom.currentFps), (k == 260) ? "inf" : Integer.valueOf(k), ((Boolean)this.client.options.getEnableVsync().getValue()).booleanValue() ? " vsync" : "", this.client.options.getGraphicsMode().getValue(), (this.client.options.getCloudRenderMode().getValue() == CloudRenderMode.OFF) ? "" : ((this.client.options.getCloudRenderMode().getValue() == CloudRenderMode.FAST) ? " fast-clouds" : " fancy-clouds"), this.client.options.getBiomeBlendRadius().getValue(), string });
}
@Inject(method = "getLeftText", at = @At("RETURN"), cancellable = true)
private void modifyFps(CallbackInfoReturnable<List<String>> cir) {
List<String> value = cir.getReturnValue();
value.set(1, getFpsDebug());
cir.setReturnValue(value);
}
@ModifyVariable(method = "getRightText", at = @At("STORE"), ordinal = 0)
private long modifyMaxMemories(long l) { | return (long) Config.INSTANCE.getMaxMemories() * 1024 * 1024; | 1 | 2023-12-24 07:03:10+00:00 | 2k |
akl7777777/ShellApiLogOptimizer | src/main/java/link/shellgpt/plugin/business/log/controller/LogController.java | [
{
"identifier": "Log",
"path": "src/main/java/link/shellgpt/plugin/business/log/model/Log.java",
"snippet": "@Data\n@IndexName(\"log_index\")\npublic class Log {\n\n @IndexId(type = IdType.CUSTOMIZE)\n @IndexField\n private String id;\n\n @IndexField\n private int userId;\n\n @IndexField(fieldType = FieldType.DATE, dateFormat = \"epoch_millis\")\n private long createdAt;\n\n @IndexField\n private int type;\n\n// @IndexField(fieldType = FieldType.TEXT, analyzer = Analyzer.IK_SMART, searchAnalyzer = Analyzer.IK_MAX_WORD)\n @IndexField(fieldType = FieldType.TEXT)\n private String content;\n\n @IndexField(strategy = FieldStrategy.NOT_EMPTY)\n private String username;\n\n @IndexField(strategy = FieldStrategy.NOT_EMPTY)\n private String tokenName;\n\n @IndexField(strategy = FieldStrategy.NOT_EMPTY)\n private String modelName;\n\n @IndexField(strategy = FieldStrategy.NOT_EMPTY)\n private String channelName;\n\n @IndexField\n private int quota;\n\n @IndexField\n private int promptTokens;\n\n @IndexField\n private int completionTokens;\n\n @IndexField\n private int channelId;\n\n @IndexField(strategy = FieldStrategy.NOT_EMPTY)\n private String tokenKey;\n\n @IndexField(fieldType = FieldType.TEXT)\n private String prompt;\n\n @IndexField(fieldType = FieldType.DATE, dateFormat = \"epoch_millis\")\n private long requestDuration;\n}"
},
{
"identifier": "LogService",
"path": "src/main/java/link/shellgpt/plugin/business/log/service/LogService.java",
"snippet": "public interface LogService {\n void createIndex();\n\n void save(Log log,String dynamicIndex);\n\n List<Log> search(Log log,String dynamicIndex);\n\n EsPageInfo<Log> pageQuery(Log log, String dynamicIndex,int page, int size);\n\n void saveBatch(List<Log> logs, String dynamicIndex);\n\n void deleteIndex(List<String> indexList);\n}"
},
{
"identifier": "ApiResponse",
"path": "src/main/java/link/shellgpt/plugin/common/utils/ApiResponse.java",
"snippet": "@Data\npublic class ApiResponse<T> {\n\n private int status;\n private String message;\n private T data;\n\n public ApiResponse(int status, String message, T data) {\n this.status = status;\n this.message = message;\n this.data = data;\n }\n\n // 快速创建成功响应的静态方法\n public static <T> ApiResponse<T> success(T data) {\n return new ApiResponse<>(200, \"操作成功\", data);\n }\n\n // 快速创建失败响应的静态方法\n public static <T> ApiResponse<T> error(int status, String message) {\n return new ApiResponse<>(status, message, null);\n }\n\n}"
}
] | import cn.easyes.core.biz.EsPageInfo;
import cn.hutool.log.LogFactory;
import link.shellgpt.plugin.business.log.model.Log;
import link.shellgpt.plugin.business.log.service.LogService;
import link.shellgpt.plugin.common.utils.ApiResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List; | 823 | package link.shellgpt.plugin.business.log.controller;
@RestController
@Validated
@RequestMapping("${api.version}/log")
public class LogController {
public static final cn.hutool.log.Log log = LogFactory.get();
| package link.shellgpt.plugin.business.log.controller;
@RestController
@Validated
@RequestMapping("${api.version}/log")
public class LogController {
public static final cn.hutool.log.Log log = LogFactory.get();
| private final LogService logService; | 1 | 2023-12-28 09:54:45+00:00 | 2k |
Man2Dev/N-Queen | lib/jfreechart-1.0.19/tests/org/jfree/chart/axis/ColorBarTest.java | [
{
"identifier": "TestUtilities",
"path": "lib/jfreechart-1.0.19/tests/org/jfree/chart/TestUtilities.java",
"snippet": "public class TestUtilities {\n\n /**\n * Returns <code>true</code> if the collections contains any object that\n * is an instance of the specified class, and <code>false</code> otherwise.\n *\n * @param collection the collection.\n * @param c the class.\n *\n * @return A boolean.\n */\n public static boolean containsInstanceOf(Collection collection, Class c) {\n Iterator iterator = collection.iterator();\n while (iterator.hasNext()) {\n Object obj = iterator.next();\n if (obj != null && obj.getClass().equals(c)) {\n return true;\n }\n }\n return false;\n }\n\n public static Object serialised(Object original) {\n Object result = null;\n ByteArrayOutputStream buffer = new ByteArrayOutputStream();\n ObjectOutput out;\n try {\n out = new ObjectOutputStream(buffer);\n out.writeObject(original);\n out.close();\n ObjectInput in = new ObjectInputStream(\n new ByteArrayInputStream(buffer.toByteArray()));\n result = in.readObject();\n in.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n return result;\n }\n \n}"
},
{
"identifier": "GreyPalette",
"path": "lib/jfreechart-1.0.19/source/org/jfree/chart/plot/GreyPalette.java",
"snippet": "public class GreyPalette extends ColorPalette implements Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = -2120941170159987395L;\r\n\r\n /**\r\n * Creates a new palette.\r\n */\r\n public GreyPalette() {\r\n super();\r\n initialize();\r\n }\r\n\r\n /**\r\n * Intializes the palette's indices.\r\n */\r\n @Override\r\n public void initialize() {\r\n\r\n setPaletteName(\"Grey\");\r\n\r\n this.r = new int[256];\r\n this.g = new int[256];\r\n this.b = new int[256];\r\n\r\n this.r[0] = 255;\r\n this.g[0] = 255;\r\n this.b[0] = 255;\r\n this.r[1] = 0;\r\n this.g[1] = 0;\r\n this.b[1] = 0;\r\n\r\n for (int i = 2; i < 256; i++) {\r\n this.r[i] = i;\r\n this.g[i] = i;\r\n this.b[i] = i;\r\n }\r\n\r\n }\r\n\r\n}\r"
}
] | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.jfree.chart.TestUtilities;
import org.jfree.chart.plot.GreyPalette;
import org.junit.Test; | 1,160 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -----------------
* ColorBarTest.java
* -----------------
* (C) Copyright 2003-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 26-Mar-2003 : Version 1 (DG);
* 07-Jan-2005 : Added test for hashCode() method (DG);
*
*/
package org.jfree.chart.axis;
/**
* Tests for the <code>ColorBar</code> class.
*/
public class ColorBarTest {
/**
* Check that the equals() method can distinguish all fields.
*/
@Test
public void testEquals() {
ColorBar c1 = new ColorBar("Test");
ColorBar c2 = new ColorBar("Test");
assertEquals(c1, c2);
c1.setAxis(new NumberAxis("Axis 1"));
assertTrue(!c1.equals(c2));
c2.setAxis(new NumberAxis("Axis 1"));
assertTrue(c1.equals(c2));
| /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -----------------
* ColorBarTest.java
* -----------------
* (C) Copyright 2003-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 26-Mar-2003 : Version 1 (DG);
* 07-Jan-2005 : Added test for hashCode() method (DG);
*
*/
package org.jfree.chart.axis;
/**
* Tests for the <code>ColorBar</code> class.
*/
public class ColorBarTest {
/**
* Check that the equals() method can distinguish all fields.
*/
@Test
public void testEquals() {
ColorBar c1 = new ColorBar("Test");
ColorBar c2 = new ColorBar("Test");
assertEquals(c1, c2);
c1.setAxis(new NumberAxis("Axis 1"));
assertTrue(!c1.equals(c2));
c2.setAxis(new NumberAxis("Axis 1"));
assertTrue(c1.equals(c2));
| c1.setColorPalette(new GreyPalette()); | 1 | 2023-12-24 12:36:47+00:00 | 2k |
viceice/verbrauchsapp | app/src/main/java/de/anipe/verbrauchsapp/TabbedImportActivity.java | [
{
"identifier": "ImportPagerAdapter",
"path": "app/src/main/java/de/anipe/verbrauchsapp/adapters/ImportPagerAdapter.java",
"snippet": "public class ImportPagerAdapter extends FragmentPagerAdapter {\n\n private final LocalImportFragment localImportFragment;\n private final GDriveImportFragment gDriveImportFragment;\n private final Context context;\n\n public ImportPagerAdapter(FragmentActivity ctx) {\n super(ctx.getSupportFragmentManager());\n context = ctx;\n localImportFragment = new LocalImportFragment();\n gDriveImportFragment = new GDriveImportFragment();\n }\n\n @Override\n public Fragment getItem(int i) {\n\n if (i == 0)\n return localImportFragment;\n else\n return gDriveImportFragment;\n }\n\n @Override\n public int getCount() {\n return 2;\n }\n\n @Override\n public CharSequence getPageTitle(int position) {\n if (position == 0) {\n return context.getString(R.string.actionbar_local);\n } else {\n return context.getString(R.string.actionbar_remote);\n }\n }\n}"
},
{
"identifier": "ImportFragment",
"path": "app/src/main/java/de/anipe/verbrauchsapp/fragments/ImportFragment.java",
"snippet": "public abstract class ImportFragment extends Fragment implements AdapterView.OnItemClickListener {\n\n private ArrayAdapter<String> adapter;\n\n\n @Override\n public final View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n\n View view = inflater.inflate(R.layout.csvimport_layout, container, false);\n // The last two arguments ensure LayoutParams are inflated properly.\n ListView rootView = view.findViewById(android.R.id.list);\n\n rootView.setAdapter(this.adapter);\n rootView.setOnItemClickListener(this);\n\n return rootView;\n }\n\n\n @Override\n public final void onCreate(Bundle savedInstanceState) {\n adapter = new ArrayAdapter<>(getActivity(),\n android.R.layout.simple_list_item_1, new ArrayList<>());\n super.onCreate(savedInstanceState);\n }\n\n @Override\n public final void onItemClick(AdapterView<?> parent, View view, int position, long id) {\n onImport(adapter.getItem(position));\n }\n\n public void update(ArrayList<String> items) {\n adapter.clear();\n adapter.addAll(items);\n }\n\n public abstract void onImport(String name);\n\n public abstract void refresh();\n}"
}
] | import android.os.Bundle;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.Toast;
import de.anipe.verbrauchsapp.adapters.ImportPagerAdapter;
import de.anipe.verbrauchsapp.fragments.ImportFragment; | 1,059 | package de.anipe.verbrauchsapp;
public class TabbedImportActivity extends AppCompatActivity {
private ImportPagerAdapter pagerAdapter;
private ViewPager viewPager;
private int loader = 0;
private ImageView iv;
private RotateAnimation rotation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_import);
Toolbar myToolbar = findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
pagerAdapter = new ImportPagerAdapter(this);
viewPager = findViewById(R.id.pager);
viewPager.setAdapter(pagerAdapter);
iv = (ImageView) getLayoutInflater().inflate(R.layout.iv_refresh, null);
rotation = (RotateAnimation) AnimationUtils.loadAnimation(this, R.anim.rotate);
rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);
ActionBar ab = getSupportActionBar();
if (ab != null)
ab.setDisplayHomeAsUpEnabled(true);
else
Toast.makeText(this, "Missing actionbar!", Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.car_import, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
refreshFragment();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onStart() {
super.onStart();
refreshFragment();
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem m = menu.findItem(R.id.action_refresh);
if (loader > 0) {
iv.startAnimation(rotation);
m.setActionView(iv);
} else {
iv.clearAnimation();
m.setActionView(null);
}
return super.onPrepareOptionsMenu(menu);
}
private void refreshFragment() {
++loader;
invalidateOptionsMenu();
| package de.anipe.verbrauchsapp;
public class TabbedImportActivity extends AppCompatActivity {
private ImportPagerAdapter pagerAdapter;
private ViewPager viewPager;
private int loader = 0;
private ImageView iv;
private RotateAnimation rotation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_import);
Toolbar myToolbar = findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
pagerAdapter = new ImportPagerAdapter(this);
viewPager = findViewById(R.id.pager);
viewPager.setAdapter(pagerAdapter);
iv = (ImageView) getLayoutInflater().inflate(R.layout.iv_refresh, null);
rotation = (RotateAnimation) AnimationUtils.loadAnimation(this, R.anim.rotate);
rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);
ActionBar ab = getSupportActionBar();
if (ab != null)
ab.setDisplayHomeAsUpEnabled(true);
else
Toast.makeText(this, "Missing actionbar!", Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.car_import, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
refreshFragment();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onStart() {
super.onStart();
refreshFragment();
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem m = menu.findItem(R.id.action_refresh);
if (loader > 0) {
iv.startAnimation(rotation);
m.setActionView(iv);
} else {
iv.clearAnimation();
m.setActionView(null);
}
return super.onPrepareOptionsMenu(menu);
}
private void refreshFragment() {
++loader;
invalidateOptionsMenu();
| ((ImportFragment) pagerAdapter.getItem(viewPager.getCurrentItem())).refresh(); | 1 | 2023-12-28 12:33:52+00:00 | 2k |
drSolutions-OpenSource/Utilizar_JDBC | psql/src/main/java/dao/UsuariosDAO.java | [
{
"identifier": "SingleConnection",
"path": "psql/src/main/java/conexaojdbc/SingleConnection.java",
"snippet": "public class SingleConnection {\n\tprivate static Connection connection = null;\n\n\tstatic {\n\t\tconectar();\n\t}\n\n\tpublic SingleConnection() {\n\t\tconectar();\n\t}\n\n\tprivate static void conectar() {\n\t\ttry {\n\t\t\tif (connection == null) {\n\t\t\t\tClass.forName(\"org.postgresql.Driver\");\n\t\t\t\tconnection = DriverManager.getConnection(ConfiguracoesPSQL.url, ConfiguracoesPSQL.username,\n\t\t\t\t\t\tConfiguracoesPSQL.password);\n\t\t\t\tconnection.setAutoCommit(false);\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic static Connection getConnection() {\n\t\treturn connection;\n\t}\n}"
},
{
"identifier": "UsuarioTelefone",
"path": "psql/src/main/java/model/UsuarioTelefone.java",
"snippet": "public class UsuarioTelefone {\n\tString nome;\n\tString email;\n\tString login;\n\tString senha;\n\tString tipo;\n\tString telefone;\n\n\tpublic String getNome() {\n\t\treturn nome;\n\t}\n\n\tpublic void setNome(String nome) {\n\t\tthis.nome = nome;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic String getTipo() {\n\t\treturn tipo;\n\t}\n\n\tpublic void setTipo(String tipo) {\n\t\tthis.tipo = tipo;\n\t}\n\n\tpublic String getTelefone() {\n\t\treturn telefone;\n\t}\n\n\tpublic void setTelefone(String telefone) {\n\t\tthis.telefone = telefone;\n\t}\n\n\tpublic String getLogin() {\n\t\treturn login;\n\t}\n\n\tpublic void setLogin(String login) {\n\t\tthis.login = login;\n\t}\n\n\tpublic String getSenha() {\n\t\treturn senha;\n\t}\n\n\tpublic void setSenha(String senha) {\n\t\tthis.senha = senha;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"UsuarioTelefone [nome=\" + nome + \", email=\" + email + \", login=\" + login + \", senha=\" + senha\n\t\t\t\t+ \", tipo=\" + tipo + \", telefone=\" + telefone + \"]\";\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(email, login, nome, senha, telefone, tipo);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tUsuarioTelefone other = (UsuarioTelefone) obj;\n\t\treturn Objects.equals(email, other.email) && Objects.equals(login, other.login)\n\t\t\t\t&& Objects.equals(nome, other.nome) && Objects.equals(senha, other.senha)\n\t\t\t\t&& Objects.equals(telefone, other.telefone) && Objects.equals(tipo, other.tipo);\n\t}\n}"
},
{
"identifier": "Usuarios",
"path": "psql/src/main/java/model/Usuarios.java",
"snippet": "public class Usuarios {\n\tprivate Long id;\n\tprivate String nome;\n\tprivate String email;\n\tprivate String login;\n\tprivate String senha;\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getNome() {\n\t\treturn nome;\n\t}\n\n\tpublic void setNome(String nome) {\n\t\tthis.nome = nome;\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\tpublic String getLogin() {\n\t\treturn login;\n\t}\n\n\tpublic void setLogin(String login) {\n\t\tthis.login = login;\n\t}\n\n\tpublic String getSenha() {\n\t\treturn senha;\n\t}\n\n\tpublic void setSenha(String senha) {\n\t\tthis.senha = senha;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Usuarios [id=\" + id + \", nome=\" + nome + \", email=\" + email + \", login=\" + login + \", senha=\" + senha\n\t\t\t\t+ \"]\";\n\t}\n}"
}
] | import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import conexaojdbc.SingleConnection;
import model.UsuarioTelefone;
import model.Usuarios; | 1,207 | package dao;
/**
* Usuários
*
* @author Diego Mendes Rodrigues
* @version 1.0
*/
public class UsuariosDAO {
private Connection connection;
/**
* Construtor que realiza a conexão com o banco de dados
*/
public UsuariosDAO() { | package dao;
/**
* Usuários
*
* @author Diego Mendes Rodrigues
* @version 1.0
*/
public class UsuariosDAO {
private Connection connection;
/**
* Construtor que realiza a conexão com o banco de dados
*/
public UsuariosDAO() { | connection = SingleConnection.getConnection(); | 0 | 2023-12-30 14:50:31+00:00 | 2k |
TuffetSpider/artismithery-0.0.1-1.20.1 | src/main/java/net/tuffetspider/artismithery/entity/custom/RockShardProjectileEntity.java | [
{
"identifier": "ModEntities",
"path": "src/main/java/net/tuffetspider/artismithery/entity/ModEntities.java",
"snippet": "public class ModEntities {\n\n public static final EntityType<RockShardProjectileEntity> ROCK_PROJECTILE = Registry.register(Registries.ENTITY_TYPE,\n new Identifier(Artismithery.MOD_ID, \"rock_projectile\"), FabricEntityTypeBuilder.<RockShardProjectileEntity>create(SpawnGroup.MISC, RockShardProjectileEntity::new)\n .dimensions(EntityDimensions.fixed(0.25f, 0.25f)).build());\n\n\n\n}"
},
{
"identifier": "ModItems",
"path": "src/main/java/net/tuffetspider/artismithery/item/ModItems.java",
"snippet": "public class ModItems {\n public static final Item ROCK_SHARD = registerItem(\"rock_shard\", new Item(new FabricItemSettings()));\n public static final Item STONE_CHISEL = registerItem(\"stone_chisel\", new Item(new FabricItemSettings()));\n public static final Item THROWING_ROCK = registerItem(\"throwing_rock\", new RockItem(new FabricItemSettings()));\n public static final Item STONE_SHARD = registerItem( \"stone_shard\", new RockItem(new FabricItemSettings()));\n\n private static void addItemsToIngredientTabItemGroup(FabricItemGroupEntries entries){\n entries.add(ROCK_SHARD);\n }\n\n\n private static Item registerItem(String name, Item item) {\n return Registry.register(Registries.ITEM, new Identifier(Artismithery.MOD_ID, name), item);\n }\n\n public static void registerModItems() {\n Artismithery.LOGGER.info(\"Registering items for \" + Artismithery.MOD_ID);\n\n ItemGroupEvents.modifyEntriesEvent(ItemGroups.INGREDIENTS).register(ModItems::addItemsToIngredientTabItemGroup);\n }\n}"
}
] | import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.projectile.thrown.ThrownItemEntity;
import net.minecraft.item.Item;
import net.minecraft.network.listener.ClientPlayPacketListener;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.s2c.play.EntitySpawnS2CPacket;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.hit.EntityHitResult;
import net.minecraft.world.World;
import net.minecraft.world.explosion.Explosion;
import net.tuffetspider.artismithery.entity.ModEntities;
import net.tuffetspider.artismithery.item.ModItems; | 672 | package net.tuffetspider.artismithery.entity.custom;
public class RockShardProjectileEntity extends ThrownItemEntity {
public RockShardProjectileEntity(EntityType<? extends ThrownItemEntity> entityType, World world) {
super(entityType, world);
}
public RockShardProjectileEntity(LivingEntity livingEntity, World world) {
super(ModEntities.ROCK_PROJECTILE, livingEntity, world);
}
@Override
protected Item getDefaultItem() { | package net.tuffetspider.artismithery.entity.custom;
public class RockShardProjectileEntity extends ThrownItemEntity {
public RockShardProjectileEntity(EntityType<? extends ThrownItemEntity> entityType, World world) {
super(entityType, world);
}
public RockShardProjectileEntity(LivingEntity livingEntity, World world) {
super(ModEntities.ROCK_PROJECTILE, livingEntity, world);
}
@Override
protected Item getDefaultItem() { | return ModItems.THROWING_ROCK; | 1 | 2023-12-29 21:59:26+00:00 | 2k |
lushi78778/springboot-api-rapid-development-templates | src/main/java/top/lushi787778/api/config/GlobalExceptionHandler.java | [
{
"identifier": "Result",
"path": "src/main/java/top/lushi787778/api/model/Result.java",
"snippet": "@Data\npublic class Result {\n\n /**\n * 100\tContinue\t继续。客户端应继续其请求\n * 200\tOK\t请求成功。一般用于GET与POST请求\n * 202\tAccepted\t已接受。已经接受请求,但未处理完成\n * 203\tParameter required\t错误的使用方法\n * 400\tBad Request\t客户端请求的语法错误,服务器无法理解\n * 401\tUnauthorized\t请求要求用户的身份认证\n * 403\tForbidden\t服务器理解请求客户端的请求,但是拒绝执行此请求\n * NOT_FOUND= 404;\n * 500\tInternal Server Error\t服务器内部错误,无法完成请求\n */\n public final static int Continue = 100;\n\n public final static int OK = 200;\n\n public final static int Accepted = 202;\n\n public final static int Parameter_Required = 203;\n\n public final static int Bad_Request = 400;\n\n public final static int Unauthorized = 401;\n\n public final static int Forbidden = 403;\n\n public final static int NOT_FOUND = 404;\n\n public final static int Internal_Server_Error = 500;\n\n /**\n * 消息码\n */\n private int code;\n /**\n * 消息凭证\n */\n private String token;\n /**\n * 请求唯一编号\n */\n private String request_id;\n\n {\n request_id = randomUUID();\n }\n\n /**\n * 消息结果集\n */\n private Object object;\n}"
},
{
"identifier": "JsonUtil",
"path": "src/main/java/top/lushi787778/api/utils/JsonUtil.java",
"snippet": "public class JsonUtil {\n\n /**\n * Servlet返回JSON(供拦截器用)\n *\n * @param response HttpServletResponse对象\n * @param result 统一返回值枚举\n */\n @SneakyThrows\n public static void response(HttpServletResponse response, Result result) {\n response.setCharacterEncoding(\"utf8\");\n response.setContentType(\"application/json\");\n ObjectMapper mapper = new ObjectMapper();\n PrintWriter writer = response.getWriter();\n writer.write(mapper.writeValueAsString(result));\n writer.flush();\n writer.close();\n }\n\n}"
}
] | import top.lushi787778.api.model.Result;
import top.lushi787778.api.utils.JsonUtil;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLIntegrityConstraintViolationException;
import cn.hutool.jwt.JWTException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice; | 1,088 | /**
* MIT License
*
* Copyright (c) 2022 lushi78778
*
* 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 top.lushi787778.api.config;
/**
* @ClassName GlobalExceptionHandler
* @Description 全局异常捕获
* @Author lushi
* @Date 2022/2/5 12:16
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理token的业务异常
*
* @param response HttpServletResponse
* @param e JWTException
*/
@ExceptionHandler(value = JWTException.class)
public void JWTExceptionHandler(HttpServletResponse response, JWTException e) { | /**
* MIT License
*
* Copyright (c) 2022 lushi78778
*
* 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 top.lushi787778.api.config;
/**
* @ClassName GlobalExceptionHandler
* @Description 全局异常捕获
* @Author lushi
* @Date 2022/2/5 12:16
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理token的业务异常
*
* @param response HttpServletResponse
* @param e JWTException
*/
@ExceptionHandler(value = JWTException.class)
public void JWTExceptionHandler(HttpServletResponse response, JWTException e) { | Result result = new Result(); | 0 | 2023-12-30 23:51:52+00:00 | 2k |
1752597830/admin-common | qf-admin/back/admin-init-main/src/main/java/com/qf/web/controller/SysDictController.java | [
{
"identifier": "BaseResponse",
"path": "qf-admin/back/admin-init-main/src/main/java/com/qf/common/utils/BaseResponse.java",
"snippet": "@Data\npublic class BaseResponse<T> implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 响应码\n */\n private String code;\n\n /**\n * 响应信息\n */\n private String msg;\n\n /**\n * 响应数据\n */\n private T data;\n\n\n public static <T> BaseResponse<T> success(T data) {\n BaseResponse<T> response = new BaseResponse<>();\n response.setCode(ResponseCode.SUCCESS.getCode());\n response.setMsg(ResponseCode.SUCCESS.getMsg());\n response.setData(data);\n return response;\n }\n\n public static <T> BaseResponse<T> success(String msg, T data) {\n BaseResponse<T> response = new BaseResponse<>();\n response.setCode(ResponseCode.SUCCESS.getCode());\n response.setMsg(msg);\n response.setData(data);\n return response;\n }\n public static <T> BaseResponse<T> fail(String msg) {\n BaseResponse<T> response = new BaseResponse<>();\n response.setCode(ResponseCode.FAIL.getCode());\n response.setMsg(msg);\n return response;\n }\n public static <T> BaseResponse<T> fail(String code, String msg) {\n BaseResponse<T> response = new BaseResponse<>();\n response.setCode(code);\n response.setMsg(msg);\n return response;\n }\n}"
},
{
"identifier": "OptionsDto",
"path": "qf-admin/back/admin-init-main/src/main/java/com/qf/web/domain/dto/OptionsDto.java",
"snippet": "@Data\n@ToString\n@AllArgsConstructor\n@Schema(description =\"性别、角色下拉选项响应对象\")\npublic class OptionsDto {\n\n /**\n * 选项值\n */\n private Long value;\n\n /**\n * 选项名称\n */\n private String label;\n\n}"
},
{
"identifier": "SysDictService",
"path": "qf-admin/back/admin-init-main/src/main/java/com/qf/web/service/SysDictService.java",
"snippet": "public interface SysDictService extends IService<SysDict> {\n\n List<OptionsDto> dictOptions(String typeCode);\n}"
}
] | import com.qf.common.utils.BaseResponse;
import com.qf.web.domain.dto.OptionsDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import com.qf.web.service.SysDictService;
import java.util.List; | 661 | package com.qf.web.controller;
/**
* @author : sin
* @date : 2023/12/16 21:08
* @Description : 字典管理
*/
@RestController
@RequestMapping("/dict")
public class SysDictController {
@Resource | package com.qf.web.controller;
/**
* @author : sin
* @date : 2023/12/16 21:08
* @Description : 字典管理
*/
@RestController
@RequestMapping("/dict")
public class SysDictController {
@Resource | private SysDictService sysDictService; | 2 | 2023-12-30 13:42:53+00:00 | 2k |
JIGerss/Salus | salus-web/src/main/java/team/glhf/salus/service/PageService.java | [
{
"identifier": "DetailVo",
"path": "salus-pojo/src/main/java/team/glhf/salus/vo/detail/DetailVo.java",
"snippet": "@Data\r\n@Builder\r\npublic class DetailVo implements Serializable {\r\n\r\n private DetailUserVo host;\r\n\r\n private String articleId;\r\n\r\n private String title;\r\n\r\n private String content;\r\n\r\n private Boolean isLiked;\r\n\r\n private Long likes;\r\n\r\n private Long comments;\r\n\r\n private List<String> tags;\r\n\r\n private List<String> images;\r\n\r\n private List<DetailCommentVo> commentList;\r\n\r\n private String position;\r\n\r\n private String formattedAddress;\r\n\r\n private String createTime;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r"
},
{
"identifier": "DynamicVo",
"path": "salus-pojo/src/main/java/team/glhf/salus/vo/dynamic/DynamicVo.java",
"snippet": "@Data\r\n@Builder\r\npublic class DynamicVo implements Serializable {\r\n\r\n private List<DynamicArticleVo> articles;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r"
},
{
"identifier": "PlaceDetailVo",
"path": "salus-pojo/src/main/java/team/glhf/salus/vo/gym/PlaceDetailVo.java",
"snippet": "@Data\r\n@Builder\r\npublic class PlaceDetailVo implements Serializable {\r\n\r\n private String name;\r\n\r\n private List<String> images;\r\n\r\n private String position;\r\n\r\n private String description;\r\n\r\n private String businessTime;\r\n\r\n private String telephone;\r\n\r\n private Double point;\r\n\r\n private List<PlaceDetailCommentVo> comments;\r\n\r\n private String formattedAddress;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r"
},
{
"identifier": "PlacePageVo",
"path": "salus-pojo/src/main/java/team/glhf/salus/vo/gym/PlacePageVo.java",
"snippet": "@Data\r\n@Builder\r\npublic class PlacePageVo implements Serializable {\r\n\r\n List<PlacePageGymVo> gyms;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r"
},
{
"identifier": "IndexListArticleVo",
"path": "salus-pojo/src/main/java/team/glhf/salus/vo/index/IndexListArticleVo.java",
"snippet": "@Data\r\n@Builder\r\npublic class IndexListArticleVo implements Serializable {\r\n\r\n private List<IndexArticleVo> articles;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r"
},
{
"identifier": "IndexVo",
"path": "salus-pojo/src/main/java/team/glhf/salus/vo/index/IndexVo.java",
"snippet": "@Data\r\n@Builder\r\npublic class IndexVo implements Serializable {\r\n\r\n private List<IndexTagVo> topics;\r\n\r\n private List<IndexArticleVo> articles;\r\n\r\n private List<IndexPlaceVo> places;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r"
},
{
"identifier": "UserPageVo",
"path": "salus-pojo/src/main/java/team/glhf/salus/vo/user/UserPageVo.java",
"snippet": "@Data\r\n@Builder\r\npublic class UserPageVo implements Serializable {\r\n\r\n private String userId;\r\n\r\n private String nickname;\r\n\r\n private String avatar;\r\n\r\n private Long fans;\r\n\r\n private Long subscriptions;\r\n\r\n private List<UserArticleVo> ownedArticles;\r\n\r\n private List<UserArticleVo> likedArticles;\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1919081114514233L;\r\n}\r"
}
] | import team.glhf.salus.dto.page.*;
import team.glhf.salus.vo.detail.DetailVo;
import team.glhf.salus.vo.dynamic.DynamicVo;
import team.glhf.salus.vo.gym.PlaceDetailVo;
import team.glhf.salus.vo.gym.PlacePageVo;
import team.glhf.salus.vo.index.IndexListArticleVo;
import team.glhf.salus.vo.index.IndexVo;
import team.glhf.salus.vo.user.UserPageVo;
| 1,084 | package team.glhf.salus.service;
/**
* @author Steveny
* @since 2023/11/12
*/
public interface PageService {
/**
* 请求首页
*/
IndexVo getIndexPage(IndexReq indexReq);
/**
* 请求额外的文章
*/
IndexListArticleVo getIndexArticles(IndexListArticleReq indexReq);
/**
* 请求用户页面
*/
UserPageVo getUserPage(String userId);
/**
* 请求动态页面
*/
DynamicVo getDynamicPage(String userId, Integer page);
/**
* 请求文章详情页面
*/
DetailVo getDetailPage(DetailReq detailReq);
/**
* 请求健身房列表页面
*/
| package team.glhf.salus.service;
/**
* @author Steveny
* @since 2023/11/12
*/
public interface PageService {
/**
* 请求首页
*/
IndexVo getIndexPage(IndexReq indexReq);
/**
* 请求额外的文章
*/
IndexListArticleVo getIndexArticles(IndexListArticleReq indexReq);
/**
* 请求用户页面
*/
UserPageVo getUserPage(String userId);
/**
* 请求动态页面
*/
DynamicVo getDynamicPage(String userId, Integer page);
/**
* 请求文章详情页面
*/
DetailVo getDetailPage(DetailReq detailReq);
/**
* 请求健身房列表页面
*/
| PlacePageVo getGymListPage(PlaceListReq placeListReq);
| 3 | 2023-12-23 15:03:37+00:00 | 2k |
swsm/proxynet | proxynet-common/src/main/java/com/swsm/proxynet/common/handler/ProxyNetMessageDecoder.java | [
{
"identifier": "ProxyNetMessage",
"path": "proxynet-common/src/main/java/com/swsm/proxynet/common/model/ProxyNetMessage.java",
"snippet": "@Data\npublic class ProxyNetMessage {\n\n public static final byte CONNECT = 0x01;\n public static final byte CONNECT_RESP = 0x02;\n public static final byte COMMAND = 0x03;\n \n public static final String COMMAND_AUTH = \"AUTH\";\n public static final String COMMAND_INFO = \"INFO\";\n public static final String COMMAND_RESP = \"RESP\";\n\n // 类型\n private byte type;\n // 消息实际信息\n private String info;\n // 用户请求消息 及 目标服务响应消息 原始数据\n private byte[] data;\n \n \n \n public static ProxyNetMessage buildCommandMessage(String type, String message) {\n ProxyNetMessage proxyNetMessage = new ProxyNetMessage();\n proxyNetMessage.setType(COMMAND);\n if (COMMAND_AUTH.equals(type)) {\n proxyNetMessage.setInfo(JSON.toJSONString(new CommandMessage(COMMAND_AUTH, message)));\n } else if (COMMAND_INFO.equals(type)){\n proxyNetMessage.setInfo(JSON.toJSONString(new CommandMessage(COMMAND_INFO, message)));\n proxyNetMessage.setData(JSON.parseObject(message, CommandInfoMessage.class).getInfo());\n } else if (COMMAND_RESP.equals(type)){\n proxyNetMessage.setInfo(JSON.toJSONString(new CommandMessage(COMMAND_RESP, message)));\n proxyNetMessage.setData(JSON.parseObject(message, CommandRespMessage.class).getRespInfo());\n } else {\n throw new RuntimeException(\"invalid command type:\" + type);\n }\n return proxyNetMessage;\n }\n \n public static ProxyNetMessage buildConnectMessage(String userId, String ip, Integer port) {\n ProxyNetMessage proxyNetMessage = new ProxyNetMessage();\n proxyNetMessage.setType(CONNECT);\n proxyNetMessage.setInfo(JSON.toJSONString(new ConnectMessage(userId, ip, port)));\n return proxyNetMessage;\n }\n\n public static ProxyNetMessage buildConnectRespMessage(String message, Boolean result, String userId) {\n ProxyNetMessage proxyNetMessage = new ProxyNetMessage();\n proxyNetMessage.setType(CONNECT_RESP);\n proxyNetMessage.setInfo(JSON.toJSONString(new ConnectRespMessage(result, message, userId)));\n return proxyNetMessage;\n }\n \n \n \n}"
},
{
"identifier": "PROXY_MESSAGE_INFO_SIZE",
"path": "proxynet-common/src/main/java/com/swsm/proxynet/common/Constants.java",
"snippet": "public static final Integer PROXY_MESSAGE_INFO_SIZE = 4;"
},
{
"identifier": "PROXY_MESSAGE_TOTAL_SIZE",
"path": "proxynet-common/src/main/java/com/swsm/proxynet/common/Constants.java",
"snippet": "public static final Integer PROXY_MESSAGE_TOTAL_SIZE = 4;"
},
{
"identifier": "PROXY_MESSAGE_TYPE_SIZE",
"path": "proxynet-common/src/main/java/com/swsm/proxynet/common/Constants.java",
"snippet": "public static final Integer PROXY_MESSAGE_TYPE_SIZE = 1;"
}
] | import com.swsm.proxynet.common.model.ProxyNetMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import static com.swsm.proxynet.common.Constants.PROXY_MESSAGE_INFO_SIZE;
import static com.swsm.proxynet.common.Constants.PROXY_MESSAGE_TOTAL_SIZE;
import static com.swsm.proxynet.common.Constants.PROXY_MESSAGE_TYPE_SIZE; | 962 | package com.swsm.proxynet.common.handler;
/**
* @author liujie
* @date 2023-04-15
*/
public class ProxyNetMessageDecoder extends LengthFieldBasedFrameDecoder {
public ProxyNetMessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) {
super(maxFrameLength, lengthFieldOffset, lengthFieldLength);
}
@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
ByteBuf newIn = (ByteBuf) super.decode(ctx, in);
if (newIn == null) {
return null;
}
if (newIn.readableBytes() < PROXY_MESSAGE_TOTAL_SIZE) {
return null;
}
int frameLength = newIn.readInt();
if (newIn.readableBytes() < frameLength) {
return null;
}
ProxyNetMessage proxyNetMessage = new ProxyNetMessage();
byte type = newIn.readByte();
proxyNetMessage.setType(type);
int infoLength = newIn.readInt();
byte[] infoBytes = new byte[infoLength];
newIn.readBytes(infoBytes);
proxyNetMessage.setInfo(new String(infoBytes));
| package com.swsm.proxynet.common.handler;
/**
* @author liujie
* @date 2023-04-15
*/
public class ProxyNetMessageDecoder extends LengthFieldBasedFrameDecoder {
public ProxyNetMessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) {
super(maxFrameLength, lengthFieldOffset, lengthFieldLength);
}
@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
ByteBuf newIn = (ByteBuf) super.decode(ctx, in);
if (newIn == null) {
return null;
}
if (newIn.readableBytes() < PROXY_MESSAGE_TOTAL_SIZE) {
return null;
}
int frameLength = newIn.readInt();
if (newIn.readableBytes() < frameLength) {
return null;
}
ProxyNetMessage proxyNetMessage = new ProxyNetMessage();
byte type = newIn.readByte();
proxyNetMessage.setType(type);
int infoLength = newIn.readInt();
byte[] infoBytes = new byte[infoLength];
newIn.readBytes(infoBytes);
proxyNetMessage.setInfo(new String(infoBytes));
| byte[] data = new byte[frameLength - PROXY_MESSAGE_TYPE_SIZE - PROXY_MESSAGE_INFO_SIZE - infoLength]; | 1 | 2023-12-25 03:25:38+00:00 | 2k |
hansmarks/yajp | src/test/java/com/okaphone/yajp/Tests.java | [
{
"identifier": "ArrayBuilder",
"path": "src/main/java/com/okaphone/yajp/Extras.java",
"snippet": "public static class ArrayBuilder\n extends ArrayList<Object> {\n public ArrayBuilder() {\n }\n\n public ArrayBuilder(final Stream<? extends Object> values) {\n values.forEach(this::add);\n }\n\n public ArrayBuilder(final Collection<? extends Object> values) {\n values.forEach(this::add);\n }\n\n public ArrayBuilder(final Object... values) {\n for(final Object value:values) {\n add(value);\n }\n }\n\n /**\n * Builds an anonymous JSON array.\n *\n * @return a valid ECMA-404 JSON string.\n */\n public String build() {\n return array(this);\n }\n}"
},
{
"identifier": "ObjectBuilder",
"path": "src/main/java/com/okaphone/yajp/Extras.java",
"snippet": "public static class ObjectBuilder\n extends HashMap<String,Object> {\n public ObjectBuilder() {\n }\n\n public ObjectBuilder(final Map<? extends Object,? extends Object> values) {\n values.entrySet().forEach(entry->put(entry.getKey().toString(),entry.getValue()));\n }\n\n /**\n * Builds an anonymous JSON object.\n *\n * @return a valid ECMA-404 JSON string.\n */\n public String build() {\n return object(this);\n }\n}"
}
] | import com.okaphone.yajp.Extras.ArrayBuilder;
import com.okaphone.yajp.Extras.ObjectBuilder;
import java.util.Collections;
import java.util.stream.Stream;
import junit.framework.TestCase; | 1,546 | package com.okaphone.yajp;
public class Tests
extends TestCase {
public Tests() {
}
public void testNullParser() {
assertTrue(Json.parse("null").isNull());
assertNull(Json.parse("null").value());
assertNull(Json.parse(" null").value());
assertNull(Json.parse("null ").value());
assertNull(Json.parse(" null ").value());
}
public void testBoolParser() {
assertFalse(Json.parse("true").isNull());
assertEquals(Boolean.TRUE,Json.parse("true").value());
assertTrue(Json.parse("true").bool());
assertTrue(Json.parse(" true").bool());
assertTrue(Json.parse("true ").bool());
assertTrue(Json.parse(" true ").bool());
assertFalse(Json.parse("false").isNull());
assertEquals(Boolean.FALSE,Json.parse("false").value());
assertFalse(Json.parse("false").bool());
assertFalse(Json.parse(" false").bool());
assertFalse(Json.parse("false ").bool());
assertFalse(Json.parse(" false ").bool());
}
public void testNumberParser() {
assertFalse(Json.parse("0").isNull());
assertTrue(Json.parse("0").isZero());
assertEquals(0.0,Json.parse("0").value());
assertFalse(Json.parse("1").isZero());
assertEquals(1.0,Json.parse("1").number(),0.0);
assertEquals(1.0,Json.parse("1.0").number(),0.0);
assertEquals(1.23,Json.parse("1.23").number(),0.0);
assertEquals(1.23,Json.parse(" 1.23").number(),0.0);
assertEquals(1.23,Json.parse("1.23 ").number(),0.0);
assertEquals(1.23,Json.parse(" 1.23 ").number(),0.0);
assertEquals(-1.23,Json.parse("-1.23").number(),0.0);
}
public void testStringParser() {
assertFalse(Json.parse("\"\"").isNull());
assertTrue(Json.parse("\"\"").isEmpty());
assertEquals("",Json.parse("\"\"").value());
assertEquals("",Json.parse("\"\"").string());
assertFalse(Json.parse("\"aap\"").isEmpty());
assertEquals("aap",Json.parse("\"aap\"").string());
assertEquals("aap",Json.parse(" \"aap\"").string());
assertEquals("aap",Json.parse("\"aap\" ").string());
assertEquals("aap",Json.parse(" \"aap\" ").string());
assertEquals("aap\"noot",Json.parse("\"aap\\\"noot\"").string());
assertEquals("aap\"noot\"mies",Json.parse("\"aap\\\"noot\\\"mies\"").string());
assertEquals("aap\\noot",Json.parse("\"aap\\\\noot\"").string());
assertEquals("aap/noot",Json.parse("\"aap\\/noot\"").string());
assertEquals("aap\bnoot",Json.parse("\"aap\\bnoot\"").string());
assertEquals("aap\fnoot",Json.parse("\"aap\\fnoot\"").string());
assertEquals("aap\nnoot",Json.parse("\"aap\\nnoot\"").string());
assertEquals("aap\rnoot",Json.parse("\"aap\\rnoot\"").string());
assertEquals("aap\tnoot",Json.parse("\"aap\\tnoot\"").string());
assertEquals("aap&noot",Json.parse("\"aap\\u0026noot\"").string());
assertEquals("aap\u0003noot",Json.parse("\"aap\\u0003noot\"").string());
}
public void testArrayParser() {
assertFalse(Json.parse("[]").isNull());
assertTrue(Json.parse("[]").isEmpty());
assertEquals(0,Json.parse("[]").array().length);
final Value<?>[] test=Json.parse("[1,[2,[{\"aap\":4},\"5\",[6,7]]],3]").array();
assertEquals(1.0,test[0].number(),0.0);
assertEquals(2.0,test[1].get(0).number(),0.0);
assertEquals(3,test[2].integer(),0.0);
assertEquals(4.0,test[1].get(1,0).get("aap").number(),0.0);
assertEquals("5",test[1].get(1,1).string());
assertEquals(6.0,test[1].get(1,2,0).number(),0.0);
}
public void testObjectParser() {
assertFalse(Json.parse("{}").isNull());
assertTrue(Json.parse("{}").isEmpty());
assertEquals(0,Json.parse("{}").object().size());
final Value<?> test=Json.parse("{\"aap\":1,\"noot\":{\"wim\":2,\"gijs\":{\"does\":[4,6],\"hok\":\"5\"}},\"mies\":3}");
assertEquals(1.0,test.get("aap").number(),0.0);
assertEquals(2.0,test.get("noot","wim").number(),0.0);
assertEquals(3.0,test.get("mies").number(),0.0);
assertEquals(4,test.get("noot","gijs","does").array()[0].integer());
assertEquals("5",test.get("noot","gijs","hok").string());
assertEquals(6.0,test.get("noot","gijs","does").get(1).number());
}
public void testArrayBuilder() { | package com.okaphone.yajp;
public class Tests
extends TestCase {
public Tests() {
}
public void testNullParser() {
assertTrue(Json.parse("null").isNull());
assertNull(Json.parse("null").value());
assertNull(Json.parse(" null").value());
assertNull(Json.parse("null ").value());
assertNull(Json.parse(" null ").value());
}
public void testBoolParser() {
assertFalse(Json.parse("true").isNull());
assertEquals(Boolean.TRUE,Json.parse("true").value());
assertTrue(Json.parse("true").bool());
assertTrue(Json.parse(" true").bool());
assertTrue(Json.parse("true ").bool());
assertTrue(Json.parse(" true ").bool());
assertFalse(Json.parse("false").isNull());
assertEquals(Boolean.FALSE,Json.parse("false").value());
assertFalse(Json.parse("false").bool());
assertFalse(Json.parse(" false").bool());
assertFalse(Json.parse("false ").bool());
assertFalse(Json.parse(" false ").bool());
}
public void testNumberParser() {
assertFalse(Json.parse("0").isNull());
assertTrue(Json.parse("0").isZero());
assertEquals(0.0,Json.parse("0").value());
assertFalse(Json.parse("1").isZero());
assertEquals(1.0,Json.parse("1").number(),0.0);
assertEquals(1.0,Json.parse("1.0").number(),0.0);
assertEquals(1.23,Json.parse("1.23").number(),0.0);
assertEquals(1.23,Json.parse(" 1.23").number(),0.0);
assertEquals(1.23,Json.parse("1.23 ").number(),0.0);
assertEquals(1.23,Json.parse(" 1.23 ").number(),0.0);
assertEquals(-1.23,Json.parse("-1.23").number(),0.0);
}
public void testStringParser() {
assertFalse(Json.parse("\"\"").isNull());
assertTrue(Json.parse("\"\"").isEmpty());
assertEquals("",Json.parse("\"\"").value());
assertEquals("",Json.parse("\"\"").string());
assertFalse(Json.parse("\"aap\"").isEmpty());
assertEquals("aap",Json.parse("\"aap\"").string());
assertEquals("aap",Json.parse(" \"aap\"").string());
assertEquals("aap",Json.parse("\"aap\" ").string());
assertEquals("aap",Json.parse(" \"aap\" ").string());
assertEquals("aap\"noot",Json.parse("\"aap\\\"noot\"").string());
assertEquals("aap\"noot\"mies",Json.parse("\"aap\\\"noot\\\"mies\"").string());
assertEquals("aap\\noot",Json.parse("\"aap\\\\noot\"").string());
assertEquals("aap/noot",Json.parse("\"aap\\/noot\"").string());
assertEquals("aap\bnoot",Json.parse("\"aap\\bnoot\"").string());
assertEquals("aap\fnoot",Json.parse("\"aap\\fnoot\"").string());
assertEquals("aap\nnoot",Json.parse("\"aap\\nnoot\"").string());
assertEquals("aap\rnoot",Json.parse("\"aap\\rnoot\"").string());
assertEquals("aap\tnoot",Json.parse("\"aap\\tnoot\"").string());
assertEquals("aap&noot",Json.parse("\"aap\\u0026noot\"").string());
assertEquals("aap\u0003noot",Json.parse("\"aap\\u0003noot\"").string());
}
public void testArrayParser() {
assertFalse(Json.parse("[]").isNull());
assertTrue(Json.parse("[]").isEmpty());
assertEquals(0,Json.parse("[]").array().length);
final Value<?>[] test=Json.parse("[1,[2,[{\"aap\":4},\"5\",[6,7]]],3]").array();
assertEquals(1.0,test[0].number(),0.0);
assertEquals(2.0,test[1].get(0).number(),0.0);
assertEquals(3,test[2].integer(),0.0);
assertEquals(4.0,test[1].get(1,0).get("aap").number(),0.0);
assertEquals("5",test[1].get(1,1).string());
assertEquals(6.0,test[1].get(1,2,0).number(),0.0);
}
public void testObjectParser() {
assertFalse(Json.parse("{}").isNull());
assertTrue(Json.parse("{}").isEmpty());
assertEquals(0,Json.parse("{}").object().size());
final Value<?> test=Json.parse("{\"aap\":1,\"noot\":{\"wim\":2,\"gijs\":{\"does\":[4,6],\"hok\":\"5\"}},\"mies\":3}");
assertEquals(1.0,test.get("aap").number(),0.0);
assertEquals(2.0,test.get("noot","wim").number(),0.0);
assertEquals(3.0,test.get("mies").number(),0.0);
assertEquals(4,test.get("noot","gijs","does").array()[0].integer());
assertEquals("5",test.get("noot","gijs","hok").string());
assertEquals(6.0,test.get("noot","gijs","does").get(1).number());
}
public void testArrayBuilder() { | assertEquals("[]",new ArrayBuilder().build()); | 0 | 2023-12-24 19:29:49+00:00 | 2k |
Trodev-IT/ScanHub | app/src/main/java/com/trodev/scanhub/fragments/EmailFragment.java | [
{
"identifier": "EmailAdapter",
"path": "app/src/main/java/com/trodev/scanhub/adapters/EmailAdapter.java",
"snippet": "public class EmailAdapter extends RecyclerView.Adapter<EmailAdapter.MyViewHolder> {\n\n private Context context;\n private ArrayList<EmailModel> list;\n private String category;\n\n public EmailAdapter(Context context, ArrayList<EmailModel> list, String category) {\n this.context = context;\n this.list = list;\n this.category = category;\n }\n\n\n @NonNull\n @Override\n public EmailAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(context).inflate(R.layout.email_qr_item, parent, false);\n return new EmailAdapter.MyViewHolder(view);\n }\n\n @Override\n public void onBindViewHolder(@NonNull EmailAdapter.MyViewHolder holder, int position) {\n\n /*get data from database model*/\n EmailModel models = list.get(position);\n\n holder.from.setText(models.getEmail_from());\n holder.to.setText(models.getEmail_to());\n holder.time.setText(models.getTime());\n holder.date.setText(models.getDate());\n\n holder.itemView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n\n Intent intent = new Intent(context, EmailQrFullActivity.class);\n intent.putExtra(\"mFrom\", models.getEmail_from());\n intent.putExtra(\"mTo\", models.getEmail_to());\n intent.putExtra(\"mText\", models.getEmail_sms());\n context.startActivity(intent);\n\n }\n });\n\n }\n\n @Override\n public int getItemCount() {\n return list.size();\n }\n\n public class MyViewHolder extends RecyclerView.ViewHolder {\n\n TextView from, to, date, time;\n\n public MyViewHolder(@NonNull View itemView) {\n super(itemView);\n\n // Here its a Time & Date Section\n date = itemView.findViewById(R.id.date);\n time = itemView.findViewById(R.id.time);\n\n from = itemView.findViewById(R.id.fromTv);\n to = itemView.findViewById(R.id.toTv);\n\n\n }\n }\n}"
},
{
"identifier": "EmailModel",
"path": "app/src/main/java/com/trodev/scanhub/models/EmailModel.java",
"snippet": "public class EmailModel {\n\n public String email_from, email_to, email_sms, date, time, uid;\n\n public EmailModel() {\n }\n\n public EmailModel(String email_from, String email_to, String email_sms, String date, String time, String uid) {\n this.email_from = email_from;\n this.email_to = email_to;\n this.email_sms = email_sms;\n this.date = date;\n this.time = time;\n this.uid = uid;\n }\n\n public String getEmail_from() {\n return email_from;\n }\n\n public void setEmail_from(String email_from) {\n this.email_from = email_from;\n }\n\n public String getEmail_to() {\n return email_to;\n }\n\n public void setEmail_to(String email_to) {\n this.email_to = email_to;\n }\n\n public String getEmail_sms() {\n return email_sms;\n }\n\n public void setEmail_sms(String email_sms) {\n this.email_sms = email_sms;\n }\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n public String getTime() {\n return time;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n\n public String getUid() {\n return uid;\n }\n\n public void setUid(String uid) {\n this.uid = uid;\n }\n}"
}
] | import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.airbnb.lottie.LottieAnimationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.trodev.scanhub.R;
import com.trodev.scanhub.adapters.EmailAdapter;
import com.trodev.scanhub.models.EmailModel;
import java.util.ArrayList; | 1,078 | package com.trodev.scanhub.fragments;
public class EmailFragment extends Fragment {
private RecyclerView recyclerView;
DatabaseReference reference;
ArrayList<EmailModel> list; | package com.trodev.scanhub.fragments;
public class EmailFragment extends Fragment {
private RecyclerView recyclerView;
DatabaseReference reference;
ArrayList<EmailModel> list; | EmailAdapter adapter; | 0 | 2023-12-26 05:10:38+00:00 | 2k |
DMSAranda/backend-usersapp | src/main/java/com/dms/backend/usersapp/backendusersapp/controllers/UserController.java | [
{
"identifier": "UserDto",
"path": "src/main/java/com/dms/backend/usersapp/backendusersapp/models/dto/UserDto.java",
"snippet": "@Getter\n@Setter\npublic class UserDto{\n\n private Long id;\n\n private String username;\n\n private String email;\n\n private boolean admin;\n\n public UserDto() {\n }\n\n public UserDto(Long id, String username, String email, boolean admin) {\n this.id = id;\n this.username = username;\n this.email = email;\n this.admin = admin;\n }\n\n}"
},
{
"identifier": "User",
"path": "src/main/java/com/dms/backend/usersapp/backendusersapp/models/entities/User.java",
"snippet": "@Getter\n@Setter\n@Entity\n@Table(name=\"users\")\npublic class User implements IUser{\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @NotBlank\n @Size(min = 3, max = 12)\n @Column(unique = true)\n private String username;\n\n @NotBlank\n private String password;\n\n @Email\n @NotEmpty\n @Column(unique = true)\n private String email; \n\n @ManyToMany\n @JoinTable(name = \"users_roles\", \n joinColumns = @JoinColumn(name=\"user_id\"), \n inverseJoinColumns = @JoinColumn(name=\"role_id\"),\n uniqueConstraints = {@UniqueConstraint(columnNames = {\"user_id\", \"role_id\"} )} \n )\n private List<Role> roles;\n\n @Transient //no se mapea a la bbdd\n private boolean admin;\n\n}"
},
{
"identifier": "UserRequest",
"path": "src/main/java/com/dms/backend/usersapp/backendusersapp/models/request/UserRequest.java",
"snippet": "@Getter\n@Setter\npublic class UserRequest implements IUser{\n\n @NotBlank\n @Size(min = 3, max = 12)\n private String username;\n\n @Email\n @NotEmpty\n private String email; \n\n private boolean admin;\n}"
},
{
"identifier": "UserService",
"path": "src/main/java/com/dms/backend/usersapp/backendusersapp/services/UserService.java",
"snippet": "public interface UserService {\n\n List<UserDto> findAll();\n\n Optional<UserDto> findByID(Long id);\n\n UserDto save(User user);\n\n Optional<UserDto> update(UserRequest userRequest, Long id);\n\n void remove(Long id);\n\n Page<UserDto> findAll(Pageable pageable); \n}"
}
] | import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dms.backend.usersapp.backendusersapp.models.dto.UserDto;
import com.dms.backend.usersapp.backendusersapp.models.entities.User;
import com.dms.backend.usersapp.backendusersapp.models.request.UserRequest;
import com.dms.backend.usersapp.backendusersapp.services.UserService;
import jakarta.validation.Valid; | 839 | package com.dms.backend.usersapp.backendusersapp.controllers;
@RestController
@RequestMapping("/users")
@CrossOrigin(originPatterns = "*")
public class UserController {
@Autowired | package com.dms.backend.usersapp.backendusersapp.controllers;
@RestController
@RequestMapping("/users")
@CrossOrigin(originPatterns = "*")
public class UserController {
@Autowired | private UserService service; | 3 | 2023-12-29 15:55:27+00:00 | 2k |
singuuu/java-spring-api | src/main/java/com/singu/api/controllers/auth/AuthenticationController.java | [
{
"identifier": "AuthenticationRequest",
"path": "src/main/java/com/singu/api/domains/requests/AuthenticationRequest.java",
"snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class AuthenticationRequest {\n\n String password;\n private String email;\n}"
},
{
"identifier": "RegisterRequest",
"path": "src/main/java/com/singu/api/domains/requests/RegisterRequest.java",
"snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class RegisterRequest {\n\n private String firstname;\n private String lastname;\n private String email;\n private String password;\n private Role role;\n}"
},
{
"identifier": "AuthenticationResponse",
"path": "src/main/java/com/singu/api/domains/responses/AuthenticationResponse.java",
"snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class AuthenticationResponse {\n\n @JsonProperty(\"access_token\")\n private String accessToken;\n @JsonProperty(\"refresh_token\")\n private String refreshToken;\n}"
},
{
"identifier": "AuthenticationService",
"path": "src/main/java/com/singu/api/services/AuthenticationService.java",
"snippet": "@Service\n@RequiredArgsConstructor\npublic class AuthenticationService {\n private final UserRepository repository;\n private final TokenRepository tokenRepository;\n private final PasswordEncoder passwordEncoder;\n private final JwtService jwtService;\n private final AuthenticationManager authenticationManager;\n\n public AuthenticationResponse register(RegisterRequest request) {\n var user = User.builder()\n .firstname(request.getFirstname())\n .lastname(request.getLastname())\n .email(request.getEmail())\n .password(passwordEncoder.encode(request.getPassword()))\n .role(request.getRole())\n .build();\n var savedUser = repository.save(user);\n var jwtToken = jwtService.generateToken(user);\n var refreshToken = jwtService.generateRefreshToken(user);\n saveUserToken(savedUser, jwtToken);\n return AuthenticationResponse.builder()\n .accessToken(jwtToken)\n .refreshToken(refreshToken)\n .build();\n }\n\n public AuthenticationResponse authenticate(AuthenticationRequest request) {\n authenticationManager.authenticate(\n new UsernamePasswordAuthenticationToken(\n request.getEmail(),\n request.getPassword()\n )\n );\n var user = repository.findByEmail(request.getEmail())\n .orElseThrow();\n var jwtToken = jwtService.generateToken(user);\n var refreshToken = jwtService.generateRefreshToken(user);\n revokeAllUserTokens(user);\n saveUserToken(user, jwtToken);\n return AuthenticationResponse.builder()\n .accessToken(jwtToken)\n .refreshToken(refreshToken)\n .build();\n }\n\n private void saveUserToken(User user, String jwtToken) {\n var token = Token.builder()\n .user(user)\n .token(jwtToken)\n .tokenType(TokenType.BEARER)\n .expired(false)\n .revoked(false)\n .build();\n tokenRepository.save(token);\n }\n\n private void revokeAllUserTokens(User user) {\n var validUserTokens = tokenRepository.findAllValidTokenByUser(user.getId());\n if (validUserTokens.isEmpty())\n return;\n validUserTokens.forEach(token -> {\n token.setExpired(true);\n token.setRevoked(true);\n });\n tokenRepository.saveAll(validUserTokens);\n }\n\n public void refreshToken(\n HttpServletRequest request,\n HttpServletResponse response\n ) throws IOException {\n final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);\n final String refreshToken;\n final String userEmail;\n if (authHeader == null || !authHeader.startsWith(\"Bearer \")) {\n return;\n }\n refreshToken = authHeader.substring(7);\n userEmail = jwtService.extractUsername(refreshToken);\n if (userEmail != null) {\n var user = this.repository.findByEmail(userEmail)\n .orElseThrow();\n if (jwtService.isTokenValid(refreshToken, user)) {\n var accessToken = jwtService.generateToken(user);\n revokeAllUserTokens(user);\n saveUserToken(user, accessToken);\n var authResponse = AuthenticationResponse.builder()\n .accessToken(accessToken)\n .refreshToken(refreshToken)\n .build();\n new ObjectMapper().writeValue(response.getOutputStream(), authResponse);\n }\n }\n }\n}"
}
] | import com.singu.api.domains.requests.AuthenticationRequest;
import com.singu.api.domains.requests.RegisterRequest;
import com.singu.api.domains.responses.AuthenticationResponse;
import com.singu.api.services.AuthenticationService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
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 java.io.IOException; | 1,104 | package com.singu.api.controllers.auth;
@RestController
@RequiredArgsConstructor
@Tag(name = "Authentication")
@RequestMapping("/api/v1/auth")
public class AuthenticationController {
| package com.singu.api.controllers.auth;
@RestController
@RequiredArgsConstructor
@Tag(name = "Authentication")
@RequestMapping("/api/v1/auth")
public class AuthenticationController {
| private final AuthenticationService service; | 3 | 2023-12-28 17:32:16+00:00 | 2k |
vnlemanhthanh/sfg-spring-6-webapp | src/main/java/com/vnlemanhthanh/spring6webapp/services/BookServiceImpl.java | [
{
"identifier": "Book",
"path": "src/main/java/com/vnlemanhthanh/spring6webapp/domain/Book.java",
"snippet": "@Entity\npublic class Book {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n private String title;\n private String isbn;\n\n @ManyToMany\n @JoinTable(name = \"author_book\",\n joinColumns = @JoinColumn(name = \"book_id\"),\n inverseJoinColumns = @JoinColumn(name = \"author_id\"))\n private Set<Author> authors = new HashSet<>();\n\n @ManyToOne\n private Publisher publisher;\n\n public Publisher getPublisher() {\n return publisher;\n }\n\n public void setPublisher(Publisher publisher) {\n this.publisher = publisher;\n }\n\n public Set<Author> getAuthors() {\n return authors;\n }\n\n public void setAuthors(Set<Author> authors) {\n this.authors = authors;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getIsbn() {\n return isbn;\n }\n\n public void setIsbn(String isbn) {\n this.isbn = isbn;\n }\n\n @Override\n public String toString() {\n return \"Book{\" + \"id=\" + id + \", title='\" + title + '\\'' + \", isbn='\" + isbn + '\\'' + \", authors=\" + authors + '}';\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Book book = (Book) o;\n\n return getId() != null ? getId().equals(book.getId()) : book.getId() == null;\n }\n\n @Override\n public int hashCode() {\n return getId() != null ? getId().hashCode() : 0;\n }\n}"
},
{
"identifier": "BookRepository",
"path": "src/main/java/com/vnlemanhthanh/spring6webapp/repositories/BookRepository.java",
"snippet": "public interface BookRepository extends CrudRepository<Book, Long> {\n}"
}
] | import org.springframework.stereotype.Service;
import com.vnlemanhthanh.spring6webapp.domain.Book;
import com.vnlemanhthanh.spring6webapp.repositories.BookRepository; | 691 | /*
* Copyright (c) 2023. vnlemanhthanh.com
*/
package com.vnlemanhthanh.spring6webapp.services;
@Service
public class BookServiceImpl implements BookService {
private final BookRepository bookRepository;
public BookServiceImpl(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@Override | /*
* Copyright (c) 2023. vnlemanhthanh.com
*/
package com.vnlemanhthanh.spring6webapp.services;
@Service
public class BookServiceImpl implements BookService {
private final BookRepository bookRepository;
public BookServiceImpl(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@Override | public Iterable<Book> findAll() { | 0 | 2023-12-25 07:31:22+00:00 | 2k |
Deepennn/NetAPP | src/main/java/com/netapp/device/NetDevice.java | [
{
"identifier": "ARP",
"path": "src/main/java/com/netapp/packet/ARP.java",
"snippet": "public class ARP extends Packet {\n\n public static short HW_TYPE_ETHERNET = 0x1;\n\n public static short PROTO_TYPE_IP = 0x800;\n\n public static final short OP_REQUEST = 0x1;\n public static final short OP_REPLY = 0x2;\n\n protected short hardwareType;\n protected short protocolType;\n protected short opCode; // 1->REQ : 2-> REPLY\n\n protected String senderHardwareAddress;\n protected String senderProtocolAddress;\n protected String targetHardwareAddress;\n protected String targetProtocolAddress;\n\n public ARP(){\n super();\n }\n\n public short getHardwareType() {\n return hardwareType;\n }\n\n public void setHardwareType(short hardwareType) {\n this.hardwareType = hardwareType;\n }\n\n public short getProtocolType() {\n return protocolType;\n }\n\n public void setProtocolType(short protocolType) {\n this.protocolType = protocolType;\n }\n\n public short getOpCode() {\n return opCode;\n }\n\n public void setOpCode(short opCode) {\n this.opCode = opCode;\n }\n\n public String getSenderHardwareAddress() {\n return senderHardwareAddress;\n }\n\n public void setSenderHardwareAddress(String senderHardwareAddress) {\n this.senderHardwareAddress = senderHardwareAddress;\n }\n\n public String getSenderProtocolAddress() {\n return senderProtocolAddress;\n }\n\n public void setSenderProtocolAddress(String senderProtocolAddress) {\n this.senderProtocolAddress = senderProtocolAddress;\n }\n\n public String getTargetHardwareAddress() {\n return targetHardwareAddress;\n }\n\n public void setTargetHardwareAddress(String targetHardwareAddress) {\n this.targetHardwareAddress = targetHardwareAddress;\n }\n\n public String getTargetProtocolAddress() {\n return targetProtocolAddress;\n }\n\n public void setTargetProtocolAddress(String targetProtocolAddress) {\n this.targetProtocolAddress = targetProtocolAddress;\n }\n\n @Override\n public String toString() {\n return \"ARP{\" +\n \"hardwareType=\" + hardwareType +\n \", protocolType=\" + protocolType +\n \", opCode=\" + opCode +\n \", senderHardwareAddress='\" + senderHardwareAddress + '\\'' +\n \", senderProtocolAddress='\" + senderProtocolAddress + '\\'' +\n \", targetHardwareAddress='\" + targetHardwareAddress + '\\'' +\n \", targetProtocolAddress='\" + targetProtocolAddress + '\\'' +\n \", payload=\" + payload +\n '}';\n }\n\n}"
},
{
"identifier": "Ethernet",
"path": "src/main/java/com/netapp/packet/Ethernet.java",
"snippet": "public class Ethernet extends Packet {\n\n public static final String BROADCAST_MAC = \"FF:FF:FF:FF:FF:FF\";\n\n public static final short TYPE_ARP = 0x0806;\n public static final short TYPE_IPv4 = 0x0800;\n public static Map<Short, Class<? extends IPacket>> etherTypeClassMap;\n\n static {\n etherTypeClassMap = new HashMap<Short, Class<? extends IPacket>>();\n etherTypeClassMap.put(TYPE_ARP, ARP.class);\n etherTypeClassMap.put(TYPE_IPv4, IPv4.class);\n }\n\n private String sourceMAC;\n private String destinationMAC;\n private short etherType;\n private int checksum;\n\n public Ethernet(){\n super();\n }\n\n /**\n * 更新校验和\n */\n public void updateChecksum(){\n this.checksum = 0;\n this.setChecksum(this.calculateChecksum(this.toString()));\n }\n\n /**\n * @return 如果以太帧是广播帧,则返回true;否则返回false\n */\n public boolean isBroadcast() {\n return destinationMAC.equals(BROADCAST_MAC);\n }\n\n public String getSourceMAC() {\n return sourceMAC;\n }\n\n public String getDestinationMAC() {\n return destinationMAC;\n }\n\n public void setSourceMAC(String sourceMAC) {\n this.sourceMAC = sourceMAC;\n }\n\n public void setDestinationMAC(String destinationMAC) {\n this.destinationMAC = destinationMAC;\n }\n\n public int getEtherType() {\n return etherType;\n }\n\n public void setEtherType(short etherType) {\n this.etherType = etherType;\n }\n\n public int getChecksum() {\n return checksum;\n }\n\n public void setChecksum(int checksum) {\n this.checksum = checksum;\n }\n\n @Override\n public String toString() {\n return \"Ethernet{\" +\n \"sourceMAC='\" + sourceMAC + '\\'' +\n \", destinationMAC='\" + destinationMAC + '\\'' +\n \", etherType=\" + etherType +\n \", checksum=\" + checksum +\n \", payload=\" + payload +\n '}';\n }\n\n}"
}
] | import com.netapp.packet.ARP;
import com.netapp.packet.Ethernet;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicReference;
import static com.netapp.config.DeviceConfig.ARP_CACHE_PREFFIX;
import static com.netapp.config.DeviceConfig.ARP_CACHE_SUFFIX; | 1,378 | package com.netapp.device;
public abstract class NetDevice extends Device
{
/** ARP 缓存 */
protected AtomicReference<ArpCache> atomicCache;
/** 为ARP设置的输出缓存区 (不知道目的 MAC 的目的 IP) --> (对应数据包队列) */ | package com.netapp.device;
public abstract class NetDevice extends Device
{
/** ARP 缓存 */
protected AtomicReference<ArpCache> atomicCache;
/** 为ARP设置的输出缓存区 (不知道目的 MAC 的目的 IP) --> (对应数据包队列) */ | protected HashMap<String, BlockingQueue<Ethernet>> outputQueueMap; | 1 | 2023-12-23 13:03:07+00:00 | 2k |
jordqubbe/Extras | src/main/java/dev/jordgubbe/extras/commands/Vanish.java | [
{
"identifier": "Main",
"path": "src/main/java/dev/jordgubbe/extras/Main.java",
"snippet": "public final class Main extends JavaPlugin {\n\n public void configMethods() {\n getConfig().options().copyDefaults(true);\n saveDefaultConfig();\n }\n\n private void registerCommands() {\n Objects.requireNonNull(getCommand(\"enchant\")).setExecutor(new Enchant());\n Objects.requireNonNull(getCommand(\"give\")).setExecutor(new Give());\n Objects.requireNonNull(getCommand(\"vanish\")).setExecutor(new Vanish(this));\n Objects.requireNonNull(getCommand(\"coordinates\")).setExecutor(new Coordinates());\n Objects.requireNonNull(getCommand(\"hologram\")).setExecutor(new Spawn());\n Objects.requireNonNull(getCommand(\"reload\")).setExecutor(new Reload(this));\n }\n\n private void registerEvents() {\n PluginManager pm = this.getServer().getPluginManager();\n pm.registerEvents(new Chat(), this);\n pm.registerEvents(new JoinLeave(this), this);\n }\n\n @Override\n public void onEnable() {\n ConsoleUtils.sendToConsole(\"&a[Extras] Plugin has been enabled.\");\n configMethods();\n registerCommands();\n registerEvents();\n }\n\n @Override\n public void onDisable() {\n ConsoleUtils.sendToConsole(\"&c[Extras] Plugin has been disabled.\");\n }\n}"
},
{
"identifier": "ColorUtils",
"path": "src/main/java/dev/jordgubbe/extras/utils/ColorUtils.java",
"snippet": "public class ColorUtils {\n\n /**\n *\n * I DO NOT OWN THIS.\n * IT IS TAKEN (AND EDITED) FROM KODY SIMPSONS SIMP-API\n * https://github.com/Cortex-MC/SimpAPI\n * <p>\n * &0 = Black\n * &1 = Dark Blue\n * &2 = Dark Green\n * &3 = Dark Aqua\n * &4 = Dark Red\n * &5 = Dark Purple\n * &6 = Gold\n * &7 = Gray\n * &8 = Dark Gray\n * &9 = Blue\n * &a = Green\n * &b = Aqua\n * &c = Red\n * &d = Light Purple\n * &e = Yellow\n * &f = White\n * &k = Obfuscated\n * &l = Bold\n * &m = Strikethrough\n * &n = Underline\n * &o = Italic\n * &r = Reset\n */\n\n @Deprecated\n public static final String WITH_DELIMITER = \"((?<=%1$s)|(?=%1$s))\";\n private static final Pattern HEX_PATTERN = Pattern.compile(\"(&#[0-9a-fA-F]{6})\");\n\n public static String translate(String text) {\n Matcher matcher = HEX_PATTERN.matcher(text);\n StringBuffer sb = new StringBuffer();\n while (matcher.find()) {\n String hex = matcher.group(1).substring(1);\n matcher.appendReplacement(sb, \"\" + ChatColor.of(hex));\n }\n matcher.appendTail(sb);\n String hexColored = sb.toString();\n return ChatColor.translateAlternateColorCodes('&', hexColored);\n }\n\n public static TextComponent translateToTextComponent(String text) {\n String colored = translate(text);\n TextComponent base = new TextComponent();\n BaseComponent[] converted = TextComponent.fromLegacyText(colored);\n for (BaseComponent comp : converted) {\n base.addExtra(comp);\n }\n return base;\n }\n\n public static String format(String string) {\n return ColorUtils.translate(string);\n }\n\n public static String stripColor(String string) {\n return org.bukkit.ChatColor.stripColor(string);\n }\n\n}"
},
{
"identifier": "ConsoleUtils",
"path": "src/main/java/dev/jordgubbe/extras/utils/ConsoleUtils.java",
"snippet": "public enum ConsoleUtils {\n\n NOT_A_PLAYER(\"&cYou must be a player to use this command!\"),\n NO_PERMISSION(\"&cYou do not have permission to use this command!\"),\n INVALID_ARGUMENTS(\"&cInvalid arguments!\"),\n NOT_ENOUGH_ARGUMENTS(\"&cNot enough arguments!\"),\n INVALID_COMMAND(\"&cInvalid command!\"),\n INVALID_PLAYER(\"&cThat player does not exist!\"),\n CONFIGURATION_ISSUE(\"&cThere was an issue with the configuration file!\");\n\n private final String warningType;\n\n ConsoleUtils(String warningType) {\n this.warningType = warningType;\n }\n\n public String print() {\n return warningType;\n }\n\n public static String notAPlayer() {\n return ColorUtils.format(NOT_A_PLAYER.warningType);\n }\n\n public static void sendToConsole(String message) {\n Bukkit.getServer().getConsoleSender().sendMessage(message);\n }\n\n}"
}
] | import dev.jordgubbe.extras.Main;
import dev.jordgubbe.extras.utils.ColorUtils;
import dev.jordgubbe.extras.utils.ConsoleUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.UUID; | 1,290 | package dev.jordgubbe.extras.commands;
public class Vanish implements CommandExecutor {
private final ArrayList<UUID> vanished = new ArrayList<>();
private final Main plugin;
public Vanish(Main plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String s, String[] strings) {
if (!(sender instanceof Player player)) { | package dev.jordgubbe.extras.commands;
public class Vanish implements CommandExecutor {
private final ArrayList<UUID> vanished = new ArrayList<>();
private final Main plugin;
public Vanish(Main plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String s, String[] strings) {
if (!(sender instanceof Player player)) { | sender.sendMessage(ColorUtils.format(ConsoleUtils.NOT_A_PLAYER.print())); | 1 | 2023-12-27 06:37:11+00:00 | 2k |
LogDeArgentina/server | src/main/java/me/drpuc/lda/service/impl/UserServiceImpl.java | [
{
"identifier": "CallsignValidator",
"path": "src/main/java/me/drpuc/lda/config/CallsignValidator.java",
"snippet": "public class CallsignValidator extends RegexValidator {\n public CallsignValidator(String regex) {\n super(regex);\n }\n}"
},
{
"identifier": "Station",
"path": "src/main/java/me/drpuc/lda/entity/Station.java",
"snippet": "@Entity\n@Getter\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class Station {\n @Id\n @GeneratedValue(strategy = GenerationType.UUID)\n @Column(unique = true, updatable = false)\n private String uuid;\n\n @Column(unique = true, nullable = false)\n private String callsign;\n\n @Column(length = 6)\n private String grid;\n\n @JsonIgnore\n @ManyToMany\n private final List<Qso> qsos = new LinkedList<>();\n\n public Station(String callsign) {\n this.callsign = callsign;\n }\n\n public void addQso(Qso qso) {\n this.qsos.add(qso);\n }\n\n public void removeQso(Qso qso) {\n this.qsos.remove(qso);\n }\n}"
},
{
"identifier": "User",
"path": "src/main/java/me/drpuc/lda/entity/User.java",
"snippet": "@Entity\n@Getter\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@Table(name = \"\\\"user\\\"\")\npublic class User {\n @Id\n @GeneratedValue(strategy = GenerationType.UUID)\n @Column(unique = true, updatable = false)\n private String uuid;\n\n @Column(unique = true, nullable = false)\n private String callsign;\n\n @OneToMany\n private List<Station> stations = new LinkedList<>();\n\n @Column(nullable = false)\n private String name;\n\n @Column(unique = true, nullable = false)\n private String email;\n\n @JsonIgnore\n @Column(nullable = false)\n private String password;\n\n @Column(nullable = false)\n private Date createdAt;\n\n @Column(nullable = false)\n private boolean verified = false;\n\n private Date verifiedAt = null;\n\n @Column(nullable = false)\n private String role = \"USER\";\n\n public User(String callsign, String name, String email, String password) {\n this.callsign = callsign;\n this.name = name;\n this.email = email;\n this.password = password;\n this.createdAt = new Date();\n }\n\n public void addStation(Station station) {\n this.stations.add(station);\n }\n\n public void verify() {\n if (this.verifiedAt == null) {\n this.verified = true;\n this.verifiedAt = new Date();\n }\n }\n\n public void unverify() {\n this.verified = false;\n this.verifiedAt = null;\n }\n}"
},
{
"identifier": "StationRepository",
"path": "src/main/java/me/drpuc/lda/repository/StationRepository.java",
"snippet": "public interface StationRepository extends JpaRepository<Station, String> {\n Optional<Station> findByCallsign(String callsign);\n}"
},
{
"identifier": "UserRepository",
"path": "src/main/java/me/drpuc/lda/repository/UserRepository.java",
"snippet": "public interface UserRepository extends JpaRepository<User, String> {\n Optional<User> findByEmail(String email);\n Optional<User> findByUuid(String uuid);\n List<User> findByVerified(boolean verified);\n boolean existsByCallsignOrEmail(String callsign, String email);\n}"
},
{
"identifier": "Jwt",
"path": "src/main/java/me/drpuc/lda/security/jwt/Jwt.java",
"snippet": "@Component\npublic class Jwt {\n @Value(\"${jwt.secret}\")\n private String secret;\n\n @Value(\"${jwt.expiry}\")\n private int expiry;\n\n\n public String generateToken(String email) throws IllegalArgumentException, JWTCreationException {\n return JWT.create()\n .withSubject(\"User Details\")\n .withIssuer(\"LDA\")\n .withIssuedAt(new Date())\n .withClaim(\"email\", email)\n .withExpiresAt(new Date(System.currentTimeMillis() + expiry))\n .sign(Algorithm.HMAC256(secret));\n }\n\n public String validateTokenAndRetrieveEmail(String token) throws JWTVerificationException {\n JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret))\n .withSubject(\"User Details\")\n .withIssuer(\"LDA\")\n .build();\n DecodedJWT jwt = verifier.verify(token);\n return jwt.getClaim(\"email\").asString();\n }\n}"
},
{
"identifier": "UserService",
"path": "src/main/java/me/drpuc/lda/service/UserService.java",
"snippet": "public interface UserService {\n User getUserViaAuthentication(Authentication auth);\n User getUserByEmail(String email);\n User getUserByUuid(String uuid);\n String login(LoginDto dto);\n String register(RegisterDto dto);\n}"
}
] | import lombok.RequiredArgsConstructor;
import me.drpuc.lda.config.CallsignValidator;
import me.drpuc.lda.dto.request.auth.LoginDto;
import me.drpuc.lda.dto.request.auth.RegisterDto;
import me.drpuc.lda.entity.Station;
import me.drpuc.lda.entity.User;
import me.drpuc.lda.repository.StationRepository;
import me.drpuc.lda.repository.UserRepository;
import me.drpuc.lda.security.jwt.Jwt;
import me.drpuc.lda.service.UserService;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | 1,308 | package me.drpuc.lda.service.impl;
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService { | package me.drpuc.lda.service.impl;
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService { | private final UserRepository userRepository; | 4 | 2023-12-24 16:58:17+00:00 | 2k |
strokegmd/StrokeClient | stroke/client/ui/MainMenu.java | [
{
"identifier": "StrokeClient",
"path": "stroke/client/StrokeClient.java",
"snippet": "public class StrokeClient {\r\n\tpublic static Minecraft mc;\r\n\t\r\n\tpublic static String dev_username = \"megao4ko\";\r\n\tpublic static String title = \"[stroke] client ・ v1.0.00 | Minecraft 1.12.2\";\r\n\tpublic static String name = \"[stroke] client ・ \";\r\n\tpublic static String version = \"v1.0.00\";\r\n\t\r\n\tpublic static StrokeClient instance;\r\n\tpublic static ClickGuiScreen clickGui;\r\n\t\r\n\tpublic static SettingsManager settingsManager;\r\n\t\r\n\tpublic static boolean destructed = false;\r\n\t\r\n\tpublic StrokeClient()\r\n\t{\r\n\t\tinstance = this;\r\n\t\tsettingsManager = new SettingsManager();\r\n\t\tclickGui = new ClickGuiScreen();\r\n\t}\r\n\t\r\n\tpublic static void launchClient() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tsettingsManager = new SettingsManager();\r\n\t\t\r\n\t\tViaMCP.getInstance().start();\r\n\t\t\r\n\t\tSystem.out.println(\"[Stroke] Launching Stroke Client \" + version + \"!\");\r\n\t\t\r\n\t\tModuleManager.loadModules();\r\n\t\tCommandManager.loadCommands();\r\n\t\t\r\n\t\tfor(BaseModule module : ModuleManager.modules) {\r\n\t\t\tif(module.autoenable) {\r\n\t\t\t\tmodule.toggle(); module.toggle(); // bugfix lmao\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tclickGui = new ClickGuiScreen();\r\n\t\t\r\n\t\tSystem.out.println(\"[Stroke] All done!\");\r\n\t}\r\n\t\r\n\tpublic static void onKeyPress(int key) {\r\n\t\tfor(BaseModule module : ModuleManager.modules) {\r\n\t\t\tif(module.keybind == key && !(mc.currentScreen instanceof GuiChat) && !(mc.currentScreen instanceof GuiContainer) && !(mc.currentScreen instanceof GuiEditSign)) {\r\n\t\t\t\tmodule.toggle();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static int getScaledWidth() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tScaledResolution sr = new ScaledResolution(mc);\r\n\t\treturn sr.getScaledWidth();\r\n\t}\r\n\t\r\n\tpublic static int getScaledHeight() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tScaledResolution sr = new ScaledResolution(mc);\r\n\t\treturn sr.getScaledHeight();\r\n\t}\r\n\t\r\n\tpublic static int getDisplayWidth() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\treturn mc.displayWidth / 2;\r\n\t}\r\n\t\r\n\tpublic static int getDisplayHeight() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\treturn mc.displayHeight / 2;\r\n\t}\r\n\t\r\n\tpublic static String getUsername() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\treturn mc.getSession().getUsername();\r\n\t}\r\n\t\r\n\tpublic static void sendChatMessage(String message) {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tTextComponentString component = new TextComponentString(\"[\\2479Stroke§r] \" + message);\r\n\t\tmc.ingameGUI.getChatGUI().printChatMessage(component);\r\n\t}\r\n}"
},
{
"identifier": "ColorUtils",
"path": "stroke/client/util/ColorUtils.java",
"snippet": "public class ColorUtils {\r\n\tpublic static int primaryColor = 0xffffff;\r\n\tpublic static int secondaryColor = 0x9b90ff;\r\n\tpublic static int settingColor = 0x999999;\r\n\t\r\n\tpublic static int primaryObjectColor = new Color(primaryColor).hashCode();\r\n\tpublic static int secondaryObjectColor = new Color(secondaryColor).hashCode();\r\n\t\r\n\t// stolen again lol kekw xd lmao lmfao))))))\r\n\t// best c0d3r ever\r\n\tpublic static int getRainbow(float seconds, float saturation, float brightness, int index) {\r\n\t\tfloat hue = ((System.currentTimeMillis() + index) % (int)(seconds * 1000)) / (float)(seconds * 1000);\r\n\t\tint color = Color.HSBtoRGB(hue, saturation, brightness);\r\n\t\treturn color;\r\n\t}\r\n}\r"
}
] | import org.lwjgl.opengl.GL11;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiMultiplayer;
import net.minecraft.client.gui.GuiOptions;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiWorldSelection;
import net.minecraft.util.ResourceLocation;
import net.stroke.client.StrokeClient;
import net.stroke.client.util.ColorUtils;
| 1,171 | package net.stroke.client.ui;
public class MainMenu extends GuiScreen {
public String[] buttons = {"Singleplayer", "Multiplayer", "Alts", "Options", "Ragequit!1!11!!", ""};
public boolean singleplayer = false;
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
if(!singleplayer) {
buttonList.clear();
mc.getTextureManager().bindTexture(new ResourceLocation("stroke/background.jpg"));
drawModalRectWithCustomSizedTexture(0, 0, 0, 0, width, height, width, height);
drawGradientRect(0, height - 100, width, height, 0x00000000, 0xff000000);
GL11.glPushMatrix();
GL11.glScalef(3.0f, 3.0f, 3.0f);
| package net.stroke.client.ui;
public class MainMenu extends GuiScreen {
public String[] buttons = {"Singleplayer", "Multiplayer", "Alts", "Options", "Ragequit!1!11!!", ""};
public boolean singleplayer = false;
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
if(!singleplayer) {
buttonList.clear();
mc.getTextureManager().bindTexture(new ResourceLocation("stroke/background.jpg"));
drawModalRectWithCustomSizedTexture(0, 0, 0, 0, width, height, width, height);
drawGradientRect(0, height - 100, width, height, 0x00000000, 0xff000000);
GL11.glPushMatrix();
GL11.glScalef(3.0f, 3.0f, 3.0f);
| mc.fontRendererObj.drawStringWithShadow("Stroke Client", 2, 2, ColorUtils.primaryColor);
| 1 | 2023-12-31 10:56:59+00:00 | 2k |
Supriya2301/EVotingSystem-SpringJPA | EVotingSystem/src/main/java/com/codingninjas/EVotingSystem/services/VotingService.java | [
{
"identifier": "Election",
"path": "EVotingSystem/src/main/java/com/codingninjas/EVotingSystem/entities/Election.java",
"snippet": "@Entity\npublic class Election {\n\t@Id\n\t@GeneratedValue(strategy= GenerationType.AUTO)\n\tprivate long id;\n\t\n\t@Column(unique=true)\n\tprivate String name;\n\n\tpublic Election() {\n\t}\n\n\tpublic Election(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\t\n}"
},
{
"identifier": "ElectionChoice",
"path": "EVotingSystem/src/main/java/com/codingninjas/EVotingSystem/entities/ElectionChoice.java",
"snippet": "@Entity\npublic class ElectionChoice {\n\t@Id\n\t@GeneratedValue(strategy=GenerationType.AUTO)\n\tprivate long id;\n\t\n\tprivate String name;\n\n\t@ManyToOne(cascade=CascadeType.ALL)\n\tprivate Election election;\n\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic Election getElection() {\n\t\treturn election;\n\t}\n\n\tpublic void setElection(Election election) {\n\t\tthis.election = election;\n\t}\n\t\n}"
},
{
"identifier": "User",
"path": "EVotingSystem/src/main/java/com/codingninjas/EVotingSystem/entities/User.java",
"snippet": "@Entity\n@Table(name=\"users\")\npublic class User {\n\t@Id\n\t@GeneratedValue(strategy=GenerationType.AUTO)\n\tprivate long id;\n\t\n\t@Column(unique=true)\n\tprivate String name; //Custom Exception\n\t\n\tpublic User() {\n\t}\n\n\tpublic User(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n}"
},
{
"identifier": "Vote",
"path": "EVotingSystem/src/main/java/com/codingninjas/EVotingSystem/entities/Vote.java",
"snippet": "@Entity\npublic class Vote {\n\t@Id\n\t@GeneratedValue(strategy=GenerationType.AUTO)\n\tprivate long id;\n\t\n\t@OneToOne(cascade = CascadeType.ALL)\n\tprivate User user;\n\t\n\t@ManyToOne(cascade = CascadeType.ALL)\n\tprivate Election election;\n\t\n\t@ManyToOne(cascade=CascadeType.ALL)\n\tprivate ElectionChoice electionChoice;\n\n\tpublic long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n\n\tpublic Election getElection() {\n\t\treturn election;\n\t}\n\n\tpublic void setElection(Election election) {\n\t\tthis.election = election;\n\t}\n\n\tpublic ElectionChoice getElectionChoice() {\n\t\treturn electionChoice;\n\t}\n\n\tpublic void setElectionChoice(ElectionChoice electionChoice) {\n\t\tthis.electionChoice = electionChoice;\n\t}\n\n}"
},
{
"identifier": "ElectionChoiceRepository",
"path": "EVotingSystem/src/main/java/com/codingninjas/EVotingSystem/repositories/ElectionChoiceRepository.java",
"snippet": "public interface ElectionChoiceRepository extends JpaRepository<ElectionChoice,Long>{\n\t\n\t@Query(\"Select count(ec) From ElectionChoice ec where ec.election = :election\")\n\tlong countByElection(@Param(\"election\") Election election);\n\n\tOptional<ElectionChoice> findByNameAndElection(String electionChoiceName, Election election);\n\t\n\t@Query(value = \"SELECT ec.* FROM election_choice ec \"\n + \"JOIN vote v ON ec.id = v.election_choice_id \"\n + \"WHERE ec.election_id = :electionId \"\n + \"GROUP BY ec.id \"\n + \"ORDER BY COUNT(v.id) DESC LIMIT 1\", nativeQuery = true)\n ElectionChoice findElectionChoiceWithMaxVotes(@Param(\"electionId\") Long electionId);\n}"
},
{
"identifier": "ElectionRepository",
"path": "EVotingSystem/src/main/java/com/codingninjas/EVotingSystem/repositories/ElectionRepository.java",
"snippet": "public interface ElectionRepository extends JpaRepository<Election, Long> {\n\n\tOptional<Election> findByName(String electionName);\n\n}"
},
{
"identifier": "UserRepository",
"path": "EVotingSystem/src/main/java/com/codingninjas/EVotingSystem/repositories/UserRepository.java",
"snippet": "public interface UserRepository extends JpaRepository<User,Long> {\n\n\tOptional<User> findByName(String userName);\n\n}"
},
{
"identifier": "VoteRepository",
"path": "EVotingSystem/src/main/java/com/codingninjas/EVotingSystem/repositories/VoteRepository.java",
"snippet": "public interface VoteRepository extends JpaRepository<Vote, Long> {\n\t@Query(value = \"SELECT COUNT(*) FROM vote\", nativeQuery = true)\n\tLong countTotalVotes();\n\n\t@Query(\"SELECT COUNT(v) FROM Vote v WHERE v.election = :election\")\n\tLong countVotesByElection(@Param(\"election\") Election election);\n}"
}
] | import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.codingninjas.EVotingSystem.entities.Election;
import com.codingninjas.EVotingSystem.entities.ElectionChoice;
import com.codingninjas.EVotingSystem.entities.User;
import com.codingninjas.EVotingSystem.entities.Vote;
import com.codingninjas.EVotingSystem.repositories.ElectionChoiceRepository;
import com.codingninjas.EVotingSystem.repositories.ElectionRepository;
import com.codingninjas.EVotingSystem.repositories.UserRepository;
import com.codingninjas.EVotingSystem.repositories.VoteRepository; | 1,511 | package com.codingninjas.EVotingSystem.services;
@Service
public class VotingService {
@Autowired
VoteRepository voteRepository;
@Autowired
UserRepository userRepository;
@Autowired
ElectionRepository electionRepository;
@Autowired | package com.codingninjas.EVotingSystem.services;
@Service
public class VotingService {
@Autowired
VoteRepository voteRepository;
@Autowired
UserRepository userRepository;
@Autowired
ElectionRepository electionRepository;
@Autowired | ElectionChoiceRepository electionChoiceRepository; | 4 | 2023-12-30 06:54:58+00:00 | 2k |
piovas-lu/condominio | src/main/java/app/condominio/ControllersConfig.java | [
{
"identifier": "Usuario",
"path": "src/main/java/app/condominio/domain/Usuario.java",
"snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"usuarios\")\r\npublic class Usuario implements Serializable {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\r\n\tprivate Long id;\r\n\r\n\t@NotBlank\r\n\t@Size(min = 1, max = 50)\r\n\tprivate String username;\r\n\r\n\t@NotBlank\r\n\t@Size(min = 4, max = 100)\r\n\tprivate String password;\r\n\r\n\t@NotNull\r\n\tprivate Boolean ativo;\r\n\r\n\t@NotBlank\r\n\t@Size(min = 1, max = 50)\r\n\tprivate String nome;\r\n\r\n\t@NotBlank\r\n\t@Size(min = 1, max = 100)\r\n\tprivate String sobrenome;\r\n\r\n\t@NotBlank\r\n\t@Size(min = 1, max = 100)\r\n\t@Email\r\n\tprivate String email;\r\n\t// LATER validar email ao criar conta\r\n\r\n\t@ElementCollection(targetClass = Autorizacao.class)\r\n\t@CollectionTable(name = \"autorizacoes\", joinColumns = @JoinColumn(name = \"id_usuario\"))\r\n\t@Enumerated(EnumType.STRING)\r\n\t@Column(name = \"autorizacao\")\r\n\tprivate Set<Autorizacao> autorizacoes = new HashSet<>();\r\n\r\n\t@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true)\r\n\t@JoinColumn(name = \"idcondominio\")\r\n\tprivate Condominio condominio;\r\n\r\n\tpublic String nomeCompleto() {\r\n\t\tif (sobrenome != null) {\r\n\t\t\treturn nome + \" \" + sobrenome;\r\n\t\t} else {\r\n\t\t\treturn nome;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic Long getId() {\r\n\t\treturn id;\r\n\t}\r\n\r\n\tpublic void setId(Long id) {\r\n\t\tthis.id = id;\r\n\t}\r\n\r\n\tpublic String getUsername() {\r\n\t\treturn username;\r\n\t}\r\n\r\n\tpublic void setUsername(String username) {\r\n\t\tthis.username = username;\r\n\t}\r\n\r\n\tpublic String getPassword() {\r\n\t\treturn password;\r\n\t}\r\n\r\n\tpublic void setPassword(String password) {\r\n\t\tthis.password = password;\r\n\t}\r\n\r\n\tpublic Boolean getAtivo() {\r\n\t\treturn ativo;\r\n\t}\r\n\r\n\tpublic void setAtivo(Boolean ativo) {\r\n\t\tthis.ativo = ativo;\r\n\t}\r\n\r\n\tpublic String getNome() {\r\n\t\treturn nome;\r\n\t}\r\n\r\n\tpublic void setNome(String nome) {\r\n\t\tthis.nome = nome;\r\n\t}\r\n\r\n\tpublic String getSobrenome() {\r\n\t\treturn sobrenome;\r\n\t}\r\n\r\n\tpublic void setSobrenome(String sobrenome) {\r\n\t\tthis.sobrenome = sobrenome;\r\n\t}\r\n\r\n\tpublic String getEmail() {\r\n\t\treturn email;\r\n\t}\r\n\r\n\tpublic void setEmail(String email) {\r\n\t\tthis.email = email;\r\n\t}\r\n\r\n\tpublic Set<Autorizacao> getAutorizacoes() {\r\n\t\treturn autorizacoes;\r\n\t}\r\n\r\n\tpublic void setAutorizacoes(Set<Autorizacao> autorizacoes) {\r\n\t\tthis.autorizacoes = autorizacoes;\r\n\t}\r\n\r\n\tpublic Condominio getCondominio() {\r\n\t\treturn condominio;\r\n\t}\r\n\r\n\tpublic void setCondominio(Condominio condominio) {\r\n\t\tthis.condominio = condominio;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (obj == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (getClass() != obj.getClass()) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tUsuario other = (Usuario) obj;\r\n\t\tif (id == null) {\r\n\t\t\tif (other.id != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!id.equals(other.id)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n}\r"
},
{
"identifier": "UsuarioService",
"path": "src/main/java/app/condominio/service/UsuarioService.java",
"snippet": "public interface UsuarioService extends CrudService<Usuario, Long> {\r\n\r\n\tpublic void salvarSindico(Usuario usuario);\r\n\r\n\tpublic void salvarCondomino(Usuario usuario);\r\n\r\n\tpublic void salvarAdmin(Usuario usuario);\r\n\r\n\tpublic Usuario ler(String username);\r\n\r\n\tpublic Usuario lerLogado();\r\n\r\n\tpublic boolean redefinirSenha(String username);\r\n\r\n\tpublic boolean redefinirSenha(String username, String token, String password);\r\n\r\n}\r"
}
] | import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import app.condominio.domain.Usuario;
import app.condominio.service.UsuarioService;
| 1,304 | package app.condominio;
@ControllerAdvice
public class ControllersConfig {
@Autowired
| package app.condominio;
@ControllerAdvice
public class ControllersConfig {
@Autowired
| UsuarioService usuarioService;
| 1 | 2023-12-29 22:19:42+00:00 | 2k |
HuXin0817/shop_api | framework/src/main/java/cn/lili/modules/wallet/entity/dos/MemberWithdrawApply.java | [
{
"identifier": "SensitiveStrategy",
"path": "framework/src/main/java/cn/lili/common/security/sensitive/enums/SensitiveStrategy.java",
"snippet": "public enum SensitiveStrategy {\n /**\n * Username sensitive strategy.\n */\n USERNAME(s -> s.replaceAll(\"(\\\\S)\\\\S(\\\\S*)\", \"$1*$2\")),\n /**\n * Id card sensitive type.\n */\n ID_CARD(s -> s.replaceAll(\"(\\\\d{4})\\\\d{10}(\\\\w{4})\", \"$1****$2\")),\n /**\n * Phone sensitive type.\n */\n PHONE(s -> s.replaceAll(\"(\\\\d{3})\\\\d{4}(\\\\d{4})\", \"$1****$2\")),\n /**\n * Email sensitive type.\n */\n EMAIL(s -> s.replaceAll(\"(^\\\\w)[^@]*(@.*$)\", \"$1****$2\")),\n /**\n * Name sensitive type.\n */\n NAME(s -> s.replaceAll(\"^(.{3}).+(.{3})$\", \"$1*****$2\")),\n /**\n * Address sensitive type.\n */\n ADDRESS(s -> s.replaceAll(\"(\\\\S{3})\\\\S{2}(\\\\S*)\\\\S{2}\", \"$1****$2****\"));\n\n\n private final Function<String, String> desensitizer;\n\n SensitiveStrategy(Function<String, String> desensitizer) {\n this.desensitizer = desensitizer;\n }\n\n public Function<String, String> desensitizer() {\n return desensitizer;\n }\n}"
},
{
"identifier": "WithdrawStatusEnum",
"path": "framework/src/main/java/cn/lili/modules/wallet/entity/enums/WithdrawStatusEnum.java",
"snippet": "public enum WithdrawStatusEnum {\n /**\n * 申请中\n */\n APPLY(\"申请中\"),\n /**\n * 审核成功即提现成功\n */\n VIA_AUDITING(\"审核通过\"),\n /**\n * 审核未通过\n */\n FAIL_AUDITING(\"审核未通过\"),\n /**\n * 提现成功\n */\n SUCCESS(\"提现成功\"),\n /**\n * 提现失败\n */\n ERROR(\"提现失败\");\n\n private String description;\n\n public String description() {\n return description;\n }\n\n WithdrawStatusEnum(String description) {\n this.description = description;\n }\n\n}"
},
{
"identifier": "BaseEntity",
"path": "framework/src/main/java/cn/lili/mybatis/BaseEntity.java",
"snippet": "@Data\n@JsonIgnoreProperties(value = { \"handler\", \"fieldHandler\"})\n@AllArgsConstructor\n@NoArgsConstructor\npublic abstract class BaseEntity implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n\n @TableId\n @ApiModelProperty(value = \"唯一标识\", hidden = true)\n private String id;\n\n\n @CreatedBy\n @TableField(fill = FieldFill.INSERT)\n @ApiModelProperty(value = \"创建者\", hidden = true)\n private String createBy;\n\n @CreatedDate\n @JsonFormat(timezone = \"GMT+8\", pattern = \"yyyy-MM-dd HH:mm:ss\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @TableField(fill = FieldFill.INSERT)\n @ApiModelProperty(value = \"创建时间\", hidden = true)\n @Field(type = FieldType.Date, format = DateFormat.custom, pattern = \"yyyy-MM-dd HH:mm:ss || yyyy-MM-dd || yyyy/MM/dd HH:mm:ss|| yyyy/MM/dd ||epoch_millis\")\n private Date createTime;\n\n @LastModifiedBy\n @TableField(fill = FieldFill.UPDATE)\n @ApiModelProperty(value = \"更新者\", hidden = true)\n private String updateBy;\n\n @LastModifiedDate\n @JsonFormat(timezone = \"GMT+8\", pattern = \"yyyy-MM-dd HH:mm:ss\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @TableField(fill = FieldFill.INSERT_UPDATE)\n @ApiModelProperty(value = \"更新时间\", hidden = true)\n @Field(type = FieldType.Date, format = DateFormat.custom, pattern = \"yyyy-MM-dd HH:mm:ss || yyyy-MM-dd || yyyy/MM/dd HH:mm:ss|| yyyy/MM/dd ||epoch_millis\")\n private Date updateTime;\n\n @TableField(fill = FieldFill.INSERT)\n @ApiModelProperty(value = \"删除标志 true/false 删除/未删除\", hidden = true)\n private Boolean deleteFlag;\n\n}"
}
] | import cn.lili.common.security.sensitive.Sensitive;
import cn.lili.common.security.sensitive.enums.SensitiveStrategy;
import cn.lili.modules.wallet.entity.enums.WithdrawStatusEnum;
import cn.lili.mybatis.BaseEntity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date; | 1,217 | package cn.lili.modules.wallet.entity.dos;
/**
* 会员提现申请
*
* @author pikachu
* @since 2020-02-25 14:10:16
*/
@Data
@TableName("li_member_withdraw_apply")
@ApiModel(value = "会员提现申请") | package cn.lili.modules.wallet.entity.dos;
/**
* 会员提现申请
*
* @author pikachu
* @since 2020-02-25 14:10:16
*/
@Data
@TableName("li_member_withdraw_apply")
@ApiModel(value = "会员提现申请") | public class MemberWithdrawApply extends BaseEntity { | 2 | 2023-12-24 19:45:18+00:00 | 2k |
bta-team-port/moon-mod | src/main/java/teamport/moonmod/mixin/RenderGlobalMixin.java | [
{
"identifier": "ISpace",
"path": "src/main/java/teamport/moonmod/world/ISpace.java",
"snippet": "public interface ISpace {\n\tfloat getGravityScalar();\n\tboolean suffocate();\n\tString getCelestialMoonTexture();\n\tString getCelestialSunTexture();\n\tfloat getStarBrightness(World world);\n}"
},
{
"identifier": "WorldTypeMoon",
"path": "src/main/java/teamport/moonmod/world/WorldTypeMoon.java",
"snippet": "public class WorldTypeMoon extends WorldTypeOverworld {\n\n\tpublic WorldTypeMoon(String languageKey) {\n\t\tsuper(languageKey, Weather.overworldClear, new WindManagerGeneric(), SeasonConfig.builder()\n\t\t\t.withSingleSeason(Seasons.NULL)\n\t\t\t.build());\n\t}\n\n\t@Override\n\tpublic int getMinY() {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxY() {\n\t\treturn 127;\n\t}\n\n\t@Override\n\tpublic int getOceanY() {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic BiomeProvider createBiomeProvider(World world) {\n\t\treturn new BiomeProviderMoon(world.getRandomSeed(), this);\n\t}\n\n\t@Override\n\tpublic float getCloudHeight() {\n\t\treturn -64;\n\t}\n\n\t@Override\n\tpublic ChunkGenerator createChunkGenerator(World world) {\n\t\treturn new ChunkGeneratorMoon(world);\n\t}\n\n\t@Override\n\tpublic boolean hasAurora() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isValidSpawn(World world, int x, int y, int z) {\n\t\treturn world.getBlockId(x, y -1, z) == MoonModBlocks.regolith.id;\n\t}\n\n\t@Override\n\tpublic boolean mayRespawn() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic int getDayNightCycleLengthTicks() {\n\t\treturn 24000;\n\t}\n\n\t@Override\n\tpublic float[] getSunriseColor(float timeOfDay, float partialTick) {\n\t\treturn new float[] {0.0f, 0.0f, 0.0f, 0.0f};\n\t}\n\n\t@Override\n\tpublic int getSkyDarken(World world, long tick, float partialTick) {\n\t\tint subtracted;\n\t\tfloat f1 = this.getCelestialAngle(world, tick, partialTick);\n\t\tfloat f2 = 1.0f - (MathHelper.cos(f1 * 3.141593f * 2.0f) * 2.0f + 0.5f);\n\t\tif (f2 < 0.0f) {\n\t\t\tf2 = 0.0f;\n\t\t}\n\t\tif (f2 > 1.0f) {\n\t\t\tf2 = 1.0f;\n\t\t}\n\t\tfloat weatherOffset = 0.0f;\n\t\tif (world.getCurrentWeather() != null) {\n\t\t\tweatherOffset = (float)world.getCurrentWeather().subtractLightLevel * world.weatherManager.getWeatherIntensity() * world.weatherManager.getWeatherPower();\n\t\t}\n\t\tif ((subtracted = (int)(f2 * (11.0f - weatherOffset) + weatherOffset)) > 8) {\n\t\t\tsubtracted = 12;\n\t\t}\n\t\treturn subtracted;\n\t}\n\n\t@Override\n\tpublic float getCelestialAngle(World world, long tick, float partialTick) {\n\t\treturn 0.5F;\n\t}\n\n\n\t@Override\n\tpublic Vec3d getFogColor(float timeOfDay, float partialTick) {\n\t\tint i = 0;\n\t\tfloat f2 = MathHelper.cos(timeOfDay * 3.141593F * 2.0F) * 2.0F + 0.5F;\n\t\tif(f2 < 0.0F)\n\t\t{\n\t\t\tf2 = 0.0F;\n\t\t}\n\t\tif(f2 > 1.0F)\n\t\t{\n\t\t\tf2 = 1.0F;\n\t\t}\n\t\tfloat f3 = (float)(i >> 16 & 0xff) / 255F;\n\t\tfloat f4 = (float)(i >> 8 & 0xff) / 255F;\n\t\tfloat f5 = (float)(i & 0xff) / 255F;\n\t\tf3 *= f2 * 0.94F + 0.06F;\n\t\tf4 *= f2 * 0.94F + 0.06F;\n\t\tf5 *= f2 * 0.91F + 0.09F;\n\t\treturn Vec3d.createVector(f3, f4, f5);\n\t}\n}"
}
] | import teamport.moonmod.world.ISpace;
import teamport.moonmod.world.WorldTypeMoon;
import net.minecraft.client.render.RenderEngine;
import net.minecraft.client.render.RenderGlobal;
import net.minecraft.core.block.Block;
import net.minecraft.core.block.entity.TileEntity;
import net.minecraft.core.entity.Entity;
import net.minecraft.core.entity.player.EntityPlayer;
import net.minecraft.core.enums.EnumBlockSoundEffectType;
import net.minecraft.core.sound.SoundType;
import net.minecraft.core.world.LevelListener;
import net.minecraft.core.world.World;
import org.lwjgl.opengl.GL11;
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; | 1,408 | package teamport.moonmod.mixin;
@Mixin(value = RenderGlobal.class, remap = false)
public class RenderGlobalMixin implements LevelListener {
@Shadow
private World worldObj;
@Shadow
private RenderEngine renderEngine;
@Inject(method = "drawSky(F)V",
at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glBindTexture(II)V",
shift = At.Shift.AFTER,
ordinal = 1))
private void renderMoonImage(float renderPartialTicks, CallbackInfo cbi) {// Replace moon texture | package teamport.moonmod.mixin;
@Mixin(value = RenderGlobal.class, remap = false)
public class RenderGlobalMixin implements LevelListener {
@Shadow
private World worldObj;
@Shadow
private RenderEngine renderEngine;
@Inject(method = "drawSky(F)V",
at = @At(value = "INVOKE", target = "Lorg/lwjgl/opengl/GL11;glBindTexture(II)V",
shift = At.Shift.AFTER,
ordinal = 1))
private void renderMoonImage(float renderPartialTicks, CallbackInfo cbi) {// Replace moon texture | if (this.worldObj.getWorldType() instanceof ISpace) { | 0 | 2023-12-24 14:52:01+00:00 | 2k |
khoa070104/StudentManagerJava | src/view/StudentManagement.java | [
{
"identifier": "Inputter",
"path": "src/inputter/Inputter.java",
"snippet": "public class Inputter {\n private static Scanner sc = new Scanner(System.in);\n\n public static String getInputString(String prompt) {\n System.out.print(prompt);\n return sc.nextLine();\n }\n\n public static int getInputInt(String prompt) {\n while (true) {\n try {\n System.out.print(prompt);\n return Integer.parseInt(sc.nextLine());\n } catch (NumberFormatException e) {\n System.out.println(\"Invalid input. Please enter a valid integer.\");\n }\n }\n }\n\n public static double getInputDouble(String prompt) {\n while (true) {\n try {\n System.out.print(prompt);\n return Double.parseDouble(sc.nextLine());\n } catch (NumberFormatException e) {\n System.out.println(\"Invalid input. Please enter a valid number.\");\n }\n }\n }\n public static String inputStr(String msg, String pattern) {\n while (true) {\n System.out.print(msg);\n String input = sc.nextLine().trim();\n if (Pattern.matches(pattern, input)) \n return input;\n else\n System.out.println(\"Invalid format. Please enter a valid value.\");\n }\n }\n}"
},
{
"identifier": "StudentList",
"path": "src/model/StudentList.java",
"snippet": "public class StudentList extends ArrayList<Student> {\n\n // this \n public void listStudent() {\n Collections.sort(this, (o1,o2)->o1.getStudentID().compareTo(o2.getStudentID()));\n System.out.println(\"List:\");\n for (Student t : this) {\n System.out.println(t.toString());\n }\n }\n\n public boolean readTextFile(String filename) {\n File f = new File(filename);\n if (!f.exists()) {\n return false;\n }\n try ( Scanner sc = new Scanner(f)) {\n while (sc.hasNext()) {\n String part[] = sc.nextLine().split(\",\");\n if (part.length == 6) {\n String id = part[0].substring(11);\n String fname = part[1].substring(11).trim();\n String lname = part[2].substring(10).trim();\n String age = part[3].substring(4).trim();\n String d = part[4].substring(6).trim();\n String gen = part[5].substring(8).trim();\n Student s = new Student(id, fname, lname, gen, d);\n this.add(s);\n }\n }\n\n } catch (Exception e) {\n return false;\n }\n return true;\n }\n public int searchId(String id){\n for (int i = 0; i < this.size(); i++) {\n if(this.get(i).getStudentID().equalsIgnoreCase(id))\n return i;\n }\n return -1;\n }\n\n public boolean seachIf(Predicate<Student> predicate) {\n for (Student p : this) {\n if (predicate.test(p)) {\n System.out.println(p.toString());\n return true;\n }\n }\n return false;\n }\n \n public boolean addNewStudent(){\n String id = Inputter.getInputString(\"Enter ID: \");\n if(searchId(id)!= -1)\n return false;\n \n String fname = Inputter.getInputString(\"Enter FirstName: \");\n String lname = Inputter.getInputString(\"Enter FirstName: \");\n String dob = Inputter.inputStr(\"Enter DOB: \", \"dd/MM/yyyy\");\n String gen = Inputter.getInputString(\"Enter gender: \");\n this.add(new Student(id, fname, lname, gen, dob));\n \n return true;\n }\n \n}"
}
] | import inputter.Inputter;
import model.StudentList; | 1,044 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package view;
/**
*
* @author Khoa Bug
*/
public class StudentManagement {
public static void menu() {
System.out.println("1. List\n2. Search\n3.Add new\n4.Exit");
}
public static void menu_search() {
System.out.println("1.Search Gender\n2.Search ID");
}
public static void main(String[] args) {
StudentManagement s11= new StudentManagement();
StudentList s = new StudentList();
if(s.readTextFile("src\\model\\student.txt"))
System.out.println("Success!");
StudentManagement.menu(); | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package view;
/**
*
* @author Khoa Bug
*/
public class StudentManagement {
public static void menu() {
System.out.println("1. List\n2. Search\n3.Add new\n4.Exit");
}
public static void menu_search() {
System.out.println("1.Search Gender\n2.Search ID");
}
public static void main(String[] args) {
StudentManagement s11= new StudentManagement();
StudentList s = new StudentList();
if(s.readTextFile("src\\model\\student.txt"))
System.out.println("Success!");
StudentManagement.menu(); | int choice = Inputter.getInputInt("Enter your choice:"); | 0 | 2023-12-25 16:57:07+00:00 | 2k |
MuskStark/EasyECharts | src/main/java/com/github/muskstark/echart/attribute/series/Series.java | [
{
"identifier": "BackgroundStyle",
"path": "src/main/java/com/github/muskstark/echart/style/background/BackgroundStyle.java",
"snippet": "@Getter\npublic class BackgroundStyle {\n\n private String color;\n private String borderColor;\n private String borderWidth;\n private String borderType;\n private Integer[] borderRadius;\n private Integer shadowBlur;\n private Color shadowColor;\n private Integer shadowOffsetX;\n private Integer shadowOffsetY;\n private Integer opacity;\n\n public BackgroundStyle defineColor(String color) {\n this.color = color;\n return this;\n }\n\n public BackgroundStyle defineBorderColor(String borderColor) {\n this.borderColor = borderColor;\n return this;\n }\n\n public BackgroundStyle defineBorderWidth(String borderWidth) {\n this.borderWidth = borderWidth;\n return this;\n }\n\n public BackgroundStyle defineBorderType(String borderType) {\n this.borderType = borderType;\n return this;\n }\n\n public BackgroundStyle defineBorderRadius(Integer leftUp, Integer rightUp, Integer rightDown, Integer leftDown) {\n this.borderRadius = new Integer[]{leftUp, rightUp, rightDown, leftDown};\n return this;\n }\n public BackgroundStyle defineBorderRadius(Integer allRadius) {\n this.borderRadius = new Integer[]{allRadius, allRadius, allRadius, allRadius};\n return this;\n }\n\n public BackgroundStyle defineShadowBlur(Integer shadowBlur) {\n this.shadowBlur = shadowBlur;\n return this;\n }\n\n public BackgroundStyle defineShadowColor(Color shadowColor) {\n this.shadowColor = shadowColor;\n return this;\n }\n\n public BackgroundStyle defineShadowOffsetX(Integer shadowOffsetX) {\n this.shadowOffsetX = shadowOffsetX;\n return this;\n }\n\n public BackgroundStyle defineShadowOffsetY(Integer shadowOffsetY) {\n this.shadowOffsetY = shadowOffsetY;\n return this;\n }\n\n public BackgroundStyle defineOpacity(Integer opacity) {\n this.opacity = opacity;\n return this;\n }\n\n\n\n}"
},
{
"identifier": "Label",
"path": "src/main/java/com/github/muskstark/echart/style/label/Label.java",
"snippet": "@Getter\npublic class Label {\n\n private boolean show;\n private int distance;\n private int rotate;\n\n public Label defineShow(boolean show){\n this.show = show;\n return this;\n }\n\n public Label defineDistance(int distance){\n this.distance = distance;\n return this;\n }\n\n public Label defineRotate(int rotate){\n this.rotate = rotate;\n return this;\n }\n \n\n}"
}
] | import com.github.muskstark.echart.style.background.BackgroundStyle;
import com.github.muskstark.echart.style.label.Label;
import lombok.Getter;
import java.util.List; | 782 | package com.github.muskstark.echart.attribute.series;
/**
* 图标数据集对象
*/
@Getter
public abstract class Series {
private String id;
private String name;
private String type;
private String colorBy;
private Boolean legendHoverLink;
private String coordinateSystem;
private Integer xAxisIndex;
private Integer yAxisIndex;
private Integer polarIndex;
private Boolean roundCap;
private Boolean realtimeSort;
private Boolean showBackground; | package com.github.muskstark.echart.attribute.series;
/**
* 图标数据集对象
*/
@Getter
public abstract class Series {
private String id;
private String name;
private String type;
private String colorBy;
private Boolean legendHoverLink;
private String coordinateSystem;
private Integer xAxisIndex;
private Integer yAxisIndex;
private Integer polarIndex;
private Boolean roundCap;
private Boolean realtimeSort;
private Boolean showBackground; | private BackgroundStyle backgroundStyle; | 0 | 2023-12-25 08:03:42+00:00 | 2k |
thanosmoschou/SpringBootPractise | databasewithjpa/src/test/java/com/thanos/databasewithjpa/services/impl/UserServiceImplTest.java | [
{
"identifier": "User",
"path": "databasewithjpa/src/main/java/com/thanos/databasewithjpa/domain/User.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Entity\n@Table(name = \"users\")\npublic class User \n{\n @Id\n private String name;\n private int age;\n\n public void printInfo()\n {\n \tSystem.out.println(\"Name: \" + this.name + \" Age: \" + this.age);\n }\n}"
},
{
"identifier": "UserRepository",
"path": "databasewithjpa/src/main/java/com/thanos/databasewithjpa/repositories/UserRepository.java",
"snippet": "@Repository\npublic interface UserRepository extends JpaRepository<User, String>\n{\n\t\n} "
}
] | import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Optional;
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 com.thanos.databasewithjpa.domain.User;
import com.thanos.databasewithjpa.repositories.UserRepository; | 918 | package com.thanos.databasewithjpa.services.impl;
/*
* Mockito is a powerful mocking framework for Java applications.
* It allows you to create mock objects, define their behavior, and
* verify interactions. To mock dependencies in your unit tests, use
* Mockito’s @Mock annotation and @InjectMocks annotation to inject the
* mocks into the class under test.
*
* Why Mock?
*
* Why should we use a mock instead of a real service object in a test?
* Imagine the service implementation above has a dependency to a database or
* some other third-party system. We don’t want to have our test run against the
* database. If the database isn’t available, the test will fail even though our
* system under test might be completely bug-free. The more dependencies we add in
* a test, the more reasons a test has to fail. And most of those reasons will be
* the wrong ones. If we use a mock instead, we can mock all those potential
* failures away.
*
* Aside from reducing failures, mocking also reduces our tests' complexity and
* thus saves us some effort. It takes a lot of boilerplate code to set up a
* whole network of correctly-initialized objects to be used in a test.
* Using mocks, we only have to “instantiate” one mock instead of a whole
* rat-tail of objects the real object might need to be instantiated.
*
* In summary, we want to move from a potentially complex, slow, and
* flaky integration test towards a simple, fast, and reliable unit test.
*
* As a mocking framework, we’ll use Mockito, since it’s well-rounded,
* well-established, and well-integrated into Spring Boot.
*
* Mockito provides some handy annotations that reduce the manual work
* of creating mock instances and passing them into the object we’re about to test.
*
* With JUnit Jupiter, we need to apply the MockitoExtension to our test:
*
* We can then use the @Mock and @InjectMocks annotations on fields of the test.
*
* Fields annotated with @Mock will then automatically be initialized with a
* mock instance of their type, just like as we would call Mockito.mock() by hand.
*
* Mockito will then try to instantiate fields annotated with @InjectMocks by
* passing all mocks into a constructor. Note that we need to provide such a
* constructor for Mockito to work reliably. If Mockito doesn’t find a constructor,
* it will try setter injection or field injection, but the cleanest way is still
* a constructor. You can read about the algorithm behind this in Mockito’s Javadoc.
*
*/
@ExtendWith(MockitoExtension.class) //Enable Mockito support
public class UserServiceImplTest
{
@Mock
private UserRepository userRepository; //a fake repository for the test cases
@InjectMocks
private UserServiceImpl underTest; //inject the mocked repository to the service
@Test
public void testIfUserIsSaved()
{ | package com.thanos.databasewithjpa.services.impl;
/*
* Mockito is a powerful mocking framework for Java applications.
* It allows you to create mock objects, define their behavior, and
* verify interactions. To mock dependencies in your unit tests, use
* Mockito’s @Mock annotation and @InjectMocks annotation to inject the
* mocks into the class under test.
*
* Why Mock?
*
* Why should we use a mock instead of a real service object in a test?
* Imagine the service implementation above has a dependency to a database or
* some other third-party system. We don’t want to have our test run against the
* database. If the database isn’t available, the test will fail even though our
* system under test might be completely bug-free. The more dependencies we add in
* a test, the more reasons a test has to fail. And most of those reasons will be
* the wrong ones. If we use a mock instead, we can mock all those potential
* failures away.
*
* Aside from reducing failures, mocking also reduces our tests' complexity and
* thus saves us some effort. It takes a lot of boilerplate code to set up a
* whole network of correctly-initialized objects to be used in a test.
* Using mocks, we only have to “instantiate” one mock instead of a whole
* rat-tail of objects the real object might need to be instantiated.
*
* In summary, we want to move from a potentially complex, slow, and
* flaky integration test towards a simple, fast, and reliable unit test.
*
* As a mocking framework, we’ll use Mockito, since it’s well-rounded,
* well-established, and well-integrated into Spring Boot.
*
* Mockito provides some handy annotations that reduce the manual work
* of creating mock instances and passing them into the object we’re about to test.
*
* With JUnit Jupiter, we need to apply the MockitoExtension to our test:
*
* We can then use the @Mock and @InjectMocks annotations on fields of the test.
*
* Fields annotated with @Mock will then automatically be initialized with a
* mock instance of their type, just like as we would call Mockito.mock() by hand.
*
* Mockito will then try to instantiate fields annotated with @InjectMocks by
* passing all mocks into a constructor. Note that we need to provide such a
* constructor for Mockito to work reliably. If Mockito doesn’t find a constructor,
* it will try setter injection or field injection, but the cleanest way is still
* a constructor. You can read about the algorithm behind this in Mockito’s Javadoc.
*
*/
@ExtendWith(MockitoExtension.class) //Enable Mockito support
public class UserServiceImplTest
{
@Mock
private UserRepository userRepository; //a fake repository for the test cases
@InjectMocks
private UserServiceImpl underTest; //inject the mocked repository to the service
@Test
public void testIfUserIsSaved()
{ | User user1 = new User("M", 30); | 0 | 2023-12-31 17:29:44+00:00 | 2k |
echothreellc/kafka-connector | Kafka/KafkaJCAAPI/src/main/java/fish/payara/cloud/connectors/kafka/inbound/KafkaActivationSpec.java | [
{
"identifier": "KafkaListener",
"path": "Kafka/KafkaJCAAPI/src/main/java/fish/payara/cloud/connectors/kafka/api/KafkaListener.java",
"snippet": "public interface KafkaListener {\n \n}"
},
{
"identifier": "AdditionalPropertiesParser",
"path": "Kafka/KafkaJCAAPI/src/main/java/fish/payara/cloud/connectors/kafka/tools/AdditionalPropertiesParser.java",
"snippet": "public class AdditionalPropertiesParser {\n\n private static final Logger LOG = Logger.getLogger(AdditionalPropertiesParser.class.getName());\n private static final String LIST_SEPARATOR = \",\";\n private static final String KEY_VALUE_SEPARATOR = \"=\";\n private static final char ESCAPE_CHARACTER = '\\'';\n\n private String propertiesString;\n\n public AdditionalPropertiesParser(String propertiesString) {\n this.propertiesString = propertiesString;\n }\n\n\n private static String[] split(String propertiesString, String separator) {\n ArrayList<String> properties = new ArrayList<>();\n boolean insideComplexValue = false;\n StringBuilder part = new StringBuilder();\n\n for (int i = 0; i < propertiesString.length(); i++) {\n part.append(propertiesString.charAt(i));\n\n if (propertiesString.charAt(i) == ESCAPE_CHARACTER) {\n insideComplexValue = !insideComplexValue;\n }\n\n // separator already in part, add to result list\n if (part.substring(part.length() - separator.length()).equals(separator) && !insideComplexValue) {\n properties.add(part.substring(0, part.length() - separator.length()));\n part.setLength(0);\n }\n }\n\n if (part.length() > 0) {\n properties.add(part.toString());\n }\n\n return properties.toArray(new String[0]);\n }\n\n private static String correctSingleQuotes(String val) {\n String cleaned = val.replace(\"\" + ESCAPE_CHARACTER + ESCAPE_CHARACTER, \"\" + ESCAPE_CHARACTER);\n\n if (cleaned.charAt(0) == ESCAPE_CHARACTER) {\n cleaned = cleaned.substring(1);\n }\n if (cleaned.charAt(cleaned.length() - 1) == ESCAPE_CHARACTER) {\n cleaned = cleaned.substring(0, cleaned.length() - 1);\n }\n\n return cleaned;\n }\n\n\n public static Properties merge(Properties base, Properties addtional){\n Properties properties = new Properties();\n properties.putAll(base);\n if(addtional != null){\n for(String key : addtional.stringPropertyNames()){\n properties.putIfAbsent(key, addtional.getProperty(key));\n }\n }\n return properties;\n }\n\n public Properties parse() {\n Properties properties = new Properties();\n if (propertiesString != null) {\n String lastKey = null;\n final String[] splittedProperties = split(propertiesString, LIST_SEPARATOR);\n for (String singleKeyValue : splittedProperties) {\n final String[] splittedKeyValue = split(singleKeyValue, KEY_VALUE_SEPARATOR);\n switch (splittedKeyValue.length) {\n case 2: {\n final String key = correctSingleQuotes(splittedKeyValue[0].trim());\n lastKey = key;\n final String value = correctSingleQuotes(splittedKeyValue[1].trim());\n final String existingValue = properties.getProperty(key);\n if (existingValue != null) {\n properties.setProperty(key, existingValue + LIST_SEPARATOR + value);\n } else {\n properties.setProperty(key, value);\n }\n break;\n }\n case 1: {\n if (lastKey != null) {\n final String value = correctSingleQuotes(splittedKeyValue[0].trim());\n // assume property to be list and use the last key to add to\n final String existingValue = properties.getProperty(lastKey);\n if (existingValue != null) {\n properties.setProperty(lastKey, existingValue + LIST_SEPARATOR + value);\n } else {\n properties.setProperty(lastKey, value);\n }\n }\n break;\n }\n default:\n LOG.warning(\"Found illegal properties \" + Arrays.toString(splittedKeyValue));\n\n }\n }\n }\n return properties;\n }\n\n}"
}
] | import fish.payara.cloud.connectors.kafka.api.KafkaListener;
import fish.payara.cloud.connectors.kafka.tools.AdditionalPropertiesParser;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import javax.resource.ResourceException;
import javax.resource.spi.Activation;
import javax.resource.spi.ActivationSpec;
import javax.resource.spi.InvalidPropertyException;
import javax.resource.spi.ResourceAdapter;
import java.util.Properties; | 1,526 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2017 Payara Foundation and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://github.com/payara/Payara/blob/master/LICENSE.txt
* See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* The Payara Foundation designates this particular file as subject to the "Classpath"
* exception as provided by the Payara Foundation in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package fish.payara.cloud.connectors.kafka.inbound;
/**
* @author Steve Millidge (Payara Foundation)
*/
@Activation(messageListeners = KafkaListener.class)
public class KafkaActivationSpec implements ActivationSpec {
private final Properties consumerProperties; | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2017 Payara Foundation and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://github.com/payara/Payara/blob/master/LICENSE.txt
* See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* The Payara Foundation designates this particular file as subject to the "Classpath"
* exception as provided by the Payara Foundation in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package fish.payara.cloud.connectors.kafka.inbound;
/**
* @author Steve Millidge (Payara Foundation)
*/
@Activation(messageListeners = KafkaListener.class)
public class KafkaActivationSpec implements ActivationSpec {
private final Properties consumerProperties; | private AdditionalPropertiesParser additionalPropertiesParser; | 1 | 2023-12-24 23:25:44+00:00 | 2k |
CompeyDev/stinky-mod | src/main/java/xyz/devcomp/mixin/ServerPlayerMixin.java | [
{
"identifier": "Stinky",
"path": "src/main/java/xyz/devcomp/Stinky.java",
"snippet": "public class Stinky implements ModInitializer {\n\t// This logger is used to write text to the console and the log file.\n\t// It is considered best practice to use your mod id as the logger's name.\n\t// That way, it's clear which mod wrote info, warnings, and errors.\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(\"stinky\");\n\tpublic static final ConfigModel Config = new ConfigHandler().getConfig();\n\t// public static final ResourceLocation EC_SOUND_ID = new ResourceLocation(\"stinky:ping\");\n // public static SoundEvent EC_SOUND_EVENT = SoundEvent.createVariableRangeEvent(EC_SOUND_ID);\n\n\t@Override\n\tpublic void onInitialize() {\n\t\t// This code runs as soon as Minecraft is in a mod-load-ready state.\n\t\t// However, some things (like resources) may still be uninitialized.\n\t\t// Proceed with mild caution.\n\n\t\tLOGGER.info(\"Hello from Stinky!\");\n\t\t\n\t\tServerMessageEvents.CHAT_MESSAGE.register((PlayerChatMessage msg, ServerPlayer plr, ChatType.Bound bound) -> {\n\t\t\t// NOTE: This makes this command dysfunctional on offline mode servers\n\t\t\tString msgString = msg.signedContent();\n\t\t\t\n\t\t\tif (msgString.trim().equalsIgnoreCase(\";ec\")) {\n\t\t\t\t// We're setting the health to 0, instead of plr.kill(), because this \n\t\t\t\t// abuses a flaw in the graves VanillaTweaks datapack to make the player\n\t\t\t\t// respawn without creating a grave or losing their items\n\t\t\t\t\n\t\t\t\t// TODO: Play stinky:ping sound\n\t\t\t\tplr.setHealth(0);\n\t\t\t}\n\t\t});\n\n\n\t\t\n\t}\n}"
},
{
"identifier": "DeathStrings",
"path": "src/main/java/xyz/devcomp/util/Strings.java",
"snippet": "public class DeathStrings {\n public static String[] Arrow = {\n \"&cplayer&7 was shot by &ckiller\",\n \"&cplayer&7 didnt survive detroit\",\n \"&cplayer&7 had died to an arrow from &ckiller\",\n \"&cplayer&7 was shot dead with &ckiller's &cweapon\",\n };\n public static String[] Melee = {\n \"&cplayer&7 was slain by &ckiller's &cweapon\",\n \"&ckiller&7 violently murdered &cplayer with a &cweapon\",\n \"&cplayer&7 got fucking killed by &ckiller's &cweapon\",\n \"&cplayer&7 got stabbed by &ckiller's &cweapon\",\n \"&ckiller&7 turned off &cplayer's life support\"\n };\n public static String[] FallDamage = {\n \"&cplayer&7 jumped\",\n \"&cplayer&7 installed proprietary spyware\",\n \"&cplayer&7 is not very intelligent\"\n };\n public static String[] Suicide = {\n \"&cplayer&7 ate glue\",\n \"&cplayer&7 jumped\",\n \"&cplayer&7 committed suicide\"\n };\n public static String[] Burned = {\n \"&cplayer&7 used too much icyhot\",\n \"&cplayer&7 is a complete dumbass\",\n \"&cplayer&7 is toast\",\n };\n public static String[] Potion = {\n \"&cplayer&7 died to &ckiller's potion\"\n };\n public static String[] Drowned = {\n \"&cplayer&7 forgot to breathe\",\n \"&cplayer&7 drowned\",\n \"&cplayer&7 drank too much water\",\n \"&cplayer&7 depleted their oxygen\",\n };\n public static String[] Suffocation = {\n \"&cplayer&7 got stuck in a wall\"\n };\n public static String[] Mob = {\n \"&cplayer&7 was killed by a &ckiller\"\n };\n public static String[] Wildcard = {\n \"&cplayer&7 was killed\",\n \"&cplayer&7 died\",\n \"&cplayer&7? &cplayer&7?? &cplayer&7!!!!!\"\n };\n public static String[] Explosion = {\n \"&cplayer&7 was blown by &ckiller\",\n \"&cplayer&7 blew up\",\n \"&cplayer&7 exploded\",\n };\n public static String[] Starved = {\n \"&cplayer&7 forgot to eat\",\n \"&cplayer&7 starved to death\"\n };\n}"
}
] | import java.util.Map;
import xyz.devcomp.Stinky;
import xyz.devcomp.util.Strings.DeathStrings;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.mojang.authlib.GameProfile;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.damagesource.DamageType;
import net.minecraft.world.damagesource.DamageTypes;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level; | 1,594 | package xyz.devcomp.mixin;
@Mixin(ServerPlayer.class)
public abstract class ServerPlayerMixin extends Player {
public ServerPlayerMixin(Level level, BlockPos blockPos, float f, GameProfile gameProfile) {
super(level, blockPos, f, gameProfile);
}
@Inject(method = "die(Lnet/minecraft/world/damagesource/DamageSource;)V", at = @At("TAIL"))
private void broadcastDeathMessage(DamageSource damageSource, CallbackInfo ci) {
ServerPlayer victim = (ServerPlayer) (Object) this;
MinecraftServer server = this.getServer();
if (damageSource.getDirectEntity() instanceof ServerPlayer aggressor) {
if (aggressor == victim) {
// suicide balls
server.sendSystemMessage(
Component.literal(DeathStrings.Suicide[(int) (Math.random() * DeathStrings.Suicide.length)]));
return;
}
Map<ResourceKey<DamageType>, String[]> relevantTypes = Map.of(
DamageTypes.ARROW, DeathStrings.Arrow,
DamageTypes.PLAYER_ATTACK, DeathStrings.Melee,
DamageTypes.MAGIC, DeathStrings.Potion,
DamageTypes.PLAYER_EXPLOSION, DeathStrings.Explosion);
for (Map.Entry<ResourceKey<DamageType>, String[]> type : relevantTypes.entrySet()) {
ResourceKey<DamageType> damageType = type.getKey();
String[] msgs = type.getValue();
if (damageSource.is(damageType)) {
server.getPlayerList().broadcastSystemMessage(Component.literal(msgs[(int) (Math.random() * msgs.length)]
.replace("player", victim.getDisplayName().getString())
.replace("killer", aggressor.getDisplayName().getString()) // check if null
.replace("weapon", (damageSource.getDirectEntity().getName() == null ? "" : damageSource.getDirectEntity().getName().getString()))), false);
}
}
;
} else {
// these death msgs dont work :( | package xyz.devcomp.mixin;
@Mixin(ServerPlayer.class)
public abstract class ServerPlayerMixin extends Player {
public ServerPlayerMixin(Level level, BlockPos blockPos, float f, GameProfile gameProfile) {
super(level, blockPos, f, gameProfile);
}
@Inject(method = "die(Lnet/minecraft/world/damagesource/DamageSource;)V", at = @At("TAIL"))
private void broadcastDeathMessage(DamageSource damageSource, CallbackInfo ci) {
ServerPlayer victim = (ServerPlayer) (Object) this;
MinecraftServer server = this.getServer();
if (damageSource.getDirectEntity() instanceof ServerPlayer aggressor) {
if (aggressor == victim) {
// suicide balls
server.sendSystemMessage(
Component.literal(DeathStrings.Suicide[(int) (Math.random() * DeathStrings.Suicide.length)]));
return;
}
Map<ResourceKey<DamageType>, String[]> relevantTypes = Map.of(
DamageTypes.ARROW, DeathStrings.Arrow,
DamageTypes.PLAYER_ATTACK, DeathStrings.Melee,
DamageTypes.MAGIC, DeathStrings.Potion,
DamageTypes.PLAYER_EXPLOSION, DeathStrings.Explosion);
for (Map.Entry<ResourceKey<DamageType>, String[]> type : relevantTypes.entrySet()) {
ResourceKey<DamageType> damageType = type.getKey();
String[] msgs = type.getValue();
if (damageSource.is(damageType)) {
server.getPlayerList().broadcastSystemMessage(Component.literal(msgs[(int) (Math.random() * msgs.length)]
.replace("player", victim.getDisplayName().getString())
.replace("killer", aggressor.getDisplayName().getString()) // check if null
.replace("weapon", (damageSource.getDirectEntity().getName() == null ? "" : damageSource.getDirectEntity().getName().getString()))), false);
}
}
;
} else {
// these death msgs dont work :( | Stinky.LOGGER.info("killer: {}, weapon: {}", damageSource.getDirectEntity().getName().getString(), damageSource.getEntity().getName().getString()); | 0 | 2023-12-26 16:23:46+00:00 | 2k |
xyzell/OOP_UAS | Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/service/impl/ReceptionistServiceImpl.java | [
{
"identifier": "Account",
"path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/pojo/Account.java",
"snippet": "public class Account {\n private String idAccount;\n private String email;\n private String username;\n private String password;\n private String level;\n\n public Account() {\n }\n\n public String getIdAccount() {\n return idAccount;\n }\n\n public void setIdAccount(String idAccount) {\n this.idAccount = idAccount;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getLevel() {\n return level;\n }\n\n public void setLevel(String level) {\n this.level = level;\n }\n \n \n \n}"
},
{
"identifier": "Receptionist",
"path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/pojo/Receptionist.java",
"snippet": "public class Receptionist {\n private String idReceptionist;\n private String namaReceptionist;\n private String numberReceptionist;\n private Account account;\n\n public Receptionist() {\n }\n\n public String getIdReceptionist() {\n return idReceptionist;\n }\n\n public void setIdReceptionist(String idReceptionist) {\n this.idReceptionist = idReceptionist;\n }\n\n public String getNamaReceptionist() {\n return namaReceptionist;\n }\n\n public void setNamaReceptionist(String namaReceptionist) {\n this.namaReceptionist = namaReceptionist;\n }\n\n public String getNumberReceptionist() {\n return numberReceptionist;\n }\n\n public void setNumberReceptionist(String numberReceptionist) {\n this.numberReceptionist = numberReceptionist;\n }\n\n public Account getAccount() {\n return account;\n }\n\n public void setAccount(Account account) {\n this.account = account;\n }\n \n}"
},
{
"identifier": "ReceptionistService",
"path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/service/ReceptionistService.java",
"snippet": "public interface ReceptionistService extends CrudRepository<Receptionist, Integer>{\n \n}"
},
{
"identifier": "ConnectionManager",
"path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/utilities/ConnectionManager.java",
"snippet": "public class ConnectionManager {\n private String DB_URL = \"jdbc:mysql://localhost:3306/hotel1\";\n private String username;\n private String password;\n private Connection connection;\n\n \n\n public ConnectionManager() {\n this.username = \"root\";\n this.password = \"basdat2022\";\n }\n\n public String getDB_URL() {\n return DB_URL;\n }\n\n public String getUsername() {\n return username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public Connection connect() {\n if (connection == null) {\n try {\n Class.forName(\"com.mysql.cj.jdbc.Driver\");\n connection = DriverManager.getConnection(getDB_URL(), \n getUsername(), getPassword());\n } catch (ClassNotFoundException | SQLException ex) {\n Logger.getLogger(ConnectionManager.class.getName())\n .log(Level.SEVERE, null, ex);\n }\n }\n return connection;\n }\n \n public Connection disconnect() {\n try {\n connection.close();\n } catch (SQLException ex) {\n Logger.getLogger(ConnectionManager.class.getName())\n .log(Level.SEVERE, null, ex);\n }\n return connection;\n }\n}"
}
] | import com.itenas.oop.org.uashotel.pojo.Account;
import com.itenas.oop.org.uashotel.pojo.Receptionist;
import com.itenas.oop.org.uashotel.service.ReceptionistService;
import com.itenas.oop.org.uashotel.utilities.ConnectionManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane; | 1,170 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.itenas.oop.org.uashotel.service.impl;
/**
*
* @author Nicholas
*/
public class ReceptionistServiceImpl implements ReceptionistService{
private ConnectionManager conMan;
private Connection conn;
Statement stmt;
ResultSet rs;
@Override | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.itenas.oop.org.uashotel.service.impl;
/**
*
* @author Nicholas
*/
public class ReceptionistServiceImpl implements ReceptionistService{
private ConnectionManager conMan;
private Connection conn;
Statement stmt;
ResultSet rs;
@Override | public List<Receptionist> findAll() { | 1 | 2023-12-24 11:39:51+00:00 | 2k |
LawMashira/Springboot-3-Security-Registration-and-Login- | Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/service/UserServiceImpl.java | [
{
"identifier": "Role",
"path": "Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/entity/Role.java",
"snippet": "@Entity\n@Setter\n@Getter\n@NoArgsConstructor\npublic class Role {\n /*\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String name;\n\n @ManyToMany(mappedBy=\"roles\")\n private Collection<User> users = new HashSet<>();\n\n public Role(String name) {\n this.name = name;\n }\n\n public void assignRoleToUser (User user){\n user.getRoles().add(this);\n this.getUsers().add(user);\n\n }\n\n\n public void removeUserFromRole(User user){\n user.getRoles().remove(this);\n this.getUsers().remove(user);\n\n }\n\n public void removeAllUsersFromRole(){ List<User> roleUsers= this.getUsers().stream().toList();\n roleUsers.forEach(this::removeUserFromRole);\n }\n }\n\n\n\n public String getName(){\n return name!=null? name:\"\";\n }\n\n */\n\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String name;\n\n @JsonIgnore\n @ManyToMany(mappedBy = \"roles\")\n private Collection<User> users = new HashSet<>();\n\n public Role(String name) {\n this.name = name;\n }\n\n public void assignRoleToUser(User user){\n user.getRoles().add(this);\n this.getUsers().add(user);\n }\n\n public void removeUserFromRole(User user){\n user.getRoles().remove(this);\n this.getUsers().remove(user);\n\n }\n\n public void removeAllUsersFromRole(){\n if (this.getUsers() != null){\n List<User> roleUsers = this.getUsers().stream().toList();\n roleUsers.forEach(this :: removeUserFromRole);\n }\n }\n public String getName(){\n return name != null? name : \"\";\n }\n}"
},
{
"identifier": "User",
"path": "Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/entity/User.java",
"snippet": "@Table(name = \"ASPIRING_STUDENTS_TB\")\n@Entity\n@Setter\n@Getter\n@NoArgsConstructor\npublic class User {\n /*@Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String name;\n private String email;\n private String password;\n\n @ManyToMany(fetch = FetchType.EAGER,cascade = {CascadeType.PERSIST,CascadeType.MERGE,CascadeType.DETACH})\n @JoinTable(name = \"user_roles\",\n joinColumns =@JoinColumn(name = \"user_id\",referencedColumnName = \"id\"),\n inverseJoinColumns = @JoinColumn(name = \"role_id\",referencedColumnName = \"id\"))\n private Collection<Role> roles = new HashSet<>();*/\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String firstName;\n private String lastName;\n private String email;\n private String password;\n @ManyToMany(fetch = FetchType.EAGER,\n cascade = {CascadeType.PERSIST,\n CascadeType.MERGE, CascadeType.DETACH})\n @JoinTable(name = \"user_roles\",\n joinColumns = @JoinColumn(name = \"user_id\", referencedColumnName = \"id\"),\n inverseJoinColumns = @JoinColumn(name = \"role_id\", referencedColumnName = \"id\"))\n private Collection<Role> roles = new HashSet<>();\n\n\n}"
},
{
"identifier": "UserAlreadyExistsException",
"path": "Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/exception/UserAlreadyExistsException.java",
"snippet": "public class UserAlreadyExistsException extends RuntimeException {\n public UserAlreadyExistsException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "UserNotFoundException",
"path": "Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/exception/UserNotFoundException.java",
"snippet": "public class UserNotFoundException extends RuntimeException {\n public UserNotFoundException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "RoleRepository",
"path": "Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/repository/RoleRepository.java",
"snippet": "public interface RoleRepository extends JpaRepository<Role,Long> {\n/*\n Optional<Role> findByName(String role);\n\n boolean existsByName(Role role);\n\n\n */\n\n Optional<Role> findByName(String role);\n\n\n boolean existsByName(String role);\n}"
},
{
"identifier": "UserRepository",
"path": "Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/repository/UserRepository.java",
"snippet": "public interface UserRepository extends JpaRepository<User,Long> {\n /* boolean existsByEmail(String email);\n\n void deleteByEmail(String email);\n\n Optional < User > findByEmail(String email);*/\n boolean existsByEmail(String email);\n\n void deleteByEmail(String email);\n\n Optional<User> findByEmail(String email);\n}"
}
] | import com.student.online.admission.system.rd.year.entity.Role;
import com.student.online.admission.system.rd.year.entity.User;
import com.student.online.admission.system.rd.year.exception.UserAlreadyExistsException;
import com.student.online.admission.system.rd.year.exception.UserNotFoundException;
import com.student.online.admission.system.rd.year.repository.RoleRepository;
import com.student.online.admission.system.rd.year.repository.UserRepository;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List; | 1,557 | package com.student.online.admission.system.rd.year.service;
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService{
/*
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final RoleRepository roleRepository;
@Override
public User registerUser(User user) throws UserAlreadyExistsException {
if(userRepository.existsByEmail(user.getEmail())){
throw new UserAlreadyExistsException(user.getEmail() + "already exists ") ;
}
user.setPassword(passwordEncoder.encode(user.getPassword()));
Role userRole = roleRepository.findByName("ROLE_USER").get();
user.setRoles(Collections.singletonList(userRole));
return userRepository.save(user);
}
@Override
public List<User> getUsers() {
return userRepository.findAll();
}
@Transactional
@Override
public void deleteUser(String email) {
User theUser = getUser(email);
if(theUser!=null){
userRepository.deleteByEmail(email);
}
}
@Override
public User getUser(String email) throws UserNotFoundException {
return userRepository.findByEmail(email).orElseThrow(()->new UserNotFoundException("User not found exception"));
}*/
| package com.student.online.admission.system.rd.year.service;
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService{
/*
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final RoleRepository roleRepository;
@Override
public User registerUser(User user) throws UserAlreadyExistsException {
if(userRepository.existsByEmail(user.getEmail())){
throw new UserAlreadyExistsException(user.getEmail() + "already exists ") ;
}
user.setPassword(passwordEncoder.encode(user.getPassword()));
Role userRole = roleRepository.findByName("ROLE_USER").get();
user.setRoles(Collections.singletonList(userRole));
return userRepository.save(user);
}
@Override
public List<User> getUsers() {
return userRepository.findAll();
}
@Transactional
@Override
public void deleteUser(String email) {
User theUser = getUser(email);
if(theUser!=null){
userRepository.deleteByEmail(email);
}
}
@Override
public User getUser(String email) throws UserNotFoundException {
return userRepository.findByEmail(email).orElseThrow(()->new UserNotFoundException("User not found exception"));
}*/
| private final UserRepository userRepository; | 5 | 2023-12-30 19:51:38+00:00 | 2k |
LeeKyeongYong/SBookStudy | src/main/java/com/multibook/bookorder/domain/book/book/controller/BookController.java | [
{
"identifier": "Book",
"path": "src/main/java/com/multibook/bookorder/domain/book/book/entity/Book.java",
"snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\npublic class Book extends BaseTime {\n @ManyToOne\n private Member author;\n @OneToOne\n private Product product;\n private String title;\n private String body;\n private int price;\n private boolean published;\n}"
},
{
"identifier": "BookService",
"path": "src/main/java/com/multibook/bookorder/domain/book/book/service/BookService.java",
"snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class BookService {\n private final BookRepository bookRepository;\n\n @Transactional\n public Book createBook(Member author, String title, String body, int price, boolean published) {\n Book book = Book.builder()\n .author(author)\n .title(title)\n .body(body)\n .price(price)\n .published(published)\n .build();\n\n bookRepository.save(book);\n\n return book;\n }\n\n public Page<Book> search(Member author, Boolean published, List<String> kwTypes, String kw, Pageable pageable) {\n return bookRepository.search(author, published, kwTypes, kw, pageable);\n }\n}"
},
{
"identifier": "Rq",
"path": "src/main/java/com/multibook/bookorder/global/rq/Rq.java",
"snippet": "@Component\n@RequestScope\n@RequiredArgsConstructor\n@Slf4j\npublic class Rq {\n private final HttpServletRequest request;\n private final HttpServletResponse response;\n private final EntityManager entityManager;\n private final MemberService memberService;\n private Member member;\n\n public String redirect(String url, String msg) {\n String[] urlBits = url.split(\"#\", 2);\n url = urlBits[0];\n StringBuilder sb = new StringBuilder();\n\n sb.append(\"redirect:\");\n sb.append(url);\n\n if (UtZip.str.hasLength(msg)) {\n msg = URLEncoder.encode(msg, StandardCharsets.UTF_8);\n\n if (url.contains(\"?\")) {\n sb.append(\"&msg=\");\n } else {\n sb.append(\"?msg=\");\n }\n\n sb.append(msg);\n }\n\n if (urlBits.length == 2) {\n sb.append(\"#\");\n sb.append(urlBits[1]);\n }\n\n return sb.toString();\n }\n\n public String historyBack(GlobalException ex) {\n String exStr = UtZip.exception.toString(ex);\n\n request.setAttribute(\"exStr\", exStr);\n log.debug(exStr);\n\n return historyBack(ex.getRsData().getMsg());\n }\n\n public String historyBack(String msg) {\n request.setAttribute(\"failMsg\", msg);\n\n return \"global/js\";\n }\n\n public String redirectOrBack(RsData<?> rs, String path) {\n if (rs.isFail()) return historyBack(rs.getMsg());\n\n return redirect(path, rs.getMsg());\n }\n\n public SecurityUser getUser() {\n return Optional.ofNullable(SecurityContextHolder.getContext())\n .map(SecurityContext::getAuthentication)\n .map(Authentication::getPrincipal)\n .filter(it -> it instanceof SecurityUser)\n .map(it -> (SecurityUser) it)\n .orElse(null);\n }\n\n public boolean isLogin() {\n return getUser() != null;\n }\n\n public boolean isLogout() {\n return !isLogin();\n }\n\n public boolean isAdmin() {\n if (isLogout()) return false;\n\n return getUser()\n .getAuthorities()\n .stream()\n .anyMatch(it -> it.getAuthority().equals(\"ROLE_ADMIN\"));\n }\n\n public void attr(String key, Object value) {\n request.setAttribute(key, value);\n }\n\n public String getCurrentQueryStringWithoutParam(String paramName) {\n String queryString = request.getQueryString();\n\n if (queryString == null) {\n return \"\";\n }\n\n queryString = UtZip.url.deleteQueryParam(queryString, paramName);\n\n return queryString;\n }\n\n public Member getMember() {\n if (isLogout()) return null;\n\n if (member == null) {\n member = entityManager.getReference(Member.class, getUser().getId());\n }\n\n return member;\n }\n\n public String getProfileImgUrl() {\n return memberService.getProfileImgUrl(getMember());\n }\n\n public String getEncodedCurrentUrl() {\n return UtZip.url.encode(getCurrentUrl());\n }\n\n private String getCurrentUrl() {\n String url = request.getRequestURI();\n String queryString = request.getQueryString();\n\n if (queryString != null) {\n url += \"?\" + queryString;\n }\n\n return url;\n }\n}"
}
] | import com.multibook.bookorder.domain.book.book.entity.Book;
import com.multibook.bookorder.domain.book.book.service.BookService;
import com.multibook.bookorder.global.rq.Rq;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; | 1,485 | package com.multibook.bookorder.domain.book.book.controller;
@Controller
@RequestMapping("/")
@RequiredArgsConstructor
public class BookController {
private final BookService bookService;
private final Rq rq;
@GetMapping("/list")
public String showList(
@RequestParam(value="kwType",defaultValue = "title")List<String> kwTypes,
@RequestParam(value="") String kw,@RequestParam(defaultValue = "1") int page,Model model){
List<Sort.Order> sorts = new ArrayList<>();
sorts.add(Sort.Order.desc("id"));
Pageable pageable = PageRequest.of(page-1,10,Sort.by(sorts));
Map<String,Boolean> kwTypesMap = kwTypes
.stream().collect(Collectors.toMap(kwType -> kwType,kwType -> true));
| package com.multibook.bookorder.domain.book.book.controller;
@Controller
@RequestMapping("/")
@RequiredArgsConstructor
public class BookController {
private final BookService bookService;
private final Rq rq;
@GetMapping("/list")
public String showList(
@RequestParam(value="kwType",defaultValue = "title")List<String> kwTypes,
@RequestParam(value="") String kw,@RequestParam(defaultValue = "1") int page,Model model){
List<Sort.Order> sorts = new ArrayList<>();
sorts.add(Sort.Order.desc("id"));
Pageable pageable = PageRequest.of(page-1,10,Sort.by(sorts));
Map<String,Boolean> kwTypesMap = kwTypes
.stream().collect(Collectors.toMap(kwType -> kwType,kwType -> true));
| Page<Book> itemsPage = bookService.search(null,true,kwTypes,kw,pageable); | 0 | 2023-12-26 14:58:59+00:00 | 2k |
Farley-Chen/fastcdc-java | src/main/java/io/github/farleychen/fastcdc/RingByteArray.java | [
{
"identifier": "EMPTY_BYTE_ARRAY",
"path": "src/main/java/io/github/farleychen/fastcdc/ArrayUtils.java",
"snippet": "public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];"
},
{
"identifier": "subarray",
"path": "src/main/java/io/github/farleychen/fastcdc/ArrayUtils.java",
"snippet": "public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n final int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return EMPTY_BYTE_ARRAY;\n }\n\n final byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n}"
}
] | import static io.github.farleychen.fastcdc.ArrayUtils.EMPTY_BYTE_ARRAY;
import static io.github.farleychen.fastcdc.ArrayUtils.subarray; | 828 | package io.github.farleychen.fastcdc;
/**
* refer to <a
* href=https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-ios/src/main/java/com/jme3/util/RingBuffer.java>jmonkeyengine</a>
* <p>
* A circular array (array with wrap-around).
*
* @author FengChen
*/
class RingByteArray {
/**
* array elements
*/
private final byte[] elements;
/**
* number of elements in array
*/
private int size = 0;
/**
* index of first element of array
*/
private int firstElementIndex = 0;
/**
* index of next available slot
*/
private int addElementIndex = 0;
RingByteArray(final int capacity) {
Assert.isTrue(capacity >= 0);
elements = new byte[capacity];
}
boolean isEmpty() {
return size == 0;
}
int size() {
return size;
}
void addAll(final byte[] bytes) {
for (final var aByte : bytes) {
add(aByte);
}
}
void add(final byte aByte) {
if (size == elements.length) {
throw new RuntimeException("Ring byte array overflow");
}
elements[addElementIndex] = aByte;
// wrap-around
addElementIndex = (addElementIndex + 1) % elements.length;
size++;
}
void position(final int index) {
Assert.isTrue(index >= 0);
if (index > size) {
throw new RuntimeException("Ring byte array underflow");
}
// wrap-around
firstElementIndex = (firstElementIndex + index) % elements.length;
size -= index;
}
byte get(final int index) {
Assert.isTrue(index >= 0);
if (index >= size) {
throw new RuntimeException("Ring byte array underflow");
}
// wrap-around
return elements[(firstElementIndex + index) % elements.length];
}
byte[] getRange(final int fromInclusive, final int toExclusive) {
Assert.isTrue(fromInclusive >= 0);
Assert.isTrue(fromInclusive <= toExclusive);
if (fromInclusive >= size || toExclusive > size) {
throw new RuntimeException("Ring byte array underflow");
}
if (fromInclusive == toExclusive) {
return EMPTY_BYTE_ARRAY;
}
// wrap-around
final int from = (firstElementIndex + fromInclusive) % elements.length;
final int to = (firstElementIndex + toExclusive) % elements.length;
if (from < to) { | package io.github.farleychen.fastcdc;
/**
* refer to <a
* href=https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-ios/src/main/java/com/jme3/util/RingBuffer.java>jmonkeyengine</a>
* <p>
* A circular array (array with wrap-around).
*
* @author FengChen
*/
class RingByteArray {
/**
* array elements
*/
private final byte[] elements;
/**
* number of elements in array
*/
private int size = 0;
/**
* index of first element of array
*/
private int firstElementIndex = 0;
/**
* index of next available slot
*/
private int addElementIndex = 0;
RingByteArray(final int capacity) {
Assert.isTrue(capacity >= 0);
elements = new byte[capacity];
}
boolean isEmpty() {
return size == 0;
}
int size() {
return size;
}
void addAll(final byte[] bytes) {
for (final var aByte : bytes) {
add(aByte);
}
}
void add(final byte aByte) {
if (size == elements.length) {
throw new RuntimeException("Ring byte array overflow");
}
elements[addElementIndex] = aByte;
// wrap-around
addElementIndex = (addElementIndex + 1) % elements.length;
size++;
}
void position(final int index) {
Assert.isTrue(index >= 0);
if (index > size) {
throw new RuntimeException("Ring byte array underflow");
}
// wrap-around
firstElementIndex = (firstElementIndex + index) % elements.length;
size -= index;
}
byte get(final int index) {
Assert.isTrue(index >= 0);
if (index >= size) {
throw new RuntimeException("Ring byte array underflow");
}
// wrap-around
return elements[(firstElementIndex + index) % elements.length];
}
byte[] getRange(final int fromInclusive, final int toExclusive) {
Assert.isTrue(fromInclusive >= 0);
Assert.isTrue(fromInclusive <= toExclusive);
if (fromInclusive >= size || toExclusive > size) {
throw new RuntimeException("Ring byte array underflow");
}
if (fromInclusive == toExclusive) {
return EMPTY_BYTE_ARRAY;
}
// wrap-around
final int from = (firstElementIndex + fromInclusive) % elements.length;
final int to = (firstElementIndex + toExclusive) % elements.length;
if (from < to) { | return subarray(elements, from, to); | 1 | 2023-12-26 18:47:28+00:00 | 2k |
Maksymth/main | java basics/sprints/sprint 5 (5 tasks)/src/Run.java | [
{
"identifier": "FirstTask",
"path": "java basics/sprints/sprint 5 (5 tasks)/src/tasks/FirstTask.java",
"snippet": "public class FirstTask {\r\n private static String dayOfWeekStrings[] = { \"Monday\", \"Tuesday\", \"Wensday\", \"Thursday\",\r\n \"Friday\", \"Saturday\", \"Sunday\" };\r\n\r\n public static void dayOfWeekShower(int day, int month, int year, int upperSpace, int bottomSpace) {\r\n Row.skip(upperSpace);\r\n\r\n int nYear = year - (14 - month) / 12;\r\n int x = nYear + nYear / 4 - nYear / 100 + nYear / 400;\r\n int nMonth = month + 12 * ((14 - month) / 12) - 2;\r\n\r\n int intResult = (day + x + 31 * nMonth / 12 - 1) % 7;\r\n\r\n Display.itn(dayOfWeekStrings[intResult]);\r\n\r\n Row.skip(bottomSpace);\r\n }\r\n}\r"
},
{
"identifier": "SecoundTask",
"path": "java basics/sprints/sprint 5 (5 tasks)/src/tasks/SecoundTask.java",
"snippet": "public class SecoundTask {\r\n public static void twoRollsDisplayer(int times) {\r\n for (int i = 0; i < times; i++) {\r\n int currentTime = i + 1;\r\n if (i == 0) {\r\n Row.skip(3);\r\n } else {\r\n Row.skip(1);\r\n }\r\n Display.itn(\"Time: \" + currentTime);\r\n Display.itn(\"First roll result: \" + rollResult());\r\n Display.itn(\"Secound roll result: \" + rollResult());\r\n Row.skip(1);\r\n }\r\n }\r\n\r\n private static int rollResult() {\r\n double rollResult = Math.random() * 6 + 1;\r\n\r\n return (int) rollResult;\r\n }\r\n}"
},
{
"identifier": "ThirdTask",
"path": "java basics/sprints/sprint 5 (5 tasks)/src/tasks/ThirdTask.java",
"snippet": "public class ThirdTask {\r\n public static void offcutLengthDisplayer(double x1, double y1, double x2, double y2) {\r\n double expression, result;\r\n\r\n expression = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\r\n result = Math.sqrt(expression);\r\n\r\n Row.skip(3);\r\n Display.itn(\"Offcut length is - \" + result);\r\n Row.skip(1);\r\n }\r\n}\r"
},
{
"identifier": "FourthTask",
"path": "java basics/sprints/sprint 5 (5 tasks)/src/tasks/FourthTask.java",
"snippet": "public class FourthTask {\r\n private static final double EARTH_MASS = 5.97 * Math.pow(10, 24);\r\n private static final double EARTH_RADIUS = 6371 * Math.pow(10, 3); // in kilometers\r\n private static final double GRAVITY_CONSTANT = 6.67 * Math.pow(10, -11);\r\n\r\n public static void satelliteEscapeVelocityDisplayer(double input) { // output in meters\r\n double sideExpression, distanceToEarth, result; // parameters\r\n\r\n distanceToEarth = input; // input setting\r\n\r\n sideExpression = (GRAVITY_CONSTANT * EARTH_MASS) / (EARTH_RADIUS + distanceToEarth); // expression\r\n result = Math.sqrt(sideExpression);\r\n\r\n Row.skip(3);\r\n Display.itn(\"Satellite speed is - \" + Math.round(result) + \" m/s.\");\r\n Row.skip(1);\r\n }\r\n}"
},
{
"identifier": "Fifth",
"path": "java basics/sprints/sprint 5 (5 tasks)/src/tasks/Fifth.java",
"snippet": "public class Fifth {\r\n private static final int UP_TO = 12;\r\n\r\n public static void rabbitsPopulationCalculation(String titleSymbol, String divisionSymbol) {\r\n title();\r\n space(titleSymbol);\r\n content(divisionSymbol);\r\n }\r\n\r\n private static void title() {\r\n Display.itn(\" Ordered number | Result \");\r\n }\r\n\r\n private static void space(String titleSymbol) {\r\n for (int i = 0; i < 36; i++) {\r\n Display.it(titleSymbol);\r\n }\r\n Row.skip(1);\r\n }\r\n\r\n private static void content(String divisionSymbol) {\r\n for (int currentRowFromZero = 0; currentRowFromZero <= UP_TO; currentRowFromZero++) {\r\n if (currentRowFromZero > 9) {\r\n Display.itn(\" \" + currentRowFromZero + \" \" + divisionSymbol + \" \"\r\n + calculationResult(currentRowFromZero) + \" \");\r\n } else {\r\n Display.itn(\" \" + currentRowFromZero + \" \" + divisionSymbol + \" \"\r\n + calculationResult(currentRowFromZero) + \" \");\r\n }\r\n }\r\n }\r\n\r\n private static String calculationResult(int currentRow) {\r\n double expression;\r\n\r\n expression = (1 / Math.sqrt(5))\r\n * (Math.pow(((1 + Math.sqrt(5)) / 2), currentRow) - Math.pow(((1 - Math.sqrt(5)) / 2), currentRow));\r\n\r\n int sideResult = (int) expression;\r\n\r\n String result = Integer.toString(sideResult);\r\n\r\n return result;\r\n }\r\n}"
}
] | import global.*;
import tasks.FirstTask;
import tasks.SecoundTask;
import tasks.ThirdTask;
import tasks.FourthTask;
import tasks.Fifth;
| 1,361 |
// * Import
// Code
public class Run {
public static void main(String[] args) {
FirstTask.dayOfWeekShower(23, 12, 2023, 4, 1);
Display.itn("\n\n--------------------------------------------------------- End of task.\n\n");
SecoundTask.twoRollsDisplayer(25);
Display.itn("\n\n--------------------------------------------------------- End of task.\n\n");
|
// * Import
// Code
public class Run {
public static void main(String[] args) {
FirstTask.dayOfWeekShower(23, 12, 2023, 4, 1);
Display.itn("\n\n--------------------------------------------------------- End of task.\n\n");
SecoundTask.twoRollsDisplayer(25);
Display.itn("\n\n--------------------------------------------------------- End of task.\n\n");
| ThirdTask.offcutLengthDisplayer(2, 0, 4, 0); // x1 & y1 is coordinates of first punctum, x2 & y2 - of secound.
| 2 | 2023-12-30 04:25:22+00:00 | 2k |
embuc/random-sentence-generator | src/test/java/se/emirbuc/randomsentence/RandomSentencesTest.java | [
{
"identifier": "RandomSentences",
"path": "src/main/java/se/emirbuc/randomsentence/RandomSentences.java",
"snippet": "public class RandomSentences {\n\n\tprivate final static String SPACE = \" \";\n\tprivate final static String PERIOD = \".\";\n\n\tprivate static final Random r = new Random();\n\n\t/**\n\t * The <code>Enum Length</code>.\n\t *\n\t * @author Emir Bucalovic (embuc)\n\t * @since 2015-okt-05\n\t */\n\tpublic enum Length {\n\t\t/** Three word sentence, think 'title | name | short description'*/\n\t\tSHORT, \n\t\t/** Six word sentences.*/\n\t\tMEDIUM, \n\t\t/** Twelve word sentences, think 'description'.*/\n\t\tLONG\n\t}\n\n\t/**\n\t * Produces one random sentence with supplied length.\n\t * @param length\n\t * @return sentence as a String\n\t */\n\tpublic static String generateRandomSentence(Length length) {\n\t\tif (length == null) {\n\t\t\tlength = Length.SHORT;\n\t\t}\n\t\tStringBuilder sb = new StringBuilder();\n\t\tString first = Grammar.ARTICLE[rand(Grammar.ARTICLE.length - 1)];\n\t\tchar c = first.charAt(0);\n\t\tfirst = first.replace(c, Character.toUpperCase(c));\n\t\tsb.append(first);\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.NOUN[rand(Grammar.NOUN.length - 1)]);\n\t\tsb.append(SPACE);\n\t\tsb.append((Grammar.VERB[rand(Grammar.VERB.length - 1)]));\n\t\tif (length == Length.SHORT) {\n\t\t\tsb.append(PERIOD);\n\t\t\treturn sb.toString();\n\t\t}\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.PREPOSITION[rand(Grammar.PREPOSITION.length - 1)]);\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.ARTICLE[rand(Grammar.ARTICLE.length - 1)] + SPACE + Grammar.NOUN[rand(Grammar.NOUN.length - 1)]);\n\t\tif (length == Length.MEDIUM) {\n\t\t\tsb.append(PERIOD);\n\t\t\treturn sb.toString();\n\t\t}\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.PREPOSITION[rand(Grammar.PREPOSITION.length - 1)]);\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.ARTICLE[rand(Grammar.ARTICLE.length - 1)]);\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.NOUN[rand(Grammar.NOUN.length - 1)]);\n\t\tsb.append(SPACE);\n\t\tsb.append((Grammar.VERB[rand(Grammar.VERB.length - 1)]));\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.ARTICLE[rand(Grammar.ARTICLE.length - 1)]);\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.NOUN[rand(Grammar.NOUN.length - 1)]);\n\n\t\tsb.append(PERIOD);\n\t\treturn sb.toString();\n\t}\n\n\tstatic int rand(int length) {\n\t\tif (length == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tint ri = r.nextInt() % length;\n\t\tif (ri < 0)\n\t\t\tri += length;\n\t\treturn ri;\n\t}\n\n}"
},
{
"identifier": "Length",
"path": "src/main/java/se/emirbuc/randomsentence/RandomSentences.java",
"snippet": "public enum Length {\n\t/** Three word sentence, think 'title | name | short description'*/\n\tSHORT, \n\t/** Six word sentences.*/\n\tMEDIUM, \n\t/** Twelve word sentences, think 'description'.*/\n\tLONG\n}"
}
] | import se.emirbuc.randomsentence.RandomSentences;
import se.emirbuc.randomsentence.RandomSentences.Length;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.Test; | 1,276 | /* The MIT License (MIT)
*
* Copyright (c) 2015 Emir Bucalovic (embuc)
*
* 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 se.emirbuc.randomsentence;
/**
* RandomSentencesTest class.
*
* @author Emir Bucalovic (embuc)
* @since 2015-okt-01
*/
public class RandomSentencesTest {
@Test
public void instantiation() {
RandomSentences target = new RandomSentences();
assertThat(target, notNullValue());
}
@Test
public void generateRandomSentence_WithArgument_Null() { | /* The MIT License (MIT)
*
* Copyright (c) 2015 Emir Bucalovic (embuc)
*
* 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 se.emirbuc.randomsentence;
/**
* RandomSentencesTest class.
*
* @author Emir Bucalovic (embuc)
* @since 2015-okt-01
*/
public class RandomSentencesTest {
@Test
public void instantiation() {
RandomSentences target = new RandomSentences();
assertThat(target, notNullValue());
}
@Test
public void generateRandomSentence_WithArgument_Null() { | Length length = null; | 1 | 2023-12-29 23:21:36+00:00 | 2k |
SDeVuyst/pingys-waddles-1.20.1 | src/main/java/com/sdevuyst/pingyswaddles/event/ModEventBusEvents.java | [
{
"identifier": "PingysWaddles",
"path": "src/main/java/com/sdevuyst/pingyswaddles/PingysWaddles.java",
"snippet": "@Mod(PingysWaddles.MOD_ID)\npublic class PingysWaddles\n{\n // Define mod id in a common place for everything to reference\n public static final String MOD_ID = \"pingyswaddles\";\n // Directly reference a slf4j logger\n private static final Logger LOGGER = LogUtils.getLogger();\n\n public PingysWaddles()\n {\n IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();\n // register Creative Tab\n ModCreativeModTabs.register(modEventBus);\n // register items\n ModItems.register(modEventBus);\n // register blocks\n ModBlocks.register(modEventBus);\n //register entities\n ModEntities.register(modEventBus);\n\n // Register the commonSetup method for modloading\n modEventBus.addListener(this::commonSetup);\n\n // Register ourselves for server and other game events we are interested in\n MinecraftForge.EVENT_BUS.register(this);\n\n // Register the item to a creative tab\n modEventBus.addListener(this::addCreative);\n\n }\n\n private void commonSetup(final FMLCommonSetupEvent event)\n {\n\n }\n\n // Add the example block item to the building blocks tab\n private void addCreative(BuildCreativeModeTabContentsEvent event)\n {\n\n }\n\n // You can use SubscribeEvent and let the Event Bus discover methods to call\n @SubscribeEvent\n public void onServerStarting(ServerStartingEvent event)\n {\n\n }\n\n // You can use EventBusSubscriber to automatically register all static methods in the class annotated with @SubscribeEvent\n @Mod.EventBusSubscriber(modid = MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)\n public static class ClientModEvents\n {\n @SubscribeEvent\n public static void onClientSetup(FMLClientSetupEvent event)\n {\n EntityRenderers.register(ModEntities.EMPEROR_PENGUIN.get(), EmperorPenguinRenderer::new);\n EntityRenderers.register(ModEntities.SURFBOARD.get(), SurfboardRenderer::new);\n }\n }\n}"
},
{
"identifier": "ModEntities",
"path": "src/main/java/com/sdevuyst/pingyswaddles/entity/ModEntities.java",
"snippet": "public class ModEntities\n{\n public static final DeferredRegister<EntityType<?>> ENTITY_TYPES =\n DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, PingysWaddles.MOD_ID);\n\n public static final RegistryObject<EntityType<EmperorPenguinEntity>> EMPEROR_PENGUIN =\n ENTITY_TYPES.register(\"emperor_penguin\", () -> EntityType.Builder.of(EmperorPenguinEntity::new, MobCategory.CREATURE)\n .sized(2, 2).build(\"emperor_penguin\"));\n\n public static final RegistryObject<EntityType<Entity>> SURFBOARD =\n ENTITY_TYPES.register(\"surfboard\", () -> EntityType.Builder.of(SurfboardEntity::new, MobCategory.MISC)\n .sized(1f, 0.05f).build(\"surfboard\"));\n\n\n\n public static void register(IEventBus eventBus)\n {\n ENTITY_TYPES.register(eventBus);\n }\n}"
},
{
"identifier": "EmperorPenguinEntity",
"path": "src/main/java/com/sdevuyst/pingyswaddles/entity/custom/EmperorPenguinEntity.java",
"snippet": "public class EmperorPenguinEntity extends AbstractPenguin {\n\n public EmperorPenguinEntity(EntityType<? extends Animal> pEntityType, Level pLevel) {\n super(pEntityType, pLevel);\n }\n\n @Nullable\n @Override\n public AgeableMob getBreedOffspring(ServerLevel serverLevel, AgeableMob ageableMob) {\n return ModEntities.EMPEROR_PENGUIN.get().create(serverLevel);\n }\n\n static {\n NORMAL_DIMENSIONS = EntityDimensions.fixed(1.0F, 1.9F);\n BABY_DIMENSIONS = EntityDimensions.fixed(0.5F, 0.9F);\n }\n}"
}
] | import com.sdevuyst.pingyswaddles.PingysWaddles;
import com.sdevuyst.pingyswaddles.entity.ModEntities;
import com.sdevuyst.pingyswaddles.entity.custom.EmperorPenguinEntity;
import net.minecraft.world.entity.SpawnPlacements;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraftforge.event.entity.EntityAttributeCreationEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; | 1,164 | package com.sdevuyst.pingyswaddles.event;
@Mod.EventBusSubscriber(modid = PingysWaddles.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
public class ModEventBusEvents
{
@SubscribeEvent
public static void commonSetup(FMLCommonSetupEvent event)
{
event.enqueueWork(() -> { | package com.sdevuyst.pingyswaddles.event;
@Mod.EventBusSubscriber(modid = PingysWaddles.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
public class ModEventBusEvents
{
@SubscribeEvent
public static void commonSetup(FMLCommonSetupEvent event)
{
event.enqueueWork(() -> { | SpawnPlacements.register(ModEntities.EMPEROR_PENGUIN.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.WORLD_SURFACE, EmperorPenguinEntity::canSpawn); | 2 | 2023-12-31 09:54:03+00:00 | 2k |
IGinX-THU/Parquet | src/main/java/org/apache/parquet/local/CodecFactory.java | [
{
"identifier": "NoopBytesInputCompressor",
"path": "src/main/java/org/apache/parquet/local/codec/NoopBytesInputCompressor.java",
"snippet": "public class NoopBytesInputCompressor implements CompressionCodecFactory.BytesInputCompressor {\n @Override\n public BytesInput compress(BytesInput bytes) throws IOException {\n return bytes;\n }\n\n @Override\n public CompressionCodecName getCodecName() {\n return CompressionCodecName.UNCOMPRESSED;\n }\n\n @Override\n public void release() {}\n}"
},
{
"identifier": "NoopBytesInputDecompressor",
"path": "src/main/java/org/apache/parquet/local/codec/NoopBytesInputDecompressor.java",
"snippet": "public class NoopBytesInputDecompressor implements CompressionCodecFactory.BytesInputDecompressor {\n @Override\n public void decompress(\n ByteBuffer input, int compressedSize, ByteBuffer output, int uncompressedSize)\n throws IOException {\n if (compressedSize != uncompressedSize) {\n throw new IOException(\n \"Non-compressed data did not have matching compressed and uncompressed sizes.\");\n }\n output.clear();\n output.put((ByteBuffer) input.duplicate().position(0).limit(compressedSize));\n }\n\n @Override\n public BytesInput decompress(BytesInput bytes, int uncompressedSize) {\n return bytes;\n }\n\n @Override\n public void release() {}\n}"
},
{
"identifier": "SnappyBytesInputCompressor",
"path": "src/main/java/org/apache/parquet/local/codec/SnappyBytesInputCompressor.java",
"snippet": "public class SnappyBytesInputCompressor implements CompressionCodecFactory.BytesInputCompressor {\n\n @Override\n public BytesInput compress(BytesInput bytes) throws IOException {\n int maxOutputSize = Snappy.maxCompressedLength((int) bytes.size());\n byte[] outgoing = new byte[maxOutputSize];\n int compressedSize = Snappy.compress(bytes.toByteArray(), 0, (int) bytes.size(), outgoing, 0);\n return BytesInput.from(outgoing, 0, compressedSize);\n }\n\n @Override\n public CompressionCodecName getCodecName() {\n return CompressionCodecName.SNAPPY;\n }\n\n @Override\n public void release() {}\n}"
},
{
"identifier": "SnappyBytesInputDecompressor",
"path": "src/main/java/org/apache/parquet/local/codec/SnappyBytesInputDecompressor.java",
"snippet": "public class SnappyBytesInputDecompressor\n implements CompressionCodecFactory.BytesInputDecompressor {\n\n @Override\n public BytesInput decompress(BytesInput bytes, int uncompressedSize) throws IOException {\n byte[] ingoing = bytes.toByteArray();\n byte[] outgoing = Snappy.uncompress(ingoing);\n if (outgoing.length != uncompressedSize) {\n throw new IOException(\"Non-compressed data did not have matching uncompressed sizes.\");\n }\n return BytesInput.from(outgoing);\n }\n\n @Override\n public void decompress(\n ByteBuffer input, int compressedSize, ByteBuffer output, int uncompressedSize)\n throws IOException {\n output.clear();\n int size = Snappy.uncompress(input, output);\n output.limit(size);\n }\n\n @Override\n public void release() {}\n}"
}
] | import org.apache.parquet.compression.CompressionCodecFactory;
import org.apache.parquet.hadoop.metadata.CompressionCodecName;
import org.apache.parquet.local.codec.NoopBytesInputCompressor;
import org.apache.parquet.local.codec.NoopBytesInputDecompressor;
import org.apache.parquet.local.codec.SnappyBytesInputCompressor;
import org.apache.parquet.local.codec.SnappyBytesInputDecompressor;
import java.util.HashMap;
import java.util.Map; | 1,231 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.parquet.local;
public class CodecFactory implements CompressionCodecFactory {
private final Map<CompressionCodecName, BytesInputCompressor> compressors = new HashMap<>();
private final Map<CompressionCodecName, BytesInputDecompressor> decompressors = new HashMap<>();
@Override
public BytesInputCompressor getCompressor(CompressionCodecName codecName) {
return createCompressor(codecName);
}
@Override
public BytesInputDecompressor getDecompressor(CompressionCodecName codecName) {
return decompressors.computeIfAbsent(codecName, this::createDecompressor);
}
protected BytesInputCompressor createCompressor(CompressionCodecName codecName) {
switch (codecName) {
case UNCOMPRESSED:
return new NoopBytesInputCompressor();
case SNAPPY:
return new SnappyBytesInputCompressor();
default:
throw new IllegalArgumentException("Unimplemented codec: " + codecName);
}
}
protected BytesInputDecompressor createDecompressor(CompressionCodecName codecName) {
switch (codecName) {
case UNCOMPRESSED: | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.parquet.local;
public class CodecFactory implements CompressionCodecFactory {
private final Map<CompressionCodecName, BytesInputCompressor> compressors = new HashMap<>();
private final Map<CompressionCodecName, BytesInputDecompressor> decompressors = new HashMap<>();
@Override
public BytesInputCompressor getCompressor(CompressionCodecName codecName) {
return createCompressor(codecName);
}
@Override
public BytesInputDecompressor getDecompressor(CompressionCodecName codecName) {
return decompressors.computeIfAbsent(codecName, this::createDecompressor);
}
protected BytesInputCompressor createCompressor(CompressionCodecName codecName) {
switch (codecName) {
case UNCOMPRESSED:
return new NoopBytesInputCompressor();
case SNAPPY:
return new SnappyBytesInputCompressor();
default:
throw new IllegalArgumentException("Unimplemented codec: " + codecName);
}
}
protected BytesInputDecompressor createDecompressor(CompressionCodecName codecName) {
switch (codecName) {
case UNCOMPRESSED: | return new NoopBytesInputDecompressor(); | 1 | 2023-12-29 01:48:28+00:00 | 2k |
AweiMC/DragonMounts3 | common/src/main/java/net/dragonmounts3/DM3Mod.java | [
{
"identifier": "DM3Item",
"path": "common/src/main/java/net/dragonmounts3/tools/DM3Item.java",
"snippet": "public interface DM3Item {\n DeferredRegister<ItemGroup> ITEM_GROUPS = DeferredRegister.create(DM3Mod.MOD_ID, RegistryKeys.ITEM_GROUP);\n\n // 创建一个 DeferredRegister 来注册物品\n RegistrySupplier<ItemGroup> DM3_GROUP = ITEM_GROUPS.register(new Identifier(\"dragonmounts3.title.group\"), () -> CreativeTabRegistry.create(\n Text.translatable(\"dragonmounts3.title.group\"),\n () -> Items.DIAMOND.asItem().getDefaultStack()\n ));\n\n\n DeferredRegister<Item> ITEMS = DeferredRegister.create(DM3Mod.MOD_ID, RegistryKeys.ITEM);\n static void ItemRegister() {\n ITEM_GROUPS.register();\n ITEMS.register(); // 这里注册你的物品\n registerTools();\n }\n\n\n\n static Item.Settings ItemToGroup() {\n return new Item.Settings().arch$tab(DM3_GROUP);\n }\n\n static void register(String name, Supplier<Item> item) {\n ITEMS.register(new Identifier(DM3Mod.MOD_ID,(name)), item);\n }\n\n static void registerTools() {\n for (String dragonType : DragonTypeManager.getDragonTypes()) {\n String DG = \"_dragon\";\n register(dragonType + DG + \"_sword\", () -> createDM3Tool(dragonType, ToolType.SWORD)); // 注册对应类型的武器\n register(dragonType + DG + \"_pickaxe\", () -> createDM3Tool(dragonType, ToolType.PICKAXE)); // 注册对应类型的镐\n register(dragonType + DG + \"_shovel\", () -> createDM3Tool(dragonType, ToolType.SHOVEL)); // 注册对应类型的锹\n // 添加其他工具类型的注册\n }\n }\n\n static Item createDM3Tool(String dragonType, ToolType toolType) {\n // 根据传递的工具类型和DragonType创建对应的工具,并返回\n // 此处根据传递的 ToolType 参数决定创建的是哪种类型的工具\n return switch (toolType) {\n case SWORD -> new DM3Sword(getToolMaterialForDragonType(dragonType), 9, 2, ItemToGroup() /*其他参数*/);\n case PICKAXE -> new PickaxeItem(getToolMaterialForDragonType(dragonType), -1, -2.4F, ItemToGroup());\n case SHOVEL -> new DM3Shovel(getToolMaterialForDragonType(dragonType), 9, 2, ItemToGroup() /*其他参数*/);\n case HOE -> new DM3Hoe(getToolMaterialForDragonType(dragonType), 9, 2, ItemToGroup() /*其他参数*/);\n };\n }\n\n static ToolMaterial getToolMaterialForDragonType(String dragonType) {\n // 根据DragonType返回对应的工具材料(ToolMaterial)\n // 可以根据DragonType的不同返回不同的材料\n // 这个方法需要根据您的需求进行具体实现\n // 示例中使用了 DM3ToolMaterials.FOREST 作为默认材料,您需要根据DragonType返回合适的材料\n return switch (dragonType) {\n case \"aether\" -> DM3ToolMaterials.AETHER;\n case \"enchant\" -> DM3ToolMaterials.ENCHANT;\n // 添加其他DragonType对应的材料\n default -> DM3ToolMaterials.FOREST; // 默认材料\n };\n }\n\n\n\n}"
},
{
"identifier": "DragonTypeManager",
"path": "common/src/main/java/net/dragonmounts3/util/DragonTypeManager.java",
"snippet": "public class DragonTypeManager {\n private static final Set<String> dragonTypes = new LinkedHashSet<>();\n\n static {\n initDefaultTypes();\n }\n\n private static void initDefaultTypes() {\n dragonTypes.add(\"aether\");\n dragonTypes.add(\"enchant\");\n dragonTypes.add(\"ender\");\n dragonTypes.add(\"fire\");\n dragonTypes.add(\"forest\");\n dragonTypes.add(\"ice\");\n dragonTypes.add(\"moonlight\");\n dragonTypes.add(\"nether\");\n dragonTypes.add(\"sculk\");\n dragonTypes.add(\"storm\");\n dragonTypes.add(\"sunlight\");\n dragonTypes.add(\"terra\");\n dragonTypes.add(\"water\");\n }\n\n public static synchronized void addDragonType(String type) {\n // 可以在这里进行网络同步,向所有玩家发送新的 DragonType\n dragonTypes.add(type);\n }\n\n public static synchronized Set<String> getDragonTypes() {\n return new LinkedHashSet<>(dragonTypes);\n }\n}"
}
] | import net.dragonmounts3.tools.DM3Item;
import net.dragonmounts3.util.DragonTypeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 1,241 | package net.dragonmounts3;
public class DM3Mod {
public static final String MOD_ID = "dragonmounts";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
public static void init() {
DragonTypeManager.init();// | package net.dragonmounts3;
public class DM3Mod {
public static final String MOD_ID = "dragonmounts";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
public static void init() {
DragonTypeManager.init();// | DM3Item.ItemRegister(); | 0 | 2023-12-28 12:11:21+00:00 | 2k |
amnoah/BetterDefusal | src/main/java/better/defusal/BetterDefusal.java | [
{
"identifier": "BetterDefusalCommand",
"path": "src/main/java/better/defusal/commands/BetterDefusalCommand.java",
"snippet": "public class BetterDefusalCommand extends Command {\n\n public BetterDefusalCommand() {\n setName(\"betterdefusal\");\n setPermission(\"better.defusal.command\");\n setSubcommands(new ReloadSubCommand(), new SetItemSubCommand());\n setRequiresArgs(false);\n setTabCompletions(\"Reload\", \"SetItem\");\n }\n\n @Override\n public void execute(CommandSender commandSender, String[] strings) {\n commandSender.sendMessage(\"§7BetterDefusal version §8\" + BetterDefusal.VERSION + \"§7!\");\n }\n}"
},
{
"identifier": "InteractListener",
"path": "src/main/java/better/defusal/listener/InteractListener.java",
"snippet": "public class InteractListener implements Listener {\n\n @EventHandler\n public void onInteractEntityRightClick(PlayerInteractEntityEvent event) {\n if (event.isCancelled()) return;\n if (!event.getPlayer().hasPermission(\"better.defusal.use\")) return;\n\n Material defusalItem = BetterDefusal.getInstance().getDefusalItem();\n ItemStack mainHand = event.getPlayer().getInventory().getItemInMainHand();\n ItemStack offHand = event.getPlayer().getInventory().getItemInOffHand();\n Damageable damageable = null;\n\n // Verify the right item is used.\n if (defusalItem != null) {\n if (mainHand.getType() == defusalItem) {\n if (mainHand.getItemMeta() instanceof Damageable && BetterDefusal.getInstance().isDurabilityUsed())\n damageable = (Damageable) mainHand.getItemMeta();\n } else if (offHand.getType() == defusalItem) {\n if (offHand.getItemMeta() instanceof Damageable && BetterDefusal.getInstance().isDurabilityUsed())\n damageable = (Damageable) offHand.getItemMeta();\n } else return;\n }\n\n Location location = event.getRightClicked().getLocation();\n Material material;\n\n // Determine the material to be dropped.\n if (event.getRightClicked() instanceof TNTPrimed) {\n material = Material.TNT;\n } else if(event.getRightClicked() instanceof ExplosiveMinecart) {\n material = Material.TNT_MINECART;\n } else if (event.getRightClicked() instanceof FallingBlock && BetterDefusal.getInstance().isAllBlocks()) {\n material = ((FallingBlock) event.getRightClicked()).getBlockData().getMaterial();\n } else return;\n\n // Drop the material and get rid of the entity.\n event.getRightClicked().getWorld().dropItem(location, new ItemStack(material));\n event.getRightClicked().getWorld().playSound(location, Sound.ENTITY_PLAYER_HURT, 1, 2);\n event.getRightClicked().remove();\n\n // Apply damage.\n if (damageable == null) return;\n if (event.getPlayer().getGameMode().equals(GameMode.CREATIVE)) return;\n damageable.setDamage(damageable.getDamage() + 1);\n if (mainHand.getType() == defusalItem) mainHand.setItemMeta(damageable);\n else offHand.setItemMeta(damageable);\n }\n}"
},
{
"identifier": "ReloadListener",
"path": "src/main/java/better/defusal/listener/ReloadListener.java",
"snippet": "public class ReloadListener implements Listener {\n\n @EventHandler\n public void onReload(ReloadEvent event) {\n BetterDefusal.getInstance().reload();\n }\n}"
}
] | import better.defusal.commands.BetterDefusalCommand;
import better.defusal.listener.InteractListener;
import better.defusal.listener.ReloadListener;
import com.imjustdoom.cmdinstruction.CMDInstruction;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.List; | 1,153 | package better.defusal;
public class BetterDefusal extends JavaPlugin {
public final static List<String> MATERIALS = new ArrayList<>();
public final static String VERSION = "1.0.0";
private static BetterDefusal instance;
private boolean allBlocks, durabilityUsed;
private Material defusalItem;
/**
* Generate a list of possible items to use as the "wire cutter".
*/
static {
MATERIALS.add("*");
for (Material material : Material.values()) if (material.isItem()) MATERIALS.add(material.name().toLowerCase());
}
/*
* Getters.
*/
/**
* Return the material used as the wire cutters.
*/
public Material getDefusalItem() {
return defusalItem;
}
/**
* Return the plugin's current instance.
*/
public static BetterDefusal getInstance() {
return instance;
}
/**
* Return whether falling blocks can also be "defused".
*/
public boolean isAllBlocks() {
return allBlocks;
}
/**
* Return whether defusing uses item durability
*/
public boolean isDurabilityUsed() {
return durabilityUsed;
}
/*
* Methods.
*/
@Override
public void onEnable() {
instance = this;
new Metrics(this, 20535);
| package better.defusal;
public class BetterDefusal extends JavaPlugin {
public final static List<String> MATERIALS = new ArrayList<>();
public final static String VERSION = "1.0.0";
private static BetterDefusal instance;
private boolean allBlocks, durabilityUsed;
private Material defusalItem;
/**
* Generate a list of possible items to use as the "wire cutter".
*/
static {
MATERIALS.add("*");
for (Material material : Material.values()) if (material.isItem()) MATERIALS.add(material.name().toLowerCase());
}
/*
* Getters.
*/
/**
* Return the material used as the wire cutters.
*/
public Material getDefusalItem() {
return defusalItem;
}
/**
* Return the plugin's current instance.
*/
public static BetterDefusal getInstance() {
return instance;
}
/**
* Return whether falling blocks can also be "defused".
*/
public boolean isAllBlocks() {
return allBlocks;
}
/**
* Return whether defusing uses item durability
*/
public boolean isDurabilityUsed() {
return durabilityUsed;
}
/*
* Methods.
*/
@Override
public void onEnable() {
instance = this;
new Metrics(this, 20535);
| CMDInstruction.registerCommands(this, new BetterDefusalCommand()); | 0 | 2023-12-22 05:38:25+00:00 | 2k |
MinsTail/essential | src/main/java/com/dotSoftix/guiManager/clickgui/Panel.java | [
{
"identifier": "ClientMain",
"path": "src/main/java/com/dotSoftix/EssentialClient/ClientMain.java",
"snippet": "public class ClientMain {\n private final static double modVersion = 1.92;\n public static String clientName = \"essential \" + modVersion;\n public static CopyOnWriteArrayList<ModuleLoader> modules = new CopyOnWriteArrayList<ModuleLoader>();\n\n public static ClickGuiScreen clickGui;\n\n public static void clientStartup() {\n Display.setTitle(clientName);\n\n modules.add(new Fly());\n modules.add(new Sprint());\n modules.add(new speedhack());\n modules.add(new FullBright());\n modules.add(new reachDistance());\n modules.add(new RedanMode());\n modules.add(new ultraFlight());\n modules.add(new Jesus());\n modules.add(new AirJump());\n modules.add(new TargetHud());\n modules.add(new Tracers());\n modules.add(new glowESP());\n modules.add(new NameTags());\n modules.add(new Velocity());\n modules.add(new InvWalk());\n modules.add(new JesusGlide());\n modules.add(new Glide());\n modules.add(new FakeCreative());\n modules.add(new ViewModel());\n modules.add(new spider());\n // -- combat -- //\n modules.add(new Aura());\n modules.add(new TriggerBot());\n // -- combat -- //\n\n // -- EXPERIMENTAL -- //\n modules.add(new AirBoost());\n modules.add(new NoWeather());\n modules.add(new noFall());\n modules.add(new packetLoss());\n modules.add(new setColor());\n modules.add(new drawCords());\n\n clickGui = new ClickGuiScreen();\n }\n public static void keyPress(int key) {\n for (ModuleLoader m : modules) {\n if (m.getKeyCode() == key) {\n m.toggle();\n }\n }\n }\n}"
},
{
"identifier": "ModuleLoader",
"path": "src/main/java/com/dotSoftix/EssentialClient/modules/ModuleLoader.java",
"snippet": "public class ModuleLoader {\n public String name;\n public boolean toggled;\n public int keyCode;\n public Category category;\n public Minecraft mc = Minecraft.getMinecraft();\n\n public ModuleLoader(String name, int key, Category c) {\n this.name = name;\n this.keyCode = key;\n this.category = c;\n }\n\n public boolean isEnabled() {\n return toggled;\n }\n\n public int getKeyCode() {\n return keyCode;\n }\n\n public void onEnable() {\n MinecraftForge.EVENT_BUS.register(this);\n }\n\n public void onDisable(){\n MinecraftForge.EVENT_BUS.unregister(this);\n }\n\n public void setKey(int key){\n this.keyCode = key;\n }\n\n public Category getCategory() {\n return category;\n }\n\n public String getName() {\n return this.name;\n }\n public void disable() {\n toggled = false;\n }\n\n public void onUpdate() {\n\n }\n\n public void toggle() {\n toggled = !toggled;\n if (toggled) {\n onEnable();\n } else {\n onDisable();\n }\n }\n\n public enum Category {\n MOVEMENT,\n RENDER,\n COMBAT,\n EXPLOIT,\n EXPERIMENTAL;\n }\n\n public void setToggled() {\n this.toggled = toggled;\n if (this.toggled) {\n onEnable();\n } else {\n onDisable();\n }\n }\n}"
},
{
"identifier": "checkRedanMode",
"path": "src/main/java/com/dotSoftix/EssentialClient/guiModes/checkRedanMode.java",
"snippet": "public class checkRedanMode {\n public static boolean isRedanModeActivated = false;\n}"
},
{
"identifier": "checkBlueMode",
"path": "src/main/java/com/dotSoftix/EssentialClient/guiModes/checkBlueMode.java",
"snippet": "public class checkBlueMode {\n public static boolean blueMode = false;\n}"
}
] | import com.dotSoftix.EssentialClient.ClientMain;
import com.dotSoftix.EssentialClient.modules.ModuleLoader;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import com.dotSoftix.EssentialClient.guiModes.checkRedanMode;
import com.dotSoftix.EssentialClient.guiModes.checkBlueMode;
import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; | 1,068 | package com.dotSoftix.guiManager.clickgui;
public class Panel {
public Minecraft mc = Minecraft.getMinecraft();
public int x, y, width, height, dragY, dragX;
public boolean extended, dragging; | package com.dotSoftix.guiManager.clickgui;
public class Panel {
public Minecraft mc = Minecraft.getMinecraft();
public int x, y, width, height, dragY, dragX;
public boolean extended, dragging; | public ModuleLoader.Category category; | 1 | 2023-12-28 15:15:14+00:00 | 2k |
Yanyutin753/PandoraNext-TokensTool | rearServer/src/main/java/com/tokensTool/pandoraNext/service/impl/loginServiceImpl.java | [
{
"identifier": "systemSetting",
"path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/systemSetting.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class systemSetting {\n /**\n * 绑定IP和端口\n */\n private String bing;\n /**\n * 请求的超时时间\n */\n private Integer timeout;\n /**\n * 部署服务流量走代理\n */\n private String proxy_url;\n /**\n * GPT中创建的对话分享\n */\n private Boolean public_share;\n /**\n * 访问网站密码\n */\n private String site_password;\n /**\n * 重载服务密码\n */\n private String setup_password;\n /**\n * 白名单(null则不限制,为空数组[]则限制所有账号)\n */\n private String whitelist;\n\n /**\n * pandoraNext验证license_id\n */\n private String license_id;\n\n /**\n * tokensTool登录Username\n */\n private String loginUsername;\n\n /**\n * tokensTool密码Password\n */\n private String loginPassword;\n\n /**\n * tokensTool 验证信息\n */\n private validation validation;\n\n /**\n * tokensTool 更新token网址\n * 为\"default\"则调用本机的,不为“default\"则自定义\n */\n private String autoToken_url;\n\n /**\n * 是否开启拿tokensTool的后台token\n */\n private Boolean isGetToken;\n /**\n * tokensTool 拿到getTokenPassword\n * 为\"getTokenPassword\" 默认:123456\n * 默认拿getTokenPassword\n */\n private String getTokenPassword;\n\n /**\n * tokensTool 更新containerName(容器名)\n * 通过容器名实现开启,关闭,重新启动容器\n */\n private String containerName;\n\n\n /**\n * PandoraNext tls证书\n */\n private tls tls;\n\n /**\n * PandoraNext config.json位置\n */\n private String configPosition;\n\n /**\n * PandoraNext 接口地址添加前缀\n */\n private String isolated_conv_title;\n\n /**\n * PandoraNext 会话标题\n */\n private String proxy_api_prefix;\n\n /**\n * 禁用注册账号功能,true或false\n */\n private Boolean disable_signup;\n\n /**\n * 在proxy模式使用gpt-4模型调用/backend-api/conversation接口是否自动打码,使用消耗为4+10。\n */\n private Boolean auto_conv_arkose;\n\n /**\n * 在proxy模式是否使用PandoraNext的文件代理服务,避免官方文件服务的墙。\n */\n private Boolean proxy_file_service;\n\n /**\n * 配置自定义的DoH主机名,建议使用IP形式。默认在+8区使用223.6.6.6,其余地区使用1.1.1.1。\n */\n private String custom_doh_host;\n\n /**\n * 自动刷新session的开关\n */\n private Boolean auto_updateSession;\n\n /**\n * 自动刷新session的时间 (天为单位)\n */\n private Integer auto_updateTime;\n\n /**\n * 自动刷新session的个数 (个)\n */\n private Integer auto_updateNumber;\n\n /**\n * PadoraNext的公网访问地址\n */\n private String pandoraNext_outUrl;\n\n /**\n * oneAPi的公网访问地址\n */\n private String oneAPi_outUrl;\n\n /**\n * oneApi访问令牌\n */\n private String oneAPi_intoToken;\n}"
},
{
"identifier": "loginService",
"path": "rearServer/src/main/java/com/tokensTool/pandoraNext/service/loginService.java",
"snippet": "public interface loginService {\n\n /**\n * 新增保存登录信息\n * 通过config.json文件可以实现修改密码,修改数据\n *\n * @return \"登录成功!\"\n * \"用户名账号错误\"\n */\n\n boolean login(systemSetting setting);\n}"
},
{
"identifier": "systemService",
"path": "rearServer/src/main/java/com/tokensTool/pandoraNext/service/systemService.java",
"snippet": "public interface systemService {\n /**\n * 修改config.json里的系统值\n *\n * @return \"修改成功!\"or\"修改失败\"\n */\n String requiredSetting(systemSetting tem);\n\n /**\n * 查询config.json里的系统值\n *\n * @return systemSettings类\n */\n systemSetting selectSetting();\n\n /**\n * 查询config.json里的baseUrl\n *\n * @return systemSettings类\n */\n systemSetting selectSettingUrl();\n\n}"
}
] | import com.tokensTool.pandoraNext.pojo.systemSetting;
import com.tokensTool.pandoraNext.service.loginService;
import com.tokensTool.pandoraNext.service.systemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; | 1,352 | package com.tokensTool.pandoraNext.service.impl;
/**
* @author Yangyang
* @create 2023-11-17 14:15
*/
@Slf4j
@Service | package com.tokensTool.pandoraNext.service.impl;
/**
* @author Yangyang
* @create 2023-11-17 14:15
*/
@Slf4j
@Service | public class loginServiceImpl implements loginService { | 1 | 2023-11-17 11:37:37+00:00 | 2k |
bryan31/Akali | src/main/java/org/dromara/akali/spring/AkaliScanner.java | [
{
"identifier": "AkaliStrategyEnum",
"path": "src/main/java/org/dromara/akali/enums/AkaliStrategyEnum.java",
"snippet": "public enum AkaliStrategyEnum {\n\n FALLBACK, HOT_METHOD\n}"
},
{
"identifier": "AkaliMethodManager",
"path": "src/main/java/org/dromara/akali/manager/AkaliMethodManager.java",
"snippet": "public class AkaliMethodManager {\n\n private static final Logger log = LoggerFactory.getLogger(AkaliMethodManager.class);\n\n private static final Map<String, Tuple2<AkaliStrategyEnum, Annotation>> akaliMethodMap = new HashMap<>();\n\n public static void addMethodStr(String methodStr, Tuple2<AkaliStrategyEnum, Annotation> tuple){\n log.info(\"[AKALI] Register akali method:[{}][{}]\", tuple.r1.name(), methodStr);\n akaliMethodMap.put(methodStr, tuple);\n }\n\n public static Tuple2<AkaliStrategyEnum, Annotation> getAnnoInfo(String methodStr){\n return akaliMethodMap.get(methodStr);\n }\n\n public static boolean contain(String methodStr){\n return akaliMethodMap.containsKey(methodStr);\n }\n}"
},
{
"identifier": "AkaliStrategyManager",
"path": "src/main/java/org/dromara/akali/manager/AkaliStrategyManager.java",
"snippet": "public class AkaliStrategyManager {\n\n private static final Map<AkaliStrategyEnum, AkaliStrategy> strategyMap = new HashMap<>();\n\n public static void addStrategy(AkaliStrategy akaliStrategy){\n strategyMap.put(akaliStrategy.getStrategy(), akaliStrategy);\n }\n\n public static AkaliStrategy getStrategy(AkaliStrategyEnum strategyEnum){\n return strategyMap.get(strategyEnum);\n }\n}"
},
{
"identifier": "AkaliByteBuddyProxy",
"path": "src/main/java/org/dromara/akali/proxy/AkaliByteBuddyProxy.java",
"snippet": "public class AkaliByteBuddyProxy {\n\n private final Logger log = LoggerFactory.getLogger(this.getClass());\n\n private final Object bean;\n\n private final Class<?> originalClazz;\n\n public AkaliByteBuddyProxy(Object bean, Class<?> originalClazz) {\n this.bean = bean;\n this.originalClazz = originalClazz;\n }\n\n public Object proxy() throws Exception{\n return new ByteBuddy().subclass(originalClazz)\n .name(StrUtil.format(\"{}$ByteBuddy${}\", bean.getClass().getName(), SerialsUtil.generateShortUUID()))\n .method(ElementMatchers.any())\n .intercept(InvocationHandlerAdapter.of(new AopInvocationHandler()))\n .attribute(MethodAttributeAppender.ForInstrumentedMethod.INCLUDING_RECEIVER)\n .annotateType(bean.getClass().getAnnotations())\n .make()\n .load(AkaliByteBuddyProxy.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)\n .getLoaded()\n .newInstance();\n }\n\n public class AopInvocationHandler implements InvocationHandler {\n\n @Override\n public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n String methodStr = MethodUtil.resolveMethodName(method);\n\n if (AkaliMethodManager.contain(methodStr)){\n AkaliStrategyEnum akaliStrategyEnum = AkaliMethodManager.getAnnoInfo(methodStr).r1;\n Annotation anno = AkaliMethodManager.getAnnoInfo(methodStr).r2;\n\n if (anno instanceof AkaliFallback){\n AkaliRuleManager.registerFallbackRule((AkaliFallback) anno, method);\n }else if (anno instanceof AkaliHot){\n AkaliRuleManager.registerHotRule((AkaliHot) anno, method);\n }else{\n throw new RuntimeException(\"annotation type error\");\n }\n\n return SphEngine.process(bean, method, args, methodStr, akaliStrategyEnum);\n }else {\n return method.invoke(bean, args);\n }\n }\n }\n}"
},
{
"identifier": "AkaliStrategy",
"path": "src/main/java/org/dromara/akali/strategy/AkaliStrategy.java",
"snippet": "public interface AkaliStrategy {\n\n AkaliStrategyEnum getStrategy();\n\n Object process(Object bean, Method method, Object[] args) throws Exception;\n}"
},
{
"identifier": "ProxyUtil",
"path": "src/main/java/org/dromara/akali/util/ProxyUtil.java",
"snippet": "public class ProxyUtil {\n\n public static Class<?> getUserClass(Class<?> clazz) {\n if (isCglibProxyClass(clazz)) {\n Class<?> superclass = clazz.getSuperclass();\n return getUserClass(superclass);\n }\n return clazz;\n }\n\n public static boolean isCglibProxyClass(Class<?> clazz) {\n return (clazz != null && isCglibProxyClassName(clazz.getName()));\n }\n\n private static boolean isCglibProxyClassName(String className) {\n return (className != null && className.contains(\"$$\"));\n }\n\n}"
}
] | import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.csp.sentinel.util.MethodUtil;
import com.alibaba.csp.sentinel.util.function.Tuple2;
import org.dromara.akali.annotation.AkaliFallback;
import org.dromara.akali.annotation.AkaliHot;
import org.dromara.akali.enums.AkaliStrategyEnum;
import org.dromara.akali.manager.AkaliMethodManager;
import org.dromara.akali.manager.AkaliStrategyManager;
import org.dromara.akali.proxy.AkaliByteBuddyProxy;
import org.dromara.akali.strategy.AkaliStrategy;
import org.dromara.akali.util.ProxyUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean; | 1,367 | package org.dromara.akali.spring;
public class AkaliScanner implements InstantiationAwareBeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Class<?> clazz = ProxyUtil.getUserClass(bean.getClass());
| package org.dromara.akali.spring;
public class AkaliScanner implements InstantiationAwareBeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Class<?> clazz = ProxyUtil.getUserClass(bean.getClass());
| if (AkaliStrategy.class.isAssignableFrom(clazz)){ | 4 | 2023-11-10 07:28:38+00:00 | 2k |
quarkiverse/quarkus-langchain4j | core/runtime/src/main/java/io/quarkiverse/langchain4j/runtime/tool/QuarkusToolExecutor.java | [
{
"identifier": "QuarkusJsonCodecFactory",
"path": "core/runtime/src/main/java/io/quarkiverse/langchain4j/QuarkusJsonCodecFactory.java",
"snippet": "public class QuarkusJsonCodecFactory implements JsonCodecFactory {\n\n @Override\n public Json.JsonCodec create() {\n return new Codec();\n }\n\n private static class Codec implements Json.JsonCodec {\n\n @Override\n public String toJson(Object o) {\n try {\n return ObjectMapperHolder.WRITER.writeValueAsString(o);\n } catch (JsonProcessingException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n @Override\n public <T> T fromJson(String json, Class<T> type) {\n try {\n return ObjectMapperHolder.MAPPER.readValue(json, type);\n } catch (JsonProcessingException e) {\n if ((e instanceof JsonParseException) && (type.isEnum())) {\n // this is the case where Langchain4j simply passes the string value of the enum to Json.fromJson()\n // and Jackson does not handle it\n Class<? extends Enum> enumClass = type.asSubclass(Enum.class);\n return (T) Enum.valueOf(enumClass, json);\n }\n throw new UncheckedIOException(e);\n }\n }\n\n @Override\n public InputStream toInputStream(Object o, Class<?> type) throws IOException {\n return new ByteArrayInputStream(ObjectMapperHolder.WRITER.writeValueAsBytes(o));\n }\n\n }\n\n public static class ObjectMapperHolder {\n public static final ObjectMapper MAPPER;\n public static final TypeReference<Map<String, Object>> MAP_TYPE_REFERENCE = new TypeReference<>() {\n };\n private static final ObjectWriter WRITER;\n\n static {\n MAPPER = Arc.container().instance(ObjectMapper.class).get()\n .copy()\n .setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE)\n .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);\n WRITER = MAPPER.writerWithDefaultPrettyPrinter();\n }\n }\n\n public static class SnakeCaseObjectMapperHolder {\n public static final ObjectMapper MAPPER = Arc.container().instance(ObjectMapper.class).get()\n .copy()\n .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)\n .setSerializationInclusion(JsonInclude.Include.NON_NULL);\n }\n\n}"
},
{
"identifier": "Mappable",
"path": "core/runtime/src/main/java/io/quarkiverse/langchain4j/runtime/prompt/Mappable.java",
"snippet": "public interface Mappable {\n\n Map<String, Object> obtainFieldValuesMap();\n}"
}
] | import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.function.BiFunction;
import org.jboss.logging.Logger;
import com.fasterxml.jackson.core.JsonProcessingException;
import dev.langchain4j.agent.tool.ToolExecutionRequest;
import dev.langchain4j.agent.tool.ToolExecutor;
import dev.langchain4j.internal.Json;
import io.quarkiverse.langchain4j.QuarkusJsonCodecFactory;
import io.quarkiverse.langchain4j.runtime.prompt.Mappable; | 1,496 | package io.quarkiverse.langchain4j.runtime.tool;
public class QuarkusToolExecutor implements ToolExecutor {
private static final Logger log = Logger.getLogger(QuarkusToolExecutor.class);
private final Context context;
public record Context(Object tool, String toolInvokerName, String methodName, String argumentMapperClassName) {
}
public interface Wrapper {
String wrap(ToolExecutionRequest toolExecutionRequest, Object memoryId,
BiFunction<ToolExecutionRequest, Object, String> fun);
}
public QuarkusToolExecutor(Context context) {
this.context = context;
}
public String execute(ToolExecutionRequest toolExecutionRequest, Object memoryId) {
log.debugv("About to execute {0}", toolExecutionRequest);
ToolInvoker invokerInstance = createInvokerInstance();
Object[] params = prepareArguments(toolExecutionRequest, invokerInstance.methodMetadata());
try {
if (log.isDebugEnabled()) {
log.debugv("Attempting to invoke tool {0} with parameters {1}", context.tool, Arrays.toString(params));
}
Object invocationResult = invokerInstance.invoke(context.tool,
params);
String result = handleResult(invokerInstance, invocationResult);
log.debugv("Tool execution result: {0}", result);
return result;
} catch (Exception e) {
if (e instanceof IllegalArgumentException) {
throw (IllegalArgumentException) e;
}
log.error("Error while executing tool '" + context.tool.getClass() + "'", e);
return e.getMessage();
}
}
private static String handleResult(ToolInvoker invokerInstance, Object invocationResult) {
if (invokerInstance.methodMetadata().isReturnsVoid()) {
return "Success";
}
return Json.toJson(invocationResult);
}
// TODO: cache
private ToolInvoker createInvokerInstance() {
ToolInvoker invokerInstance;
try {
invokerInstance = (ToolInvoker) Class.forName(context.toolInvokerName, true, Thread.currentThread()
.getContextClassLoader()).getConstructor().newInstance();
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException
| InvocationTargetException e) {
throw new IllegalStateException(
"Unable to create instance of '" + context.toolInvokerName
+ "'. Please report this issue to the maintainers",
e);
}
return invokerInstance;
}
private Object[] prepareArguments(ToolExecutionRequest toolExecutionRequest,
ToolInvoker.MethodMetadata methodMetadata) {
String argumentsJsonStr = toolExecutionRequest.arguments();
Map<String, Object> argumentsFromRequest;
try {
log.debugv("Attempting to convert {0} JSON string into args map", argumentsJsonStr);
argumentsFromRequest = convertJsonToArguments(argumentsJsonStr);
log.debugv("Converted {0} JSON string into args map {1}", argumentsJsonStr, argumentsFromRequest);
} catch (JsonProcessingException e) {
log.error(e);
invalidMethodParams(argumentsJsonStr);
return null; //keep the compiler happy
}
if (argumentsFromRequest.size() != methodMetadata.getNameToParamPosition().size()) {
invalidMethodParams(argumentsJsonStr);
}
Object[] finalArgs = new Object[argumentsFromRequest.size()];
for (var entry : argumentsFromRequest.entrySet()) {
Integer pos = methodMetadata.getNameToParamPosition().get(entry.getKey());
if (pos == null) {
invalidMethodParams(argumentsJsonStr);
} else {
finalArgs[pos] = entry.getValue();
}
}
return finalArgs;
}
private Map<String, Object> convertJsonToArguments(String argumentsJsonStr) throws JsonProcessingException {
if (argumentsJsonStr == null || argumentsJsonStr.isEmpty()) {
return Collections.emptyMap();
} | package io.quarkiverse.langchain4j.runtime.tool;
public class QuarkusToolExecutor implements ToolExecutor {
private static final Logger log = Logger.getLogger(QuarkusToolExecutor.class);
private final Context context;
public record Context(Object tool, String toolInvokerName, String methodName, String argumentMapperClassName) {
}
public interface Wrapper {
String wrap(ToolExecutionRequest toolExecutionRequest, Object memoryId,
BiFunction<ToolExecutionRequest, Object, String> fun);
}
public QuarkusToolExecutor(Context context) {
this.context = context;
}
public String execute(ToolExecutionRequest toolExecutionRequest, Object memoryId) {
log.debugv("About to execute {0}", toolExecutionRequest);
ToolInvoker invokerInstance = createInvokerInstance();
Object[] params = prepareArguments(toolExecutionRequest, invokerInstance.methodMetadata());
try {
if (log.isDebugEnabled()) {
log.debugv("Attempting to invoke tool {0} with parameters {1}", context.tool, Arrays.toString(params));
}
Object invocationResult = invokerInstance.invoke(context.tool,
params);
String result = handleResult(invokerInstance, invocationResult);
log.debugv("Tool execution result: {0}", result);
return result;
} catch (Exception e) {
if (e instanceof IllegalArgumentException) {
throw (IllegalArgumentException) e;
}
log.error("Error while executing tool '" + context.tool.getClass() + "'", e);
return e.getMessage();
}
}
private static String handleResult(ToolInvoker invokerInstance, Object invocationResult) {
if (invokerInstance.methodMetadata().isReturnsVoid()) {
return "Success";
}
return Json.toJson(invocationResult);
}
// TODO: cache
private ToolInvoker createInvokerInstance() {
ToolInvoker invokerInstance;
try {
invokerInstance = (ToolInvoker) Class.forName(context.toolInvokerName, true, Thread.currentThread()
.getContextClassLoader()).getConstructor().newInstance();
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException
| InvocationTargetException e) {
throw new IllegalStateException(
"Unable to create instance of '" + context.toolInvokerName
+ "'. Please report this issue to the maintainers",
e);
}
return invokerInstance;
}
private Object[] prepareArguments(ToolExecutionRequest toolExecutionRequest,
ToolInvoker.MethodMetadata methodMetadata) {
String argumentsJsonStr = toolExecutionRequest.arguments();
Map<String, Object> argumentsFromRequest;
try {
log.debugv("Attempting to convert {0} JSON string into args map", argumentsJsonStr);
argumentsFromRequest = convertJsonToArguments(argumentsJsonStr);
log.debugv("Converted {0} JSON string into args map {1}", argumentsJsonStr, argumentsFromRequest);
} catch (JsonProcessingException e) {
log.error(e);
invalidMethodParams(argumentsJsonStr);
return null; //keep the compiler happy
}
if (argumentsFromRequest.size() != methodMetadata.getNameToParamPosition().size()) {
invalidMethodParams(argumentsJsonStr);
}
Object[] finalArgs = new Object[argumentsFromRequest.size()];
for (var entry : argumentsFromRequest.entrySet()) {
Integer pos = methodMetadata.getNameToParamPosition().get(entry.getKey());
if (pos == null) {
invalidMethodParams(argumentsJsonStr);
} else {
finalArgs[pos] = entry.getValue();
}
}
return finalArgs;
}
private Map<String, Object> convertJsonToArguments(String argumentsJsonStr) throws JsonProcessingException {
if (argumentsJsonStr == null || argumentsJsonStr.isEmpty()) {
return Collections.emptyMap();
} | Mappable mappable = QuarkusJsonCodecFactory.ObjectMapperHolder.MAPPER.readValue(argumentsJsonStr, loadMapperClass()); | 1 | 2023-11-13 09:10:27+00:00 | 2k |
qiusunshine/xiu | app/src/main/java/org/mozilla/xiu/browser/video/VideoDetector.java | [
{
"identifier": "DetectedMediaResult",
"path": "app/src/main/java/org/mozilla/xiu/browser/video/model/DetectedMediaResult.java",
"snippet": "public class DetectedMediaResult {\n private String url;\n private String title;\n private Media mediaType;\n private long timestamp;\n private boolean clicked;\n private Map<String, String> headers;\n\n public DetectedMediaResult(String url) {\n this.url = url;\n this.mediaType = new Media(Media.OTHER);\n }\n\n public DetectedMediaResult(String url, String title) {\n this.url = url;\n this.title = title;\n this.mediaType = new Media(Media.OTHER);\n }\n\n public DetectedMediaResult() {\n this.mediaType = new Media(Media.OTHER);\n }\n\n public Media getMediaType() {\n return mediaType;\n }\n\n public void setMediaType(Media mediaType) {\n this.mediaType = mediaType;\n }\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public long getTimestamp() {\n return timestamp;\n }\n\n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n\n public boolean isClicked() {\n return clicked;\n }\n\n public void setClicked(boolean clicked) {\n this.clicked = clicked;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public Map<String, String> getHeaders() {\n return headers;\n }\n\n public void setHeaders(Map<String, String> headers) {\n this.headers = headers;\n }\n}"
},
{
"identifier": "MediaType",
"path": "app/src/main/java/org/mozilla/xiu/browser/video/model/MediaType.java",
"snippet": "public enum MediaType {\n\n VIDEO(\"VIDEO\", \"\"), VIDEO_MUSIC(\"VIDEO_MUSIC\", \"\"), IMAGE(\"IMAGE\", \"\"), MUSIC(\"MUSIC\", \"\"), HTML(\"HTML\",\"\"), OTHER(\"OTHER\",\"\"), BLOCK(\"BLOCK\",\"\");\n\n MediaType(String name, String type) {\n this.name = name;\n this.type = type;\n }\n\n private String name;\n private String type;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }}"
}
] | import android.content.Context;
import org.mozilla.xiu.browser.video.model.DetectedMediaResult;
import org.mozilla.xiu.browser.video.model.MediaType;
import java.util.List; | 727 | package org.mozilla.xiu.browser.video;
/**
* 作者:By 15968
* 日期:On 2022/5/23
* 时间:At 11:21
*/
public interface VideoDetector {
void putIntoXiuTanLiked(Context context, String dom, String url); | package org.mozilla.xiu.browser.video;
/**
* 作者:By 15968
* 日期:On 2022/5/23
* 时间:At 11:21
*/
public interface VideoDetector {
void putIntoXiuTanLiked(Context context, String dom, String url); | List<DetectedMediaResult> getDetectedMediaResults(String webUrl, MediaType mediaType); | 0 | 2023-11-10 14:28:40+00:00 | 2k |
noear/folkmq | folkmq-test/src/test/java/features/cases/BaseTestCase.java | [
{
"identifier": "MqClient",
"path": "folkmq/src/main/java/org/noear/folkmq/client/MqClient.java",
"snippet": "public interface MqClient extends Closeable {\n /**\n * 连接\n */\n MqClient connect() throws IOException;\n\n /**\n * 断开连接\n */\n void disconnect() throws IOException;\n\n /**\n * 客户端配置\n */\n MqClient config(ClientConfigHandler configHandler);\n\n /**\n * 自动回执\n *\n * @param auto 自动(默认为 true)\n */\n MqClient autoAcknowledge(boolean auto);\n\n /**\n * 订阅主题\n *\n * @param topic 主题\n * @param consumerGroup 消费者组\n * @param consumerHandler 消费处理\n */\n void subscribe(String topic, String consumerGroup, MqConsumeHandler consumerHandler) throws IOException;\n\n /**\n * 取消订阅主题\n *\n * @param topic 主题\n * @param consumerGroup 消费者组\n */\n void unsubscribe(String topic, String consumerGroup) throws IOException;\n\n /**\n * 同步发布消息\n *\n * @param topic 主题\n * @param message 消息\n */\n void publish(String topic, IMqMessage message) throws IOException;\n\n /**\n * 异步发布消息\n *\n * @param topic 主题\n * @param message 消息\n */\n CompletableFuture<Boolean> publishAsync(String topic, IMqMessage message) throws IOException;\n\n /**\n * 取消发布\n *\n * @param topic 主题\n * @param tid 事务id\n */\n void unpublish(String topic, String tid) throws IOException;\n\n /**\n * 取消发布\n *\n * @param topic 主题\n * @param tid 事务id\n */\n CompletableFuture<Boolean> unpublishAsync(String topic, String tid) throws IOException;\n}"
},
{
"identifier": "MqServer",
"path": "folkmq/src/main/java/org/noear/folkmq/server/MqServer.java",
"snippet": "public interface MqServer {\n /**\n * 服务端配置\n */\n MqServer config(ServerConfigHandler configHandler);\n\n /**\n * 配置观察者\n */\n MqServer watcher(MqWatcher watcher);\n\n /**\n * 配置访问账号\n *\n * @param ak 访问者身份\n * @param sk 访问者密钥\n */\n MqServer addAccess(String ak, String sk);\n\n /**\n * 配置访问账号\n *\n * @param accessMap 访问账号集合\n */\n MqServer addAccessAll(Map<String, String> accessMap);\n\n /**\n * 启动\n */\n MqServer start(int port) throws Exception;\n\n /**\n * 停止\n */\n void stop();\n\n\n /**\n * 获取内部服务\n */\n MqServiceInternal getServerInternal();\n}"
}
] | import org.noear.folkmq.client.MqClient;
import org.noear.folkmq.server.MqServer; | 875 | package features.cases;
/**
* @author noear
* @since 1.0
*/
public abstract class BaseTestCase {
private final int port; | package features.cases;
/**
* @author noear
* @since 1.0
*/
public abstract class BaseTestCase {
private final int port; | protected MqServer server; | 1 | 2023-11-18 19:09:28+00:00 | 2k |
leluque/java2uml | src/main/java/br/com/luque/java2uml/plantuml/writer/classdiagram/PlantUMLMethodWriter.java | [
{
"identifier": "Method",
"path": "src/main/java/br/com/luque/java2uml/core/classdiagram/reflection/model/Method.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic class Method extends BaseItem {\n private java.lang.reflect.Method method;\n private java.lang.reflect.Constructor<?> constructor;\n private Visibilities visibility;\n private Parameter[] parameters;\n private Clazz returnType;\n private boolean static_;\n private boolean abstract_;\n\n public Method(java.lang.reflect.Method method, ClazzPool clazzPool) {\n super(method.getName(), clazzPool);\n setMethod(method);\n extractMethodInfo();\n }\n\n public Method(java.lang.reflect.Constructor<?> constructor, ClazzPool clazzPool) {\n super(constructor.getDeclaringClass().getSimpleName(), clazzPool);\n setConstructor(constructor);\n extractConstructorInfo();\n }\n\n public void setMethod(java.lang.reflect.Method method) {\n this.method = Objects.requireNonNull(method);\n }\n\n public void setConstructor(java.lang.reflect.Constructor<?> constructor) {\n this.constructor = Objects.requireNonNull(constructor);\n }\n\n public Visibilities getVisibility() {\n return visibility;\n }\n\n public void setVisibility(Visibilities visibility) {\n this.visibility = Objects.requireNonNull(visibility);\n }\n\n public Parameter[] getParameters() {\n return parameters;\n }\n\n public void setParameters(Parameter[] parameters) {\n this.parameters = parameters;\n }\n\n public Clazz getReturnType() {\n return returnType;\n }\n\n public void setReturnType(Clazz returnType) {\n this.returnType = Objects.requireNonNull(returnType);\n }\n\n public boolean isConstructor() {\n return returnType == null;\n }\n\n public boolean isStatic() {\n return static_;\n }\n\n public boolean isAbstract() {\n return abstract_;\n }\n\n public boolean hasDependency() {\n return getDependencies().length > 0;\n }\n\n public Clazz[] getDependencies() {\n List<Clazz> dependencies = new ArrayList<>();\n if (returnType != null && getClazzPool().getRules().includes(returnType.getJavaClass())) {\n dependencies.add(returnType);\n }\n Stream.of(parameters).filter(p -> getClazzPool().getRules().includes(p.getType().getJavaClass())).forEach(p -> dependencies.add(p.getType()));\n return dependencies.toArray(Clazz[]::new);\n }\n\n private void extractMethodInfo() {\n this.visibility = Visibilities.fromModifiers(method.getModifiers());\n this.parameters = Stream.of(method.getParameters()).map(p -> new Parameter(p.getName(), getClazzPool().getFor(p.getType()), getClazzPool())).toArray(Parameter[]::new);\n this.returnType = getClazzPool().getFor(method.getReturnType());\n this.static_ = java.lang.reflect.Modifier.isStatic(method.getModifiers());\n this.abstract_ = java.lang.reflect.Modifier.isAbstract(method.getModifiers());\n }\n\n private void extractConstructorInfo() {\n this.visibility = Visibilities.fromModifiers(constructor.getModifiers());\n this.parameters = Stream.of(constructor.getParameters()).map(p -> new Parameter(p.getName(), getClazzPool().getFor(p.getType()), getClazzPool())).toArray(Parameter[]::new);\n }\n}"
},
{
"identifier": "MethodWriter",
"path": "src/main/java/br/com/luque/java2uml/core/classdiagram/writer/MethodWriter.java",
"snippet": "public interface MethodWriter {\n String getString(Method method);\n}"
},
{
"identifier": "YUMLHelper",
"path": "src/main/java/br/com/luque/java2uml/yuml/writer/classdiagram/YUMLHelper.java",
"snippet": "public class YUMLHelper {\n public static String getVisibilityText(Visibilities visibility) {\n return switch (visibility) {\n case PUBLIC -> \"+\";\n case PROTECTED -> \"#\";\n case PRIVATE -> \"-\";\n default -> \"~\";\n };\n }\n\n public static String getStereotypeText(String stereotype) {\n return String.format(\"⪡%s⪢\", stereotype);\n }\n}"
}
] | import br.com.luque.java2uml.core.classdiagram.reflection.model.Method;
import br.com.luque.java2uml.core.classdiagram.writer.MethodWriter;
import br.com.luque.java2uml.yuml.writer.classdiagram.YUMLHelper;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream; | 1,053 | package br.com.luque.java2uml.plantuml.writer.classdiagram;
public class PlantUMLMethodWriter implements MethodWriter {
public String getString(Method method) {
Objects.requireNonNull(method);
| package br.com.luque.java2uml.plantuml.writer.classdiagram;
public class PlantUMLMethodWriter implements MethodWriter {
public String getString(Method method) {
Objects.requireNonNull(method);
| return YUMLHelper | 2 | 2023-11-10 16:49:58+00:00 | 2k |
javpower/JavaVision | src/main/java/com/github/javpower/javavision/util/OcrV4Util.java | [
{
"identifier": "OcrV4Detect",
"path": "src/main/java/com/github/javpower/javavision/detect/OcrV4Detect.java",
"snippet": "public class OcrV4Detect extends AbstractDjlTranslator<NDList> {\n\n private static final Logger logger = LoggerFactory.getLogger(OcrV4Detect.class);\n\n public OcrV4Detect(Map<String, Object> arguments) {\n super(\"ch_PP-OCRv4_det_infer.onnx\",arguments);\n }\n @Override\n protected Translator<Image, NDList> getTranslator(Map<String, Object> arguments) {\n return new OCRDetectionTranslator(new ConcurrentHashMap<String, String>());\n }\n\n @Override\n protected Class<NDList> getClassOfT() {\n return NDList.class;\n }\n @Override\n protected String getEngine(){\n return \"OnnxRuntime\";\n }\n}"
},
{
"identifier": "OcrV4Recognition",
"path": "src/main/java/com/github/javpower/javavision/detect/OcrV4Recognition.java",
"snippet": "public class OcrV4Recognition extends AbstractDjlTranslator<WordBlock> {\n\n private static final Logger logger = LoggerFactory.getLogger(OcrV4Recognition.class);\n\n public OcrV4Recognition(Map<String, Object> arguments) {\n super(\"ch_PP-OCRv4_rec_infer.onnx\", arguments);\n }\n @Override\n protected Translator<Image, WordBlock> getTranslator(Map<String, Object> arguments) {\n return new OCRRecTranslator(new ConcurrentHashMap<String, String>());\n }\n\n @Override\n protected Class<WordBlock> getClassOfT() {\n return WordBlock.class;\n }\n @Override\n protected String getEngine(){\n return \"OnnxRuntime\";\n }\n}"
},
{
"identifier": "WordBlock",
"path": "src/main/java/com/github/javpower/javavision/entity/WordBlock.java",
"snippet": "@Data\npublic class WordBlock {\n private String text;\n private float[] charScores;\n private List<Point> boxPoint;\n}"
}
] | import ai.djl.MalformedModelException;
import ai.djl.inference.Predictor;
import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.ImageFactory;
import ai.djl.modality.cv.output.Point;
import ai.djl.modality.cv.util.NDImageUtils;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.NDManager;
import ai.djl.repository.zoo.Criteria;
import ai.djl.repository.zoo.ModelNotFoundException;
import ai.djl.repository.zoo.ModelZoo;
import ai.djl.repository.zoo.ZooModel;
import ai.djl.translate.TranslateException;
import ai.onnxruntime.OrtException;
import cn.hutool.json.JSONUtil;
import com.github.javpower.javavision.detect.OcrV4Detect;
import com.github.javpower.javavision.detect.OcrV4Recognition;
import com.github.javpower.javavision.entity.WordBlock;
import lombok.extern.slf4j.Slf4j;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | 889 | package com.github.javpower.javavision.util;
@Slf4j
public class OcrV4Util {
public static List<WordBlock> runOcr(String imagePath)
throws TranslateException, IOException, ModelNotFoundException, MalformedModelException, OrtException {
Path imageFile = Paths.get(imagePath);
Image image = ImageFactory.getInstance().fromFile(imageFile);
Map<String,Object> param=new HashMap<>();
OcrV4Detect ocrV4Detect = new OcrV4Detect(param);
Criteria<Image, NDList> criteria = ocrV4Detect.criteria(); | package com.github.javpower.javavision.util;
@Slf4j
public class OcrV4Util {
public static List<WordBlock> runOcr(String imagePath)
throws TranslateException, IOException, ModelNotFoundException, MalformedModelException, OrtException {
Path imageFile = Paths.get(imagePath);
Image image = ImageFactory.getInstance().fromFile(imageFile);
Map<String,Object> param=new HashMap<>();
OcrV4Detect ocrV4Detect = new OcrV4Detect(param);
Criteria<Image, NDList> criteria = ocrV4Detect.criteria(); | OcrV4Recognition ocrV4Recognition = new OcrV4Recognition(param); | 1 | 2023-11-10 01:57:37+00:00 | 2k |
naveenchr/SpringBoot-SeleniumFramework | src/test/java/com/auto/framework/pageobjects/common/BasePage.java | [
{
"identifier": "ActionsBaseClass",
"path": "src/main/java/com/auto/framework/actions/ActionsBaseClass.java",
"snippet": "@Component\npublic class ActionsBaseClass {\n\n\t@Autowired\n\t@Lazy // to start browser only on script execution\n\tpublic WebDriver driver;\n\n\t@Autowired\n\t@Lazy\n\tpublic WebDriverWait webDriverWait;\n\n\t@Autowired\n\tpublic ApplicationContext applicationContext;\n\n\t@Autowired\n\tpublic MyProperties myProperties;\n\t\n\t@Autowired\n\tpublic UtilityClass utilityClass;\n\n}"
},
{
"identifier": "IElementVerification",
"path": "src/main/java/com/auto/framework/interfaces/IElementVerification.java",
"snippet": "public interface IElementVerification {\n\tpublic String getTitle();\n\n\tpublic String getText(By by);\n\n}"
},
{
"identifier": "IExplicitWait",
"path": "src/main/java/com/auto/framework/interfaces/IExplicitWait.java",
"snippet": "public interface IExplicitWait {\n\tpublic WebElement waitForElementToBeClickable(By by);\n}"
},
{
"identifier": "IJavaScriptActions",
"path": "src/main/java/com/auto/framework/interfaces/IJavaScriptActions.java",
"snippet": "public interface IJavaScriptActions {\n\n\tpublic void scrollIntoView(By by);\n\n\tpublic void click(By by);\n\n}"
},
{
"identifier": "IUIElements",
"path": "src/main/java/com/auto/framework/interfaces/IUIElements.java",
"snippet": "public interface IUIElements {\n\n\tWebDriver getWebDriver();\n\n\tvoid sendKeys(By by, String keysToSend);\n\n\tvoid click(By by);\n\n\tvoid openURL(String url);\n\n\tvoid searchAndClickByText(By by, String textForSearch);\n\n\tvoid clickNestedMenus(By by, String tagName, List<String> menuList);\n\n\tvoid searchAndClickTableByText(By by, String textForSearch, String value);\n\n\tString findElementsbyIndex(By by, int index);\n\n\tvoid searchAndClickRelativeLeftElement(By toLeftoOfBy, By withBy, String textForSearch);\n\n\tvoid clickRelativeLeftElement(By toLeftoOfBy, By withBy);\n\n}"
}
] | import static java.util.Objects.nonNull;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.auto.framework.actions.ActionsBaseClass;
import com.auto.framework.interfaces.IElementVerification;
import com.auto.framework.interfaces.IExplicitWait;
import com.auto.framework.interfaces.IJavaScriptActions;
import com.auto.framework.interfaces.IUIElements;
import io.qameta.allure.Attachment;
import lombok.extern.slf4j.Slf4j; | 686 | package com.auto.framework.pageobjects.common;
/************************************************************************************************************************
* @Date : Nov. 14, 2023
* @Author : nachrist
* @Description : Base page for all POM page classes
* @Version : 1.0
************************************************************************************************************************/
@Slf4j
@Component
//@Scope("driverscope")
public class BasePage extends ActionsBaseClass {
@Autowired
public IUIElements iUIElements;
@Autowired
public IElementVerification iElementVerification;
@Autowired
public IExplicitWait iExplicitWait;
@Autowired | package com.auto.framework.pageobjects.common;
/************************************************************************************************************************
* @Date : Nov. 14, 2023
* @Author : nachrist
* @Description : Base page for all POM page classes
* @Version : 1.0
************************************************************************************************************************/
@Slf4j
@Component
//@Scope("driverscope")
public class BasePage extends ActionsBaseClass {
@Autowired
public IUIElements iUIElements;
@Autowired
public IElementVerification iElementVerification;
@Autowired
public IExplicitWait iExplicitWait;
@Autowired | public IJavaScriptActions iJavaScriptActions; | 3 | 2023-11-12 21:51:45+00:00 | 2k |
SpiralMoon/maplestory.openapi | java/src/main/java/dev/spiralmoon/maplestory/api/template/UnionApi.java | [
{
"identifier": "UnionDTO",
"path": "java/src/main/java/dev/spiralmoon/maplestory/api/dto/union/UnionDTO.java",
"snippet": "@AllArgsConstructor\n@Data\n@ToString\npublic class UnionDTO {\n\n /**\n * 조회 기준일 (KST, 일 단위 데이터로 시, 분은 일괄 0으로 표기)\n */\n @SerializedName(\"date\")\n private String date;\n\n /**\n * 유니온 레벨\n */\n @SerializedName(\"union_level\")\n private long unionLevel;\n\n /**\n * 유니온 등급\n */\n @SerializedName(\"union_grade\")\n private String unionGrade;\n\n public LocalDateTime getDate() {\n return Utils.toLocalDateTime(this.date);\n }\n}"
},
{
"identifier": "UnionRaiderDTO",
"path": "java/src/main/java/dev/spiralmoon/maplestory/api/dto/union/UnionRaiderDTO.java",
"snippet": "@AllArgsConstructor\n@Data\n@ToString\npublic class UnionRaiderDTO {\n\n /**\n * 조회 기준일 (KST, 일 단위 데이터로 시, 분은 일괄 0으로 표기)\n */\n @SerializedName(\"date\")\n private String date;\n\n /**\n * 유니온 공격대원 효과\n */\n @SerializedName(\"union_raider_stat\")\n private List<String> unionRaiderStat;\n\n /**\n * 유니온 공격대 점령 효과\n */\n @SerializedName(\"union_occupied_stat\")\n private List<String> unionOccupiedStat;\n\n /**\n * 유니온 공격대 배치\n */\n @SerializedName(\"union_inner_stat\")\n private List<UnionRaiderInnerStatDTO> unionInnerStat;\n\n /**\n * 유니온 블록 정보\n */\n @SerializedName(\"union_block\")\n private List<UnionRaiderBlockDTO> unionBlock;\n\n public LocalDateTime getDate() {\n return Utils.toLocalDateTime(this.date);\n }\n}"
}
] | import dev.spiralmoon.maplestory.api.dto.union.UnionDTO;
import dev.spiralmoon.maplestory.api.dto.union.UnionRaiderDTO;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Query; | 672 | package dev.spiralmoon.maplestory.api.template;
public interface UnionApi {
@GET("maplestory/v1/user/union")
Call<UnionDTO> getUnion(@Header("x-nxopen-api-key") String apiKey, @Query("ocid") String ocid, @Query("date") String date);
@GET("maplestory/v1/user/union-raider") | package dev.spiralmoon.maplestory.api.template;
public interface UnionApi {
@GET("maplestory/v1/user/union")
Call<UnionDTO> getUnion(@Header("x-nxopen-api-key") String apiKey, @Query("ocid") String ocid, @Query("date") String date);
@GET("maplestory/v1/user/union-raider") | Call<UnionRaiderDTO> getUnionRaider(@Header("x-nxopen-api-key") String apiKey, @Query("ocid") String ocid, @Query("date") String date); | 1 | 2023-11-14 17:53:10+00:00 | 2k |
feiniaojin/graceful-response-boot2 | src/main/java/com/feiniaojin/gracefulresponse/defaults/DefaultResponseStatusFactoryImpl.java | [
{
"identifier": "GracefulResponseProperties",
"path": "src/main/java/com/feiniaojin/gracefulresponse/GracefulResponseProperties.java",
"snippet": "@ConfigurationProperties(prefix = \"graceful-response\")\npublic class GracefulResponseProperties {\n\n /**\n * 在全局异常处理器中打印异常,默认不打印\n */\n private boolean printExceptionInGlobalAdvice = false;\n\n /**\n * 默认的Response实现类名称,配置了responseClassFullName,则responseStyle不生效\n */\n private String responseClassFullName;\n\n /**\n * responseStyle的风格,responseClassFullName为空时才会生效\n * responseStyle==null或者responseStyle==0,Response风格为 DefaultResponseImplStyle0\n * responseStyle=1,Response风格为 DefaultResponseImplStyle1\n */\n private Integer responseStyle;\n\n /**\n * 默认的成功返回码\n */\n private String defaultSuccessCode = DefaultConstants.DEFAULT_SUCCESS_CODE;\n\n /**\n * 默认的成功提示\n */\n private String defaultSuccessMsg = DefaultConstants.DEFAULT_SUCCESS_MSG;\n\n /**\n * 默认的失败码\n */\n private String defaultErrorCode = DefaultConstants.DEFAULT_ERROR_CODE;\n\n /**\n * 默认的失败提示\n */\n private String defaultErrorMsg = DefaultConstants.DEFAULT_ERROR_MSG;\n\n /**\n * Validate异常码,不提供的话默认DefaultConstants.DEFAULT_ERROR_CODE\n */\n private String defaultValidateErrorCode;\n\n /**\n * 例外包路径\n */\n private List<String> excludePackages;\n\n /**\n * 不使用@ExceptionMapper和@ExceptionAliasFor修饰的原生异常\n * 是否使用异常信息Throwable类的detailMessage进行返回\n * originExceptionUsingDetailMessage=false,则msg=defaultErrorMsg\n */\n private Boolean originExceptionUsingDetailMessage = false;\n\n public boolean isPrintExceptionInGlobalAdvice() {\n return printExceptionInGlobalAdvice;\n }\n\n public void setPrintExceptionInGlobalAdvice(boolean printExceptionInGlobalAdvice) {\n this.printExceptionInGlobalAdvice = printExceptionInGlobalAdvice;\n }\n\n public String getDefaultSuccessCode() {\n return defaultSuccessCode;\n }\n\n public void setDefaultSuccessCode(String defaultSuccessCode) {\n this.defaultSuccessCode = defaultSuccessCode;\n }\n\n public String getDefaultSuccessMsg() {\n return defaultSuccessMsg;\n }\n\n public void setDefaultSuccessMsg(String defaultSuccessMsg) {\n this.defaultSuccessMsg = defaultSuccessMsg;\n }\n\n public String getDefaultErrorCode() {\n return defaultErrorCode;\n }\n\n public void setDefaultErrorCode(String defaultErrorCode) {\n this.defaultErrorCode = defaultErrorCode;\n }\n\n public String getDefaultErrorMsg() {\n return defaultErrorMsg;\n }\n\n public void setDefaultErrorMsg(String defaultErrorMsg) {\n this.defaultErrorMsg = defaultErrorMsg;\n }\n\n public String getResponseClassFullName() {\n return responseClassFullName;\n }\n\n public void setResponseClassFullName(String responseClassFullName) {\n this.responseClassFullName = responseClassFullName;\n }\n\n public Integer getResponseStyle() {\n return responseStyle;\n }\n\n public void setResponseStyle(Integer responseStyle) {\n this.responseStyle = responseStyle;\n }\n\n public String getDefaultValidateErrorCode() {\n return defaultValidateErrorCode;\n }\n\n public void setDefaultValidateErrorCode(String defaultValidateErrorCode) {\n this.defaultValidateErrorCode = defaultValidateErrorCode;\n }\n\n public List<String> getExcludePackages() {\n return excludePackages;\n }\n\n public void setExcludePackages(List<String> excludePackages) {\n this.excludePackages = excludePackages;\n }\n\n public Boolean getOriginExceptionUsingDetailMessage() {\n return originExceptionUsingDetailMessage;\n }\n\n public void setOriginExceptionUsingDetailMessage(Boolean originExceptionUsingDetailMessage) {\n this.originExceptionUsingDetailMessage = originExceptionUsingDetailMessage;\n }\n}"
},
{
"identifier": "ResponseStatusFactory",
"path": "src/main/java/com/feiniaojin/gracefulresponse/api/ResponseStatusFactory.java",
"snippet": "public interface ResponseStatusFactory {\n /**\n * 获得响应成功的ResponseMeta.\n *\n * @return\n */\n ResponseStatus defaultSuccess();\n\n /**\n * 获得失败的ResponseMeta.\n *\n * @return\n */\n ResponseStatus defaultError();\n\n\n /**\n * 从code和msg创建ResponseStatus\n * @param code\n * @param msg\n * @return\n */\n ResponseStatus newInstance(String code,String msg);\n\n}"
},
{
"identifier": "ResponseStatus",
"path": "src/main/java/com/feiniaojin/gracefulresponse/data/ResponseStatus.java",
"snippet": "public interface ResponseStatus {\n /**\n * 设置响应码.\n *\n * @param code 设置的响应码.\n */\n void setCode(String code);\n\n /**\n * 获得响应码.\n *\n * @return\n */\n String getCode();\n\n /**\n * 设置响应提示信息.\n *\n * @param msg 设置响应提示信息.\n */\n void setMsg(String msg);\n\n /**\n * 获得响应信息.\n *\n * @return\n */\n String getMsg();\n}"
}
] | import com.feiniaojin.gracefulresponse.GracefulResponseProperties;
import com.feiniaojin.gracefulresponse.api.ResponseStatusFactory;
import com.feiniaojin.gracefulresponse.data.ResponseStatus;
import javax.annotation.Resource; | 1,451 | package com.feiniaojin.gracefulresponse.defaults;
/**
* 提供的默认的ResponseMetaFactory实现.
*
* @author <a href="mailto:[email protected]">Yujie</a>
* @version 0.1
*/
public class DefaultResponseStatusFactoryImpl implements ResponseStatusFactory {
@Resource | package com.feiniaojin.gracefulresponse.defaults;
/**
* 提供的默认的ResponseMetaFactory实现.
*
* @author <a href="mailto:[email protected]">Yujie</a>
* @version 0.1
*/
public class DefaultResponseStatusFactoryImpl implements ResponseStatusFactory {
@Resource | private GracefulResponseProperties properties; | 0 | 2023-11-15 10:54:19+00:00 | 2k |
BlyznytsiaOrg/bring | web/src/main/java/io/github/blyznytsiaorg/bring/web/actuator/service/impl/DefaultActuatorService.java | [
{
"identifier": "Commit",
"path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/actuator/dto/Commit.java",
"snippet": "@Setter\n@Getter\n@ToString\n@Builder\npublic class Commit {\n // Commit ID\n private String id;\n\n // Commit message\n private String message;\n\n // Commit timestamp\n private String time;\n}"
},
{
"identifier": "GitInfo",
"path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/actuator/dto/GitInfo.java",
"snippet": "@Setter\n@Getter\n@ToString\n@Builder\npublic class GitInfo {\n // Git branch information\n private String branch;\n\n // Details about the latest commit\n private Commit commit;\n}"
},
{
"identifier": "PropertiesData",
"path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/actuator/dto/PropertiesData.java",
"snippet": "@Setter\n@Getter\n@ToString\n@Builder\npublic class PropertiesData {\n /**\n * A map representing system properties, where keys are property names and values are property values.\n */\n private Map<String, String> properties;\n}"
},
{
"identifier": "ActuatorService",
"path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/actuator/service/ActuatorService.java",
"snippet": "public interface ActuatorService {\n\n /**\n * Prepares Git information including branch details and the latest commit information.\n *\n * @return Git information.\n */\n GitInfo getGitInfo();\n\n /**\n * Prepares system properties data.\n *\n * @return System properties data.\n */\n PropertiesData preparePropertyData();\n\n}"
},
{
"identifier": "ServerProperties",
"path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/server/properties/ServerProperties.java",
"snippet": "@Data\n@Component\npublic class ServerProperties {\n\n /**\n * The port on which the web server will listen for incoming requests.\n */\n @Value(\"server.port:9000\")\n private int port;\n\n /**\n * The context path for the web server. It represents the base path for all\n * requests handled by the server.\n */\n @Value(\"server.contextPath:\")\n private String contextPath;\n\n /**\n * Indicates whether stack traces should be included in error responses.\n * {@code true} if stack traces should be included, {@code false} otherwise\n */\n @Value(\"server.withStackTrace:false\")\n private boolean withStackTrace;\n\n /**\n * Configuration property for controlling whether commit messages are included in GitInfo responses.\n * It is used by the DefaultActuatorService to determine whether to fetch and display commit messages.\n *\n * <p>The default value is {@code false}, meaning commit messages will not be included.\n */\n @Value(\"server.actuator.git.commit.withMessage:false\")\n private boolean withMessage;\n\n}"
}
] | import io.github.blyznytsiaorg.bring.core.annotation.PostConstruct;
import io.github.blyznytsiaorg.bring.core.annotation.Service;
import io.github.blyznytsiaorg.bring.web.actuator.dto.Commit;
import io.github.blyznytsiaorg.bring.web.actuator.dto.GitInfo;
import io.github.blyznytsiaorg.bring.web.actuator.dto.PropertiesData;
import io.github.blyznytsiaorg.bring.web.actuator.service.ActuatorService;
import io.github.blyznytsiaorg.bring.web.server.properties.ServerProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.io.InputStream;
import java.util.Map;
import java.util.Objects;
import java.util.Properties; | 1,082 | package io.github.blyznytsiaorg.bring.web.actuator.service.impl;
/**
* Default implementation of the {@link ActuatorService} interface.
* Provides methods for preparing Git information and system properties data for the Actuator endpoint.
* <p>
* This class uses the {@code @Service} annotation to indicate that it is a Bring component and should be
* automatically detected and registered during component scanning.
* <p>
* The Git information is loaded from the "git.properties" file, and the system properties data is obtained
* using {@code System.getProperties()}.
* <p>
* The {@code @PostConstruct} method {@code prepareGitInfo()} is annotated to be executed after the
* bean is constructed. It loads the Git information during the initialization phase.
* <p>
* The class uses constants for error messages, Git file name, and keys of properties of Git.
*
* @author Blyzhnytsia Team
* @since 1.0
*/
@Slf4j
@Service
@RequiredArgsConstructor | package io.github.blyznytsiaorg.bring.web.actuator.service.impl;
/**
* Default implementation of the {@link ActuatorService} interface.
* Provides methods for preparing Git information and system properties data for the Actuator endpoint.
* <p>
* This class uses the {@code @Service} annotation to indicate that it is a Bring component and should be
* automatically detected and registered during component scanning.
* <p>
* The Git information is loaded from the "git.properties" file, and the system properties data is obtained
* using {@code System.getProperties()}.
* <p>
* The {@code @PostConstruct} method {@code prepareGitInfo()} is annotated to be executed after the
* bean is constructed. It loads the Git information during the initialization phase.
* <p>
* The class uses constants for error messages, Git file name, and keys of properties of Git.
*
* @author Blyzhnytsia Team
* @since 1.0
*/
@Slf4j
@Service
@RequiredArgsConstructor | public class DefaultActuatorService implements ActuatorService { | 3 | 2023-11-10 13:42:05+00:00 | 2k |
RIA-AED/RIABandwidthSaver | src/main/java/com/ghostchu/plugins/riabandwidthsaver/RIABandwidthSaver.java | [
{
"identifier": "CMIHook",
"path": "src/main/java/com/ghostchu/plugins/riabandwidthsaver/hooks/cmi/CMIHook.java",
"snippet": "public class CMIHook extends AFKHook implements Listener {\n\n public CMIHook(RIABandwidthSaver plugin) {\n super(plugin);\n }\n\n @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)\n public void onPlayerAfk(CMIAfkEnterEvent event) {\n getPlugin().playerEcoEnable(event.getPlayer());\n }\n\n @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)\n public void onPlayerLeaveAfk(CMIAfkLeaveEvent event) {\n getPlugin().playerEcoDisable(event.getPlayer());\n }\n}"
},
{
"identifier": "ESSXHook",
"path": "src/main/java/com/ghostchu/plugins/riabandwidthsaver/hooks/essx/ESSXHook.java",
"snippet": "public class ESSXHook extends AFKHook {\n public ESSXHook(RIABandwidthSaver plugin) {\n super(plugin);\n }\n\n @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)\n public void onPlayerAfk(AfkStatusChangeEvent event) {\n if (event.getValue()) {\n getPlugin().playerEcoEnable(event.getAffected().getBase());\n } else {\n getPlugin().playerEcoDisable(event.getAffected().getBase());\n }\n }\n\n}"
}
] | import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.*;
import com.comphenix.protocol.injector.temporary.TemporaryPlayer;
import com.ghostchu.plugins.riabandwidthsaver.hooks.cmi.CMIHook;
import com.ghostchu.plugins.riabandwidthsaver.hooks.essx.ESSXHook;
import io.netty.buffer.ByteBuf;
import io.netty.util.ReferenceCountUtil;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.Stream; | 788 | package com.ghostchu.plugins.riabandwidthsaver;
public final class RIABandwidthSaver extends JavaPlugin implements Listener {
private final Set<UUID> AFK_PLAYERS = new HashSet<>();
private final Map<PacketType, PacketInfo> PKT_TYPE_STATS = new ConcurrentHashMap<>();
private final Map<UUID, PacketInfo> PLAYER_PKT_SAVED_STATS = new ConcurrentHashMap<>();
private final Map<PacketType, PacketInfo> UNFILTERED_PKT_TYPE_STATS = new ConcurrentHashMap<>();
private final Map<UUID, PacketInfo> UNFILTERED_PLAYER_PKT_SAVED_STATS = new ConcurrentHashMap<>();
private final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();
private boolean calcAllPackets = false;
private final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();
private final List<AFKHook> afkHooks = new ArrayList<>();
@Override
public void onEnable() {
// Plugin startup logic
saveDefaultConfig();
Bukkit.getPluginManager().registerEvents(this, this);
reloadConfig();
scanHooks();
}
private void scanHooks() {
if(Bukkit.getPluginManager().getPlugin("CMI") != null){ | package com.ghostchu.plugins.riabandwidthsaver;
public final class RIABandwidthSaver extends JavaPlugin implements Listener {
private final Set<UUID> AFK_PLAYERS = new HashSet<>();
private final Map<PacketType, PacketInfo> PKT_TYPE_STATS = new ConcurrentHashMap<>();
private final Map<UUID, PacketInfo> PLAYER_PKT_SAVED_STATS = new ConcurrentHashMap<>();
private final Map<PacketType, PacketInfo> UNFILTERED_PKT_TYPE_STATS = new ConcurrentHashMap<>();
private final Map<UUID, PacketInfo> UNFILTERED_PLAYER_PKT_SAVED_STATS = new ConcurrentHashMap<>();
private final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();
private boolean calcAllPackets = false;
private final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();
private final List<AFKHook> afkHooks = new ArrayList<>();
@Override
public void onEnable() {
// Plugin startup logic
saveDefaultConfig();
Bukkit.getPluginManager().registerEvents(this, this);
reloadConfig();
scanHooks();
}
private void scanHooks() {
if(Bukkit.getPluginManager().getPlugin("CMI") != null){ | afkHooks.add(new CMIHook(this)); | 0 | 2023-11-18 11:52:47+00:00 | 2k |
johndeweyzxc/AWPS-Command | app/src/main/java/com/johndeweydev/awps/viewmodel/serial/terminalviewmodel/TerminalViewModel.java | [
{
"identifier": "LauncherOutputData",
"path": "app/src/main/java/com/johndeweydev/awps/model/data/LauncherOutputData.java",
"snippet": "public class LauncherOutputData {\n\n private String time;\n private final String output;\n\n\n public LauncherOutputData(String time, String output) {\n this.time = time;\n this.output = output;\n }\n\n public String getTime() {\n return time;\n }\n\n public String getOutput() {\n return output;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n}"
},
{
"identifier": "TerminalRepoSerial",
"path": "app/src/main/java/com/johndeweydev/awps/model/repo/serial/terminalreposerial/TerminalRepoSerial.java",
"snippet": "public class TerminalRepoSerial extends RepositoryIOControl implements Launcher.UsbSerialIOEvent {\n\n public interface RepositoryEvent extends RepositoryIOEvent {}\n private TerminalRepoSerial.RepositoryEvent repositoryEvent;\n private final StringBuilder queueData = new StringBuilder();\n @Override\n public void onUsbSerialOutput(String data) {\n char[] dataChar = data.toCharArray();\n for (char c : dataChar) {\n if (c == '\\n') {\n\n String strData = queueData.toString();\n String strTime = createStringTime();\n\n LauncherOutputData launcherOutputData = new LauncherOutputData(strTime, strData);\n\n char firstChar = strData.charAt(0);\n char lastChar = strData.charAt(strData.length() - 2);\n if (firstChar == '{' && lastChar == '}') {\n repositoryEvent.onRepoOutputFormatted(launcherOutputData);\n } else {\n repositoryEvent.onRepoOutputRaw(launcherOutputData);\n }\n\n queueData.setLength(0);\n } else {\n queueData.append(c);\n }\n }\n }\n\n @Override\n public void onUsbSerialOutputError(String error) {\n repositoryEvent.onRepoOutputError(error);\n }\n @Override\n public void onUsbSerialInputError(String input) {\n repositoryEvent.onRepoInputError(input);\n }\n public void setEventHandler(\n TerminalRepoSerial.RepositoryEvent repositoryEvent\n ) {\n this.repositoryEvent = repositoryEvent;\n Log.d(\"dev-log\", \"TerminalRepository.setEventHandler: Terminal repository event \" +\n \"callback set\");\n }\n\n public void setLauncherEventHandler() {\n LauncherSingleton.getInstance().getLauncher().setLauncherEventHandler(\n this);\n Log.d(\"dev-log\", \"TerminalRepository.setLauncherEventHandler: Launcher event callback \" +\n \"set in the context of terminal repository\");\n }\n\n private String createStringTime() {\n Calendar calendar = Calendar.getInstance();\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"HH:mm:ss\", Locale.getDefault());\n return dateFormat.format(calendar.getTime());\n }\n\n public ArrayList<UsbDeviceData> getAvailableDevices() {\n return LauncherSingleton.getInstance().getLauncher().getAvailableDevices();\n }\n}"
},
{
"identifier": "ViewModelIOControl",
"path": "app/src/main/java/com/johndeweydev/awps/viewmodel/serial/ViewModelIOControl.java",
"snippet": "public interface ViewModelIOControl {\n\n /**\n * Sets the repository serial event callback in the launcher\n * */\n void setLauncherEventHandler();\n\n /**\n * Connects to the usb serial device\n * @param deviceConnectionParamData the necessary parameters such as baud rate, stop bits and\n * etc to connect to the device\n * */\n String connectToDevice(DeviceConnectionParamData deviceConnectionParamData);\n\n /**\n * Disconnects from the usb serial device\n * */\n void disconnectFromDevice();\n\n /**\n * Starts the thread for reading serial output in the usb device\n * */\n void startEventDrivenReadFromDevice();\n\n /**\n * Stops the thread for reading serial output in the usb device\n * */\n void stopEventDrivenReadFromDevice();\n}"
}
] | import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.johndeweydev.awps.model.data.DeviceConnectionParamData;
import com.johndeweydev.awps.model.data.LauncherOutputData;
import com.johndeweydev.awps.model.data.UsbDeviceData;
import com.johndeweydev.awps.model.repo.serial.terminalreposerial.TerminalRepoSerial;
import com.johndeweydev.awps.viewmodel.serial.ViewModelIOControl;
import java.util.ArrayList; | 1,197 | package com.johndeweydev.awps.viewmodel.serial.terminalviewmodel;
public class TerminalViewModel extends ViewModel implements ViewModelIOControl,
TerminalRepoSerial.RepositoryEvent {
/**
* Device id, port number and baud rate is set by terminal fragment as a backup source
* in case getArgument is empty when terminal fragment goes to onCreateView state
* */
public int deviceIdFromTerminalArgs;
public int portNumFromTerminalArgs;
public int baudRateFromTerminalArgs;
public TerminalRepoSerial terminalRepoSerial;
public MutableLiveData<ArrayList<UsbDeviceData>> devicesList = new MutableLiveData<>(); | package com.johndeweydev.awps.viewmodel.serial.terminalviewmodel;
public class TerminalViewModel extends ViewModel implements ViewModelIOControl,
TerminalRepoSerial.RepositoryEvent {
/**
* Device id, port number and baud rate is set by terminal fragment as a backup source
* in case getArgument is empty when terminal fragment goes to onCreateView state
* */
public int deviceIdFromTerminalArgs;
public int portNumFromTerminalArgs;
public int baudRateFromTerminalArgs;
public TerminalRepoSerial terminalRepoSerial;
public MutableLiveData<ArrayList<UsbDeviceData>> devicesList = new MutableLiveData<>(); | public MutableLiveData<LauncherOutputData> currentSerialOutput = new MutableLiveData<>(); | 0 | 2023-11-15 15:54:39+00:00 | 2k |
Samuel-Ricardo/Pic-Pay_simplified | src/main/java/com/picpay/payment/application/service/UserServiceImpl.java | [
{
"identifier": "FindAllUsersUseCase",
"path": "src/main/java/com/picpay/payment/application/usecase/user/FindAllUsersUseCase.java",
"snippet": "@Component\npublic class FindAllUsersUseCase {\n\n @Autowired\n private UserRepository repository;\n\n public List<User> execute() {\n return this.repository.findAll();\n }\n}"
},
{
"identifier": "FindUserByEmailUseCase",
"path": "src/main/java/com/picpay/payment/application/usecase/user/FindUserByEmailUseCase.java",
"snippet": "@Component\npublic class FindUserByEmailUseCase {\n\n @Autowired private UserRepository repository;\n\n public Optional<User> execute(String email) {\n return repository.findByEmail(email);\n }\n}"
},
{
"identifier": "FindUserByIdUseCase",
"path": "src/main/java/com/picpay/payment/application/usecase/user/FindUserByIdUseCase.java",
"snippet": "@Component\npublic class FindUserByIdUseCase {\n\n @Autowired\n private UserRepository repository;\n\n public User execute(UUID id) throws Exception {\n return this\n .repository\n .findUserById(id)\n .orElseThrow(() -> new Exception(\"Usuário não encontrado\"));\n }\n}"
},
{
"identifier": "SaveUserUseCase",
"path": "src/main/java/com/picpay/payment/application/usecase/user/SaveUserUseCase.java",
"snippet": "@Component\npublic class SaveUserUseCase {\n\n @Autowired\n private UserRepository repository;\n\n public User execute(User user){\n return this.repository.save(user);\n }\n}"
},
{
"identifier": "User",
"path": "src/main/java/com/picpay/payment/domain/entities/user/User.java",
"snippet": "@Entity(name = \"tb_users\") @Table(name = \"tb_users\")\n@AllArgsConstructor @NoArgsConstructor\n@EqualsAndHashCode(of = \"id\")\n@Getter @Setter\npublic class User implements UserDetails {\n\n @Id\n @GeneratedValue(strategy = GenerationType.UUID)\n private UUID id;\n\n private String firstName;\n private String lastName;\n\n @Column(unique = true)\n private String email;\n private String password;\n\n @Column(unique = true)\n private String document;\n private BigDecimal balance;\n @Enumerated(EnumType.STRING)\n private UserType userType;\n\n @Enumerated\n private Role role;\n\n\n public static User from(UserDTO dto) {\n var user = new User();\n BeanUtils.copyProperties(dto, user);\n\n return user;\n }\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return role.getAuthorities();\n }\n\n @Override\n public String getUsername() {\n return email;\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n @Override\n public boolean isEnabled() {\n return true;\n }\n}"
},
{
"identifier": "UserService",
"path": "src/main/java/com/picpay/payment/domain/services/UserService.java",
"snippet": "@Service\npublic interface UserService {\n\n public User findUserById(UUID id) throws Exception;\n\n public User saveUser(UserDTO data);\n\n public User saveUser(User data);\n\n public List<User> findAllUsers();\n\n public Optional<User> findUserByEmail(String email);\n\n}"
}
] | import com.picpay.payment.application.usecase.user.FindAllUsersUseCase;
import com.picpay.payment.application.usecase.user.FindUserByEmailUseCase;
import com.picpay.payment.application.usecase.user.FindUserByIdUseCase;
import com.picpay.payment.application.usecase.user.SaveUserUseCase;
import com.picpay.payment.domain.dto.user.UserDTO;
import com.picpay.payment.domain.entities.user.User;
import com.picpay.payment.domain.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.UUID; | 954 | package com.picpay.payment.application.service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private FindUserByIdUseCase findById;
@Autowired
private FindUserByEmailUseCase findByEmail;
@Autowired | package com.picpay.payment.application.service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private FindUserByIdUseCase findById;
@Autowired
private FindUserByEmailUseCase findByEmail;
@Autowired | private FindAllUsersUseCase findAll; | 0 | 2023-11-18 18:00:28+00:00 | 2k |
sondosaabed/Taskaty | app/src/main/java/com/taskaty/informational/GettingStarted.java | [
{
"identifier": "Preferences",
"path": "app/src/main/java/com/taskaty/model/Preferences.java",
"snippet": "public class Preferences {\n /*\n Attriutes\n */\n // I initialize Sample Tasks in the tasks list\n static Task t1 = new Task(0,\"Smile to a Stranger\",\"Today I will smile and make someone happy\",\"\",null, false);\n static Task t2 = new Task(1,\"Submit Assignment 1\",\"Your mobile course work\",\"Study\", LocalDate.parse(\"2023-11-18\"), true);\n private static final String DATA = \"DATA\";\n private static final String FIRST_TIME = \"is_first_time\";\n private static SharedPreferences preferences;\n private static SharedPreferences.Editor editor;\n\n /*\n I created these two methods in order to show diffrent activities when the user starts or gets back\n */\n public static boolean isFirstTime(Context context) {\n preferences = getPreferences(context);\n return preferences.getBoolean(FIRST_TIME, true);\n }\n\n public static void setNotFirstTime(Context context) {\n preferences = getPreferences(context);\n editor = preferences.edit();\n editor.putBoolean(FIRST_TIME, false);\n editor.apply();\n }\n\n public static ArrayList<Task> initializeTaskatySample(){\n return new ArrayList<>(Arrays.asList(t1, t2));\n }\n\n public static ArrayList<Task> loadTasks(Context context) {\n preferences = getPreferences(context);\n Gson gson = new Gson();\n String str = preferences.getString(DATA, \"\");\n Task[] tasks = gson.fromJson(str, Task[].class);\n if(tasks != null){\n return new ArrayList<>(Arrays.asList(tasks));\n }\n return initializeTaskatySample();\n }\n\n /*\n I created this method to save the tasks list which I called after each modification on the list\n */\n public static void saveTaskaty(ArrayList<Task> tasks) {\n Gson gson = new Gson();\n String str = gson.toJson(tasks);\n editor.putString(DATA, str);\n editor.apply();\n }\n\n public static SharedPreferences getPreferences(Context context) {\n if (preferences == null) {\n preferences = PreferenceManager.getDefaultSharedPreferences(context);\n editor = preferences.edit();\n }\n return preferences;\n }\n}"
},
{
"identifier": "TasksList",
"path": "app/src/main/java/com/taskaty/taskManagment/TasksList.java",
"snippet": "public class TasksList extends AppCompatActivity{\n /*\n Attributes\n */\n ImageButton add;\n Button search;\n ListView tasksVeiw;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n initialize();\n }\n\n private void initialize() {\n if(getSupportActionBar()!=null)\n getSupportActionBar().hide();\n setContentView(R.layout.tasks_list);\n\n setAdd(findViewById(R.id.add));\n setTasks(findViewById(R.id.taskListView));\n setSearch(findViewById(R.id.search));\n\n Tasks.initTasks(this);\n\n ArrayAdapter<Task> listAdapter = new ArrayAdapter<>(this,\n android.R.layout.simple_list_item_1,\n Tasks.getTaskaty());\n getTasks().setAdapter(listAdapter);\n\n handle_add(getAdd());\n handle_taskClick(getTasks());\n handle_search(getSearch());\n }\n\n private void handle_search(Button search) {\n /*\n When a user searches for a task by it's name\n - if it's not found the status inform of not found will be shown\n */\n search.setOnClickListener(veiw->{\n Intent intent = new Intent(this, FindTasks.class);\n startActivity(intent);\n });\n }\n\n private void handle_taskClick(ListView tasks) {\n /*\n When a user clicks on a list item they are allowed to edit it\n */\n tasks.setOnItemClickListener((parent, view, position, id) -> {\n Intent intent = new Intent(this, EditTask.class);\n intent.putExtra(\"selectedTaskID\", position);\n startActivity(intent);\n });\n }\n\n private void handle_add(ImageButton add) {\n /*\n When the user clicks Add, the user is able to fill a form and add a new one\n */\n add.setOnClickListener(veiw->{\n Intent intent = new Intent(this, AddNewTask.class);\n startActivity(intent);\n });\n }\n\n /*\n Getters & Setters\n */\n public void setAdd(ImageButton add) {\n this.add = add;\n }\n public ImageButton getAdd() {\n return add;\n }\n public void setTasks(ListView tasks) {\n this.tasksVeiw = tasks;\n }\n public ListView getTasks() {\n return tasksVeiw;\n }\n public Button getSearch() {\n return search;\n }\n public void setSearch(Button search) {\n this.search = search;\n }\n}"
}
] | import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import com.taskaty.model.Preferences;
import com.taskaty.taskManagment.TasksList;
import com.taskaty.R; | 1,277 | package com.taskaty.informational;
/*
This is the starting activity of the mobile app, the user is able to
start
*/
public class GettingStarted extends AppCompatActivity {
/*
Attributes
*/
Button start;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
Check if it's the first time for the user using taskaty
if so show them getting started otherwise show them welcome back
for more personalized experience
*/ | package com.taskaty.informational;
/*
This is the starting activity of the mobile app, the user is able to
start
*/
public class GettingStarted extends AppCompatActivity {
/*
Attributes
*/
Button start;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
Check if it's the first time for the user using taskaty
if so show them getting started otherwise show them welcome back
for more personalized experience
*/ | if (Preferences.isFirstTime(this)) { | 0 | 2023-11-10 13:10:12+00:00 | 2k |
Charles7c/continew-starter | continew-starter-auth/continew-starter-auth-satoken/src/main/java/top/charles7c/continew/starter/auth/satoken/autoconfigure/SaTokenAutoConfiguration.java | [
{
"identifier": "StringConstants",
"path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/constant/StringConstants.java",
"snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class StringConstants implements StrPool {\n\n /**\n * 空字符串\n */\n public static final String EMPTY = \"\";\n\n /**\n * 空格\n */\n public static final String SPACE = \" \";\n\n /**\n * 分号\n */\n public static final String SEMICOLON = \";\";\n\n /**\n * 星号\n */\n public static final String ASTERISK = \"*\";\n\n /**\n * 问号\n */\n public static final String QUESTION_MARK = \"?\";\n\n /**\n * 中文逗号\n */\n public static final String CHINESE_COMMA = \",\";\n\n /**\n * 路径模式\n */\n public static final String PATH_PATTERN = \"/**\";\n}"
},
{
"identifier": "GeneralPropertySourceFactory",
"path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/handler/GeneralPropertySourceFactory.java",
"snippet": "public class GeneralPropertySourceFactory extends DefaultPropertySourceFactory {\n\n @Override\n public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource encodedResource) throws IOException {\n Resource resource = encodedResource.getResource();\n String resourceName = resource.getFilename();\n if (StrUtil.isNotBlank(resourceName) && StrUtil.endWithAny(resourceName, \".yml\", \".yaml\")) {\n return new YamlPropertySourceLoader().load(resourceName, resource).get(0);\n }\n return super.createPropertySource(name, encodedResource);\n }\n}"
}
] | import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ReflectUtil;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import top.charles7c.continew.starter.core.constant.StringConstants;
import top.charles7c.continew.starter.core.handler.GeneralPropertySourceFactory; | 894 | /*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.continew.starter.auth.satoken.autoconfigure;
/**
* Sa-Token 自动配置
*
* @author Charles7c
* @since 1.0.0
*/
@Slf4j
@AutoConfiguration
@RequiredArgsConstructor
@EnableConfigurationProperties(SaTokenExtensionProperties.class)
@ConditionalOnProperty(prefix = "sa-token.extension", name = "enabled", havingValue = "true") | /*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package top.charles7c.continew.starter.auth.satoken.autoconfigure;
/**
* Sa-Token 自动配置
*
* @author Charles7c
* @since 1.0.0
*/
@Slf4j
@AutoConfiguration
@RequiredArgsConstructor
@EnableConfigurationProperties(SaTokenExtensionProperties.class)
@ConditionalOnProperty(prefix = "sa-token.extension", name = "enabled", havingValue = "true") | @PropertySource(value = "classpath:default-auth-satoken.yml", factory = GeneralPropertySourceFactory.class) | 1 | 2023-11-16 15:48:18+00:00 | 2k |
rafaelsantos01/icaro | src/main/java/com/mail/icaro/modules/email/service/sendNewEmailSync/SendNewEmailSyncService.java | [
{
"identifier": "SendNewEmailSyncRequestDTO",
"path": "src/main/java/com/mail/icaro/modules/email/service/sendNewEmailSync/dto/SendNewEmailSyncRequestDTO.java",
"snippet": "@Getter\n@Setter\npublic class SendNewEmailSyncRequestDTO {\n\n @NotNull\n @NotBlank\n @NotEmpty\n @Email\n private String userMail;\n\n @NotNull\n @NotBlank\n @NotEmpty\n private String title;\n\n @NotNull\n @NotBlank\n @NotEmpty\n private String content;\n}"
},
{
"identifier": "SendNewEmailSyncResponseDTO",
"path": "src/main/java/com/mail/icaro/modules/email/service/sendNewEmailSync/dto/SendNewEmailSyncResponseDTO.java",
"snippet": "@Getter\n@Setter\npublic class SendNewEmailSyncResponseDTO {\n\n private String userMail;\n\n private String title;\n\n private String content;\n\n private UUID id;\n\n private boolean sync;\n\n}"
},
{
"identifier": "ShippingHistory",
"path": "src/main/java/com/mail/icaro/modules/history/entity/ShippingHistory.java",
"snippet": "@Getter\n@Setter\n\n@Entity\n@Table(name = \"shipping_history\")\npublic class ShippingHistory extends DateBase {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Column(name = \"id\", columnDefinition = \"uuid\")\n private UUID id;\n\n @Column(name = \"content\")\n private String content;\n\n @Column(name = \"title\")\n private String title;\n\n @Column(name = \"user_mail\")\n private String userMail;\n\n @Column(name = \"sync\")\n private Boolean sync;\n\n @Column(name = \"fail_send\")\n private Boolean failSend;\n\n}"
},
{
"identifier": "ShippingHistoryRepository",
"path": "src/main/java/com/mail/icaro/modules/history/repository/ShippingHistoryRepository.java",
"snippet": "@Repository\npublic interface ShippingHistoryRepository extends JpaRepository<ShippingHistory, UUID> {\n List<ShippingHistory> findBySyncFalseAndFailSendNull();\n List<ShippingHistory> findBySyncFalse();\n}"
},
{
"identifier": "SendNewEmailDTO",
"path": "src/main/java/com/mail/icaro/modules/email/service/sendNewEmail/dto/SendNewEmailDTO.java",
"snippet": "@Getter\n@Setter\npublic class SendNewEmailDTO {\n\n @NotNull\n @NotBlank\n @NotEmpty\n @Email\n private String userMail;\n\n @NotNull\n @NotBlank\n @NotEmpty\n private String title;\n\n @NotNull\n @NotBlank\n @NotEmpty\n private String content;\n}"
},
{
"identifier": "SendEmailServiceSimpleDTO",
"path": "src/main/java/com/mail/icaro/shared/sendEmail/dtos/SendEmailServiceSimpleDTO.java",
"snippet": "@Getter\n@Setter\npublic class SendEmailServiceSimpleDTO {\n\n @NotNull @NotBlank @NotEmpty\n private String userMail;\n\n @NotNull @NotBlank @NotEmpty\n private String title;\n\n @NotNull @NotBlank @NotEmpty\n private String content;\n\n}"
},
{
"identifier": "SendMailServiceSimple",
"path": "src/main/java/com/mail/icaro/shared/sendEmail/service/SendMailServiceSimple.java",
"snippet": "@Log4j2\n\n@Service\npublic class SendMailServiceSimple {\n\n @Autowired\n private JavaMailSender javaMailSender;\n\n public boolean execute(SendEmailServiceSimpleDTO data){\n try{\n MimeMessage message = javaMailSender.createMimeMessage();\n MimeMessageHelper helper = new MimeMessageHelper(message, true);\n\n helper.setTo(data.getUserMail());\n helper.setSubject(data.getTitle());\n helper.setText(data.getContent(), true);\n\n javaMailSender.send(message);\n\n log.info(\"Email enviado com sucesso\");\n return true;\n }catch (Exception e){\n log.error(\"Error when sending simple email\",e);\n return false;\n }\n }\n}"
}
] | import com.mail.icaro.modules.email.service.sendNewEmailSync.dto.SendNewEmailSyncRequestDTO;
import com.mail.icaro.modules.email.service.sendNewEmailSync.dto.SendNewEmailSyncResponseDTO;
import com.mail.icaro.modules.history.entity.ShippingHistory;
import com.mail.icaro.modules.history.repository.ShippingHistoryRepository;
import com.mail.icaro.modules.email.service.sendNewEmail.dto.SendNewEmailDTO;
import com.mail.icaro.shared.sendEmail.dtos.SendEmailServiceSimpleDTO;
import com.mail.icaro.shared.sendEmail.service.SendMailServiceSimple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; | 1,058 | package com.mail.icaro.modules.email.service.sendNewEmailSync;
@Service
public class SendNewEmailSyncService {
@Autowired
ShippingHistoryRepository shippingHistoryRepository;
@Autowired | package com.mail.icaro.modules.email.service.sendNewEmailSync;
@Service
public class SendNewEmailSyncService {
@Autowired
ShippingHistoryRepository shippingHistoryRepository;
@Autowired | SendMailServiceSimple sendMailServiceSimple; | 6 | 2023-11-12 21:58:03+00:00 | 2k |
luca-software-developer/CalcolatriceScientificaGruppo04 | CalcolatriceScientificaGruppo04/src/main/java/it/unisa/diem/ids2023/rpnpsc/RPNStack.java | [
{
"identifier": "RPNException",
"path": "CalcolatriceScientificaGruppo04/src/main/java/it/unisa/diem/ids2023/rpnpsc/exceptions/RPNException.java",
"snippet": "public class RPNException extends Exception {\n\n /**\n * Intestazione del messaggio di errore o di warning.\n */\n private final String headerText;\n\n /**\n * Testo del messaggio di errore o di warning.\n */\n private final String contentText;\n\n /**\n * Costruttore della classe {@code RPNException}.\n *\n * @param headerText Intestazione del messaggio di errore o di warning.\n * @param contentText Testo del messaggio di errore o di warning.\n */\n public RPNException(String headerText, String contentText) {\n super(String.format(\"%s %s\", headerText, contentText));\n this.headerText = headerText;\n this.contentText = contentText;\n }\n\n /**\n * Restituisce l'intestazione del messaggio di errore o di warning.\n *\n * @return Restituisce l'intestazione del messaggio di errore o di warning.\n */\n public String getHeaderText() {\n return headerText;\n }\n\n /**\n * Restituisce il testo del messaggio di errore o di warning.\n *\n * @return Restituisce il testo del messaggio di errore o di warning.\n */\n public String getContentText() {\n return contentText;\n }\n\n}"
},
{
"identifier": "InsufficientArgumentsException",
"path": "CalcolatriceScientificaGruppo04/src/main/java/it/unisa/diem/ids2023/rpnpsc/exceptions/InsufficientArgumentsException.java",
"snippet": "public class InsufficientArgumentsException extends RPNException {\n\n /**\n * Costruttore della classe {@code InsufficientArgumentsException}.\n *\n * @param headerText Intestazione del messaggio di errore o di warning.\n * @param contentText Testo del messaggio di errore o di warning.\n */\n public InsufficientArgumentsException(String headerText, String contentText) {\n super(headerText, contentText);\n }\n\n}"
},
{
"identifier": "InvalidFormatException",
"path": "CalcolatriceScientificaGruppo04/src/main/java/it/unisa/diem/ids2023/rpnpsc/exceptions/InvalidFormatException.java",
"snippet": "public class InvalidFormatException extends RPNException {\n\n /**\n * Costruttore della classe {@code InvalidFormatException}.\n *\n * @param headerText Intestazione del messaggio di errore o di warning.\n * @param contentText Testo del messaggio di errore o di warning.\n */\n public InvalidFormatException(String headerText, String contentText) {\n super(headerText, contentText);\n }\n\n}"
},
{
"identifier": "EmptyStackException",
"path": "CalcolatriceScientificaGruppo04/src/main/java/it/unisa/diem/ids2023/rpnpsc/exceptions/EmptyStackException.java",
"snippet": "public class EmptyStackException extends RPNException {\n\n /**\n * Costruttore della classe {@code EmptyStackException}.\n *\n * @param headerText Intestazione del messaggio di errore o di warning.\n * @param contentText Testo del messaggio di errore o di warning.\n */\n public EmptyStackException(String headerText, String contentText) {\n super(headerText, contentText);\n }\n\n}"
}
] | import it.unisa.diem.ids2023.rpnpsc.exceptions.RPNException;
import it.unisa.diem.ids2023.rpnpsc.exceptions.InsufficientArgumentsException;
import it.unisa.diem.ids2023.rpnpsc.exceptions.InvalidFormatException;
import it.unisa.diem.ids2023.rpnpsc.exceptions.EmptyStackException;
import java.util.Arrays;
import java.util.Stack;
import java.util.regex.Pattern;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList; | 1,324 | package it.unisa.diem.ids2023.rpnpsc;
/**
* La classe {@code RPNStack} rappresenta uno stack di operandi e operatori.
* Fornisce metodi statici per il riconoscimento del tipo di elemento contenuto
* nello stack e per la verifica del relativo formato. Definisce tutte le
* operazioni di manipolazione dello stack indicate nella Specifica dei
* Requisiti. Fornisce, inoltre, il metodo di risoluzione dello stack di
* operazioni.
*/
public class RPNStack {
/**
* Costituisce lo stack di elementi utilizzato per memorizzare operandi e
* operazioni.
*/
private final Stack<String> stack;
/**
* Lista osservabile utilizzata per consentire la visualizzazione dello
* stack aggiornato all'interno della visualizzazione principale.
*/
private final ObservableList<String> observableList;
/**
* Costruttore della classe {@code RPNStack}.
*/
public RPNStack() {
this.stack = new Stack<>();
this.observableList = FXCollections.observableList(stack);
}
/**
* Restituisce la lista osservabile.
*
* @return Restituisce la lista osservabile.
*/
public ObservableList<String> getObservableList() {
return observableList;
}
/**
* Restituisce true se l'elemento è un operando reale o complesso.
*
* @param item Elemento dello stack.
* @return Restituisce true se l'elemento è un operando reale o complesso.
* @see Complex
*/
public static boolean isOperand(String item) {
try {
Complex.parse(item);
return true; | package it.unisa.diem.ids2023.rpnpsc;
/**
* La classe {@code RPNStack} rappresenta uno stack di operandi e operatori.
* Fornisce metodi statici per il riconoscimento del tipo di elemento contenuto
* nello stack e per la verifica del relativo formato. Definisce tutte le
* operazioni di manipolazione dello stack indicate nella Specifica dei
* Requisiti. Fornisce, inoltre, il metodo di risoluzione dello stack di
* operazioni.
*/
public class RPNStack {
/**
* Costituisce lo stack di elementi utilizzato per memorizzare operandi e
* operazioni.
*/
private final Stack<String> stack;
/**
* Lista osservabile utilizzata per consentire la visualizzazione dello
* stack aggiornato all'interno della visualizzazione principale.
*/
private final ObservableList<String> observableList;
/**
* Costruttore della classe {@code RPNStack}.
*/
public RPNStack() {
this.stack = new Stack<>();
this.observableList = FXCollections.observableList(stack);
}
/**
* Restituisce la lista osservabile.
*
* @return Restituisce la lista osservabile.
*/
public ObservableList<String> getObservableList() {
return observableList;
}
/**
* Restituisce true se l'elemento è un operando reale o complesso.
*
* @param item Elemento dello stack.
* @return Restituisce true se l'elemento è un operando reale o complesso.
* @see Complex
*/
public static boolean isOperand(String item) {
try {
Complex.parse(item);
return true; | } catch (InvalidFormatException ex) { | 2 | 2023-11-17 20:16:14+00:00 | 2k |
GoogleCloudPlatform/dataproc-trino-autoscaler | src/main/java/com/google/cloud/solutions/trinoscaler/gcp/DataprocInstanceShutdownService.java | [
{
"identifier": "ClusterInformation",
"path": "src/main/java/com/google/cloud/solutions/trinoscaler/ClusterInformation.java",
"snippet": "@AutoValue\npublic abstract class ClusterInformation {\n public abstract String projectId();\n\n public abstract String region();\n\n public abstract String zone();\n\n public abstract String name();\n\n public static ClusterInformation create(\n String projectId, String region, String zone, String name) {\n return new AutoValue_ClusterInformation(projectId, region, zone, name);\n }\n}"
},
{
"identifier": "Factory",
"path": "src/main/java/com/google/cloud/solutions/trinoscaler/Factory.java",
"snippet": "public interface Factory<T> {\n T create() throws IOException;\n}"
},
{
"identifier": "WorkerShutdownService",
"path": "src/main/java/com/google/cloud/solutions/trinoscaler/scaler/WorkerShutdownService.java",
"snippet": "public interface WorkerShutdownService {\n\n void markWorkerForShutdown(String workerName) throws IOException;\n\n void shutdownWorker(String workerName) throws IOException;\n}"
}
] | import com.google.auth.oauth2.AccessToken;
import com.google.cloud.compute.v1.GetInstanceRequest;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.InstancesSetLabelsRequest;
import com.google.cloud.compute.v1.Items;
import com.google.cloud.compute.v1.SetLabelsInstanceRequest;
import com.google.cloud.compute.v1.SetMetadataInstanceRequest;
import com.google.cloud.solutions.trinoscaler.ClusterInformation;
import com.google.cloud.solutions.trinoscaler.Factory;
import com.google.cloud.solutions.trinoscaler.proto.Clusters.RepairClusterRequest;
import com.google.cloud.solutions.trinoscaler.proto.Clusters.RepairClusterRequest.NodePool;
import com.google.cloud.solutions.trinoscaler.proto.Clusters.RepairClusterRequest.NodePoolType;
import com.google.cloud.solutions.trinoscaler.proto.Clusters.RepairClusterRequest.RepairAction;
import com.google.cloud.solutions.trinoscaler.scaler.WorkerShutdownService;
import com.google.common.collect.Queues;
import com.google.common.flogger.GoogleLogger;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody; | 781 | /*
* Copyright 2023 Google LLC
*
* 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.google.cloud.solutions.trinoscaler.gcp;
/**
* Dataproc specific implementation that first add the shutting-down metadata flag and then resizes
* the Dataproc cluster to stop a specific worker machine.
*/
public class DataprocInstanceShutdownService implements WorkerShutdownService, Runnable {
static final String TRINO_WORKER_SHUTTING_DOWN_LABEL_KEY = "trino-autoscaler-shuttingdown";
private static final String ENDPOINT = "/v1/projects/%1$s/regions/%2$s/clusters/%3$s:repair";
private static final String HOSTNAME = "https://dataproc.googleapis.com";
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
| /*
* Copyright 2023 Google LLC
*
* 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.google.cloud.solutions.trinoscaler.gcp;
/**
* Dataproc specific implementation that first add the shutting-down metadata flag and then resizes
* the Dataproc cluster to stop a specific worker machine.
*/
public class DataprocInstanceShutdownService implements WorkerShutdownService, Runnable {
static final String TRINO_WORKER_SHUTTING_DOWN_LABEL_KEY = "trino-autoscaler-shuttingdown";
private static final String ENDPOINT = "/v1/projects/%1$s/regions/%2$s/clusters/%3$s:repair";
private static final String HOSTNAME = "https://dataproc.googleapis.com";
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
| private final ClusterInformation clusterInformation; | 0 | 2023-11-17 03:39:59+00:00 | 2k |
yoanpetrov02/todo-app | src/main/java/com/tudu/todoapp/rest/controllers/BoardController.java | [
{
"identifier": "Board",
"path": "src/main/java/com/tudu/todoapp/entities/Board.java",
"snippet": "@Entity\n@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\n@Table(name=\"boards\")\npublic class Board {\n\n @Id\n @GeneratedValue\n @Column(name = \"board_id\")\n private Long boardId;\n @Column(name = \"title\")\n private String title;\n @Column(name = \"description\")\n private String description;\n\n @ManyToOne(cascade = CascadeType.ALL)\n @JoinColumn(name = \"user_id\")\n private User user;\n\n @OneToMany(mappedBy = \"board\", cascade = CascadeType.ALL)\n private List<TodoList> todoLists;\n}"
},
{
"identifier": "ResourceConflictException",
"path": "src/main/java/com/tudu/todoapp/exceptions/ResourceConflictException.java",
"snippet": "public class ResourceConflictException extends RuntimeException {\n\n public ResourceConflictException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "ResourceNotFoundException",
"path": "src/main/java/com/tudu/todoapp/exceptions/ResourceNotFoundException.java",
"snippet": "public class ResourceNotFoundException extends RuntimeException {\n\n public ResourceNotFoundException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "BoardService",
"path": "src/main/java/com/tudu/todoapp/services/interfaces/BoardService.java",
"snippet": "public interface BoardService {\n\n /**\n * Returns all boards.\n */\n List<Board> getAllBoards();\n\n /**\n * Returns the page with the amount of boards per page, or as many as there are on that page in the database.\n *\n * @param pageNumber the number of the page.\n * This value gets converted to an index by subtracting 1 from it,\n * so don't modify the value before passing it to this method.\n * @param perPage the amount of boards on each page.\n * @return the page as a {@code List}.\n */\n List<Board> getBoardsPage(int pageNumber, int perPage);\n\n /**\n * Returns the board with that id.\n *\n * @throws ResourceNotFoundException if the board was not found.\n */\n Board getBoardById(Long boardId) throws ResourceNotFoundException;\n\n /**\n * Creates the new board in the database.\n *\n * @param board the board's information.\n * @return the saved {@code Board}.\n * @throws ResourceConflictException if a board with the same id already exists.\n */\n Board createBoard(Board board) throws ResourceConflictException;\n\n /**\n * Updates the board with the given id with the new data.\n *\n * @param boardId the id of the board.\n * @param newData the new data of the board.\n * @return the updated {@code Board}.\n * @throws ResourceNotFoundException if the board was not found.\n */\n Board updateBoard(Long boardId, Board newData) throws ResourceNotFoundException;\n\n /**\n * Deletes all boards from the database.\n */\n void deleteAllBoards();\n\n /**\n * Deletes the board with the given id.\n *\n * @param boardId the id of the board.\n */\n void deleteBoardById(Long boardId) throws ResourceNotFoundException;\n}"
}
] | import com.tudu.todoapp.entities.Board;
import com.tudu.todoapp.exceptions.ResourceConflictException;
import com.tudu.todoapp.exceptions.ResourceNotFoundException;
import com.tudu.todoapp.services.interfaces.BoardService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List; | 1,005 | package com.tudu.todoapp.rest.controllers;
/**
* Rest controller for boards.
*/
@RequiredArgsConstructor
@RestController
@RequestMapping("api/v1/boards")
public class BoardController {
private final BoardService boardService;
// TODO Add validation for pageNumber and itemsPerPage (check how to validate @RequestParam-s)
@GetMapping
public ResponseEntity<?> getBoards(
@RequestParam Integer pageNumber,
@RequestParam Integer itemsPerPage
) {
List<Board> boards = boardService.getBoardsPage(pageNumber, itemsPerPage);
if (boards.isEmpty()) {
return ResponseEntity.noContent().build();
}
return new ResponseEntity<>(boards, HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<?> getBoardById(@PathVariable Long id) {
try {
Board board = boardService.getBoardById(id);
return new ResponseEntity<>(board, HttpStatus.OK); | package com.tudu.todoapp.rest.controllers;
/**
* Rest controller for boards.
*/
@RequiredArgsConstructor
@RestController
@RequestMapping("api/v1/boards")
public class BoardController {
private final BoardService boardService;
// TODO Add validation for pageNumber and itemsPerPage (check how to validate @RequestParam-s)
@GetMapping
public ResponseEntity<?> getBoards(
@RequestParam Integer pageNumber,
@RequestParam Integer itemsPerPage
) {
List<Board> boards = boardService.getBoardsPage(pageNumber, itemsPerPage);
if (boards.isEmpty()) {
return ResponseEntity.noContent().build();
}
return new ResponseEntity<>(boards, HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<?> getBoardById(@PathVariable Long id) {
try {
Board board = boardService.getBoardById(id);
return new ResponseEntity<>(board, HttpStatus.OK); | } catch (ResourceNotFoundException e) { | 2 | 2023-11-15 09:10:13+00:00 | 2k |
SplitfireUptown/datalinkx | datalinkx-server/src/main/java/com/datalinkx/dataserver/client/xxljob/XxlJobClient.java | [
{
"identifier": "LogQueryParam",
"path": "datalinkx-server/src/main/java/com/datalinkx/dataserver/client/xxljob/request/LogQueryParam.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\npublic class LogQueryParam {\n @Field(\"start\")\n int start;\n @Field(\"length\")\n int length;\n @Field(\"jobGroup\")\n int jobGroup;\n @Field(\"logStatus\")\n int logStatus;\n @Field(\"jobId\")\n int jobId;\n}"
},
{
"identifier": "PageQueryParam",
"path": "datalinkx-server/src/main/java/com/datalinkx/dataserver/client/xxljob/request/PageQueryParam.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\npublic class PageQueryParam {\n @Field(\"start\")\n int start;\n @Field(\"length\")\n int length;\n @Field(\"jobGroup\")\n int jobGroup;\n @Field(\"triggerStatus\")\n int triggerStatus;\n @Field(\"jobDesc\")\n String jobDesc;\n @Field(\"executorHandler\")\n String executorHandler;\n @Field(\"author\")\n String author;\n}"
},
{
"identifier": "XxlJobInfo",
"path": "datalinkx-server/src/main/java/com/datalinkx/dataserver/client/xxljob/request/XxlJobInfo.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\npublic class XxlJobInfo {\n @Field(\"id\")\n int id;\t\t\t\t// 主键ID\n\n @Field(\"jobGroup\")\n int jobGroup;\t\t// 执行器主键ID\n\n @Field(\"jobDesc\")\n String jobDesc;\n\n @Field(\"author\")\n String author;\t\t// 负责人\n\n @Field(\"alarmEmail\")\n String alarmEmail;\t// 报警邮件\n\n @Field(\"scheduleType\")\n String scheduleType;\t\t\t// 调度类型 NONE/CRON/FIX_RATE\n\n @Field(\"scheduleConf\")\n String scheduleConf;\t\t\t// 调度配置,值含义取决于调度类型\n\n @Field(\"misfireStrategy\")\n String misfireStrategy;\t\t\t// 调度过期策略\n\n @Field(\"executorRouteStrategy\")\n String executorRouteStrategy;\t// 执行器路由策略\n\n @Field(\"executorHandler\")\n String executorHandler;\t\t // 执行器,任务Handler名称\n\n @Field(\"executorParam\")\n String executorParam;\t\t // 执行器,任务参数\n\n @Field(\"executorBlockStrategy\")\n String executorBlockStrategy;\t// 阻塞处理策略\n\n @Field(\"executorTimeout\")\n int executorTimeout; \t\t// 任务执行超时时间,单位秒\n\n @Field(\"executorFailRetryCount\")\n int executorFailRetryCount;\t\t// 失败重试次数\n\n @Field(\"glueType\")\n String glueType;\t\t// GLUE类型\t#com.xxl.job.core.glue.GlueTypeEnum\n\n @Field(\"glueSource\")\n String glueSource;\t\t// GLUE源代码\n\n @Field(\"glueRemark\")\n String glueRemark;\t\t// GLUE备注\n\n @Field(\"childJobId\")\n String childJobId;\t// 子任务ID,多个逗号分隔\n\n @Field(\"addTime\")\n private Date addTime;\n\n @Field(\"updateTime\")\n private Date updateTime;\n\n @Field(\"glueUpdatetime\")\n private Date glueUpdatetime;\t// GLUE更新时间\n\n @Field(\"triggerStatus\")\n private int triggerStatus;\t\t// 调度状态:0-停止,1-运行\n @Field(\"triggerLastTime\")\n private long triggerLastTime;\t// 上次调度时间\n @Field(\"triggerNextTime\")\n private long triggerNextTime;\t// 下次调度时间\n}"
},
{
"identifier": "ReturnT",
"path": "datalinkx-server/src/main/java/com/datalinkx/dataserver/client/xxljob/response/ReturnT.java",
"snippet": "@Data\n@AllArgsConstructor\npublic class ReturnT<T> implements Serializable {\n public static final long serialVersionUID = 42L;\n\n public static final int SUCCESS_CODE = 200;\n public static final int FAIL_CODE = 500;\n\n public static final ReturnT<String> SUCCESS = new ReturnT<String>(null);\n public static final ReturnT<String> FAIL = new ReturnT<String>(FAIL_CODE, null);\n\n private int code;\n private String msg;\n private T content;\n\n public ReturnT() {\n }\n\n public ReturnT(int code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n public ReturnT(T content) {\n this.code = SUCCESS_CODE;\n this.content = content;\n }\n}"
}
] | import java.util.Map;
import com.datalinkx.dataserver.client.xxljob.request.LogQueryParam;
import com.datalinkx.dataserver.client.xxljob.request.PageQueryParam;
import com.datalinkx.dataserver.client.xxljob.request.XxlJobInfo;
import com.datalinkx.dataserver.client.xxljob.response.ReturnT;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
import retrofit2.http.QueryBean; | 1,444 | package com.datalinkx.dataserver.client.xxljob;
/**
* xxl-job service api interface
*/
public interface XxlJobClient {
@FormUrlEncoded
@POST("/xxl-job-admin/jobinfo/add")
ReturnT<String> add(@QueryBean XxlJobInfo xxlJobInfo);
@FormUrlEncoded
@POST("/xxl-job-admin/jobinfo/update")
ReturnT<String> update(@QueryBean XxlJobInfo xxlJobInfo);
@FormUrlEncoded
@POST("/xxl-job-admin/jobinfo/pageList") | package com.datalinkx.dataserver.client.xxljob;
/**
* xxl-job service api interface
*/
public interface XxlJobClient {
@FormUrlEncoded
@POST("/xxl-job-admin/jobinfo/add")
ReturnT<String> add(@QueryBean XxlJobInfo xxlJobInfo);
@FormUrlEncoded
@POST("/xxl-job-admin/jobinfo/update")
ReturnT<String> update(@QueryBean XxlJobInfo xxlJobInfo);
@FormUrlEncoded
@POST("/xxl-job-admin/jobinfo/pageList") | Map<String, Object> pageList(@QueryBean PageQueryParam queryParam); | 1 | 2023-11-16 02:22:52+00:00 | 2k |
bdmarius/jndarray-toolbox | src/main/java/internals/TensorSlice.java | [
{
"identifier": "ShapeUtils",
"path": "src/main/java/utils/ShapeUtils.java",
"snippet": "public class ShapeUtils {\n\n public static int[][] getShapesMatrix(int[] firstShape, int[] secondShape) {\n if (firstShape.length <= secondShape.length) {\n return buildShapesMatrix(firstShape, secondShape);\n } else {\n return buildShapesMatrix(secondShape, firstShape);\n }\n }\n\n public static int getSizeFromShape(List<Integer> shape) {\n return shape.stream().reduce(1, (i, j) -> i * j);\n }\n\n private static int[][] buildShapesMatrix(int[] smallerShape, int[] largerShape) {\n int[][] shapesMatrix = new int[2][largerShape.length];\n int shapeDeltaIndex = 0;\n while (shapeDeltaIndex < (largerShape.length - smallerShape.length)) {\n shapesMatrix[0][shapeDeltaIndex] = 1;\n shapeDeltaIndex++;\n }\n for (int value : smallerShape) {\n shapesMatrix[0][shapeDeltaIndex] = value;\n shapeDeltaIndex++;\n }\n System.arraycopy(largerShape, 0, shapesMatrix[1], 0, largerShape.length);\n return shapesMatrix;\n }\n}"
},
{
"identifier": "StrideUtils",
"path": "src/main/java/utils/StrideUtils.java",
"snippet": "public class StrideUtils {\n\n public static List<Integer> buildStridesFromShape(int[] shape) {\n List<Integer> strides = new ArrayList<>();\n int currentStride = 1;\n for (int i = shape.length - 1; i >= 0; i--) {\n strides.add(currentStride);\n currentStride *= shape[i];\n }\n Collections.reverse(strides);\n return strides;\n }\n}"
}
] | import utils.ShapeUtils;
import utils.StrideUtils;
import java.util.Arrays;
import java.util.stream.Collectors; | 812 | package internals;
public class TensorSlice {
/**
* Limits need to be provided as a 2-D array: an array of length equal to the shape length of the original tensor,
* then each sub-array has a length of exactly 2 (start and end limits). The start limits needs to be at least 0,
* the end limit needs to be maximum n-1, where n is the size in that dimension.
* The returned tensor is a view of the original tensor.
* If the input tensor is a view, the base is also transferred to the new Tensor
*/
static Tensor slice(Tensor tensor, int[][] limits) {
int[] currentShape = tensor.getShape();
int[] currentStrides = tensor.getStrides();
if (limits.length != currentShape.length) {
illegalLimits(limits, currentShape);
}
int[] startLimits = new int[currentShape.length];
int[] newShape = new int[currentShape.length];
for (int i = 0; i < currentShape.length; i++) {
if (limits[i].length != 2) {
illegalLimits(limits, currentShape);
}
if (limits[i][0] < 0 || limits[i][1] < limits[i][0] || limits[i][1] >= currentShape[i]) {
illegalLimits(limits, currentShape);
}
startLimits[i] = limits[i][0];
newShape[i] = limits[i][1] - limits[i][0] + 1;
}
Tensor result = tensor.view();
result.setShape(Arrays.stream(newShape).boxed().collect(Collectors.toList()));
result.setStrides(StrideUtils.buildStridesFromShape(newShape));
int[] newStrides = result.getStrides();
| package internals;
public class TensorSlice {
/**
* Limits need to be provided as a 2-D array: an array of length equal to the shape length of the original tensor,
* then each sub-array has a length of exactly 2 (start and end limits). The start limits needs to be at least 0,
* the end limit needs to be maximum n-1, where n is the size in that dimension.
* The returned tensor is a view of the original tensor.
* If the input tensor is a view, the base is also transferred to the new Tensor
*/
static Tensor slice(Tensor tensor, int[][] limits) {
int[] currentShape = tensor.getShape();
int[] currentStrides = tensor.getStrides();
if (limits.length != currentShape.length) {
illegalLimits(limits, currentShape);
}
int[] startLimits = new int[currentShape.length];
int[] newShape = new int[currentShape.length];
for (int i = 0; i < currentShape.length; i++) {
if (limits[i].length != 2) {
illegalLimits(limits, currentShape);
}
if (limits[i][0] < 0 || limits[i][1] < limits[i][0] || limits[i][1] >= currentShape[i]) {
illegalLimits(limits, currentShape);
}
startLimits[i] = limits[i][0];
newShape[i] = limits[i][1] - limits[i][0] + 1;
}
Tensor result = tensor.view();
result.setShape(Arrays.stream(newShape).boxed().collect(Collectors.toList()));
result.setStrides(StrideUtils.buildStridesFromShape(newShape));
int[] newStrides = result.getStrides();
| int newIndexingTableSize = ShapeUtils.getSizeFromShape(result.getShapeList()); | 0 | 2023-11-13 19:53:02+00:00 | 2k |
raphael-goetz/betterflowers | src/main/java/com/uroria/betterflowers/listeners/CustomFlowerPlaceListener.java | [
{
"identifier": "BetterFlowers",
"path": "src/main/java/com/uroria/betterflowers/BetterFlowers.java",
"snippet": "@Getter\npublic final class BetterFlowers extends JavaPlugin {\n\n private final FlowerManager flowerManager;\n private final LanguageManager languageManager;\n\n public BetterFlowers() {\n this.flowerManager = new FlowerManager();\n this.languageManager = new LanguageManager();\n }\n\n @Override\n public void onEnable() {\n registerCommands();\n registerListener();\n }\n\n private void registerCommands() {\n final var flowerCommand = getCommand(\"flower\");\n if (flowerCommand != null) {\n flowerCommand.setAliases(List.of(\"f\", \"F\"));\n flowerCommand.setExecutor(new Flower(this));\n }\n\n final var flowerBrushCommand = getCommand(\"flowerbrush\");\n if (flowerBrushCommand != null) {\n flowerBrushCommand.setAliases(List.of(\"fb\", \"Fb\", \"fB\", \"FB\"));\n flowerBrushCommand.setExecutor(new FlowerBrush(this));\n }\n\n final var undoFlowerCommand = getCommand(\"undoflower\");\n if (undoFlowerCommand != null) {\n undoFlowerCommand.setAliases(List.of(\"uf\", \"Uf\", \"uF\", \"UF\"));\n undoFlowerCommand.setExecutor(new UndoFlower(this));\n }\n }\n\n private void registerListener() {\n Bukkit.getPluginManager().registerEvents(new CustomFlowerPlaceListener(this), this);\n Bukkit.getPluginManager().registerEvents(new CustomFlowerBrushListener(this), this);\n }\n}"
},
{
"identifier": "FlowerManager",
"path": "src/main/java/com/uroria/betterflowers/managers/FlowerManager.java",
"snippet": "@Getter\npublic final class FlowerManager {\n\n private final Map<ItemStack, FlowerGroupData> flowers;\n private final Map<ItemStack, BrushData> brushes;\n private final Map<FlowerGroupData, List<Boolean>> flowerRandomizer;\n private final Map<UUID, List<Operation>> operationHistory;\n\n public FlowerManager() {\n this.flowers = new HashMap<>();\n this.brushes = new HashMap<>();\n this.flowerRandomizer = new HashMap<>();\n this.operationHistory = new HashMap<>();\n }\n}"
}
] | import com.uroria.betterflowers.BetterFlowers;
import com.uroria.betterflowers.data.Operation;
import com.uroria.betterflowers.managers.FlowerManager;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Block;
import org.bukkit.block.data.BlockData;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random; | 716 | package com.uroria.betterflowers.listeners;
public final class CustomFlowerPlaceListener implements Listener {
private final FlowerManager flowerManager;
private final List<Block> flowerBlocks;
| package com.uroria.betterflowers.listeners;
public final class CustomFlowerPlaceListener implements Listener {
private final FlowerManager flowerManager;
private final List<Block> flowerBlocks;
| public CustomFlowerPlaceListener(BetterFlowers betterFlowers) { | 0 | 2023-11-18 16:13:59+00:00 | 2k |
DatCoder464/Malumian-Skies | src/main/java/org/valkyrienskies/malumian_skies/registry/block/MSBlockRegistry.java | [
{
"identifier": "CombustionSilo",
"path": "src/main/java/org/valkyrienskies/malumian_skies/common/block/CombustionSilo.java",
"snippet": "public class CombustionSilo extends Block implements EntityBlock {\n public CombustionSilo(Properties pProperties) {\n super(pProperties);\n }\n\n @Nullable\n @Override\n public BlockEntity newBlockEntity(BlockPos Pos, BlockState State) {\n return BlockEntityRegistry.COMBUSTION_SILO.get().create(Pos,State);\n }\n}"
},
{
"identifier": "CombustionTank",
"path": "src/main/java/org/valkyrienskies/malumian_skies/common/block/CombustionTank.java",
"snippet": "public class CombustionTank extends Block implements EntityBlock {\n public CombustionTank(Properties pProperties) {\n super(pProperties);\n }\n\n @Nullable\n @Override\n public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {\n return BlockEntityRegistry.COMBUSTION_TANK.get().create(pos, state);\n }\n}"
},
{
"identifier": "CombustionThruster",
"path": "src/main/java/org/valkyrienskies/malumian_skies/common/block/CombustionThruster.java",
"snippet": "public class CombustionThruster extends Block implements EntityBlock {\n public CombustionThruster(Properties pProperties) {\n super(pProperties);\n }\n\n @Nullable\n @Override\n public BlockEntity newBlockEntity(BlockPos pPos, BlockState pState) {\n return null;\n }\n}"
},
{
"identifier": "MSTabRegistry",
"path": "src/main/java/org/valkyrienskies/malumian_skies/registry/tab/MSTabRegistry.java",
"snippet": "public class MSTabRegistry {\n public static final MSTab CONTENT = new MSTab(\"basis_of_magic\", MSItemRegistry.HALLOWED_LEAD_INGOT);\n\n public static void register(IEventBus modEventBus) {\n }\n}"
},
{
"identifier": "MOD_ID",
"path": "src/main/java/org/valkyrienskies/malumian_skies/MalumianSkies.java",
"snippet": "public static final String MOD_ID = \"malumian_skies\";"
},
{
"identifier": "HALLOWED_LEAD",
"path": "src/main/java/org/valkyrienskies/malumian_skies/registry/block/MSBlockProperties.java",
"snippet": "public static LodestoneBlockProperties HALLOWED_LEAD() {\n return new LodestoneBlockProperties(Material.HEAVY_METAL, MaterialColor.COLOR_PURPLE)\n .addTag(BlockTagRegistry.RITE_IMMUNE)\n .sound(SoundType.METAL);\n}"
}
] | import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;
import org.lwjgl.system.CallbackI;
import org.valkyrienskies.malumian_skies.common.block.CombustionSilo;
import org.valkyrienskies.malumian_skies.common.block.CombustionTank;
import org.valkyrienskies.malumian_skies.common.block.CombustionThruster;
import org.valkyrienskies.malumian_skies.registry.tab.MSTabRegistry;
import static org.valkyrienskies.malumian_skies.MalumianSkies.MOD_ID;
import static org.valkyrienskies.malumian_skies.registry.block.MSBlockProperties.HALLOWED_LEAD; | 947 | package org.valkyrienskies.malumian_skies.registry.block;
public class MSBlockRegistry extends Blocks {
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD_ID);
public static final RegistryObject<CombustionThruster> COMBUSTION_THRUSTER = BLOCKS.register("combustion_thruster", () -> new CombustionThruster(HALLOWED_LEAD()));
public static final RegistryObject<CombustionTank> COMBUSTION_TANK = BLOCKS.register("combustion_tank", () -> new CombustionTank(HALLOWED_LEAD())); | package org.valkyrienskies.malumian_skies.registry.block;
public class MSBlockRegistry extends Blocks {
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD_ID);
public static final RegistryObject<CombustionThruster> COMBUSTION_THRUSTER = BLOCKS.register("combustion_thruster", () -> new CombustionThruster(HALLOWED_LEAD()));
public static final RegistryObject<CombustionTank> COMBUSTION_TANK = BLOCKS.register("combustion_tank", () -> new CombustionTank(HALLOWED_LEAD())); | public static final RegistryObject<CombustionSilo> COMBUSTION_SILO = BLOCKS.register("combustion_silo", () -> new CombustionSilo(HALLOWED_LEAD())); | 0 | 2023-11-14 20:50:34+00:00 | 2k |
12manel123/tsys-my-food-api-1011 | src/main/java/com/myfood/services/ListOrderServiceImpl.java | [
{
"identifier": "IListOrderDAO",
"path": "src/main/java/com/myfood/dao/IListOrderDAO.java",
"snippet": "@Repository\npublic interface IListOrderDAO extends JpaRepository<ListOrder, Long> {\n\t\n Optional<ListOrder> findByOrderIdAndMenuId(Long orderId, Long menuId);\n\n Optional<ListOrder> findByOrderIdAndDishId(Long orderId, Long dishId);\n \n Page<ListOrder> findAll(Pageable pageable);\n \n Page<ListOrder> findByOrderId(Long orderId, Pageable pageable);\n \n}"
},
{
"identifier": "ListOrder",
"path": "src/main/java/com/myfood/dto/ListOrder.java",
"snippet": "@Entity\n@Table(name = \"list_orders\")\npublic class ListOrder {\n\n\t@Id\n\t@Column(name = \"id\")\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\n\t@ManyToOne\n\t@JoinColumn(name = \"menu_id\")\n\tprivate Menu menu;\n\n\t@ManyToOne\n\t@JoinColumn(name = \"dish_id\")\n\tprivate Dish dish;\n\n\t@ManyToOne(cascade = CascadeType.REMOVE)\n\t@JoinColumn(name = \"order_id\")\n\tprivate Order order;\n\t\n\tpublic ListOrder() {\n\t}\n\n\tpublic ListOrder(Long id, Menu menu, Dish dish, Order order) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.menu = menu;\n\t\tthis.dish = dish;\n\t\tthis.order = order;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic Menu getMenu() {\n\t\treturn menu;\n\t}\n\n\tpublic void setMenu(Menu menu) {\n\t\tthis.menu = menu;\n\t}\n\n\tpublic Dish getDish() {\n\t\treturn dish;\n\t}\n\n\tpublic void setDish(Dish dish) {\n\t\tthis.dish = dish;\n\t}\n\n\tpublic Order getOrder() {\n\t\treturn order;\n\t}\n\n\tpublic void setOrder(Order order) {\n\t\tthis.order = order;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"ListOrder [id=\" + id + \", menu=\" + menu + \", dish=\" + dish + \", order=\" + order + \"]\";\n\t}\n\n}"
}
] | import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.myfood.dao.IListOrderDAO;
import com.myfood.dto.ListOrder; | 649 | package com.myfood.services;
@Service
public class ListOrderServiceImpl implements IListOrderService {
@Autowired
private IListOrderDAO dao;
@Override | package com.myfood.services;
@Service
public class ListOrderServiceImpl implements IListOrderService {
@Autowired
private IListOrderDAO dao;
@Override | public List<ListOrder> getAllListOrders() { | 1 | 2023-11-10 16:09:43+00:00 | 2k |
huzpsb/LC4J | src/org/eu/huzpsb/unichat/agent/impl/latex/LatexTransformer.java | [
{
"identifier": "Transformer",
"path": "src/org/eu/huzpsb/unichat/agent/Transformer.java",
"snippet": "public interface Transformer {\n Conversation beforeSend(Conversation conversation);\n\n Entry afterReceive(Entry entry);\n}"
},
{
"identifier": "Conversation",
"path": "src/org/eu/huzpsb/unichat/conversation/Conversation.java",
"snippet": "public class Conversation {\n public List<Entry> entries = new ArrayList<>();\n\n @SuppressWarnings(\"ALL\")\n @Override\n public Conversation clone() {\n // 1, We don't need to clone entries, because they are immutable.\n // 2, We don't need to call super.clone(), because it's an empty method.\n Conversation conversation = new Conversation();\n conversation.entries.addAll(entries);\n return conversation;\n }\n}"
},
{
"identifier": "Entry",
"path": "src/org/eu/huzpsb/unichat/conversation/Entry.java",
"snippet": "public class Entry {\n public final EntryOwner owner;\n public final String content;\n\n public Entry(EntryOwner owner, String content) {\n this.owner = owner;\n this.content = content;\n }\n}"
},
{
"identifier": "EntryOwner",
"path": "src/org/eu/huzpsb/unichat/conversation/EntryOwner.java",
"snippet": "public enum EntryOwner {\n USER,\n BOT,\n SYSTEM\n}"
},
{
"identifier": "TransformerException",
"path": "src/org/eu/huzpsb/unichat/exceptions/TransformerException.java",
"snippet": "public class TransformerException extends RuntimeException {\n public TransformerException(String message) {\n super(message);\n }\n\n public static void throwIfNotAu(Conversation conversation) {\n switch (conversation.entries.size()) {\n case 0:\n throw new TransformerException(\"Conversation has no entries\");\n case 1:\n Entry entry = conversation.entries.get(0);\n if (entry.owner != EntryOwner.USER) {\n throw new TransformerException(\"Conversation has only one non-user entry\");\n }\n break;\n default:\n int size = conversation.entries.size();\n Entry first = conversation.entries.get(size - 1);\n Entry second = conversation.entries.get(size - 2);\n if (first.owner != EntryOwner.USER || second.owner == EntryOwner.USER) {\n throw new TransformerException(\"Conversation doesn't end with Au pattern\");\n }\n }\n }\n}"
}
] | import org.eu.huzpsb.unichat.agent.Transformer;
import org.eu.huzpsb.unichat.conversation.Conversation;
import org.eu.huzpsb.unichat.conversation.Entry;
import org.eu.huzpsb.unichat.conversation.EntryOwner;
import org.eu.huzpsb.unichat.exceptions.TransformerException; | 1,056 | package org.eu.huzpsb.unichat.agent.impl.latex;
@SuppressWarnings("ALL")
// Mute the annoying "typo" warning. Many LaTeX commands are not in the dictionary. Stupid IDE.
public class LatexTransformer implements Transformer {
public static final String instruction = "\nThis is a Latex file.\n\nmain.tex\n````TeX\n\\documentclass[UTF8]{ctexart}\n\\pagestyle{plain}\n\\begin{document}\n \\begin{center}\n \\textbf{\\huge [YOUR TITLE HERE]}\n \\end{center}\n \\section{\n [THIS IS THE BLANK]\n \\begingroup\n \\bibliography{main}\n \\bibliographystyle{plain}\n \\endgroup\n\\end{document}\n````\n\nNow fill in the blank of the main.tex with ~1000 characters to meet the requirements above. \nGive the complete document, including the provided items. \nAdd \\cite{name0} \\cite{name1}, etc. at the end of each sentence as placeholder of citations.\nThere are 20 placeholder entries available. They are named, name0, name1, ..., name19.\nUse no less than 10 of them, and no more than 20 of them.\nUse them in the numercial order. Say, only use name3 if you've already used name2.\nSpread the cites at the end of each sentence. Do not place them all at the end of the paragraph.\nFor example, \"On the one hand, xxxx\\cite{name0}, on the other hand, xxxx\\cite{name1}. Thus, xxxx\\cite{name2}\" is good, and \"On the one hand, xxxx, on the other hand, xxxx. Thus, xxxx \\cite{name0} \\cite{name1} \\cite{name2}\" is bad.\nUse one placeholder item no more than once.\nYou don't have to do anything but giving me the generated text in the required format.\n";
@Override
public Conversation beforeSend(Conversation conversation) { | package org.eu.huzpsb.unichat.agent.impl.latex;
@SuppressWarnings("ALL")
// Mute the annoying "typo" warning. Many LaTeX commands are not in the dictionary. Stupid IDE.
public class LatexTransformer implements Transformer {
public static final String instruction = "\nThis is a Latex file.\n\nmain.tex\n````TeX\n\\documentclass[UTF8]{ctexart}\n\\pagestyle{plain}\n\\begin{document}\n \\begin{center}\n \\textbf{\\huge [YOUR TITLE HERE]}\n \\end{center}\n \\section{\n [THIS IS THE BLANK]\n \\begingroup\n \\bibliography{main}\n \\bibliographystyle{plain}\n \\endgroup\n\\end{document}\n````\n\nNow fill in the blank of the main.tex with ~1000 characters to meet the requirements above. \nGive the complete document, including the provided items. \nAdd \\cite{name0} \\cite{name1}, etc. at the end of each sentence as placeholder of citations.\nThere are 20 placeholder entries available. They are named, name0, name1, ..., name19.\nUse no less than 10 of them, and no more than 20 of them.\nUse them in the numercial order. Say, only use name3 if you've already used name2.\nSpread the cites at the end of each sentence. Do not place them all at the end of the paragraph.\nFor example, \"On the one hand, xxxx\\cite{name0}, on the other hand, xxxx\\cite{name1}. Thus, xxxx\\cite{name2}\" is good, and \"On the one hand, xxxx, on the other hand, xxxx. Thus, xxxx \\cite{name0} \\cite{name1} \\cite{name2}\" is bad.\nUse one placeholder item no more than once.\nYou don't have to do anything but giving me the generated text in the required format.\n";
@Override
public Conversation beforeSend(Conversation conversation) { | TransformerException.throwIfNotAu(conversation); | 4 | 2023-11-16 11:44:05+00:00 | 2k |