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-api/service-api-admin/src/main/java/fun/isite/service/api/admin/controller/RoleInfoController.java | [
{
"identifier": "RestResponse",
"path": "service-common/service-common-bean/src/main/java/fun/isite/service/common/bean/http/RestResponse.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Schema(name = \"RestResponse\", description = \"接口响应\")\n@Slf4j\npublic class RestResponse<T> impl... | import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import fun.isite.service.common.bean.http.RestResponse;
import fun.isite.service.common.db.dto.SplitPageDTO;
import fun.isite.service.common.db.vo.PageVO;
import fun.isite.service.core.basic.controller.BaseController;
import fun.isite.service.core.system.entity.RoleInfo;
import fun.isite.service.core.system.service.IRoleInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List; | 2,220 | package fun.isite.service.api.admin.controller;
/**
* 角色信息 控制层
*
* @author Enigma
*/
@RestController
@RequestMapping("/system/role")
@Tag(name = "角色信息", description = "角色信息相关接口") | package fun.isite.service.api.admin.controller;
/**
* 角色信息 控制层
*
* @author Enigma
*/
@RestController
@RequestMapping("/system/role")
@Tag(name = "角色信息", description = "角色信息相关接口") | public class RoleInfoController extends BaseController { | 3 | 2023-12-26 01:55:01+00:00 | 4k |
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(... | 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,625 | package com.yutian4090.bypass.service.impl;
@Service
public class CompileServiceImpl implements CompileService {
@Override
public CompilationResponseDTO compileCodeC(CompileRequestDTO request) throws IOException {
CompilationResult compilationResult = CodeCompilationUtils.compileCCode(request.getCode(), request.getTemplateName()); | package com.yutian4090.bypass.service.impl;
@Service
public class CompileServiceImpl implements CompileService {
@Override
public CompilationResponseDTO compileCodeC(CompileRequestDTO request) throws IOException {
CompilationResult compilationResult = CodeCompilationUtils.compileCCode(request.getCode(), request.getTemplateName()); | saveFile(compilationResult.getFileBytes(), compilationResult.getFileName()); | 5 | 2023-12-28 06:22:12+00:00 | 4k |
37214728aaa/android_key_logger | app/src/main/java/com/maemresen/infsec/keylogapp/KeyLogger.java | [
{
"identifier": "KeyLog",
"path": "app/src/main/java/com/maemresen/infsec/keylogapp/model/KeyLog.java",
"snippet": "public class KeyLog {\n\n private String uuid;\n private Date keyLogDate;\n private String accessibilityEvent;\n private String msg;\n\n\n public String getUuid() {\n ... | import android.accessibilityservice.AccessibilityService;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.maemresen.infsec.keylogapp.model.KeyLog;
import com.maemresen.infsec.keylogapp.util.DateTimeHelper;
import com.maemresen.infsec.keylogapp.util.Helper;
import org.json.JSONObject;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map; | 1,994 | package com.maemresen.infsec.keylogapp;
/**
* @author Emre Sen, 14.05.2019
* @contact maemresen07@gmail.com
*/
public class KeyLogger extends AccessibilityService {
private final static String LOG_TAG = Helper.getLogTag(KeyLogger.class);
@Override
public void onServiceConnected() {
Log.i(LOG_TAG, "Starting service");
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
String uuid = Helper.getUuid(); | package com.maemresen.infsec.keylogapp;
/**
* @author Emre Sen, 14.05.2019
* @contact maemresen07@gmail.com
*/
public class KeyLogger extends AccessibilityService {
private final static String LOG_TAG = Helper.getLogTag(KeyLogger.class);
@Override
public void onServiceConnected() {
Log.i(LOG_TAG, "Starting service");
}
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
String uuid = Helper.getUuid(); | Date now = DateTimeHelper.getCurrentDay(); | 1 | 2023-12-27 12:35:31+00:00 | 4k |
codingmiao/hppt | ss/src/main/java/org/wowtools/hppt/ss/service/ServerSession.java | [
{
"identifier": "BytesUtil",
"path": "common/src/main/java/org/wowtools/hppt/common/util/BytesUtil.java",
"snippet": "public class BytesUtil {\n /**\n * 按每个数组的最大长度限制,将一个数组拆分为多个\n *\n * @param originalArray 原数组\n * @param maxChunkSize 最大长度限制\n * @return 拆分结果\n */\n public s... | import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.wowtools.hppt.common.util.BytesUtil;
import org.wowtools.hppt.common.util.RoughTimeUtil;
import org.wowtools.hppt.ss.StartSs;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit; | 2,180 | package org.wowtools.hppt.ss.service;
/**
* @author liuyu
* @date 2023/11/17
*/
@Slf4j
public class ServerSession {
private final SimpleClientHandler simpleClientHandler;
private final String clientId;
private final int sessionId;
private volatile boolean running = true;
private final ServerSession serverSession = this;
//真实端口发回来的消息,存在队列里等待回发客户端
private final BlockingQueue<byte[]> serverSessionSendQueue = new ArrayBlockingQueue<>(StartSs.config.messageQueueSize);
//在何时检查超时
private long checkOutTime;
//在何时超时
private long outTime;
public ServerSession(String host, int port, String clientId, int sessionId) {
activeSession();
this.clientId = clientId;
this.sessionId = sessionId;
simpleClientHandler = new SimpleClientHandler(sessionId);
Thread.startVirtualThread(() -> {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(simpleClientHandler);
}
});
ChannelFuture future = bootstrap.connect(host, port).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
group.shutdownGracefully();
log.debug("ServerSession group.shutdownGracefully();");
}
});
}
private class SimpleClientHandler extends ChannelInboundHandlerAdapter {
private final int sessionId;
private final BlockingQueue<byte[]> sendQueue = new ArrayBlockingQueue<>(StartSs.config.messageQueueSize);
private Thread sendThread;
private ChannelHandlerContext ctx;
public SimpleClientHandler(int sessionId) {
this.sessionId = sessionId;
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
//连接建立 从队列中取数据发送到目标端口
if (null != sendThread) {
throw new RuntimeException("逻辑错误 sendThread 重复构建");
}
sendThread = Thread.startVirtualThread(() -> {
try {
while (running) {
byte[] bytes;
try {
bytes = sendQueue.poll(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
log.debug("sendThread {} Interrupted", sessionId);
break;
}
if (bytes == null) {
continue;
} | package org.wowtools.hppt.ss.service;
/**
* @author liuyu
* @date 2023/11/17
*/
@Slf4j
public class ServerSession {
private final SimpleClientHandler simpleClientHandler;
private final String clientId;
private final int sessionId;
private volatile boolean running = true;
private final ServerSession serverSession = this;
//真实端口发回来的消息,存在队列里等待回发客户端
private final BlockingQueue<byte[]> serverSessionSendQueue = new ArrayBlockingQueue<>(StartSs.config.messageQueueSize);
//在何时检查超时
private long checkOutTime;
//在何时超时
private long outTime;
public ServerSession(String host, int port, String clientId, int sessionId) {
activeSession();
this.clientId = clientId;
this.sessionId = sessionId;
simpleClientHandler = new SimpleClientHandler(sessionId);
Thread.startVirtualThread(() -> {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(simpleClientHandler);
}
});
ChannelFuture future = bootstrap.connect(host, port).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
group.shutdownGracefully();
log.debug("ServerSession group.shutdownGracefully();");
}
});
}
private class SimpleClientHandler extends ChannelInboundHandlerAdapter {
private final int sessionId;
private final BlockingQueue<byte[]> sendQueue = new ArrayBlockingQueue<>(StartSs.config.messageQueueSize);
private Thread sendThread;
private ChannelHandlerContext ctx;
public SimpleClientHandler(int sessionId) {
this.sessionId = sessionId;
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
//连接建立 从队列中取数据发送到目标端口
if (null != sendThread) {
throw new RuntimeException("逻辑错误 sendThread 重复构建");
}
sendThread = Thread.startVirtualThread(() -> {
try {
while (running) {
byte[] bytes;
try {
bytes = sendQueue.poll(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
log.debug("sendThread {} Interrupted", sessionId);
break;
}
if (bytes == null) {
continue;
} | BytesUtil.writeToChannelHandlerContext(ctx, bytes); | 0 | 2023-12-22 14:14:27+00:00 | 4k |
3arthqu4ke/phobot | src/main/java/me/earth/phobot/services/PlayerPredictionService.java | [
{
"identifier": "IAbstractClientPlayer",
"path": "src/main/java/me/earth/phobot/ducks/IAbstractClientPlayer.java",
"snippet": "public interface IAbstractClientPlayer extends ILivingEntity {\n PredictionPlayer[] phobot$getPredictions();\n\n}"
},
{
"identifier": "LerpToEvent",
"path": "src/... | import me.earth.phobot.ducks.IAbstractClientPlayer;
import me.earth.phobot.event.LerpToEvent;
import me.earth.phobot.modules.client.anticheat.AntiCheat;
import me.earth.phobot.movement.Movement;
import me.earth.phobot.util.player.PredictionPlayer;
import me.earth.phobot.util.time.TimeUtil;
import me.earth.pingbypass.api.event.SubscriberImpl;
import me.earth.pingbypass.commons.event.SafeListener;
import me.earth.pingbypass.commons.event.loop.TickEvent;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.MoverType;
import net.minecraft.world.phys.Vec3; | 2,643 | package me.earth.phobot.services;
public class PlayerPredictionService extends SubscriberImpl {
public static final double DISTANCE_SQUARED = Mth.square(6.0 + 12.0 + 2.0); // range + crystal range + lenience
public PlayerPredictionService(AntiCheat antiCheat, Minecraft mc, MovementService movementService) {
listen(new SafeListener<TickEvent>(mc) {
@Override
public void onEvent(TickEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) {
for (AbstractClientPlayer clientPlayer : level.players()) {
if (clientPlayer != player && clientPlayer instanceof IAbstractClientPlayer access) { | package me.earth.phobot.services;
public class PlayerPredictionService extends SubscriberImpl {
public static final double DISTANCE_SQUARED = Mth.square(6.0 + 12.0 + 2.0); // range + crystal range + lenience
public PlayerPredictionService(AntiCheat antiCheat, Minecraft mc, MovementService movementService) {
listen(new SafeListener<TickEvent>(mc) {
@Override
public void onEvent(TickEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) {
for (AbstractClientPlayer clientPlayer : level.players()) {
if (clientPlayer != player && clientPlayer instanceof IAbstractClientPlayer access) { | for (PredictionPlayer pp : access.phobot$getPredictions()) { | 4 | 2023-12-22 14:32:16+00:00 | 4k |
Video-Hub-Org/video-hub | backend/src/main/java/org/videohub/demo/RedBookDownloaderNode.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_AGEN... | import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.videohub.constant.VideoHubConstants;
import org.videohub.controller.RedBookController;
import org.videohub.model.RedBookRequest;
import org.videohub.service.RedBookService;
import org.videohub.utils.VideoHubUtils;
import java.util.List; | 3,480 | package org.videohub.demo;
/**
* 本地运行-小红书批量笔记下载
* 如果你是把笔记链接直接放到了redbook-node.link文件里,可以直接运行这个类
*
* @author @fmz200
* @date 2023-12-18
*/
@Slf4j
public class RedBookDownloaderNode {
public static void main(String[] args) {
// 小红书笔记的分享链接
RedBookRequest redBookRequest = new RedBookRequest();
redBookRequest.setUrl(VideoHubUtils.readLinkFromFile("redbook-node.link")); | package org.videohub.demo;
/**
* 本地运行-小红书批量笔记下载
* 如果你是把笔记链接直接放到了redbook-node.link文件里,可以直接运行这个类
*
* @author @fmz200
* @date 2023-12-18
*/
@Slf4j
public class RedBookDownloaderNode {
public static void main(String[] args) {
// 小红书笔记的分享链接
RedBookRequest redBookRequest = new RedBookRequest();
redBookRequest.setUrl(VideoHubUtils.readLinkFromFile("redbook-node.link")); | RedBookController redBookController = new RedBookController(); | 1 | 2023-12-23 03:43:13+00:00 | 4k |
ArmanKhanDev/FakepixelDungeonHelper | src/main/java/io/github/quantizr/utils/Utils.java | [
{
"identifier": "DungeonRooms",
"path": "build/sources/main/java/io/github/quantizr/DungeonRooms.java",
"snippet": "@Mod(modid = DungeonRooms.MODID, version = DungeonRooms.VERSION)\npublic class DungeonRooms\n{\n public static final String MODID = \"FDH\";\n public static final String VERSION = \"... | import com.google.gson.JsonElement;
import io.github.quantizr.DungeonRooms;
import io.github.quantizr.handlers.ScoreboardHandler;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.scoreboard.ScoreObjective;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*; | 2,603 | package io.github.quantizr.utils;
public class Utils {
/*
checkForSkyblock and checkForDungeons were taken from Danker's Skyblock Mod (https://github.com/bowser0000/SkyblockMod/).
Those methods were released under GNU General Public License v3.0 and remains under said license.
Modified by Quantizr (_risk) in Feb. 2021.
*/
public static boolean inSkyblock = false;
public static boolean inDungeons = false;
public static boolean dungeonOverride = false;
public static BlockPos originBlock = null;
public static String originCorner = null;
public static void checkForSkyblock() {
Minecraft mc = Minecraft.getMinecraft();
if (mc != null && mc.theWorld != null && !mc.isSingleplayer()) {
ScoreObjective scoreboardObj = mc.theWorld.getScoreboard().getObjectiveInDisplaySlot(1);
if (scoreboardObj != null) { | package io.github.quantizr.utils;
public class Utils {
/*
checkForSkyblock and checkForDungeons were taken from Danker's Skyblock Mod (https://github.com/bowser0000/SkyblockMod/).
Those methods were released under GNU General Public License v3.0 and remains under said license.
Modified by Quantizr (_risk) in Feb. 2021.
*/
public static boolean inSkyblock = false;
public static boolean inDungeons = false;
public static boolean dungeonOverride = false;
public static BlockPos originBlock = null;
public static String originCorner = null;
public static void checkForSkyblock() {
Minecraft mc = Minecraft.getMinecraft();
if (mc != null && mc.theWorld != null && !mc.isSingleplayer()) {
ScoreObjective scoreboardObj = mc.theWorld.getScoreboard().getObjectiveInDisplaySlot(1);
if (scoreboardObj != null) { | String scObjName = ScoreboardHandler.cleanSB(scoreboardObj.getDisplayName()); | 1 | 2023-12-22 04:44:39+00:00 | 4k |
PENEKhun/baekjoon-java-starter | src/test/java/kr/huni/Integration/IntegrationTests.java | [
{
"identifier": "BojStarter",
"path": "src/main/java/kr/huni/BojStarter.java",
"snippet": "@Slf4j\n@RequiredArgsConstructor\npublic class BojStarter {\n\n private final CodeOpenManager codeOpenManager;\n private final JavaSourceCodeFile fileUtil;\n private final CodeGenerator codeGenerator;\n privat... | import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
import kr.huni.BojStarter;
import kr.huni.TestCleaner;
import kr.huni.code.runner.FakeCodeOpen;
import kr.huni.code_generator.JavaCodeGenerator;
import kr.huni.file_generator.JavaSourceCodeFile;
import kr.huni.problem_parser.BaekjoonProblemParser;
import kr.huni.problem_parser.JsoupWebParser;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test; | 2,001 | package kr.huni.Integration;
@DisplayName("Large Integration Test")
class IntegrationTests {
@BeforeEach
void setUp() throws IOException {
TestCleaner.clean();
}
@AfterEach
void tearDown() throws IOException {
TestCleaner.clean();
}
@Test
@DisplayName("프로그램에서 Main.java 파일이 잘 생성된다.")
void applicationTest() {
// given
BojStarter program = new BojStarter(
new FakeCodeOpen(),
new JavaSourceCodeFile(),
new JavaCodeGenerator(), | package kr.huni.Integration;
@DisplayName("Large Integration Test")
class IntegrationTests {
@BeforeEach
void setUp() throws IOException {
TestCleaner.clean();
}
@AfterEach
void tearDown() throws IOException {
TestCleaner.clean();
}
@Test
@DisplayName("프로그램에서 Main.java 파일이 잘 생성된다.")
void applicationTest() {
// given
BojStarter program = new BojStarter(
new FakeCodeOpen(),
new JavaSourceCodeFile(),
new JavaCodeGenerator(), | new BaekjoonProblemParser(new JsoupWebParser(1000))); | 6 | 2023-12-22 09:23:38+00:00 | 4k |
R2turnTrue/chzzk4j | src/test/java/ChzzkTestBase.java | [
{
"identifier": "Chzzk",
"path": "src/main/java/xyz/r2turntrue/chzzk4j/Chzzk.java",
"snippet": "public class Chzzk {\n public static String API_URL = \"https://api.chzzk.naver.com\";\n public static String GAME_API_URL = \"https://comm-api.game.naver.com/nng_main\";\n\n public boolean isDebug =... | import xyz.r2turntrue.chzzk4j.Chzzk;
import xyz.r2turntrue.chzzk4j.ChzzkBuilder;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties; | 1,792 |
public class ChzzkTestBase {
Properties properties = new Properties();
String currentUserId = ""; |
public class ChzzkTestBase {
Properties properties = new Properties();
String currentUserId = ""; | Chzzk chzzk; | 0 | 2023-12-30 20:01:23+00:00 | 4k |
lonelytransistor/LauncherAndroidTV | app/src/main/java/net/lonelytransistor/launcher/entrypoints/BackgroundService.java | [
{
"identifier": "LauncherWindow",
"path": "app/src/main/java/net/lonelytransistor/launcher/LauncherWindow.java",
"snippet": "@SuppressLint(\"RestrictedApi\")\npublic class LauncherWindow extends GenericWindow {\n private static final String TAG = \"LauncherWindow\";\n\n private final Executor exec... | import android.content.Context;
import android.content.Intent;
import net.lonelytransistor.commonlib.ForegroundService;
import net.lonelytransistor.launcher.LauncherWindow;
import net.lonelytransistor.launcher.RecentsWindow;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; | 3,298 | package net.lonelytransistor.launcher.entrypoints;
public class BackgroundService extends ForegroundService {
public BackgroundService() {}
private LauncherWindow mLauncher = null; | package net.lonelytransistor.launcher.entrypoints;
public class BackgroundService extends ForegroundService {
public BackgroundService() {}
private LauncherWindow mLauncher = null; | private RecentsWindow mRecents = null; | 1 | 2023-12-28 18:24:12+00:00 | 4k |
Patbox/GlideAway | src/main/java/eu/pb4/glideaway/ModInit.java | [
{
"identifier": "GlideEntities",
"path": "src/main/java/eu/pb4/glideaway/entity/GlideEntities.java",
"snippet": "public class GlideEntities {\n public static final EntityType<GliderEntity> GLIDER\n = register(\"hang_glider\", FabricEntityTypeBuilder\n .create().trackedUpdateRate... | import eu.pb4.glideaway.entity.GlideEntities;
import eu.pb4.glideaway.item.GlideItems;
import eu.pb4.glideaway.util.GlideGamerules;
import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.util.Identifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 1,869 | package eu.pb4.glideaway;
public class ModInit implements ModInitializer {
public static final String ID = "glideaway";
public static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMetadata().getVersion().getFriendlyString();
public static final Logger LOGGER = LoggerFactory.getLogger("Glide Away!");
public static final boolean DEV_ENV = FabricLoader.getInstance().isDevelopmentEnvironment();
public static final boolean DEV_MODE = VERSION.contains("-dev.") || DEV_ENV;
@SuppressWarnings("PointlessBooleanExpression")
public static final boolean DYNAMIC_ASSETS = true && DEV_ENV;
public static Identifier id(String path) {
return new Identifier(ID, path);
}
@Override
public void onInitialize() {
if (VERSION.contains("-dev.")) {
LOGGER.warn("=====================================================");
LOGGER.warn("You are using development version of Glide Away!");
LOGGER.warn("Support is limited, as features might be unfinished!");
LOGGER.warn("You are on your own!");
LOGGER.warn("=====================================================");
}
GlideItems.register();
GlideEntities.register(); | package eu.pb4.glideaway;
public class ModInit implements ModInitializer {
public static final String ID = "glideaway";
public static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMetadata().getVersion().getFriendlyString();
public static final Logger LOGGER = LoggerFactory.getLogger("Glide Away!");
public static final boolean DEV_ENV = FabricLoader.getInstance().isDevelopmentEnvironment();
public static final boolean DEV_MODE = VERSION.contains("-dev.") || DEV_ENV;
@SuppressWarnings("PointlessBooleanExpression")
public static final boolean DYNAMIC_ASSETS = true && DEV_ENV;
public static Identifier id(String path) {
return new Identifier(ID, path);
}
@Override
public void onInitialize() {
if (VERSION.contains("-dev.")) {
LOGGER.warn("=====================================================");
LOGGER.warn("You are using development version of Glide Away!");
LOGGER.warn("Support is limited, as features might be unfinished!");
LOGGER.warn("You are on your own!");
LOGGER.warn("=====================================================");
}
GlideItems.register();
GlideEntities.register(); | GlideGamerules.register(); | 2 | 2023-12-22 11:00:52+00:00 | 4k |
andrewlalis/javafx-scene-router | src/test/java/com/andrewlalis/javafx_scene_router/test/SceneRouterTest.java | [
{
"identifier": "AnchorPaneRouterView",
"path": "src/main/java/com/andrewlalis/javafx_scene_router/AnchorPaneRouterView.java",
"snippet": "public class AnchorPaneRouterView extends SimpleRouterView<AnchorPane> {\n private final boolean expandContents;\n\n /**\n * Constructs this router view wi... | import com.andrewlalis.javafx_scene_router.AnchorPaneRouterView;
import com.andrewlalis.javafx_scene_router.SceneRouter;
import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CompletableFuture;
import static org.junit.jupiter.api.Assertions.*; | 3,522 | package com.andrewlalis.javafx_scene_router.test;
public class SceneRouterTest {
@Test
public void testNavigate() {
var router = getSampleRouter();
// Make some assertions prior to navigation.
assertTrue(router.getHistory().getItems().isEmpty());
assertFalse(router.navigateBack().join());
assertFalse(router.navigateForward().join());
assertNull(router.currentRouteProperty().get());
// Test some basic navigation.
var contextA = "CONTEXT";
router.navigate("A", contextA).join();
assertEquals(1, router.getHistory().getItems().size());
assertEquals("A", router.currentRouteProperty().get());
assertEquals(contextA, router.getContext());
assertEquals(1, router.getBreadCrumbs().size());
assertTrue(router.getBreadCrumbs().getFirst().current());
router.navigate("B").join();
assertEquals(2, router.getHistory().getItems().size());
assertEquals("B", router.currentRouteProperty().get());
assertNull(router.getContext());
assertEquals(2, router.getBreadCrumbs().size());
assertTrue(router.getBreadCrumbs().getLast().current());
assertFalse(router.getBreadCrumbs().getFirst().current());
// Test that navigating back and forward works.
assertTrue(router.navigateBack().join());
assertEquals("A", router.currentRouteProperty().get());
assertEquals(contextA, router.getContext());
assertTrue(router.navigateForward().join());
assertEquals("B", router.currentRouteProperty().get());
assertNull(router.getContext());
assertFalse(router.navigateForward().join());
// Test that navigateBackAndClear works.
assertTrue(router.navigateBackAndClear().join());
assertEquals("A", router.currentRouteProperty().get());
assertEquals(1, router.getHistory().getItems().size());
}
private SceneRouter getSampleRouter() {
CompletableFuture<SceneRouter> future = new CompletableFuture<>();
Platform.startup(() -> { | package com.andrewlalis.javafx_scene_router.test;
public class SceneRouterTest {
@Test
public void testNavigate() {
var router = getSampleRouter();
// Make some assertions prior to navigation.
assertTrue(router.getHistory().getItems().isEmpty());
assertFalse(router.navigateBack().join());
assertFalse(router.navigateForward().join());
assertNull(router.currentRouteProperty().get());
// Test some basic navigation.
var contextA = "CONTEXT";
router.navigate("A", contextA).join();
assertEquals(1, router.getHistory().getItems().size());
assertEquals("A", router.currentRouteProperty().get());
assertEquals(contextA, router.getContext());
assertEquals(1, router.getBreadCrumbs().size());
assertTrue(router.getBreadCrumbs().getFirst().current());
router.navigate("B").join();
assertEquals(2, router.getHistory().getItems().size());
assertEquals("B", router.currentRouteProperty().get());
assertNull(router.getContext());
assertEquals(2, router.getBreadCrumbs().size());
assertTrue(router.getBreadCrumbs().getLast().current());
assertFalse(router.getBreadCrumbs().getFirst().current());
// Test that navigating back and forward works.
assertTrue(router.navigateBack().join());
assertEquals("A", router.currentRouteProperty().get());
assertEquals(contextA, router.getContext());
assertTrue(router.navigateForward().join());
assertEquals("B", router.currentRouteProperty().get());
assertNull(router.getContext());
assertFalse(router.navigateForward().join());
// Test that navigateBackAndClear works.
assertTrue(router.navigateBackAndClear().join());
assertEquals("A", router.currentRouteProperty().get());
assertEquals(1, router.getHistory().getItems().size());
}
private SceneRouter getSampleRouter() {
CompletableFuture<SceneRouter> future = new CompletableFuture<>();
Platform.startup(() -> { | SceneRouter router = new SceneRouter(new AnchorPaneRouterView()); | 0 | 2023-12-22 14:26:31+00:00 | 4k |
danielfeitopin/MUNICS-SAPP-P1 | src/main/java/es/storeapp/web/exceptions/ErrorHandlingUtils.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 Authentication... | 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 es.storeapp.common.Constants;
import java.util.Locale;
import es.storeapp.common.EscapingLoggerWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult; | 3,217 | package es.storeapp.web.exceptions;
@Component
public class ErrorHandlingUtils {
private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(ErrorHandlingUtils.class);
@Autowired
private MessageSource messageSource;
public String handleInvalidFormError(BindingResult result, String template,
Model model, Locale locale) {
if(logger.isErrorEnabled()) {
logger.error(result.toString());
}
String message = messageSource.getMessage(template, new Object[0], locale);
model.addAttribute(Constants.ERROR_MESSAGE, message);
return Constants.ERROR_PAGE;
}
public String handleInstanceNotFoundException(InstanceNotFoundException e, Model model, Locale locale) {
logger.error(e.getMessage(), e);
model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());
model.addAttribute(Constants.EXCEPTION, e);
return Constants.ERROR_PAGE;
}
public String handleDuplicatedResourceException(DuplicatedResourceException e, String targetPage,
Model model, Locale locale) {
logger.error(e.getMessage(), e);
model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());
model.addAttribute(Constants.EXCEPTION, e);
return targetPage;
}
public String handleAuthenticationException(AuthenticationException e, String user, String targetPage,
Model model, Locale locale) {
logger.error(e.getMessage(), e);
model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());
model.addAttribute(Constants.EXCEPTION, e);
return targetPage;
}
| package es.storeapp.web.exceptions;
@Component
public class ErrorHandlingUtils {
private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(ErrorHandlingUtils.class);
@Autowired
private MessageSource messageSource;
public String handleInvalidFormError(BindingResult result, String template,
Model model, Locale locale) {
if(logger.isErrorEnabled()) {
logger.error(result.toString());
}
String message = messageSource.getMessage(template, new Object[0], locale);
model.addAttribute(Constants.ERROR_MESSAGE, message);
return Constants.ERROR_PAGE;
}
public String handleInstanceNotFoundException(InstanceNotFoundException e, Model model, Locale locale) {
logger.error(e.getMessage(), e);
model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());
model.addAttribute(Constants.EXCEPTION, e);
return Constants.ERROR_PAGE;
}
public String handleDuplicatedResourceException(DuplicatedResourceException e, String targetPage,
Model model, Locale locale) {
logger.error(e.getMessage(), e);
model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());
model.addAttribute(Constants.EXCEPTION, e);
return targetPage;
}
public String handleAuthenticationException(AuthenticationException e, String user, String targetPage,
Model model, Locale locale) {
logger.error(e.getMessage(), e);
model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());
model.addAttribute(Constants.EXCEPTION, e);
return targetPage;
}
| public String handleInvalidStateException(InvalidStateException e, Model model, Locale locale) { | 3 | 2023-12-24 19:24:49+00:00 | 4k |
Brath1024/SensiCheck | src/main/java/cn/brath/sensicheck/strategy/SensiHolder.java | [
{
"identifier": "SenKey",
"path": "src/main/java/cn/brath/sensicheck/core/SenKey.java",
"snippet": "public class SenKey implements Serializable {\n private static final long serialVersionUID = -8879895979621579720L;\n /** The beginning index, inclusive. */\n private final int begin;\n /** Th... | import cn.brath.sensicheck.core.SenKey;
import cn.brath.sensicheck.core.SenKeys;
import cn.brath.sensicheck.core.SenTrie;
import cn.brath.sensicheck.utils.StringUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors; | 3,393 | package cn.brath.sensicheck.strategy;
/**
* 敏感词处理
*
* @author Brath
* @since 2023-07-28 14:17:54
* <p>
* 使用AC自动机实现敏感词处理
* </p>
*/
public class SensiHolder {
private static final Logger logger = LoggerFactory.getLogger(SensiHolder.class);
//默认敏感词地址
private String filepath = "/senwords.txt";
//核心Trie结构
private SenTrie senTrie;
//当前敏感词列表
private List<String> lines;
/**
* 默认构造
*/
public SensiHolder() {
try {
List<String> lines = readLines();
this.senTrie = new SenTrie(new HashSet<>(lines));
this.lines = lines;
} catch (IOException e) {
logger.error("Failed to initialize the sensitive word instance - {}", e.getMessage());
e.printStackTrace();
}
}
/**
* 自定义FilePath
*
* @param filepath
*/
public SensiHolder(String filepath) {
this.filepath = filepath;
try {
List<String> lines = readLines();
this.senTrie = new SenTrie(new HashSet<>(lines));
this.lines = lines;
logger.info("The current sensitive word text source comes from - {}", filepath);
} catch (IOException e) {
logger.error("Failed to initialize the sensitive word instance - {}", e.getMessage());
e.printStackTrace();
}
}
/**
* 读取敏感词Base64文本
*
* @return
* @throws IOException
*/
private List<String> readLines() throws IOException {
List<String> lines = new ArrayList<>();
try (InputStream inputStream = getClass().getResourceAsStream(filepath)) {
assert inputStream != null;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = reader.readLine()) != null) {
byte[] decode = Base64.getDecoder().decode(line);
String decodedString = new String(decode, StandardCharsets.UTF_8);
lines.add(decodedString);
}
}
}
return lines;
}
/**
* 是否存在敏感词
*
* @param input
* @param ifLog
* @return
*/
public boolean exists(String input, boolean ifLog) {
input = standardizeInput(input); | package cn.brath.sensicheck.strategy;
/**
* 敏感词处理
*
* @author Brath
* @since 2023-07-28 14:17:54
* <p>
* 使用AC自动机实现敏感词处理
* </p>
*/
public class SensiHolder {
private static final Logger logger = LoggerFactory.getLogger(SensiHolder.class);
//默认敏感词地址
private String filepath = "/senwords.txt";
//核心Trie结构
private SenTrie senTrie;
//当前敏感词列表
private List<String> lines;
/**
* 默认构造
*/
public SensiHolder() {
try {
List<String> lines = readLines();
this.senTrie = new SenTrie(new HashSet<>(lines));
this.lines = lines;
} catch (IOException e) {
logger.error("Failed to initialize the sensitive word instance - {}", e.getMessage());
e.printStackTrace();
}
}
/**
* 自定义FilePath
*
* @param filepath
*/
public SensiHolder(String filepath) {
this.filepath = filepath;
try {
List<String> lines = readLines();
this.senTrie = new SenTrie(new HashSet<>(lines));
this.lines = lines;
logger.info("The current sensitive word text source comes from - {}", filepath);
} catch (IOException e) {
logger.error("Failed to initialize the sensitive word instance - {}", e.getMessage());
e.printStackTrace();
}
}
/**
* 读取敏感词Base64文本
*
* @return
* @throws IOException
*/
private List<String> readLines() throws IOException {
List<String> lines = new ArrayList<>();
try (InputStream inputStream = getClass().getResourceAsStream(filepath)) {
assert inputStream != null;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = reader.readLine()) != null) {
byte[] decode = Base64.getDecoder().decode(line);
String decodedString = new String(decode, StandardCharsets.UTF_8);
lines.add(decodedString);
}
}
}
return lines;
}
/**
* 是否存在敏感词
*
* @param input
* @param ifLog
* @return
*/
public boolean exists(String input, boolean ifLog) {
input = standardizeInput(input); | SenKeys senKeys = this.senTrie.findAll(input); | 1 | 2023-12-28 04:50:04+00:00 | 4k |
RoderickQiu/SUSTech_CSE_Projects | CS109_2022_Fall/Chess/chessComponent/EatenComponent.java | [
{
"identifier": "Main",
"path": "CS109_2022_Fall/Chess/Main.java",
"snippet": "public class Main {\r\n private static ChessGameFrame gameFrame = null;\r\n private static StartFrame startFrame = null;\r\n public static Font titleFont, sansFont, serifFont;\r\n public static String theme = \"像素... | import Chess.Main;
import Chess.model.ChessColor;
import Chess.utils.ImageUtils;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import static Chess.chessComponent.SquareComponent.CHESS_FONT; | 2,374 | package Chess.chessComponent;
public class EatenComponent extends JComponent {
String type, color;
int number, x, y;
static final int width = 24, height = 24;
public EatenComponent(String type, int number, int x, int y, String color) {
this.type = type;
this.number = number;
this.color = color;
this.x = x;
this.y = y;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponents(g);
if (Main.theme.equals("像素")) {
if (number > 0) {
InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource("chess-pixel"));
try { | package Chess.chessComponent;
public class EatenComponent extends JComponent {
String type, color;
int number, x, y;
static final int width = 24, height = 24;
public EatenComponent(String type, int number, int x, int y, String color) {
this.type = type;
this.number = number;
this.color = color;
this.x = x;
this.y = y;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponents(g);
if (Main.theme.equals("像素")) {
if (number > 0) {
InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource("chess-pixel"));
try { | g.drawImage(ImageUtils.changeToOriginalSize(new ImageIcon(stream.readAllBytes()), | 2 | 2023-12-31 05:50:13+00:00 | 4k |
Ertinox45/ImmersiveAddon | src/main/java/fr/dynamx/addons/immersive/common/modules/RadioModule.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, ... | import fr.dynamx.addons.immersive.ImmersiveAddon;
import fr.dynamx.addons.immersive.client.controllers.RadioController;
import fr.dynamx.addons.immersive.common.helpers.ConfigReader;
import fr.dynamx.addons.immersive.common.helpers.RadioPlayer;
import fr.dynamx.addons.immersive.common.infos.RadioAddonInfos;
import fr.dynamx.api.entities.modules.IPhysicsModule;
import fr.dynamx.api.entities.modules.IVehicleController;
import fr.dynamx.api.network.sync.SimulationHolder;
import fr.dynamx.api.network.sync.SynchronizedEntityVariable;
import fr.dynamx.common.entities.BaseVehicleEntity;
import fr.dynamx.common.entities.modules.SeatsModule;
import fr.dynamx.common.physics.entities.AbstractEntityPhysicsHandler;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundCategory;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nullable;
import java.net.MalformedURLException;
import java.net.URL; | 2,726 | package fr.dynamx.addons.immersive.common.modules;
@SynchronizedEntityVariable.SynchronizedPhysicsModule(modid = ImmersiveAddon.ID)
public class RadioModule implements IPhysicsModule<AbstractEntityPhysicsHandler<?, ?>>, IPhysicsModule.IEntityUpdateListener {
private RadioController controller;
private final BaseVehicleEntity<?> entity;
private final RadioAddonInfos infos;
private int currentRadioIndex = 0;
private boolean isRadioOn;
public RadioModule(BaseVehicleEntity<?> entity, RadioAddonInfos<?> infos) {
System.out.println("RadioModule");
this.entity = entity;
this.infos = infos;
if (entity.world.isRemote) {
controller = new RadioController(entity, this);
}
}
@Override
public boolean listenEntityUpdates(Side side) {
return true;
}
private int cachedRadioIndex = -1;
private boolean cachedRadioOn = false;
public void resetCached()
{
cachedRadioOn = false;
cachedRadioIndex = -1;
}
@Override
@SideOnly(Side.CLIENT)
public void updateEntity() {
if(FMLCommonHandler.instance().getSide().isClient())
{
if(!entity.world.isRemote)
return;
SeatsModule seatsModule = entity.getModuleByType(SeatsModule.class);
if(seatsModule == null)
return;
if(!seatsModule.isEntitySitting(Minecraft.getMinecraft().player))
return;
if(ImmersiveAddon.radioPlayer == null)
{
ImmersiveAddon.radioPlayer = new RadioPlayer();
}
if(ImmersiveAddon.radioPlayer != null)
{
ImmersiveAddon.radioPlayer.setGain(Minecraft.getMinecraft().gameSettings.getSoundLevel(SoundCategory.RECORDS));
}
if(cachedRadioOn != isRadioOn)
{
cachedRadioOn = isRadioOn;
if(isRadioOn)
{
System.out.println("RadioModule.updateEntity() - isRadioOn");
ImmersiveAddon.radioPlayer.resume(); | package fr.dynamx.addons.immersive.common.modules;
@SynchronizedEntityVariable.SynchronizedPhysicsModule(modid = ImmersiveAddon.ID)
public class RadioModule implements IPhysicsModule<AbstractEntityPhysicsHandler<?, ?>>, IPhysicsModule.IEntityUpdateListener {
private RadioController controller;
private final BaseVehicleEntity<?> entity;
private final RadioAddonInfos infos;
private int currentRadioIndex = 0;
private boolean isRadioOn;
public RadioModule(BaseVehicleEntity<?> entity, RadioAddonInfos<?> infos) {
System.out.println("RadioModule");
this.entity = entity;
this.infos = infos;
if (entity.world.isRemote) {
controller = new RadioController(entity, this);
}
}
@Override
public boolean listenEntityUpdates(Side side) {
return true;
}
private int cachedRadioIndex = -1;
private boolean cachedRadioOn = false;
public void resetCached()
{
cachedRadioOn = false;
cachedRadioIndex = -1;
}
@Override
@SideOnly(Side.CLIENT)
public void updateEntity() {
if(FMLCommonHandler.instance().getSide().isClient())
{
if(!entity.world.isRemote)
return;
SeatsModule seatsModule = entity.getModuleByType(SeatsModule.class);
if(seatsModule == null)
return;
if(!seatsModule.isEntitySitting(Minecraft.getMinecraft().player))
return;
if(ImmersiveAddon.radioPlayer == null)
{
ImmersiveAddon.radioPlayer = new RadioPlayer();
}
if(ImmersiveAddon.radioPlayer != null)
{
ImmersiveAddon.radioPlayer.setGain(Minecraft.getMinecraft().gameSettings.getSoundLevel(SoundCategory.RECORDS));
}
if(cachedRadioOn != isRadioOn)
{
cachedRadioOn = isRadioOn;
if(isRadioOn)
{
System.out.println("RadioModule.updateEntity() - isRadioOn");
ImmersiveAddon.radioPlayer.resume(); | Minecraft.getMinecraft().player.sendStatusMessage(new net.minecraft.util.text.TextComponentString("§c§lRadio: §r§e" + ConfigReader.frequencies.get(getCurrentRadioIndex()).getName()), true); | 2 | 2023-12-30 08:33:54+00:00 | 4k |
HighlanderRobotics/Crescendo | src/main/java/frc/robot/Robot.java | [
{
"identifier": "GyroIO",
"path": "src/main/java/frc/robot/subsystems/swerve/GyroIO.java",
"snippet": "public interface GyroIO {\n @AutoLog\n public static class GyroIOInputs {\n public boolean connected = false;\n public Rotation2d yawPosition = new Rotation2d();\n public Rotation2d[] odomet... | import edu.wpi.first.math.kinematics.ChassisSpeeds;
import edu.wpi.first.wpilibj.PowerDistribution;
import edu.wpi.first.wpilibj.PowerDistribution.ModuleType;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.CommandScheduler;
import edu.wpi.first.wpilibj2.command.Commands;
import edu.wpi.first.wpilibj2.command.button.CommandXboxController;
import frc.robot.subsystems.swerve.GyroIO;
import frc.robot.subsystems.swerve.GyroIOPigeon2;
import frc.robot.subsystems.swerve.SwerveSubsystem;
import org.littletonrobotics.junction.LogFileUtil;
import org.littletonrobotics.junction.LoggedRobot;
import org.littletonrobotics.junction.Logger;
import org.littletonrobotics.junction.networktables.NT4Publisher;
import org.littletonrobotics.junction.wpilog.WPILOGReader;
import org.littletonrobotics.junction.wpilog.WPILOGWriter; | 3,157 | // 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;
public class Robot extends LoggedRobot {
public static enum RobotMode {
SIM,
REPLAY,
REAL
}
public static final RobotMode mode = Robot.isReal() ? RobotMode.REAL : RobotMode.SIM;
private Command autonomousCommand;
private final CommandXboxController controller = new CommandXboxController(0);
private final SwerveSubsystem swerve =
new SwerveSubsystem( | // 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;
public class Robot extends LoggedRobot {
public static enum RobotMode {
SIM,
REPLAY,
REAL
}
public static final RobotMode mode = Robot.isReal() ? RobotMode.REAL : RobotMode.SIM;
private Command autonomousCommand;
private final CommandXboxController controller = new CommandXboxController(0);
private final SwerveSubsystem swerve =
new SwerveSubsystem( | mode == RobotMode.REAL ? new GyroIOPigeon2() : new GyroIO() {}, | 1 | 2023-12-26 21:26:46+00:00 | 4k |
Patbox/serveruifix | src/main/java/eu/pb4/serveruifix/ui/StonecutterGui.java | [
{
"identifier": "StonecutterScreenHandlerAccessor",
"path": "src/main/java/eu/pb4/serveruifix/mixin/StonecutterScreenHandlerAccessor.java",
"snippet": "@Mixin(StonecutterScreenHandler.class)\npublic interface StonecutterScreenHandlerAccessor {\n @Accessor\n List<RecipeEntry<StonecuttingRecipe>> ge... | import eu.pb4.serveruifix.mixin.StonecutterScreenHandlerAccessor;
import eu.pb4.serveruifix.polydex.PolydexCompat;
import eu.pb4.serveruifix.util.GuiTextures;
import eu.pb4.serveruifix.util.GuiUtils;
import eu.pb4.sgui.api.ClickType;
import eu.pb4.sgui.api.elements.GuiElement;
import eu.pb4.sgui.api.gui.SimpleGui;
import net.minecraft.item.ItemStack;
import net.minecraft.recipe.RecipeEntry;
import net.minecraft.recipe.RecipeType;
import net.minecraft.recipe.StonecuttingRecipe;
import net.minecraft.screen.ScreenHandlerType;
import net.minecraft.screen.StonecutterScreenHandler;
import net.minecraft.screen.slot.Slot;
import net.minecraft.screen.slot.SlotActionType;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt; | 1,657 | package eu.pb4.serveruifix.ui;
public class StonecutterGui extends SimpleGui {
private static final int MAX_RECIPES = 3 * 3;
private final StonecutterScreenHandler wrapped;
private final List<GuiElement> recipeEntries = new ArrayList<>(16);
private List<RecipeEntry<StonecuttingRecipe>> lastRecipes;
private int page = 0;
public StonecutterGui(Text text, StonecutterScreenHandler handler, ServerPlayerEntity player) {
super(ScreenHandlerType.GENERIC_9X4, player, false);
this.wrapped = handler;
this.setTitle(GuiTextures.STONECUTTER.apply(text));
this.setSlotRedirect(9 + 1, this.wrapped.getSlot(0));
this.setSlotRedirect(9 + 7, this.wrapped.getSlot(1));
this.setSlot(9 * 3 + 1, PolydexCompat.getButton(RecipeType.STONECUTTING));
this.updateRecipes();
}
private void updateRecipes() {
this.recipeEntries.clear();
var recipes = ((StonecutterScreenHandlerAccessor) this.wrapped).getAvailableRecipes();
var drm = this.player.getWorld().getRegistryManager();
for (int i = 0; i < recipes.size(); i++) {
var recipe = recipes.get(i);
int finalI = i;
this.recipeEntries.add(new GuiElement(recipe.value().getResult(drm), (index, type, action) -> {
if (type.isLeft) { | package eu.pb4.serveruifix.ui;
public class StonecutterGui extends SimpleGui {
private static final int MAX_RECIPES = 3 * 3;
private final StonecutterScreenHandler wrapped;
private final List<GuiElement> recipeEntries = new ArrayList<>(16);
private List<RecipeEntry<StonecuttingRecipe>> lastRecipes;
private int page = 0;
public StonecutterGui(Text text, StonecutterScreenHandler handler, ServerPlayerEntity player) {
super(ScreenHandlerType.GENERIC_9X4, player, false);
this.wrapped = handler;
this.setTitle(GuiTextures.STONECUTTER.apply(text));
this.setSlotRedirect(9 + 1, this.wrapped.getSlot(0));
this.setSlotRedirect(9 + 7, this.wrapped.getSlot(1));
this.setSlot(9 * 3 + 1, PolydexCompat.getButton(RecipeType.STONECUTTING));
this.updateRecipes();
}
private void updateRecipes() {
this.recipeEntries.clear();
var recipes = ((StonecutterScreenHandlerAccessor) this.wrapped).getAvailableRecipes();
var drm = this.player.getWorld().getRegistryManager();
for (int i = 0; i < recipes.size(); i++) {
var recipe = recipes.get(i);
int finalI = i;
this.recipeEntries.add(new GuiElement(recipe.value().getResult(drm), (index, type, action) -> {
if (type.isLeft) { | GuiUtils.playClickSound(this.player); | 3 | 2023-12-28 23:01:30+00:00 | 4k |
psobiech/opengr8on | lib/src/test/java/pl/psobiech/opengr8on/client/commands/SetKeyCommandTest.java | [
{
"identifier": "Command",
"path": "lib/src/main/java/pl/psobiech/opengr8on/client/Command.java",
"snippet": "public interface Command {\n int INITIAL_BUFFER_SIZE = 256;\n\n int MIN_IP_SIZE = 7;\n\n int IV_SIZE = 16;\n\n int KEY_SIZE = 16;\n\n int MAC_SIZE = 12;\n\n int MIN_SERIAL_NUMB... | import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import pl.psobiech.opengr8on.client.Command;
import pl.psobiech.opengr8on.client.commands.SetKeyCommand.Request;
import pl.psobiech.opengr8on.client.commands.SetKeyCommand.Response;
import pl.psobiech.opengr8on.util.RandomUtil;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; | 2,306 | /*
* OpenGr8on, open source extensions to systems based on Grenton devices
* Copyright (C) 2023 Piotr Sobiech
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package pl.psobiech.opengr8on.client.commands;
@Execution(ExecutionMode.CONCURRENT)
class SetKeyCommandTest {
@Test
void correctRequest() {
final Request input = SetKeyCommand.request(
RandomUtil.bytes(32), RandomUtil.bytes(16), RandomUtil.bytes(16)
);
//
final Request output = SetKeyCommand.requestFromByteArray(input.asByteArray())
.get();
//
assertArrayEquals(input.asByteArray(), output.asByteArray());
}
@Test
void correctResponse() {
final Response input = SetKeyCommand.response();
//
final Response output = SetKeyCommand.responseFromByteArray(input.asByteArray())
.get();
//
assertArrayEquals(input.asByteArray(), output.asByteArray());
}
@Test
void invalid() {
byte[] buffer;
//
assertFalse(SetKeyCommand.requestFromByteArray(new byte[0]).isPresent());
assertFalse(SetKeyCommand.requestFromByteArray(new byte[100]).isPresent());
buffer = new byte[100]; | /*
* OpenGr8on, open source extensions to systems based on Grenton devices
* Copyright (C) 2023 Piotr Sobiech
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package pl.psobiech.opengr8on.client.commands;
@Execution(ExecutionMode.CONCURRENT)
class SetKeyCommandTest {
@Test
void correctRequest() {
final Request input = SetKeyCommand.request(
RandomUtil.bytes(32), RandomUtil.bytes(16), RandomUtil.bytes(16)
);
//
final Request output = SetKeyCommand.requestFromByteArray(input.asByteArray())
.get();
//
assertArrayEquals(input.asByteArray(), output.asByteArray());
}
@Test
void correctResponse() {
final Response input = SetKeyCommand.response();
//
final Response output = SetKeyCommand.responseFromByteArray(input.asByteArray())
.get();
//
assertArrayEquals(input.asByteArray(), output.asByteArray());
}
@Test
void invalid() {
byte[] buffer;
//
assertFalse(SetKeyCommand.requestFromByteArray(new byte[0]).isPresent());
assertFalse(SetKeyCommand.requestFromByteArray(new byte[100]).isPresent());
buffer = new byte[100]; | buffer[Command.RANDOM_ENCRYPTED_SIZE] = ':'; | 0 | 2023-12-23 09:56:14+00:00 | 4k |
Pigmice2733/frc-2024 | src/main/java/frc/robot/subsystems/Intake.java | [
{
"identifier": "Constants",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public final class Constants {\n public static final ShuffleboardTab DRIVER_TAB = Shuffleboard.getTab(\"Driver\");\n public static final ShuffleboardTab SWERVE_TAB = Shuffleboard.getTab(\"Drivetrain\");\n ... | import com.pigmice.frc.lib.pid_subsystem.PIDSubsystemBase;
import com.pigmice.frc.lib.shuffleboard_helper.ShuffleboardHelper;
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
import edu.wpi.first.math.trajectory.TrapezoidProfile.Constraints;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.Commands;
import frc.robot.Constants;
import frc.robot.Constants.CANConfig;
import frc.robot.Constants.IntakeConfig;
import frc.robot.Constants.IntakeConfig.IntakeState; | 3,144 | // 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.subsystems;
public class Intake extends PIDSubsystemBase {
private final CANSparkMax wheelsMotor = new CANSparkMax(CANConfig.INTAKE_WHEELS, MotorType.kBrushless);
public Intake() { | // 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.subsystems;
public class Intake extends PIDSubsystemBase {
private final CANSparkMax wheelsMotor = new CANSparkMax(CANConfig.INTAKE_WHEELS, MotorType.kBrushless);
public Intake() { | super(new CANSparkMax(CANConfig.INTAKE_PIVOT, MotorType.kBrushless), IntakeConfig.P, IntakeConfig.I, | 2 | 2023-12-30 06:06:45+00:00 | 4k |
373675032/kaka-shop | src/main/java/world/xuewei/controller/BaseController.java | [
{
"identifier": "MailClient",
"path": "src/main/java/world/xuewei/component/MailClient.java",
"snippet": "@Component\npublic class MailClient {\n\n /**\n * 邮件发送器\n */\n @Autowired\n private JavaMailSenderImpl mailSender;\n\n /**\n * 邮件发送方\n */\n @Value(\"${spring.mail.user... | import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ModelAttribute;
import world.xuewei.component.MailClient;
import world.xuewei.component.OssClient;
import world.xuewei.dto.ResponseResult;
import world.xuewei.entity.Cart;
import world.xuewei.entity.Order;
import world.xuewei.entity.User;
import world.xuewei.service.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List; | 2,188 | package world.xuewei.controller;
/**
* 基础控制器
*
* @author XUEW
*/
public class BaseController {
/**
* 注入所有的业务逻辑操作类
*/
@Autowired
protected AddressService addressService;
@Autowired
protected ClassifyService classifyService;
@Autowired
protected CartService cartService;
@Autowired
protected CollectionService collectionService;
@Autowired
protected CommodityCommentService commodityCommentService;
@Autowired
protected CommodityService commodityService;
@Autowired
protected OrderService orderService;
@Autowired
protected UserService userService;
@Autowired
protected OssClient ossClient;
/**
* 注入Http对象
*/
protected HttpServletRequest request;
protected HttpServletResponse response;
protected HttpSession session;
/**
* 当前登陆对象
*/ | package world.xuewei.controller;
/**
* 基础控制器
*
* @author XUEW
*/
public class BaseController {
/**
* 注入所有的业务逻辑操作类
*/
@Autowired
protected AddressService addressService;
@Autowired
protected ClassifyService classifyService;
@Autowired
protected CartService cartService;
@Autowired
protected CollectionService collectionService;
@Autowired
protected CommodityCommentService commodityCommentService;
@Autowired
protected CommodityService commodityService;
@Autowired
protected OrderService orderService;
@Autowired
protected UserService userService;
@Autowired
protected OssClient ossClient;
/**
* 注入Http对象
*/
protected HttpServletRequest request;
protected HttpServletResponse response;
protected HttpSession session;
/**
* 当前登陆对象
*/ | protected User loginUser; | 5 | 2023-12-27 15:17:13+00:00 | 4k |
tommyskeff/JObserve | src/main/java/dev/tommyjs/jobserve/attribute/AttributeRegistry.java | [
{
"identifier": "AttributeRegistryImpl",
"path": "src/main/java/dev/tommyjs/jobserve/attribute/impl/AttributeRegistryImpl.java",
"snippet": "public class AttributeRegistryImpl implements AttributeRegistry, Observable {\n\n private final ObserverEmitter emitter;\n private final ReadWriteLock mutex;... | import dev.tommyjs.jobserve.attribute.impl.AttributeRegistryImpl;
import dev.tommyjs.jobserve.observer.Observable;
import dev.tommyjs.jobserve.observer.key.DuplexKey;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier; | 1,858 | package dev.tommyjs.jobserve.attribute;
public interface AttributeRegistry extends Observable {
DuplexKey<AttributeKey, Object> UPDATE_ATTRIBUTE_OBSERVER = DuplexKey.register(AttributeKey.class, Object.class);
<T> @Nullable T getAttribute(@NotNull AttributeKey<T> key);
<T> @Nullable T getAttributeOrDefault(@NotNull AttributeKey<T> key, @Nullable T defaultValue);
<T> @NotNull T getAttributeOrCreateDefault(@NotNull AttributeKey<T> key, @NotNull Supplier<@NotNull T> supplier);
<T> void setAttribute(@NotNull AttributeKey<T> key, @Nullable T value);
<T> @Nullable T getAttributeOrSetDefault(@NotNull AttributeKey<T> key, @Nullable T defaultValue);
<T> T getAndUpdate(@NotNull AttributeKey<T> key, @NotNull Function<@Nullable T, @Nullable T> function);
<T> Optional<T> getAsOptional(@NotNull AttributeKey<T> key);
static AttributeRegistry create() { | package dev.tommyjs.jobserve.attribute;
public interface AttributeRegistry extends Observable {
DuplexKey<AttributeKey, Object> UPDATE_ATTRIBUTE_OBSERVER = DuplexKey.register(AttributeKey.class, Object.class);
<T> @Nullable T getAttribute(@NotNull AttributeKey<T> key);
<T> @Nullable T getAttributeOrDefault(@NotNull AttributeKey<T> key, @Nullable T defaultValue);
<T> @NotNull T getAttributeOrCreateDefault(@NotNull AttributeKey<T> key, @NotNull Supplier<@NotNull T> supplier);
<T> void setAttribute(@NotNull AttributeKey<T> key, @Nullable T value);
<T> @Nullable T getAttributeOrSetDefault(@NotNull AttributeKey<T> key, @Nullable T defaultValue);
<T> T getAndUpdate(@NotNull AttributeKey<T> key, @NotNull Function<@Nullable T, @Nullable T> function);
<T> Optional<T> getAsOptional(@NotNull AttributeKey<T> key);
static AttributeRegistry create() { | return new AttributeRegistryImpl(); | 0 | 2023-12-26 17:02:45+00:00 | 4k |
fanxiaoning/framifykit | framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/factory/LogisticsExecutorFactory.java | [
{
"identifier": "KD100Executor",
"path": "framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/KD100Executor.java",
"snippet": "@Slf4j\npublic class KD100Executor extends AbstractLogisticsExecutor<KD100Req, KD100Res>\n implements ILogisticsExecut... | import com.framifykit.starter.logistics.executor.KD100Executor;
import com.framifykit.starter.logistics.executor.constant.LogisticsTypeEnum;
import com.framifykit.starter.logistics.executor.ILogisticsExecutor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; | 2,033 | package com.framifykit.starter.logistics.executor.factory;
/**
* <p>
* 物流组件执行器工厂
* </p>
*
* @author fxn
* @since 1.0.0
**/
public class LogisticsExecutorFactory {
private static final Map<String, ILogisticsExecutor> LOGISTICS_EXECUTOR_CONTEXT = new ConcurrentHashMap<>();
static { | package com.framifykit.starter.logistics.executor.factory;
/**
* <p>
* 物流组件执行器工厂
* </p>
*
* @author fxn
* @since 1.0.0
**/
public class LogisticsExecutorFactory {
private static final Map<String, ILogisticsExecutor> LOGISTICS_EXECUTOR_CONTEXT = new ConcurrentHashMap<>();
static { | register(LogisticsTypeEnum.KD_100, new KD100Executor()); | 0 | 2023-12-31 03:48:33+00:00 | 4k |
yangpluseven/Simulate-Something | simulation/src/entities/SimuObject.java | [
{
"identifier": "Rectangle",
"path": "simulation/src/entities/painters/Rectangle.java",
"snippet": "public class Rectangle implements Painter {\n\n\tprivate double scale;\n\n\tpublic Rectangle() {\n\t\tscale = 1D;\n\t}\n\t\n\tpublic Rectangle(double scale) {\n\t\tthis.scale = scale;\n\t}\n\n\t@Override\... | import java.awt.Color;
import entities.painters.Rectangle;
import interfaces.Painter;
import simulator.GridMap; | 2,428 | package entities;
// TODO SimuObject doc
public abstract class SimuObject {
protected Painter painter; | package entities;
// TODO SimuObject doc
public abstract class SimuObject {
protected Painter painter; | protected GridMap gridMap; | 2 | 2023-12-23 13:51:12+00:00 | 4k |
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 * 输出文件... | 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,620 | 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)));
//本地规则
ruleConfig.getLocal().stream()
.filter(StrUtil::isNotBlank)
.map(e -> {
e = FileUtil.normalize(e);
if (FileUtil.isAbsolutePath(e)) {
return e;
}
return FileUtil.normalize(Constant.LOCAL_RULE_SUFFIX + File.separator + e);
}) | 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)));
//本地规则
ruleConfig.getLocal().stream()
.filter(StrUtil::isNotBlank)
.map(e -> {
e = FileUtil.normalize(e);
if (FileUtil.isAbsolutePath(e)) {
return e;
}
return FileUtil.normalize(Constant.LOCAL_RULE_SUFFIX + File.separator + e);
}) | .forEach(e -> executor.execute(new LocalRuleThread(e, typeFileMap, filter))); | 3 | 2023-12-30 04:47:07+00:00 | 4k |
bmarwell/sipper | impl/src/main/java/io/github/bmarwell/sipper/impl/internal/SipConnectionFactory.java | [
{
"identifier": "RegisteredSipConnection",
"path": "api/src/main/java/io/github/bmarwell/sipper/api/RegisteredSipConnection.java",
"snippet": "public interface RegisteredSipConnection extends SipConnection {}"
},
{
"identifier": "SipConfiguration",
"path": "api/src/main/java/io/github/bmarwe... | import org.slf4j.LoggerFactory;
import io.github.bmarwell.sipper.api.RegisteredSipConnection;
import io.github.bmarwell.sipper.api.SipConfiguration;
import io.github.bmarwell.sipper.api.SipConnection;
import io.github.bmarwell.sipper.impl.SocketInConnectionReader;
import io.github.bmarwell.sipper.impl.ip.IpUtil;
import io.github.bmarwell.sipper.impl.proto.*;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Base64;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.random.RandomGeneratorFactory;
import org.slf4j.Logger; | 3,092 | /*
* 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.internal;
public class SipConnectionFactory {
private static final Logger LOG = LoggerFactory.getLogger(SipConnectionFactory.class);
private final SipConfiguration sipConfiguration;
private final SipMessageFactory messageFactory;
public SipConnectionFactory(SipConfiguration sipConfiguration) {
this.sipConfiguration = sipConfiguration;
this.messageFactory = new SipMessageFactory(this.sipConfiguration);
}
public SipConnection build() throws IOException {
final var tagBytes = new byte[12];
final var callIdBytes = new byte[12];
RandomGeneratorFactory.getDefault().create().nextBytes(tagBytes);
RandomGeneratorFactory.getDefault().create().nextBytes(callIdBytes);
final var encoder = Base64.getEncoder().withoutPadding();
var tag = encoder.encodeToString(tagBytes).replaceAll("/", "g");
var callId = encoder.encodeToString(callIdBytes).replaceAll("/", "g");
return buildSocketSipConnection(tag, callId);
}
public RegisteredSipConnection register(SipConnection sipConnection) {
final var connectedSipConnection = (ConnectedSipConnection) sipConnection;
final var registerPreflight = this.messageFactory.getRegisterPreflight(connectedSipConnection);
CompletableFuture.supplyAsync(() -> this.registerPreflight(connectedSipConnection, registerPreflight))
.orTimeout(2_000L, TimeUnit.MILLISECONDS)
.thenAcceptAsync(
(SipAuthenticationRequest authRequest) -> doRegister(authRequest, connectedSipConnection))
.orTimeout(2_000L, TimeUnit.MILLISECONDS)
.join();
return new DefaultRegisteredSipConnection(connectedSipConnection);
}
private void doRegister(SipAuthenticationRequest authRequest, ConnectedSipConnection connectedSipConnection) {
final var msgHandler = new NotifyingSipLoginRequestHandler(
connectedSipConnection.getInReader().getMsgHandler());
final var login = this.messageFactory.getLogin(
authRequest,
connectedSipConnection,
this.sipConfiguration.getLoginUserId(),
this.sipConfiguration.getLoginPassword());
connectedSipConnection.writeAndFlush(login.message());
connectedSipConnection.setAuthorizationString(login.authorization());
msgHandler.run();
LOG.debug("Login successful");
}
public SipAuthenticationRequest registerPreflight(ConnectedSipConnection connectedSipConnection, String message) {
final var inReader = connectedSipConnection.getInReader();
connectedSipConnection.writeAndFlush(message);
final var msgHandler = new NotifyingSipIncomingAuthenticationRequestHandler(inReader.getMsgHandler());
msgHandler.run();
return msgHandler.getSipAuthenticationRequest();
}
protected ConnectedSipConnection buildSocketSipConnection(String tag, String callId) throws IOException {
var socket = createSocket();
var out = new BufferedOutputStream(socket.getOutputStream());
var onResponse = new QueueingSipIncomingMessageHandler();
var inReader = new SocketInConnectionReader(socket.getInputStream(), onResponse);
return new ConnectedSipConnection(
socket,
out,
inReader,
this.sipConfiguration.getRegistrar(),
this.sipConfiguration.getSipId(),
tag,
callId, | /*
* 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.internal;
public class SipConnectionFactory {
private static final Logger LOG = LoggerFactory.getLogger(SipConnectionFactory.class);
private final SipConfiguration sipConfiguration;
private final SipMessageFactory messageFactory;
public SipConnectionFactory(SipConfiguration sipConfiguration) {
this.sipConfiguration = sipConfiguration;
this.messageFactory = new SipMessageFactory(this.sipConfiguration);
}
public SipConnection build() throws IOException {
final var tagBytes = new byte[12];
final var callIdBytes = new byte[12];
RandomGeneratorFactory.getDefault().create().nextBytes(tagBytes);
RandomGeneratorFactory.getDefault().create().nextBytes(callIdBytes);
final var encoder = Base64.getEncoder().withoutPadding();
var tag = encoder.encodeToString(tagBytes).replaceAll("/", "g");
var callId = encoder.encodeToString(callIdBytes).replaceAll("/", "g");
return buildSocketSipConnection(tag, callId);
}
public RegisteredSipConnection register(SipConnection sipConnection) {
final var connectedSipConnection = (ConnectedSipConnection) sipConnection;
final var registerPreflight = this.messageFactory.getRegisterPreflight(connectedSipConnection);
CompletableFuture.supplyAsync(() -> this.registerPreflight(connectedSipConnection, registerPreflight))
.orTimeout(2_000L, TimeUnit.MILLISECONDS)
.thenAcceptAsync(
(SipAuthenticationRequest authRequest) -> doRegister(authRequest, connectedSipConnection))
.orTimeout(2_000L, TimeUnit.MILLISECONDS)
.join();
return new DefaultRegisteredSipConnection(connectedSipConnection);
}
private void doRegister(SipAuthenticationRequest authRequest, ConnectedSipConnection connectedSipConnection) {
final var msgHandler = new NotifyingSipLoginRequestHandler(
connectedSipConnection.getInReader().getMsgHandler());
final var login = this.messageFactory.getLogin(
authRequest,
connectedSipConnection,
this.sipConfiguration.getLoginUserId(),
this.sipConfiguration.getLoginPassword());
connectedSipConnection.writeAndFlush(login.message());
connectedSipConnection.setAuthorizationString(login.authorization());
msgHandler.run();
LOG.debug("Login successful");
}
public SipAuthenticationRequest registerPreflight(ConnectedSipConnection connectedSipConnection, String message) {
final var inReader = connectedSipConnection.getInReader();
connectedSipConnection.writeAndFlush(message);
final var msgHandler = new NotifyingSipIncomingAuthenticationRequestHandler(inReader.getMsgHandler());
msgHandler.run();
return msgHandler.getSipAuthenticationRequest();
}
protected ConnectedSipConnection buildSocketSipConnection(String tag, String callId) throws IOException {
var socket = createSocket();
var out = new BufferedOutputStream(socket.getOutputStream());
var onResponse = new QueueingSipIncomingMessageHandler();
var inReader = new SocketInConnectionReader(socket.getInputStream(), onResponse);
return new ConnectedSipConnection(
socket,
out,
inReader,
this.sipConfiguration.getRegistrar(),
this.sipConfiguration.getSipId(),
tag,
callId, | IpUtil.getPublicIpv4()); | 4 | 2023-12-28 13:13:07+00:00 | 4k |
Deenu143/GradleParser | app/src/main/java/org/deenu/gradle/script/visitors/GradleScriptVisitor.java | [
{
"identifier": "Dependency",
"path": "app/src/main/java/org/deenu/gradle/models/Dependency.java",
"snippet": "public class Dependency {\n\n private String configuration;\n private String group;\n private String name;\n private String version;\n\n public Dependency(String group, String name, String... | import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import org.codehaus.groovy.ast.CodeVisitorSupport;
import org.codehaus.groovy.ast.expr.ArgumentListExpression;
import org.codehaus.groovy.ast.expr.BinaryExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.expr.TupleExpression;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.deenu.gradle.models.Dependency;
import org.deenu.gradle.models.FlatDir;
import org.deenu.gradle.models.Include;
import org.deenu.gradle.models.Plugin;
import org.deenu.gradle.models.Repository; | 1,936 | package org.deenu.gradle.script.visitors;
public class GradleScriptVisitor extends CodeVisitorSupport {
private Stack<Boolean> blockStatementStack = new Stack<>();
private int pluginsLastLineNumber = -1;
private String pluginsConfigurationName;
private boolean inPlugins = false;
private List<Plugin> plugins = new ArrayList<>();
private int repositoriesLastLineNumber = -1;
private String repositoriesConfigurationName;
private boolean inRepositories = false;
private List<Repository> repositories = new ArrayList<>();
private int buildscriptRepositoriesLastLineNumber = -1;
private String buildscriptRepositoriesConfigurationName;
private boolean inBuildScriptRepositories = false;
private List<Repository> buildscriptRepositories = new ArrayList<>();
private int buildscriptLastLineNumber = -1;
private String buildscriptConfigurationName;
private boolean inBuildScript = false;
private int allprojectsLastLineNumber = -1;
private String allprojectsConfigurationName;
private boolean inAllProjects = false;
private int allprojectsRepositoriesLastLineNumber = -1;
private String allprojectsRepositoriesConfigurationName;
private boolean inAllProjectsRepositories = false;
private List<Repository> allprojectsRepositories = new ArrayList<>();
private String rootProjectName;
private int includeLastLineNumber = -1;
private String includeConfigurationName;
private boolean inInclude = false;
private List<Include> includes = new ArrayList<>();
private int flatDirLastLineNumber = -1;
private String flatDirConfigurationName;
private boolean inFlatDir = false;
private int allprojectsrepositoriesflatDirLastLineNumber = -1;
private String allprojectsrepositoriesflatDirConfigurationName;
private boolean inAllProjectsRepositoriesFlatDir = false;
private int flatDirdirsLastLineNumber = -1;
private String flatDirdirsConfigurationName;
private boolean inFlatDirDirs = false;
private int allprojectsrepositoriesflatDirdirsLastLineNumber = -1;
private String allprojectsrepositoriesflatDirdirsConfigurationName;
private boolean inAllProjectsRepositoriesFlatDirDirs = false;
private List<FlatDir> allprojectsrepositoriesflatDirDirs = new ArrayList<>();
private int pluginManagementLastLineNumber = -1;
private String pluginManagementConfigurationName;
private boolean inPluginManagement = false;
private int pluginManagementRepositoriesLastLineNumber = -1;
private String pluginManagementRepositoriesConfigurationName;
private boolean inPluginManagementRepositories = false;
private List<Repository> pluginManagementRepositories = new ArrayList<>();
private int dependencyResolutionManagementLastLineNumber = -1;
private String dependencyResolutionManagementConfigurationName;
private boolean inDependencyResolutionManagement = false;
private int dependencyResolutionManagementRepositoriesLastLineNumber = -1;
private String dependencyResolutionManagementRepositoriesConfigurationName;
private boolean inDependencyResolutionManagementRepositories = false;
private List<Repository> dependencyResolutionManagementRepositories = new ArrayList<>();
private int dependencyresolutionmanagementrepositoriesflatDirLastLineNumber = -1;
private String dependencyresolutionmanagementrepositoriesflatDirConfigurationName;
private boolean inDependencyResolutionManagementRepositoriesFlatDir = false;
private int dependencyresolutionmanagementrepositoriesflatDirdirsLastLineNumber = -1;
private String dependencyresolutionmanagementrepositoriesflatDirdirsConfigurationName;
private boolean inDependencyResolutionManagementRepositoriesFlatDirDirs = false;
private List<FlatDir> dependencyresolutionmanagementrepositoriesflatDirDirs = new ArrayList<>();
private int dependenciesLastLineNumber = -1;
private String dependenciesConfigurationName;
private boolean inDependencies = false; | package org.deenu.gradle.script.visitors;
public class GradleScriptVisitor extends CodeVisitorSupport {
private Stack<Boolean> blockStatementStack = new Stack<>();
private int pluginsLastLineNumber = -1;
private String pluginsConfigurationName;
private boolean inPlugins = false;
private List<Plugin> plugins = new ArrayList<>();
private int repositoriesLastLineNumber = -1;
private String repositoriesConfigurationName;
private boolean inRepositories = false;
private List<Repository> repositories = new ArrayList<>();
private int buildscriptRepositoriesLastLineNumber = -1;
private String buildscriptRepositoriesConfigurationName;
private boolean inBuildScriptRepositories = false;
private List<Repository> buildscriptRepositories = new ArrayList<>();
private int buildscriptLastLineNumber = -1;
private String buildscriptConfigurationName;
private boolean inBuildScript = false;
private int allprojectsLastLineNumber = -1;
private String allprojectsConfigurationName;
private boolean inAllProjects = false;
private int allprojectsRepositoriesLastLineNumber = -1;
private String allprojectsRepositoriesConfigurationName;
private boolean inAllProjectsRepositories = false;
private List<Repository> allprojectsRepositories = new ArrayList<>();
private String rootProjectName;
private int includeLastLineNumber = -1;
private String includeConfigurationName;
private boolean inInclude = false;
private List<Include> includes = new ArrayList<>();
private int flatDirLastLineNumber = -1;
private String flatDirConfigurationName;
private boolean inFlatDir = false;
private int allprojectsrepositoriesflatDirLastLineNumber = -1;
private String allprojectsrepositoriesflatDirConfigurationName;
private boolean inAllProjectsRepositoriesFlatDir = false;
private int flatDirdirsLastLineNumber = -1;
private String flatDirdirsConfigurationName;
private boolean inFlatDirDirs = false;
private int allprojectsrepositoriesflatDirdirsLastLineNumber = -1;
private String allprojectsrepositoriesflatDirdirsConfigurationName;
private boolean inAllProjectsRepositoriesFlatDirDirs = false;
private List<FlatDir> allprojectsrepositoriesflatDirDirs = new ArrayList<>();
private int pluginManagementLastLineNumber = -1;
private String pluginManagementConfigurationName;
private boolean inPluginManagement = false;
private int pluginManagementRepositoriesLastLineNumber = -1;
private String pluginManagementRepositoriesConfigurationName;
private boolean inPluginManagementRepositories = false;
private List<Repository> pluginManagementRepositories = new ArrayList<>();
private int dependencyResolutionManagementLastLineNumber = -1;
private String dependencyResolutionManagementConfigurationName;
private boolean inDependencyResolutionManagement = false;
private int dependencyResolutionManagementRepositoriesLastLineNumber = -1;
private String dependencyResolutionManagementRepositoriesConfigurationName;
private boolean inDependencyResolutionManagementRepositories = false;
private List<Repository> dependencyResolutionManagementRepositories = new ArrayList<>();
private int dependencyresolutionmanagementrepositoriesflatDirLastLineNumber = -1;
private String dependencyresolutionmanagementrepositoriesflatDirConfigurationName;
private boolean inDependencyResolutionManagementRepositoriesFlatDir = false;
private int dependencyresolutionmanagementrepositoriesflatDirdirsLastLineNumber = -1;
private String dependencyresolutionmanagementrepositoriesflatDirdirsConfigurationName;
private boolean inDependencyResolutionManagementRepositoriesFlatDirDirs = false;
private List<FlatDir> dependencyresolutionmanagementrepositoriesflatDirDirs = new ArrayList<>();
private int dependenciesLastLineNumber = -1;
private String dependenciesConfigurationName;
private boolean inDependencies = false; | private List<Dependency> dependencies = new ArrayList<>(); | 0 | 2023-12-27 10:10:31+00:00 | 4k |
NickReset/JavaNPM | src/main/java/social/nickrest/npm/NPM.java | [
{
"identifier": "InstalledNPMPackage",
"path": "src/main/java/social/nickrest/npm/module/InstalledNPMPackage.java",
"snippet": "@Getter\npublic class InstalledNPMPackage {\n\n private final NPM parent;\n private final File dir;\n\n private JSONObject packageJson;\n private NPMPackageData dat... | import lombok.Getter;
import lombok.Setter;
import social.nickrest.npm.module.InstalledNPMPackage;
import social.nickrest.npm.module.NPMPackage;
import java.io.File; | 1,714 | package social.nickrest.npm;
@Getter @Setter
public class NPM {
public static final String BASE_URL = "https://registry.npmjs.org";
private final File nodeModulesDir;
private NPMLogger logger;
public NPM(File nodeModulesDir) {
this.nodeModulesDir = nodeModulesDir;
this.logger = new DefualtNPMLogger();
}
| package social.nickrest.npm;
@Getter @Setter
public class NPM {
public static final String BASE_URL = "https://registry.npmjs.org";
private final File nodeModulesDir;
private NPMLogger logger;
public NPM(File nodeModulesDir) {
this.nodeModulesDir = nodeModulesDir;
this.logger = new DefualtNPMLogger();
}
| public NPMPackage getPackage(String name) { | 1 | 2023-12-22 20:46:10+00:00 | 4k |
Prototik/TheConfigLib | common/src/main/java/dev/tcl/gui/controllers/dropdown/DropdownStringControllerElement.java | [
{
"identifier": "Dimension",
"path": "common/src/main/java/dev/tcl/api/utils/Dimension.java",
"snippet": "public interface Dimension<T extends Number> {\n T x();\n T y();\n\n T width();\n T height();\n\n T xLimit();\n T yLimit();\n\n T centerX();\n T centerY();\n\n boolean isP... | import dev.tcl.api.utils.Dimension;
import dev.tcl.gui.TCLScreen;
import java.util.List; | 3,192 | package dev.tcl.gui.controllers.dropdown;
public class DropdownStringControllerElement extends AbstractDropdownControllerElement<String, String> {
private final DropdownStringController controller;
| package dev.tcl.gui.controllers.dropdown;
public class DropdownStringControllerElement extends AbstractDropdownControllerElement<String, String> {
private final DropdownStringController controller;
| public DropdownStringControllerElement(DropdownStringController control, TCLScreen screen, Dimension<Integer> dim) { | 0 | 2023-12-25 14:48:27+00:00 | 4k |
vadage/rs4j | src/main/java/space/provided/rs/option/Option.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",
"... | import space.provided.rs.error.ValueAccessError;
import space.provided.rs.ops.ArgInvokable;
import space.provided.rs.ops.ArgVoidInvokable;
import space.provided.rs.ops.Invokable;
import space.provided.rs.ops.PlainInvokable;
import space.provided.rs.result.Result;
import java.util.function.Predicate; | 1,827 | package space.provided.rs.option;
public final class Option<Some> {
private final Some some;
private final OptionType type;
private Option(Some some, OptionType type) {
this.some = some;
this.type = type;
}
public static <Some> Option<Some> some(Some some) {
return new Option<>(some, OptionType.SOME);
}
public static <Some> Option<Some> none() {
return new Option<>(null, OptionType.NONE);
}
public boolean isSome() {
return type.equals(OptionType.SOME);
}
public boolean isNone() {
return !isSome();
}
public boolean isSomeAnd(ArgInvokable<Some, Boolean> invokable) {
return switch (type) {
case NONE -> false;
case SOME -> invokable.invoke(some);
};
}
public Some unwrap() throws ValueAccessError {
if (!isSome()) {
throw new ValueAccessError("Called `unwrap` on %1$s Option.".formatted(type));
}
return some;
}
public Some unwrapOr(Some fallback) {
return switch (type) {
case SOME -> some;
case NONE -> fallback;
};
}
public <Mapped> Option<Mapped> map(ArgInvokable<Some, Mapped> invokable) {
return switch (type) {
case SOME -> Option.some(invokable.invoke(some));
case NONE -> Option.none();
};
}
public <Mapped> Mapped mapOr(Mapped fallback, ArgInvokable<Some, Mapped> invokable) {
return switch (type) {
case SOME -> invokable.invoke(some);
case NONE -> fallback;
};
}
public <Mapped> Mapped mapOrElse(PlainInvokable<Mapped> fallback, ArgInvokable<Some, Mapped> invokable) {
return switch (type) {
case SOME -> invokable.invoke(some);
case NONE -> fallback.invoke();
};
}
| package space.provided.rs.option;
public final class Option<Some> {
private final Some some;
private final OptionType type;
private Option(Some some, OptionType type) {
this.some = some;
this.type = type;
}
public static <Some> Option<Some> some(Some some) {
return new Option<>(some, OptionType.SOME);
}
public static <Some> Option<Some> none() {
return new Option<>(null, OptionType.NONE);
}
public boolean isSome() {
return type.equals(OptionType.SOME);
}
public boolean isNone() {
return !isSome();
}
public boolean isSomeAnd(ArgInvokable<Some, Boolean> invokable) {
return switch (type) {
case NONE -> false;
case SOME -> invokable.invoke(some);
};
}
public Some unwrap() throws ValueAccessError {
if (!isSome()) {
throw new ValueAccessError("Called `unwrap` on %1$s Option.".formatted(type));
}
return some;
}
public Some unwrapOr(Some fallback) {
return switch (type) {
case SOME -> some;
case NONE -> fallback;
};
}
public <Mapped> Option<Mapped> map(ArgInvokable<Some, Mapped> invokable) {
return switch (type) {
case SOME -> Option.some(invokable.invoke(some));
case NONE -> Option.none();
};
}
public <Mapped> Mapped mapOr(Mapped fallback, ArgInvokable<Some, Mapped> invokable) {
return switch (type) {
case SOME -> invokable.invoke(some);
case NONE -> fallback;
};
}
public <Mapped> Mapped mapOrElse(PlainInvokable<Mapped> fallback, ArgInvokable<Some, Mapped> invokable) {
return switch (type) {
case SOME -> invokable.invoke(some);
case NONE -> fallback.invoke();
};
}
| public <Err> Result<Some, Err> okOr(Err error) { | 5 | 2023-12-27 15:33:17+00:00 | 4k |
wicksonZhang/Spring-Cloud | 08-spring-cloud-hystrix-payment-8000/src/main/java/cn/wickson/cloud/hystrix/payment/service/impl/PaymentServiceImpl.java | [
{
"identifier": "ResultCodeEnum",
"path": "01-spring-cloud-common/src/main/java/cn/wickson/cloud/common/enums/ResultCodeEnum.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic enum ResultCodeEnum {\n\n /**\n * 成功状态码:1\n */\n SUCCESS(1, \"成功\"),\n /**\n * 失败状态码\n */\n FAI... | import cn.hutool.core.util.IdUtil;
import cn.wickson.cloud.common.enums.ResultCodeEnum;
import cn.wickson.cloud.common.exception.UserOperationException;
import cn.wickson.cloud.common.utils.ResultUtil;
import cn.wickson.cloud.hystrix.payment.service.IPaymentService;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit; | 1,991 | package cn.wickson.cloud.hystrix.payment.service.impl;
/**
* 支付服务-应用服务实现类
*
* @author ZhangZiHeng
* @date 2024-01-08
*/
@Service
public class PaymentServiceImpl implements IPaymentService {
/**
* 成功
*
* @return String
*/
@Override | package cn.wickson.cloud.hystrix.payment.service.impl;
/**
* 支付服务-应用服务实现类
*
* @author ZhangZiHeng
* @date 2024-01-08
*/
@Service
public class PaymentServiceImpl implements IPaymentService {
/**
* 成功
*
* @return String
*/
@Override | public ResultUtil paymentBySuccess() { | 2 | 2023-12-27 09:42:02+00:00 | 4k |
behnamnasehi/playsho | app/src/main/java/com/playsho/android/base/BaseBottomSheet.java | [
{
"identifier": "SessionStorage",
"path": "app/src/main/java/com/playsho/android/db/SessionStorage.java",
"snippet": "public class SessionStorage {\n private final SharedPreferences pref;\n private final SharedPreferences.Editor editor;\n\n // Name of the shared preference file\n private fin... | import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.playsho.android.R;
import com.playsho.android.db.SessionStorage;
import com.playsho.android.utils.Validator; | 3,062 | package com.playsho.android.base;
public abstract class BaseBottomSheet<B extends ViewDataBinding> extends BottomSheetDialogFragment {
protected B binding;
private String origin;
protected BottomSheetStatusCallback bottomSheetStatusCallback;
protected BottomSheetResultCallback bottomSheetResultCallback;
public String getClassName(){
return this.getClass().getSimpleName();
}
public interface BottomSheetStatusCallback {
void onBottomSheetShow();
void onBottomSheetDismiss();
}
public interface BottomSheetResultCallback {
void onBottomSheetProcessSuccess(String data);
void onBottomSheetProcessFail(String data);
}
/**
* Get the resource ID for the layout of the fragment.
*
* @return the layout resource ID
*/
protected abstract int getLayoutResourceId();
/**
* Initialize views in the fragment.
*/
protected abstract void initView();
/**
* Constructor for the BaseBottomSheet class.
* It sets the origin of the fragment based on the parent fragment or the activity if there is no parent fragment.
*/
public BaseBottomSheet() {
Fragment parentFragment = getParentFragment();
setOrigin( parentFragment != null ?
parentFragment.getClass().getSimpleName() :
(getActivity() != null ? getActivity().getClass().getSimpleName() : "")
);
}
/**
* Set the BottomSheetCallback for the fragment.
*
* @param bottomSheetCallback the BottomSheetCallback to set
*/
public void setStatusCallback(BottomSheetStatusCallback bottomSheetCallback) {
this.bottomSheetStatusCallback = bottomSheetCallback;
}
public void setResultCallback(BottomSheetResultCallback callback) {
this.bottomSheetResultCallback = callback;
}
/**
* Set the origin of the fragment.
*
* @param origin the origin of the fragment
*/
protected void setOrigin(String origin) {
this.origin = origin;
}
/**
* Get the origin of the fragment.
*
* @return the origin of the fragment
*/
protected String getOrigin() {
return this.origin;
}
/**
* Inflate the view for the fragment.
*
* @param inflater the layout inflater
* @param container the view group container
* @param savedInstanceState the saved instance state
* @return the inflated view
*/
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, getLayoutResourceId(), container, false);
return binding.getRoot();
}
/**
* Called when the view has been created.
*
* @param view the created view
* @param savedInstanceState the saved instance state
*/
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initView();
}
/**
* Get the session storage instance.
*
* @return the session storage instance
*/
protected SessionStorage getSessionStorage() {
return ApplicationLoader.getSessionStorage();
}
/**
* Show the fragment.
*/
public void show() {
show(getParentFragmentManager(), getOrigin());
}
/**
* Get the custom theme for the bottom sheet dialog.
*
* @return the custom theme resource ID
*/
@Override
public int getTheme() {
return R.style.Base_Theme_Playsho;
}
@Override
public void onDismiss(@NonNull DialogInterface dialog) {
super.onDismiss(dialog); | package com.playsho.android.base;
public abstract class BaseBottomSheet<B extends ViewDataBinding> extends BottomSheetDialogFragment {
protected B binding;
private String origin;
protected BottomSheetStatusCallback bottomSheetStatusCallback;
protected BottomSheetResultCallback bottomSheetResultCallback;
public String getClassName(){
return this.getClass().getSimpleName();
}
public interface BottomSheetStatusCallback {
void onBottomSheetShow();
void onBottomSheetDismiss();
}
public interface BottomSheetResultCallback {
void onBottomSheetProcessSuccess(String data);
void onBottomSheetProcessFail(String data);
}
/**
* Get the resource ID for the layout of the fragment.
*
* @return the layout resource ID
*/
protected abstract int getLayoutResourceId();
/**
* Initialize views in the fragment.
*/
protected abstract void initView();
/**
* Constructor for the BaseBottomSheet class.
* It sets the origin of the fragment based on the parent fragment or the activity if there is no parent fragment.
*/
public BaseBottomSheet() {
Fragment parentFragment = getParentFragment();
setOrigin( parentFragment != null ?
parentFragment.getClass().getSimpleName() :
(getActivity() != null ? getActivity().getClass().getSimpleName() : "")
);
}
/**
* Set the BottomSheetCallback for the fragment.
*
* @param bottomSheetCallback the BottomSheetCallback to set
*/
public void setStatusCallback(BottomSheetStatusCallback bottomSheetCallback) {
this.bottomSheetStatusCallback = bottomSheetCallback;
}
public void setResultCallback(BottomSheetResultCallback callback) {
this.bottomSheetResultCallback = callback;
}
/**
* Set the origin of the fragment.
*
* @param origin the origin of the fragment
*/
protected void setOrigin(String origin) {
this.origin = origin;
}
/**
* Get the origin of the fragment.
*
* @return the origin of the fragment
*/
protected String getOrigin() {
return this.origin;
}
/**
* Inflate the view for the fragment.
*
* @param inflater the layout inflater
* @param container the view group container
* @param savedInstanceState the saved instance state
* @return the inflated view
*/
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, getLayoutResourceId(), container, false);
return binding.getRoot();
}
/**
* Called when the view has been created.
*
* @param view the created view
* @param savedInstanceState the saved instance state
*/
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initView();
}
/**
* Get the session storage instance.
*
* @return the session storage instance
*/
protected SessionStorage getSessionStorage() {
return ApplicationLoader.getSessionStorage();
}
/**
* Show the fragment.
*/
public void show() {
show(getParentFragmentManager(), getOrigin());
}
/**
* Get the custom theme for the bottom sheet dialog.
*
* @return the custom theme resource ID
*/
@Override
public int getTheme() {
return R.style.Base_Theme_Playsho;
}
@Override
public void onDismiss(@NonNull DialogInterface dialog) {
super.onDismiss(dialog); | if (!Validator.isNull(this.bottomSheetStatusCallback)) this.bottomSheetStatusCallback.onBottomSheetDismiss(); | 1 | 2023-12-26 08:14:29+00:00 | 4k |
lunasaw/voglander | voglander-manager/src/main/java/io/github/lunasaw/voglander/manager/async/AsyncManager.java | [
{
"identifier": "SpringUtils",
"path": "voglander-manager/src/main/java/io/github/lunasaw/voglander/manager/spring/SpringUtils.java",
"snippet": "@Component\npublic final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware {\n /**\n * Spring应用上下文环境\n */\n private... | import io.github.lunasaw.voglander.manager.spring.SpringUtils;
import io.github.lunasaw.voglander.common.util.Threads;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; | 1,690 | package io.github.lunasaw.voglander.manager.async;
/**
* 异步任务管理器
*
* @author ruoyi
*/
public class AsyncManager
{
/**
* 操作延迟10毫秒
*/
private final int OPERATE_DELAY_TIME = 10;
/**
* 异步操作任务调度线程池
*/ | package io.github.lunasaw.voglander.manager.async;
/**
* 异步任务管理器
*
* @author ruoyi
*/
public class AsyncManager
{
/**
* 操作延迟10毫秒
*/
private final int OPERATE_DELAY_TIME = 10;
/**
* 异步操作任务调度线程池
*/ | private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService"); | 0 | 2023-12-27 07:28:18+00:00 | 4k |
GrailStack/grail-codegen | src/main/java/com/itgrail/grail/codegen/components/db/database/AbstractDatabase.java | [
{
"identifier": "DbModelConverter",
"path": "src/main/java/com/itgrail/grail/codegen/components/db/common/DbModelConverter.java",
"snippet": "public class DbModelConverter {\n\n public static String columnNameToField(String columnName) {\n return CamelCaseFormat.getCamelCaseString(columnName, ... | import com.google.common.collect.Lists;
import com.itgrail.grail.codegen.components.db.common.DbModelConverter;
import com.itgrail.grail.codegen.components.db.enums.TableMetaDataEnum;
import com.itgrail.grail.codegen.components.db.exceptions.DbException;
import com.itgrail.grail.codegen.components.db.model.Column;
import com.itgrail.grail.codegen.components.db.model.PrimaryKeyColumn;
import com.itgrail.grail.codegen.components.db.model.Table;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.lang3.StringUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors; | 2,564 | package com.itgrail.grail.codegen.components.db.database;
@Slf4j
public abstract class AbstractDatabase implements Database {
protected Connection connection;
protected DBProperties dbProperties;
public AbstractDatabase(DBProperties dbProperties) {
this.dbProperties = dbProperties;
}
@Override
public List<String> getAllTableNames() {
return getTableNames("%");
}
@Override
public List<String> getTableNames(String tableNamePattern) throws DbException {
tableNamePattern = StringUtils.isBlank(tableNamePattern) ? "%" : tableNamePattern;
try {
ResultSet resultSet = connection.getMetaData()
.getTables(getDbName(), null, tableNamePattern, new String[]{"TABLE"});
List<String> tables = new ArrayList<String>();
while (resultSet.next()) {
String tableName = resultSet.getString(TableMetaDataEnum.TABLE_NAME.getValue());
tables.add(tableName);
}
return tables;
} catch (Exception ex) {
String msg = String.format("查询数据库%s中表名称失败,tableNamePattern=%s", getDbName(), tableNamePattern);
log.error(msg, ex);
throw new DbException(msg);
}
}
@Override
public List<Table> getAllTables() throws DbException {
return getTables("%");
}
@Override
public List<Table> getTables(String tableNamePattern) throws DbException {
try {
List<String> tableNames = getTableNames(tableNamePattern);
if (CollectionUtils.isEmpty(tableNames)) {
return Lists.newArrayList();
}
List<Table> tables = new ArrayList<Table>();
for (String tableName : tableNames) {
tables.add(getTable(tableName));
}
return tables;
} catch (Exception ex) {
String msg = String.format("查询数据库%s中表失败,tableNamePattern=%s", getDbName(), tableNamePattern);
log.error(msg, ex);
throw new DbException(msg);
}
}
public List<Table> getTables(List<String> tableNames) throws DbException {
if (CollectionUtils.isEmpty(tableNames)) {
return Lists.newArrayList();
}
List<Table> tables = Lists.newArrayList();
for (String tableName : tableNames) {
tables.add(getTable(tableName));
}
return tables;
}
@Override
public Table getTable(String tableName) {
try {
ResultSet resultSet = getConnection().getMetaData().getTables(getDbName(), null, tableName, new String[]{"TABLE"});
if (resultSet.next()) {
Table table = new Table();
table.setTableName(tableName);
table.setDoName(DbModelConverter.tableNameToDoName(tableName));
table.setDaoName(DbModelConverter.tableNameToDaoName(tableName));
table.setComment(getTableComment(tableName));
table.setColumns(getColumns(tableName));
table.setPrimaryKeys(retrievePrimaryKeyColumns(table.getColumns()));
table.setComment(getTableComment(tableName));
return table;
} else {
throw new DbException(String.format("数据库%s中找不到表%s", getDbName(), tableName));
}
} catch (SQLException ex) {
String msg = String.format("查询数据库%s中表%s信息失败", getDbName(), tableName);
log.error(msg, ex);
throw new DbException(msg);
}
}
| package com.itgrail.grail.codegen.components.db.database;
@Slf4j
public abstract class AbstractDatabase implements Database {
protected Connection connection;
protected DBProperties dbProperties;
public AbstractDatabase(DBProperties dbProperties) {
this.dbProperties = dbProperties;
}
@Override
public List<String> getAllTableNames() {
return getTableNames("%");
}
@Override
public List<String> getTableNames(String tableNamePattern) throws DbException {
tableNamePattern = StringUtils.isBlank(tableNamePattern) ? "%" : tableNamePattern;
try {
ResultSet resultSet = connection.getMetaData()
.getTables(getDbName(), null, tableNamePattern, new String[]{"TABLE"});
List<String> tables = new ArrayList<String>();
while (resultSet.next()) {
String tableName = resultSet.getString(TableMetaDataEnum.TABLE_NAME.getValue());
tables.add(tableName);
}
return tables;
} catch (Exception ex) {
String msg = String.format("查询数据库%s中表名称失败,tableNamePattern=%s", getDbName(), tableNamePattern);
log.error(msg, ex);
throw new DbException(msg);
}
}
@Override
public List<Table> getAllTables() throws DbException {
return getTables("%");
}
@Override
public List<Table> getTables(String tableNamePattern) throws DbException {
try {
List<String> tableNames = getTableNames(tableNamePattern);
if (CollectionUtils.isEmpty(tableNames)) {
return Lists.newArrayList();
}
List<Table> tables = new ArrayList<Table>();
for (String tableName : tableNames) {
tables.add(getTable(tableName));
}
return tables;
} catch (Exception ex) {
String msg = String.format("查询数据库%s中表失败,tableNamePattern=%s", getDbName(), tableNamePattern);
log.error(msg, ex);
throw new DbException(msg);
}
}
public List<Table> getTables(List<String> tableNames) throws DbException {
if (CollectionUtils.isEmpty(tableNames)) {
return Lists.newArrayList();
}
List<Table> tables = Lists.newArrayList();
for (String tableName : tableNames) {
tables.add(getTable(tableName));
}
return tables;
}
@Override
public Table getTable(String tableName) {
try {
ResultSet resultSet = getConnection().getMetaData().getTables(getDbName(), null, tableName, new String[]{"TABLE"});
if (resultSet.next()) {
Table table = new Table();
table.setTableName(tableName);
table.setDoName(DbModelConverter.tableNameToDoName(tableName));
table.setDaoName(DbModelConverter.tableNameToDaoName(tableName));
table.setComment(getTableComment(tableName));
table.setColumns(getColumns(tableName));
table.setPrimaryKeys(retrievePrimaryKeyColumns(table.getColumns()));
table.setComment(getTableComment(tableName));
return table;
} else {
throw new DbException(String.format("数据库%s中找不到表%s", getDbName(), tableName));
}
} catch (SQLException ex) {
String msg = String.format("查询数据库%s中表%s信息失败", getDbName(), tableName);
log.error(msg, ex);
throw new DbException(msg);
}
}
| protected List<PrimaryKeyColumn> retrievePrimaryKeyColumns(List<Column> columns) { | 4 | 2023-12-30 15:32:55+00:00 | 4k |
Man2Dev/N-Queen | lib/jfreechart-1.0.19/tests/org/jfree/chart/plot/dial/DialPlotTest.java | [
{
"identifier": "TestUtilities",
"path": "lib/jfreechart-1.0.19/tests/org/jfree/chart/TestUtilities.java",
"snippet": "public class TestUtilities {\n\n /**\n * Returns <code>true</code> if the collections contains any object that\n * is an instance of the specified class, and <code>false</cod... | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertNotNull;
import java.awt.Color;
import java.awt.GradientPaint;
import org.jfree.chart.TestUtilities;
import org.jfree.chart.event.PlotChangeEvent;
import org.jfree.chart.event.PlotChangeListener;
import org.junit.Test; | 1,793 | /* ===========================================================
* 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.]
*
* -----------------
* DialPlotTest.java
* -----------------
* (C) Copyright 2006-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 03-Nov-2006 : Version 1 (DG);
*
*/
package org.jfree.chart.plot.dial;
/**
* Tests for the {@link DialPlot} class.
*/
public class DialPlotTest implements PlotChangeListener {
/** The last plot change event received. */
private PlotChangeEvent lastEvent;
/**
* Records the last plot change event received.
*
* @param event the event.
*/
@Override
public void plotChanged(PlotChangeEvent event) {
this.lastEvent = event;
}
/**
* Confirm that the equals method can distinguish all the required fields.
*/
@Test
public void testEquals() {
DialPlot p1 = new DialPlot();
DialPlot p2 = new DialPlot();
assertTrue(p1.equals(p2));
// background
p1.setBackground(new DialBackground(Color.green));
assertFalse(p1.equals(p2));
p2.setBackground(new DialBackground(Color.green));
assertTrue(p1.equals(p2));
p1.setBackground(null);
assertFalse(p1.equals(p2));
p2.setBackground(null);
assertTrue(p1.equals(p2));
// dial cap
DialCap cap1 = new DialCap();
cap1.setFillPaint(Color.red);
p1.setCap(cap1);
assertFalse(p1.equals(p2));
DialCap cap2 = new DialCap();
cap2.setFillPaint(Color.red);
p2.setCap(cap2);
assertTrue(p1.equals(p2));
p1.setCap(null);
assertFalse(p1.equals(p2));
p2.setCap(null);
assertTrue(p1.equals(p2));
// frame
StandardDialFrame f1 = new StandardDialFrame();
f1.setBackgroundPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f,
4.0f, Color.white));
p1.setDialFrame(f1);
assertFalse(p1.equals(p2));
StandardDialFrame f2 = new StandardDialFrame();
f2.setBackgroundPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f,
4.0f, Color.white));
p2.setDialFrame(f2);
assertTrue(p1.equals(p2));
// view
p1.setView(0.2, 0.0, 0.8, 1.0);
assertFalse(p1.equals(p2));
p2.setView(0.2, 0.0, 0.8, 1.0);
assertTrue(p1.equals(p2));
// layer
p1.addLayer(new StandardDialScale());
assertFalse(p1.equals(p2));
p2.addLayer(new StandardDialScale());
assertTrue(p1.equals(p2));
}
/**
* Two objects that are equal are required to return the same hashCode.
*/
@Test
public void testHashCode() {
DialPlot p1 = new DialPlot();
DialPlot p2 = new DialPlot();
assertTrue(p1.equals(p2));
int h1 = p1.hashCode();
int h2 = p2.hashCode();
assertEquals(h1, h2);
}
/**
* Confirm that cloning works.
*/
@Test
public void testCloning() throws CloneNotSupportedException {
DialPlot p1 = new DialPlot();
DialPlot p2 = (DialPlot) p1.clone();
assertTrue(p1 != p2);
assertTrue(p1.getClass() == p2.getClass());
assertTrue(p1.equals(p2));
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() {
DialPlot p1 = new DialPlot(); | /* ===========================================================
* 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.]
*
* -----------------
* DialPlotTest.java
* -----------------
* (C) Copyright 2006-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 03-Nov-2006 : Version 1 (DG);
*
*/
package org.jfree.chart.plot.dial;
/**
* Tests for the {@link DialPlot} class.
*/
public class DialPlotTest implements PlotChangeListener {
/** The last plot change event received. */
private PlotChangeEvent lastEvent;
/**
* Records the last plot change event received.
*
* @param event the event.
*/
@Override
public void plotChanged(PlotChangeEvent event) {
this.lastEvent = event;
}
/**
* Confirm that the equals method can distinguish all the required fields.
*/
@Test
public void testEquals() {
DialPlot p1 = new DialPlot();
DialPlot p2 = new DialPlot();
assertTrue(p1.equals(p2));
// background
p1.setBackground(new DialBackground(Color.green));
assertFalse(p1.equals(p2));
p2.setBackground(new DialBackground(Color.green));
assertTrue(p1.equals(p2));
p1.setBackground(null);
assertFalse(p1.equals(p2));
p2.setBackground(null);
assertTrue(p1.equals(p2));
// dial cap
DialCap cap1 = new DialCap();
cap1.setFillPaint(Color.red);
p1.setCap(cap1);
assertFalse(p1.equals(p2));
DialCap cap2 = new DialCap();
cap2.setFillPaint(Color.red);
p2.setCap(cap2);
assertTrue(p1.equals(p2));
p1.setCap(null);
assertFalse(p1.equals(p2));
p2.setCap(null);
assertTrue(p1.equals(p2));
// frame
StandardDialFrame f1 = new StandardDialFrame();
f1.setBackgroundPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f,
4.0f, Color.white));
p1.setDialFrame(f1);
assertFalse(p1.equals(p2));
StandardDialFrame f2 = new StandardDialFrame();
f2.setBackgroundPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f,
4.0f, Color.white));
p2.setDialFrame(f2);
assertTrue(p1.equals(p2));
// view
p1.setView(0.2, 0.0, 0.8, 1.0);
assertFalse(p1.equals(p2));
p2.setView(0.2, 0.0, 0.8, 1.0);
assertTrue(p1.equals(p2));
// layer
p1.addLayer(new StandardDialScale());
assertFalse(p1.equals(p2));
p2.addLayer(new StandardDialScale());
assertTrue(p1.equals(p2));
}
/**
* Two objects that are equal are required to return the same hashCode.
*/
@Test
public void testHashCode() {
DialPlot p1 = new DialPlot();
DialPlot p2 = new DialPlot();
assertTrue(p1.equals(p2));
int h1 = p1.hashCode();
int h2 = p2.hashCode();
assertEquals(h1, h2);
}
/**
* Confirm that cloning works.
*/
@Test
public void testCloning() throws CloneNotSupportedException {
DialPlot p1 = new DialPlot();
DialPlot p2 = (DialPlot) p1.clone();
assertTrue(p1 != p2);
assertTrue(p1.getClass() == p2.getClass());
assertTrue(p1.equals(p2));
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() {
DialPlot p1 = new DialPlot(); | DialPlot p2 = (DialPlot) TestUtilities.serialised(p1); | 0 | 2023-12-24 12:36:47+00:00 | 4k |
viceice/verbrauchsapp | app/src/main/java/de/anipe/verbrauchsapp/tasks/UpdateGDriveCarList.java | [
{
"identifier": "TabbedImportActivity",
"path": "app/src/main/java/de/anipe/verbrauchsapp/TabbedImportActivity.java",
"snippet": "public class TabbedImportActivity extends AppCompatActivity {\n\n private ImportPagerAdapter pagerAdapter;\n private ViewPager viewPager;\n\n private int loader = 0;... | import android.content.IntentSender;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.Metadata;
import com.google.android.gms.drive.MetadataBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import de.anipe.verbrauchsapp.TabbedImportActivity;
import de.anipe.verbrauchsapp.fragments.GDriveImportFragment;
import de.anipe.verbrauchsapp.util.ResetableCountDownLatch;
import static com.google.android.gms.common.api.GoogleApiClient.Builder;
import static com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import static com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import static com.google.android.gms.drive.DriveApi.MetadataBufferResult; | 2,979 | package de.anipe.verbrauchsapp.tasks;
public class UpdateGDriveCarList extends AsyncTask<Void, Void, Void> {
private GDriveImportFragment mCon;
private int dataSets = 0;
public HashMap<String, String> fileMapping;
private ArrayList<String> filesList;
private GoogleApiClient mClient;
public UpdateGDriveCarList(GDriveImportFragment con) {
mCon = con;
Builder builder = new Builder(con.getActivity())
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE);
mClient = builder.build();
}
@Override
protected Void doInBackground(Void... params) {
Log.d("UpdateGDriveCarList", "Listing gdrive files.");
final ResetableCountDownLatch latch = new ResetableCountDownLatch(1);
mClient.registerConnectionCallbacks(new ConnectionCallbacks() {
@Override
public void onConnectionSuspended(int cause) {
}
@Override
public void onConnected(Bundle arg0) {
latch.countDown();
}
});
mClient.registerConnectionFailedListener(result -> {
try {
result.startResolutionForResult(mCon.getActivity(), 1);
} catch (IntentSender.SendIntentException e) {
Log.e("UpdateGDriveCarList", "Exception while starting resolution activity", e);
}
latch.countDown();
});
mClient.connect();
try {
latch.await();
} catch (InterruptedException e) {
return null;
}
if (!mClient.isConnected()) {
return null;
}
try {
filesList = new ArrayList<>();
fileMapping = new HashMap<>();
MetadataBufferResult result = Drive.DriveApi.getRootFolder(mClient)
.listChildren(mClient).await();
if (!result.getStatus().isSuccess())
{
Log.w("UpdateGDriveCarList", result.getStatus().getStatusMessage());
return null;
}
MetadataBuffer buffer = result.getMetadataBuffer();
try {
for (int i = 0; i < buffer.getCount(); i++) {
Metadata meta = buffer.get(i);
String title = meta.getTitle();
if (!meta.isTrashed() && !(title == null)) {
filesList.add(title);
fileMapping.put(title, meta.getDriveId().encodeToString());
dataSets++;
}
}
} catch (Exception e) {
Log.e("UpdateGDriveCarList", "Error listing files", e);
} finally {
buffer.release();
}
Collections.sort(filesList);
return null;
} finally {
mClient.disconnect();
}
}
@Override
protected void onPostExecute(Void nope) {
| package de.anipe.verbrauchsapp.tasks;
public class UpdateGDriveCarList extends AsyncTask<Void, Void, Void> {
private GDriveImportFragment mCon;
private int dataSets = 0;
public HashMap<String, String> fileMapping;
private ArrayList<String> filesList;
private GoogleApiClient mClient;
public UpdateGDriveCarList(GDriveImportFragment con) {
mCon = con;
Builder builder = new Builder(con.getActivity())
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE);
mClient = builder.build();
}
@Override
protected Void doInBackground(Void... params) {
Log.d("UpdateGDriveCarList", "Listing gdrive files.");
final ResetableCountDownLatch latch = new ResetableCountDownLatch(1);
mClient.registerConnectionCallbacks(new ConnectionCallbacks() {
@Override
public void onConnectionSuspended(int cause) {
}
@Override
public void onConnected(Bundle arg0) {
latch.countDown();
}
});
mClient.registerConnectionFailedListener(result -> {
try {
result.startResolutionForResult(mCon.getActivity(), 1);
} catch (IntentSender.SendIntentException e) {
Log.e("UpdateGDriveCarList", "Exception while starting resolution activity", e);
}
latch.countDown();
});
mClient.connect();
try {
latch.await();
} catch (InterruptedException e) {
return null;
}
if (!mClient.isConnected()) {
return null;
}
try {
filesList = new ArrayList<>();
fileMapping = new HashMap<>();
MetadataBufferResult result = Drive.DriveApi.getRootFolder(mClient)
.listChildren(mClient).await();
if (!result.getStatus().isSuccess())
{
Log.w("UpdateGDriveCarList", result.getStatus().getStatusMessage());
return null;
}
MetadataBuffer buffer = result.getMetadataBuffer();
try {
for (int i = 0; i < buffer.getCount(); i++) {
Metadata meta = buffer.get(i);
String title = meta.getTitle();
if (!meta.isTrashed() && !(title == null)) {
filesList.add(title);
fileMapping.put(title, meta.getDriveId().encodeToString());
dataSets++;
}
}
} catch (Exception e) {
Log.e("UpdateGDriveCarList", "Error listing files", e);
} finally {
buffer.release();
}
Collections.sort(filesList);
return null;
} finally {
mClient.disconnect();
}
}
@Override
protected void onPostExecute(Void nope) {
| ((TabbedImportActivity) mCon.getActivity()).endRefreshFragment(); | 0 | 2023-12-28 12:33:52+00:00 | 4k |
PSButlerII/SqlScriptGen | src/main/java/com/recondev/userinteraction/UserInteraction.java | [
{
"identifier": "Enums",
"path": "src/main/java/com/recondev/helpers/Enums.java",
"snippet": "public class Enums {\n\n public enum DatabaseType {\n POSTGRESQL(\"PostgreSQL\"),\n MYSQL(\"MySQL\"),\n MONGODB(\"MongoDB\");\n\n private final String type;\n\n DatabaseTyp... | import com.recondev.helpers.Enums;
import com.recondev.interfaces.DatabaseConstraintType;
import java.util.*; | 2,602 | package com.recondev.userinteraction;
public class UserInteraction {
// private String getConstraintString(int constraintCount) {
//
// //TODO: Make this method more generic so it can be used for other databases
// String constraintSQL = null;
// for (int i = 0; i < constraintCount; i++) {
// System.out.println("Choose constraint type:");
//
// // print out the constraint types
// for (int j = 0; j < Enums.PostgreSQLConstraintType.values().length; j++) {
// System.out.println(j + ": " + Enums.PostgreSQLConstraintType.values()[j].getConstraintType());
// }
//
// int constraintTypeIndex = Integer.parseInt(scanner.nextLine());
// Enums.PostgreSQLConstraintType constraintType = Enums.PostgreSQLConstraintType.fromInt(constraintTypeIndex);
//
// System.out.println("Enter column name for constraint:");
// String columnName = scanner.nextLine();
//
// String additionalInput = "";
// if (constraintType.requiresAdditionalInput()) {
// if (constraintType == Enums.PostgreSQLConstraintType.FOREIGN_KEY) {
// System.out.println("Enter table name for the constraint:");
// String tableName = scanner.nextLine();
//
// System.out.println("Enter column name for the constraint:");
// String foreignKeyColumnName = scanner.nextLine();
//
// additionalInput = tableName + "(" + foreignKeyColumnName + ")";
// } else if (constraintType == Enums.PostgreSQLConstraintType.CHECK) {
// System.out.println("Enter check condition (e.g., column_name > 5):");
// additionalInput = scanner.nextLine();
// }
//
// // Assuming other constraint types might need a generic input
// else if (constraintType == Enums.PostgreSQLConstraintType.UNIQUE ||
// constraintType == Enums.PostgreSQLConstraintType.PRIMARY_KEY /*||
// constraintType == Enums.PostgreSQLConstraintType.EXCLUSION*/) {
// System.out.println("Enter additional input for the constraint:");
// additionalInput = scanner.nextLine();
// }
// // Handle any other constraints that might need additional input
// else {
// System.out.println("Enter additional input for the constraint:");
// additionalInput = scanner.nextLine();
// }
// }
// constraintSQL = constraintType.getConstraintSQL(columnName, additionalInput);
// }
// return constraintSQL;
// }
private final Scanner scanner = new Scanner(System.in);
| package com.recondev.userinteraction;
public class UserInteraction {
// private String getConstraintString(int constraintCount) {
//
// //TODO: Make this method more generic so it can be used for other databases
// String constraintSQL = null;
// for (int i = 0; i < constraintCount; i++) {
// System.out.println("Choose constraint type:");
//
// // print out the constraint types
// for (int j = 0; j < Enums.PostgreSQLConstraintType.values().length; j++) {
// System.out.println(j + ": " + Enums.PostgreSQLConstraintType.values()[j].getConstraintType());
// }
//
// int constraintTypeIndex = Integer.parseInt(scanner.nextLine());
// Enums.PostgreSQLConstraintType constraintType = Enums.PostgreSQLConstraintType.fromInt(constraintTypeIndex);
//
// System.out.println("Enter column name for constraint:");
// String columnName = scanner.nextLine();
//
// String additionalInput = "";
// if (constraintType.requiresAdditionalInput()) {
// if (constraintType == Enums.PostgreSQLConstraintType.FOREIGN_KEY) {
// System.out.println("Enter table name for the constraint:");
// String tableName = scanner.nextLine();
//
// System.out.println("Enter column name for the constraint:");
// String foreignKeyColumnName = scanner.nextLine();
//
// additionalInput = tableName + "(" + foreignKeyColumnName + ")";
// } else if (constraintType == Enums.PostgreSQLConstraintType.CHECK) {
// System.out.println("Enter check condition (e.g., column_name > 5):");
// additionalInput = scanner.nextLine();
// }
//
// // Assuming other constraint types might need a generic input
// else if (constraintType == Enums.PostgreSQLConstraintType.UNIQUE ||
// constraintType == Enums.PostgreSQLConstraintType.PRIMARY_KEY /*||
// constraintType == Enums.PostgreSQLConstraintType.EXCLUSION*/) {
// System.out.println("Enter additional input for the constraint:");
// additionalInput = scanner.nextLine();
// }
// // Handle any other constraints that might need additional input
// else {
// System.out.println("Enter additional input for the constraint:");
// additionalInput = scanner.nextLine();
// }
// }
// constraintSQL = constraintType.getConstraintSQL(columnName, additionalInput);
// }
// return constraintSQL;
// }
private final Scanner scanner = new Scanner(System.in);
| public Enums.DatabaseType getDatabaseType() { | 0 | 2023-12-29 01:53:43+00:00 | 4k |
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 v... | 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; | 2,101 | 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();
}
/**
* Salvar um novo usuário no banco de dados
*
* @param Usuarios sendo as informações do usuário
* @return boolean sendo true no caso de sucesso, e false caso contrário
*/
public boolean salvar(Usuarios usuario) {
String sql = "insert into usuarios (nome,email,login,senha) values (?, ?, ?, ?)";
try {
PreparedStatement insert = connection.prepareStatement(sql);
insert.setString(1, usuario.getNome());
insert.setString(2, usuario.getEmail());
insert.setString(3, usuario.getLogin());
insert.setString(4, usuario.getSenha());
int retorno = insert.executeUpdate();
connection.commit(); /* Salvar no banco de dados */
if (retorno > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
try {
connection.rollback(); /* Reverter a operação no BD */
} catch (SQLException sqle) {
sqle.printStackTrace();
}
e.printStackTrace();
return false;
}
}
/**
* Alterar um usuário no banco de dados
*
* @param Usuarios sendo as informações do usuário
* @return boolean sendo true no caso de sucesso, e false caso contrário
*/
public boolean alterar(Usuarios usuario) {
String sql = "update usuarios set nome = ? , email = ? , login = ? , senha = ? where id = ?";
try {
PreparedStatement update = connection.prepareStatement(sql);
update.setString(1, usuario.getNome());
update.setString(2, usuario.getEmail());
update.setString(3, usuario.getLogin());
update.setString(4, usuario.getSenha());
update.setLong(5, usuario.getId());
int retorno = update.executeUpdate();
connection.commit(); /* Salvar no banco de dados */
if (retorno > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
try {
connection.rollback(); /* Reverter a operação no BD */
} catch (SQLException sqle) {
sqle.printStackTrace();
}
e.printStackTrace();
return false;
}
}
/**
* Excluir um usuário do banco de dados
*
* @param Long id sendo o id do usuário
* @return boolean sendo true no caso de sucesso, e false caso contrário
*/
public boolean excluir(Long id) {
String sql = "delete from usuarios where id = ?";
try {
PreparedStatement delete = connection.prepareStatement(sql);
delete.setLong(1, id);
int retorno = delete.executeUpdate();
connection.commit(); /* Salvar no banco de dados */
if (retorno > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
try {
connection.rollback(); /* Reverter a operação no BD */
} catch (SQLException sqle) {
sqle.printStackTrace();
}
e.printStackTrace();
return false;
}
}
/**
* Listar todos os usuários do banco de dados
*
* @return List<Usuarios> sendo a lista de usuários
*/
public List<Usuarios> listar() {
List<Usuarios> lista = new ArrayList<Usuarios>();
String sql = "select * from usuarios order by id";
try {
PreparedStatement select = connection.prepareStatement(sql);
ResultSet resultado = select.executeQuery();
while (resultado.next()) {
Usuarios usuario = new Usuarios();
usuario.setId(resultado.getLong("id"));
usuario.setNome(resultado.getString("nome"));
usuario.setEmail(resultado.getString("email"));
usuario.setLogin(resultado.getString("login"));
usuario.setSenha(resultado.getString("senha"));
lista.add(usuario);
}
return lista;
} catch (Exception e) {
e.printStackTrace();
return lista;
}
}
/**
* Listar todos os usuários do banco de dados com seus telefones
*
* @return List<UsuarioTelefone> sendo a lista de usuários
*/ | 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();
}
/**
* Salvar um novo usuário no banco de dados
*
* @param Usuarios sendo as informações do usuário
* @return boolean sendo true no caso de sucesso, e false caso contrário
*/
public boolean salvar(Usuarios usuario) {
String sql = "insert into usuarios (nome,email,login,senha) values (?, ?, ?, ?)";
try {
PreparedStatement insert = connection.prepareStatement(sql);
insert.setString(1, usuario.getNome());
insert.setString(2, usuario.getEmail());
insert.setString(3, usuario.getLogin());
insert.setString(4, usuario.getSenha());
int retorno = insert.executeUpdate();
connection.commit(); /* Salvar no banco de dados */
if (retorno > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
try {
connection.rollback(); /* Reverter a operação no BD */
} catch (SQLException sqle) {
sqle.printStackTrace();
}
e.printStackTrace();
return false;
}
}
/**
* Alterar um usuário no banco de dados
*
* @param Usuarios sendo as informações do usuário
* @return boolean sendo true no caso de sucesso, e false caso contrário
*/
public boolean alterar(Usuarios usuario) {
String sql = "update usuarios set nome = ? , email = ? , login = ? , senha = ? where id = ?";
try {
PreparedStatement update = connection.prepareStatement(sql);
update.setString(1, usuario.getNome());
update.setString(2, usuario.getEmail());
update.setString(3, usuario.getLogin());
update.setString(4, usuario.getSenha());
update.setLong(5, usuario.getId());
int retorno = update.executeUpdate();
connection.commit(); /* Salvar no banco de dados */
if (retorno > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
try {
connection.rollback(); /* Reverter a operação no BD */
} catch (SQLException sqle) {
sqle.printStackTrace();
}
e.printStackTrace();
return false;
}
}
/**
* Excluir um usuário do banco de dados
*
* @param Long id sendo o id do usuário
* @return boolean sendo true no caso de sucesso, e false caso contrário
*/
public boolean excluir(Long id) {
String sql = "delete from usuarios where id = ?";
try {
PreparedStatement delete = connection.prepareStatement(sql);
delete.setLong(1, id);
int retorno = delete.executeUpdate();
connection.commit(); /* Salvar no banco de dados */
if (retorno > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
try {
connection.rollback(); /* Reverter a operação no BD */
} catch (SQLException sqle) {
sqle.printStackTrace();
}
e.printStackTrace();
return false;
}
}
/**
* Listar todos os usuários do banco de dados
*
* @return List<Usuarios> sendo a lista de usuários
*/
public List<Usuarios> listar() {
List<Usuarios> lista = new ArrayList<Usuarios>();
String sql = "select * from usuarios order by id";
try {
PreparedStatement select = connection.prepareStatement(sql);
ResultSet resultado = select.executeQuery();
while (resultado.next()) {
Usuarios usuario = new Usuarios();
usuario.setId(resultado.getLong("id"));
usuario.setNome(resultado.getString("nome"));
usuario.setEmail(resultado.getString("email"));
usuario.setLogin(resultado.getString("login"));
usuario.setSenha(resultado.getString("senha"));
lista.add(usuario);
}
return lista;
} catch (Exception e) {
e.printStackTrace();
return lista;
}
}
/**
* Listar todos os usuários do banco de dados com seus telefones
*
* @return List<UsuarioTelefone> sendo a lista de usuários
*/ | public List<UsuarioTelefone> listarComTelefones() { | 1 | 2023-12-30 14:50:31+00:00 | 4k |
JoshiCodes/NewLabyAPI | src/main/java/de/joshicodes/newlabyapi/NewLabyPlugin.java | [
{
"identifier": "LabyModAPI",
"path": "src/main/java/de/joshicodes/newlabyapi/api/LabyModAPI.java",
"snippet": "public class LabyModAPI {\n\n private static final HashMap<Player, LabyModPlayer> labyModPlayers = new HashMap<>();\n\n private static boolean updateExistingPlayersOnJoin = false;\n\n ... | import de.joshicodes.newlabyapi.api.LabyModAPI;
import de.joshicodes.newlabyapi.listener.ConfigListener;
import de.joshicodes.newlabyapi.listener.LabyPluginMessageListener;
import de.joshicodes.newlabyapi.listener.PlayerListener;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.JoinConfiguration;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.IOException; | 1,997 | package de.joshicodes.newlabyapi;
public final class NewLabyPlugin extends JavaPlugin {
public static final Component PREFIX = MiniMessage.miniMessage().deserialize(
"<b><gradient:#227eb8:#53bbfb>NewLabyAPI</gradient></b> <gray>»</gray>"
);
private static NewLabyPlugin instance;
@Override
public void onEnable() {
instance = this;
if (!getDataFolder().exists())
getDataFolder().mkdir();
saveDefaultConfig();
LabyModAPI.init(this);
getServer().getMessenger().registerIncomingPluginChannel(this, "labymod3:main", new LabyPluginMessageListener());
getServer().getMessenger().registerOutgoingPluginChannel(this, "labymod3:main");
PluginManager pluginManager = getServer().getPluginManager(); | package de.joshicodes.newlabyapi;
public final class NewLabyPlugin extends JavaPlugin {
public static final Component PREFIX = MiniMessage.miniMessage().deserialize(
"<b><gradient:#227eb8:#53bbfb>NewLabyAPI</gradient></b> <gray>»</gray>"
);
private static NewLabyPlugin instance;
@Override
public void onEnable() {
instance = this;
if (!getDataFolder().exists())
getDataFolder().mkdir();
saveDefaultConfig();
LabyModAPI.init(this);
getServer().getMessenger().registerIncomingPluginChannel(this, "labymod3:main", new LabyPluginMessageListener());
getServer().getMessenger().registerOutgoingPluginChannel(this, "labymod3:main");
PluginManager pluginManager = getServer().getPluginManager(); | pluginManager.registerEvents(new PlayerListener(), this); | 3 | 2023-12-24 15:00:08+00:00 | 4k |
1752597830/admin-common | qf-admin/back/admin-init-main/src/main/java/com/qf/web/controller/SysUserController.java | [
{
"identifier": "BaseController",
"path": "qf-admin/back/admin-init-main/src/main/java/com/qf/common/core/controller/BaseController.java",
"snippet": "public class BaseController {\n\n /* 当前记录起始索引 */\n public static final String PAGE_NUM = \"pageNum\";\n\n /* 每页显示记录数 */\n public static final... | import com.qf.common.core.controller.BaseController;
import com.qf.common.core.page.PageResult;
import com.qf.common.utils.BaseResponse;
import com.qf.web.domain.dto.UserPage;
import com.qf.web.domain.vo.UserForm;
import com.qf.web.domain.vo.UserPageVo;
import com.qf.web.domain.vo.UserVo;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import com.qf.web.service.SysUserService;
import java.util.List; | 2,589 | package com.qf.web.controller;
/**
* @author : sin
* @date : 2023/12/13 12:54
* @Description :
*/
@RestController
@Tag(name = "02.用户接口")
@RequestMapping("/users")
@Slf4j
public class SysUserController extends BaseController {
@Resource
SysUserService sysUserService;
/**
* 根据uid获取用户
*/
@Schema(title = "根据uid获取用户")
@GetMapping("/{userId}/form")
public BaseResponse getUserByUid(@Parameter(description = "用户ID") @PathVariable Long userId) {
UserForm form = sysUserService.getUserFormByUid(userId);
return BaseResponse.success(form);
}
/**
* 获取当前用户信息
*/
@Schema(title = "获取当前用户信息")
@GetMapping("/me")
public BaseResponse getUserInfo() {
UserVo userVo = sysUserService.getUserInfo();
System.out.println(userVo);
return BaseResponse.success(userVo);
}
/**
* 获取分页用户
*/
@Schema(title = "获取分页用户")
@GetMapping("/page")
public BaseResponse getPage(UserPage userPage) {
startPage();
List<UserPageVo> userPageVoList = sysUserService.getPage(userPage); | package com.qf.web.controller;
/**
* @author : sin
* @date : 2023/12/13 12:54
* @Description :
*/
@RestController
@Tag(name = "02.用户接口")
@RequestMapping("/users")
@Slf4j
public class SysUserController extends BaseController {
@Resource
SysUserService sysUserService;
/**
* 根据uid获取用户
*/
@Schema(title = "根据uid获取用户")
@GetMapping("/{userId}/form")
public BaseResponse getUserByUid(@Parameter(description = "用户ID") @PathVariable Long userId) {
UserForm form = sysUserService.getUserFormByUid(userId);
return BaseResponse.success(form);
}
/**
* 获取当前用户信息
*/
@Schema(title = "获取当前用户信息")
@GetMapping("/me")
public BaseResponse getUserInfo() {
UserVo userVo = sysUserService.getUserInfo();
System.out.println(userVo);
return BaseResponse.success(userVo);
}
/**
* 获取分页用户
*/
@Schema(title = "获取分页用户")
@GetMapping("/page")
public BaseResponse getPage(UserPage userPage) {
startPage();
List<UserPageVo> userPageVoList = sysUserService.getPage(userPage); | PageResult pageResult = getData(userPageVoList); | 1 | 2023-12-30 13:42:53+00:00 | 4k |
JIGerss/Salus | salus-web/src/main/java/team/glhf/salus/controller/PlaceController.java | [
{
"identifier": "CommentReq",
"path": "salus-pojo/src/main/java/team/glhf/salus/dto/place/CommentReq.java",
"snippet": "@Data\r\n@Builder\r\npublic class CommentReq implements Serializable {\r\n\r\n @Null(message = \"cannot use userId to access\")\r\n private String userId;\r\n\r\n @NotBlank(me... | import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import team.glhf.salus.annotation.JwtVerify;
import team.glhf.salus.dto.place.CommentReq;
import team.glhf.salus.dto.place.CreateReq;
import team.glhf.salus.dto.place.CreateRes;
import team.glhf.salus.dto.place.PointReq;
import team.glhf.salus.result.Result;
import team.glhf.salus.service.PlaceService;
| 2,000 | package team.glhf.salus.controller;
/**
* Place controller for web application
*
* @author Felix
* @since 2023/11/21
*/
@RestController
@RequestMapping("/place")
public class PlaceController {
private final PlaceService placeService;
public PlaceController(PlaceService placeService) {
this.placeService = placeService;
}
@PostMapping("/create")
public Result<CreateRes> createPlace(CreateReq createReq) {
return Result.okResult(placeService.createPlace(createReq));
}
@JwtVerify
@PostMapping("/point")
| package team.glhf.salus.controller;
/**
* Place controller for web application
*
* @author Felix
* @since 2023/11/21
*/
@RestController
@RequestMapping("/place")
public class PlaceController {
private final PlaceService placeService;
public PlaceController(PlaceService placeService) {
this.placeService = placeService;
}
@PostMapping("/create")
public Result<CreateRes> createPlace(CreateReq createReq) {
return Result.okResult(placeService.createPlace(createReq));
}
@JwtVerify
@PostMapping("/point")
| public Result<Object> pointPlace(@RequestBody @Validated PointReq pointReq) {
| 3 | 2023-12-23 15:03:37+00:00 | 4k |
swsm/proxynet | proxynet-server/src/main/java/com/swsm/proxynet/server/handler/ServerClientChannelHandler.java | [
{
"identifier": "Constants",
"path": "proxynet-common/src/main/java/com/swsm/proxynet/common/Constants.java",
"snippet": "public class Constants {\n\n public static final AttributeKey<Channel> NEXT_CHANNEL = AttributeKey.newInstance(\"nxt_channel\");\n public static final AttributeKey<String> VISI... | import com.alibaba.fastjson.JSON;
import com.swsm.proxynet.common.Constants;
import com.swsm.proxynet.common.cache.ChannelRelationCache;
import com.swsm.proxynet.common.model.CommandMessage;
import com.swsm.proxynet.common.model.ConnectRespMessage;
import com.swsm.proxynet.common.model.ProxyNetMessage;
import com.swsm.proxynet.server.config.ProxyConfig;
import com.swsm.proxynet.server.util.ConfigUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.util.List;
import lombok.extern.slf4j.Slf4j; | 3,259 | package com.swsm.proxynet.server.handler;
/**
* @author liujie
* @date 2023-04-15
*/
@Slf4j
public class ServerClientChannelHandler extends SimpleChannelInboundHandler<ProxyNetMessage> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, ProxyNetMessage proxyNetMessage) throws Exception {
log.info("收到客户端的请求:{}", proxyNetMessage);
if (proxyNetMessage.getType() == ProxyNetMessage.COMMAND) {
executeCommand(channelHandlerContext, proxyNetMessage);
} else if (proxyNetMessage.getType() == ProxyNetMessage.CONNECT_RESP) {
executeConnectResp(proxyNetMessage, channelHandlerContext);
}
}
private void executeConnectResp(ProxyNetMessage proxyNetMessage, ChannelHandlerContext channelHandlerContext) {
Channel clientChannel = channelHandlerContext.channel();
ConnectRespMessage connectRespMessage = JSON.parseObject(proxyNetMessage.getInfo(), ConnectRespMessage.class);
boolean isSuccess = connectRespMessage.getResult();
log.info("客户端与目标服务连接结果={}", connectRespMessage);
if (!isSuccess) {
log.info("客户端与目标服务连接没有成功,关闭所有连接此目标服务的channel", connectRespMessage);
List<Channel> userChannelList = ChannelRelationCache.getUserChannelList(clientChannel.id());
for (Channel channel : userChannelList) {
channel.close();
}
return;
}
Channel userChannel = ChannelRelationCache.getUserChannel(connectRespMessage.getUserId());
if (userChannel == null) {
log.warn("用户id={}的channel已经断开!", connectRespMessage.getUserId());
return;
}
clientChannel.attr(Constants.VISITOR_ID).set(connectRespMessage.getUserId());
clientChannel.attr(Constants.NEXT_CHANNEL).set(userChannel);
userChannel.attr(Constants.NEXT_CHANNEL).set(clientChannel);
userChannel.config().setAutoRead(true);
}
private void executeCommand(ChannelHandlerContext channelHandlerContext, ProxyNetMessage proxyNetMessage) {
Channel clientChannel = channelHandlerContext.channel();
String info = proxyNetMessage.getInfo();
CommandMessage commandMessage = JSON.parseObject(info, CommandMessage.class);
if (commandMessage.getType().equals(ProxyNetMessage.COMMAND_AUTH)) { | package com.swsm.proxynet.server.handler;
/**
* @author liujie
* @date 2023-04-15
*/
@Slf4j
public class ServerClientChannelHandler extends SimpleChannelInboundHandler<ProxyNetMessage> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, ProxyNetMessage proxyNetMessage) throws Exception {
log.info("收到客户端的请求:{}", proxyNetMessage);
if (proxyNetMessage.getType() == ProxyNetMessage.COMMAND) {
executeCommand(channelHandlerContext, proxyNetMessage);
} else if (proxyNetMessage.getType() == ProxyNetMessage.CONNECT_RESP) {
executeConnectResp(proxyNetMessage, channelHandlerContext);
}
}
private void executeConnectResp(ProxyNetMessage proxyNetMessage, ChannelHandlerContext channelHandlerContext) {
Channel clientChannel = channelHandlerContext.channel();
ConnectRespMessage connectRespMessage = JSON.parseObject(proxyNetMessage.getInfo(), ConnectRespMessage.class);
boolean isSuccess = connectRespMessage.getResult();
log.info("客户端与目标服务连接结果={}", connectRespMessage);
if (!isSuccess) {
log.info("客户端与目标服务连接没有成功,关闭所有连接此目标服务的channel", connectRespMessage);
List<Channel> userChannelList = ChannelRelationCache.getUserChannelList(clientChannel.id());
for (Channel channel : userChannelList) {
channel.close();
}
return;
}
Channel userChannel = ChannelRelationCache.getUserChannel(connectRespMessage.getUserId());
if (userChannel == null) {
log.warn("用户id={}的channel已经断开!", connectRespMessage.getUserId());
return;
}
clientChannel.attr(Constants.VISITOR_ID).set(connectRespMessage.getUserId());
clientChannel.attr(Constants.NEXT_CHANNEL).set(userChannel);
userChannel.attr(Constants.NEXT_CHANNEL).set(clientChannel);
userChannel.config().setAutoRead(true);
}
private void executeCommand(ChannelHandlerContext channelHandlerContext, ProxyNetMessage proxyNetMessage) {
Channel clientChannel = channelHandlerContext.channel();
String info = proxyNetMessage.getInfo();
CommandMessage commandMessage = JSON.parseObject(info, CommandMessage.class);
if (commandMessage.getType().equals(ProxyNetMessage.COMMAND_AUTH)) { | for (ProxyConfig.ProxyInfo proxyInfo : ConfigUtil.getProxyInfos()) { | 6 | 2023-12-25 03:25:38+00:00 | 4k |
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 ... | 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,627 | 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());
assertEquals("[]",new ArrayBuilder(Collections.emptyList()).build());
assertEquals("[]",new ArrayBuilder(Stream.empty()).build());
assertEquals("[1,2,3]",new ArrayBuilder(1,2,3).build());
assertEquals("[\"1\",\"2\",\"3\"]",new ArrayBuilder("1","2","3").build()); | 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());
assertEquals("[]",new ArrayBuilder(Collections.emptyList()).build());
assertEquals("[]",new ArrayBuilder(Stream.empty()).build());
assertEquals("[1,2,3]",new ArrayBuilder(1,2,3).build());
assertEquals("[\"1\",\"2\",\"3\"]",new ArrayBuilder("1","2","3").build()); | final ObjectBuilder object=new ObjectBuilder(); | 1 | 2023-12-24 19:29:49+00:00 | 4k |
Trodev-IT/ScanHub | app/src/main/java/com/trodev/scanhub/fragments/LocationFragment.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... | import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
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.adapters.LocationAdapter;
import com.trodev.scanhub.models.EmailModel;
import com.trodev.scanhub.models.LocationModel;
import java.util.ArrayList; | 1,977 | package com.trodev.scanhub.fragments;
public class LocationFragment extends Fragment {
private RecyclerView recyclerView;
DatabaseReference reference;
ArrayList<LocationModel> list; | package com.trodev.scanhub.fragments;
public class LocationFragment extends Fragment {
private RecyclerView recyclerView;
DatabaseReference reference;
ArrayList<LocationModel> list; | LocationAdapter adapter; | 1 | 2023-12-26 05:10:38+00:00 | 4k |
DMSAranda/backend-usersapp | src/main/java/com/dms/backend/usersapp/backendusersapp/auth/SpringSecurityConfig.java | [
{
"identifier": "JwtAuthenticationFilter",
"path": "src/main/java/com/dms/backend/usersapp/backendusersapp/auth/filters/JwtAuthenticationFilter.java",
"snippet": "public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter{\n\n private AuthenticationManager authenticationManager... | import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import com.dms.backend.usersapp.backendusersapp.auth.filters.JwtAuthenticationFilter;
import com.dms.backend.usersapp.backendusersapp.auth.filters.JwtValidationFilter; | 1,602 | package com.dms.backend.usersapp.backendusersapp.auth;
//import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
@Configuration
public class SpringSecurityConfig {
@Autowired
private AuthenticationConfiguration authenticationConfiguration;
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
AuthenticationManager authenticationManager() throws Exception{
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(authRules -> authRules
.requestMatchers(HttpMethod.GET, "/users", "/users/page/{page}").permitAll()
.requestMatchers(HttpMethod.GET, "/users/{id}").hasAnyRole("USER", "ADMIN")
.requestMatchers(HttpMethod.POST, "/users").hasRole( "ADMIN")
.requestMatchers(HttpMethod.PUT, "/users/{id}").hasRole( "ADMIN")
.requestMatchers(HttpMethod.DELETE, "/users/{id}").hasRole( "ADMIN")
.anyRequest().authenticated()
) | package com.dms.backend.usersapp.backendusersapp.auth;
//import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
@Configuration
public class SpringSecurityConfig {
@Autowired
private AuthenticationConfiguration authenticationConfiguration;
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
AuthenticationManager authenticationManager() throws Exception{
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(authRules -> authRules
.requestMatchers(HttpMethod.GET, "/users", "/users/page/{page}").permitAll()
.requestMatchers(HttpMethod.GET, "/users/{id}").hasAnyRole("USER", "ADMIN")
.requestMatchers(HttpMethod.POST, "/users").hasRole( "ADMIN")
.requestMatchers(HttpMethod.PUT, "/users/{id}").hasRole( "ADMIN")
.requestMatchers(HttpMethod.DELETE, "/users/{id}").hasRole( "ADMIN")
.anyRequest().authenticated()
) | .addFilter(new JwtAuthenticationFilter(authenticationConfiguration.getAuthenticationManager())) | 0 | 2023-12-29 15:55:27+00:00 | 4k |
singuuu/java-spring-api | src/main/java/com/singu/api/services/AuthenticationService.java | [
{
"identifier": "Token",
"path": "src/main/java/com/singu/api/domains/Token.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\npublic class Token {\n\n @Id\n @GeneratedValue\n public Integer id;\n\n @Column(unique = true)\n public String token;\n\n @E... | import com.fasterxml.jackson.databind.ObjectMapper;
import com.singu.api.domains.Token;
import com.singu.api.domains.TokenType;
import com.singu.api.domains.User;
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.repositories.TokenRepository;
import com.singu.api.repositories.UserRepository;
import com.singu.api.security.JwtService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.io.IOException; | 1,629 | package com.singu.api.services;
@Service
@RequiredArgsConstructor
public class AuthenticationService {
private final UserRepository repository;
private final TokenRepository tokenRepository;
private final PasswordEncoder passwordEncoder; | package com.singu.api.services;
@Service
@RequiredArgsConstructor
public class AuthenticationService {
private final UserRepository repository;
private final TokenRepository tokenRepository;
private final PasswordEncoder passwordEncoder; | private final JwtService jwtService; | 8 | 2023-12-28 17:32:16+00:00 | 4k |
vnlemanhthanh/sfg-spring-6-webapp | src/main/java/com/vnlemanhthanh/spring6webapp/bootstrap/BootstrapData.java | [
{
"identifier": "Author",
"path": "src/main/java/com/vnlemanhthanh/spring6webapp/domain/Author.java",
"snippet": "@Entity\npublic class Author {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n private String firstName;\n private String lastName;\n\n @Many... | import com.vnlemanhthanh.spring6webapp.domain.Author;
import com.vnlemanhthanh.spring6webapp.domain.Book;
import com.vnlemanhthanh.spring6webapp.domain.Publisher;
import com.vnlemanhthanh.spring6webapp.repositories.AuthorRepository;
import com.vnlemanhthanh.spring6webapp.repositories.BookRepository;
import com.vnlemanhthanh.spring6webapp.repositories.PublisherRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component; | 2,140 | /*
* Copyright (c) 2023. vnlemanhthanh.com
*/
package com.vnlemanhthanh.spring6webapp.bootstrap;
@Component
public class BootstrapData implements CommandLineRunner {
private final AuthorRepository authorRepository;
private final BookRepository bookRepository;
private final PublisherRepository publisherRepository;
public BootstrapData(AuthorRepository authorRepository,
BookRepository bookRepository,
PublisherRepository publisherRepository) {
this.authorRepository = authorRepository;
this.bookRepository = bookRepository;
this.publisherRepository = publisherRepository;
}
@Override
public void run(String... args) throws Exception {
Author eric = new Author();
eric.setFirstName("Eric");
eric.setLastName("Evans");
Book ddd = new Book();
ddd.setTitle("Domain Driven Design");
ddd.setIsbn("123456");
Author ericSaved = authorRepository.save(eric);
Book dddSaved = bookRepository.save(ddd);
Author rod = new Author();
rod.setFirstName("Rod");
rod.setLastName("Johnson");
Book noEJB = new Book();
noEJB.setTitle("J2EE Development without EJB");
noEJB.setIsbn("54757585");
Author rodSaved = authorRepository.save(rod);
Book noEJBSaved = bookRepository.save(noEJB);
ericSaved.getBooks().add(dddSaved);
rodSaved.getBooks().add(noEJBSaved);
dddSaved.getAuthors().add(ericSaved);
noEJBSaved.getAuthors().add(rodSaved);
| /*
* Copyright (c) 2023. vnlemanhthanh.com
*/
package com.vnlemanhthanh.spring6webapp.bootstrap;
@Component
public class BootstrapData implements CommandLineRunner {
private final AuthorRepository authorRepository;
private final BookRepository bookRepository;
private final PublisherRepository publisherRepository;
public BootstrapData(AuthorRepository authorRepository,
BookRepository bookRepository,
PublisherRepository publisherRepository) {
this.authorRepository = authorRepository;
this.bookRepository = bookRepository;
this.publisherRepository = publisherRepository;
}
@Override
public void run(String... args) throws Exception {
Author eric = new Author();
eric.setFirstName("Eric");
eric.setLastName("Evans");
Book ddd = new Book();
ddd.setTitle("Domain Driven Design");
ddd.setIsbn("123456");
Author ericSaved = authorRepository.save(eric);
Book dddSaved = bookRepository.save(ddd);
Author rod = new Author();
rod.setFirstName("Rod");
rod.setLastName("Johnson");
Book noEJB = new Book();
noEJB.setTitle("J2EE Development without EJB");
noEJB.setIsbn("54757585");
Author rodSaved = authorRepository.save(rod);
Book noEJBSaved = bookRepository.save(noEJB);
ericSaved.getBooks().add(dddSaved);
rodSaved.getBooks().add(noEJBSaved);
dddSaved.getAuthors().add(ericSaved);
noEJBSaved.getAuthors().add(rodSaved);
| Publisher publisher = new Publisher(); | 2 | 2023-12-25 07:31:22+00:00 | 4k |
Deepennn/NetAPP | src/main/java/com/netapp/device/router/RouteTable.java | [
{
"identifier": "Iface",
"path": "src/main/java/com/netapp/device/Iface.java",
"snippet": "public class Iface\n{\n protected String iName; // 接口名称\n protected String macAddress; // MAC地址\n protected BlockingQueue<Ethernet> inputQueue; // 输入队列\n protected BlockingQueue<Ethernet> o... | import com.netapp.device.Iface;
import com.netapp.packet.IPv4;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 2,413 | package com.netapp.device.router;
public class RouteTable {
private List<RouteEntry> entries;
public RouteTable() { this.entries = new LinkedList<RouteEntry>(); }
/**
* 向路由表中插入一条条目。
* @param dstIp 目标 IP
* @param gwIp 网关 IP
* @param maskIp 子网掩码
* @param iface 通过该接口发送数据包以到达目标或网关
*/ | package com.netapp.device.router;
public class RouteTable {
private List<RouteEntry> entries;
public RouteTable() { this.entries = new LinkedList<RouteEntry>(); }
/**
* 向路由表中插入一条条目。
* @param dstIp 目标 IP
* @param gwIp 网关 IP
* @param maskIp 子网掩码
* @param iface 通过该接口发送数据包以到达目标或网关
*/ | public void insert(String dstIp, String gwIp, String maskIp, Iface iface) { | 0 | 2023-12-23 13:03:07+00:00 | 4k |
jordqubbe/Extras | src/main/java/dev/jordgubbe/extras/library/Item.java | [
{
"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 ... | import dev.jordgubbe.extras.utils.ColorUtils;
import dev.jordgubbe.extras.utils.SkullCreator;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import java.util.List; | 3,314 | package dev.jordgubbe.extras.library;
public class Item {
/**
* Creates a new ItemStack
* @param name - Name of the new item
* @param mat - Material of the new item (Don't use skulls with textures here)
* @param amount - Amount of the new item
* @param lore - Lore (if any) of the new item
* @return - The newly created ItemStack
*/
public static ItemStack createItem(String name, Material mat, int amount, List<String> lore) {
ItemStack item = new ItemStack(mat, amount);
ItemMeta meta = item.getItemMeta();
assert meta != null; | package dev.jordgubbe.extras.library;
public class Item {
/**
* Creates a new ItemStack
* @param name - Name of the new item
* @param mat - Material of the new item (Don't use skulls with textures here)
* @param amount - Amount of the new item
* @param lore - Lore (if any) of the new item
* @return - The newly created ItemStack
*/
public static ItemStack createItem(String name, Material mat, int amount, List<String> lore) {
ItemStack item = new ItemStack(mat, amount);
ItemMeta meta = item.getItemMeta();
assert meta != null; | meta.setDisplayName(ColorUtils.format(name)); | 0 | 2023-12-27 06:37:11+00:00 | 4k |
LogDeArgentina/server | src/main/java/me/drpuc/lda/service/impl/QsoServiceImpl.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": "Qso",
"path": "src/... | import lombok.RequiredArgsConstructor;
import me.drpuc.lda.config.CallsignValidator;
import me.drpuc.lda.dto.request.radio.CreateQsoDto;
import me.drpuc.lda.dto.request.radio.StationDto;
import me.drpuc.lda.entity.Qso;
import me.drpuc.lda.entity.Station;
import me.drpuc.lda.entity.User;
import me.drpuc.lda.radio.QsoConfirmation;
import me.drpuc.lda.radio.RadioStatus;
import me.drpuc.lda.repository.QsoRepository;
import me.drpuc.lda.repository.StationRepository;
import me.drpuc.lda.service.QsoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import java.time.temporal.ChronoUnit;
import java.util.*; | 1,903 | package me.drpuc.lda.service.impl;
@Service
@RequiredArgsConstructor
public class QsoServiceImpl implements QsoService {
@Value("${qso.validation.threshold.minutes}")
private short threshold;
private final QsoRepository qsoRepository;
private final StationRepository stationRepository;
private final CallsignValidator callsignValidator;
public String create(User fromUser, CreateQsoDto qsoDto) {
if (!fromUser.isVerified()) {
throw new AccessDeniedException("not verified");
}
var timestamp = qsoDto.timestamp();
var fromStationDtoUnverified = qsoDto.sentFromStation();
var toStationDto = qsoDto.sentToStation();
var radioStatus = qsoDto.radioStatus();
var comment = qsoDto.comment() == null ? "" : qsoDto.comment();
if (invalidStationDto(fromStationDtoUnverified)
|| invalidStationDto(toStationDto)) {
throw new IllegalArgumentException("invalid station");
}
if (radioStatus.rst() < 0 || radioStatus.rst() > 599) {
throw new IllegalArgumentException("invalid rst");
}
var fromStation = stationRepository.findByCallsign(fromStationDtoUnverified.callsign()).orElseThrow(
() -> new IllegalArgumentException("invalid station")
);
if (!fromUser.getStations().contains(fromStation)) {
throw new IllegalArgumentException("invalid station");
}
var toStation = stationRepository.findByCallsign(toStationDto.callsign()).orElseGet( | package me.drpuc.lda.service.impl;
@Service
@RequiredArgsConstructor
public class QsoServiceImpl implements QsoService {
@Value("${qso.validation.threshold.minutes}")
private short threshold;
private final QsoRepository qsoRepository;
private final StationRepository stationRepository;
private final CallsignValidator callsignValidator;
public String create(User fromUser, CreateQsoDto qsoDto) {
if (!fromUser.isVerified()) {
throw new AccessDeniedException("not verified");
}
var timestamp = qsoDto.timestamp();
var fromStationDtoUnverified = qsoDto.sentFromStation();
var toStationDto = qsoDto.sentToStation();
var radioStatus = qsoDto.radioStatus();
var comment = qsoDto.comment() == null ? "" : qsoDto.comment();
if (invalidStationDto(fromStationDtoUnverified)
|| invalidStationDto(toStationDto)) {
throw new IllegalArgumentException("invalid station");
}
if (radioStatus.rst() < 0 || radioStatus.rst() > 599) {
throw new IllegalArgumentException("invalid rst");
}
var fromStation = stationRepository.findByCallsign(fromStationDtoUnverified.callsign()).orElseThrow(
() -> new IllegalArgumentException("invalid station")
);
if (!fromUser.getStations().contains(fromStation)) {
throw new IllegalArgumentException("invalid station");
}
var toStation = stationRepository.findByCallsign(toStationDto.callsign()).orElseGet( | () -> stationRepository.save(new Station(toStationDto.callsign())) | 2 | 2023-12-24 16:58:17+00:00 | 4k |
strokegmd/StrokeClient | stroke/client/clickgui/component/components/sub/ModeButton.java | [
{
"identifier": "Setting",
"path": "stroke/client/clickgui/Setting.java",
"snippet": "public class Setting {\n\t\n\tprivate String name;\n\tprivate BaseModule parent;\n\tprivate String mode;\n\t\n\tprivate String sval;\n\tprivate ArrayList<String> options;\n\tprivate String title;\n\t\n\tprivate boolean... | import org.lwjgl.opengl.GL11;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.stroke.client.clickgui.Setting;
import net.stroke.client.clickgui.component.Component;
import net.stroke.client.clickgui.component.components.Button;
import net.stroke.client.modules.BaseModule; | 2,551 | package net.stroke.client.clickgui.component.components.sub;
public class ModeButton extends Component {
private boolean hovered;
private Button parent; | package net.stroke.client.clickgui.component.components.sub;
public class ModeButton extends Component {
private boolean hovered;
private Button parent; | private Setting set; | 0 | 2023-12-31 10:56:59+00:00 | 4k |
Supriya2301/EVotingSystem-SpringJPA | EVotingSystem/src/main/java/com/codingninjas/EVotingSystem/controllers/VotingController.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\tpubl... | import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import 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.services.VotingService; | 1,752 | package com.codingninjas.EVotingSystem.controllers;
@CrossOrigin
@RestController
public class VotingController {
@Autowired
VotingService votingService;
@GetMapping("/get/votes")
public List<Vote> getAllVotes() {
return votingService.getAllVotes();
}
@GetMapping("/get/users")
public List<User> getAllUsers(){
return votingService.getAllUsers();
}
@PostMapping("/add/user")
public void addUser(@RequestBody User user) {
votingService.addUser(user);
}
@PostMapping("/add/vote")
public void addVote(@RequestBody Vote vote) {
Vote updatedVote = new Vote();
User user = votingService.findUserByName(vote.getUser().getName());
Election election = votingService.findElectionByName(vote.getElection().getName()); | package com.codingninjas.EVotingSystem.controllers;
@CrossOrigin
@RestController
public class VotingController {
@Autowired
VotingService votingService;
@GetMapping("/get/votes")
public List<Vote> getAllVotes() {
return votingService.getAllVotes();
}
@GetMapping("/get/users")
public List<User> getAllUsers(){
return votingService.getAllUsers();
}
@PostMapping("/add/user")
public void addUser(@RequestBody User user) {
votingService.addUser(user);
}
@PostMapping("/add/vote")
public void addVote(@RequestBody Vote vote) {
Vote updatedVote = new Vote();
User user = votingService.findUserByName(vote.getUser().getName());
Election election = votingService.findElectionByName(vote.getElection().getName()); | ElectionChoice electionChoice = votingService.findElectionChoiceByNameAndElection(vote.getElectionChoice().getName(),election); | 1 | 2023-12-30 06:54:58+00:00 | 4k |
adamalexandru4/pgmq-spring | src/main/java/io/tembo/pgmq/config/PGMQAutoConfiguration.java | [
{
"identifier": "PGMQClient",
"path": "src/main/java/io/tembo/pgmq/PGMQClient.java",
"snippet": "public class PGMQClient {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(PGMQClient.class);\n\n private final JdbcOperations operations;\n private final PGMQConfigurationProperties... | import com.fasterxml.jackson.databind.ObjectMapper;
import io.tembo.pgmq.PGMQClient;
import io.tembo.pgmq.json.PGMQJsonProcessor;
import io.tembo.pgmq.json.PGMQJsonProcessorJackson;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcOperations; | 2,285 | package io.tembo.pgmq.config;
@AutoConfiguration(after = {
JacksonAutoConfiguration.class,
DataSourceAutoConfiguration.class
})
@EnableConfigurationProperties(PGMQConfigurationProperties.class)
public class PGMQAutoConfiguration {
@Bean
@ConditionalOnMissingBean(PGMQJsonProcessor.class)
@ConditionalOnBean(ObjectMapper.class)
public PGMQJsonProcessor pgmqJsonProcessor(ObjectMapper objectMapper) { | package io.tembo.pgmq.config;
@AutoConfiguration(after = {
JacksonAutoConfiguration.class,
DataSourceAutoConfiguration.class
})
@EnableConfigurationProperties(PGMQConfigurationProperties.class)
public class PGMQAutoConfiguration {
@Bean
@ConditionalOnMissingBean(PGMQJsonProcessor.class)
@ConditionalOnBean(ObjectMapper.class)
public PGMQJsonProcessor pgmqJsonProcessor(ObjectMapper objectMapper) { | return new PGMQJsonProcessorJackson(objectMapper); | 2 | 2023-12-22 19:29:05+00:00 | 4k |
piovas-lu/condominio | src/main/java/app/condominio/controller/CondominioController.java | [
{
"identifier": "Condominio",
"path": "src/main/java/app/condominio/domain/Condominio.java",
"snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"condominios\")\r\npublic class Condominio implements Serializable, Comparable<Condominio> {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = Ge... | import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import app.condominio.domain.Condominio;
import app.condominio.domain.enums.Estado;
import app.condominio.service.CondominioService;
| 3,008 | package app.condominio.controller;
@Controller
@RequestMapping("sindico/condominio")
public class CondominioController {
@Autowired
| package app.condominio.controller;
@Controller
@RequestMapping("sindico/condominio")
public class CondominioController {
@Autowired
| private CondominioService condominioService;
| 2 | 2023-12-29 22:19:42+00:00 | 4k |
Tomate0613/boids | src/main/java/dev/doublekekse/boids/mixin/AbstractSchoolingFishMixin.java | [
{
"identifier": "BoidGoal",
"path": "src/main/java/dev/doublekekse/boids/goals/BoidGoal.java",
"snippet": "public class BoidGoal extends Goal {\n public static final Logger LOGGER = LogManager.getLogger();\n\n public final float separationInfluence;\n public final float separationRange;\n pu... | import dev.doublekekse.boids.goals.BoidGoal;
import dev.doublekekse.boids.goals.LimitSpeedAndLookInVelocityDirectionGoal;
import dev.doublekekse.boids.goals.StayInWaterGoal;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.animal.AbstractFish;
import net.minecraft.world.entity.animal.AbstractSchoolingFish;
import net.minecraft.world.level.Level;
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; | 1,752 | package dev.doublekekse.boids.mixin;
@Mixin(AbstractSchoolingFish.class)
public abstract class AbstractSchoolingFishMixin extends AbstractFish {
public AbstractSchoolingFishMixin(EntityType<? extends AbstractFish> entityType, Level level) {
super(entityType, level);
}
@Inject(method = "registerGoals", at = @At("HEAD"), cancellable = true)
protected void registerGoals(CallbackInfo ci) { | package dev.doublekekse.boids.mixin;
@Mixin(AbstractSchoolingFish.class)
public abstract class AbstractSchoolingFishMixin extends AbstractFish {
public AbstractSchoolingFishMixin(EntityType<? extends AbstractFish> entityType, Level level) {
super(entityType, level);
}
@Inject(method = "registerGoals", at = @At("HEAD"), cancellable = true)
protected void registerGoals(CallbackInfo ci) { | this.goalSelector.addGoal(5, new BoidGoal(this, 0.5f, 0.9f, 8 / 20f, 1 / 20f)); | 0 | 2023-12-27 15:14:24+00:00 | 4k |
HuXin0817/shop_api | manager-api/src/main/java/cn/lili/controller/member/MemberPointsHistoryManagerController.java | [
{
"identifier": "ResultUtil",
"path": "framework/src/main/java/cn/lili/common/enums/ResultUtil.java",
"snippet": "public class ResultUtil<T> {\n\n /**\n * 抽象类,存放结果\n */\n private final ResultMessage<T> resultMessage;\n /**\n * 正常响应\n */\n private static final Integer SUCCESS ... | import cn.lili.common.enums.ResultUtil;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.entity.dos.MemberPointsHistory;
import cn.lili.modules.member.entity.vo.MemberPointsHistoryVO;
import cn.lili.modules.member.service.MemberPointsHistoryService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; | 2,325 | package cn.lili.controller.member;
/**
* 管理端,会员积分历史接口
*
* @author Bulbasaur
* @since 2020-02-25 14:10:16
*/
@RestController
@Api(tags = "管理端,会员积分历史接口")
@RequestMapping("/manager/member/memberPointsHistory")
public class MemberPointsHistoryManagerController {
@Autowired
private MemberPointsHistoryService memberPointsHistoryService;
@ApiOperation(value = "分页获取")
@ApiImplicitParams({
@ApiImplicitParam(name = "memberId", value = "会员ID", required = true, paramType = "query"),
@ApiImplicitParam(name = "memberName", value = "会员名称", required = true, paramType = "query")
})
@GetMapping(value = "/getByPage") | package cn.lili.controller.member;
/**
* 管理端,会员积分历史接口
*
* @author Bulbasaur
* @since 2020-02-25 14:10:16
*/
@RestController
@Api(tags = "管理端,会员积分历史接口")
@RequestMapping("/manager/member/memberPointsHistory")
public class MemberPointsHistoryManagerController {
@Autowired
private MemberPointsHistoryService memberPointsHistoryService;
@ApiOperation(value = "分页获取")
@ApiImplicitParams({
@ApiImplicitParam(name = "memberId", value = "会员ID", required = true, paramType = "query"),
@ApiImplicitParam(name = "memberName", value = "会员名称", required = true, paramType = "query")
})
@GetMapping(value = "/getByPage") | public ResultMessage<IPage<MemberPointsHistory>> getByPage(PageVO page, String memberId, String memberName) { | 3 | 2023-12-24 19:45:18+00:00 | 4k |
SocialPanda3578/OnlineShop | shop/src/shop/Panel/AdminPanel.java | [
{
"identifier": "Admin",
"path": "shop/src/shop/Admin.java",
"snippet": "public class Admin extends User{\n public Admin(){\n\n }\n public Admin(String name,String pass){\n setUsername(name);\n setPassword(pass);\n }\n \n public void login(){\n if (isLogin()) {\n ... | import shop.Admin;
import shop.Main;
import shop.Shop;
import java.sql.SQLException;
| 3,087 | package shop.Panel;
public class AdminPanel extends MainPanel{
Admin admin = new Admin();
public void FirstMenu() throws SQLException {
while (true) {
System.out.println("***************************");
System.out.println("\t1.管理商城");
System.out.println("\t2.查看用户信息");
System.out.println("\t3.退出管理员登录");
System.out.println("***************************");
System.out.print("请选择菜单:");
| package shop.Panel;
public class AdminPanel extends MainPanel{
Admin admin = new Admin();
public void FirstMenu() throws SQLException {
while (true) {
System.out.println("***************************");
System.out.println("\t1.管理商城");
System.out.println("\t2.查看用户信息");
System.out.println("\t3.退出管理员登录");
System.out.println("***************************");
System.out.print("请选择菜单:");
| int x = Main.sc.nextInt();
| 1 | 2023-12-28 04:26:15+00:00 | 4k |
emtee40/cpuspy-droid | app/src/main/java/com/tortel/cpuspy/ui/StateFragment.java | [
{
"identifier": "CpuSpyApp",
"path": "app/src/main/java/com/tortel/cpuspy/CpuSpyApp.java",
"snippet": "public class CpuSpyApp extends Application {\n\n private static final String KERNEL_VERSION_PATH = \"/proc/version\";\n\n private static final String TAG = \"CpuSpyApp\";\n\n private static fi... | import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.tortel.cpuspy.CpuSpyApp;
import com.tortel.cpuspy.CpuStateMonitor;
import com.tortel.cpuspy.R;
import java.util.ArrayList;
import java.util.List; | 2,131 | package com.tortel.cpuspy.ui;
/**
* Fragment that shows the CPU state info
*/
public class StateFragment extends Fragment {
public static final String CPU = "cpu";
// the views
private LinearLayout mStatesView = null;
private TextView mAdditionalStates = null;
private TextView mTotalStateTime = null;
private TextView mHeaderAdditionalStates = null;
private TextView mHeaderTotalStateTime = null;
private TextView mStatesWarning = null;
private TextView mKernelString = null;
private int mCpu;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCpu = getArguments().getInt(CPU);
mApp = (CpuSpyApp) getActivity().getApplicationContext();
}
private CpuSpyApp mApp;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.state_fragment, container, false);
mStatesView = view.findViewById(R.id.ui_states_view);
mKernelString = view.findViewById(R.id.ui_kernel_string);
mAdditionalStates = view.findViewById(
R.id.ui_additional_states);
mHeaderAdditionalStates = view.findViewById(
R.id.ui_header_additional_states);
mHeaderTotalStateTime = view.findViewById(
R.id.ui_header_total_state_time);
mStatesWarning = view.findViewById(R.id.ui_states_warning);
mTotalStateTime = view.findViewById(R.id.ui_total_state_time);
updateView();
return view;
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
updateView();
}
/**
* Generate and update all UI elements
*/
public void updateView() {
/* Get the CpuStateMonitor from the app, and iterate over all states,
* creating a row if the duration is > 0 or otherwise marking it in
* extraStates (missing) */ | package com.tortel.cpuspy.ui;
/**
* Fragment that shows the CPU state info
*/
public class StateFragment extends Fragment {
public static final String CPU = "cpu";
// the views
private LinearLayout mStatesView = null;
private TextView mAdditionalStates = null;
private TextView mTotalStateTime = null;
private TextView mHeaderAdditionalStates = null;
private TextView mHeaderTotalStateTime = null;
private TextView mStatesWarning = null;
private TextView mKernelString = null;
private int mCpu;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCpu = getArguments().getInt(CPU);
mApp = (CpuSpyApp) getActivity().getApplicationContext();
}
private CpuSpyApp mApp;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.state_fragment, container, false);
mStatesView = view.findViewById(R.id.ui_states_view);
mKernelString = view.findViewById(R.id.ui_kernel_string);
mAdditionalStates = view.findViewById(
R.id.ui_additional_states);
mHeaderAdditionalStates = view.findViewById(
R.id.ui_header_additional_states);
mHeaderTotalStateTime = view.findViewById(
R.id.ui_header_total_state_time);
mStatesWarning = view.findViewById(R.id.ui_states_warning);
mTotalStateTime = view.findViewById(R.id.ui_total_state_time);
updateView();
return view;
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
updateView();
}
/**
* Generate and update all UI elements
*/
public void updateView() {
/* Get the CpuStateMonitor from the app, and iterate over all states,
* creating a row if the duration is > 0 or otherwise marking it in
* extraStates (missing) */ | CpuStateMonitor monitor = mApp.getCpuStateMonitor(); | 1 | 2023-12-30 02:50:51+00:00 | 4k |
serpapi/serpapi-java | demo/src/main/java/demo/App.java | [
{
"identifier": "SerpApi",
"path": "src/main/java/serpapi/SerpApi.java",
"snippet": "public class SerpApi extends Exception {\n\n /** \n * client parameters\n */\n public Map<String, String> parameter;\n\n // initialize gson\n private static Gson gson = new Gson();\n\n /**\n * https client implem... | import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.Map;
import java.util.HashMap;
import serpapi.SerpApi;
import serpapi.SerpApiException; | 1,637 | /*
* This Java source file was generated by the Gradle 'init' task.
*/
package demo;
public class App {
public static void main(String[] args) throws SerpApiException {
if(args.length != 1) {
System.out.println("Usage: app <secret api key>");
System.exit(1);
}
String location = "Austin,Texas";
System.out.println("find the first Coffee in " + location);
// set api_key provided by the command line
Map<String, String> auth = new HashMap<>();
auth.put("api_key", args[0]);
// Create search | /*
* This Java source file was generated by the Gradle 'init' task.
*/
package demo;
public class App {
public static void main(String[] args) throws SerpApiException {
if(args.length != 1) {
System.out.println("Usage: app <secret api key>");
System.exit(1);
}
String location = "Austin,Texas";
System.out.println("find the first Coffee in " + location);
// set api_key provided by the command line
Map<String, String> auth = new HashMap<>();
auth.put("api_key", args[0]);
// Create search | SerpApi serpapi= new SerpApi(auth); | 0 | 2023-12-27 22:12:09+00:00 | 4k |
MuskStark/EasyECharts | src/main/java/com/github/muskstark/echart/attribute/Legend.java | [
{
"identifier": "EChartsExceptionsEnum",
"path": "src/main/java/com/github/muskstark/echart/enums/EChartsExceptionsEnum.java",
"snippet": "@Getter\npublic enum EChartsExceptionsEnum {\n\n ECharts_Invalid_TypeError(\"方法传入的参数为不受支持的类型\")\n ;\n private String message;\n\n private EChartsExceptio... | import com.github.muskstark.echart.enums.EChartsExceptionsEnum;
import com.github.muskstark.echart.exception.EChartsException;
import com.github.muskstark.echart.style.line.LineStyle;
import com.github.muskstark.echart.style.text.TextStyle;
import lombok.Getter;
import java.util.List; | 1,941 | package com.github.muskstark.echart.attribute;
/**
* Legend for charts
*/
@Getter
public class Legend {
private String type;
private String id;
private Boolean show;
private Double zLevel;
private Double z;
private Object left;
private Object top;
private Object right;
private Object bottom;
private Object width;
private Object height;
private String orient;
private String align;
private Integer[] padding;
private Double itemGap;
private Double itemWidth;
private Double itemHeight;
// private ItemStyle itemStyle;
private LineStyle lineStyle;
private Object symbolRotate;
private String formatter;
private Boolean selectedMode;
private String inactiveColor;
private String inactiveBorderColor;
private String inactiveBorderWidth;
private Object selected;
private TextStyle textStyle;
private ToolTip tooltip;
private String icon;
private List<Object> data;
private String backgroundColor;
private String borderColor;
private Double borderWidth;
private Integer[] borderRadius;
private Double shadowBlur;
private String shadowColor;
private Double shadowOffsetX;
private Double shadowOffsetY;
private Double scrollDataIndex;
private Double pageButtonItemGap;
private Double pageButtonGap;
private String pageButtonPosition;
private String pageFormatter;
// private PageIcons pageIcons;
private String pageIconColor;
private String pageIconInactiveColor;
private Integer[] pageIconSize;
// private TextStyle pageTextStyle;
private Boolean animation;
private Double animationDurationUpdate;
// private Object emphasis;
private Boolean[] selector;
// private SelectorLabel selectorLabel;
private String selectorPosition;
private Integer selectorItemGap;
private Integer selectorButtonGap;
public Legend type(String type){
this.type = type;
return this;
}
public Legend id(String id){
this.id = id;
return this;
}
public Legend show(Boolean show){
this.show = show;
return this;
}
public Legend zLevel(Double zLevel){
this.zLevel = zLevel;
return this;
}
public Legend z(Double z){
this.z = z;
return this;
}
public Legend left(Object left){
if(left instanceof String || left instanceof Double){
this.left = left;
}else { | package com.github.muskstark.echart.attribute;
/**
* Legend for charts
*/
@Getter
public class Legend {
private String type;
private String id;
private Boolean show;
private Double zLevel;
private Double z;
private Object left;
private Object top;
private Object right;
private Object bottom;
private Object width;
private Object height;
private String orient;
private String align;
private Integer[] padding;
private Double itemGap;
private Double itemWidth;
private Double itemHeight;
// private ItemStyle itemStyle;
private LineStyle lineStyle;
private Object symbolRotate;
private String formatter;
private Boolean selectedMode;
private String inactiveColor;
private String inactiveBorderColor;
private String inactiveBorderWidth;
private Object selected;
private TextStyle textStyle;
private ToolTip tooltip;
private String icon;
private List<Object> data;
private String backgroundColor;
private String borderColor;
private Double borderWidth;
private Integer[] borderRadius;
private Double shadowBlur;
private String shadowColor;
private Double shadowOffsetX;
private Double shadowOffsetY;
private Double scrollDataIndex;
private Double pageButtonItemGap;
private Double pageButtonGap;
private String pageButtonPosition;
private String pageFormatter;
// private PageIcons pageIcons;
private String pageIconColor;
private String pageIconInactiveColor;
private Integer[] pageIconSize;
// private TextStyle pageTextStyle;
private Boolean animation;
private Double animationDurationUpdate;
// private Object emphasis;
private Boolean[] selector;
// private SelectorLabel selectorLabel;
private String selectorPosition;
private Integer selectorItemGap;
private Integer selectorButtonGap;
public Legend type(String type){
this.type = type;
return this;
}
public Legend id(String id){
this.id = id;
return this;
}
public Legend show(Boolean show){
this.show = show;
return this;
}
public Legend zLevel(Double zLevel){
this.zLevel = zLevel;
return this;
}
public Legend z(Double z){
this.z = z;
return this;
}
public Legend left(Object left){
if(left instanceof String || left instanceof Double){
this.left = left;
}else { | throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError); | 0 | 2023-12-25 08:03:42+00:00 | 4k |
thanosmoschou/SpringBootPractise | colors/src/main/java/com/example/colors/config/PrinterConfig.java | [
{
"identifier": "BluePrinter",
"path": "colors/src/main/java/com/example/colors/services/BluePrinter.java",
"snippet": "public interface BluePrinter\r\n{\r\n\tpublic String print();\r\n}\r"
},
{
"identifier": "ColorPrinter",
"path": "colors/src/main/java/com/example/colors/services/ColorPrin... | import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.example.colors.services.BluePrinter;
import com.example.colors.services.ColorPrinter;
import com.example.colors.services.GreenPrinter;
import com.example.colors.services.RedPrinter;
import com.example.colors.services.impl.ColorPrinterImpl;
import com.example.colors.services.impl.SpanishBluePrinter;
import com.example.colors.services.impl.SpanishGreenPrinter;
import com.example.colors.services.impl.SpanishRedPrinter;
| 1,884 | package com.example.colors.config;
/*
In Spring Boot, a bean is a Java object managed by the Spring framework's IoC (Inversion of Control) container.
It is a fundamental building block of a Spring application and represents a reusable component that can be wired
together with other beans to create the application's functionality.
@Bean is used to define individual beans explicitly in Spring. When you create a method annotated with @Bean within
a Spring @Configuration class, Spring will register the return value of that method as a bean in the Spring application context.
You can use this annotation to customize the instantiation and configuration of specific beans, and it allows you
to have fine-grained control over the objects created by Spring.
@Configuration is used to indicate that a class defines Spring bean configurations.
When you annotate a class with @Configuration, it tells Spring that this class contains one or more @Bean definitions or
other bean-related configurations. Spring will process the bean definitions inside the @Configuration class and add them to the application context.
@EnableAutoConfiguration is used to enable Spring Boot's auto-configuration mechanism.
When you annotate your main class (the one annotated with @SpringBootApplication) or any other
configuration class with @EnableAutoConfiguration, Spring Boot will automatically attempt to configure
the application based on the dependencies and the classpath. It will enable sensible defaults for various configurations,
such as database connections, message queues, and web frameworks, among others. Essentially,
it allows you to let Spring Boot do much of the configuration work for you, based on the dependencies present in your project.
In summary, @Bean is used to explicitly define individual beans in a Spring application,
@Configuration is used to define a class as a source of bean configurations, and
@EnableAutoConfiguration is used to enable Spring Boot's automatic configuration feature,
which simplifies the setup of your application by configuring beans based on classpath and dependencies.
*/
@Configuration
public class PrinterConfig
{
/*
* Each method will create a Bean to be managed by the Spring container
* Now that I have these Beans I can inject them wherever they are needed
*/
@Bean
public RedPrinter redPrinter()
{
//The implementation of this method will return the implementation of RedPrinter
//Remember from theory that interface types can also be used for declaring some objects
//but you cannot use them with the new keyword to create objects of that interface.
//You can only create objects of classes that implement this interface but their type
//can also be declared as the interface name
//For example:
//RedPrinter printer = new EnglishRedPrinter(); this is valid if EnglishRedPrinter implements RedPrinter interface
//RedPrinter printer = new Printer(); this is not valid because you cannot use the interface name to create objects
//return new EnglishRedPrinter();
//Now I can change the implementation here without having to change anything else on the project
//I declared interfaces there and I created Beans as concrete classes and spring will inject them
//to the interface declarations
return new SpanishRedPrinter();
}
@Bean
public BluePrinter bluePrinter()
{
//return new EnglishBluePrinter();
return new SpanishBluePrinter();
}
@Bean
| package com.example.colors.config;
/*
In Spring Boot, a bean is a Java object managed by the Spring framework's IoC (Inversion of Control) container.
It is a fundamental building block of a Spring application and represents a reusable component that can be wired
together with other beans to create the application's functionality.
@Bean is used to define individual beans explicitly in Spring. When you create a method annotated with @Bean within
a Spring @Configuration class, Spring will register the return value of that method as a bean in the Spring application context.
You can use this annotation to customize the instantiation and configuration of specific beans, and it allows you
to have fine-grained control over the objects created by Spring.
@Configuration is used to indicate that a class defines Spring bean configurations.
When you annotate a class with @Configuration, it tells Spring that this class contains one or more @Bean definitions or
other bean-related configurations. Spring will process the bean definitions inside the @Configuration class and add them to the application context.
@EnableAutoConfiguration is used to enable Spring Boot's auto-configuration mechanism.
When you annotate your main class (the one annotated with @SpringBootApplication) or any other
configuration class with @EnableAutoConfiguration, Spring Boot will automatically attempt to configure
the application based on the dependencies and the classpath. It will enable sensible defaults for various configurations,
such as database connections, message queues, and web frameworks, among others. Essentially,
it allows you to let Spring Boot do much of the configuration work for you, based on the dependencies present in your project.
In summary, @Bean is used to explicitly define individual beans in a Spring application,
@Configuration is used to define a class as a source of bean configurations, and
@EnableAutoConfiguration is used to enable Spring Boot's automatic configuration feature,
which simplifies the setup of your application by configuring beans based on classpath and dependencies.
*/
@Configuration
public class PrinterConfig
{
/*
* Each method will create a Bean to be managed by the Spring container
* Now that I have these Beans I can inject them wherever they are needed
*/
@Bean
public RedPrinter redPrinter()
{
//The implementation of this method will return the implementation of RedPrinter
//Remember from theory that interface types can also be used for declaring some objects
//but you cannot use them with the new keyword to create objects of that interface.
//You can only create objects of classes that implement this interface but their type
//can also be declared as the interface name
//For example:
//RedPrinter printer = new EnglishRedPrinter(); this is valid if EnglishRedPrinter implements RedPrinter interface
//RedPrinter printer = new Printer(); this is not valid because you cannot use the interface name to create objects
//return new EnglishRedPrinter();
//Now I can change the implementation here without having to change anything else on the project
//I declared interfaces there and I created Beans as concrete classes and spring will inject them
//to the interface declarations
return new SpanishRedPrinter();
}
@Bean
public BluePrinter bluePrinter()
{
//return new EnglishBluePrinter();
return new SpanishBluePrinter();
}
@Bean
| public GreenPrinter greenPrinter()
| 2 | 2023-12-31 17:29:44+00:00 | 4k |
dmanzhang/jsystem-master6112_autotest | standupAgainstWind/automationProj/automationProj/src/main/java/org/jsystem/automationProj/MultiSwitchCase.java | [
{
"identifier": "MyTestEnvironment",
"path": "standupAgainstWind/drive-switch/drive-switch/src/main/java/org/jsystem/automationProj/MyTestEnvironment.java",
"snippet": "public class MyTestEnvironment extends SystemObjectImpl {\r\n private String environmentName;\r\n private int switchNumber;\r\n ... | import org.junit.Before;
import org.junit.Test;
import org.jsystem.automationProj.MyTestEnvironment;
import org.jsystem.automationProj.MySwitchOpen;
import jsystem.extensions.analyzers.text.FindText;
import junit.framework.SystemTestCase4;
| 3,314 | package org.jsystem.automationProj;
public class MultiSwitchCase extends SystemTestCase4 {
public static int MaxSwitchs=8;
MyTestEnvironment myEnvironment;
| package org.jsystem.automationProj;
public class MultiSwitchCase extends SystemTestCase4 {
public static int MaxSwitchs=8;
MyTestEnvironment myEnvironment;
| public static MySwitchOpen [] mySwitchOpen = new MySwitchOpen[MaxSwitchs];
| 1 | 2023-12-22 01:32:25+00:00 | 4k |
echothreellc/kafka-connector | Kafka/KafkaJCAAPI/src/main/java/fish/payara/cloud/connectors/kafka/outbound/KafkaManagedConnectionFactory.java | [
{
"identifier": "KafkaConnection",
"path": "Kafka/KafkaJCAAPI/src/main/java/fish/payara/cloud/connectors/kafka/api/KafkaConnection.java",
"snippet": "public interface KafkaConnection extends AutoCloseable {\n \n public Future<RecordMetadata> send(ProducerRecord record) throws ResourceException;\n ... | import fish.payara.cloud.connectors.kafka.api.KafkaConnection;
import fish.payara.cloud.connectors.kafka.api.KafkaConnectionFactory;
import fish.payara.cloud.connectors.kafka.tools.AdditionalPropertiesParser;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import javax.resource.ResourceException;
import javax.resource.spi.ConfigProperty;
import javax.resource.spi.ConnectionDefinition;
import javax.resource.spi.ConnectionManager;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionFactory;
import javax.resource.spi.TransactionSupport;
import javax.security.auth.Subject;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig; | 1,820 | /*
* 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.outbound;
/**
*
* @author Steve Millidge (Payara Foundation)
*/
@ConnectionDefinition( connection = KafkaConnection.class,
connectionFactory = KafkaConnectionFactory.class,
connectionFactoryImpl = KafkaConnectionFactoryImpl.class,
connectionImpl = KafkaConnectionImpl.class
)
public class KafkaManagedConnectionFactory implements ManagedConnectionFactory, TransactionSupport {
private final Properties producerProperties; | /*
* 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.outbound;
/**
*
* @author Steve Millidge (Payara Foundation)
*/
@ConnectionDefinition( connection = KafkaConnection.class,
connectionFactory = KafkaConnectionFactory.class,
connectionFactoryImpl = KafkaConnectionFactoryImpl.class,
connectionImpl = KafkaConnectionImpl.class
)
public class KafkaManagedConnectionFactory implements ManagedConnectionFactory, TransactionSupport {
private final Properties producerProperties; | private AdditionalPropertiesParser additionalPropertiesParser; | 2 | 2023-12-24 23:25:44+00:00 | 4k |
xyzell/OOP_UAS | Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/swing/DashboardManageReceptionist.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 Acc... | 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.service.impl.ReceptionistServiceLoginImpl;
import com.itenas.oop.org.uashotel.service.impl.ReceptionistServiceImpl;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.Timer; | 2,892 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package com.itenas.oop.org.uashotel.swing;
//Fero Refadha Zaidan bagian logic
//Nicholas G.I Simanjuntak bagian user interface / design
/**
*
* @author Nicholas
*/
public class DashboardManageReceptionist extends javax.swing.JFrame {
ReceptionistServiceLoginImpl receplogin;
ReceptionistServiceImpl recepDetail; | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package com.itenas.oop.org.uashotel.swing;
//Fero Refadha Zaidan bagian logic
//Nicholas G.I Simanjuntak bagian user interface / design
/**
*
* @author Nicholas
*/
public class DashboardManageReceptionist extends javax.swing.JFrame {
ReceptionistServiceLoginImpl receplogin;
ReceptionistServiceImpl recepDetail; | Receptionist receptionist; | 1 | 2023-12-24 11:39:51+00:00 | 4k |
LawMashira/Springboot-3-Security-Registration-and-Login- | Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/controller/AuthController.java | [
{
"identifier": "JwtResponse",
"path": "Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/controller/response/JwtResponse.java",
"snippet": "@Data\n\n@NoArgsConstructor\npublic class JwtResponse {\n private Long id;\n private String email;\n private Str... | import com.student.online.admission.system.rd.year.controller.response.JwtResponse;
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.request.LoginRequest;
import com.student.online.admission.system.rd.year.security.jwt.JwtUtils;
import com.student.online.admission.system.rd.year.security.user.StudentUserDetails;
import com.student.online.admission.system.rd.year.service.UserService;
import jakarta.persistence.NamedStoredProcedureQuery;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
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.util.List; | 2,735 | package com.student.online.admission.system.rd.year.controller;
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {
/*
private final UserService userService;
private final AuthenticationManager authenticationManager;
private final JwtUtils jwtUtils;
@PostMapping("/register-user")
public ResponseEntity<?> registerUser(User user){
try{
userService.registerUser(user);
return ResponseEntity.ok("Registration successful");
}catch (UserAlreadyExistsException e){
return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage());
}
}
@PostMapping("/login")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest){
Authentication authentication= authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(),loginRequest.getPassword()));
SecurityContextHolder .getContext().setAuthentication(authentication);
String jwt =jwtUtils.generateJwtTokenForUser(authentication);
StudentUserDetails userDetails= (StudentUserDetails) authentication.getPrincipal();
List<String> roles =userDetails.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.toList();
return ResponseEntity.ok(new JwtResponse(
userDetails.getId(),
userDetails.getEmail(),
jwt,
roles));
}*/
//0000000000000000000000000000000000000000000000000000 | package com.student.online.admission.system.rd.year.controller;
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {
/*
private final UserService userService;
private final AuthenticationManager authenticationManager;
private final JwtUtils jwtUtils;
@PostMapping("/register-user")
public ResponseEntity<?> registerUser(User user){
try{
userService.registerUser(user);
return ResponseEntity.ok("Registration successful");
}catch (UserAlreadyExistsException e){
return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage());
}
}
@PostMapping("/login")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest){
Authentication authentication= authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getEmail(),loginRequest.getPassword()));
SecurityContextHolder .getContext().setAuthentication(authentication);
String jwt =jwtUtils.generateJwtTokenForUser(authentication);
StudentUserDetails userDetails= (StudentUserDetails) authentication.getPrincipal();
List<String> roles =userDetails.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.toList();
return ResponseEntity.ok(new JwtResponse(
userDetails.getId(),
userDetails.getEmail(),
jwt,
roles));
}*/
//0000000000000000000000000000000000000000000000000000 | private final UserService userService; | 6 | 2023-12-30 19:51:38+00:00 | 4k |
Duucking/UniversalTeleport | android-client/app/src/main/java/com/duucking/universalteleport/service/QuickActionService.java | [
{
"identifier": "MainActivity",
"path": "android-client/app/src/main/java/com/duucking/universalteleport/MainActivity.java",
"snippet": "public class MainActivity extends AppCompatActivity {\n private EditText key_edit;\n private EditText ip_edit;\n\n private SharedPreferences sharedPreferences... | import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.Icon;
import android.os.IBinder;
import android.service.quicksettings.Tile;
import android.service.quicksettings.TileService;
import android.util.Log;
import com.duucking.universalteleport.MainActivity;
import com.duucking.universalteleport.R;
import com.duucking.universalteleport.ShareActivity;
import com.duucking.universalteleport.ShareTextActivity;
import com.duucking.universalteleport.noActivity;
import java.util.List; | 2,328 | package com.duucking.universalteleport.service;
public class QuickActionService extends TileService {
public QuickActionService() {
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Tile tile = getQsTile();
tile.setState(Tile.STATE_INACTIVE);
tile.setIcon(Icon.createWithResource(this, R.drawable.ic_public_email_send_filled));
tile.updateTile();
Log.e("UniversalTeleportTest", "tile service onTaskRemoved");
super.onTaskRemoved(rootIntent);
}
@Override
public void onStartListening() {
super.onStartListening();
Log.e("UniversalTeleportTest", "tile service Listening");
changeTileState();
}
@Override
public void onClick() {
super.onClick();
Tile tile = getQsTile();
if (tile.getState() != Tile.STATE_ACTIVE) {
Intent noActivityinten = new Intent(this, noActivity.class);
noActivityinten.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(noActivityinten);
} catch (Exception e) {
Log.e("UniversalTeleportTest", "Exception :" + e);
}
tile.setState(Tile.STATE_ACTIVE);
tile.setIcon(Icon.createWithResource(this, R.drawable.ic_public_email_send));
tile.updateTile();
} else {
Intent AppServiceintent = new Intent(this, AppService.class);
tile.setState(Tile.STATE_INACTIVE);
tile.setIcon(Icon.createWithResource(this, R.drawable.ic_public_email_send_filled));
tile.updateTile();
MainActivity mainActivity = new MainActivity();
noActivity noActivity = new noActivity(); | package com.duucking.universalteleport.service;
public class QuickActionService extends TileService {
public QuickActionService() {
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Tile tile = getQsTile();
tile.setState(Tile.STATE_INACTIVE);
tile.setIcon(Icon.createWithResource(this, R.drawable.ic_public_email_send_filled));
tile.updateTile();
Log.e("UniversalTeleportTest", "tile service onTaskRemoved");
super.onTaskRemoved(rootIntent);
}
@Override
public void onStartListening() {
super.onStartListening();
Log.e("UniversalTeleportTest", "tile service Listening");
changeTileState();
}
@Override
public void onClick() {
super.onClick();
Tile tile = getQsTile();
if (tile.getState() != Tile.STATE_ACTIVE) {
Intent noActivityinten = new Intent(this, noActivity.class);
noActivityinten.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(noActivityinten);
} catch (Exception e) {
Log.e("UniversalTeleportTest", "Exception :" + e);
}
tile.setState(Tile.STATE_ACTIVE);
tile.setIcon(Icon.createWithResource(this, R.drawable.ic_public_email_send));
tile.updateTile();
} else {
Intent AppServiceintent = new Intent(this, AppService.class);
tile.setState(Tile.STATE_INACTIVE);
tile.setIcon(Icon.createWithResource(this, R.drawable.ic_public_email_send_filled));
tile.updateTile();
MainActivity mainActivity = new MainActivity();
noActivity noActivity = new noActivity(); | ShareActivity shareActivity = new ShareActivity(); | 1 | 2023-12-24 11:03:05+00:00 | 4k |
LeeKyeongYong/SBookStudy | src/main/java/com/multibook/bookorder/global/security/service/CustomOAuth2UserService.java | [
{
"identifier": "Member",
"path": "src/main/java/com/multibook/bookorder/domain/member/member/entity/Member.java",
"snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true, exclude = {\"myBooks\", \"owner... | import com.multibook.bookorder.domain.member.member.entity.Member;
import com.multibook.bookorder.domain.member.member.service.MemberService;
import com.multibook.bookorder.global.security.entity.SecurityUser;
import lombok.RequiredArgsConstructor;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Map; | 1,825 | package com.multibook.bookorder.global.security.service;
@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
private final MemberService memberService;
// 카카오톡 로그인이 성공할 때 마다 이 함수가 실행된다.
@Override
@Transactional
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2User oAuth2User = super.loadUser(userRequest);
String oauthId = oAuth2User.getName();
Map<String, Object> attributes = oAuth2User.getAttributes();
Map attributesProperties = (Map) attributes.get("properties");
String nickname = (String) attributesProperties.get("nickname");
String profileImgUrl = (String) attributesProperties.get("profile_image");
String providerTypeCode = userRequest.getClientRegistration().getRegistrationId().toUpperCase();
String username = providerTypeCode + "__%s".formatted(oauthId);
Member member = memberService.whenSocialLogin(providerTypeCode, username, nickname, profileImgUrl).getData();
| package com.multibook.bookorder.global.security.service;
@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class CustomOAuth2UserService extends DefaultOAuth2UserService {
private final MemberService memberService;
// 카카오톡 로그인이 성공할 때 마다 이 함수가 실행된다.
@Override
@Transactional
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2User oAuth2User = super.loadUser(userRequest);
String oauthId = oAuth2User.getName();
Map<String, Object> attributes = oAuth2User.getAttributes();
Map attributesProperties = (Map) attributes.get("properties");
String nickname = (String) attributesProperties.get("nickname");
String profileImgUrl = (String) attributesProperties.get("profile_image");
String providerTypeCode = userRequest.getClientRegistration().getRegistrationId().toUpperCase();
String username = providerTypeCode + "__%s".formatted(oauthId);
Member member = memberService.whenSocialLogin(providerTypeCode, username, nickname, profileImgUrl).getData();
| return new SecurityUser(member.getId(), member.getUsername(), member.getPassword(), member.getAuthorities()); | 2 | 2023-12-26 14:58:59+00:00 | 4k |
huidongyin/kafka-2.7.2 | clients/src/main/java/org/apache/kafka/common/record/MemoryRecords.java | [
{
"identifier": "TopicPartition",
"path": "clients/src/main/java/org/apache/kafka/common/TopicPartition.java",
"snippet": "public final class TopicPartition implements Serializable {\n private static final long serialVersionUID = -613627415771699627L;\n\n private int hash = 0;\n private final i... | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.CorruptRecordException;
import org.apache.kafka.common.message.LeaderChangeMessage;
import org.apache.kafka.common.record.MemoryRecords.RecordFilter.BatchRetention;
import org.apache.kafka.common.utils.AbstractIterator;
import org.apache.kafka.common.utils.ByteBufferOutputStream;
import org.apache.kafka.common.utils.CloseableIterator;
import org.apache.kafka.common.utils.Time;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel; | 3,329 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.common.record;
/**
* A {@link Records} implementation backed by a ByteBuffer. This is used only for reading or
* modifying in-place an existing buffer of record batches. To create a new buffer see {@link MemoryRecordsBuilder},
* or one of the {@link #builder(ByteBuffer, byte, CompressionType, TimestampType, long)} variants.
*/
public class MemoryRecords extends AbstractRecords {
private static final Logger log = LoggerFactory.getLogger(MemoryRecords.class);
public static final MemoryRecords EMPTY = MemoryRecords.readableRecords(ByteBuffer.allocate(0));
private final ByteBuffer buffer;
private final Iterable<MutableRecordBatch> batches = this::batchIterator;
private int validBytes = -1;
// Construct a writable memory records
private MemoryRecords(ByteBuffer buffer) {
Objects.requireNonNull(buffer, "buffer should not be null");
this.buffer = buffer;
}
@Override
public int sizeInBytes() {
return buffer.limit();
}
@Override
public long writeTo(GatheringByteChannel channel, long position, int length) throws IOException {
if (position > Integer.MAX_VALUE)
throw new IllegalArgumentException("position should not be greater than Integer.MAX_VALUE: " + position);
if (position + length > buffer.limit())
throw new IllegalArgumentException("position+length should not be greater than buffer.limit(), position: "
+ position + ", length: " + length + ", buffer.limit(): " + buffer.limit());
int pos = (int) position;
ByteBuffer dup = buffer.duplicate();
dup.position(pos);
dup.limit(pos + length);
return channel.write(dup);
}
/**
* Write all records to the given channel (including partial records).
* @param channel The channel to write to
* @return The number of bytes written
* @throws IOException For any IO errors writing to the channel
*/
public int writeFullyTo(GatheringByteChannel channel) throws IOException {
buffer.mark();
int written = 0;
while (written < sizeInBytes())
written += channel.write(buffer);
buffer.reset();
return written;
}
/**
* The total number of bytes in this message set not including any partial, trailing messages. This
* may be smaller than what is returned by {@link #sizeInBytes()}.
* @return The number of valid bytes
*/
public int validBytes() {
if (validBytes >= 0)
return validBytes;
int bytes = 0;
for (RecordBatch batch : batches())
bytes += batch.sizeInBytes();
this.validBytes = bytes;
return bytes;
}
@Override | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.common.record;
/**
* A {@link Records} implementation backed by a ByteBuffer. This is used only for reading or
* modifying in-place an existing buffer of record batches. To create a new buffer see {@link MemoryRecordsBuilder},
* or one of the {@link #builder(ByteBuffer, byte, CompressionType, TimestampType, long)} variants.
*/
public class MemoryRecords extends AbstractRecords {
private static final Logger log = LoggerFactory.getLogger(MemoryRecords.class);
public static final MemoryRecords EMPTY = MemoryRecords.readableRecords(ByteBuffer.allocate(0));
private final ByteBuffer buffer;
private final Iterable<MutableRecordBatch> batches = this::batchIterator;
private int validBytes = -1;
// Construct a writable memory records
private MemoryRecords(ByteBuffer buffer) {
Objects.requireNonNull(buffer, "buffer should not be null");
this.buffer = buffer;
}
@Override
public int sizeInBytes() {
return buffer.limit();
}
@Override
public long writeTo(GatheringByteChannel channel, long position, int length) throws IOException {
if (position > Integer.MAX_VALUE)
throw new IllegalArgumentException("position should not be greater than Integer.MAX_VALUE: " + position);
if (position + length > buffer.limit())
throw new IllegalArgumentException("position+length should not be greater than buffer.limit(), position: "
+ position + ", length: " + length + ", buffer.limit(): " + buffer.limit());
int pos = (int) position;
ByteBuffer dup = buffer.duplicate();
dup.position(pos);
dup.limit(pos + length);
return channel.write(dup);
}
/**
* Write all records to the given channel (including partial records).
* @param channel The channel to write to
* @return The number of bytes written
* @throws IOException For any IO errors writing to the channel
*/
public int writeFullyTo(GatheringByteChannel channel) throws IOException {
buffer.mark();
int written = 0;
while (written < sizeInBytes())
written += channel.write(buffer);
buffer.reset();
return written;
}
/**
* The total number of bytes in this message set not including any partial, trailing messages. This
* may be smaller than what is returned by {@link #sizeInBytes()}.
* @return The number of valid bytes
*/
public int validBytes() {
if (validBytes >= 0)
return validBytes;
int bytes = 0;
for (RecordBatch batch : batches())
bytes += batch.sizeInBytes();
this.validBytes = bytes;
return bytes;
}
@Override | public ConvertedRecords<MemoryRecords> downConvert(byte toMagic, long firstOffset, Time time) { | 6 | 2023-12-23 07:12:18+00:00 | 4k |
SDeVuyst/pingys-waddles-1.20.1 | src/main/java/com/sdevuyst/pingyswaddles/item/ModItems.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 ... | import com.sdevuyst.pingyswaddles.PingysWaddles;
import com.sdevuyst.pingyswaddles.entity.ModEntities;
import com.sdevuyst.pingyswaddles.entity.custom.SurfboardEntity;
import com.sdevuyst.pingyswaddles.item.custom.SurfboardItem;
import net.minecraft.world.item.*;
import net.minecraftforge.common.ForgeSpawnEggItem;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject; | 1,870 | package com.sdevuyst.pingyswaddles.item;
public class ModItems {
public static final DeferredRegister<Item> ITEMS =
DeferredRegister.create(ForgeRegistries.ITEMS, PingysWaddles.MOD_ID);
public static final RegistryObject<Item> EMPEROR_PENGUIN_SPAWN_EGG = ITEMS.register("emperor_penguin_spawn_egg",
() -> new ForgeSpawnEggItem(ModEntities.EMPEROR_PENGUIN, 0xf9f6ee, 0xf0b722, new Item.Properties()));
public static final RegistryObject<Item> OAK_SURFBOARD = ITEMS.register("oak_surfboard", | package com.sdevuyst.pingyswaddles.item;
public class ModItems {
public static final DeferredRegister<Item> ITEMS =
DeferredRegister.create(ForgeRegistries.ITEMS, PingysWaddles.MOD_ID);
public static final RegistryObject<Item> EMPEROR_PENGUIN_SPAWN_EGG = ITEMS.register("emperor_penguin_spawn_egg",
() -> new ForgeSpawnEggItem(ModEntities.EMPEROR_PENGUIN, 0xf9f6ee, 0xf0b722, new Item.Properties()));
public static final RegistryObject<Item> OAK_SURFBOARD = ITEMS.register("oak_surfboard", | () -> new SurfboardItem(false, SurfboardEntity.Type.OAK, new Item.Properties())); | 3 | 2023-12-31 09:54:03+00:00 | 4k |
AweiMC/DragonMounts3 | common/src/main/java/net/dragonmounts3/tools/DM3Item.java | [
{
"identifier": "DM3Mod",
"path": "common/src/main/java/net/dragonmounts3/DM3Mod.java",
"snippet": "public class DM3Mod {\n public static final String MOD_ID = \"dragonmounts\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n public static void init() {\n Drago... | import dev.architectury.registry.CreativeTabRegistry;
import dev.architectury.registry.registries.DeferredRegister;
import dev.architectury.registry.registries.RegistrySupplier;
import net.dragonmounts3.DM3Mod;
import net.dragonmounts3.tools.DM3ToolMaterial.DM3Hoe;
import net.dragonmounts3.tools.DM3ToolMaterial.DM3Shovel;
import net.dragonmounts3.tools.DM3ToolMaterial.DM3Sword;
import net.dragonmounts3.tools.DM3ToolMaterial.DM3ToolMaterials;
import net.dragonmounts3.util.DragonTypeManager;
import net.dragonmounts3.util.ToolType;
import net.minecraft.item.*;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import java.util.function.Supplier; | 1,999 | package net.dragonmounts3.tools;
public interface DM3Item {
DeferredRegister<ItemGroup> ITEM_GROUPS = DeferredRegister.create(DM3Mod.MOD_ID, RegistryKeys.ITEM_GROUP);
// 创建一个 DeferredRegister 来注册物品
RegistrySupplier<ItemGroup> DM3_GROUP = ITEM_GROUPS.register(new Identifier("dragonmounts3.title.group"), () -> CreativeTabRegistry.create(
Text.translatable("dragonmounts3.title.group"),
() -> Items.DIAMOND.asItem().getDefaultStack()
));
DeferredRegister<Item> ITEMS = DeferredRegister.create(DM3Mod.MOD_ID, RegistryKeys.ITEM);
static void ItemRegister() {
ITEM_GROUPS.register();
ITEMS.register(); // 这里注册你的物品
registerTools();
}
static Item.Settings ItemToGroup() {
return new Item.Settings().arch$tab(DM3_GROUP);
}
static void register(String name, Supplier<Item> item) {
ITEMS.register(new Identifier(DM3Mod.MOD_ID,(name)), item);
}
static void registerTools() {
for (String dragonType : DragonTypeManager.getDragonTypes()) {
String DG = "_dragon";
register(dragonType + DG + "_sword", () -> createDM3Tool(dragonType, ToolType.SWORD)); // 注册对应类型的武器
register(dragonType + DG + "_pickaxe", () -> createDM3Tool(dragonType, ToolType.PICKAXE)); // 注册对应类型的镐
register(dragonType + DG + "_shovel", () -> createDM3Tool(dragonType, ToolType.SHOVEL)); // 注册对应类型的锹
// 添加其他工具类型的注册
}
}
static Item createDM3Tool(String dragonType, ToolType toolType) {
// 根据传递的工具类型和DragonType创建对应的工具,并返回
// 此处根据传递的 ToolType 参数决定创建的是哪种类型的工具
return switch (toolType) {
case SWORD -> new DM3Sword(getToolMaterialForDragonType(dragonType), 9, 2, ItemToGroup() /*其他参数*/);
case PICKAXE -> new PickaxeItem(getToolMaterialForDragonType(dragonType), -1, -2.4F, ItemToGroup());
case SHOVEL -> new DM3Shovel(getToolMaterialForDragonType(dragonType), 9, 2, ItemToGroup() /*其他参数*/);
case HOE -> new DM3Hoe(getToolMaterialForDragonType(dragonType), 9, 2, ItemToGroup() /*其他参数*/);
};
}
static ToolMaterial getToolMaterialForDragonType(String dragonType) {
// 根据DragonType返回对应的工具材料(ToolMaterial)
// 可以根据DragonType的不同返回不同的材料
// 这个方法需要根据您的需求进行具体实现
// 示例中使用了 DM3ToolMaterials.FOREST 作为默认材料,您需要根据DragonType返回合适的材料
return switch (dragonType) { | package net.dragonmounts3.tools;
public interface DM3Item {
DeferredRegister<ItemGroup> ITEM_GROUPS = DeferredRegister.create(DM3Mod.MOD_ID, RegistryKeys.ITEM_GROUP);
// 创建一个 DeferredRegister 来注册物品
RegistrySupplier<ItemGroup> DM3_GROUP = ITEM_GROUPS.register(new Identifier("dragonmounts3.title.group"), () -> CreativeTabRegistry.create(
Text.translatable("dragonmounts3.title.group"),
() -> Items.DIAMOND.asItem().getDefaultStack()
));
DeferredRegister<Item> ITEMS = DeferredRegister.create(DM3Mod.MOD_ID, RegistryKeys.ITEM);
static void ItemRegister() {
ITEM_GROUPS.register();
ITEMS.register(); // 这里注册你的物品
registerTools();
}
static Item.Settings ItemToGroup() {
return new Item.Settings().arch$tab(DM3_GROUP);
}
static void register(String name, Supplier<Item> item) {
ITEMS.register(new Identifier(DM3Mod.MOD_ID,(name)), item);
}
static void registerTools() {
for (String dragonType : DragonTypeManager.getDragonTypes()) {
String DG = "_dragon";
register(dragonType + DG + "_sword", () -> createDM3Tool(dragonType, ToolType.SWORD)); // 注册对应类型的武器
register(dragonType + DG + "_pickaxe", () -> createDM3Tool(dragonType, ToolType.PICKAXE)); // 注册对应类型的镐
register(dragonType + DG + "_shovel", () -> createDM3Tool(dragonType, ToolType.SHOVEL)); // 注册对应类型的锹
// 添加其他工具类型的注册
}
}
static Item createDM3Tool(String dragonType, ToolType toolType) {
// 根据传递的工具类型和DragonType创建对应的工具,并返回
// 此处根据传递的 ToolType 参数决定创建的是哪种类型的工具
return switch (toolType) {
case SWORD -> new DM3Sword(getToolMaterialForDragonType(dragonType), 9, 2, ItemToGroup() /*其他参数*/);
case PICKAXE -> new PickaxeItem(getToolMaterialForDragonType(dragonType), -1, -2.4F, ItemToGroup());
case SHOVEL -> new DM3Shovel(getToolMaterialForDragonType(dragonType), 9, 2, ItemToGroup() /*其他参数*/);
case HOE -> new DM3Hoe(getToolMaterialForDragonType(dragonType), 9, 2, ItemToGroup() /*其他参数*/);
};
}
static ToolMaterial getToolMaterialForDragonType(String dragonType) {
// 根据DragonType返回对应的工具材料(ToolMaterial)
// 可以根据DragonType的不同返回不同的材料
// 这个方法需要根据您的需求进行具体实现
// 示例中使用了 DM3ToolMaterials.FOREST 作为默认材料,您需要根据DragonType返回合适的材料
return switch (dragonType) { | case "aether" -> DM3ToolMaterials.AETHER; | 4 | 2023-12-28 12:11:21+00:00 | 4k |
MinsTail/essential | src/main/java/com/dotSoftix/EssentialClient/EssentialMain.java | [
{
"identifier": "onGuiOpenEvent",
"path": "src/main/java/com/dotSoftix/Menu/onGuiOpenEvent.java",
"snippet": "public class onGuiOpenEvent {\n @SideOnly(Side.CLIENT)\n @SubscribeEvent\n public void onGuiOpenEvent(GuiOpenEvent e) {\n if (e.getGui() instanceof GuiMainMenu) {\n e.... | import com.dotSoftix.Menu.onGuiOpenEvent;
import com.dotSoftix.EssentialClient.keyBinds.keyBind;
import com.dotSoftix.EssentialClient.modules.RENDER.RedanMode;
import com.dotSoftix.EssentialClient.modules.ui;
import net.minecraft.init.Blocks;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import org.apache.logging.log4j.Logger;
import org.lwjgl.opengl.Display;
import net.minecraft.client.Minecraft;
import net.minecraft.util.Session;
import java.lang.reflect.Field; | 2,307 | package com.dotSoftix.EssentialClient;
@Mod(modid = EssentialMain.MODID, name = EssentialMain.NAME, version = EssentialMain.VERSION)
public class EssentialMain
{
public static final String MODID = "essential (dotsoftix)";
public static final String NAME = "essential";
public static final String VERSION = "1.92";
private static Logger logger;
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
Display.setTitle("Loading " + ClientMain.clientName);
logger = event.getModLog();
}
@EventHandler
public void init(FMLInitializationEvent event)
{
ClientMain.clientStartup();
MinecraftForge.EVENT_BUS.register(new keyBind());
MinecraftForge.EVENT_BUS.register(new ui()); | package com.dotSoftix.EssentialClient;
@Mod(modid = EssentialMain.MODID, name = EssentialMain.NAME, version = EssentialMain.VERSION)
public class EssentialMain
{
public static final String MODID = "essential (dotsoftix)";
public static final String NAME = "essential";
public static final String VERSION = "1.92";
private static Logger logger;
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
Display.setTitle("Loading " + ClientMain.clientName);
logger = event.getModLog();
}
@EventHandler
public void init(FMLInitializationEvent event)
{
ClientMain.clientStartup();
MinecraftForge.EVENT_BUS.register(new keyBind());
MinecraftForge.EVENT_BUS.register(new ui()); | MinecraftForge.EVENT_BUS.register(new onGuiOpenEvent()); | 0 | 2023-12-28 15:15:14+00:00 | 4k |
Yanyutin753/PandoraNext-TokensTool | rearServer/src/main/java/com/tokensTool/pandoraNext/controller/chatController.java | [
{
"identifier": "Conversation",
"path": "rearServer/src/main/java/com/tokensTool/pandoraNext/chat/Conversation.java",
"snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Conversation {\n\n private String model;\n\n private List<Message> messages;\n\n private Boole... | import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tokensTool.pandoraNext.chat.Conversation;
import com.tokensTool.pandoraNext.pojo.Result;
import com.tokensTool.pandoraNext.pojo.modelsUsage;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.TimeUnit; | 1,629 | package com.tokensTool.pandoraNext.controller;
/**
* @author Yangyang
* @create 2023-12-25 18:29
*/
@Slf4j
@RestController()
public class chatController {
/**
* 缓存cocopilotToken
*/
private static final HashMap<String, String> copilotTokenList;
/**
* 缓存copilotToken
*/
private static final HashMap<String, String> coCopilotTokenList;
/**
* 模型
*/
private static final String models = "{\"data\":[{\"id\":\"text-search-babbage-doc-001\",\"object\":\"model\",\"created\":1651172509,\"owned_by\":\"openai-dev\"},{\"id\":\"gpt-4\",\"object\":\"model\",\"created\":1687882411,\"owned_by\":\"openai\"},{\"id\":\"babbage\",\"object\":\"model\",\"created\":1649358449,\"owned_by\":\"openai\"},{\"id\":\"gpt-3.5-turbo-0613\",\"object\":\"model\",\"created\":1686587434,\"owned_by\":\"openai\"},{\"id\":\"text-babbage-001\",\"object\":\"model\",\"created\":1649364043,\"owned_by\":\"openai\"},{\"id\":\"gpt-3.5-turbo\",\"object\":\"model\",\"created\":1677610602,\"owned_by\":\"openai\"},{\"id\":\"gpt-3.5-turbo-1106\",\"object\":\"model\",\"created\":1698959748,\"owned_by\":\"system\"},{\"id\":\"curie-instruct-beta\",\"object\":\"model\",\"created\":1649364042,\"owned_by\":\"openai\"},{\"id\":\"gpt-3.5-turbo-0301\",\"object\":\"model\",\"created\":1677649963,\"owned_by\":\"openai\"},{\"id\":\"gpt-3.5-turbo-16k-0613\",\"object\":\"model\",\"created\":1685474247,\"owned_by\":\"openai\"},{\"id\":\"text-embedding-ada-002\",\"object\":\"model\",\"created\":1671217299,\"owned_by\":\"openai-internal\"},{\"id\":\"davinci-similarity\",\"object\":\"model\",\"created\":1651172509,\"owned_by\":\"openai-dev\"},{\"id\":\"curie-similarity\",\"object\":\"model\",\"created\":1651172510,\"owned_by\":\"openai-dev\"},{\"id\":\"babbage-search-document\",\"object\":\"model\",\"created\":1651172510,\"owned_by\":\"openai-dev\"},{\"id\":\"curie-search-document\",\"object\":\"model\",\"created\":1651172508,\"owned_by\":\"openai-dev\"},{\"id\":\"babbage-code-search-code\",\"object\":\"model\",\"created\":1651172509,\"owned_by\":\"openai-dev\"},{\"id\":\"ada-code-search-text\",\"object\":\"model\",\"created\":1651172510,\"owned_by\":\"openai-dev\"},{\"id\":\"text-search-curie-query-001\",\"object\":\"model\",\"created\":1651172509,\"owned_by\":\"openai-dev\"},{\"id\":\"text-davinci-002\",\"object\":\"model\",\"created\":1649880484,\"owned_by\":\"openai\"},{\"id\":\"ada\",\"object\":\"model\",\"created\":1649357491,\"owned_by\":\"openai\"},{\"id\":\"text-ada-001\",\"object\":\"model\",\"created\":1649364042,\"owned_by\":\"openai\"},{\"id\":\"ada-similarity\",\"object\":\"model\",\"created\":1651172507,\"owned_by\":\"openai-dev\"},{\"id\":\"code-search-ada-code-001\",\"object\":\"model\",\"created\":1651172507,\"owned_by\":\"openai-dev\"},{\"id\":\"text-similarity-ada-001\",\"object\":\"model\",\"created\":1651172505,\"owned_by\":\"openai-dev\"},{\"id\":\"text-davinci-edit-001\",\"object\":\"model\",\"created\":1649809179,\"owned_by\":\"openai\"},{\"id\":\"code-davinci-edit-001\",\"object\":\"model\",\"created\":1649880484,\"owned_by\":\"openai\"},{\"id\":\"text-search-curie-doc-001\",\"object\":\"model\",\"created\":1651172509,\"owned_by\":\"openai-dev\"},{\"id\":\"text-curie-001\",\"object\":\"model\",\"created\":1649364043,\"owned_by\":\"openai\"},{\"id\":\"curie\",\"object\":\"model\",\"created\":1649359874,\"owned_by\":\"openai\"},{\"id\":\"davinci\",\"object\":\"model\",\"created\":1649359874,\"owned_by\":\"openai\"}]}";
private static final String machineId; | package com.tokensTool.pandoraNext.controller;
/**
* @author Yangyang
* @create 2023-12-25 18:29
*/
@Slf4j
@RestController()
public class chatController {
/**
* 缓存cocopilotToken
*/
private static final HashMap<String, String> copilotTokenList;
/**
* 缓存copilotToken
*/
private static final HashMap<String, String> coCopilotTokenList;
/**
* 模型
*/
private static final String models = "{\"data\":[{\"id\":\"text-search-babbage-doc-001\",\"object\":\"model\",\"created\":1651172509,\"owned_by\":\"openai-dev\"},{\"id\":\"gpt-4\",\"object\":\"model\",\"created\":1687882411,\"owned_by\":\"openai\"},{\"id\":\"babbage\",\"object\":\"model\",\"created\":1649358449,\"owned_by\":\"openai\"},{\"id\":\"gpt-3.5-turbo-0613\",\"object\":\"model\",\"created\":1686587434,\"owned_by\":\"openai\"},{\"id\":\"text-babbage-001\",\"object\":\"model\",\"created\":1649364043,\"owned_by\":\"openai\"},{\"id\":\"gpt-3.5-turbo\",\"object\":\"model\",\"created\":1677610602,\"owned_by\":\"openai\"},{\"id\":\"gpt-3.5-turbo-1106\",\"object\":\"model\",\"created\":1698959748,\"owned_by\":\"system\"},{\"id\":\"curie-instruct-beta\",\"object\":\"model\",\"created\":1649364042,\"owned_by\":\"openai\"},{\"id\":\"gpt-3.5-turbo-0301\",\"object\":\"model\",\"created\":1677649963,\"owned_by\":\"openai\"},{\"id\":\"gpt-3.5-turbo-16k-0613\",\"object\":\"model\",\"created\":1685474247,\"owned_by\":\"openai\"},{\"id\":\"text-embedding-ada-002\",\"object\":\"model\",\"created\":1671217299,\"owned_by\":\"openai-internal\"},{\"id\":\"davinci-similarity\",\"object\":\"model\",\"created\":1651172509,\"owned_by\":\"openai-dev\"},{\"id\":\"curie-similarity\",\"object\":\"model\",\"created\":1651172510,\"owned_by\":\"openai-dev\"},{\"id\":\"babbage-search-document\",\"object\":\"model\",\"created\":1651172510,\"owned_by\":\"openai-dev\"},{\"id\":\"curie-search-document\",\"object\":\"model\",\"created\":1651172508,\"owned_by\":\"openai-dev\"},{\"id\":\"babbage-code-search-code\",\"object\":\"model\",\"created\":1651172509,\"owned_by\":\"openai-dev\"},{\"id\":\"ada-code-search-text\",\"object\":\"model\",\"created\":1651172510,\"owned_by\":\"openai-dev\"},{\"id\":\"text-search-curie-query-001\",\"object\":\"model\",\"created\":1651172509,\"owned_by\":\"openai-dev\"},{\"id\":\"text-davinci-002\",\"object\":\"model\",\"created\":1649880484,\"owned_by\":\"openai\"},{\"id\":\"ada\",\"object\":\"model\",\"created\":1649357491,\"owned_by\":\"openai\"},{\"id\":\"text-ada-001\",\"object\":\"model\",\"created\":1649364042,\"owned_by\":\"openai\"},{\"id\":\"ada-similarity\",\"object\":\"model\",\"created\":1651172507,\"owned_by\":\"openai-dev\"},{\"id\":\"code-search-ada-code-001\",\"object\":\"model\",\"created\":1651172507,\"owned_by\":\"openai-dev\"},{\"id\":\"text-similarity-ada-001\",\"object\":\"model\",\"created\":1651172505,\"owned_by\":\"openai-dev\"},{\"id\":\"text-davinci-edit-001\",\"object\":\"model\",\"created\":1649809179,\"owned_by\":\"openai\"},{\"id\":\"code-davinci-edit-001\",\"object\":\"model\",\"created\":1649880484,\"owned_by\":\"openai\"},{\"id\":\"text-search-curie-doc-001\",\"object\":\"model\",\"created\":1651172509,\"owned_by\":\"openai-dev\"},{\"id\":\"text-curie-001\",\"object\":\"model\",\"created\":1649364043,\"owned_by\":\"openai\"},{\"id\":\"curie\",\"object\":\"model\",\"created\":1649359874,\"owned_by\":\"openai\"},{\"id\":\"davinci\",\"object\":\"model\",\"created\":1649359874,\"owned_by\":\"openai\"}]}";
private static final String machineId; | private static HashMap<String, Integer> modelsUsage; | 2 | 2023-11-17 11:37:37+00:00 | 4k |
quarkiverse/quarkus-langchain4j | openai/azure-openai/deployment/src/main/java/io/quarkiverse/langchain4j/azure/openai/deployment/AzureOpenAiProcessor.java | [
{
"identifier": "CHAT_MODEL",
"path": "core/deployment/src/main/java/io/quarkiverse/langchain4j/deployment/Langchain4jDotNames.java",
"snippet": "public static final DotName CHAT_MODEL = DotName.createSimple(ChatLanguageModel.class);"
},
{
"identifier": "EMBEDDING_MODEL",
"path": "core/deplo... | import static io.quarkiverse.langchain4j.deployment.Langchain4jDotNames.CHAT_MODEL;
import static io.quarkiverse.langchain4j.deployment.Langchain4jDotNames.EMBEDDING_MODEL;
import static io.quarkiverse.langchain4j.deployment.Langchain4jDotNames.STREAMING_CHAT_MODEL;
import java.util.Optional;
import jakarta.enterprise.context.ApplicationScoped;
import io.quarkiverse.langchain4j.azure.openai.runtime.AzureOpenAiRecorder;
import io.quarkiverse.langchain4j.azure.openai.runtime.config.Langchain4jAzureOpenAiConfig;
import io.quarkiverse.langchain4j.deployment.items.ChatModelProviderCandidateBuildItem;
import io.quarkiverse.langchain4j.deployment.items.EmbeddingModelProviderCandidateBuildItem;
import io.quarkiverse.langchain4j.deployment.items.ModerationModelProviderCandidateBuildItem;
import io.quarkiverse.langchain4j.deployment.items.SelectedChatModelProviderBuildItem;
import io.quarkiverse.langchain4j.deployment.items.SelectedEmbeddingModelCandidateBuildItem;
import io.quarkiverse.langchain4j.deployment.items.SelectedModerationModelProviderBuildItem;
import io.quarkus.arc.deployment.SyntheticBeanBuildItem;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.ExecutionTime;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.deployment.builditem.ShutdownContextBuildItem; | 2,888 | package io.quarkiverse.langchain4j.azure.openai.deployment;
public class AzureOpenAiProcessor {
private static final String FEATURE = "langchain4j-azure-openai";
private static final String PROVIDER = "azure-openai";
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(FEATURE);
}
@BuildStep
public void providerCandidates(BuildProducer<ChatModelProviderCandidateBuildItem> chatProducer,
BuildProducer<EmbeddingModelProviderCandidateBuildItem> embeddingProducer,
BuildProducer<ModerationModelProviderCandidateBuildItem> moderationProducer,
Langchain4jAzureOpenAiBuildConfig config) {
if (config.chatModel().enabled().isEmpty() || config.chatModel().enabled().get()) {
chatProducer.produce(new ChatModelProviderCandidateBuildItem(PROVIDER));
}
if (config.embeddingModel().enabled().isEmpty() || config.embeddingModel().enabled().get()) {
embeddingProducer.produce(new EmbeddingModelProviderCandidateBuildItem(PROVIDER));
}
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@BuildStep
@Record(ExecutionTime.RUNTIME_INIT)
void generateBeans(AzureOpenAiRecorder recorder,
Optional<SelectedChatModelProviderBuildItem> selectedChatItem,
Optional<SelectedEmbeddingModelCandidateBuildItem> selectedEmbedding,
Optional<SelectedModerationModelProviderBuildItem> selectedModeration,
Langchain4jAzureOpenAiConfig config,
BuildProducer<SyntheticBeanBuildItem> beanProducer) {
if (selectedChatItem.isPresent() && PROVIDER.equals(selectedChatItem.get().getProvider())) {
beanProducer.produce(SyntheticBeanBuildItem
.configure(CHAT_MODEL)
.setRuntimeInit()
.defaultBean()
.scope(ApplicationScoped.class)
.supplier(recorder.chatModel(config))
.done());
beanProducer.produce(SyntheticBeanBuildItem | package io.quarkiverse.langchain4j.azure.openai.deployment;
public class AzureOpenAiProcessor {
private static final String FEATURE = "langchain4j-azure-openai";
private static final String PROVIDER = "azure-openai";
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(FEATURE);
}
@BuildStep
public void providerCandidates(BuildProducer<ChatModelProviderCandidateBuildItem> chatProducer,
BuildProducer<EmbeddingModelProviderCandidateBuildItem> embeddingProducer,
BuildProducer<ModerationModelProviderCandidateBuildItem> moderationProducer,
Langchain4jAzureOpenAiBuildConfig config) {
if (config.chatModel().enabled().isEmpty() || config.chatModel().enabled().get()) {
chatProducer.produce(new ChatModelProviderCandidateBuildItem(PROVIDER));
}
if (config.embeddingModel().enabled().isEmpty() || config.embeddingModel().enabled().get()) {
embeddingProducer.produce(new EmbeddingModelProviderCandidateBuildItem(PROVIDER));
}
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@BuildStep
@Record(ExecutionTime.RUNTIME_INIT)
void generateBeans(AzureOpenAiRecorder recorder,
Optional<SelectedChatModelProviderBuildItem> selectedChatItem,
Optional<SelectedEmbeddingModelCandidateBuildItem> selectedEmbedding,
Optional<SelectedModerationModelProviderBuildItem> selectedModeration,
Langchain4jAzureOpenAiConfig config,
BuildProducer<SyntheticBeanBuildItem> beanProducer) {
if (selectedChatItem.isPresent() && PROVIDER.equals(selectedChatItem.get().getProvider())) {
beanProducer.produce(SyntheticBeanBuildItem
.configure(CHAT_MODEL)
.setRuntimeInit()
.defaultBean()
.scope(ApplicationScoped.class)
.supplier(recorder.chatModel(config))
.done());
beanProducer.produce(SyntheticBeanBuildItem | .configure(STREAMING_CHAT_MODEL) | 2 | 2023-11-13 09:10:27+00:00 | 4k |
qiusunshine/xiu | app/src/main/java/org/mozilla/xiu/browser/dlan/DlanListPopUtil.java | [
{
"identifier": "ClingDevice",
"path": "clinglibrary/src/main/java/com/qingfeng/clinglibrary/entity/ClingDevice.java",
"snippet": "public class ClingDevice implements IDevice<Device> {\n\n private Device mDevice;\n /** 是否已选中 */\n private boolean isSelected;\n\n public ClingDevice(Device dev... | import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
import com.qingfeng.clinglibrary.entity.ClingDevice;
import com.qingfeng.clinglibrary.entity.IDevice;
import com.qingfeng.clinglibrary.listener.BrowseRegistryListener;
import com.qingfeng.clinglibrary.listener.DeviceListChangedListener;
import com.qingfeng.clinglibrary.service.ClingUpnpService;
import com.qingfeng.clinglibrary.service.manager.ClingManager;
import com.qingfeng.clinglibrary.service.manager.DeviceManager;
import org.greenrobot.eventbus.EventBus;
import org.mozilla.xiu.browser.App;
import org.mozilla.xiu.browser.video.event.OnDeviceUpdateEvent;
import java.util.ArrayList;
import java.util.List; | 3,283 | package org.mozilla.xiu.browser.dlan;
/**
* 作者:By 15968
* 日期:On 2019/12/1
* 时间:At 18:03
*/
public class DlanListPopUtil {
private static final String TAG = "DlanListPopUtil";
private volatile static DlanListPopUtil sInstance;
private static boolean hasBind = false;
private ClingDevice usedDevice;
private DlanListPopUtil() {
}
public static DlanListPopUtil instance() {
if (sInstance == null) {
synchronized (DlanListPopUtil.class) {
if (sInstance == null) {
sInstance = new DlanListPopUtil();
}
}
}
return sInstance;
}
private ServiceConnection mUpnpServiceConnection;
private BrowseRegistryListener registryListener = new BrowseRegistryListener();
private ClingUpnpService beyondUpnpService;
private ClingManager clingUpnpServiceManager;
private List<ClingDevice> list = new ArrayList<>();
public List<ClingDevice> getDevices() {
return list;
}
private void init() {
list.clear();
usedDevice = null;
registryListener.setOnDeviceListChangedListener(new DeviceListChangedListener() {
@Override
public void onDeviceAdded(final IDevice device) {
list.add((ClingDevice) device); | package org.mozilla.xiu.browser.dlan;
/**
* 作者:By 15968
* 日期:On 2019/12/1
* 时间:At 18:03
*/
public class DlanListPopUtil {
private static final String TAG = "DlanListPopUtil";
private volatile static DlanListPopUtil sInstance;
private static boolean hasBind = false;
private ClingDevice usedDevice;
private DlanListPopUtil() {
}
public static DlanListPopUtil instance() {
if (sInstance == null) {
synchronized (DlanListPopUtil.class) {
if (sInstance == null) {
sInstance = new DlanListPopUtil();
}
}
}
return sInstance;
}
private ServiceConnection mUpnpServiceConnection;
private BrowseRegistryListener registryListener = new BrowseRegistryListener();
private ClingUpnpService beyondUpnpService;
private ClingManager clingUpnpServiceManager;
private List<ClingDevice> list = new ArrayList<>();
public List<ClingDevice> getDevices() {
return list;
}
private void init() {
list.clear();
usedDevice = null;
registryListener.setOnDeviceListChangedListener(new DeviceListChangedListener() {
@Override
public void onDeviceAdded(final IDevice device) {
list.add((ClingDevice) device); | if (EventBus.getDefault().hasSubscriberForEvent(OnDeviceUpdateEvent.class)) { | 7 | 2023-11-10 14:28:40+00:00 | 4k |
noear/folkmq | folkmq-server/src/main/java/org/noear/folkmq/server/pro/admin/LoginController.java | [
{
"identifier": "ImageUtils",
"path": "folkmq-server/src/main/java/org/noear/folkmq/server/pro/admin/utils/ImageUtils.java",
"snippet": "public class ImageUtils {\n /*\n * 获取验证码图片\n */\n public static BufferedImage getValidationImage(String validation) {\n return getValidationImage(... | import org.noear.folkmq.server.pro.admin.utils.ImageUtils;
import org.noear.folkmq.server.pro.admin.utils.RandomUtils;
import org.noear.folkmq.server.pro.common.ConfigNames;
import org.noear.solon.Solon;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Post;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.core.handle.ModelAndView;
import org.noear.solon.core.handle.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException; | 1,784 | package org.noear.folkmq.server.pro.admin;
/**
* 登录控制器
*
* @author noear
* @since 1.0
*/
@Controller
public class LoginController extends BaseController {
static final Logger log = LoggerFactory.getLogger(LoginController.class);
private final String adminPassword;
private final String adminUser = "admin";
public LoginController(){ | package org.noear.folkmq.server.pro.admin;
/**
* 登录控制器
*
* @author noear
* @since 1.0
*/
@Controller
public class LoginController extends BaseController {
static final Logger log = LoggerFactory.getLogger(LoginController.class);
private final String adminPassword;
private final String adminUser = "admin";
public LoginController(){ | adminPassword = Solon.cfg().get(ConfigNames.folkmq_admin, ""); | 2 | 2023-11-18 19:09:28+00:00 | 4k |
leluque/java2uml | src/main/java/br/com/luque/java2uml/yuml/writer/classdiagram/YUMLClassWriter.java | [
{
"identifier": "Clazz",
"path": "src/main/java/br/com/luque/java2uml/core/classdiagram/reflection/model/Clazz.java",
"snippet": "public abstract class Clazz extends BaseItem {\n private final Class<?> javaClass;\n private final boolean abstract_;\n private boolean interface_;\n\n public Cla... | import br.com.luque.java2uml.core.classdiagram.reflection.model.Clazz;
import br.com.luque.java2uml.core.classdiagram.reflection.model.Method;
import br.com.luque.java2uml.core.classdiagram.reflection.model.ScopedClazz;
import br.com.luque.java2uml.core.classdiagram.reflection.model.UnscopedClazz;
import br.com.luque.java2uml.core.classdiagram.writer.ClassWriter;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream; | 2,375 | package br.com.luque.java2uml.yuml.writer.classdiagram;
public class YUMLClassWriter implements ClassWriter {
private final YUMLFieldWriter attributeWriter;
private final YUMLConstructorWriter constructorWriter;
private final YUMLMethodWriter methodWriter;
private boolean generateAccessors = false;
public YUMLClassWriter(YUMLFieldWriter attributeWriter,
YUMLConstructorWriter constructorWriter,
YUMLMethodWriter methodWriter) {
this.attributeWriter = Objects.requireNonNull(attributeWriter);
this.constructorWriter = Objects.requireNonNull(constructorWriter);
this.methodWriter = Objects.requireNonNull(methodWriter);
}
public YUMLClassWriter generateAccessors(boolean generateAccessors) {
this.generateAccessors = generateAccessors;
return this;
}
@Override | package br.com.luque.java2uml.yuml.writer.classdiagram;
public class YUMLClassWriter implements ClassWriter {
private final YUMLFieldWriter attributeWriter;
private final YUMLConstructorWriter constructorWriter;
private final YUMLMethodWriter methodWriter;
private boolean generateAccessors = false;
public YUMLClassWriter(YUMLFieldWriter attributeWriter,
YUMLConstructorWriter constructorWriter,
YUMLMethodWriter methodWriter) {
this.attributeWriter = Objects.requireNonNull(attributeWriter);
this.constructorWriter = Objects.requireNonNull(constructorWriter);
this.methodWriter = Objects.requireNonNull(methodWriter);
}
public YUMLClassWriter generateAccessors(boolean generateAccessors) {
this.generateAccessors = generateAccessors;
return this;
}
@Override | public String getString(Clazz clazz) { | 0 | 2023-11-10 16:49:58+00:00 | 4k |
javpower/JavaVision | src/main/java/com/github/javpower/javavision/detect/FaceDetect.java | [
{
"identifier": "AbstractDjlTranslator",
"path": "src/main/java/com/github/javpower/javavision/detect/translator/AbstractDjlTranslator.java",
"snippet": "public abstract class AbstractDjlTranslator<T> {\n\n public String modelName;\n\n public Map<String, Object> arguments;\n\n static {\n ... | import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.translate.Translator;
import com.github.javpower.javavision.detect.translator.AbstractDjlTranslator;
import com.github.javpower.javavision.detect.translator.FaceDetectionTranslator;
import java.util.Map; | 2,689 | package com.github.javpower.javavision.detect;
/**
* @author gc.x
* @date 2022-04
*/
public class FaceDetect extends AbstractDjlTranslator<DetectedObjects> {
public FaceDetect(Map<String, Object> arguments) {
super("ultranet.zip",arguments);
}
@Override
protected Translator<Image, DetectedObjects> getTranslator(Map<String, Object> arguments) {
int topK = (Integer) arguments.get("topK");
double confThresh = (Double) arguments.get("confThresh");
double nmsThresh = (Double)arguments.get("nmsThresh");
double[] variance = {0.1f, 0.2f};
int[][] scales = {{10, 16, 24}, {32, 48}, {64, 96}, {128, 192, 256}};
int[] steps = {8, 16, 32, 64}; | package com.github.javpower.javavision.detect;
/**
* @author gc.x
* @date 2022-04
*/
public class FaceDetect extends AbstractDjlTranslator<DetectedObjects> {
public FaceDetect(Map<String, Object> arguments) {
super("ultranet.zip",arguments);
}
@Override
protected Translator<Image, DetectedObjects> getTranslator(Map<String, Object> arguments) {
int topK = (Integer) arguments.get("topK");
double confThresh = (Double) arguments.get("confThresh");
double nmsThresh = (Double)arguments.get("nmsThresh");
double[] variance = {0.1f, 0.2f};
int[][] scales = {{10, 16, 24}, {32, 48}, {64, 96}, {128, 192, 256}};
int[] steps = {8, 16, 32, 64}; | return new FaceDetectionTranslator(confThresh, nmsThresh, variance, topK, scales, steps); | 1 | 2023-11-10 01:57:37+00:00 | 4k |
tientham/rn-video | android/src/main/java/com/rnvideo/RnVideoPackage.java | [
{
"identifier": "BlurGifViewManager",
"path": "android/src/main/java/com/rnvideo/video/BlurGifViewManager.java",
"snippet": "public class BlurGifViewManager extends ViewGroupManager<BlurGifView> {\n private static final String REACT_PACKAGE = \"RnVideo-3sbg\";\n private final String SET_SOURCE = \"sou... | import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.rnvideo.video.BlurGifViewManager;
import com.rnvideo.video.GifViewManager;
import com.rnvideo.video.RnVideoConfig;
import com.rnvideo.video.RnVideoConfigImpl;
import com.rnvideo.video.ThreeSecPlayerViewManager;
import com.rnvideo.video.ThreeSecVideoViewManager;
import com.rnvideo.video.VideoViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List; | 2,562 | package com.rnvideo;
public class RnVideoPackage implements ReactPackage {
private RnVideoConfig config;
public RnVideoPackage() {
}
public RnVideoPackage(RnVideoConfig config) {
this.config = config;
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
if (config == null) {
config = new RnVideoConfigImpl(reactContext);
}
return Arrays.<ViewManager>asList(
new VideoViewManager(config),
new ThreeSecVideoViewManager(config),
new ThreeSecPlayerViewManager(),
new GifViewManager(), | package com.rnvideo;
public class RnVideoPackage implements ReactPackage {
private RnVideoConfig config;
public RnVideoPackage() {
}
public RnVideoPackage(RnVideoConfig config) {
this.config = config;
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
if (config == null) {
config = new RnVideoConfigImpl(reactContext);
}
return Arrays.<ViewManager>asList(
new VideoViewManager(config),
new ThreeSecVideoViewManager(config),
new ThreeSecPlayerViewManager(),
new GifViewManager(), | new BlurGifViewManager() | 0 | 2023-11-11 16:54:59+00:00 | 4k |
feiniaojin/graceful-response-boot2 | src/main/java/com/feiniaojin/gracefulresponse/advice/GlobalExceptionAdvice.java | [
{
"identifier": "ExceptionAliasRegister",
"path": "src/main/java/com/feiniaojin/gracefulresponse/ExceptionAliasRegister.java",
"snippet": "public class ExceptionAliasRegister {\n\n private final Logger logger = LoggerFactory.getLogger(ExceptionAliasRegister.class);\n\n private ConcurrentHashMap<Cl... | import com.feiniaojin.gracefulresponse.ExceptionAliasRegister;
import com.feiniaojin.gracefulresponse.GracefulResponseException;
import com.feiniaojin.gracefulresponse.GracefulResponseProperties;
import com.feiniaojin.gracefulresponse.api.ExceptionAliasFor;
import com.feiniaojin.gracefulresponse.api.ExceptionMapper;
import com.feiniaojin.gracefulresponse.api.ResponseFactory;
import com.feiniaojin.gracefulresponse.api.ResponseStatusFactory;
import com.feiniaojin.gracefulresponse.data.Response;
import com.feiniaojin.gracefulresponse.data.ResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource; | 2,606 | package com.feiniaojin.gracefulresponse.advice;
/**
* 全局异常处理.
*
* @author <a href="mailto:943868899@qq.com">Yujie</a>
* @version 0.1
* @since 0.1
*/
@ControllerAdvice
@Order(200)
public class GlobalExceptionAdvice implements ApplicationContextAware {
private final Logger logger = LoggerFactory.getLogger(GlobalExceptionAdvice.class);
@Resource | package com.feiniaojin.gracefulresponse.advice;
/**
* 全局异常处理.
*
* @author <a href="mailto:943868899@qq.com">Yujie</a>
* @version 0.1
* @since 0.1
*/
@ControllerAdvice
@Order(200)
public class GlobalExceptionAdvice implements ApplicationContextAware {
private final Logger logger = LoggerFactory.getLogger(GlobalExceptionAdvice.class);
@Resource | private ResponseStatusFactory responseStatusFactory; | 4 | 2023-11-15 10:54:19+00:00 | 4k |
innogames/flink-real-time-crm | src/main/java/com/innogames/analytics/rtcrm/App.java | [
{
"identifier": "Config",
"path": "src/main/java/com/innogames/analytics/rtcrm/config/Config.java",
"snippet": "@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)\npublic class Config {\n\n\tprivate int defaultParallelism;\n\tprivate int checkpointInterval;\n\tprivate String checkpointDir;\n\... | import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.innogames.analytics.rtcrm.config.Config;
import com.innogames.analytics.rtcrm.entity.Campaign;
import com.innogames.analytics.rtcrm.entity.TrackingEvent;
import com.innogames.analytics.rtcrm.function.EvaluateFilter;
import com.innogames.analytics.rtcrm.map.StringToCampaign;
import com.innogames.analytics.rtcrm.map.StringToTrackingEvent;
import com.innogames.analytics.rtcrm.sink.TriggerCampaignSink;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; | 3,506 | package com.innogames.analytics.rtcrm;
public class App {
// pass config path via parameter or use config from resources as default
private static final String configParameter = "config";
private static final String configResource = "config.json";
// state key: campaign ID
// state value: campaign definition
public static final MapStateDescriptor<Integer, Campaign> CAMPAIGN_STATE_DESCRIPTOR = new MapStateDescriptor<>(
"CampaignState",
BasicTypeInfo.INT_TYPE_INFO,
TypeInformation.of(new TypeHint<>() {})
);
public static void main(String[] args) throws Exception {
// 1 - parse config
final ParameterTool parameterTool = ParameterTool.fromArgs(args); | package com.innogames.analytics.rtcrm;
public class App {
// pass config path via parameter or use config from resources as default
private static final String configParameter = "config";
private static final String configResource = "config.json";
// state key: campaign ID
// state value: campaign definition
public static final MapStateDescriptor<Integer, Campaign> CAMPAIGN_STATE_DESCRIPTOR = new MapStateDescriptor<>(
"CampaignState",
BasicTypeInfo.INT_TYPE_INFO,
TypeInformation.of(new TypeHint<>() {})
);
public static void main(String[] args) throws Exception {
// 1 - parse config
final ParameterTool parameterTool = ParameterTool.fromArgs(args); | final Config config = readConfigFromFileOrResource(new ObjectMapper(), new TypeReference<>() {}, parameterTool); | 0 | 2023-11-12 17:52:45+00:00 | 4k |
BlyznytsiaOrg/bring | web/src/test/java/io/github/blyznytsiaorg/bring/web/MixConfigurationBeanAndRestControllerTest.java | [
{
"identifier": "BringApplicationContext",
"path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/context/impl/BringApplicationContext.java",
"snippet": "@Slf4j\npublic class BringApplicationContext extends AnnotationBringBeanRegistry implements BringBeanFactory {\n\n private final BeanPostPr... | import io.github.blyznytsiaorg.bring.core.context.impl.BringApplicationContext;
import io.github.blyznytsiaorg.bring.web.server.properties.ServerProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import testdata.mixconfigurationandrestcontroller.dto.UserRequest;
import testdata.mixconfigurationandrestcontroller.dto.UserResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import static io.github.blyznytsiaorg.bring.web.RestControllerTest.APPLICATION_JSON;
import static org.assertj.core.api.Assertions.assertThat; | 1,834 | package io.github.blyznytsiaorg.bring.web;
class MixConfigurationBeanAndRestControllerTest {
public static final String SHORTEN_PATH = "/api/shorten";
public static final String PACKAGE = "testdata.mixconfigurationandrestcontroller";
public static final String URL = "http://localhost:%s%s";
public static final String CONTENT_TYPE = "Content-Type";
private static ServerProperties serverProperties;
private static ObjectMapper objectMapper;
private HttpClient httpClient;
@BeforeAll
static void beforeAll() {
BringApplicationContext bringApplicationContext = BringWebApplication.run(PACKAGE);
objectMapper = bringApplicationContext.getBean(ObjectMapper.class);
serverProperties = bringApplicationContext.getBean(ServerProperties.class);
}
@BeforeEach
void setUp() {
httpClient = HttpClient.newHttpClient();
}
@Test
@DisplayName("Should return model with one field")
void shouldReturnModelWithOneField() throws URISyntaxException, IOException, InterruptedException {
//given
String url = getHost() + SHORTEN_PATH;
| package io.github.blyznytsiaorg.bring.web;
class MixConfigurationBeanAndRestControllerTest {
public static final String SHORTEN_PATH = "/api/shorten";
public static final String PACKAGE = "testdata.mixconfigurationandrestcontroller";
public static final String URL = "http://localhost:%s%s";
public static final String CONTENT_TYPE = "Content-Type";
private static ServerProperties serverProperties;
private static ObjectMapper objectMapper;
private HttpClient httpClient;
@BeforeAll
static void beforeAll() {
BringApplicationContext bringApplicationContext = BringWebApplication.run(PACKAGE);
objectMapper = bringApplicationContext.getBean(ObjectMapper.class);
serverProperties = bringApplicationContext.getBean(ServerProperties.class);
}
@BeforeEach
void setUp() {
httpClient = HttpClient.newHttpClient();
}
@Test
@DisplayName("Should return model with one field")
void shouldReturnModelWithOneField() throws URISyntaxException, IOException, InterruptedException {
//given
String url = getHost() + SHORTEN_PATH;
| var userRequest = new UserRequest(); | 2 | 2023-11-10 13:42:05+00:00 | 4k |
johndeweyzxc/AWPS-Command | app/src/main/java/com/johndeweydev/awps/view/hashesfragment/HashesRvAdapter.java | [
{
"identifier": "HashInfoEntity",
"path": "app/src/main/java/com/johndeweydev/awps/model/data/HashInfoEntity.java",
"snippet": "@Entity(tableName = \"hash_information\")\npublic class HashInfoEntity {\n\n @PrimaryKey(autoGenerate = true)\n public int uid;\n @ColumnInfo(name = \"ssid\")\n public Stri... | import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.card.MaterialCardView;
import com.johndeweydev.awps.R;
import com.johndeweydev.awps.model.data.HashInfoEntity;
import com.johndeweydev.awps.view.hashinfomodalbottomsheetdialog.HashInfoModalBottomArgs;
import java.util.ArrayList; | 1,628 | package com.johndeweydev.awps.view.hashesfragment;
public class HashesRvAdapter extends RecyclerView.Adapter<HashesRvAdapter.HashesAdapterViewHolder> {
public interface Event {
void onHashInfoClick(HashInfoModalBottomArgs hashInfoModalBottomArgs);
}
| package com.johndeweydev.awps.view.hashesfragment;
public class HashesRvAdapter extends RecyclerView.Adapter<HashesRvAdapter.HashesAdapterViewHolder> {
public interface Event {
void onHashInfoClick(HashInfoModalBottomArgs hashInfoModalBottomArgs);
}
| private final ArrayList<HashInfoEntity> hashInfoEntityList = new ArrayList<>(); | 0 | 2023-11-15 15:54:39+00:00 | 4k |
Samuel-Ricardo/Pic-Pay_simplified | src/main/java/com/picpay/payment/application/service/TransactionServiceImpl.java | [
{
"identifier": "MerchantUserCantTransactPolicyImpl",
"path": "src/main/java/com/picpay/payment/application/policy/transaction/MerchantUserCantTransactPolicyImpl.java",
"snippet": "@Component\npublic class MerchantUserCantTransactPolicyImpl implements MerchantUserCantTransactPolicy {\n @Override\n ... | import com.picpay.payment.application.policy.transaction.MerchantUserCantTransactPolicyImpl;
import com.picpay.payment.application.usecase.transaction.FindAllTransactionsUseCase;
import com.picpay.payment.application.usecase.transaction.SaveTransactionUseCase;
import com.picpay.payment.application.usecase.transaction.TransactionUseCase;
import com.picpay.payment.domain.dto.transaction.TransactionDTO;
import com.picpay.payment.domain.entities.transaction.Transaction;
import com.picpay.payment.domain.entities.user.User;
import com.picpay.payment.domain.policy.transaction.CannotTransactWithoutSufficientBalancePolicy;
import com.picpay.payment.domain.policy.transaction.MerchantUserCantTransactPolicy;
import com.picpay.payment.domain.policy.transaction.SendNotificationOnTransactPolicy;
import com.picpay.payment.domain.services.AuthorizationService;
import com.picpay.payment.domain.services.TransactionService;
import com.picpay.payment.domain.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List; | 1,661 | package com.picpay.payment.application.service;
@Service
public class TransactionServiceImpl implements TransactionService {
@Autowired
private AuthorizationService authorizationService;
@Autowired
private UserService userService;
@Autowired
private MerchantUserCantTransactPolicy merchantUserCantTransactPolicy;
@Autowired
private CannotTransactWithoutSufficientBalancePolicy cannotTransactWithoutSufficientBalancePolicy;
@Autowired
private SendNotificationOnTransactPolicy sendNotificationOnTransactPolicy;
@Autowired
private TransactionUseCase transct;
@Autowired
private SaveTransactionUseCase save;
@Autowired
private FindAllTransactionsUseCase findAllTransactions;
@Override
public boolean validate(User sender, BigDecimal amount) throws Exception {
if(merchantUserCantTransactPolicy.execute(sender.getUserType()))
throw new Exception("Merchant User is not authorized to transact");
if(cannotTransactWithoutSufficientBalancePolicy.execute(sender, amount))
throw new Exception("Balance is not enough");
if(!authorizationService.isTransactionAuthorized(sender, amount))
throw new Exception("Transaction Not Authorized, try again later...");
return true;
}
@Override | package com.picpay.payment.application.service;
@Service
public class TransactionServiceImpl implements TransactionService {
@Autowired
private AuthorizationService authorizationService;
@Autowired
private UserService userService;
@Autowired
private MerchantUserCantTransactPolicy merchantUserCantTransactPolicy;
@Autowired
private CannotTransactWithoutSufficientBalancePolicy cannotTransactWithoutSufficientBalancePolicy;
@Autowired
private SendNotificationOnTransactPolicy sendNotificationOnTransactPolicy;
@Autowired
private TransactionUseCase transct;
@Autowired
private SaveTransactionUseCase save;
@Autowired
private FindAllTransactionsUseCase findAllTransactions;
@Override
public boolean validate(User sender, BigDecimal amount) throws Exception {
if(merchantUserCantTransactPolicy.execute(sender.getUserType()))
throw new Exception("Merchant User is not authorized to transact");
if(cannotTransactWithoutSufficientBalancePolicy.execute(sender, amount))
throw new Exception("Balance is not enough");
if(!authorizationService.isTransactionAuthorized(sender, amount))
throw new Exception("Transaction Not Authorized, try again later...");
return true;
}
@Override | public Transaction transact(TransactionDTO dto) throws Exception { | 4 | 2023-11-18 18:00:28+00:00 | 4k |
sondosaabed/Taskaty | app/src/main/java/com/taskaty/taskManagment/EditTask.java | [
{
"identifier": "StatusInform",
"path": "app/src/main/java/com/taskaty/informational/StatusInform.java",
"snippet": "public class StatusInform extends AppCompatActivity {\n /*\n Attributes\n */\n Button back;\n @Override\n public void onCreate(Bundle savedInstanceState) {\n ... | import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import androidx.appcompat.app.AppCompatActivity;
import com.taskaty.R;
import com.taskaty.informational.StatusInform;
import com.taskaty.model.Task;
import com.taskaty.model.Tasks;
import java.time.LocalDate;
import java.util.Calendar; | 2,309 | package com.taskaty.taskManagment;
/*
I have created this activity to enable the user to update an existing task, for example to set it as done
*/
public class EditTask extends AppCompatActivity {
/*
Attributes
*/
Button update;
Button delete;
EditText title;
EditText description;
Button updateDate;
EditText date;
Spinner categorySpinner;
CheckBox isDone;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int selectedTaskID = getIntent().getIntExtra("selectedTaskID", 0);
initialize(selectedTaskID);
}
private void initialize(int selectedTaskID) {
if(getSupportActionBar()!=null)
getSupportActionBar().hide();
setContentView(R.layout.edit_task);
setUpdate(findViewById(R.id.updateTaskButton));
setUpdateDate(findViewById(R.id.uodateDate));
setTitle((EditText) findViewById(R.id.titleEditTextUpdate));
setDescriptionn(findViewById(R.id.descriptionEditTextUpdate));
setDate(findViewById(R.id.dateEditTextUpdate));
setCategorySpinner(findViewById(R.id.categorySpinnerUpdate));
setIsDone(findViewById(R.id.isDone));
setDelete(findViewById(R.id.delete));
handle_date(getUpdateDate());
handle_update(getUpdate(), selectedTaskID);
handle_delete(getDelete(), selectedTaskID);
setValuesToBeUpdated(selectedTaskID);
}
private void handle_delete(Button delete, int selectedTaskID) {
delete.setOnClickListener(veiw->{
Tasks.deleteTask(selectedTaskID);
Intent intent = new Intent(this, StatusInform.class);
intent.putExtra("status", "deleted");
startActivity(intent);
});
}
private void setValuesToBeUpdated(int selectedTaskID) {
/*
In this method, When the usre wants to update a task it's previous values should be there
*/ | package com.taskaty.taskManagment;
/*
I have created this activity to enable the user to update an existing task, for example to set it as done
*/
public class EditTask extends AppCompatActivity {
/*
Attributes
*/
Button update;
Button delete;
EditText title;
EditText description;
Button updateDate;
EditText date;
Spinner categorySpinner;
CheckBox isDone;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int selectedTaskID = getIntent().getIntExtra("selectedTaskID", 0);
initialize(selectedTaskID);
}
private void initialize(int selectedTaskID) {
if(getSupportActionBar()!=null)
getSupportActionBar().hide();
setContentView(R.layout.edit_task);
setUpdate(findViewById(R.id.updateTaskButton));
setUpdateDate(findViewById(R.id.uodateDate));
setTitle((EditText) findViewById(R.id.titleEditTextUpdate));
setDescriptionn(findViewById(R.id.descriptionEditTextUpdate));
setDate(findViewById(R.id.dateEditTextUpdate));
setCategorySpinner(findViewById(R.id.categorySpinnerUpdate));
setIsDone(findViewById(R.id.isDone));
setDelete(findViewById(R.id.delete));
handle_date(getUpdateDate());
handle_update(getUpdate(), selectedTaskID);
handle_delete(getDelete(), selectedTaskID);
setValuesToBeUpdated(selectedTaskID);
}
private void handle_delete(Button delete, int selectedTaskID) {
delete.setOnClickListener(veiw->{
Tasks.deleteTask(selectedTaskID);
Intent intent = new Intent(this, StatusInform.class);
intent.putExtra("status", "deleted");
startActivity(intent);
});
}
private void setValuesToBeUpdated(int selectedTaskID) {
/*
In this method, When the usre wants to update a task it's previous values should be there
*/ | Task taskToUpdate = Tasks.getTaskaty().get(selectedTaskID); | 1 | 2023-11-10 13:10:12+00:00 | 4k |
Charles7c/continew-starter | continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/handler/CrudRequestMappingHandlerMapping.java | [
{
"identifier": "ExceptionUtils",
"path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/util/ExceptionUtils.java",
"snippet": "@Slf4j\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class ExceptionUtils {\n\n /**\n * 打印线程异常信息\n *\n * @param runnable 线... | import cn.hutool.core.util.ArrayUtil;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.pattern.PathPatternParser;
import top.charles7c.continew.starter.core.util.ExceptionUtils;
import top.charles7c.continew.starter.extension.crud.annotation.CrudRequestMapping;
import top.charles7c.continew.starter.extension.crud.enums.Api;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method; | 1,601 | /*
* 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.extension.crud.handler;
/**
* CRUD 请求映射器处理器映射器
*
* @author Charles7c
* @since 1.0.0
*/
public class CrudRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
@Override
protected RequestMappingInfo getMappingForMethod(@NonNull Method method, @NonNull Class<?> handlerType) {
RequestMappingInfo requestMappingInfo = super.getMappingForMethod(method, handlerType);
if (null == requestMappingInfo) {
return null;
}
// 如果没有声明 @CrudRequestMapping 注解,直接返回
if (!handlerType.isAnnotationPresent(CrudRequestMapping.class)) {
return requestMappingInfo;
}
CrudRequestMapping crudRequestMapping = handlerType.getDeclaredAnnotation(CrudRequestMapping.class);
// 过滤 API,如果非本类中定义,且 API 列表中不包含,则忽略
Api[] apiArr = crudRequestMapping.api(); | /*
* 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.extension.crud.handler;
/**
* CRUD 请求映射器处理器映射器
*
* @author Charles7c
* @since 1.0.0
*/
public class CrudRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
@Override
protected RequestMappingInfo getMappingForMethod(@NonNull Method method, @NonNull Class<?> handlerType) {
RequestMappingInfo requestMappingInfo = super.getMappingForMethod(method, handlerType);
if (null == requestMappingInfo) {
return null;
}
// 如果没有声明 @CrudRequestMapping 注解,直接返回
if (!handlerType.isAnnotationPresent(CrudRequestMapping.class)) {
return requestMappingInfo;
}
CrudRequestMapping crudRequestMapping = handlerType.getDeclaredAnnotation(CrudRequestMapping.class);
// 过滤 API,如果非本类中定义,且 API 列表中不包含,则忽略
Api[] apiArr = crudRequestMapping.api(); | Api api = ExceptionUtils.exToNull(() -> Api.valueOf(method.getName().toUpperCase())); | 0 | 2023-11-16 15:48:18+00:00 | 4k |
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 S... | 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,973 | 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) {
return false;
}
}
/**
* Restituisce true se l'elemento è un operatore binario.
*
* @param item Elemento dello stack.
* @return Restituisce true se l'elemento è un operatore binario.
*/
public static boolean isBinaryOperator(String item) {
return Arrays.asList("+", "-", "*", "/").contains(item);
}
/**
* Restituisce true se l'elemento è un operatore unario.
*
* @param item Elemento dello stack.
* @return Restituisce true se l'elemento è un operatore unario.
*/
public static boolean isUnaryOperator(String item) {
return Arrays.asList("+-", "sqrt").contains(item);
}
/**
* Restituisce true se l'elemento è un operatore unario o binario.
*
* @param item Elemento dello stack.
* @return Restituisce true se l'elemento è un operatore unario o binario.
*/
public static boolean isOperator(String item) {
return isBinaryOperator(item) || isUnaryOperator(item);
}
/**
* Restituisce true se l'elemento indica un'operazione di manipolazione
* dello stack.
*
* @param item Elemento dello stack.
* @return Restituisce true se l'elemento indica un'operazione di
* manipolazione dello stack.
*/
public static boolean isStackManipulation(String item) {
return Arrays.asList("clear", "drop", "dup", "swap", "over").contains(item);
}
/**
* Restituisce true se l'elemento specifica un'operazione su variabile.
*
* @param item Elemento dello stack.
* @return Restituisce true se l'elemento specifica un'operazione su
* variabile.
*/
public static boolean isVariableOperation(String item) {
String element = item.replaceAll("\\s", "");
Pattern variablePattern = Pattern.compile("[><+-][a-z]");
return variablePattern.matcher(element).find();
}
/**
* Metodo di risoluzione dello stack di operandi e operazioni. L'obiettivo
* del metodo {@code solve} è di fornire il risultato complesso della
* valutazione del sotto-stack su cui viene chiamato. Utilizza, quindi, un
* approccio ricorsivo.
*
* @return Restituisce il risultato della valutazione dello stack di
* operandi e operazioni.
* @throws RPNException Se vengono riscontrati errori durante la valutazione
* dello stack di operandi e operazioni.
* @see Complex
*/
public Complex solve() throws RPNException {
if (isEmpty()) { | 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) {
return false;
}
}
/**
* Restituisce true se l'elemento è un operatore binario.
*
* @param item Elemento dello stack.
* @return Restituisce true se l'elemento è un operatore binario.
*/
public static boolean isBinaryOperator(String item) {
return Arrays.asList("+", "-", "*", "/").contains(item);
}
/**
* Restituisce true se l'elemento è un operatore unario.
*
* @param item Elemento dello stack.
* @return Restituisce true se l'elemento è un operatore unario.
*/
public static boolean isUnaryOperator(String item) {
return Arrays.asList("+-", "sqrt").contains(item);
}
/**
* Restituisce true se l'elemento è un operatore unario o binario.
*
* @param item Elemento dello stack.
* @return Restituisce true se l'elemento è un operatore unario o binario.
*/
public static boolean isOperator(String item) {
return isBinaryOperator(item) || isUnaryOperator(item);
}
/**
* Restituisce true se l'elemento indica un'operazione di manipolazione
* dello stack.
*
* @param item Elemento dello stack.
* @return Restituisce true se l'elemento indica un'operazione di
* manipolazione dello stack.
*/
public static boolean isStackManipulation(String item) {
return Arrays.asList("clear", "drop", "dup", "swap", "over").contains(item);
}
/**
* Restituisce true se l'elemento specifica un'operazione su variabile.
*
* @param item Elemento dello stack.
* @return Restituisce true se l'elemento specifica un'operazione su
* variabile.
*/
public static boolean isVariableOperation(String item) {
String element = item.replaceAll("\\s", "");
Pattern variablePattern = Pattern.compile("[><+-][a-z]");
return variablePattern.matcher(element).find();
}
/**
* Metodo di risoluzione dello stack di operandi e operazioni. L'obiettivo
* del metodo {@code solve} è di fornire il risultato complesso della
* valutazione del sotto-stack su cui viene chiamato. Utilizza, quindi, un
* approccio ricorsivo.
*
* @return Restituisce il risultato della valutazione dello stack di
* operandi e operazioni.
* @throws RPNException Se vengono riscontrati errori durante la valutazione
* dello stack di operandi e operazioni.
* @see Complex
*/
public Complex solve() throws RPNException {
if (isEmpty()) { | throw new InsufficientArgumentsException("Argomenti insufficienti!", "Gli argomenti forniti sono insufficienti."); | 1 | 2023-11-17 20:16:14+00:00 | 4k |
SplitfireUptown/datalinkx | datalinkx-server/src/main/java/com/datalinkx/dataserver/controller/JobGraphController.java | [
{
"identifier": "JobForm",
"path": "datalinkx-server/src/main/java/com/datalinkx/dataserver/controller/form/JobForm.java",
"snippet": "public class JobForm {\n\n\t@Data\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic static final class ConfigForm {\n\t\t// mysql/postgreSQL/es需要的参数\n\t\tprivate ... | import java.util.List;
import com.datalinkx.dataserver.controller.form.JobForm;
import com.datalinkx.driver.model.DataTransJobDetail;
import com.datalinkx.common.result.WebResult;
import com.datalinkx.dataserver.controller.form.JobStateForm;
import com.datalinkx.dataserver.service.DtsJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; | 2,516 | package com.datalinkx.dataserver.controller;
@Slf4j
@RestController
@RequestMapping("/api/job_graph")
public class JobGraphController {
@Autowired
private DtsJobService dtsJobService;
@RequestMapping("/execute_info")
public WebResult<DataTransJobDetail> getJobExecInfo(String jobId,
@RequestParam(value = "tableIds", required = false) List<String> tableIds,
@RequestParam(value = "tbDetail", defaultValue = "false") Boolean tbDetail) {
return WebResult.of(dtsJobService.getJobExecInfo(jobId, tableIds, tbDetail));
}
@RequestMapping("/update_job")
public WebResult<String> updateJobStatus(JobStateForm jobStateForm) {
return WebResult.of(this.dtsJobService.updateJobStatus(jobStateForm));
}
@RequestMapping("/update_sync_mode") | package com.datalinkx.dataserver.controller;
@Slf4j
@RestController
@RequestMapping("/api/job_graph")
public class JobGraphController {
@Autowired
private DtsJobService dtsJobService;
@RequestMapping("/execute_info")
public WebResult<DataTransJobDetail> getJobExecInfo(String jobId,
@RequestParam(value = "tableIds", required = false) List<String> tableIds,
@RequestParam(value = "tbDetail", defaultValue = "false") Boolean tbDetail) {
return WebResult.of(dtsJobService.getJobExecInfo(jobId, tableIds, tbDetail));
}
@RequestMapping("/update_job")
public WebResult<String> updateJobStatus(JobStateForm jobStateForm) {
return WebResult.of(this.dtsJobService.updateJobStatus(jobStateForm));
}
@RequestMapping("/update_sync_mode") | public WebResult<String> updateSyncMode(JobForm.SyncModifyForm syncmodifyForm) { | 0 | 2023-11-16 02:22:52+00:00 | 4k |
DJ-Raven/raven-dashboard | src/raven/drawer/MyDrawerBuilder.java | [
{
"identifier": "TestForm",
"path": "src/raven/form/TestForm.java",
"snippet": "public class TestForm extends TabbedForm {\n\n /**\n * Creates new form TestForm\n */\n public TestForm() {\n initComponents();\n }\n\n /**\n * This method is called from within the constructor... | import raven.drawer.component.SimpleDrawerBuilder;
import raven.drawer.component.footer.SimpleFooterData;
import raven.drawer.component.header.SimpleHeaderData;
import raven.drawer.component.menu.MenuAction;
import raven.drawer.component.menu.MenuEvent;
import raven.drawer.component.menu.MenuValidation;
import raven.drawer.component.menu.SimpleMenuOption;
import raven.form.TestForm;
import raven.main.Main;
import raven.swing.AvatarIcon;
import raven.tabbed.WindowsTabbed; | 2,798 | package raven.drawer;
/**
*
* @author RAVEN
*/
public class MyDrawerBuilder extends SimpleDrawerBuilder {
@Override
public SimpleHeaderData getSimpleHeaderData() {
return new SimpleHeaderData()
.setIcon(new AvatarIcon(getClass().getResource("/raven/image/profile.png"), 60, 60, 999))
.setTitle("Ra Ven")
.setDescription("raven@gmail.com");
}
@Override
public SimpleMenuOption getSimpleMenuOption() {
String menus[][] = {
{"~MAIN~"},
{"Dashboard"},
{"~WEB APP~"},
{"Email", "Inbox", "Read", "Compost"},
{"Chat"},
{"Calendar"},
{"~COMPONENT~"},
{"Advanced UI", "Cropper", "Owl Carousel", "Sweet Alert"},
{"Forms", "Basic Elements", "Advanced Elements", "SEditors", "Wizard"},
{"~OTHER~"},
{"Charts", "Apex", "Flot", "Sparkline"},
{"Icons", "Feather Icons", "Flag Icons", "Mdi Icons"},
{"Special Pages", "Blank page", "Faq", "Invoice", "Profile", "Pricing", "Timeline"},
{"Logout"}};
String icons[] = {
"dashboard.svg",
"email.svg",
"chat.svg",
"calendar.svg",
"ui.svg",
"forms.svg",
"chart.svg",
"icon.svg",
"page.svg",
"logout.svg"};
return new SimpleMenuOption()
.setMenus(menus)
.setIcons(icons)
.setBaseIconPath("raven/drawer/icon")
.setIconScale(0.45f)
.addMenuEvent(new MenuEvent() {
@Override
public void selected(MenuAction action, int index, int subIndex) {
if (index == 0) { | package raven.drawer;
/**
*
* @author RAVEN
*/
public class MyDrawerBuilder extends SimpleDrawerBuilder {
@Override
public SimpleHeaderData getSimpleHeaderData() {
return new SimpleHeaderData()
.setIcon(new AvatarIcon(getClass().getResource("/raven/image/profile.png"), 60, 60, 999))
.setTitle("Ra Ven")
.setDescription("raven@gmail.com");
}
@Override
public SimpleMenuOption getSimpleMenuOption() {
String menus[][] = {
{"~MAIN~"},
{"Dashboard"},
{"~WEB APP~"},
{"Email", "Inbox", "Read", "Compost"},
{"Chat"},
{"Calendar"},
{"~COMPONENT~"},
{"Advanced UI", "Cropper", "Owl Carousel", "Sweet Alert"},
{"Forms", "Basic Elements", "Advanced Elements", "SEditors", "Wizard"},
{"~OTHER~"},
{"Charts", "Apex", "Flot", "Sparkline"},
{"Icons", "Feather Icons", "Flag Icons", "Mdi Icons"},
{"Special Pages", "Blank page", "Faq", "Invoice", "Profile", "Pricing", "Timeline"},
{"Logout"}};
String icons[] = {
"dashboard.svg",
"email.svg",
"chat.svg",
"calendar.svg",
"ui.svg",
"forms.svg",
"chart.svg",
"icon.svg",
"page.svg",
"logout.svg"};
return new SimpleMenuOption()
.setMenus(menus)
.setIcons(icons)
.setBaseIconPath("raven/drawer/icon")
.setIconScale(0.45f)
.addMenuEvent(new MenuEvent() {
@Override
public void selected(MenuAction action, int index, int subIndex) {
if (index == 0) { | WindowsTabbed.getInstance().addTab("Test Form", new TestForm()); | 0 | 2023-11-12 14:19:10+00:00 | 4k |
raphael-goetz/betterflowers | src/main/java/com/uroria/betterflowers/menus/FlowerBrushMenu.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 BetterFlowe... | import com.uroria.betterflowers.BetterFlowers;
import com.uroria.betterflowers.data.BrushData;
import com.uroria.betterflowers.data.FlowerGroupData;
import com.uroria.betterflowers.managers.FlowerManager;
import com.uroria.betterflowers.managers.LanguageManager;
import com.uroria.betterflowers.utils.BukkitPlayerInventory;
import com.uroria.betterflowers.utils.ItemBuilder;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import java.util.*; | 2,796 | package com.uroria.betterflowers.menus;
public final class FlowerBrushMenu extends BukkitPlayerInventory {
private final FlowerManager flowerManager;
private final LanguageManager languageManager;
private final Map<FlowerGroupData, Material> maskData;
private final List<FlowerGroupData> flowerGroupData;
private final Player player;
private int radius;
private float airRandomizer;
| package com.uroria.betterflowers.menus;
public final class FlowerBrushMenu extends BukkitPlayerInventory {
private final FlowerManager flowerManager;
private final LanguageManager languageManager;
private final Map<FlowerGroupData, Material> maskData;
private final List<FlowerGroupData> flowerGroupData;
private final Player player;
private int radius;
private float airRandomizer;
| public FlowerBrushMenu(BetterFlowers betterFlowers, Player player) { | 0 | 2023-11-18 16:13:59+00:00 | 4k |
Appu26J/Softuninstall | src/appu26j/utils/AppUtil.java | [
{
"identifier": "GuiSoftuninstall",
"path": "src/appu26j/gui/screens/GuiSoftuninstall.java",
"snippet": "public class GuiSoftuninstall extends GuiScreen\n{\n public static final ArrayList<AppInfo> apps = new ArrayList<>();\n private String previousUninstalledApp = \"\";\n private float scroll =... | import appu26j.Registry;
import appu26j.gui.screens.GuiSoftuninstall;
import appu26j.utils.apps.AppInfo; | 1,990 | package appu26j.utils;
public class AppUtil
{
public static void loadApps()
{
Thread thread1 = new Thread(() ->
{
try
{
loadAppsFromPath("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
}
catch (Exception e)
{
;
}
GuiSoftuninstall.loading -= 1;
});
Thread thread2 = new Thread(() ->
{
try
{
loadAppsFromPath("HKEY_LOCAL_MACHINE\\SOFTWARE\\WoW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
}
catch (Exception e)
{
;
}
GuiSoftuninstall.loading -= 1;
});
thread1.setDaemon(true);
thread2.setDaemon(true);
thread1.start();
thread2.start();
}
private static void loadAppsFromPath(String pathToCheckAppsFrom) throws Exception
{
String[] paths = Registry.execute("QUERY \"" + pathToCheckAppsFrom + "\"").split("\n");
for (String path : paths)
{
try
{
String keys = Registry.execute("QUERY \"" + path + "\"");
boolean containsInfo = keys.contains("DisplayName ") && keys.contains("UninstallString ") && !keys.contains("SystemComponent ");
if (!containsInfo)
{
continue;
}
String name = Registry.execute("QUERY \"" + path + "\" /v DisplayName").trim().split(" {4}")[3];
String publisher = keys.contains("Publisher") ? Registry.execute("QUERY \"" + path + "\" /v Publisher").trim().split(" {4}")[3] : "Unknown";
String uninstallCmd = Registry.execute("QUERY \"" + path + "\" /v UninstallString").trim().split(" {4}")[3]; | package appu26j.utils;
public class AppUtil
{
public static void loadApps()
{
Thread thread1 = new Thread(() ->
{
try
{
loadAppsFromPath("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
}
catch (Exception e)
{
;
}
GuiSoftuninstall.loading -= 1;
});
Thread thread2 = new Thread(() ->
{
try
{
loadAppsFromPath("HKEY_LOCAL_MACHINE\\SOFTWARE\\WoW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
}
catch (Exception e)
{
;
}
GuiSoftuninstall.loading -= 1;
});
thread1.setDaemon(true);
thread2.setDaemon(true);
thread1.start();
thread2.start();
}
private static void loadAppsFromPath(String pathToCheckAppsFrom) throws Exception
{
String[] paths = Registry.execute("QUERY \"" + pathToCheckAppsFrom + "\"").split("\n");
for (String path : paths)
{
try
{
String keys = Registry.execute("QUERY \"" + path + "\"");
boolean containsInfo = keys.contains("DisplayName ") && keys.contains("UninstallString ") && !keys.contains("SystemComponent ");
if (!containsInfo)
{
continue;
}
String name = Registry.execute("QUERY \"" + path + "\" /v DisplayName").trim().split(" {4}")[3];
String publisher = keys.contains("Publisher") ? Registry.execute("QUERY \"" + path + "\" /v Publisher").trim().split(" {4}")[3] : "Unknown";
String uninstallCmd = Registry.execute("QUERY \"" + path + "\" /v UninstallString").trim().split(" {4}")[3]; | GuiSoftuninstall.apps.add(new AppInfo(name, publisher, uninstallCmd, path)); | 1 | 2023-11-13 03:20:19+00:00 | 4k |
DatCoder464/Malumian-Skies | src/main/java/org/valkyrienskies/malumian_skies/registry/block/entity/BlockEntityRegistry.java | [
{
"identifier": "MalumianSkies",
"path": "src/main/java/org/valkyrienskies/malumian_skies/MalumianSkies.java",
"snippet": "@Mod(\"malumian_skies\")\npublic class MalumianSkies {\n\n // Directly reference a slf4j logger\n\n public static final String MOD_ID = \"malumian_skies\";\n private static... | import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;
import org.valkyrienskies.malumian_skies.MalumianSkies;
import org.valkyrienskies.malumian_skies.common.block.entity.CombustionSiloEntity;
import org.valkyrienskies.malumian_skies.common.block.entity.CombustionTankEntity;
import org.valkyrienskies.malumian_skies.common.block.entity.CombustionThrusterEntity;
import org.valkyrienskies.malumian_skies.registry.block.MSBlockRegistry; | 1,619 | package org.valkyrienskies.malumian_skies.registry.block.entity;
public class BlockEntityRegistry {
public static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITIES, MalumianSkies.MOD_ID);
public static final RegistryObject<BlockEntityType<CombustionSiloEntity>> COMBUSTION_SILO = BLOCK_ENTITY_TYPES.register("combustion_silo", | package org.valkyrienskies.malumian_skies.registry.block.entity;
public class BlockEntityRegistry {
public static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITIES, MalumianSkies.MOD_ID);
public static final RegistryObject<BlockEntityType<CombustionSiloEntity>> COMBUSTION_SILO = BLOCK_ENTITY_TYPES.register("combustion_silo", | () -> BlockEntityType.Builder.of(CombustionSiloEntity::new, MSBlockRegistry.COMBUSTION_SILO.get()).build(null)); | 4 | 2023-11-14 20:50:34+00:00 | 4k |
12manel123/tsys-my-food-api-1011 | src/main/java/com/myfood/services/Atribut_DishServiceImpl.java | [
{
"identifier": "IAtribut_DishDAO",
"path": "src/main/java/com/myfood/dao/IAtribut_DishDAO.java",
"snippet": "public interface IAtribut_DishDAO extends JpaRepository<Atribut_Dish, Long> {\n\t\n\n Page<Atribut_Dish> findAll(Pageable pageable);\n \n List<Atribut_Dish> findByAttributes(String atri... | import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
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.IAtribut_DishDAO;
import com.myfood.dto.Atribut_Dish;
import com.myfood.dto.Dish; | 1,878 | package com.myfood.services;
@Service
public class Atribut_DishServiceImpl implements IAtribut_DishService {
@Autowired
private IAtribut_DishDAO atribut_DishDAO;
@Override
public Page<Atribut_Dish> getAllAtribut_Dishes(Pageable pageable) {
return atribut_DishDAO.findAll(pageable);
}
@Override
public Optional<Atribut_Dish> getOneAtribut_Dish(Long id) {
return atribut_DishDAO.findById(id);
}
@Override | package com.myfood.services;
@Service
public class Atribut_DishServiceImpl implements IAtribut_DishService {
@Autowired
private IAtribut_DishDAO atribut_DishDAO;
@Override
public Page<Atribut_Dish> getAllAtribut_Dishes(Pageable pageable) {
return atribut_DishDAO.findAll(pageable);
}
@Override
public Optional<Atribut_Dish> getOneAtribut_Dish(Long id) {
return atribut_DishDAO.findById(id);
}
@Override | public List<Dish> getDishesByAtribut(String atribut) { | 2 | 2023-11-10 16:09:43+00:00 | 4k |
Artillex-Studios/AxGraves | src/main/java/com/artillexstudios/axgraves/grave/Grave.java | [
{
"identifier": "GraveInteractEvent",
"path": "src/main/java/com/artillexstudios/axgraves/api/events/GraveInteractEvent.java",
"snippet": "public class GraveInteractEvent extends Event implements Cancellable {\n private static final HandlerList handlerList = new HandlerList();\n private final Play... | import com.artillexstudios.axapi.entity.PacketEntityFactory;
import com.artillexstudios.axapi.entity.impl.PacketArmorStand;
import com.artillexstudios.axapi.hologram.Hologram;
import com.artillexstudios.axapi.hologram.HologramFactory;
import com.artillexstudios.axapi.scheduler.Scheduler;
import com.artillexstudios.axapi.serializers.Serializers;
import com.artillexstudios.axapi.utils.EquipmentSlot;
import com.artillexstudios.axapi.utils.StringUtils;
import com.artillexstudios.axgraves.api.events.GraveInteractEvent;
import com.artillexstudios.axgraves.api.events.GraveOpenEvent;
import com.artillexstudios.axgraves.utils.BlacklistUtils;
import com.artillexstudios.axgraves.utils.ExperienceUtils;
import com.artillexstudios.axgraves.utils.LocationUtils;
import com.artillexstudios.axgraves.utils.Utils;
import dev.triumphteam.gui.guis.Gui;
import dev.triumphteam.gui.guis.StorageGui;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import static com.artillexstudios.axgraves.AxGraves.CONFIG;
import static com.artillexstudios.axgraves.AxGraves.MESSAGES;
import static com.artillexstudios.axgraves.AxGraves.MESSAGEUTILS; | 3,241 | package com.artillexstudios.axgraves.grave;
public class Grave {
private final long spawned;
private final Location location;
private final OfflinePlayer player;
private final String playerName;
private final StorageGui gui;
private int storedXP;
private final PacketArmorStand entity;
private final Hologram hologram;
public Grave(Location loc, @NotNull Player player, @NotNull ItemStack[] itemsAr, int storedXP) {
this.location = LocationUtils.getCenterOf(loc);
this.player = player;
this.playerName = player.getName();
final ItemStack[] items = Arrays.stream(itemsAr).filter(Objects::nonNull).toArray(ItemStack[]::new);
this.gui = Gui.storage()
.title(StringUtils.format(MESSAGES.getString("gui-name").replace("%player%", playerName)))
.rows(items.length % 9 == 0 ? items.length / 9 : 1 + (items.length / 9))
.create();
this.storedXP = storedXP;
this.spawned = System.currentTimeMillis();
for (ItemStack it : items) {
if (it == null) continue;
if (BlacklistUtils.isBlacklisted(it)) continue;
gui.addItem(it);
}
entity = (PacketArmorStand) PacketEntityFactory.get().spawnEntity(location.clone().add(0, CONFIG.getFloat("head-height", -1.2f), 0), EntityType.ARMOR_STAND);
entity.setItem(EquipmentSlot.HELMET, Utils.getPlayerHead(player));
entity.setSmall(true);
entity.setInvisible(true);
entity.setHasBasePlate(false);
if (CONFIG.getBoolean("rotate-head-360", true)) {
entity.getLocation().setYaw(player.getLocation().getYaw());
entity.teleport(entity.getLocation());
} else {
entity.getLocation().setYaw(LocationUtils.getNearestDirection(player.getLocation().getYaw()));
entity.teleport(entity.getLocation());
}
entity.onClick(event -> Scheduler.get().run(task -> interact(event.getPlayer(), event.getHand())));
hologram = HologramFactory.get().spawnHologram(location.clone().add(0, CONFIG.getFloat("hologram-height", 1.2f), 0), Serializers.LOCATION.serialize(location), 0.3);
for (String msg : MESSAGES.getStringList("hologram")) {
msg = msg.replace("%player%", playerName);
msg = msg.replace("%xp%", "" + storedXP);
msg = msg.replace("%item%", "" + countItems());
msg = msg.replace("%despawn-time%", StringUtils.formatTime(CONFIG.getInt("despawn-time-seconds", 180) * 1_000L - (System.currentTimeMillis() - spawned)));
hologram.addLine(StringUtils.format(msg));
}
}
public void update() {
if (CONFIG.getBoolean("auto-rotation.enabled", false)) {
entity.getLocation().setYaw(entity.getLocation().getYaw() + CONFIG.getFloat("auto-rotation.speed", 10f));
entity.teleport(entity.getLocation());
}
int items = countItems();
int dTime = CONFIG.getInt("despawn-time-seconds", 180);
if (dTime != -1 && (dTime * 1_000L <= (System.currentTimeMillis() - spawned) || items == 0)) {
remove();
return;
}
int ms = MESSAGES.getStringList("hologram").size();
for (int i = 0; i < ms; i++) {
String msg = MESSAGES.getStringList("hologram").get(i);
msg = msg.replace("%player%", playerName);
msg = msg.replace("%xp%", "" + storedXP);
msg = msg.replace("%item%", "" + items);
msg = msg.replace("%despawn-time%", StringUtils.formatTime(dTime != -1 ? (dTime * 1_000L - (System.currentTimeMillis() - spawned)) : System.currentTimeMillis() - spawned));
if (i > hologram.getLines().size() - 1) {
hologram.addLine(StringUtils.format(msg));
} else {
hologram.setLine(i, StringUtils.format(msg));
}
}
}
public void interact(@NotNull Player player, org.bukkit.inventory.EquipmentSlot slot) {
if (CONFIG.getBoolean("interact-only-own", false) && !player.getUniqueId().equals(player.getUniqueId()) && !player.hasPermission("axgraves.admin")) { | package com.artillexstudios.axgraves.grave;
public class Grave {
private final long spawned;
private final Location location;
private final OfflinePlayer player;
private final String playerName;
private final StorageGui gui;
private int storedXP;
private final PacketArmorStand entity;
private final Hologram hologram;
public Grave(Location loc, @NotNull Player player, @NotNull ItemStack[] itemsAr, int storedXP) {
this.location = LocationUtils.getCenterOf(loc);
this.player = player;
this.playerName = player.getName();
final ItemStack[] items = Arrays.stream(itemsAr).filter(Objects::nonNull).toArray(ItemStack[]::new);
this.gui = Gui.storage()
.title(StringUtils.format(MESSAGES.getString("gui-name").replace("%player%", playerName)))
.rows(items.length % 9 == 0 ? items.length / 9 : 1 + (items.length / 9))
.create();
this.storedXP = storedXP;
this.spawned = System.currentTimeMillis();
for (ItemStack it : items) {
if (it == null) continue;
if (BlacklistUtils.isBlacklisted(it)) continue;
gui.addItem(it);
}
entity = (PacketArmorStand) PacketEntityFactory.get().spawnEntity(location.clone().add(0, CONFIG.getFloat("head-height", -1.2f), 0), EntityType.ARMOR_STAND);
entity.setItem(EquipmentSlot.HELMET, Utils.getPlayerHead(player));
entity.setSmall(true);
entity.setInvisible(true);
entity.setHasBasePlate(false);
if (CONFIG.getBoolean("rotate-head-360", true)) {
entity.getLocation().setYaw(player.getLocation().getYaw());
entity.teleport(entity.getLocation());
} else {
entity.getLocation().setYaw(LocationUtils.getNearestDirection(player.getLocation().getYaw()));
entity.teleport(entity.getLocation());
}
entity.onClick(event -> Scheduler.get().run(task -> interact(event.getPlayer(), event.getHand())));
hologram = HologramFactory.get().spawnHologram(location.clone().add(0, CONFIG.getFloat("hologram-height", 1.2f), 0), Serializers.LOCATION.serialize(location), 0.3);
for (String msg : MESSAGES.getStringList("hologram")) {
msg = msg.replace("%player%", playerName);
msg = msg.replace("%xp%", "" + storedXP);
msg = msg.replace("%item%", "" + countItems());
msg = msg.replace("%despawn-time%", StringUtils.formatTime(CONFIG.getInt("despawn-time-seconds", 180) * 1_000L - (System.currentTimeMillis() - spawned)));
hologram.addLine(StringUtils.format(msg));
}
}
public void update() {
if (CONFIG.getBoolean("auto-rotation.enabled", false)) {
entity.getLocation().setYaw(entity.getLocation().getYaw() + CONFIG.getFloat("auto-rotation.speed", 10f));
entity.teleport(entity.getLocation());
}
int items = countItems();
int dTime = CONFIG.getInt("despawn-time-seconds", 180);
if (dTime != -1 && (dTime * 1_000L <= (System.currentTimeMillis() - spawned) || items == 0)) {
remove();
return;
}
int ms = MESSAGES.getStringList("hologram").size();
for (int i = 0; i < ms; i++) {
String msg = MESSAGES.getStringList("hologram").get(i);
msg = msg.replace("%player%", playerName);
msg = msg.replace("%xp%", "" + storedXP);
msg = msg.replace("%item%", "" + items);
msg = msg.replace("%despawn-time%", StringUtils.formatTime(dTime != -1 ? (dTime * 1_000L - (System.currentTimeMillis() - spawned)) : System.currentTimeMillis() - spawned));
if (i > hologram.getLines().size() - 1) {
hologram.addLine(StringUtils.format(msg));
} else {
hologram.setLine(i, StringUtils.format(msg));
}
}
}
public void interact(@NotNull Player player, org.bukkit.inventory.EquipmentSlot slot) {
if (CONFIG.getBoolean("interact-only-own", false) && !player.getUniqueId().equals(player.getUniqueId()) && !player.hasPermission("axgraves.admin")) { | MESSAGEUTILS.sendLang(player, "interact.not-your-grave"); | 8 | 2023-11-18 16:37:27+00:00 | 4k |
huzpsb/LC4J | src/org/eu/huzpsb/unichat/agent/impl/c4j/C4JTransformer.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": "Core",
"path": "src/org/eu/huzpsb/uni... | import org.eu.huzpsb.unichat.agent.Transformer;
import org.eu.huzpsb.unichat.agent.impl.c4j.search.Core;
import org.eu.huzpsb.unichat.agent.impl.c4j.search.PendingResult;
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;
import java.util.List; | 1,677 | package org.eu.huzpsb.unichat.agent.impl.c4j;
public class C4JTransformer implements Transformer {
@Override
public Conversation beforeSend(Conversation conversation) {
TransformerException.throwIfNotAu(conversation);
String userPrompt = conversation.entries.get(conversation.entries.size() - 1).content; | package org.eu.huzpsb.unichat.agent.impl.c4j;
public class C4JTransformer implements Transformer {
@Override
public Conversation beforeSend(Conversation conversation) {
TransformerException.throwIfNotAu(conversation);
String userPrompt = conversation.entries.get(conversation.entries.size() - 1).content; | List<PendingResult> pendingResults = Core.doSearch(userPrompt); | 2 | 2023-11-16 11:44:05+00:00 | 4k |
jpdev01/asaasSdk | src/main/java/io/github/jpdev/asaassdk/rest/payment/Payment.java | [
{
"identifier": "Discount",
"path": "src/main/java/io/github/jpdev/asaassdk/rest/payment/children/Discount.java",
"snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Discount {\n\n private BigDecimal value;\n private Integer dueDateLimitDays;\n private DiscountType type;\n ... | import io.github.jpdev.asaassdk.rest.payment.children.Discount;
import io.github.jpdev.asaassdk.rest.payment.children.Fine;
import io.github.jpdev.asaassdk.rest.payment.children.Interest;
import io.github.jpdev.asaassdk.rest.payment.delete.PaymentDeleter;
import io.github.jpdev.asaassdk.rest.payment.identificationfield.PaymentIdentificationFieldFetcher;
import io.github.jpdev.asaassdk.rest.payment.restore.PaymentRestorer;
import io.github.jpdev.asaassdk.rest.payment.status.PaymentStatusFetcher;
import io.github.jpdev.asaassdk.utils.BillingType;
import io.github.jpdev.asaassdk.rest.payment.enums.PaymentStatus;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.Date; | 1,988 | package io.github.jpdev.asaassdk.rest.payment;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Payment {
@JsonProperty("object")
private String object;
private String id;
private String dateCreated;
private String customer;
private String paymentLink;
private BigDecimal value;
private BigDecimal netValue;
private BigDecimal originalValue;
private BigDecimal interestValue;
private String description;
private BillingType billingType;
private String pixTransaction;
private PaymentStatus status;
private Date dueDate;
private Date originalDueDate;
private Date paymentDate;
private Date clientPaymentDate;
private String installment;
private String installmentNumber;
private String invoiceUrl;
private String invoiceNumber;
private String externalReference;
private boolean deleted;
private boolean anticipated;
private boolean anticipable;
private String creditDate;
private String estimatedCreditDate;
private String transactionReceiptUrl;
private String nossoNumero;
private String bankSlipUrl;
private String lastInvoiceViewedDate;
private String lastBankSlipViewedDate;
private Discount discount;
private Fine fine;
private Interest interest;
private boolean postalService;
private Object custody; // You may need to define a specific type for this property
private Object refunds; // You may need to define a specific type for this property
public static PaymentCreator creator() {
return new PaymentCreator();
}
public static PaymentReader reader() {
return new PaymentReader();
}
public static PaymentRefunder refunder(Long id) {
return new PaymentRefunder(id);
}
public static PaymentDeleter deleter(String id) {
return new PaymentDeleter(id);
}
| package io.github.jpdev.asaassdk.rest.payment;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Payment {
@JsonProperty("object")
private String object;
private String id;
private String dateCreated;
private String customer;
private String paymentLink;
private BigDecimal value;
private BigDecimal netValue;
private BigDecimal originalValue;
private BigDecimal interestValue;
private String description;
private BillingType billingType;
private String pixTransaction;
private PaymentStatus status;
private Date dueDate;
private Date originalDueDate;
private Date paymentDate;
private Date clientPaymentDate;
private String installment;
private String installmentNumber;
private String invoiceUrl;
private String invoiceNumber;
private String externalReference;
private boolean deleted;
private boolean anticipated;
private boolean anticipable;
private String creditDate;
private String estimatedCreditDate;
private String transactionReceiptUrl;
private String nossoNumero;
private String bankSlipUrl;
private String lastInvoiceViewedDate;
private String lastBankSlipViewedDate;
private Discount discount;
private Fine fine;
private Interest interest;
private boolean postalService;
private Object custody; // You may need to define a specific type for this property
private Object refunds; // You may need to define a specific type for this property
public static PaymentCreator creator() {
return new PaymentCreator();
}
public static PaymentReader reader() {
return new PaymentReader();
}
public static PaymentRefunder refunder(Long id) {
return new PaymentRefunder(id);
}
public static PaymentDeleter deleter(String id) {
return new PaymentDeleter(id);
}
| public static PaymentRestorer restorer(String id) { | 5 | 2023-11-12 01:19:17+00:00 | 4k |
GoldenStack/minestom-ca | src/main/java/dev/goldenstack/minestom_ca/server/ExampleRules.java | [
{
"identifier": "Neighbors",
"path": "src/main/java/dev/goldenstack/minestom_ca/Neighbors.java",
"snippet": "public final class Neighbors {\n public static final @NotNull Point SELF = Vec.ZERO;\n\n public static final @NotNull Point UP = new Vec(0, 1, 0);\n\n public static final @NotNull Point ... | import dev.goldenstack.minestom_ca.Neighbors;
import dev.goldenstack.minestom_ca.Rule;
import dev.goldenstack.minestom_ca.Rule.Expression;
import net.minestom.server.instance.block.Block;
import java.util.List;
import static dev.goldenstack.minestom_ca.Neighbors.*;
import static dev.goldenstack.minestom_ca.Rule.Condition;
import static dev.goldenstack.minestom_ca.Rule.Result; | 2,664 | package dev.goldenstack.minestom_ca.server;
/**
* Example rules for simple behaviour.
*/
public final class ExampleRules {
public static final List<Rule> GROW_DIRT = List.of(new Rule(
new Condition.Equal(Block.DIRT),
new Result.SetIndex(Block.GRASS_BLOCK)
));
public static final List<Rule> GROW_DIRT_AGE = List.of(
new Rule(
new Condition.And(
new Condition.Equal(Block.DIRT)
),
new Result.SetIndex(1,
new Expression.Operation(new Expression.Index(1),
new Expression.Literal(1), Expression.Operation.Type.ADD))
),
new Rule(
new Condition.And(
new Condition.Equal(Block.DIRT),
new Condition.Equal(new Expression.Index(1), new Expression.Literal(60))
),
new Result.SetIndex(0, new Expression.Literal(Block.GRASS_BLOCK.stateId())),
new Result.SetIndex(1, new Expression.Literal(0))
)
);
public static final List<Rule> MOVING_OAK = List.of(
new Rule(
new Condition.And(
new Condition.Equal(Block.AIR),
new Condition.Equal(new Expression.NeighborsCount(WEST, new Condition.Equal(Block.OAK_LOG)), new Expression.Literal(1))
),
new Result.SetIndex(Block.OAK_LOG)),
new Rule(
new Condition.And(
new Condition.Equal(Block.OAK_LOG),
new Condition.Equal(new Expression.NeighborsCount(EAST, new Condition.Equal(Block.AIR)), new Expression.Literal(1))
),
new Result.SetIndex(Block.OAK_PLANKS))
);
public static final List<Rule> HAY_RAINBOW = List.of(
new Rule(
new Condition.And(
new Condition.Equal(Block.RED_WOOL),
new Condition.Equal(new Expression.NeighborsCount(UP, new Condition.Equal(Block.HAY_BLOCK)), new Expression.Literal(1))
),
new Result.SetIndex(Block.ORANGE_WOOL)
),
new Rule(
new Condition.Equal(Block.ORANGE_WOOL),
new Result.SetIndex(Block.YELLOW_WOOL)
),
new Rule(
new Condition.Equal(Block.YELLOW_WOOL),
new Result.SetIndex(Block.LIME_WOOL)
),
new Rule(
new Condition.Equal(Block.LIME_WOOL),
new Result.SetIndex(Block.GREEN_WOOL)
),
new Rule(
new Condition.Equal(Block.GREEN_WOOL),
new Result.SetIndex(Block.CYAN_WOOL)
),
new Rule(
new Condition.Equal(Block.CYAN_WOOL),
new Result.SetIndex(Block.LIGHT_BLUE_WOOL)
),
new Rule(
new Condition.Equal(Block.LIGHT_BLUE_WOOL),
new Result.SetIndex(Block.BLUE_WOOL)
),
new Rule(
new Condition.Equal(Block.BLUE_WOOL),
new Result.SetIndex(Block.PURPLE_WOOL)
)
);
private static final Expression NUM_ALIVE_NEIGHBORS =
new Expression.NeighborsCount( | package dev.goldenstack.minestom_ca.server;
/**
* Example rules for simple behaviour.
*/
public final class ExampleRules {
public static final List<Rule> GROW_DIRT = List.of(new Rule(
new Condition.Equal(Block.DIRT),
new Result.SetIndex(Block.GRASS_BLOCK)
));
public static final List<Rule> GROW_DIRT_AGE = List.of(
new Rule(
new Condition.And(
new Condition.Equal(Block.DIRT)
),
new Result.SetIndex(1,
new Expression.Operation(new Expression.Index(1),
new Expression.Literal(1), Expression.Operation.Type.ADD))
),
new Rule(
new Condition.And(
new Condition.Equal(Block.DIRT),
new Condition.Equal(new Expression.Index(1), new Expression.Literal(60))
),
new Result.SetIndex(0, new Expression.Literal(Block.GRASS_BLOCK.stateId())),
new Result.SetIndex(1, new Expression.Literal(0))
)
);
public static final List<Rule> MOVING_OAK = List.of(
new Rule(
new Condition.And(
new Condition.Equal(Block.AIR),
new Condition.Equal(new Expression.NeighborsCount(WEST, new Condition.Equal(Block.OAK_LOG)), new Expression.Literal(1))
),
new Result.SetIndex(Block.OAK_LOG)),
new Rule(
new Condition.And(
new Condition.Equal(Block.OAK_LOG),
new Condition.Equal(new Expression.NeighborsCount(EAST, new Condition.Equal(Block.AIR)), new Expression.Literal(1))
),
new Result.SetIndex(Block.OAK_PLANKS))
);
public static final List<Rule> HAY_RAINBOW = List.of(
new Rule(
new Condition.And(
new Condition.Equal(Block.RED_WOOL),
new Condition.Equal(new Expression.NeighborsCount(UP, new Condition.Equal(Block.HAY_BLOCK)), new Expression.Literal(1))
),
new Result.SetIndex(Block.ORANGE_WOOL)
),
new Rule(
new Condition.Equal(Block.ORANGE_WOOL),
new Result.SetIndex(Block.YELLOW_WOOL)
),
new Rule(
new Condition.Equal(Block.YELLOW_WOOL),
new Result.SetIndex(Block.LIME_WOOL)
),
new Rule(
new Condition.Equal(Block.LIME_WOOL),
new Result.SetIndex(Block.GREEN_WOOL)
),
new Rule(
new Condition.Equal(Block.GREEN_WOOL),
new Result.SetIndex(Block.CYAN_WOOL)
),
new Rule(
new Condition.Equal(Block.CYAN_WOOL),
new Result.SetIndex(Block.LIGHT_BLUE_WOOL)
),
new Rule(
new Condition.Equal(Block.LIGHT_BLUE_WOOL),
new Result.SetIndex(Block.BLUE_WOOL)
),
new Rule(
new Condition.Equal(Block.BLUE_WOOL),
new Result.SetIndex(Block.PURPLE_WOOL)
)
);
private static final Expression NUM_ALIVE_NEIGHBORS =
new Expression.NeighborsCount( | Neighbors.MOORE_2D, | 1 | 2023-11-18 21:49:11+00:00 | 4k |
kotmatross28729/EnviroMine-continuation | src/main/java/enviromine/client/gui/menu/EM_Gui_SoundSettings.java | [
{
"identifier": "SaveController",
"path": "src/main/java/enviromine/client/gui/SaveController.java",
"snippet": "@SideOnly(Side.CLIENT)\npublic class SaveController {\n\t\n\t/**\n\t * Configuration version number. If changed the version file will be reset to defaults to prevent glitches\n\t */\n\tstatic... | import cpw.mods.fml.client.config.GuiSlider;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import enviromine.client.gui.SaveController;
import enviromine.client.gui.UI_Settings;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.StatCollector; | 2,089 | package enviromine.client.gui.menu;
@SideOnly(Side.CLIENT)
public class EM_Gui_SoundSettings extends GuiScreen
{
private GuiScreen parentGuiScreen;
public EM_Gui_SoundSettings(GuiScreen par1GuiScreen)
{
this.parentGuiScreen = par1GuiScreen;
}
@SuppressWarnings("unchecked")
@Override
public void initGui()
{ | package enviromine.client.gui.menu;
@SideOnly(Side.CLIENT)
public class EM_Gui_SoundSettings extends GuiScreen
{
private GuiScreen parentGuiScreen;
public EM_Gui_SoundSettings(GuiScreen par1GuiScreen)
{
this.parentGuiScreen = par1GuiScreen;
}
@SuppressWarnings("unchecked")
@Override
public void initGui()
{ | float volume = UI_Settings.breathVolume * 100; | 1 | 2023-11-16 18:15:29+00:00 | 4k |
spring-projects/spring-rewrite-commons | spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/project/resource/finder/PathPatternMatchingProjectResourceFinder.java | [
{
"identifier": "ProjectResource",
"path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/project/resource/ProjectResource.java",
"snippet": "public interface ProjectResource {\n\n\tString print();\n\n\t/**\n\t * @return Path relative to module root.\n\t */\n\tPath getSourceP... | import org.springframework.rewrite.project.resource.ProjectResource;
import org.springframework.rewrite.project.resource.ProjectResourceSet;
import org.springframework.rewrite.utils.OsAgnosticPathMatcher;
import org.springframework.util.PathMatcher;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors; | 1,611 | /*
* Copyright 2021 - 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.rewrite.project.resource.finder;
public class PathPatternMatchingProjectResourceFinder implements ProjectResourceFinder<List<ProjectResource>> {
/**
* Ant-style path patterns to filter resources.
*/
private final List<String> matchingPatterns;
| /*
* Copyright 2021 - 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.rewrite.project.resource.finder;
public class PathPatternMatchingProjectResourceFinder implements ProjectResourceFinder<List<ProjectResource>> {
/**
* Ant-style path patterns to filter resources.
*/
private final List<String> matchingPatterns;
| private final PathMatcher matcher = new OsAgnosticPathMatcher(); | 2 | 2023-11-14 23:02:37+00:00 | 4k |
giftorg/gift | gift-analyze/src/main/java/org/giftorg/analyze/entity/Function.java | [
{
"identifier": "BigModel",
"path": "gift-common/src/main/java/org/giftorg/common/bigmodel/BigModel.java",
"snippet": "public interface BigModel extends Serializable {\n\n /**\n * 大模型聊天接口\n */\n String chat(List<Message> messages) throws Exception;\n\n /**\n * 计算文本嵌入向量\n */\n ... | import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.giftorg.common.bigmodel.BigModel;
import org.giftorg.common.bigmodel.impl.ChatGLM;
import org.giftorg.common.bigmodel.impl.ChatGPT;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List; | 2,467 | /**
* Copyright 2023 GiftOrg Authors
*
* 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.giftorg.analyze.entity;
/**
* 代码实体
*/
@Data
@Slf4j
public class Function implements Serializable {
private String name;
private String source;
private String description;
private List<Double> embedding;
private Position begin;
private Position end;
private String language;
private Integer repoId;
private String filePath;
/**
* 技术栈列表,以空格分隔
*/
private String technologyStack;
public void setRepoId(Integer repoId) {
this.repoId = repoId;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
/* prompt
分析用户输入的Java方法代码,回答一个json字符串。
json结构包含3个字段:
1. name: 方法的名称;
2. desc: 采用中文描述方法处理的业务,30到50字/词;
3. techs:与该方法相关的搜索词列表,以中文为主,术语可用英文,多个单词拆分成多个元素,搜索词列表要尽量全面。
回答示例:
{
"name": "retrieval",
"desc": "通过指定值过滤并向量化检索文档,实现基于向量化的文档相似度查询",
"techs": ["elasticsearch", "向量化", "检索", "dense", "vector", "相似度", "检索", "文本", "文本匹配"]
}
*/
private static final String FUNCTION_ANALYZE_PROMPT = "Analyze Java method code provided by the user and respond with a JSON string. The JSON structure includes three fields:\n" +
"1. name: The name of the method;\n" +
"2. desc: A Chinese description (30 to 50 characters/words) of the business process handled by the method;\n" +
"3. techs: A list of search terms related to the method, primarily in Chinese with English terms allowed. If a term consists of multiple words, break them into separate elements. The search term list should be as comprehensive as possible.\n" +
"Example response:\n" +
"{\n" +
" \"name\": \"retrieval\",\n" +
" \"desc\": \"通过指定值过滤并向量化检索文档,实现基于向量化的文档相似度查询\",\n" +
" \"techs\": [\"elasticsearch\", \"向量化\", \"检索\", \"dense\", \"vector\", \"相似度\", \"检索\", \"文本\", \"文本匹配\"]\n" +
"}";
/**
* 代码分析与向量化
*/
public Boolean analyze() {
// 获取函数的描述信息 | /**
* Copyright 2023 GiftOrg Authors
*
* 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.giftorg.analyze.entity;
/**
* 代码实体
*/
@Data
@Slf4j
public class Function implements Serializable {
private String name;
private String source;
private String description;
private List<Double> embedding;
private Position begin;
private Position end;
private String language;
private Integer repoId;
private String filePath;
/**
* 技术栈列表,以空格分隔
*/
private String technologyStack;
public void setRepoId(Integer repoId) {
this.repoId = repoId;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
/* prompt
分析用户输入的Java方法代码,回答一个json字符串。
json结构包含3个字段:
1. name: 方法的名称;
2. desc: 采用中文描述方法处理的业务,30到50字/词;
3. techs:与该方法相关的搜索词列表,以中文为主,术语可用英文,多个单词拆分成多个元素,搜索词列表要尽量全面。
回答示例:
{
"name": "retrieval",
"desc": "通过指定值过滤并向量化检索文档,实现基于向量化的文档相似度查询",
"techs": ["elasticsearch", "向量化", "检索", "dense", "vector", "相似度", "检索", "文本", "文本匹配"]
}
*/
private static final String FUNCTION_ANALYZE_PROMPT = "Analyze Java method code provided by the user and respond with a JSON string. The JSON structure includes three fields:\n" +
"1. name: The name of the method;\n" +
"2. desc: A Chinese description (30 to 50 characters/words) of the business process handled by the method;\n" +
"3. techs: A list of search terms related to the method, primarily in Chinese with English terms allowed. If a term consists of multiple words, break them into separate elements. The search term list should be as comprehensive as possible.\n" +
"Example response:\n" +
"{\n" +
" \"name\": \"retrieval\",\n" +
" \"desc\": \"通过指定值过滤并向量化检索文档,实现基于向量化的文档相似度查询\",\n" +
" \"techs\": [\"elasticsearch\", \"向量化\", \"检索\", \"dense\", \"vector\", \"相似度\", \"检索\", \"文本\", \"文本匹配\"]\n" +
"}";
/**
* 代码分析与向量化
*/
public Boolean analyze() {
// 获取函数的描述信息 | BigModel gpt = new ChatGPT(); | 0 | 2023-11-15 08:58:35+00:00 | 4k |
exadel-inc/etoolbox-anydiff | core/src/test/java/com/exadel/etoolbox/anydiff/comparison/DiffTaskTest.java | [
{
"identifier": "ContentType",
"path": "core/src/main/java/com/exadel/etoolbox/anydiff/ContentType.java",
"snippet": "@RequiredArgsConstructor(access = AccessLevel.PRIVATE)\n@Getter\npublic enum ContentType {\n\n UNDEFINED {\n @Override\n public boolean matchesMime(String value) {\n ... | import com.exadel.etoolbox.anydiff.ContentType;
import com.exadel.etoolbox.anydiff.OutputType;
import com.exadel.etoolbox.anydiff.diff.Diff;
import com.exadel.etoolbox.anydiff.diff.DiffEntry;
import com.exadel.etoolbox.anydiff.diff.DiffState;
import com.exadel.etoolbox.anydiff.diff.EntryHolder;
import com.exadel.etoolbox.anydiff.diff.PrintableEntry;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List; | 2,728 | /*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.exadel.etoolbox.anydiff.comparison;
public class DiffTaskTest {
@Test
public void shouldReturnEmptyDiff() { | /*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.exadel.etoolbox.anydiff.comparison;
public class DiffTaskTest {
@Test
public void shouldReturnEmptyDiff() { | Diff diff = DiffTask | 2 | 2023-11-16 14:29:45+00:00 | 4k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.