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
weibocom/rill-flow
rill-flow-service/src/main/java/com/weibo/rill/flow/service/dispatcher/FunctionProtocolDispatcher.java
[ { "identifier": "TaskException", "path": "rill-flow-common/src/main/java/com/weibo/rill/flow/common/exception/TaskException.java", "snippet": "@ResponseStatus(HttpStatus.BAD_REQUEST)\npublic class TaskException extends RuntimeException {\n private final int errorCode;\n private final String execut...
import com.weibo.rill.flow.common.exception.TaskException; import com.weibo.rill.flow.common.model.BizError; import com.weibo.rill.flow.interfaces.dispatcher.DispatcherExtension; import com.weibo.rill.flow.interfaces.model.http.HttpParameter; import com.weibo.rill.flow.interfaces.model.resource.Resource; import com.weibo.rill.flow.interfaces.model.strategy.DispatchInfo; import com.weibo.rill.flow.interfaces.model.task.FunctionTask; import com.weibo.rill.flow.interfaces.model.task.TaskInfo; import com.weibo.rill.flow.olympicene.core.switcher.SwitcherManager; import com.weibo.rill.flow.service.invoke.HttpInvokeHelper; import com.weibo.rill.flow.service.statistic.DAGResourceStatistic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestClientResponseException; import java.util.Map; import java.util.Optional;
6,499
/* * Copyright 2021-2023 Weibo, Inc. * * 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.weibo.rill.flow.service.dispatcher; @Service("functionDispatcher") public class FunctionProtocolDispatcher implements DispatcherExtension { @Autowired private HttpInvokeHelper httpInvokeHelper; @Autowired private DAGResourceStatistic dagResourceStatistic; @Autowired private SwitcherManager switcherManagerImpl; @Override public String handle(Resource resource, DispatchInfo dispatchInfo) { String executionId = dispatchInfo.getExecutionId(); Map<String, Object> input = dispatchInfo.getInput(); TaskInfo taskInfo = dispatchInfo.getTaskInfo(); String taskInfoName = taskInfo.getName(); String requestType = ((FunctionTask) taskInfo.getTask()).getRequestType(); MultiValueMap<String, String> header = dispatchInfo.getHeaders(); try { HttpParameter requestParams = httpInvokeHelper.functionRequestParams(executionId, taskInfoName, resource, input); Optional.of(requestParams) .map(it -> requestParams.getHeader()) .ifPresent(header::setAll); String url = httpInvokeHelper.buildUrl(resource, requestParams.getQueryParams()); int maxInvokeTime = switcherManagerImpl.getSwitcherState("ENABLE_FUNCTION_DISPATCH_RET_CHECK") ? 2 : 1; HttpMethod method = Optional.ofNullable(requestType).map(String::toUpperCase).map(HttpMethod::resolve).orElse(HttpMethod.POST); Map<String, Object> body = method != HttpMethod.POST ? null : requestParams.getBody(); HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(body, header); String ret = httpInvokeHelper.invokeRequest(executionId, taskInfoName, url, requestEntity, method, maxInvokeTime); dagResourceStatistic.updateUrlTypeResourceStatus(executionId, taskInfoName, resource.getResourceName(), ret); return ret; } catch (RestClientResponseException e) { String responseBody = e.getResponseBodyAsString(); dagResourceStatistic.updateUrlTypeResourceStatus(executionId, taskInfoName, resource.getResourceName(), responseBody);
/* * Copyright 2021-2023 Weibo, Inc. * * 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.weibo.rill.flow.service.dispatcher; @Service("functionDispatcher") public class FunctionProtocolDispatcher implements DispatcherExtension { @Autowired private HttpInvokeHelper httpInvokeHelper; @Autowired private DAGResourceStatistic dagResourceStatistic; @Autowired private SwitcherManager switcherManagerImpl; @Override public String handle(Resource resource, DispatchInfo dispatchInfo) { String executionId = dispatchInfo.getExecutionId(); Map<String, Object> input = dispatchInfo.getInput(); TaskInfo taskInfo = dispatchInfo.getTaskInfo(); String taskInfoName = taskInfo.getName(); String requestType = ((FunctionTask) taskInfo.getTask()).getRequestType(); MultiValueMap<String, String> header = dispatchInfo.getHeaders(); try { HttpParameter requestParams = httpInvokeHelper.functionRequestParams(executionId, taskInfoName, resource, input); Optional.of(requestParams) .map(it -> requestParams.getHeader()) .ifPresent(header::setAll); String url = httpInvokeHelper.buildUrl(resource, requestParams.getQueryParams()); int maxInvokeTime = switcherManagerImpl.getSwitcherState("ENABLE_FUNCTION_DISPATCH_RET_CHECK") ? 2 : 1; HttpMethod method = Optional.ofNullable(requestType).map(String::toUpperCase).map(HttpMethod::resolve).orElse(HttpMethod.POST); Map<String, Object> body = method != HttpMethod.POST ? null : requestParams.getBody(); HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(body, header); String ret = httpInvokeHelper.invokeRequest(executionId, taskInfoName, url, requestEntity, method, maxInvokeTime); dagResourceStatistic.updateUrlTypeResourceStatus(executionId, taskInfoName, resource.getResourceName(), ret); return ret; } catch (RestClientResponseException e) { String responseBody = e.getResponseBodyAsString(); dagResourceStatistic.updateUrlTypeResourceStatus(executionId, taskInfoName, resource.getResourceName(), responseBody);
throw new TaskException(BizError.ERROR_INVOKE_URI.getCode(),
1
2023-11-03 03:46:01+00:00
8k
aliyun/alibabacloud-compute-nest-saas-boost
boost.common/src/main/java/org/example/common/adapter/impl/BaseAlipayClientImpl.java
[ { "identifier": "BaseAlipayClient", "path": "boost.common/src/main/java/org/example/common/adapter/BaseAlipayClient.java", "snippet": "public interface BaseAlipayClient {\n\n /**\n * Query order.\n * @param outTradeNumber out payment trade number\n * @return AlipayTradeQueryResponse\n ...
import com.alibaba.fastjson.JSONObject; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.DefaultAlipayClient; import com.alipay.api.internal.util.AlipaySignature; import com.alipay.api.request.AlipayTradeCloseRequest; import com.alipay.api.request.AlipayTradePagePayRequest; import com.alipay.api.request.AlipayTradeQueryRequest; import com.alipay.api.request.AlipayTradeRefundRequest; import com.alipay.api.response.AlipayTradeCloseResponse; import com.alipay.api.response.AlipayTradePagePayResponse; import com.alipay.api.response.AlipayTradeQueryResponse; import com.alipay.api.response.AlipayTradeRefundResponse; import lombok.extern.slf4j.Slf4j; import org.example.common.adapter.BaseAlipayClient; import org.example.common.config.AlipayConfig; import org.example.common.constant.AliPayConstants; import org.example.common.constant.Constants; import org.example.common.errorinfo.ErrorInfo; import org.example.common.exception.BizException; import org.example.common.utils.DateUtil; import org.springframework.stereotype.Component; import java.util.Optional; import static org.example.common.constant.AliPayConstants.OUT_TRADE_NO; import static org.example.common.constant.AliPayConstants.REFUND_AMOUNT; import static org.example.common.constant.AliPayConstants.REFUND_REQUEST_ID;
4,790
/* *Copyright (c) Alibaba Group; *Licensed under the Apache License, Version 2.0 (the "License"); *you may not use this file except in compliance with the License. *You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 *Unless required by applicable law or agreed to in writing, software *distributed under the License is distributed on an "AS IS" BASIS, *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *See the License for the specific language governing permissions and *limitations under the License. */ package org.example.common.adapter.impl; @Component @Slf4j public class BaseAlipayClientImpl implements BaseAlipayClient { private AlipayConfig alipayConfig; private AlipayClient alipayClient; private static final Integer CLOSE_TRANSACTION_TIME = 15; @Override public AlipayTradeQueryResponse queryOutTrade(String outTradeNumber) { AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); request.setBizContent(new JSONObject().fluentPut(OUT_TRADE_NO, outTradeNumber).toString()); try { return alipayClient.execute(request); } catch (AlipayApiException e) { throw new BizException(ErrorInfo.ENTITY_NOT_EXIST, e); } } @Override public boolean verifySignature(String sign, String content) { try { return AlipaySignature.rsaCheck(content, sign, alipayConfig.getOfficialPublicKey(),
/* *Copyright (c) Alibaba Group; *Licensed under the Apache License, Version 2.0 (the "License"); *you may not use this file except in compliance with the License. *You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 *Unless required by applicable law or agreed to in writing, software *distributed under the License is distributed on an "AS IS" BASIS, *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *See the License for the specific language governing permissions and *limitations under the License. */ package org.example.common.adapter.impl; @Component @Slf4j public class BaseAlipayClientImpl implements BaseAlipayClient { private AlipayConfig alipayConfig; private AlipayClient alipayClient; private static final Integer CLOSE_TRANSACTION_TIME = 15; @Override public AlipayTradeQueryResponse queryOutTrade(String outTradeNumber) { AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); request.setBizContent(new JSONObject().fluentPut(OUT_TRADE_NO, outTradeNumber).toString()); try { return alipayClient.execute(request); } catch (AlipayApiException e) { throw new BizException(ErrorInfo.ENTITY_NOT_EXIST, e); } } @Override public boolean verifySignature(String sign, String content) { try { return AlipaySignature.rsaCheck(content, sign, alipayConfig.getOfficialPublicKey(),
Constants.TRANSFORMATION_FORMAT_UTF_8, AliPayConstants.SIGN_TYPE_RSA2);
2
2023-11-01 08:19:34+00:00
8k
mioclient/oyvey-ported
src/main/java/me/alpha432/oyvey/manager/ConfigManager.java
[ { "identifier": "OyVey", "path": "src/main/java/me/alpha432/oyvey/OyVey.java", "snippet": "public class OyVey implements ModInitializer, ClientModInitializer {\n public static final String NAME = \"OyVey\";\n public static final String VERSION = \"0.0.3 - 1.20.1\";\n\n public static float TIMER...
import com.google.gson.*; import me.alpha432.oyvey.OyVey; import me.alpha432.oyvey.features.Feature; import me.alpha432.oyvey.features.settings.Bind; import me.alpha432.oyvey.features.settings.EnumConverter; import me.alpha432.oyvey.features.settings.Setting; import me.alpha432.oyvey.util.traits.Jsonable; import net.fabricmc.loader.api.FabricLoader; import java.nio.file.Files; import java.nio.file.Path; import java.util.List;
3,795
package me.alpha432.oyvey.manager; public class ConfigManager { private static final Path OYVEY_PATH = FabricLoader.getInstance().getGameDir().resolve("oyvey"); private static final Gson gson = new GsonBuilder() .setLenient() .setPrettyPrinting() .create();
package me.alpha432.oyvey.manager; public class ConfigManager { private static final Path OYVEY_PATH = FabricLoader.getInstance().getGameDir().resolve("oyvey"); private static final Gson gson = new GsonBuilder() .setLenient() .setPrettyPrinting() .create();
private final List<Jsonable> jsonables = List.of(OyVey.friendManager, OyVey.moduleManager, OyVey.commandManager);
5
2023-11-05 18:10:28+00:00
8k
EB-wilson/TooManyItems
src/main/java/tmi/recipe/parser/ConsGeneratorParser.java
[ { "identifier": "Recipe", "path": "src/main/java/tmi/recipe/Recipe.java", "snippet": "public class Recipe {\n private static final EffFunc ONE_BASE = getDefaultEff(1);\n private static final EffFunc ZERO_BASE = getDefaultEff(0);\n\n /**该配方的类型,请参阅{@link RecipeType}*/\n public final RecipeType recipeT...
import arc.struct.Seq; import mindustry.world.Block; import mindustry.world.blocks.power.ConsumeGenerator; import tmi.recipe.Recipe; import tmi.recipe.RecipeParser; import tmi.recipe.RecipeType; import tmi.recipe.types.PowerMark;
3,689
package tmi.recipe.parser; public class ConsGeneratorParser extends ConsumerParser<ConsumeGenerator>{ {excludes.add(GeneratorParser.class);} @Override public boolean isTarget(Block content) { return content instanceof ConsumeGenerator; } @Override public Seq<Recipe> parse(ConsumeGenerator content) {
package tmi.recipe.parser; public class ConsGeneratorParser extends ConsumerParser<ConsumeGenerator>{ {excludes.add(GeneratorParser.class);} @Override public boolean isTarget(Block content) { return content instanceof ConsumeGenerator; } @Override public Seq<Recipe> parse(ConsumeGenerator content) {
Recipe res = new Recipe(RecipeType.generator)
2
2023-11-05 11:39:21+00:00
8k
dulaiduwang003/DeepSee
microservices/ts-drawing/src/main/java/com/cn/service/impl/DrawingServiceImpl.java
[ { "identifier": "SdCommon", "path": "microservices/ts-drawing/src/main/java/com/cn/common/SdCommon.java", "snippet": "@Component\n@RequiredArgsConstructor\npublic class SdCommon {\n\n\n private final SdDefaultConfiguration configuration;\n public static final SdStructure STRUCTURE = new SdStructur...
import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.cn.common.SdCommon; import com.cn.constant.DrawingConstant; import com.cn.constant.DrawingStatusConstant; import com.cn.dto.GenerateDrawingDeleteDto; import com.cn.entity.TsDrawingPrompt; import com.cn.entity.TsGenerateDrawing; import com.cn.enums.DrawingTypeEnum; import com.cn.exception.DrawingException; import com.cn.mapper.TsDrawingPromptMapper; import com.cn.mapper.TsGenerateDrawingMapper; import com.cn.service.DrawingService; import com.cn.structure.TaskStructure; import com.cn.utils.RedisUtils; import com.cn.utils.UploadUtil; import com.cn.utils.UserUtils; import com.cn.vo.DrawingResultVo; import com.cn.vo.PromptWordVo; import com.cn.vo.TaskResultVo; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import java.util.HashMap; import java.util.List; import java.util.Objects;
4,638
package com.cn.service.impl; /** * The type Drawing service. */ @Service @Slf4j @RequiredArgsConstructor public class DrawingServiceImpl implements DrawingService { private final TsGenerateDrawingMapper tsGenerateDrawingMapper; private final TsDrawingPromptMapper tsDrawingPromptMapper;
package com.cn.service.impl; /** * The type Drawing service. */ @Service @Slf4j @RequiredArgsConstructor public class DrawingServiceImpl implements DrawingService { private final TsGenerateDrawingMapper tsGenerateDrawingMapper; private final TsDrawingPromptMapper tsDrawingPromptMapper;
private final RedisUtils redisUtils;
12
2023-11-05 16:26:39+00:00
8k
373675032/xw-fast
xw-fast-crud/src/main/java/world/xuewei/fast/crud/controller/BaseController.java
[ { "identifier": "BusinessRunTimeException", "path": "xw-fast-core/src/main/java/world/xuewei/fast/core/exception/BusinessRunTimeException.java", "snippet": "@Setter\n@Getter\npublic class BusinessRunTimeException extends RuntimeException {\n\n private static final long serialVersionUID = -48796772838...
import cn.hutool.core.lang.Assert; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import world.xuewei.fast.core.exception.BusinessRunTimeException; import world.xuewei.fast.core.exception.ParamEmptyException; import world.xuewei.fast.crud.dto.request.ReqBody; import world.xuewei.fast.crud.query.QueryBody; import world.xuewei.fast.crud.query.ResultPage; import world.xuewei.fast.crud.service.BaseDBService; import world.xuewei.fast.web.dto.response.RespResult; import java.io.Serializable; import java.util.List;
5,630
package world.xuewei.fast.crud.controller; /** * 基础控制器 * * @author XUEW * @since 2023/11/1 18:02 */ public class BaseController<T> { protected final BaseDBService<T> baseService; public BaseController(BaseDBService<T> baseService) { this.baseService = baseService; } /** * 保存实体 * * @param reqBody 通用请求体 * @return 实体对象 */ @PostMapping("/saveData") @ResponseBody
package world.xuewei.fast.crud.controller; /** * 基础控制器 * * @author XUEW * @since 2023/11/1 18:02 */ public class BaseController<T> { protected final BaseDBService<T> baseService; public BaseController(BaseDBService<T> baseService) { this.baseService = baseService; } /** * 保存实体 * * @param reqBody 通用请求体 * @return 实体对象 */ @PostMapping("/saveData") @ResponseBody
public RespResult saveData(@RequestBody ReqBody<T> reqBody) {
6
2023-11-07 11:45:40+00:00
8k
daominh-studio/quick-mem
app/src/main/java/com/daominh/quickmem/ui/fragments/library/FoldersFragment.java
[ { "identifier": "FolderCopyAdapter", "path": "app/src/main/java/com/daominh/quickmem/adapter/folder/FolderCopyAdapter.java", "snippet": "public class FolderCopyAdapter extends RecyclerView.Adapter<FolderCopyAdapter.FolderViewHolder>{\n private final Context context;\n private final ArrayList<Folde...
import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.daominh.quickmem.adapter.folder.FolderCopyAdapter; import com.daominh.quickmem.data.dao.FolderDAO; import com.daominh.quickmem.data.model.Folder; import com.daominh.quickmem.databinding.FragmentFoldersBinding; import com.daominh.quickmem.preferen.UserSharePreferences; import com.daominh.quickmem.ui.activities.create.CreateFolderActivity; import org.jetbrains.annotations.NotNull; import java.util.ArrayList;
5,105
package com.daominh.quickmem.ui.fragments.library; public class FoldersFragment extends Fragment { private FragmentFoldersBinding binding; private UserSharePreferences userSharePreferences; private ArrayList<Folder> folders; private FolderCopyAdapter folderAdapter; private FolderDAO folderDAO; private String idUser; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); userSharePreferences = new UserSharePreferences(requireActivity()); idUser = userSharePreferences.getId(); folderDAO = new FolderDAO(requireActivity()); } @Override public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentFoldersBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setupUserPreferences(); setupCreateButton(); setupFolders(); setupRecyclerView(); } private void setupUserPreferences() { userSharePreferences = new UserSharePreferences(requireActivity()); idUser = userSharePreferences.getId(); } private void setupCreateButton() {
package com.daominh.quickmem.ui.fragments.library; public class FoldersFragment extends Fragment { private FragmentFoldersBinding binding; private UserSharePreferences userSharePreferences; private ArrayList<Folder> folders; private FolderCopyAdapter folderAdapter; private FolderDAO folderDAO; private String idUser; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); userSharePreferences = new UserSharePreferences(requireActivity()); idUser = userSharePreferences.getId(); folderDAO = new FolderDAO(requireActivity()); } @Override public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentFoldersBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setupUserPreferences(); setupCreateButton(); setupFolders(); setupRecyclerView(); } private void setupUserPreferences() { userSharePreferences = new UserSharePreferences(requireActivity()); idUser = userSharePreferences.getId(); } private void setupCreateButton() {
binding.createSetBtn.setOnClickListener(view1 -> startActivity(new Intent(getActivity(), CreateFolderActivity.class)));
4
2023-11-07 16:56:39+00:00
8k
FRCTeam2910/2023CompetitionRobot-Public
src/main/java/org/frcteam2910/c2023/util/DriverReadouts.java
[ { "identifier": "RobotContainer", "path": "src/main/java/org/frcteam2910/c2023/RobotContainer.java", "snippet": "public class RobotContainer {\n private final PathChooser pathChooser;\n\n private final DrivetrainSubsystem drivetrainSubsystem;\n\n private final LEDSubsystem ledSubsystem;\n\n ...
import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab; import org.frcteam2910.c2023.RobotContainer; import org.frcteam2910.c2023.util.constants.Constants;
6,610
package org.frcteam2910.c2023.util; public class DriverReadouts { public DriverReadouts(RobotContainer container) {
package org.frcteam2910.c2023.util; public class DriverReadouts { public DriverReadouts(RobotContainer container) {
ShuffleboardTab tab = Shuffleboard.getTab(Constants.DRIVER_READOUTS_TAB_NAME);
1
2023-11-03 02:12:12+00:00
8k
YunaBraska/type-map
src/test/java/berlin/yuna/typemap/logic/TypeConverterTest.java
[ { "identifier": "TestEnum", "path": "src/test/java/berlin/yuna/typemap/model/TestEnum.java", "snippet": "public enum TestEnum {\n\n AA,\n BB,\n CC\n}" }, { "identifier": "UnknownClass", "path": "src/test/java/berlin/yuna/typemap/model/UnknownClass.java", "snippet": "public class...
import berlin.yuna.typemap.model.TestEnum; import berlin.yuna.typemap.model.UnknownClass; import berlin.yuna.typemap.model.UnknownNumber; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import static berlin.yuna.typemap.logic.TypeConverter.*; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat;
5,203
package berlin.yuna.typemap.logic; class TypeConverterTest { @BeforeEach void setUp() { System.getProperties().setProperty("user.timezone", "UTC"); TimeZone.setDefault(null); } @Test void convertNullTest() { assertThat(convertObj(null, String.class)).isNull(); } @Test void convertSameTypeTest() { final StringBuilder sb = new StringBuilder("AA"); assertThat(convertObj(sb, StringBuilder.class)).isEqualTo(sb); } @Test void convertFirstItemTest() { assertThat(convertObj(asList("123", "456"), Integer.class)).isEqualTo(123); } @Test void convertEnumTest() { assertThat(convertObj("BB", TestEnum.class)).isEqualTo(TestEnum.BB); assertThat(convertObj("ZZ", TestEnum.class)).isNull(); assertThat(enumOf("BB", TestEnum.class)).isEqualTo(TestEnum.BB); assertThat(enumOf("ZZ", TestEnum.class)).isNull(); } @Test void convertPatentAndExactMatchTest() { assertThat(convertObj("123", Long.class)).isEqualTo(123L); assertThat(convertObj("123", Number.class)).isEqualTo(123d); assertThat(convertObj(123, Long.class)).isEqualTo(123L); assertThat(convertObj(123, Number.class)).isEqualTo(123); } @Test void convertFallBackToStringTest() {
package berlin.yuna.typemap.logic; class TypeConverterTest { @BeforeEach void setUp() { System.getProperties().setProperty("user.timezone", "UTC"); TimeZone.setDefault(null); } @Test void convertNullTest() { assertThat(convertObj(null, String.class)).isNull(); } @Test void convertSameTypeTest() { final StringBuilder sb = new StringBuilder("AA"); assertThat(convertObj(sb, StringBuilder.class)).isEqualTo(sb); } @Test void convertFirstItemTest() { assertThat(convertObj(asList("123", "456"), Integer.class)).isEqualTo(123); } @Test void convertEnumTest() { assertThat(convertObj("BB", TestEnum.class)).isEqualTo(TestEnum.BB); assertThat(convertObj("ZZ", TestEnum.class)).isNull(); assertThat(enumOf("BB", TestEnum.class)).isEqualTo(TestEnum.BB); assertThat(enumOf("ZZ", TestEnum.class)).isNull(); } @Test void convertPatentAndExactMatchTest() { assertThat(convertObj("123", Long.class)).isEqualTo(123L); assertThat(convertObj("123", Number.class)).isEqualTo(123d); assertThat(convertObj(123, Long.class)).isEqualTo(123L); assertThat(convertObj(123, Number.class)).isEqualTo(123); } @Test void convertFallBackToStringTest() {
assertThat(convertObj(new UnknownNumber(), Long.class)).isEqualTo(123L);
2
2023-11-09 14:40:13+00:00
8k
estkme-group/InfiLPA
app/src/main/java/com/infineon/esim/lpa/euicc/se/SeEuiccConnection.java
[ { "identifier": "EuiccConnectionSettings", "path": "app/src/main/java/com/infineon/esim/lpa/euicc/EuiccConnectionSettings.java", "snippet": "public class EuiccConnectionSettings {\n final boolean shallSendTerminalCapability;\n final boolean shallSendOpenLogicalChannel;\n final int profileInitia...
import com.infineon.esim.lpa.euicc.base.generic.Definitions; import com.infineon.esim.util.Bytes; import com.infineon.esim.util.Log; import java.io.IOException; import java.util.ArrayList; import java.util.List; import android.se.omapi.Channel; import android.se.omapi.Reader; import android.se.omapi.Session; import com.infineon.esim.lpa.euicc.EuiccConnectionSettings; import com.infineon.esim.lpa.euicc.base.EuiccConnection; import com.infineon.esim.lpa.euicc.base.generic.Atr;
5,820
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.euicc.se; public class SeEuiccConnection implements EuiccConnection { private static final String TAG = SeEuiccConnection.class.getName(); private final Reader reader; private Session session; private Channel channel; private EuiccConnectionSettings euiccConnectionSettings; public SeEuiccConnection(Reader reader) { this.reader = reader; } @Override public void updateEuiccConnectionSettings(EuiccConnectionSettings euiccConnectionSettings) { this.euiccConnectionSettings = euiccConnectionSettings; } @Override public String getEuiccName() { return reader.getName(); } @Override public boolean resetEuicc() throws Exception { Log.debug(TAG, "Resetting the eUICC."); // Close the connection first close(); // Wait for the phone to detect the profile change try { Thread.sleep(euiccConnectionSettings.getProfileInitializationTime()); } catch (Exception e) { Log.error(Log.getFileLineNumber() + " " + e.getMessage()); } // Open the connection again return open(); } @Override public boolean open() throws Exception { Log.debug(TAG, "Opening connection for eUICC " + reader.getName()); try { if (session == null || session.isClosed()) { Log.debug(TAG, "Opening a new session..."); session = reader.openSession(); if(session != null) { Log.debug(TAG, "Successfully opened a new session."); } else { Log.error(TAG, "Failed to open a new session."); return false; } if(!Atr.isAtrValid(session.getATR())) { Log.error(TAG, "eUICC not allowed!"); close(); throw new Exception("eUICC not allowed!"); } } if (channel == null || !channel.isOpen()) { Log.debug(TAG, "Opening a new logical channel...");
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.euicc.se; public class SeEuiccConnection implements EuiccConnection { private static final String TAG = SeEuiccConnection.class.getName(); private final Reader reader; private Session session; private Channel channel; private EuiccConnectionSettings euiccConnectionSettings; public SeEuiccConnection(Reader reader) { this.reader = reader; } @Override public void updateEuiccConnectionSettings(EuiccConnectionSettings euiccConnectionSettings) { this.euiccConnectionSettings = euiccConnectionSettings; } @Override public String getEuiccName() { return reader.getName(); } @Override public boolean resetEuicc() throws Exception { Log.debug(TAG, "Resetting the eUICC."); // Close the connection first close(); // Wait for the phone to detect the profile change try { Thread.sleep(euiccConnectionSettings.getProfileInitializationTime()); } catch (Exception e) { Log.error(Log.getFileLineNumber() + " " + e.getMessage()); } // Open the connection again return open(); } @Override public boolean open() throws Exception { Log.debug(TAG, "Opening connection for eUICC " + reader.getName()); try { if (session == null || session.isClosed()) { Log.debug(TAG, "Opening a new session..."); session = reader.openSession(); if(session != null) { Log.debug(TAG, "Successfully opened a new session."); } else { Log.error(TAG, "Failed to open a new session."); return false; } if(!Atr.isAtrValid(session.getATR())) { Log.error(TAG, "eUICC not allowed!"); close(); throw new Exception("eUICC not allowed!"); } } if (channel == null || !channel.isOpen()) { Log.debug(TAG, "Opening a new logical channel...");
channel = session.openLogicalChannel(Bytes.decodeHexString(Definitions.ISDR_AID));
4
2023-11-06 02:41:13+00:00
8k
Teleight/TeleightBots
src/main/java/org/teleight/teleightbots/updateprocessor/LongPollingUpdateProcessor.java
[ { "identifier": "TeleightBots", "path": "src/main/java/org/teleight/teleightbots/TeleightBots.java", "snippet": "public final class TeleightBots {\n\n private static TeleightBotsProcess teleightBotsProcess;\n\n public static @NotNull TeleightBots init() {\n updateProcess();\n return ...
import com.fasterxml.jackson.core.JsonProcessingException; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.teleight.teleightbots.TeleightBots; import org.teleight.teleightbots.api.ApiMethod; import org.teleight.teleightbots.api.MultiPartApiMethod; import org.teleight.teleightbots.api.methods.GetMe; import org.teleight.teleightbots.api.methods.GetUpdates; import org.teleight.teleightbots.api.objects.Message; import org.teleight.teleightbots.api.objects.Update; import org.teleight.teleightbots.api.objects.User; import org.teleight.teleightbots.api.objects.chat.Chat; import org.teleight.teleightbots.api.objects.chat.ChatMemberUpdated; import org.teleight.teleightbots.api.objects.chat.member.*; import org.teleight.teleightbots.bot.Bot; import org.teleight.teleightbots.bot.BotSettings; import org.teleight.teleightbots.event.bot.UpdateReceivedEvent; import org.teleight.teleightbots.event.bot.channel.BotJoinChannelEvent; import org.teleight.teleightbots.event.bot.channel.BotQuitChannelEvent; import org.teleight.teleightbots.event.bot.channel.ChannelSendMessageEvent; import org.teleight.teleightbots.event.bot.group.BotJoinedGroupEvent; import org.teleight.teleightbots.event.bot.group.BotLeftGroupEvent; import org.teleight.teleightbots.event.keyboard.ButtonPressEvent; import org.teleight.teleightbots.event.user.UserInlineQueryReceivedEvent; import org.teleight.teleightbots.event.user.UserMessageReceivedEvent; import org.teleight.teleightbots.exception.exceptions.RateLimitException; import org.teleight.teleightbots.exception.exceptions.TelegramRequestException; import org.teleight.teleightbots.utils.MultiPartBodyPublisher; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean;
5,330
package org.teleight.teleightbots.updateprocessor; public class LongPollingUpdateProcessor implements UpdateProcessor { private final HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.of(10, ChronoUnit.SECONDS)) .version(HttpClient.Version.HTTP_2) .build(); private Thread updateProcessorThread; private Bot bot; private int lastReceivedUpdate = 0; private final Object AUTH_LOCK = new Object(); @Override public void setBot(@NotNull Bot bot) { if (this.bot != null) { throw new IllegalArgumentException("Bot instance was already assigned to this update processor"); } this.bot = bot; } @Override public void start() { bot.execute(new GetMe()) .thenAcceptAsync(user -> { synchronized (AUTH_LOCK) { System.out.println("Bot authenticated: " + user.username()); AUTH_LOCK.notifyAll(); } }) .exceptionally(throwable -> { synchronized (AUTH_LOCK) { shutdown(); AUTH_LOCK.notifyAll(); System.out.println("Failed to authenticate bot: " + throwable.getMessage()); } return null; }); updateProcessorThread = new UpdateProcessorThread(); updateProcessorThread.setName(bot.getBotUsername() + " Update Processor"); updateProcessorThread.start(); } @Override public void shutdown() { updateProcessorThread.interrupt(); } private void executeGetUpdates() { final BotSettings settings = bot.getBotSettings(); final GetUpdates getUpdates = GetUpdates.of() .withTimeout(settings.updatesTimeout()) .withLimit(settings.updatesLimit()) .withOffset(lastReceivedUpdate + 1); final String responseJson = UNSAFE_executeMethod(getUpdates) .exceptionally(throwable -> { return null; }) .join(); if(responseJson == null){ return; } Update[] updates; try { updates = getUpdates.deserializeResponse(responseJson); } catch (TelegramRequestException e) { TeleightBots.getExceptionManager().handleException(e); return; } if (updates.length == 0) { return; } // Mark updates for removal int newSize = 0; for (int i = 0; i < updates.length; i++) { Update update = updates[i]; if (update.updateId() >= lastReceivedUpdate) { updates[newSize] = update; newSize++; } } // Compact the array if (newSize < updates.length) { Update[] newUpdates = new Update[newSize]; System.arraycopy(updates, 0, newUpdates, 0, newSize); updates = newUpdates; } // Process the updates for (final Update update : updates) { handleNewUpdate(update, responseJson); } // Update lastReceivedUpdate if (updates.length > 0) { lastReceivedUpdate = updates[updates.length - 1].updateId(); } } @ApiStatus.Internal private void handleNewUpdate(@NotNull Update update, String responseJson) { bot.getEventManager() .call(new UpdateReceivedEvent(bot, update, responseJson)) .thenAccept(updateReceivedEvent -> { final boolean hasCallbackQuery = update.callbackQuery() != null; if (hasCallbackQuery) { final AtomicBoolean completed = new AtomicBoolean();
package org.teleight.teleightbots.updateprocessor; public class LongPollingUpdateProcessor implements UpdateProcessor { private final HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.of(10, ChronoUnit.SECONDS)) .version(HttpClient.Version.HTTP_2) .build(); private Thread updateProcessorThread; private Bot bot; private int lastReceivedUpdate = 0; private final Object AUTH_LOCK = new Object(); @Override public void setBot(@NotNull Bot bot) { if (this.bot != null) { throw new IllegalArgumentException("Bot instance was already assigned to this update processor"); } this.bot = bot; } @Override public void start() { bot.execute(new GetMe()) .thenAcceptAsync(user -> { synchronized (AUTH_LOCK) { System.out.println("Bot authenticated: " + user.username()); AUTH_LOCK.notifyAll(); } }) .exceptionally(throwable -> { synchronized (AUTH_LOCK) { shutdown(); AUTH_LOCK.notifyAll(); System.out.println("Failed to authenticate bot: " + throwable.getMessage()); } return null; }); updateProcessorThread = new UpdateProcessorThread(); updateProcessorThread.setName(bot.getBotUsername() + " Update Processor"); updateProcessorThread.start(); } @Override public void shutdown() { updateProcessorThread.interrupt(); } private void executeGetUpdates() { final BotSettings settings = bot.getBotSettings(); final GetUpdates getUpdates = GetUpdates.of() .withTimeout(settings.updatesTimeout()) .withLimit(settings.updatesLimit()) .withOffset(lastReceivedUpdate + 1); final String responseJson = UNSAFE_executeMethod(getUpdates) .exceptionally(throwable -> { return null; }) .join(); if(responseJson == null){ return; } Update[] updates; try { updates = getUpdates.deserializeResponse(responseJson); } catch (TelegramRequestException e) { TeleightBots.getExceptionManager().handleException(e); return; } if (updates.length == 0) { return; } // Mark updates for removal int newSize = 0; for (int i = 0; i < updates.length; i++) { Update update = updates[i]; if (update.updateId() >= lastReceivedUpdate) { updates[newSize] = update; newSize++; } } // Compact the array if (newSize < updates.length) { Update[] newUpdates = new Update[newSize]; System.arraycopy(updates, 0, newUpdates, 0, newSize); updates = newUpdates; } // Process the updates for (final Update update : updates) { handleNewUpdate(update, responseJson); } // Update lastReceivedUpdate if (updates.length > 0) { lastReceivedUpdate = updates[updates.length - 1].updateId(); } } @ApiStatus.Internal private void handleNewUpdate(@NotNull Update update, String responseJson) { bot.getEventManager() .call(new UpdateReceivedEvent(bot, update, responseJson)) .thenAccept(updateReceivedEvent -> { final boolean hasCallbackQuery = update.callbackQuery() != null; if (hasCallbackQuery) { final AtomicBoolean completed = new AtomicBoolean();
final ButtonPressEvent buttonPressEvent = new ButtonPressEvent(bot, update, completed);
5
2023-11-04 16:55:27+00:00
8k
DJ-Raven/swing-glasspane-popup
src/test/java/test/MyDrawerBuilder.java
[ { "identifier": "DrawerPanel", "path": "src/main/java/raven/drawer/component/DrawerPanel.java", "snippet": "public class DrawerPanel extends GlassPaneChild {\n\n private final DrawerBuilder drawerBuilder;\n\n public DrawerPanel(DrawerBuilder drawerBuilder) {\n this.drawerBuilder = drawerBui...
import com.formdev.flatlaf.FlatClientProperties; import com.formdev.flatlaf.extras.FlatSVGIcon; import raven.drawer.component.DrawerPanel; import raven.drawer.component.footer.SimpleFooterData; import raven.drawer.component.footer.SimpleFooterStyle; import raven.drawer.component.header.SimpleHeaderData; import raven.drawer.component.header.SimpleHeaderStyle; import raven.drawer.component.menu.*; import raven.drawer.component.SimpleDrawerBuilder; import raven.drawer.component.menu.data.Item; import raven.drawer.component.menu.data.MenuItem; import raven.swing.AvatarIcon; import javax.swing.*; import java.awt.*; import java.util.Arrays;
4,222
public SimpleMenuOption getSimpleMenuOption() { MenuItem items[] = new MenuItem[]{ new Item.Label("MAIN"), new Item("Dashboard", "dashboard.svg"), new Item.Label("WEB APP"), new Item("Email", "email.svg") .subMenu("Inbox") .subMenu( new Item("Group Read") .subMenu("Read 1") .subMenu("Read 2") .subMenu( new Item("Group Item") .subMenu("Item 1") .subMenu("Item 2") .subMenu("Item 3") .subMenu("Item 4") .subMenu("Item 5") .subMenu("Item 6") ) .subMenu("Read 3") .subMenu("Read 4") .subMenu("Read 5") ) .subMenu("Compost"), new Item("Chat", "chat.svg"), new Item("Calendar", "calendar.svg"), new Item.Label("COMPONENT"), new Item("Advanced UI", "ui.svg") .subMenu("Cropper") .subMenu("Owl Carousel") .subMenu("Sweet Alert"), new Item("Forms", "forms.svg") .subMenu("Basic Elements") .subMenu("Advanced Elements") .subMenu("SEditors") .subMenu("Wizard"), new Item.Label("OTHER"), new Item("Charts", "chart.svg") .subMenu("Apex") .subMenu("Flot") .subMenu("Sparkline"), new Item("Icons", "icon.svg") .subMenu("Feather Icons") .subMenu("Flag Icons") .subMenu("Mdi Icons"), new Item("Special Pages", "page.svg") .subMenu("Blank page") .subMenu("Faq") .subMenu("Invoice") .subMenu("Profile") .subMenu("Pricing") .subMenu("Timeline") }; SimpleMenuOption simpleMenuOption = new SimpleMenuOption() { @Override public Icon buildMenuIcon(String path, float scale) { FlatSVGIcon icon = new FlatSVGIcon(path, scale); FlatSVGIcon.ColorFilter colorFilter = new FlatSVGIcon.ColorFilter(); colorFilter.add(Color.decode("#969696"), Color.decode("#FAFAFA"), Color.decode("#969696")); icon.setColorFilter(colorFilter); return icon; } }; simpleMenuOption.addMenuEvent(new MenuEvent() { @Override public void selected(MenuAction action, int[] index) { System.out.println("Drawer menu selected " + Arrays.toString(index)); } }); simpleMenuOption.setMenuStyle(new SimpleMenuStyle() { @Override public void styleMenuItem(JButton menu, int[] index) { menu.putClientProperty(FlatClientProperties.STYLE, "" + "[light]foreground:#FAFAFA;" + "arc:0"); } @Override public void styleMenu(JComponent component) { component.putClientProperty(FlatClientProperties.STYLE, "" + "background:$Drawer.background"); } @Override public void styleLabel(JLabel label) { label.putClientProperty(FlatClientProperties.STYLE, "" + "[light]foreground:darken(#FAFAFA,15%);" + "[dark]foreground:darken($Label.foreground,30%)"); } }); simpleMenuOption.setMenuValidation(new MenuValidation() { @Override public boolean menuValidation(int[] index) { if (index.length == 1) { // Hide Calendar if (index[0] == 3) { return false; } } else if (index.length == 3) { // Hide Read 4 if (index[0] == 1 && index[1] == 1 && index[2] == 4) { return false; } } return true; } }); simpleMenuOption.setMenus(items) .setBaseIconPath("icon") .setIconScale(0.45f); return simpleMenuOption; } @Override
package test; public class MyDrawerBuilder extends SimpleDrawerBuilder { @Override public SimpleHeaderData getSimpleHeaderData() { AvatarIcon icon = new AvatarIcon(getClass().getResource("/image/profile.png"), 60, 60, 999); icon.setBorder(2); return new SimpleHeaderData() .setIcon(icon) .setTitle("Ra Ven") .setDescription("raven@gmail.com") .setHeaderStyle(new SimpleHeaderStyle() { @Override public void styleTitle(JLabel label) { label.putClientProperty(FlatClientProperties.STYLE, "" + "[light]foreground:#FAFAFA"); } @Override public void styleDescription(JLabel label) { label.putClientProperty(FlatClientProperties.STYLE, "" + "[light]foreground:#E1E1E1"); } }); } @Override public SimpleFooterData getSimpleFooterData() { return new SimpleFooterData() .setTitle("Java Swing Drawer") .setDescription("Version 1.1.0") .setFooterStyle(new SimpleFooterStyle() { @Override public void styleTitle(JLabel label) { label.putClientProperty(FlatClientProperties.STYLE, "" + "[light]foreground:#FAFAFA"); } @Override public void styleDescription(JLabel label) { label.putClientProperty(FlatClientProperties.STYLE, "" + "[light]foreground:#E1E1E1"); } }); } @Override public SimpleMenuOption getSimpleMenuOption() { MenuItem items[] = new MenuItem[]{ new Item.Label("MAIN"), new Item("Dashboard", "dashboard.svg"), new Item.Label("WEB APP"), new Item("Email", "email.svg") .subMenu("Inbox") .subMenu( new Item("Group Read") .subMenu("Read 1") .subMenu("Read 2") .subMenu( new Item("Group Item") .subMenu("Item 1") .subMenu("Item 2") .subMenu("Item 3") .subMenu("Item 4") .subMenu("Item 5") .subMenu("Item 6") ) .subMenu("Read 3") .subMenu("Read 4") .subMenu("Read 5") ) .subMenu("Compost"), new Item("Chat", "chat.svg"), new Item("Calendar", "calendar.svg"), new Item.Label("COMPONENT"), new Item("Advanced UI", "ui.svg") .subMenu("Cropper") .subMenu("Owl Carousel") .subMenu("Sweet Alert"), new Item("Forms", "forms.svg") .subMenu("Basic Elements") .subMenu("Advanced Elements") .subMenu("SEditors") .subMenu("Wizard"), new Item.Label("OTHER"), new Item("Charts", "chart.svg") .subMenu("Apex") .subMenu("Flot") .subMenu("Sparkline"), new Item("Icons", "icon.svg") .subMenu("Feather Icons") .subMenu("Flag Icons") .subMenu("Mdi Icons"), new Item("Special Pages", "page.svg") .subMenu("Blank page") .subMenu("Faq") .subMenu("Invoice") .subMenu("Profile") .subMenu("Pricing") .subMenu("Timeline") }; SimpleMenuOption simpleMenuOption = new SimpleMenuOption() { @Override public Icon buildMenuIcon(String path, float scale) { FlatSVGIcon icon = new FlatSVGIcon(path, scale); FlatSVGIcon.ColorFilter colorFilter = new FlatSVGIcon.ColorFilter(); colorFilter.add(Color.decode("#969696"), Color.decode("#FAFAFA"), Color.decode("#969696")); icon.setColorFilter(colorFilter); return icon; } }; simpleMenuOption.addMenuEvent(new MenuEvent() { @Override public void selected(MenuAction action, int[] index) { System.out.println("Drawer menu selected " + Arrays.toString(index)); } }); simpleMenuOption.setMenuStyle(new SimpleMenuStyle() { @Override public void styleMenuItem(JButton menu, int[] index) { menu.putClientProperty(FlatClientProperties.STYLE, "" + "[light]foreground:#FAFAFA;" + "arc:0"); } @Override public void styleMenu(JComponent component) { component.putClientProperty(FlatClientProperties.STYLE, "" + "background:$Drawer.background"); } @Override public void styleLabel(JLabel label) { label.putClientProperty(FlatClientProperties.STYLE, "" + "[light]foreground:darken(#FAFAFA,15%);" + "[dark]foreground:darken($Label.foreground,30%)"); } }); simpleMenuOption.setMenuValidation(new MenuValidation() { @Override public boolean menuValidation(int[] index) { if (index.length == 1) { // Hide Calendar if (index[0] == 3) { return false; } } else if (index.length == 3) { // Hide Read 4 if (index[0] == 1 && index[1] == 1 && index[2] == 4) { return false; } } return true; } }); simpleMenuOption.setMenus(items) .setBaseIconPath("icon") .setIconScale(0.45f); return simpleMenuOption; } @Override
public void build(DrawerPanel drawerPanel) {
0
2023-11-08 14:06:16+00:00
8k
CxyJerry/pilipala
src/main/java/com/jerry/pilipala/domain/user/service/impl/UserServiceImpl.java
[ { "identifier": "UserInfoBO", "path": "src/main/java/com/jerry/pilipala/application/bo/UserInfoBO.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class UserInfoBO {\n private String uid;\n private String roleId;\n private List<String> permissionIdList;\n}" }, { "identifier": ...
import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.date.DateUtil; import com.jerry.pilipala.application.bo.UserInfoBO; import com.jerry.pilipala.application.dto.EmailLoginDTO; import com.jerry.pilipala.application.dto.LoginDTO; import com.jerry.pilipala.application.vo.user.UserVO; import com.jerry.pilipala.domain.common.template.MessageTrigger; import com.jerry.pilipala.domain.message.service.SmsService; import com.jerry.pilipala.domain.user.entity.mongo.Role; import com.jerry.pilipala.domain.user.entity.mongo.User; import com.jerry.pilipala.domain.user.entity.neo4j.UserEntity; import com.jerry.pilipala.domain.user.repository.UserEntityRepository; import com.jerry.pilipala.domain.user.service.UserService; import com.jerry.pilipala.infrastructure.common.errors.BusinessException; import com.jerry.pilipala.infrastructure.common.response.StandardResponse; import com.jerry.pilipala.infrastructure.enums.message.TemplateNameEnum; import com.jerry.pilipala.infrastructure.enums.redis.UserCacheKeyEnum; import com.jerry.pilipala.infrastructure.utils.CaptchaUtil; import com.jerry.pilipala.infrastructure.utils.JsonHelper; import com.jerry.pilipala.infrastructure.utils.Page; import com.jerry.pilipala.infrastructure.utils.RequestUtil; import org.apache.commons.lang3.StringUtils; import org.bson.types.ObjectId; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.time.LocalDateTime; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
6,539
package com.jerry.pilipala.domain.user.service.impl; @Service public class UserServiceImpl implements UserService { private final RedisTemplate<String, Object> redisTemplate; private final MongoTemplate mongoTemplate; private final SmsService smsService; private final UserEntityRepository userEntityRepository; private final HttpServletRequest request; private final JsonHelper jsonHelper; private final MessageTrigger messageTrigger; public UserServiceImpl(RedisTemplate<String, Object> redisTemplate, MongoTemplate mongoTemplate, SmsService smsService, UserEntityRepository userEntityRepository, HttpServletRequest request, JsonHelper jsonHelper, MessageTrigger messageTrigger) { this.redisTemplate = redisTemplate; this.mongoTemplate = mongoTemplate; this.smsService = smsService; this.userEntityRepository = userEntityRepository; this.request = request; this.jsonHelper = jsonHelper; this.messageTrigger = messageTrigger; } @Override
package com.jerry.pilipala.domain.user.service.impl; @Service public class UserServiceImpl implements UserService { private final RedisTemplate<String, Object> redisTemplate; private final MongoTemplate mongoTemplate; private final SmsService smsService; private final UserEntityRepository userEntityRepository; private final HttpServletRequest request; private final JsonHelper jsonHelper; private final MessageTrigger messageTrigger; public UserServiceImpl(RedisTemplate<String, Object> redisTemplate, MongoTemplate mongoTemplate, SmsService smsService, UserEntityRepository userEntityRepository, HttpServletRequest request, JsonHelper jsonHelper, MessageTrigger messageTrigger) { this.redisTemplate = redisTemplate; this.mongoTemplate = mongoTemplate; this.smsService = smsService; this.userEntityRepository = userEntityRepository; this.request = request; this.jsonHelper = jsonHelper; this.messageTrigger = messageTrigger; } @Override
public UserVO login(LoginDTO loginDTO) {
3
2023-11-03 10:05:02+00:00
8k
viego1999/xuecheng-plus-project
xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/impl/CourseBaseInfoServiceImpl.java
[ { "identifier": "XueChengPlusException", "path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/exception/XueChengPlusException.java", "snippet": "public class XueChengPlusException extends RuntimeException {\n private static final long serialVersionUID = 5565760508056698922L;\n private Strin...
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.xuecheng.base.exception.XueChengPlusException; import com.xuecheng.base.model.PageParams; import com.xuecheng.base.model.PageResult; import com.xuecheng.base.model.RestResponse; import com.xuecheng.content.mapper.CourseBaseMapper; import com.xuecheng.content.mapper.CourseCategoryMapper; import com.xuecheng.content.mapper.CourseMarketMapper; import com.xuecheng.content.model.dto.AddCourseDto; import com.xuecheng.content.model.dto.CourseBaseInfoDto; import com.xuecheng.content.model.dto.EditCourseDto; import com.xuecheng.content.model.dto.QueryCourseParamsDto; import com.xuecheng.content.model.po.CourseBase; import com.xuecheng.content.model.po.CourseCategory; import com.xuecheng.content.model.po.CourseMarket; import com.xuecheng.content.service.CourseBaseInfoService; import com.xuecheng.content.service.CourseMarketService; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.time.LocalDateTime; import java.util.List;
5,715
package com.xuecheng.content.service.impl; /** * @author Wuxy * @version 1.0 * @ClassName CourseBaseInfoServiceImpl * @since 2023/1/19 10:18 */ @Service public class CourseBaseInfoServiceImpl implements CourseBaseInfoService { @Resource private CourseBaseMapper courseBaseMapper; @Resource private CourseMarketMapper courseMarketMapper; @Resource private CourseCategoryMapper courseCategoryMapper; @Resource private CourseMarketService courseMarketService; @Override public PageResult<CourseBase> queryCourseBaseList(Long companyId, PageParams params, QueryCourseParamsDto queryCourseParams) { LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>(); // 拼接查询条件 // 根据机构id进行查询 queryWrapper.eq(CourseBase::getCompanyId, companyId); // 根据课程名称模糊查询 name like '%name%' queryWrapper.like(StringUtils.isNotEmpty(queryCourseParams.getCourseName()), CourseBase::getName, queryCourseParams.getCourseName()); // 根据课程审核状态 queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParams.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParams.getAuditStatus()); // 根据课程发布状态 queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParams.getPublishStatus()), CourseBase::getStatus, queryCourseParams.getPublishStatus()); // 分页参数 Page<CourseBase> page = new Page<>(params.getPageNo(), params.getPageSize()); // 分页查询 Page 分页参数 Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper); // 数据 List<CourseBase> items = pageResult.getRecords(); // 总记录数 long total = pageResult.getTotal(); return new PageResult<>(items, total, params.getPageNo(), params.getPageSize()); } @Transactional @Override public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto courseDto) { // 对参数进行合法性校验 // 合法性校验 if (StringUtils.isBlank(courseDto.getName())) { XueChengPlusException.cast("课程名称为空"); } if (StringUtils.isBlank(courseDto.getMt())) { XueChengPlusException.cast("课程分类为空"); } if (StringUtils.isBlank(courseDto.getSt())) { XueChengPlusException.cast("课程分类为空"); } if (StringUtils.isBlank(courseDto.getGrade())) { XueChengPlusException.cast("课程等级为空"); } if (StringUtils.isBlank(courseDto.getTeachmode())) { XueChengPlusException.cast("教育模式为空"); } if (StringUtils.isBlank(courseDto.getUsers())) { XueChengPlusException.cast("适应人群为空"); } if (StringUtils.isBlank(courseDto.getCharge())) { XueChengPlusException.cast("收费规则为空"); } // 对数据进行封装,调用 mapper 进行数据持久化 CourseBase courseBase = new CourseBase(); // 拷贝基本信息 BeanUtils.copyProperties(courseDto, courseBase); // 设置机构 id courseBase.setCompanyId(companyId); // 创建时间 courseBase.setCreateDate(LocalDateTime.now()); // 审核状态设置为未提交 courseBase.setAuditStatus("202002"); // 发布状态默认为未发布 courseBase.setStatus("203001"); // 向课程基本表插入一条数据 int insert1 = courseBaseMapper.insert(courseBase); // 获取课程id Long courseId = courseBase.getId(); CourseMarket courseMarket = new CourseMarket(); BeanUtils.copyProperties(courseDto, courseMarket); courseMarket.setId(courseId); int insert2 = this.saveCourseMarket(courseMarket); if (insert1 < 1 || insert2 < 1) { XueChengPlusException.cast("添加课程失败"); } // 组装要返回的结果 return getCourseBaseInfo(courseId); } @Override public CourseBaseInfoDto queryCourseBaseById(Long courseId) { CourseBase courseBase = courseBaseMapper.selectById(courseId); LambdaQueryWrapper<CourseMarket> queryWrapper = new LambdaQueryWrapper<>(); CourseMarket courseMarket = courseMarketMapper.selectOne(queryWrapper.eq(CourseMarket::getId, courseId)); if (courseBase == null || courseMarket == null) { return null; } CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto(); BeanUtils.copyProperties(courseBase, courseBaseInfoDto); BeanUtils.copyProperties(courseMarket, courseBaseInfoDto); // 填充 mtName 和 stName courseBaseInfoDto.setMtName(courseCategoryMapper.selectNameById(courseBase.getMt())); courseBaseInfoDto.setStName(courseCategoryMapper.selectNameById(courseBase.getSt())); return courseBaseInfoDto; } @Transactional @Override public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto dto) { // 校验 // 课程 id Long courseId = dto.getId(); CourseBase courseBase = courseBaseMapper.selectById(courseId); if (courseBase == null) { XueChengPlusException.cast("课程不存在"); ; } // 校验本机构只能修改本机构的课程 if (!courseBase.getCompanyId().equals(companyId)) { XueChengPlusException.cast("本机构只能修改本机构的课程"); } // 封装基本信息的数据 BeanUtils.copyProperties(dto, courseBase); // 更新课程基本信息 courseBase.setChangeDate(LocalDateTime.now()); courseBaseMapper.updateById(courseBase); // 封装营销信息的数据 CourseMarket courseMarket = courseMarketMapper.selectById(courseId); if (courseMarket == null) { courseMarket = new CourseMarket(); } BeanUtils.copyProperties(dto, courseMarket); int update = this.saveCourseMarket(courseMarket); System.out.println("更新营销表影响条数:" + update); // 查询课程信息并返回 return getCourseBaseInfo(courseId); } @Override
package com.xuecheng.content.service.impl; /** * @author Wuxy * @version 1.0 * @ClassName CourseBaseInfoServiceImpl * @since 2023/1/19 10:18 */ @Service public class CourseBaseInfoServiceImpl implements CourseBaseInfoService { @Resource private CourseBaseMapper courseBaseMapper; @Resource private CourseMarketMapper courseMarketMapper; @Resource private CourseCategoryMapper courseCategoryMapper; @Resource private CourseMarketService courseMarketService; @Override public PageResult<CourseBase> queryCourseBaseList(Long companyId, PageParams params, QueryCourseParamsDto queryCourseParams) { LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>(); // 拼接查询条件 // 根据机构id进行查询 queryWrapper.eq(CourseBase::getCompanyId, companyId); // 根据课程名称模糊查询 name like '%name%' queryWrapper.like(StringUtils.isNotEmpty(queryCourseParams.getCourseName()), CourseBase::getName, queryCourseParams.getCourseName()); // 根据课程审核状态 queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParams.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParams.getAuditStatus()); // 根据课程发布状态 queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParams.getPublishStatus()), CourseBase::getStatus, queryCourseParams.getPublishStatus()); // 分页参数 Page<CourseBase> page = new Page<>(params.getPageNo(), params.getPageSize()); // 分页查询 Page 分页参数 Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper); // 数据 List<CourseBase> items = pageResult.getRecords(); // 总记录数 long total = pageResult.getTotal(); return new PageResult<>(items, total, params.getPageNo(), params.getPageSize()); } @Transactional @Override public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto courseDto) { // 对参数进行合法性校验 // 合法性校验 if (StringUtils.isBlank(courseDto.getName())) { XueChengPlusException.cast("课程名称为空"); } if (StringUtils.isBlank(courseDto.getMt())) { XueChengPlusException.cast("课程分类为空"); } if (StringUtils.isBlank(courseDto.getSt())) { XueChengPlusException.cast("课程分类为空"); } if (StringUtils.isBlank(courseDto.getGrade())) { XueChengPlusException.cast("课程等级为空"); } if (StringUtils.isBlank(courseDto.getTeachmode())) { XueChengPlusException.cast("教育模式为空"); } if (StringUtils.isBlank(courseDto.getUsers())) { XueChengPlusException.cast("适应人群为空"); } if (StringUtils.isBlank(courseDto.getCharge())) { XueChengPlusException.cast("收费规则为空"); } // 对数据进行封装,调用 mapper 进行数据持久化 CourseBase courseBase = new CourseBase(); // 拷贝基本信息 BeanUtils.copyProperties(courseDto, courseBase); // 设置机构 id courseBase.setCompanyId(companyId); // 创建时间 courseBase.setCreateDate(LocalDateTime.now()); // 审核状态设置为未提交 courseBase.setAuditStatus("202002"); // 发布状态默认为未发布 courseBase.setStatus("203001"); // 向课程基本表插入一条数据 int insert1 = courseBaseMapper.insert(courseBase); // 获取课程id Long courseId = courseBase.getId(); CourseMarket courseMarket = new CourseMarket(); BeanUtils.copyProperties(courseDto, courseMarket); courseMarket.setId(courseId); int insert2 = this.saveCourseMarket(courseMarket); if (insert1 < 1 || insert2 < 1) { XueChengPlusException.cast("添加课程失败"); } // 组装要返回的结果 return getCourseBaseInfo(courseId); } @Override public CourseBaseInfoDto queryCourseBaseById(Long courseId) { CourseBase courseBase = courseBaseMapper.selectById(courseId); LambdaQueryWrapper<CourseMarket> queryWrapper = new LambdaQueryWrapper<>(); CourseMarket courseMarket = courseMarketMapper.selectOne(queryWrapper.eq(CourseMarket::getId, courseId)); if (courseBase == null || courseMarket == null) { return null; } CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto(); BeanUtils.copyProperties(courseBase, courseBaseInfoDto); BeanUtils.copyProperties(courseMarket, courseBaseInfoDto); // 填充 mtName 和 stName courseBaseInfoDto.setMtName(courseCategoryMapper.selectNameById(courseBase.getMt())); courseBaseInfoDto.setStName(courseCategoryMapper.selectNameById(courseBase.getSt())); return courseBaseInfoDto; } @Transactional @Override public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto dto) { // 校验 // 课程 id Long courseId = dto.getId(); CourseBase courseBase = courseBaseMapper.selectById(courseId); if (courseBase == null) { XueChengPlusException.cast("课程不存在"); ; } // 校验本机构只能修改本机构的课程 if (!courseBase.getCompanyId().equals(companyId)) { XueChengPlusException.cast("本机构只能修改本机构的课程"); } // 封装基本信息的数据 BeanUtils.copyProperties(dto, courseBase); // 更新课程基本信息 courseBase.setChangeDate(LocalDateTime.now()); courseBaseMapper.updateById(courseBase); // 封装营销信息的数据 CourseMarket courseMarket = courseMarketMapper.selectById(courseId); if (courseMarket == null) { courseMarket = new CourseMarket(); } BeanUtils.copyProperties(dto, courseMarket); int update = this.saveCourseMarket(courseMarket); System.out.println("更新营销表影响条数:" + update); // 查询课程信息并返回 return getCourseBaseInfo(courseId); } @Override
public RestResponse<Boolean> deleteCourseBase(Long courseId) {
3
2023-11-04 07:15:26+00:00
8k
dionp3/xplora
app/src/main/java/org/gnulag/xplora/controllers/Controller.java
[ { "identifier": "RedBlackTreeMap", "path": "app/src/main/java/org/gnulag/xplora/models/RedBlackTreeMap.java", "snippet": "public class RedBlackTreeMap<K extends Comparable<K>, V extends Comparable<V>> {\n private Node<K, V> root;\n private Node<K, V> TNULL;\n\n public RedBlackTreeMap() {\n TNULL =...
import java.net.URL; import java.util.List; import java.util.ResourceBundle; import javafx.animation.TranslateTransition; import javafx.concurrent.Worker; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.control.Button; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.cell.TextFieldListCell; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import javafx.scene.web.WebView; import javafx.util.Duration; import org.gnulag.xplora.models.RedBlackTreeMap; import org.gnulag.xplora.utils.GameGimmick; import org.gnulag.xplora.utils.JSONUtil; import org.gnulag.xplora.utils.PrintsUtil; import org.gnulag.xplora.utils.RandomGimmick;
5,902
package org.gnulag.xplora.controllers; public class Controller implements Initializable { @FXML private ListView<String> listView; @FXML private TextField searchBar; @FXML private Label searchButton; @FXML private Label clearListView; @FXML private AnchorPane slider; @FXML private VBox textAreaContainer; @FXML private Label backButton; @FXML private TextArea description; private boolean isFullText = false;
package org.gnulag.xplora.controllers; public class Controller implements Initializable { @FXML private ListView<String> listView; @FXML private TextField searchBar; @FXML private Label searchButton; @FXML private Label clearListView; @FXML private AnchorPane slider; @FXML private VBox textAreaContainer; @FXML private Label backButton; @FXML private TextArea description; private boolean isFullText = false;
private RedBlackTreeMap<String, String> rbTree;
0
2023-11-03 13:01:57+00:00
8k
Verusins/CMS-Android-Simulation
app/src/main/java/example/com/cmsandroidsimulation/EventStudentFragment.java
[ { "identifier": "EventComment", "path": "app/src/main/java/example/com/cmsandroidsimulation/datastructures/EventComment.java", "snippet": "public class EventComment extends UserPost {\n private final int rating;\n private final Date date;\n public EventComment(String author, String details, int...
import android.annotation.SuppressLint; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.navigation.fragment.NavHostFragment; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.DocumentSnapshot; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Locale; import example.com.cmsandroidsimulation.databinding.FragmentEventStudentBinding; import example.com.cmsandroidsimulation.datastructures.EventComment; import example.com.cmsandroidsimulation.datastructures.EventInfo; import example.com.cmsandroidsimulation.apiwrapper.Student;
3,764
// Un-RSVP binding.eventRSVPed.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { binding.eventWriteCommentWrapper.setVisibility(View.GONE); binding.eventRSVPed.setVisibility(View.GONE); binding.eventRSVP.setVisibility(View.VISIBLE); registeredMembers[0]--; binding.eventMembers.setText("Registered: " + registeredMembers[0] + "/" + maxMembers); Student.getInstance().setEventHasRSVPd(eventInfo, false); } }); // Click rating and change rating final int[] rating = {-1}; binding.commentWriteRating1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { rating[0] = 1; binding.commentWriteRating1.setText("★"); binding.commentWriteRating2.setText("☆"); binding.commentWriteRating3.setText("☆"); binding.commentWriteRating4.setText("☆"); binding.commentWriteRating5.setText("☆"); } }); binding.commentWriteRating2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { rating[0] = 2; binding.commentWriteRating1.setText("★"); binding.commentWriteRating2.setText("★"); binding.commentWriteRating3.setText("☆"); binding.commentWriteRating4.setText("☆"); binding.commentWriteRating5.setText("☆"); } }); binding.commentWriteRating3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { rating[0] = 3; binding.commentWriteRating1.setText("★"); binding.commentWriteRating2.setText("★"); binding.commentWriteRating3.setText("★"); binding.commentWriteRating4.setText("☆"); binding.commentWriteRating5.setText("☆"); } }); binding.commentWriteRating4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { rating[0] = 4; binding.commentWriteRating1.setText("★"); binding.commentWriteRating2.setText("★"); binding.commentWriteRating3.setText("★"); binding.commentWriteRating4.setText("★"); binding.commentWriteRating5.setText("☆"); } }); binding.commentWriteRating5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { rating[0] = 5; binding.commentWriteRating1.setText("★"); binding.commentWriteRating2.setText("★"); binding.commentWriteRating3.setText("★"); binding.commentWriteRating4.setText("★"); binding.commentWriteRating5.setText("★"); } }); // Submit Comment binding.commentWritePost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(rating[0] == -1) { Toast myToast = Toast.makeText(getActivity(), "You must click a rating!", Toast.LENGTH_SHORT); myToast.show(); }else { Task<DocumentSnapshot> task = Student.getInstance().postEventComment(eventInfo, binding.commentContentWrite.getText().toString(), rating[0]); task.addOnSuccessListener( new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { requireActivity().runOnUiThread(() -> { Bundle bundle = new Bundle(); bundle.putInt("selectedEventIndex", getArguments().getInt("selectedEventIndex")); NavHostFragment.findNavController(EventStudentFragment.this).navigate(R.id.eventFragment, bundle); // TODO: add toast }); } }, 1000); } } ); task.addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // TODO: add toast } } ); } } }); // Comments loading LinearLayout commentsLayout = binding.comments; // TODO: Implement other event details.
package example.com.cmsandroidsimulation; public class EventStudentFragment extends Fragment { FragmentEventStudentBinding binding; @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) { binding = FragmentEventStudentBinding.inflate(inflater, container, false); return binding.getRoot(); } @SuppressLint("MissingInflatedId") @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Load Content from db int eventIndex = getArguments().getInt("selectedEventIndex"); Student.getInstance().getEvents().thenAccept((ArrayList<EventInfo> events) -> { try { afterFetchEventInfo(events.get(eventIndex)); } catch (Exception e) { Log.e("MASTER APP", e.toString()); } }); } private void afterFetchEventInfo(EventInfo eventInfo) { Log.i("MASTER APP", "RSVP INFO"); Log.i("MASTER APP", eventInfo.getAttendees().toString()); Log.i("MASTER APP", Student.getInstance().getEmail()); Log.i("MASTER APP", "dateFormat.format(eventInfo.getEventStartDateTime())"); DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy hh:mm:ss", Locale.CANADA); Log.i("MASTER APP", "dateFormat.format(eventInfo.getEventStartDateTime())"); Log.i("MASTER APP", eventInfo.getEventStartDateTime() +""); Log.i("MASTER APP", dateFormat.format(eventInfo.getEventStartDateTime())); binding.eventTitle.setText(eventInfo.getTitle()); binding.eventContent.setText(eventInfo.getDetails()); binding.eventAuthor.setText(eventInfo.getAuthor()); Log.i("MASTER APP", dateFormat.format(eventInfo.getEventStartDateTime())); binding.eventLocationAndTime.setText(dateFormat.format(eventInfo.getEventStartDateTime()) + " to " + dateFormat.format(eventInfo.getEventEndDateTime()) + " at " + eventInfo.getLocation()); final int[] registeredMembers = {eventInfo.getAttendees().size()}; int maxMembers = eventInfo.getMaxppl(); boolean full = registeredMembers[0] >= maxMembers; binding.eventMembers.setText("Registered: " + registeredMembers[0] + "/" + maxMembers); // Disable the comment section / RSVP clicking binding.eventWriteCommentWrapper.setVisibility(View.GONE); binding.eventRSVPed.setVisibility(View.GONE); binding.eventRSVP.setVisibility(View.VISIBLE); if (eventInfo.getAttendees().contains(Student.getInstance().getEmail())){ Log.i("MASTER APP", "RSVPED ALREADY"); binding.eventWriteCommentWrapper.setVisibility(View.VISIBLE); binding.eventRSVPed.setVisibility(View.VISIBLE); binding.eventRSVP.setVisibility(View.GONE); } if(full) binding.eventRSVP.setVisibility(View.GONE); // RSVP binding.eventRSVP.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { binding.eventWriteCommentWrapper.setVisibility(View.VISIBLE); binding.eventRSVPed.setVisibility(View.VISIBLE); binding.eventRSVP.setVisibility(View.GONE); registeredMembers[0]++; binding.eventMembers.setText("Registered: " + registeredMembers[0] + "/" + maxMembers); Student.getInstance().setEventHasRSVPd(eventInfo, true); } }); // Un-RSVP binding.eventRSVPed.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { binding.eventWriteCommentWrapper.setVisibility(View.GONE); binding.eventRSVPed.setVisibility(View.GONE); binding.eventRSVP.setVisibility(View.VISIBLE); registeredMembers[0]--; binding.eventMembers.setText("Registered: " + registeredMembers[0] + "/" + maxMembers); Student.getInstance().setEventHasRSVPd(eventInfo, false); } }); // Click rating and change rating final int[] rating = {-1}; binding.commentWriteRating1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { rating[0] = 1; binding.commentWriteRating1.setText("★"); binding.commentWriteRating2.setText("☆"); binding.commentWriteRating3.setText("☆"); binding.commentWriteRating4.setText("☆"); binding.commentWriteRating5.setText("☆"); } }); binding.commentWriteRating2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { rating[0] = 2; binding.commentWriteRating1.setText("★"); binding.commentWriteRating2.setText("★"); binding.commentWriteRating3.setText("☆"); binding.commentWriteRating4.setText("☆"); binding.commentWriteRating5.setText("☆"); } }); binding.commentWriteRating3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { rating[0] = 3; binding.commentWriteRating1.setText("★"); binding.commentWriteRating2.setText("★"); binding.commentWriteRating3.setText("★"); binding.commentWriteRating4.setText("☆"); binding.commentWriteRating5.setText("☆"); } }); binding.commentWriteRating4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { rating[0] = 4; binding.commentWriteRating1.setText("★"); binding.commentWriteRating2.setText("★"); binding.commentWriteRating3.setText("★"); binding.commentWriteRating4.setText("★"); binding.commentWriteRating5.setText("☆"); } }); binding.commentWriteRating5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { rating[0] = 5; binding.commentWriteRating1.setText("★"); binding.commentWriteRating2.setText("★"); binding.commentWriteRating3.setText("★"); binding.commentWriteRating4.setText("★"); binding.commentWriteRating5.setText("★"); } }); // Submit Comment binding.commentWritePost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(rating[0] == -1) { Toast myToast = Toast.makeText(getActivity(), "You must click a rating!", Toast.LENGTH_SHORT); myToast.show(); }else { Task<DocumentSnapshot> task = Student.getInstance().postEventComment(eventInfo, binding.commentContentWrite.getText().toString(), rating[0]); task.addOnSuccessListener( new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { requireActivity().runOnUiThread(() -> { Bundle bundle = new Bundle(); bundle.putInt("selectedEventIndex", getArguments().getInt("selectedEventIndex")); NavHostFragment.findNavController(EventStudentFragment.this).navigate(R.id.eventFragment, bundle); // TODO: add toast }); } }, 1000); } } ); task.addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // TODO: add toast } } ); } } }); // Comments loading LinearLayout commentsLayout = binding.comments; // TODO: Implement other event details.
for(EventComment eventComment: eventInfo.getComments()) {
0
2023-11-07 16:52:01+00:00
8k
ProjectBIGWHALE/bigwhale-api
src/main/java/com/whale/web/documents/DocumentsController.java
[ { "identifier": "CreateCertificateService", "path": "src/main/java/com/whale/web/documents/certificategenerator/service/CreateCertificateService.java", "snippet": "@Service\npublic class CreateCertificateService {\n\n\n private final EditSVGFiles createCerificateService;\n\n public CreateCertifica...
import com.whale.web.documents.certificategenerator.dto.CertificateRecordDto; import com.whale.web.documents.certificategenerator.service.CreateCertificateService; import com.whale.web.documents.certificategenerator.service.ProcessWorksheetService; import com.whale.web.documents.compressedfileconverter.CompactConverterService; import com.whale.web.documents.zipfilegenerator.ZipFileCompressorService; import com.whale.web.documents.imageconverter.service.ImageConverterService; import com.whale.web.documents.qrcodegenerator.dto.QRCodeEmailRecordDto; import com.whale.web.documents.qrcodegenerator.dto.QRCodeLinkRecordDto; import com.whale.web.documents.qrcodegenerator.dto.QRCodeWhatsappRecordDto; import com.whale.web.documents.qrcodegenerator.model.QRCodeEmailModel; import com.whale.web.documents.qrcodegenerator.model.QRCodeLinkModel; import com.whale.web.documents.qrcodegenerator.model.QRCodeWhatsappModel; import com.whale.web.documents.qrcodegenerator.service.QRCodeEmailService; import com.whale.web.documents.qrcodegenerator.service.QRCodeLinkService; import com.whale.web.documents.qrcodegenerator.service.QRCodeWhatsappService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.http.*; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import jakarta.validation.Valid; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import java.util.Objects; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;
3,950
package com.whale.web.documents; @RestController @RequestMapping(value = "api/v1/documents") @Tag(name = "API for documents resource palette") @CrossOrigin(origins = "*") public class DocumentsController {
package com.whale.web.documents; @RestController @RequestMapping(value = "api/v1/documents") @Tag(name = "API for documents resource palette") @CrossOrigin(origins = "*") public class DocumentsController {
private final CompactConverterService compactConverterService;
2
2023-11-08 22:41:22+00:00
8k
Mau38/SparePartsFTC
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/opmode/TrackingWheelForwardOffsetTuner.java
[ { "identifier": "SampleMecanumDrive", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/SampleMecanumDrive.java", "snippet": "@Config\npublic class SampleMecanumDrive extends MecanumDrive {\n public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(0, 0, 0);...
import com.acmerobotics.dashboard.FtcDashboard; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.dashboard.telemetry.MultipleTelemetry; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.util.Angle; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.util.MovingStatistics; import com.qualcomm.robotcore.util.RobotLog; import org.firstinspires.ftc.robotcore.external.Telemetry; import org.firstinspires.ftc.robotcore.internal.system.Misc; import org.firstinspires.ftc.teamcode.roadRunner.drive.SampleMecanumDrive; import org.firstinspires.ftc.teamcode.roadRunner.drive.StandardTrackingWheelLocalizer;
3,986
package org.firstinspires.ftc.teamcode.roadRunner.drive.opmode; /** * This routine determines the effective forward offset for the lateral tracking wheel. * The procedure executes a point turn at a given angle for a certain number of trials, * along with a specified delay in milliseconds. The purpose of this is to track the * change in the y position during the turn. The offset, or distance, of the lateral tracking * wheel from the center or rotation allows the wheel to spin during a point turn, leading * to an incorrect measurement for the y position. This creates an arc around around * the center of rotation with an arc length of change in y and a radius equal to the forward * offset. We can compute this offset by calculating (change in y position) / (change in heading) * which returns the radius if the angle (change in heading) is in radians. This is based * on the arc length formula of length = theta * radius. * * To run this routine, simply adjust the desired angle and specify the number of trials * and the desired delay. Then, run the procedure. Once it finishes, it will print the * average of all the calculated forward offsets derived from the calculation. This calculated * forward offset is then added onto the current forward offset to produce an overall estimate * for the forward offset. You can run this procedure as many times as necessary until a * satisfactory result is produced. */ @Config @Autonomous(group="drive") public class TrackingWheelForwardOffsetTuner extends LinearOpMode { public static double ANGLE = 180; // deg public static int NUM_TRIALS = 5; public static int DELAY = 1000; // ms @Override public void runOpMode() throws InterruptedException { Telemetry telemetry = new MultipleTelemetry(this.telemetry, FtcDashboard.getInstance().getTelemetry()); SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap);
package org.firstinspires.ftc.teamcode.roadRunner.drive.opmode; /** * This routine determines the effective forward offset for the lateral tracking wheel. * The procedure executes a point turn at a given angle for a certain number of trials, * along with a specified delay in milliseconds. The purpose of this is to track the * change in the y position during the turn. The offset, or distance, of the lateral tracking * wheel from the center or rotation allows the wheel to spin during a point turn, leading * to an incorrect measurement for the y position. This creates an arc around around * the center of rotation with an arc length of change in y and a radius equal to the forward * offset. We can compute this offset by calculating (change in y position) / (change in heading) * which returns the radius if the angle (change in heading) is in radians. This is based * on the arc length formula of length = theta * radius. * * To run this routine, simply adjust the desired angle and specify the number of trials * and the desired delay. Then, run the procedure. Once it finishes, it will print the * average of all the calculated forward offsets derived from the calculation. This calculated * forward offset is then added onto the current forward offset to produce an overall estimate * for the forward offset. You can run this procedure as many times as necessary until a * satisfactory result is produced. */ @Config @Autonomous(group="drive") public class TrackingWheelForwardOffsetTuner extends LinearOpMode { public static double ANGLE = 180; // deg public static int NUM_TRIALS = 5; public static int DELAY = 1000; // ms @Override public void runOpMode() throws InterruptedException { Telemetry telemetry = new MultipleTelemetry(this.telemetry, FtcDashboard.getInstance().getTelemetry()); SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap);
if (!(drive.getLocalizer() instanceof StandardTrackingWheelLocalizer)) {
1
2023-11-06 21:25:54+00:00
8k
project-BarryBarry/coffeeport
src/main/java/com/barrybarry/coffeeport/Main.java
[ { "identifier": "Config", "path": "src/main/java/com/barrybarry/coffeeport/constant/Config.java", "snippet": "@SuppressWarnings({\"FieldCanBeLocal\", \"unused\"})\npublic class Config {\n public static String veraVersion = \"3,8,6,7\";\n public static int httpPort = 16106;\n public static int h...
import com.barrybarry.coffeeport.constant.Config; import com.barrybarry.coffeeport.handler.TaskHandler; import com.barrybarry.coffeeport.router.VeraportRouter; import com.barrybarry.coffeeport.utils.SecurityUtil; import com.barrybarry.coffeeport.utils.SystemUtil; import com.linecorp.armeria.server.Server; import com.linecorp.armeria.server.ServerBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.KeyManagerFactory; import java.net.InetAddress; import java.net.InetSocketAddress; import java.security.KeyStore;
5,067
package com.barrybarry.coffeeport; public class Main { private static final Logger logger = LoggerFactory.getLogger(Main.class); public static void main(String[] args) {
package com.barrybarry.coffeeport; public class Main { private static final Logger logger = LoggerFactory.getLogger(Main.class); public static void main(String[] args) {
TaskHandler th = new TaskHandler();
1
2023-11-08 01:22:24+00:00
8k
celedev97/asa-server-manager
src/main/java/dev/cele/asa_sm/AsaSmApplication.java
[ { "identifier": "SpringApplicationContext", "path": "src/main/java/dev/cele/asa_sm/config/SpringApplicationContext.java", "snippet": "@Configuration\npublic class SpringApplicationContext implements ApplicationContextAware {\n private static ApplicationContext context;\n\n @Override\n public vo...
import com.formdev.flatlaf.FlatLaf; import com.formdev.flatlaf.IntelliJTheme; import dev.cele.asa_sm.config.SpringApplicationContext; import dev.cele.asa_sm.services.SettingsService; import dev.cele.asa_sm.services.SteamCMDService; import dev.cele.asa_sm.services.UpdateService; import dev.cele.asa_sm.ui.frames.MainFrame; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Lazy; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent;
5,756
package dev.cele.asa_sm; @SpringBootApplication @EnableFeignClients("dev.cele.asa_sm") @Slf4j @RequiredArgsConstructor public class AsaSmApplication implements CommandLineRunner { @Autowired @Lazy private ApplicationContext appContext; private final UpdateService updateService; private final SteamCMDService steamCMDService;
package dev.cele.asa_sm; @SpringBootApplication @EnableFeignClients("dev.cele.asa_sm") @Slf4j @RequiredArgsConstructor public class AsaSmApplication implements CommandLineRunner { @Autowired @Lazy private ApplicationContext appContext; private final UpdateService updateService; private final SteamCMDService steamCMDService;
private final SettingsService settingsService;
1
2023-11-07 19:36:49+00:00
8k
fredpena/barcamp2023
src/main/java/dev/fredpena/barcamp/views/MainLayout.java
[ { "identifier": "TenantContext", "path": "src/main/java/dev/fredpena/barcamp/config/TenantContext.java", "snippet": "public final class TenantContext {\n\n private TenantContext() {\n }\n\n private static final ThreadLocal<String> currentTenant = new ThreadLocal<>();\n private static final T...
import com.vaadin.flow.component.Component; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.applayout.AppLayout; import com.vaadin.flow.component.avatar.Avatar; import com.vaadin.flow.component.contextmenu.MenuItem; import com.vaadin.flow.component.html.*; import com.vaadin.flow.component.icon.Icon; import com.vaadin.flow.component.menubar.MenuBar; import com.vaadin.flow.router.BeforeEnterEvent; import com.vaadin.flow.router.BeforeEnterObserver; import com.vaadin.flow.router.RouterLink; import com.vaadin.flow.server.StreamResource; import com.vaadin.flow.server.auth.AccessAnnotationChecker; import com.vaadin.flow.theme.lumo.LumoUtility.*; import dev.fredpena.barcamp.config.TenantContext; import dev.fredpena.barcamp.data.tenant.entity.User; import dev.fredpena.barcamp.security.AuthenticatedUser; import dev.fredpena.barcamp.views.person.PersonView; import org.springframework.util.StringUtils; import org.vaadin.lineawesome.LineAwesomeIcon; import java.io.ByteArrayInputStream; import java.util.Optional;
4,647
package dev.fredpena.barcamp.views; /** * The main view is a top-level placeholder for other views. */ public class MainLayout extends AppLayout implements BeforeEnterObserver { /** * A simple navigation item component, based on ListItem element. */ public static class MenuItemInfo extends ListItem { private final Class<? extends Component> view; public MenuItemInfo(String menuTitle, Component icon, Class<? extends Component> view) { this.view = view; RouterLink link = new RouterLink(); // Use Lumo classnames for various styling link.addClassNames(Display.FLEX, Gap.XSMALL, Height.MEDIUM, AlignItems.CENTER, Padding.Horizontal.SMALL, TextColor.BODY); link.setRoute(view); Span text = new Span(menuTitle); // Use Lumo classnames for various styling text.addClassNames(FontWeight.MEDIUM, FontSize.MEDIUM, Whitespace.NOWRAP); if (icon != null) { link.add(icon); } link.add(text); add(link); } public Class<?> getView() { return view; } }
package dev.fredpena.barcamp.views; /** * The main view is a top-level placeholder for other views. */ public class MainLayout extends AppLayout implements BeforeEnterObserver { /** * A simple navigation item component, based on ListItem element. */ public static class MenuItemInfo extends ListItem { private final Class<? extends Component> view; public MenuItemInfo(String menuTitle, Component icon, Class<? extends Component> view) { this.view = view; RouterLink link = new RouterLink(); // Use Lumo classnames for various styling link.addClassNames(Display.FLEX, Gap.XSMALL, Height.MEDIUM, AlignItems.CENTER, Padding.Horizontal.SMALL, TextColor.BODY); link.setRoute(view); Span text = new Span(menuTitle); // Use Lumo classnames for various styling text.addClassNames(FontWeight.MEDIUM, FontSize.MEDIUM, Whitespace.NOWRAP); if (icon != null) { link.add(icon); } link.add(text); add(link); } public Class<?> getView() { return view; } }
private final transient AuthenticatedUser authenticatedUser;
2
2023-11-08 18:12:12+00:00
8k
1341191074/aibote4j
sdk-core/src/main/java/net/aibote/sdk/WinBot.java
[ { "identifier": "OCRResult", "path": "sdk-core/src/main/java/net/aibote/sdk/dto/OCRResult.java", "snippet": "public class OCRResult {\n public Point lt;\n public Point rt;\n public Point ld;\n public Point rd;\n public String word;\n public double rate;\n}" }, { "identifier": "...
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONObject; import lombok.Data; import lombok.EqualsAndHashCode; import net.aibote.sdk.dto.OCRResult; import net.aibote.sdk.dto.Point; import net.aibote.sdk.options.Mode; import net.aibote.sdk.options.Region; import net.aibote.sdk.options.SubColor; import net.aibote.utils.HttpClientUtils; import net.aibote.utils.ImageBase64Converter; import org.apache.commons.lang3.StringUtils; import java.util.*;
7,188
package net.aibote.sdk; @EqualsAndHashCode(callSuper = true) @Data public abstract class WinBot extends Aibote { /** * 查找窗口句柄 * * @param className 窗口类名 * @param windowName 窗口名 * @return String 成功返回窗口句柄,失败返回null */ public String findWindow(String className, String windowName) { return strCmd("findWindow", className, windowName); } /** * 查找窗口句柄数组, 以 “|” 分割 * * @param className 窗口类名 * @param windowName 窗口名 * @return String 成功返回窗口句柄,失败返回null */ public String findWindows(String className, String windowName) { return strCmd("findWindows", className, windowName); } /** * 查找窗口句柄 * * @param curHwnd 当前窗口句柄 * @param className 窗口类名 * @param windowName 窗口名 * @return String 成功返回窗口句柄,失败返回null */ public String findSubWindow(String curHwnd, String className, String windowName) { return strCmd("findSubWindow", curHwnd, className, windowName); } /** * 查找父窗口句柄 * * @param curHwnd 当前窗口句柄 * @return String 成功返回窗口句柄,失败返回null */ public String findParentWindow(String curHwnd) { return strCmd("findParentWindow", curHwnd); } /** * 查找桌面窗口句柄 * * @return 成功返回窗口句柄,失败返回null */ public String findDesktopWindow() { return strCmd("findDesktopWindow"); } /** * 获取窗口名称 * * @param hwnd 当前窗口句柄 * @return String 成功返回窗口句柄,失败返回null */ public String getWindowName(String hwnd) { return strCmd("getWindowName", hwnd); } /** * 显示/隐藏窗口 * * @param hwnd 当前窗口句柄 * @param isShow 是否显示 * @return boolean 成功返回true,失败返回false */ public boolean showWindow(String hwnd, boolean isShow) { return boolCmd("showWindow", hwnd, String.valueOf(isShow)); } /** * 显示/隐藏窗口 * * @param hwnd 当前窗口句柄 * @param isTop 是否置顶 * @return boolean 成功返回true,失败返回false */ public boolean setWindowTop(String hwnd, boolean isTop) { return boolCmd("setWindowTop", hwnd, String.valueOf(isTop)); } /** * 获取窗口位置。 用“|”分割 * * @param hwnd 当前窗口句柄 * @return 0|0|0|0 */ public String getWindowPos(String hwnd) { return strCmd("getWindowPos", hwnd); } /** * 设置窗口位置 * * @param hwnd 当前窗口句柄 * @param left 左上角横坐标 * @param top 左上角纵坐标 * @param width width 窗口宽度 * @param height height 窗口高度 * @return boolean 成功返回true 失败返回 false */ public boolean setWindowPos(String hwnd, int left, int top, int width, int height) { return boolCmd("setWindowPos", hwnd, Integer.toString(left), Integer.toString(top), Integer.toString(width), Integer.toString(height)); } /** * 移动鼠标 <br /> * 如果mode值为true且目标控件有单独的句柄,则需要通过getElementWindow获得元素句柄,指定elementHwnd的值(极少应用窗口由父窗口响应消息,则无需指定) * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作。 * @param elementHwnd 元素句柄 * @return boolean 总是返回true */ public boolean moveMouse(String hwnd, int x, int y, Mode mode, String elementHwnd) { return boolCmd("moveMouse", hwnd, Integer.toString(x), Integer.toString(y), mode.boolValueStr(), elementHwnd); } /** * 移动鼠标(相对坐标) * * @param hwnd 窗口句柄 * @param x 相对横坐标 * @param y 相对纵坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return boolean 总是返回true */ public boolean moveMouseRelative(String hwnd, int x, int y, Mode mode) { return boolCmd("moveMouseRelative", hwnd, Integer.toString(x), Integer.toString(y), mode.boolValueStr()); } /** * 滚动鼠标 * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param dwData 鼠标滚动次数,负数下滚鼠标,正数上滚鼠标 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return boolean 总是返回true */ public boolean rollMouse(String hwnd, int x, int y, int dwData, Mode mode) { return boolCmd("rollMouse", hwnd, Integer.toString(x), Integer.toString(y), Integer.toString(dwData), mode.boolValueStr()); } /** * 鼠标点击<br /> * 如果mode值为true且目标控件有单独的句柄,则需要通过getElementWindow获得元素句柄,指定elementHwnd的值(极少应用窗口由父窗口响应消息,则无需指定) * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param mouseType 单击左键:1 单击右键:2 按下左键:3 弹起左键:4 按下右键:5 弹起右键:6 双击左键:7 双击右键:8 * @param mode 操作模式,后台 true,前台 false。默认前台操作。 * @param elementHwnd 元素句柄 * @return boolean 总是返回true。 */ public boolean clickMouse(String hwnd, int x, int y, int mouseType, Mode mode, String elementHwnd) { return boolCmd("clickMouse", hwnd, Integer.toString(x), Integer.toString(y), Integer.toString(mouseType), mode.boolValueStr(), elementHwnd); } /** * 输入文本 * * @param txt 输入的文本 * @return boolean 总是返回true */ public boolean sendKeys(String txt) { return boolCmd("sendKeys", txt); } /** * 后台输入文本 * * @param hwnd 窗口句柄,如果目标控件有单独的句柄,需要通过getElementWindow获得句柄 * @param txt 输入的文本 * @return boolean 总是返回true */ public boolean sendKeysByHwnd(String hwnd, String txt) { return boolCmd("sendKeysByHwnd", hwnd, txt); } /** * 输入虚拟键值(VK) * * @param vk VK键值,例如:回车对应 VK键值 13 * @param keyState 按下弹起:1 按下:2 弹起:3 * @return boolean 总是返回true */ public boolean sendVk(int vk, int keyState) { return boolCmd("sendVk", Integer.toString(vk), Integer.toString(keyState)); } /** * 后台输入虚拟键值(VK) * * @param hwnd 窗口句柄,如果目标控件有单独的句柄,需要通过getElementWindow获得句柄 * @param vk VK键值,例如:回车对应 VK键值 13 * @param keyState 按下弹起:1 按下:2 弹起:3 * @return boolean 总是返回true */ public boolean sendVkByHwnd(String hwnd, int vk, int keyState) { return boolCmd("sendVkByHwnd", hwnd, Integer.toString(vk), Integer.toString(keyState)); } /** * 截图保存。threshold默认保存原图。 * * @param hwnd 窗口句柄 * @param savePath 保存的位置 * @param region 区域 * @param thresholdType hresholdType算法类型。<br /> * 0 THRESH_BINARY算法,当前点值大于阈值thresh时,取最大值maxva,否则设置为0 * 1 THRESH_BINARY_INV算法,当前点值大于阈值thresh时,设置为0,否则设置为最大值maxva * 2 THRESH_TOZERO算法,当前点值大于阈值thresh时,不改变,否则设置为0 * 3 THRESH_TOZERO_INV算法,当前点值大于阈值thresh时,设置为0,否则不改变 * 4 THRESH_TRUNC算法,当前点值大于阈值thresh时,设置为阈值thresh,否则不改变 * 5 ADAPTIVE_THRESH_MEAN_C算法,自适应阈值 * 6 ADAPTIVE_THRESH_GAUSSIAN_C算法,自适应阈值 * @param thresh 阈值。 thresh和maxval同为255时灰度处理 * @param maxval 最大值。 thresh和maxval同为255时灰度处理 * @return boolean */ public boolean saveScreenshot(String hwnd, String savePath, Region region, int thresholdType, int thresh, int maxval) { if (thresholdType == 5 || thresholdType == 6) { thresh = 127; maxval = 255; } return boolCmd("saveScreenshot", hwnd, savePath, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Integer.toString(thresholdType), Integer.toString(thresh), Integer.toString(maxval)); } /** * 获取指定坐标点的色值 * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return 成功返回#开头的颜色值,失败返回null */ public String getColor(String hwnd, int x, int y, boolean mode) { return strCmd("getColor", hwnd, Integer.toString(x), Integer.toString(y), Boolean.toString(mode)); } /** * @param hwndOrBigImagePath 窗口句柄或者图片路径 * @param smallImagePath 小图片路径,多张小图查找应当用"|"分开小图路径 * @param region 区域 * @param sim 图片相似度 0.0-1.0,sim默认0.95 * @param thresholdType thresholdType算法类型:<br /> * 0 THRESH_BINARY算法,当前点值大于阈值thresh时,取最大值maxva,否则设置为0 * 1 THRESH_BINARY_INV算法,当前点值大于阈值thresh时,设置为0,否则设置为最大值maxva * 2 THRESH_TOZERO算法,当前点值大于阈值thresh时,不改变,否则设置为0 * 3 THRESH_TOZERO_INV算法,当前点值大于阈值thresh时,设置为0,否则不改变 * 4 THRESH_TRUNC算法,当前点值大于阈值thresh时,设置为阈值thresh,否则不改变 * 5 ADAPTIVE_THRESH_MEAN_C算法,自适应阈值 * 6 ADAPTIVE_THRESH_GAUSSIAN_C算法,自适应阈值 * @param thresh 阈值。threshold默认保存原图。thresh和maxval同为255时灰度处理 * @param maxval 最大值。threshold默认保存原图。thresh和maxval同为255时灰度处理 * @param multi 找图数量,默认为1 找单个图片坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作。hwndOrBigImagePath为图片文件,此参数无效 * @return 成功返回 单坐标点[{x:number, y:number}],多坐标点[{x1:number, y1:number}, {x2:number, y2:number}...] 失败返回null */ public String findImages(String hwndOrBigImagePath, String smallImagePath, Region region, float sim, int thresholdType, int thresh, int maxval, int multi, Mode mode) { if (thresholdType == 5 || thresholdType == 6) { thresh = 127; maxval = 255; } String strData = null; if (hwndOrBigImagePath.toString().indexOf(".") == -1) {//在窗口上找图 return strDelayCmd("findImage", hwndOrBigImagePath, smallImagePath, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), Integer.toString(thresholdType), Integer.toString(thresh), Integer.toString(maxval), Integer.toString(multi), mode.boolValueStr()); } else {//在文件上找图 return this.strDelayCmd("findImageByFile", hwndOrBigImagePath, smallImagePath, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), Integer.toString(thresholdType), Integer.toString(thresh), Integer.toString(maxval), Integer.toString(multi), mode.boolValueStr()); } } /** * 找动态图 * * @param hwnd 窗口句柄 * @param frameRate 前后两张图相隔的时间,单位毫秒 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return 成功返回 单坐标点[{x:number, y:number}],多坐标点[{x1:number, y1:number}, {x2:number, y2:number}...] 失败返回null */ public String findAnimation(String hwnd, int frameRate, Region region, Mode mode) { return strDelayCmd("findAnimation", hwnd, Integer.toString(frameRate), Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), mode.boolValueStr()); } /** * 查找指定色值的坐标点 * * @param hwnd 窗口句柄 * @param strMainColor 颜色字符串,必须以 # 开头,例如:#008577; * @param subColors 辅助定位的其他颜色; * @param region 在指定区域内找色,默认全屏; * @param sim 相似度。0.0-1.0,sim默认为1 * @param mode 后台 true,前台 false。默认前台操作。 * @return String 成功返回 x|y 失败返回null */
package net.aibote.sdk; @EqualsAndHashCode(callSuper = true) @Data public abstract class WinBot extends Aibote { /** * 查找窗口句柄 * * @param className 窗口类名 * @param windowName 窗口名 * @return String 成功返回窗口句柄,失败返回null */ public String findWindow(String className, String windowName) { return strCmd("findWindow", className, windowName); } /** * 查找窗口句柄数组, 以 “|” 分割 * * @param className 窗口类名 * @param windowName 窗口名 * @return String 成功返回窗口句柄,失败返回null */ public String findWindows(String className, String windowName) { return strCmd("findWindows", className, windowName); } /** * 查找窗口句柄 * * @param curHwnd 当前窗口句柄 * @param className 窗口类名 * @param windowName 窗口名 * @return String 成功返回窗口句柄,失败返回null */ public String findSubWindow(String curHwnd, String className, String windowName) { return strCmd("findSubWindow", curHwnd, className, windowName); } /** * 查找父窗口句柄 * * @param curHwnd 当前窗口句柄 * @return String 成功返回窗口句柄,失败返回null */ public String findParentWindow(String curHwnd) { return strCmd("findParentWindow", curHwnd); } /** * 查找桌面窗口句柄 * * @return 成功返回窗口句柄,失败返回null */ public String findDesktopWindow() { return strCmd("findDesktopWindow"); } /** * 获取窗口名称 * * @param hwnd 当前窗口句柄 * @return String 成功返回窗口句柄,失败返回null */ public String getWindowName(String hwnd) { return strCmd("getWindowName", hwnd); } /** * 显示/隐藏窗口 * * @param hwnd 当前窗口句柄 * @param isShow 是否显示 * @return boolean 成功返回true,失败返回false */ public boolean showWindow(String hwnd, boolean isShow) { return boolCmd("showWindow", hwnd, String.valueOf(isShow)); } /** * 显示/隐藏窗口 * * @param hwnd 当前窗口句柄 * @param isTop 是否置顶 * @return boolean 成功返回true,失败返回false */ public boolean setWindowTop(String hwnd, boolean isTop) { return boolCmd("setWindowTop", hwnd, String.valueOf(isTop)); } /** * 获取窗口位置。 用“|”分割 * * @param hwnd 当前窗口句柄 * @return 0|0|0|0 */ public String getWindowPos(String hwnd) { return strCmd("getWindowPos", hwnd); } /** * 设置窗口位置 * * @param hwnd 当前窗口句柄 * @param left 左上角横坐标 * @param top 左上角纵坐标 * @param width width 窗口宽度 * @param height height 窗口高度 * @return boolean 成功返回true 失败返回 false */ public boolean setWindowPos(String hwnd, int left, int top, int width, int height) { return boolCmd("setWindowPos", hwnd, Integer.toString(left), Integer.toString(top), Integer.toString(width), Integer.toString(height)); } /** * 移动鼠标 <br /> * 如果mode值为true且目标控件有单独的句柄,则需要通过getElementWindow获得元素句柄,指定elementHwnd的值(极少应用窗口由父窗口响应消息,则无需指定) * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作。 * @param elementHwnd 元素句柄 * @return boolean 总是返回true */ public boolean moveMouse(String hwnd, int x, int y, Mode mode, String elementHwnd) { return boolCmd("moveMouse", hwnd, Integer.toString(x), Integer.toString(y), mode.boolValueStr(), elementHwnd); } /** * 移动鼠标(相对坐标) * * @param hwnd 窗口句柄 * @param x 相对横坐标 * @param y 相对纵坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return boolean 总是返回true */ public boolean moveMouseRelative(String hwnd, int x, int y, Mode mode) { return boolCmd("moveMouseRelative", hwnd, Integer.toString(x), Integer.toString(y), mode.boolValueStr()); } /** * 滚动鼠标 * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param dwData 鼠标滚动次数,负数下滚鼠标,正数上滚鼠标 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return boolean 总是返回true */ public boolean rollMouse(String hwnd, int x, int y, int dwData, Mode mode) { return boolCmd("rollMouse", hwnd, Integer.toString(x), Integer.toString(y), Integer.toString(dwData), mode.boolValueStr()); } /** * 鼠标点击<br /> * 如果mode值为true且目标控件有单独的句柄,则需要通过getElementWindow获得元素句柄,指定elementHwnd的值(极少应用窗口由父窗口响应消息,则无需指定) * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param mouseType 单击左键:1 单击右键:2 按下左键:3 弹起左键:4 按下右键:5 弹起右键:6 双击左键:7 双击右键:8 * @param mode 操作模式,后台 true,前台 false。默认前台操作。 * @param elementHwnd 元素句柄 * @return boolean 总是返回true。 */ public boolean clickMouse(String hwnd, int x, int y, int mouseType, Mode mode, String elementHwnd) { return boolCmd("clickMouse", hwnd, Integer.toString(x), Integer.toString(y), Integer.toString(mouseType), mode.boolValueStr(), elementHwnd); } /** * 输入文本 * * @param txt 输入的文本 * @return boolean 总是返回true */ public boolean sendKeys(String txt) { return boolCmd("sendKeys", txt); } /** * 后台输入文本 * * @param hwnd 窗口句柄,如果目标控件有单独的句柄,需要通过getElementWindow获得句柄 * @param txt 输入的文本 * @return boolean 总是返回true */ public boolean sendKeysByHwnd(String hwnd, String txt) { return boolCmd("sendKeysByHwnd", hwnd, txt); } /** * 输入虚拟键值(VK) * * @param vk VK键值,例如:回车对应 VK键值 13 * @param keyState 按下弹起:1 按下:2 弹起:3 * @return boolean 总是返回true */ public boolean sendVk(int vk, int keyState) { return boolCmd("sendVk", Integer.toString(vk), Integer.toString(keyState)); } /** * 后台输入虚拟键值(VK) * * @param hwnd 窗口句柄,如果目标控件有单独的句柄,需要通过getElementWindow获得句柄 * @param vk VK键值,例如:回车对应 VK键值 13 * @param keyState 按下弹起:1 按下:2 弹起:3 * @return boolean 总是返回true */ public boolean sendVkByHwnd(String hwnd, int vk, int keyState) { return boolCmd("sendVkByHwnd", hwnd, Integer.toString(vk), Integer.toString(keyState)); } /** * 截图保存。threshold默认保存原图。 * * @param hwnd 窗口句柄 * @param savePath 保存的位置 * @param region 区域 * @param thresholdType hresholdType算法类型。<br /> * 0 THRESH_BINARY算法,当前点值大于阈值thresh时,取最大值maxva,否则设置为0 * 1 THRESH_BINARY_INV算法,当前点值大于阈值thresh时,设置为0,否则设置为最大值maxva * 2 THRESH_TOZERO算法,当前点值大于阈值thresh时,不改变,否则设置为0 * 3 THRESH_TOZERO_INV算法,当前点值大于阈值thresh时,设置为0,否则不改变 * 4 THRESH_TRUNC算法,当前点值大于阈值thresh时,设置为阈值thresh,否则不改变 * 5 ADAPTIVE_THRESH_MEAN_C算法,自适应阈值 * 6 ADAPTIVE_THRESH_GAUSSIAN_C算法,自适应阈值 * @param thresh 阈值。 thresh和maxval同为255时灰度处理 * @param maxval 最大值。 thresh和maxval同为255时灰度处理 * @return boolean */ public boolean saveScreenshot(String hwnd, String savePath, Region region, int thresholdType, int thresh, int maxval) { if (thresholdType == 5 || thresholdType == 6) { thresh = 127; maxval = 255; } return boolCmd("saveScreenshot", hwnd, savePath, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Integer.toString(thresholdType), Integer.toString(thresh), Integer.toString(maxval)); } /** * 获取指定坐标点的色值 * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return 成功返回#开头的颜色值,失败返回null */ public String getColor(String hwnd, int x, int y, boolean mode) { return strCmd("getColor", hwnd, Integer.toString(x), Integer.toString(y), Boolean.toString(mode)); } /** * @param hwndOrBigImagePath 窗口句柄或者图片路径 * @param smallImagePath 小图片路径,多张小图查找应当用"|"分开小图路径 * @param region 区域 * @param sim 图片相似度 0.0-1.0,sim默认0.95 * @param thresholdType thresholdType算法类型:<br /> * 0 THRESH_BINARY算法,当前点值大于阈值thresh时,取最大值maxva,否则设置为0 * 1 THRESH_BINARY_INV算法,当前点值大于阈值thresh时,设置为0,否则设置为最大值maxva * 2 THRESH_TOZERO算法,当前点值大于阈值thresh时,不改变,否则设置为0 * 3 THRESH_TOZERO_INV算法,当前点值大于阈值thresh时,设置为0,否则不改变 * 4 THRESH_TRUNC算法,当前点值大于阈值thresh时,设置为阈值thresh,否则不改变 * 5 ADAPTIVE_THRESH_MEAN_C算法,自适应阈值 * 6 ADAPTIVE_THRESH_GAUSSIAN_C算法,自适应阈值 * @param thresh 阈值。threshold默认保存原图。thresh和maxval同为255时灰度处理 * @param maxval 最大值。threshold默认保存原图。thresh和maxval同为255时灰度处理 * @param multi 找图数量,默认为1 找单个图片坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作。hwndOrBigImagePath为图片文件,此参数无效 * @return 成功返回 单坐标点[{x:number, y:number}],多坐标点[{x1:number, y1:number}, {x2:number, y2:number}...] 失败返回null */ public String findImages(String hwndOrBigImagePath, String smallImagePath, Region region, float sim, int thresholdType, int thresh, int maxval, int multi, Mode mode) { if (thresholdType == 5 || thresholdType == 6) { thresh = 127; maxval = 255; } String strData = null; if (hwndOrBigImagePath.toString().indexOf(".") == -1) {//在窗口上找图 return strDelayCmd("findImage", hwndOrBigImagePath, smallImagePath, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), Integer.toString(thresholdType), Integer.toString(thresh), Integer.toString(maxval), Integer.toString(multi), mode.boolValueStr()); } else {//在文件上找图 return this.strDelayCmd("findImageByFile", hwndOrBigImagePath, smallImagePath, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), Integer.toString(thresholdType), Integer.toString(thresh), Integer.toString(maxval), Integer.toString(multi), mode.boolValueStr()); } } /** * 找动态图 * * @param hwnd 窗口句柄 * @param frameRate 前后两张图相隔的时间,单位毫秒 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return 成功返回 单坐标点[{x:number, y:number}],多坐标点[{x1:number, y1:number}, {x2:number, y2:number}...] 失败返回null */ public String findAnimation(String hwnd, int frameRate, Region region, Mode mode) { return strDelayCmd("findAnimation", hwnd, Integer.toString(frameRate), Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), mode.boolValueStr()); } /** * 查找指定色值的坐标点 * * @param hwnd 窗口句柄 * @param strMainColor 颜色字符串,必须以 # 开头,例如:#008577; * @param subColors 辅助定位的其他颜色; * @param region 在指定区域内找色,默认全屏; * @param sim 相似度。0.0-1.0,sim默认为1 * @param mode 后台 true,前台 false。默认前台操作。 * @return String 成功返回 x|y 失败返回null */
public String findColor(String hwnd, String strMainColor, SubColor[] subColors, Region region, float sim, Mode mode) {
4
2023-11-08 14:31:58+00:00
8k
wuyu-wy/mgzm_volunteer
volunteer/src/main/java/com/blbd/volunteer/webSocket/WebSocketServer.java
[ { "identifier": "ChatFriendListEntity", "path": "volunteer/src/main/java/com/blbd/volunteer/dao/entity/ChatFriendListEntity.java", "snippet": "@Data\npublic class ChatFriendListEntity implements Serializable {\n /**\n * 聊天列表主键\n */\n private Integer listId;\n\n /**\n * 聊天主表id\n ...
import com.alibaba.fastjson.JSON; import com.blbd.volunteer.dao.entity.ChatFriendListEntity; import com.blbd.volunteer.dao.entity.ChatMsgEntity; import com.blbd.volunteer.service.ChatFriendListService; import com.blbd.volunteer.service.ChatMsgService; import com.blbd.volunteer.utils.ResponseEntity; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.support.ScheduledMethodRunnable; import org.springframework.stereotype.Component; import org.springframework.web.socket.TextMessage; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
4,124
package com.blbd.volunteer.webSocket; // @ServerEndpoint注解类似于Controller层的 @RequestMapping注解 // 此处websocket服务地址例如:http://127.0.0.1:8080/websocket/1,地址中1为userId,使用@PathParam("userId")提取 @ServerEndpoint(value = "/websocket/{userId}") @Component public class WebSocketServer { /** * 定义静态,然后给类的静态service注入 */ private static ChatMsgService chatMsgService; private static ChatFriendListService chatFriendListService; private static WebSocketUtils webSocketUtils; @Autowired public void setChatFriendListService(ChatFriendListService chatFriendListService) { WebSocketServer.chatFriendListService = chatFriendListService; } @Autowired public void setChatMsgService(ChatMsgService chatMsgService) { WebSocketServer.chatMsgService = chatMsgService; } @Autowired public void setWebSocketUtils(WebSocketUtils webSocketUtils) { WebSocketServer.webSocketUtils = webSocketUtils; } private static Logger log = LoggerFactory.getLogger(WebSocketServer.class); /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/ private static int onlineCount = 0; /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/ private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>(); /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/ private Session session; /**接收userId*/ private String userId=""; /** * 连接建立成功调用的方法 * */ @OnOpen public void onOpen(Session session,@PathParam("userId") String userId) { this.session = session; this.userId=userId; //判断用户集合中是否存在当前用户 if(webSocketMap.containsKey(userId)){ //有则先删除已有用户,再添加 webSocketMap.remove(userId); //加入set中 webSocketMap.put(userId,this); }else{ //加入set中 webSocketMap.put(userId,this); //在线数加1 addOnlineCount(); } webSocketUtils.userOnline(userId); log.info("用户连接: "+userId+",当前在线人数为: " + getOnlineCount()); sendServerMessage("连接成功"); } /** * 连接关闭执行 */ @OnClose public void onClose() { webSocketUtils.userOffline(userId); log.error("用户:" + userId + " 因断开WebSOcket连接下线"); if(webSocketMap.containsKey(userId)){ //将当前用户在集合中删除 webSocketMap.remove(userId); //从set中删除 subOnlineCount(); } log.info("用户【"+userId+"】退出: 当前在线人数为: " + getOnlineCount()); } /** * 收到客户端String消息时执行 * * @param message 客户端发送过来的消息*/ @OnMessage public void onMessage(String message, Session session) { log.info("当前用户: "+userId+",报文: "+message); if(StringUtils.isNotBlank(message)){ try { //传送给对应userId用户的websocket, 如果userId不为空 并且 webSocketMap种包含userId 才会发送消息 if(StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)){ //处理用户发来的消息 handleMessage(session, new TextMessage(message)); }else{ //否则不在这个服务器上 log.error("请求的userId:"+userId+" 不在该服务器上"); } }catch (Exception e){ e.printStackTrace(); } } } /** * 收到客户端二进制流消息时执行 * * @param messages 客户端发送过来的消息*/ @OnMessage public void onMessage(byte[] messages, Session session) { String messageString; try { messageString = new String(messages,"utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } log.info("当前用户二进制消息: "+userId+",报文: "+ messageString); //返回信息 if(StringUtils.isNotBlank(messageString)){ try { //传送给对应userId用户的websocket, 如果userId不为空 并且 webSocketMap种包含userId 才会发送消息 if(StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)){ //处理用户发来的消息 handleMessage(session, new TextMessage(messageString)); }else{ //否则不在这个服务器上 log.error("请求的userId:"+userId+" 不在该服务器上"); } }catch (Exception e){ e.printStackTrace(); } } } /** * 链接异常时执行 * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("用户错误:"+this.userId+",原因:"+error.getMessage()); webSocketUtils.userOffline(userId); log.error("用户:" + userId + " 因错误强制下线"); error.printStackTrace(); } /** * 处理信息 */ public void handleMessage(Session session, TextMessage message) throws Exception { log.warn("=========== Received message: {}", message.getPayload()); //承接客户端message ChatMsgEntity chatMsgEntity = JSON.parseObject(message.getPayload(), ChatMsgEntity.class); if (StringUtils.isBlank(chatMsgEntity.getSenderId())) { throw new Exception("用户ID不能为空"); } //根据消息类型分别处理 if (chatMsgEntity.getMsgType() == SocketConstants.MsgType.HEART_BEAT) { // 心跳消息 sendServerMessage("pong"); } else if (chatMsgEntity.getMsgType() == SocketConstants.MsgType.ONLINE) { log.info("登录消息,用户:" + chatMsgEntity.getSenderId() + "上线"); //调用工具类中用户上线方法
package com.blbd.volunteer.webSocket; // @ServerEndpoint注解类似于Controller层的 @RequestMapping注解 // 此处websocket服务地址例如:http://127.0.0.1:8080/websocket/1,地址中1为userId,使用@PathParam("userId")提取 @ServerEndpoint(value = "/websocket/{userId}") @Component public class WebSocketServer { /** * 定义静态,然后给类的静态service注入 */ private static ChatMsgService chatMsgService; private static ChatFriendListService chatFriendListService; private static WebSocketUtils webSocketUtils; @Autowired public void setChatFriendListService(ChatFriendListService chatFriendListService) { WebSocketServer.chatFriendListService = chatFriendListService; } @Autowired public void setChatMsgService(ChatMsgService chatMsgService) { WebSocketServer.chatMsgService = chatMsgService; } @Autowired public void setWebSocketUtils(WebSocketUtils webSocketUtils) { WebSocketServer.webSocketUtils = webSocketUtils; } private static Logger log = LoggerFactory.getLogger(WebSocketServer.class); /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/ private static int onlineCount = 0; /**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/ private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>(); /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/ private Session session; /**接收userId*/ private String userId=""; /** * 连接建立成功调用的方法 * */ @OnOpen public void onOpen(Session session,@PathParam("userId") String userId) { this.session = session; this.userId=userId; //判断用户集合中是否存在当前用户 if(webSocketMap.containsKey(userId)){ //有则先删除已有用户,再添加 webSocketMap.remove(userId); //加入set中 webSocketMap.put(userId,this); }else{ //加入set中 webSocketMap.put(userId,this); //在线数加1 addOnlineCount(); } webSocketUtils.userOnline(userId); log.info("用户连接: "+userId+",当前在线人数为: " + getOnlineCount()); sendServerMessage("连接成功"); } /** * 连接关闭执行 */ @OnClose public void onClose() { webSocketUtils.userOffline(userId); log.error("用户:" + userId + " 因断开WebSOcket连接下线"); if(webSocketMap.containsKey(userId)){ //将当前用户在集合中删除 webSocketMap.remove(userId); //从set中删除 subOnlineCount(); } log.info("用户【"+userId+"】退出: 当前在线人数为: " + getOnlineCount()); } /** * 收到客户端String消息时执行 * * @param message 客户端发送过来的消息*/ @OnMessage public void onMessage(String message, Session session) { log.info("当前用户: "+userId+",报文: "+message); if(StringUtils.isNotBlank(message)){ try { //传送给对应userId用户的websocket, 如果userId不为空 并且 webSocketMap种包含userId 才会发送消息 if(StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)){ //处理用户发来的消息 handleMessage(session, new TextMessage(message)); }else{ //否则不在这个服务器上 log.error("请求的userId:"+userId+" 不在该服务器上"); } }catch (Exception e){ e.printStackTrace(); } } } /** * 收到客户端二进制流消息时执行 * * @param messages 客户端发送过来的消息*/ @OnMessage public void onMessage(byte[] messages, Session session) { String messageString; try { messageString = new String(messages,"utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } log.info("当前用户二进制消息: "+userId+",报文: "+ messageString); //返回信息 if(StringUtils.isNotBlank(messageString)){ try { //传送给对应userId用户的websocket, 如果userId不为空 并且 webSocketMap种包含userId 才会发送消息 if(StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)){ //处理用户发来的消息 handleMessage(session, new TextMessage(messageString)); }else{ //否则不在这个服务器上 log.error("请求的userId:"+userId+" 不在该服务器上"); } }catch (Exception e){ e.printStackTrace(); } } } /** * 链接异常时执行 * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("用户错误:"+this.userId+",原因:"+error.getMessage()); webSocketUtils.userOffline(userId); log.error("用户:" + userId + " 因错误强制下线"); error.printStackTrace(); } /** * 处理信息 */ public void handleMessage(Session session, TextMessage message) throws Exception { log.warn("=========== Received message: {}", message.getPayload()); //承接客户端message ChatMsgEntity chatMsgEntity = JSON.parseObject(message.getPayload(), ChatMsgEntity.class); if (StringUtils.isBlank(chatMsgEntity.getSenderId())) { throw new Exception("用户ID不能为空"); } //根据消息类型分别处理 if (chatMsgEntity.getMsgType() == SocketConstants.MsgType.HEART_BEAT) { // 心跳消息 sendServerMessage("pong"); } else if (chatMsgEntity.getMsgType() == SocketConstants.MsgType.ONLINE) { log.info("登录消息,用户:" + chatMsgEntity.getSenderId() + "上线"); //调用工具类中用户上线方法
ResponseEntity responseEntity = webSocketUtils.userOnline(chatMsgEntity.getSenderId());
4
2023-11-02 05:55:45+00:00
8k
SeanPesce/AWS-IoT-Recon
src/main/java/com/seanpesce/aws/iot/AwsIotRecon.java
[ { "identifier": "AwsIotConstants", "path": "src/main/java/com/seanpesce/aws/iot/AwsIotConstants.java", "snippet": "public class AwsIotConstants {\n\n public static final String PROJECT_TITLE = \"[AWS IoT Core Enumeration Tool by Sean Pesce]\";\n\n public static final String ACTION_MQTT_DUMP = \"mq...
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.security.cert.CertificateException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.ArrayList; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.function.Consumer; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import com.seanpesce.aws.iot.AwsIotConstants; import com.seanpesce.http.MtlsHttpClient; import com.seanpesce.mqtt.MqttScript; import com.seanpesce.regex.PatternWithNamedGroups; import com.seanpesce.Util; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import software.amazon.awssdk.crt.auth.credentials.Credentials; import software.amazon.awssdk.crt.auth.credentials.X509CredentialsProvider; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.io.ClientTlsContext; import software.amazon.awssdk.crt.io.TlsContextOptions; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.mqtt.MqttMessage; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.crt.mqtt5.Mqtt5Client; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder;
6,748
// Author: Sean Pesce // // References: // https://aws.github.io/aws-iot-device-sdk-java-v2/ // https://docs.aws.amazon.com/iot/latest/developerguide // https://github.com/aws/aws-iot-device-sdk-java-v2/blob/main/samples/ // https://explore.skillbuilder.aws/learn/course/external/view/elearning/5667/deep-dive-into-aws-iot-authentication-and-authorization // // @TODO: // - Re-architect this tool to be more object-oriented (e.g., fewer static/global variables) // - Use CountDownLatch(count) in subscription message handlers for improved reliability package com.seanpesce.aws.iot; // import software.amazon.awssdk.services.iotdataplane.IotDataPlaneClient; public class AwsIotRecon { // MQTT topics to subscribe to (if empty, defaults to "#" - all topics) public static ArrayList<String> topicSubcriptions = new ArrayList<String>(); // Regular expressions with named capture groups for harvesting fields from MQTT topics
// Author: Sean Pesce // // References: // https://aws.github.io/aws-iot-device-sdk-java-v2/ // https://docs.aws.amazon.com/iot/latest/developerguide // https://github.com/aws/aws-iot-device-sdk-java-v2/blob/main/samples/ // https://explore.skillbuilder.aws/learn/course/external/view/elearning/5667/deep-dive-into-aws-iot-authentication-and-authorization // // @TODO: // - Re-architect this tool to be more object-oriented (e.g., fewer static/global variables) // - Use CountDownLatch(count) in subscription message handlers for improved reliability package com.seanpesce.aws.iot; // import software.amazon.awssdk.services.iotdataplane.IotDataPlaneClient; public class AwsIotRecon { // MQTT topics to subscribe to (if empty, defaults to "#" - all topics) public static ArrayList<String> topicSubcriptions = new ArrayList<String>(); // Regular expressions with named capture groups for harvesting fields from MQTT topics
public static ArrayList<PatternWithNamedGroups> topicsRegex = new ArrayList<PatternWithNamedGroups>(Arrays.asList(AwsIotConstants.RESERVED_TOPICS_REGEX));
3
2023-11-06 23:10:21+00:00
8k
baguchan/BetterWithAquatic
src/main/java/baguchan/better_with_aquatic/entity/EntityDrowned.java
[ { "identifier": "ISwiming", "path": "src/main/java/baguchan/better_with_aquatic/api/ISwiming.java", "snippet": "public interface ISwiming {\n\tvoid setSwimming(boolean swiming);\n\n\tboolean isSwimming();\n\n\tfloat getSwimAmount(float p_20999_);\n}" }, { "identifier": "BetterSwimWalkPathFinder"...
import baguchan.better_ai.api.IPathGetter; import baguchan.better_ai.util.BlockPath; import baguchan.better_with_aquatic.api.ISwiming; import baguchan.better_with_aquatic.entity.path.BetterSwimWalkPathFinder; import baguchan.better_with_aquatic.util.MathUtil; import net.minecraft.core.entity.Entity; import net.minecraft.core.entity.monster.EntityZombie; import net.minecraft.core.entity.player.EntityPlayer; import net.minecraft.core.util.helper.MathHelper; import net.minecraft.core.util.phys.Vec3d; import net.minecraft.core.world.World;
3,832
float distanceToEntity = this.entityToAttack.distanceTo(this); if (this.canEntityBeSeen(this.entityToAttack)) { this.attackEntity(this.entityToAttack, distanceToEntity); } else { this.attackBlockedEntity(this.entityToAttack, distanceToEntity); } } if (!(this.hasAttacked || this.entityToAttack == null || this.pathToEntity != null && this.random.nextInt(20) != 0)) { this.pathToEntity = this.world.getPathToEntity(this, this.entityToAttack, sightRadius); } else if (!this.hasAttacked && this.closestFireflyEntity == null && (this.pathToEntity == null && this.random.nextInt(80) == 0 || this.random.nextInt(80) == 0)) { this.roamRandomPath(); } this.xRot = 0.0f; if (this.pathToEntity == null || this.random.nextInt(100) == 0) { this.defaultPlayerActionState(); this.pathToEntity = null; return; } Vec3d coordsForNextPath = this.pathToEntity.getPos(this); double d = this.bbWidth * 2.0f; double d2 = this.bbHeight * 2.0f; while (coordsForNextPath != null && coordsForNextPath.squareDistanceTo(this.x, this.y, this.z) < d * d + d2 * d2) { this.pathToEntity.next(); if (this.pathToEntity.isDone()) { this.closestFireflyEntity = null; coordsForNextPath = null; this.pathToEntity = null; continue; } coordsForNextPath = this.pathToEntity.getPos(this); } this.isJumping = false; if (coordsForNextPath != null) { float f3; double x1 = coordsForNextPath.xCoord - this.x; double z1 = coordsForNextPath.zCoord - this.z; double y1 = coordsForNextPath.yCoord - this.y; float f2 = (float) (Math.atan2(z1, x1) * 180.0 / 3.1415927410125732) - 90.0f; this.moveForward = this.moveSpeed * 0.15F; for (f3 = f2 - this.yRot; f3 < -180.0f; f3 += 360.0f) { } while (f3 >= 180.0f) { f3 -= 360.0f; } if (f3 > 30.0f) { f3 = 30.0f; } if (f3 < -30.0f) { f3 = -30.0f; } this.yRot += f3; if (this.hasAttacked && this.entityToAttack != null) { double d4 = this.entityToAttack.x - this.x; double d5 = this.entityToAttack.z - this.z; float f5 = this.yRot; this.yRot = (float) (Math.atan2(d5, d4) * 180.0 / 3.1415927410125732) - 90.0f; float f4 = (f5 - this.yRot + 90.0f) * 3.141593f / 180.0f; this.moveStrafing = -MathHelper.sin(f4) * this.moveForward * 1.0f; this.moveForward = MathHelper.cos(f4) * this.moveForward * 1.0f; } double d3 = Math.sqrt(x1 * x1 + y1 * y1 + z1 * z1); this.yd += MathHelper.clamp(y1 / d3, -0.5F, 0.5F) * 0.15F * this.moveSpeed; } if (this.entityToAttack != null) { this.faceEntity(this.entityToAttack, 30.0f, 30.0f); } } else { super.updatePlayerActionState(); this.currentTarget = null; } } protected void defaultPlayerActionState() { ++this.entityAge; this.tryToDespawn(); this.moveStrafing = 0.0f; this.moveForward = 0.0f; float f = 8.0f; if (this.random.nextFloat() < 0.02f) { EntityPlayer entityplayer1 = this.world.getClosestPlayerToEntity(this, f); if (entityplayer1 != null) { this.currentTarget = entityplayer1; this.numTicksToChaseTarget = 10 + this.random.nextInt(20); } else { this.randomYawVelocity = (this.random.nextFloat() - 0.5f) * 20.0f; } } if (this.currentTarget != null) { this.faceEntity(this.currentTarget, 10.0f, this.func_25026_x()); if (this.numTicksToChaseTarget-- <= 0 || this.currentTarget.removed || this.currentTarget.distanceToSqr(this) > (double) (f * f)) { this.currentTarget = null; } } else { if (this.random.nextFloat() < 0.05f) { this.randomYawVelocity = (this.random.nextFloat() - 0.5f) * 20.0f; } this.yRot += this.randomYawVelocity; this.xRot = this.defaultPitch; } } @Override public boolean canBreatheUnderwater() { return true; } @Override public void setSwimming(boolean swiming) { this.swimming = swiming; } @Override public boolean isSwimming() { return this.swimming; } @Override public float getSwimAmount(float p_20999_) {
package baguchan.better_with_aquatic.entity; public class EntityDrowned extends EntityZombie implements IPathGetter, ISwiming { private Entity currentTarget; public boolean swimming; private float swimAmount; private float swimAmountO; public EntityDrowned(World world) { super(world); this.setPathFinder(this, new BetterSwimWalkPathFinder(world)); this.setPathfindingMalus(this, BlockPath.WATER, 0.0F); this.setPathfindingMalus(this, BlockPath.OPEN, -1.0F); this.footSize = 1f; this.skinName = "drowned"; } @Override public String getEntityTexture() { return "/assets/better_with_aquatic/entity/drowned.png"; } @Override public String getDefaultEntityTexture() { return "/assets/better_with_aquatic/entity/drowned.png"; } @Override public void tick() { super.tick(); setSwimming(this.isInWater()); this.updateSwimAmount(); } private void updateSwimAmount() { this.swimAmountO = this.swimAmount; if (this.isSwimming()) { this.swimAmount = Math.min(1.0F, this.swimAmount + 0.09F); } else { this.swimAmount = Math.max(0.0F, this.swimAmount - 0.09F); } } @Override public void moveEntityWithHeading(float moveStrafing, float moveForward) { if (this.isInWater()) { this.moveRelative(moveStrafing, moveForward, 0.2F); this.move(this.xd, this.yd, this.zd); this.xd *= 0.8; this.yd *= 0.8; this.zd *= 0.8; this.prevLimbYaw = this.limbYaw; double d2 = this.x - this.xo; double d3 = this.z - this.zo; float f5 = MathHelper.sqrt_double(d2 * d2 + d3 * d3) * 4.0f; if (f5 > 1.0f) { f5 = 1.0f; } this.limbYaw += (f5 - this.limbYaw) * 0.4f; this.limbSwing += this.limbYaw; } else { super.moveEntityWithHeading(moveStrafing, moveForward); } } @Override protected void updatePlayerActionState() { if (this.isInWater()) { this.hasAttacked = this.isMovementCeased(); float sightRadius = 16.0f; if (this.entityToAttack == null) { this.entityToAttack = this.findPlayerToAttack(); if (this.entityToAttack != null) { this.pathToEntity = this.world.getPathToEntity(this, this.entityToAttack, sightRadius); } } else if (!this.entityToAttack.isAlive()) { this.entityToAttack = null; } else { float distanceToEntity = this.entityToAttack.distanceTo(this); if (this.canEntityBeSeen(this.entityToAttack)) { this.attackEntity(this.entityToAttack, distanceToEntity); } else { this.attackBlockedEntity(this.entityToAttack, distanceToEntity); } } if (!(this.hasAttacked || this.entityToAttack == null || this.pathToEntity != null && this.random.nextInt(20) != 0)) { this.pathToEntity = this.world.getPathToEntity(this, this.entityToAttack, sightRadius); } else if (!this.hasAttacked && this.closestFireflyEntity == null && (this.pathToEntity == null && this.random.nextInt(80) == 0 || this.random.nextInt(80) == 0)) { this.roamRandomPath(); } this.xRot = 0.0f; if (this.pathToEntity == null || this.random.nextInt(100) == 0) { this.defaultPlayerActionState(); this.pathToEntity = null; return; } Vec3d coordsForNextPath = this.pathToEntity.getPos(this); double d = this.bbWidth * 2.0f; double d2 = this.bbHeight * 2.0f; while (coordsForNextPath != null && coordsForNextPath.squareDistanceTo(this.x, this.y, this.z) < d * d + d2 * d2) { this.pathToEntity.next(); if (this.pathToEntity.isDone()) { this.closestFireflyEntity = null; coordsForNextPath = null; this.pathToEntity = null; continue; } coordsForNextPath = this.pathToEntity.getPos(this); } this.isJumping = false; if (coordsForNextPath != null) { float f3; double x1 = coordsForNextPath.xCoord - this.x; double z1 = coordsForNextPath.zCoord - this.z; double y1 = coordsForNextPath.yCoord - this.y; float f2 = (float) (Math.atan2(z1, x1) * 180.0 / 3.1415927410125732) - 90.0f; this.moveForward = this.moveSpeed * 0.15F; for (f3 = f2 - this.yRot; f3 < -180.0f; f3 += 360.0f) { } while (f3 >= 180.0f) { f3 -= 360.0f; } if (f3 > 30.0f) { f3 = 30.0f; } if (f3 < -30.0f) { f3 = -30.0f; } this.yRot += f3; if (this.hasAttacked && this.entityToAttack != null) { double d4 = this.entityToAttack.x - this.x; double d5 = this.entityToAttack.z - this.z; float f5 = this.yRot; this.yRot = (float) (Math.atan2(d5, d4) * 180.0 / 3.1415927410125732) - 90.0f; float f4 = (f5 - this.yRot + 90.0f) * 3.141593f / 180.0f; this.moveStrafing = -MathHelper.sin(f4) * this.moveForward * 1.0f; this.moveForward = MathHelper.cos(f4) * this.moveForward * 1.0f; } double d3 = Math.sqrt(x1 * x1 + y1 * y1 + z1 * z1); this.yd += MathHelper.clamp(y1 / d3, -0.5F, 0.5F) * 0.15F * this.moveSpeed; } if (this.entityToAttack != null) { this.faceEntity(this.entityToAttack, 30.0f, 30.0f); } } else { super.updatePlayerActionState(); this.currentTarget = null; } } protected void defaultPlayerActionState() { ++this.entityAge; this.tryToDespawn(); this.moveStrafing = 0.0f; this.moveForward = 0.0f; float f = 8.0f; if (this.random.nextFloat() < 0.02f) { EntityPlayer entityplayer1 = this.world.getClosestPlayerToEntity(this, f); if (entityplayer1 != null) { this.currentTarget = entityplayer1; this.numTicksToChaseTarget = 10 + this.random.nextInt(20); } else { this.randomYawVelocity = (this.random.nextFloat() - 0.5f) * 20.0f; } } if (this.currentTarget != null) { this.faceEntity(this.currentTarget, 10.0f, this.func_25026_x()); if (this.numTicksToChaseTarget-- <= 0 || this.currentTarget.removed || this.currentTarget.distanceToSqr(this) > (double) (f * f)) { this.currentTarget = null; } } else { if (this.random.nextFloat() < 0.05f) { this.randomYawVelocity = (this.random.nextFloat() - 0.5f) * 20.0f; } this.yRot += this.randomYawVelocity; this.xRot = this.defaultPitch; } } @Override public boolean canBreatheUnderwater() { return true; } @Override public void setSwimming(boolean swiming) { this.swimming = swiming; } @Override public boolean isSwimming() { return this.swimming; } @Override public float getSwimAmount(float p_20999_) {
return MathUtil.lerp(p_20999_, this.swimAmountO, this.swimAmount);
2
2023-11-08 23:02:14+00:00
8k
By1337/BAuction
Core/src/main/java/org/by1337/bauction/network/in/PlayInAddSellItemPacket.java
[ { "identifier": "SellItem", "path": "BaucApi/src/main/java/org/by1337/bauction/auc/SellItem.java", "snippet": "public interface SellItem extends Placeholderable, SerializableToByteArray {\n\n /**\n * Get the item available for sale as an ItemStack.\n *\n * @return ItemStack representing t...
import org.by1337.bauction.auc.SellItem; import org.by1337.bauction.db.kernel.CSellItem; import org.by1337.bauction.network.PacketIn; import org.by1337.bauction.network.PacketType; import java.io.DataInputStream; import java.io.IOException;
6,347
package org.by1337.bauction.network.in; public class PlayInAddSellItemPacket extends PacketIn { private final SellItem sellItem; public PlayInAddSellItemPacket(DataInputStream in) throws IOException {
package org.by1337.bauction.network.in; public class PlayInAddSellItemPacket extends PacketIn { private final SellItem sellItem; public PlayInAddSellItemPacket(DataInputStream in) throws IOException {
super(PacketType.ADD_SELL_ITEM);
3
2023-11-08 18:25:18+00:00
8k
Svydovets-Bobocode-Java-Ultimate-3-0/Bring
src/main/java/svydovets/core/context/beanDefinition/BeanDefinitionFactory.java
[ { "identifier": "BeanFactoryImpl", "path": "src/main/java/svydovets/core/context/beanFactory/BeanFactoryImpl.java", "snippet": "public class BeanFactoryImpl implements BeanFactory {\n private static final Logger log = LoggerFactory.getLogger(BeanFactoryImpl.class);\n\n public static final Set<Stri...
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import svydovets.core.annotation.Autowired; import svydovets.core.annotation.Bean; import svydovets.core.annotation.Primary; import svydovets.core.annotation.Scope; import svydovets.core.context.beanFactory.BeanFactoryImpl; import svydovets.core.exception.BeanDefinitionCreateException; import svydovets.core.exception.UnsupportedScopeException; import svydovets.util.ErrorMessageConstants; import svydovets.util.ReflectionsUtil; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import static svydovets.core.context.ApplicationContext.SCOPE_PROTOTYPE; import static svydovets.core.context.ApplicationContext.SCOPE_SINGLETON; import static svydovets.util.NameResolver.resolveBeanName; import static svydovets.util.ReflectionsUtil.findAutowiredFieldNames;
5,720
package svydovets.core.context.beanDefinition; /** * The BeanDefinitionFactory class manages the creation, registration, and retrieval of * BeanDefinitions in a Spring-like framework context. */ public class BeanDefinitionFactory { private static final Logger log = LoggerFactory.getLogger(BeanDefinitionFactory.class); private final Map<String, BeanDefinition> beanDefinitionMap = new LinkedHashMap<>(); /** * Registers bean definitions for the provided set of bean classes. * * @param beanClasses The set of classes representing beans to register. * @return A map containing registered bean definitions. */ public Map<String, BeanDefinition> registerBeanDefinitions(Set<Class<?>> beanClasses) { log.trace("Call registerBeanDefinitions({})", beanClasses); for (Class<?> configClass : beanClasses) { registerBeanDefinition(configClass); beanDefinitionMap.putAll(createBeanDefinitionMapByConfigClass(configClass)); } log.trace("Bean definition map has been created with keys: {}", beanDefinitionMap.keySet()); return beanDefinitionMap; } /** * Registers a bean definition based on a given bean class. * * @param beanClass The class representing the bean to register. */ public void registerBeanDefinition(Class<?> beanClass) { log.trace("Call registerBeanDefinition({})", beanClass); BeanDefinition beanDefinition = createComponentBeanDefinitionByBeanClass(beanClass);
package svydovets.core.context.beanDefinition; /** * The BeanDefinitionFactory class manages the creation, registration, and retrieval of * BeanDefinitions in a Spring-like framework context. */ public class BeanDefinitionFactory { private static final Logger log = LoggerFactory.getLogger(BeanDefinitionFactory.class); private final Map<String, BeanDefinition> beanDefinitionMap = new LinkedHashMap<>(); /** * Registers bean definitions for the provided set of bean classes. * * @param beanClasses The set of classes representing beans to register. * @return A map containing registered bean definitions. */ public Map<String, BeanDefinition> registerBeanDefinitions(Set<Class<?>> beanClasses) { log.trace("Call registerBeanDefinitions({})", beanClasses); for (Class<?> configClass : beanClasses) { registerBeanDefinition(configClass); beanDefinitionMap.putAll(createBeanDefinitionMapByConfigClass(configClass)); } log.trace("Bean definition map has been created with keys: {}", beanDefinitionMap.keySet()); return beanDefinitionMap; } /** * Registers a bean definition based on a given bean class. * * @param beanClass The class representing the bean to register. */ public void registerBeanDefinition(Class<?> beanClass) { log.trace("Call registerBeanDefinition({})", beanClass); BeanDefinition beanDefinition = createComponentBeanDefinitionByBeanClass(beanClass);
beanDefinitionMap.put(resolveBeanName(beanClass), beanDefinition);
5
2023-11-07 06:36:50+00:00
8k
oneqxz/RiseLoader
src/main/java/me/oneqxz/riseloader/fxml/controllers/impl/MainController.java
[ { "identifier": "RiseUI", "path": "src/main/java/me/oneqxz/riseloader/RiseUI.java", "snippet": "public class RiseUI extends Application {\n\n private static final Logger log = LogManager.getLogger(\"RiseLoader\");\n public static final Version version = new Version(\"1.0.8\");\n public static f...
import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.paint.ImagePattern; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import me.oneqxz.riseloader.RiseUI; import me.oneqxz.riseloader.fxml.components.impl.ErrorBox; import me.oneqxz.riseloader.fxml.controllers.Controller; import me.oneqxz.riseloader.fxml.scenes.MainScene; import me.oneqxz.riseloader.rise.RiseInfo; import java.awt.*; import java.net.URI;
3,632
package me.oneqxz.riseloader.fxml.controllers.impl; public class MainController extends Controller { Button home, settings, scripts, discord, github; Text version, riseVersion; Rectangle background; @Override protected void init() { this.home = ((Button) root.lookup("#btnHome")); this.settings = ((Button) root.lookup("#btnSettings")); this.scripts = ((Button) root.lookup("#btnScripts")); this.discord = ((Button) root.lookup("#discord")); this.github = ((Button) root.lookup("#github")); this.background = ((Rectangle) root.lookup("#background")); this.version = ((Text) root.lookup("#version")); this.riseVersion = ((Text) root.lookup("#riseReleaseVersion")); this.riseVersion.setText(RiseInfo.getInstance().getClientInfo().getRelease().getVersion()); this.home.setOnMouseClicked(event -> {
package me.oneqxz.riseloader.fxml.controllers.impl; public class MainController extends Controller { Button home, settings, scripts, discord, github; Text version, riseVersion; Rectangle background; @Override protected void init() { this.home = ((Button) root.lookup("#btnHome")); this.settings = ((Button) root.lookup("#btnSettings")); this.scripts = ((Button) root.lookup("#btnScripts")); this.discord = ((Button) root.lookup("#discord")); this.github = ((Button) root.lookup("#github")); this.background = ((Rectangle) root.lookup("#background")); this.version = ((Text) root.lookup("#version")); this.riseVersion = ((Text) root.lookup("#riseReleaseVersion")); this.riseVersion.setText(RiseInfo.getInstance().getClientInfo().getRelease().getVersion()); this.home.setOnMouseClicked(event -> {
MainScene.setCurrenViewPage(MainScene.Page.HOME);
3
2023-11-01 01:40:52+00:00
8k
YufiriaMazenta/CrypticLib
nms/src/main/java/crypticlib/nms/tile/TileEntityFactory.java
[ { "identifier": "CrypticLib", "path": "common/src/main/java/crypticlib/CrypticLib.java", "snippet": "public class CrypticLib {\n\n\n private static final CommandManager commandManager;\n private static final PermissionManager permissionManager;\n private static IPlatform platform;\n private ...
import crypticlib.CrypticLib; import crypticlib.nms.tile.v1_12_R1.V1_12_R1NbtTileEntity; import crypticlib.nms.tile.v1_13_R1.V1_13_R1NbtTileEntity; import crypticlib.nms.tile.v1_13_R2.V1_13_R2NbtTileEntity; import crypticlib.nms.tile.v1_14_R1.V1_14_R1NbtTileEntity; import crypticlib.nms.tile.v1_15_R1.V1_15_R1NbtTileEntity; import crypticlib.nms.tile.v1_16_R1.V1_16_R1NbtTileEntity; import crypticlib.nms.tile.v1_16_R2.V1_16_R2NbtTileEntity; import crypticlib.nms.tile.v1_16_R3.V1_16_R3NbtTileEntity; import crypticlib.nms.tile.v1_17_R1.V1_17_R1NbtTileEntity; import crypticlib.nms.tile.v1_18_R1.V1_18_R1NbtTileEntity; import crypticlib.nms.tile.v1_18_R2.V1_18_R2NbtTileEntity; import crypticlib.nms.tile.v1_19_R1.V1_19_R1NbtTileEntity; import crypticlib.nms.tile.v1_19_R2.V1_19_R2NbtTileEntity; import crypticlib.nms.tile.v1_19_R3.V1_19_R3NbtTileEntity; import crypticlib.nms.tile.v1_20_R1.V1_20_R1NbtTileEntity; import crypticlib.nms.tile.v1_20_R2.V1_20_R2NbtTileEntity; import crypticlib.nms.tile.v1_20_R3.V1_20_R3NbtTileEntity; import org.bukkit.block.BlockState; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function;
5,848
package crypticlib.nms.tile; public class TileEntityFactory { private static final Map<String, Function<BlockState, NbtTileEntity>> nbtTileEntityProviderMap; static { nbtTileEntityProviderMap = new ConcurrentHashMap<>(); regNbtTileEntityProvider("v1_12_R1", V1_12_R1NbtTileEntity::new); regNbtTileEntityProvider("v1_13_R1", V1_13_R1NbtTileEntity::new); regNbtTileEntityProvider("v1_13_R2", V1_13_R2NbtTileEntity::new); regNbtTileEntityProvider("v1_14_R1", V1_14_R1NbtTileEntity::new); regNbtTileEntityProvider("v1_15_R1", V1_15_R1NbtTileEntity::new); regNbtTileEntityProvider("v1_16_R1", V1_16_R1NbtTileEntity::new);
package crypticlib.nms.tile; public class TileEntityFactory { private static final Map<String, Function<BlockState, NbtTileEntity>> nbtTileEntityProviderMap; static { nbtTileEntityProviderMap = new ConcurrentHashMap<>(); regNbtTileEntityProvider("v1_12_R1", V1_12_R1NbtTileEntity::new); regNbtTileEntityProvider("v1_13_R1", V1_13_R1NbtTileEntity::new); regNbtTileEntityProvider("v1_13_R2", V1_13_R2NbtTileEntity::new); regNbtTileEntityProvider("v1_14_R1", V1_14_R1NbtTileEntity::new); regNbtTileEntityProvider("v1_15_R1", V1_15_R1NbtTileEntity::new); regNbtTileEntityProvider("v1_16_R1", V1_16_R1NbtTileEntity::new);
regNbtTileEntityProvider("v1_16_R2", V1_16_R2NbtTileEntity::new);
7
2023-11-07 12:39:20+00:00
8k
Traben-0/resource_explorer
common/src/main/java/traben/resource_explorer/explorer/REExplorer.java
[ { "identifier": "REConfig", "path": "common/src/main/java/traben/resource_explorer/REConfig.java", "snippet": "public class REConfig {\n\n private static REConfig instance;\n public boolean showResourcePackButton = true;\n public boolean logFullFileTree = false;\n public boolean addCauseToRe...
import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; import net.minecraft.client.MinecraftClient; import net.minecraft.client.texture.AbstractTexture; import net.minecraft.client.texture.NativeImage; import net.minecraft.client.toast.SystemToast; import net.minecraft.client.toast.ToastManager; import net.minecraft.resource.Resource; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import org.apache.commons.io.IOUtils; import traben.resource_explorer.REConfig; import traben.resource_explorer.ResourceExplorerClient; import traben.resource_explorer.mixin.TextureManagerAccessor; import java.io.*; import java.nio.file.Path; import java.util.*;
3,682
package traben.resource_explorer.explorer; public class REExplorer { public static final Identifier ICON_FILE_BUILT = new Identifier("resource_explorer:textures/file_built.png"); public static final Identifier ICON_FOLDER_BUILT = new Identifier("resource_explorer:textures/folder_built.png"); public static final Identifier ICON_FOLDER = new Identifier("resource_explorer:textures/folder.png"); public static final Identifier ICON_FOLDER_OPEN = new Identifier("resource_explorer:textures/folder_open.png"); public static final Identifier ICON_FOLDER_BACK = new Identifier("resource_explorer:textures/folder_back.png"); public static final Identifier ICON_FILE_PNG = new Identifier("resource_explorer:textures/file_png.png"); public static final Identifier ICON_FILE_TEXT = new Identifier("resource_explorer:textures/file_text.png"); public static final Identifier ICON_FILE_PROPERTY = new Identifier("resource_explorer:textures/file_property.png"); public static final Identifier ICON_FILE_OGG = new Identifier("resource_explorer:textures/file_ogg.png"); public static final Identifier ICON_FILE_UNKNOWN = new Identifier("resource_explorer:textures/file_unknown.png"); public static final Identifier ICON_FOLDER_MOJANG = new Identifier("resource_explorer:textures/folder_mojang.png"); public static final Identifier ICON_FOLDER_OPTIFINE = new Identifier("resource_explorer:textures/folder_optifine.png"); public static final Identifier ICON_FOLDER_ETF = new Identifier("resource_explorer:textures/folder_etf.png"); public static final Identifier ICON_FOLDER_EMF = new Identifier("resource_explorer:textures/folder_emf.png"); public static final Identifier ICON_FOLDER_CORNER = new Identifier("resource_explorer:textures/folder_corner.png"); public static final Identifier ICON_FILE_BLANK = new Identifier("resource_explorer:textures/file_blank.png"); public static final Identifier ICON_FILE_JSON = new Identifier("resource_explorer:textures/file_json.png"); public static final Identifier ICON_FOLDER_UP = new Identifier("resource_explorer:textures/folder_up.png"); public static final Identifier ICON_FOLDER_UP_SELECTED = new Identifier("resource_explorer:textures/folder_up_selected.png"); public static final Identifier ICON_FILE_ZIP = new Identifier("resource_explorer:textures/file_zip.png"); public static final Identifier ICON_FILE_JEM = new Identifier("resource_explorer:textures/file_jem.png"); public static final Identifier ICON_HAS_META = new Identifier("resource_explorer:textures/has_meta.png"); public static final Identifier ICON_FOLDER_FABRIC = new Identifier("resource_explorer:textures/folder_fabric.png"); public static final Identifier ICON_FOLDER_PNG = new Identifier("resource_explorer:textures/folder_png.png"); public static final Identifier ICON_FOLDER_OGG = new Identifier("resource_explorer:textures/folder_ogg.png"); public static final Identifier ICON_MOD = new Identifier("resource_explorer:textures/icon.png"); public static LinkedList<REResourceEntry> getResourceFolderRoot() { try { ObjectLinkedOpenHashSet<REResourceFile> allFilesList = new ObjectLinkedOpenHashSet<>();
package traben.resource_explorer.explorer; public class REExplorer { public static final Identifier ICON_FILE_BUILT = new Identifier("resource_explorer:textures/file_built.png"); public static final Identifier ICON_FOLDER_BUILT = new Identifier("resource_explorer:textures/folder_built.png"); public static final Identifier ICON_FOLDER = new Identifier("resource_explorer:textures/folder.png"); public static final Identifier ICON_FOLDER_OPEN = new Identifier("resource_explorer:textures/folder_open.png"); public static final Identifier ICON_FOLDER_BACK = new Identifier("resource_explorer:textures/folder_back.png"); public static final Identifier ICON_FILE_PNG = new Identifier("resource_explorer:textures/file_png.png"); public static final Identifier ICON_FILE_TEXT = new Identifier("resource_explorer:textures/file_text.png"); public static final Identifier ICON_FILE_PROPERTY = new Identifier("resource_explorer:textures/file_property.png"); public static final Identifier ICON_FILE_OGG = new Identifier("resource_explorer:textures/file_ogg.png"); public static final Identifier ICON_FILE_UNKNOWN = new Identifier("resource_explorer:textures/file_unknown.png"); public static final Identifier ICON_FOLDER_MOJANG = new Identifier("resource_explorer:textures/folder_mojang.png"); public static final Identifier ICON_FOLDER_OPTIFINE = new Identifier("resource_explorer:textures/folder_optifine.png"); public static final Identifier ICON_FOLDER_ETF = new Identifier("resource_explorer:textures/folder_etf.png"); public static final Identifier ICON_FOLDER_EMF = new Identifier("resource_explorer:textures/folder_emf.png"); public static final Identifier ICON_FOLDER_CORNER = new Identifier("resource_explorer:textures/folder_corner.png"); public static final Identifier ICON_FILE_BLANK = new Identifier("resource_explorer:textures/file_blank.png"); public static final Identifier ICON_FILE_JSON = new Identifier("resource_explorer:textures/file_json.png"); public static final Identifier ICON_FOLDER_UP = new Identifier("resource_explorer:textures/folder_up.png"); public static final Identifier ICON_FOLDER_UP_SELECTED = new Identifier("resource_explorer:textures/folder_up_selected.png"); public static final Identifier ICON_FILE_ZIP = new Identifier("resource_explorer:textures/file_zip.png"); public static final Identifier ICON_FILE_JEM = new Identifier("resource_explorer:textures/file_jem.png"); public static final Identifier ICON_HAS_META = new Identifier("resource_explorer:textures/has_meta.png"); public static final Identifier ICON_FOLDER_FABRIC = new Identifier("resource_explorer:textures/folder_fabric.png"); public static final Identifier ICON_FOLDER_PNG = new Identifier("resource_explorer:textures/folder_png.png"); public static final Identifier ICON_FOLDER_OGG = new Identifier("resource_explorer:textures/folder_ogg.png"); public static final Identifier ICON_MOD = new Identifier("resource_explorer:textures/icon.png"); public static LinkedList<REResourceEntry> getResourceFolderRoot() { try { ObjectLinkedOpenHashSet<REResourceFile> allFilesList = new ObjectLinkedOpenHashSet<>();
boolean print = REConfig.getInstance().logFullFileTree;
0
2023-11-05 17:35:39+00:00
8k
cypcodestudio/rbacspring
rbacspring/src/main/java/com/cypcode/rbacspring/controller/UserAccessController.java
[ { "identifier": "EntityResponse", "path": "rbacspring/src/main/java/com/cypcode/rbacspring/entity/dto/EntityResponse.java", "snippet": "public class EntityResponse {\n\tpublic static ResponseEntity<Object> generateResponse(String message, HttpStatus status, Object responseObj) {\n\t\t\n\t\tMap<String, O...
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.PasswordEncoder; 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.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.cypcode.rbacspring.entity.dto.EntityResponse; import com.cypcode.rbacspring.entity.dto.UserRegisterRequestDTO; import com.cypcode.rbacspring.security.JWTTokenUtil; import com.cypcode.rbacspring.security.dto.AuthenticationRequest; import com.cypcode.rbacspring.security.dto.AuthenticationResponse; import com.cypcode.rbacspring.service.WUserService;
3,649
package com.cypcode.rbacspring.controller; @RestController @RequestMapping("user") public class UserAccessController { @Autowired private AuthenticationManager authenticationManager; @Autowired WUserService userService; @Autowired
package com.cypcode.rbacspring.controller; @RestController @RequestMapping("user") public class UserAccessController { @Autowired private AuthenticationManager authenticationManager; @Autowired WUserService userService; @Autowired
private JWTTokenUtil jwtTokenUtil;
2
2023-11-05 05:38:31+00:00
8k
data-harness-cloud/data_harness-be
application-webadmin/src/main/java/supie/webadmin/app/liteFlow/node/SqlNode.java
[ { "identifier": "ProjectDatasourceMapper", "path": "application-webadmin/src/main/java/supie/webadmin/app/dao/ProjectDatasourceMapper.java", "snippet": "@EnableDataPerm\npublic interface ProjectDatasourceMapper extends BaseDaoMapper<ProjectDatasource> {\n\n /**\n * 批量插入对象列表。\n *\n * @para...
import cn.hutool.json.JSONUtil; import com.yomahub.liteflow.annotation.LiteflowComponent; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import supie.webadmin.app.dao.ProjectDatasourceMapper; import supie.webadmin.app.liteFlow.exception.MyLiteFlowException; import supie.webadmin.app.liteFlow.model.ErrorMessageModel; import supie.webadmin.app.liteFlow.model.LiteFlowNodeLogModel; import supie.webadmin.app.liteFlow.model.SqlAndShellModel; import supie.webadmin.app.model.ProjectDatasource; import supie.webadmin.app.service.databasemanagement.Strategy; import supie.webadmin.app.service.databasemanagement.StrategyFactory; import supie.webadmin.app.service.databasemanagement.model.DatabaseManagement; import java.util.List; import java.util.Map;
5,444
package supie.webadmin.app.liteFlow.node; /** * 描述:用于执行客户自定义的SQL语句 * * @author 王立宏 * @date 2023/10/22 14:32 * @path SDT-supie.webadmin.app.node-SqlNode */ @Slf4j @Component @LiteflowComponent(id = "sqlNode", name = "sqlNode") public class SqlNode extends BaseNode { private SqlAndShellModel sqlAndShellModel; private ProjectDatasource projectDatasource = null; private DatabaseManagement databaseManagement; @Autowired private ProjectDatasourceMapper projectDatasourceMapper; @Autowired
package supie.webadmin.app.liteFlow.node; /** * 描述:用于执行客户自定义的SQL语句 * * @author 王立宏 * @date 2023/10/22 14:32 * @path SDT-supie.webadmin.app.node-SqlNode */ @Slf4j @Component @LiteflowComponent(id = "sqlNode", name = "sqlNode") public class SqlNode extends BaseNode { private SqlAndShellModel sqlAndShellModel; private ProjectDatasource projectDatasource = null; private DatabaseManagement databaseManagement; @Autowired private ProjectDatasourceMapper projectDatasourceMapper; @Autowired
private StrategyFactory strategyFactory;
7
2023-11-04 12:36:44+00:00
8k
FTC-ORBIT/14872-2024-CenterStage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/opmode/ManualFeedforwardTuner.java
[ { "identifier": "MAX_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double MAX_ACCEL = 60;" }, { "identifier": "MAX_VEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", ...
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV; import com.acmerobotics.dashboard.FtcDashboard; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.dashboard.telemetry.MultipleTelemetry; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.kinematics.Kinematics; import com.acmerobotics.roadrunner.profile.MotionProfile; import com.acmerobotics.roadrunner.profile.MotionProfileGenerator; import com.acmerobotics.roadrunner.profile.MotionState; import com.acmerobotics.roadrunner.util.NanoClock; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.util.RobotLog; import org.firstinspires.ftc.robotcore.external.Telemetry; import org.firstinspires.ftc.teamcode.drive.DriveConstants; import org.firstinspires.ftc.teamcode.drive.SampleMecanumDrive; import java.util.Objects;
4,741
package org.firstinspires.ftc.teamcode.drive.opmode; /* * This routine is designed to tune the open-loop feedforward coefficients. Although it may seem unnecessary, * tuning these coefficients is just as important as the positional parameters. Like the other * manual tuning routines, this op mode relies heavily upon the dashboard. To access the dashboard, * connect your computer to the RC's WiFi network. In your browser, navigate to * https://192.168.49.1:8080/dash if you're using the RC phone or https://192.168.43.1:8080/dash if * you are using the Control Hub. Once you've successfully connected, start the program, and your * robot will begin moving forward and backward according to a motion profile. Your job is to graph * the velocity errors over time and adjust the feedforward coefficients. Once you've found a * satisfactory set of gains, add them to the appropriate fields in the DriveConstants.java file. * * Pressing Y/Δ (Xbox/PS4) will pause the tuning process and enter driver override, allowing the * user to reset the position of the bot in the event that it drifts off the path. * Pressing B/O (Xbox/PS4) will cede control back to the tuning process. */ @Config @Autonomous(group = "drive") public class ManualFeedforwardTuner extends LinearOpMode { public static double DISTANCE = 72; // in private FtcDashboard dashboard = FtcDashboard.getInstance(); private SampleMecanumDrive drive; enum Mode { DRIVER_MODE, TUNING_MODE } private Mode mode; private static MotionProfile generateProfile(boolean movingForward) { MotionState start = new MotionState(movingForward ? 0 : DISTANCE, 0, 0, 0); MotionState goal = new MotionState(movingForward ? DISTANCE : 0, 0, 0, 0); return MotionProfileGenerator.generateSimpleMotionProfile(start, goal, MAX_VEL, MAX_ACCEL); } @Override public void runOpMode() { if (RUN_USING_ENCODER) { RobotLog.setGlobalErrorMsg("Feedforward constants usually don't need to be tuned " + "when using the built-in drive motor velocity PID."); } Telemetry telemetry = new MultipleTelemetry(this.telemetry, dashboard.getTelemetry()); drive = new SampleMecanumDrive(hardwareMap); final VoltageSensor voltageSensor = hardwareMap.voltageSensor.iterator().next(); mode = Mode.TUNING_MODE; NanoClock clock = NanoClock.system(); telemetry.addLine("Ready!"); telemetry.update(); telemetry.clearAll(); waitForStart(); if (isStopRequested()) return; boolean movingForwards = true; MotionProfile activeProfile = generateProfile(true); double profileStart = clock.seconds(); while (!isStopRequested()) { telemetry.addData("mode", mode); switch (mode) { case TUNING_MODE: if (gamepad1.y) { mode = Mode.DRIVER_MODE; } // calculate and set the motor power double profileTime = clock.seconds() - profileStart; if (profileTime > activeProfile.duration()) { // generate a new profile movingForwards = !movingForwards; activeProfile = generateProfile(movingForwards); profileStart = clock.seconds(); } MotionState motionState = activeProfile.get(profileTime);
package org.firstinspires.ftc.teamcode.drive.opmode; /* * This routine is designed to tune the open-loop feedforward coefficients. Although it may seem unnecessary, * tuning these coefficients is just as important as the positional parameters. Like the other * manual tuning routines, this op mode relies heavily upon the dashboard. To access the dashboard, * connect your computer to the RC's WiFi network. In your browser, navigate to * https://192.168.49.1:8080/dash if you're using the RC phone or https://192.168.43.1:8080/dash if * you are using the Control Hub. Once you've successfully connected, start the program, and your * robot will begin moving forward and backward according to a motion profile. Your job is to graph * the velocity errors over time and adjust the feedforward coefficients. Once you've found a * satisfactory set of gains, add them to the appropriate fields in the DriveConstants.java file. * * Pressing Y/Δ (Xbox/PS4) will pause the tuning process and enter driver override, allowing the * user to reset the position of the bot in the event that it drifts off the path. * Pressing B/O (Xbox/PS4) will cede control back to the tuning process. */ @Config @Autonomous(group = "drive") public class ManualFeedforwardTuner extends LinearOpMode { public static double DISTANCE = 72; // in private FtcDashboard dashboard = FtcDashboard.getInstance(); private SampleMecanumDrive drive; enum Mode { DRIVER_MODE, TUNING_MODE } private Mode mode; private static MotionProfile generateProfile(boolean movingForward) { MotionState start = new MotionState(movingForward ? 0 : DISTANCE, 0, 0, 0); MotionState goal = new MotionState(movingForward ? DISTANCE : 0, 0, 0, 0); return MotionProfileGenerator.generateSimpleMotionProfile(start, goal, MAX_VEL, MAX_ACCEL); } @Override public void runOpMode() { if (RUN_USING_ENCODER) { RobotLog.setGlobalErrorMsg("Feedforward constants usually don't need to be tuned " + "when using the built-in drive motor velocity PID."); } Telemetry telemetry = new MultipleTelemetry(this.telemetry, dashboard.getTelemetry()); drive = new SampleMecanumDrive(hardwareMap); final VoltageSensor voltageSensor = hardwareMap.voltageSensor.iterator().next(); mode = Mode.TUNING_MODE; NanoClock clock = NanoClock.system(); telemetry.addLine("Ready!"); telemetry.update(); telemetry.clearAll(); waitForStart(); if (isStopRequested()) return; boolean movingForwards = true; MotionProfile activeProfile = generateProfile(true); double profileStart = clock.seconds(); while (!isStopRequested()) { telemetry.addData("mode", mode); switch (mode) { case TUNING_MODE: if (gamepad1.y) { mode = Mode.DRIVER_MODE; } // calculate and set the motor power double profileTime = clock.seconds() - profileStart; if (profileTime > activeProfile.duration()) { // generate a new profile movingForwards = !movingForwards; activeProfile = generateProfile(movingForwards); profileStart = clock.seconds(); } MotionState motionState = activeProfile.get(profileTime);
double targetPower = Kinematics.calculateMotorFeedforward(motionState.getV(), motionState.getA(), kV, kA, kStatic);
3
2023-11-03 13:32:48+00:00
8k
momentohq/momento-dynamodb-lock-client
src/test/java/com/amazonaws/services/dynamodbv2/MomentoDynamoDBLockClientTest.java
[ { "identifier": "MomentoDynamoDBLockClientOptions", "path": "src/main/java/momento/lock/client/MomentoDynamoDBLockClientOptions.java", "snippet": "public class MomentoDynamoDBLockClientOptions {\n\n private final String cacheName;\n private final CredentialProvider credentialProvider;\n private...
import com.amazonaws.services.dynamodbv2.model.LockCurrentlyUnavailableException; import com.amazonaws.services.dynamodbv2.model.LockNotGrantedException; import momento.lock.client.MomentoDynamoDBLockClientOptions; import momento.lock.client.MomentoLockClient; import momento.lock.client.MomentoLockItem; import momento.sdk.CacheClient; import momento.sdk.auth.CredentialProvider; import momento.sdk.config.Configurations; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.ByteBuffer; import java.time.Duration; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit;
5,498
package com.amazonaws.services.dynamodbv2; public class MomentoDynamoDBLockClientTest { private static MomentoDynamoDBLockClient momentoDynamoDBLockClient; private static MomentoDynamoDBLockClient momentoDynamoDBLockClientWithoutHeartbeat; private static MomentoLockClient momentoLockClient; private static MomentoLockClient momentoLockClientNoHeartBeats; private static CacheClient cacheClient; private static String LOCK_CACHE_NAME = "lock"; private static String LOCK_CACHE_NAME_NO_HEARTBEATS = "lock_no_heartbeats"; @BeforeAll public static void setup() {
package com.amazonaws.services.dynamodbv2; public class MomentoDynamoDBLockClientTest { private static MomentoDynamoDBLockClient momentoDynamoDBLockClient; private static MomentoDynamoDBLockClient momentoDynamoDBLockClientWithoutHeartbeat; private static MomentoLockClient momentoLockClient; private static MomentoLockClient momentoLockClientNoHeartBeats; private static CacheClient cacheClient; private static String LOCK_CACHE_NAME = "lock"; private static String LOCK_CACHE_NAME_NO_HEARTBEATS = "lock_no_heartbeats"; @BeforeAll public static void setup() {
momentoDynamoDBLockClient = new MomentoDynamoDBLockClient(MomentoDynamoDBLockClientOptions.builder("lock")
0
2023-11-07 03:56:11+00:00
8k
beminder/BeautyMinder
java/src/main/java/app/beautyminder/controller/redis/RedisController.java
[ { "identifier": "Cosmetic", "path": "java/src/main/java/app/beautyminder/domain/Cosmetic.java", "snippet": "@Document(collection = \"cosmetics\") // mongodb\n@AllArgsConstructor\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@Getter\n@Builder\npublic class Cosmetic {\n\n @Id\n private String...
import app.beautyminder.domain.Cosmetic; import app.beautyminder.dto.KeywordRankResponse; import app.beautyminder.dto.ProductRankResponse; import app.beautyminder.repository.KeywordRankRepository; import app.beautyminder.service.cosmetic.CosmeticRankService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.List;
6,000
package app.beautyminder.controller.redis; @RequiredArgsConstructor @RestController @RequestMapping("/redis") public class RedisController { private final CosmeticRankService cosmeticRankService; private final KeywordRankRepository keywordRankRepository; @Operation( summary = "Get N ranked products", description = "N개의 실시간 랭킹 제품들을 불러옵니다.", tags = {"Redis Operations"}, parameters = { @Parameter(name = "size", description = "N개 제품") }, responses = { @ApiResponse(responseCode = "200", description = "성공", content = @Content(schema = @Schema(implementation = Cosmetic.class, type = "array"))) } ) @GetMapping("/top/cosmetics") public ResponseEntity<ProductRankResponse> getTopRankedCosmetics( @RequestParam(defaultValue = "10") int size) { List<Cosmetic> topRankedCosmetics = cosmeticRankService.getTopRankedCosmetics(size); return new ResponseEntity<>(new ProductRankResponse(topRankedCosmetics, LocalDateTime.now(ZoneId.of("Asia/Seoul"))), HttpStatus.OK); } @Operation( summary = "Get top 10 keywords", description = "가장 최근의 검색어 랭킹을 불러옵니다.", tags = {"Redis Operations"}, responses = { @ApiResponse(responseCode = "200", description = "성공", content = @Content(schema = @Schema(implementation = String.class, type = "array"))) } ) @GetMapping("/top/keywords")
package app.beautyminder.controller.redis; @RequiredArgsConstructor @RestController @RequestMapping("/redis") public class RedisController { private final CosmeticRankService cosmeticRankService; private final KeywordRankRepository keywordRankRepository; @Operation( summary = "Get N ranked products", description = "N개의 실시간 랭킹 제품들을 불러옵니다.", tags = {"Redis Operations"}, parameters = { @Parameter(name = "size", description = "N개 제품") }, responses = { @ApiResponse(responseCode = "200", description = "성공", content = @Content(schema = @Schema(implementation = Cosmetic.class, type = "array"))) } ) @GetMapping("/top/cosmetics") public ResponseEntity<ProductRankResponse> getTopRankedCosmetics( @RequestParam(defaultValue = "10") int size) { List<Cosmetic> topRankedCosmetics = cosmeticRankService.getTopRankedCosmetics(size); return new ResponseEntity<>(new ProductRankResponse(topRankedCosmetics, LocalDateTime.now(ZoneId.of("Asia/Seoul"))), HttpStatus.OK); } @Operation( summary = "Get top 10 keywords", description = "가장 최근의 검색어 랭킹을 불러옵니다.", tags = {"Redis Operations"}, responses = { @ApiResponse(responseCode = "200", description = "성공", content = @Content(schema = @Schema(implementation = String.class, type = "array"))) } ) @GetMapping("/top/keywords")
public ResponseEntity<KeywordRankResponse> getTopRankedKeywords() {
1
2023-11-01 12:37:16+00:00
8k
Xrayya/java-cli-pbpu
src/main/java/com/App.java
[ { "identifier": "Auth", "path": "src/main/java/com/CashierAppUtil/Auth.java", "snippet": "public class Auth {\n public static Employee authenticate(String username, String password) {\n List<Manager> managers = new Record<Manager>(\"managers\", Manager[].class).readRecordFile();\n for (...
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.UUID; import com.CashierAppUtil.Auth; import com.CashierAppUtil.CashierMachine; import com.CashierAppUtil.ManagerMachine; import com.Model.Employee; import com.Model.EmployeeModel; import com.Model.FoodCategory; import com.Model.Manager; import com.Model.Menu; import com.Model.MenuOrder; import com.Model.Order; import com.RecordUtil.Log;
5,121
} printExitMenus(); System.out.print("Enter the number: "); String inputNumber = input.nextLine(); switch (inputNumber) { case "1": printAllMenu(); break; case "2": takeOrder(); break; case "3": markOrderComplete(); break; case "4": editUnfinishedOrder(); break; case "5": cancelUnfinishedOrder(); break; case "6": printUnfinishedOrders(); break; case "7": printNewFinishedOrders(); break; case "8": printAllOrderNewOrders(); break; case "9": saveOrderToRecord(); break; case "0": logout(); keepLoop = false; break; case "00": exit(); break; default: if (employee instanceof Manager) { switch (inputNumber) { case "10": printOrderRecord(); break; case "11": addMenu(); break; case "12": removeMenu(); break; case "13": editMenu(); break; } } else { System.out.println("Sorry, your input is not recognized, please input valid number"); } break; } } } private static void printMainMenu() { printBoldSeparator(); System.out.println("Cashier App"); printBoldSeparator(); System.out.println("1. Print All Menu"); System.out.println("2. Take Order"); System.out.println("3. Mark Order Done"); System.out.println("4. Edit Unfinished Order"); System.out.println("5. Cancel Unfinished Order"); // not mvp System.out.println("6. Print Unfinished Orders"); // not mvp System.out.println("7. Print New Finished Orders"); // not mvp System.out.println("8. Print All new Orders"); System.out.println("9. Save Order to Record"); // tiap take order, not mvp } private static void printManagerAdditionalMainMenu() { System.out.println("10. Print Order Record"); // not mvp System.out.println("11. Add Menu"); System.out.println("12. Remove Menu"); System.out.println("13. Edit Menu"); } private static void printExitMenus() { System.out.println("0. Logout"); // buat keluar loop System.out.println("00. Exit"); } private static void login() { while (employee == null) { System.out.print("Enter username: "); String username = input.nextLine(); System.out.print("Enter password: "); String password = input.nextLine(); employee = Auth.authenticate(username, password); if (employee == null) { System.out.println("Username or password mismatch"); } } cashierMachine = employee.getMachine(); } private static void logout() { employee = null; cashierMachine = null; } private static void exit() { System.exit(0); } private static void printAllMenu() { cashierMachine.printMenu(); } private static void takeOrder() {
package com; /** * Hello world! * */ public class App { private static final Scanner input = new Scanner(System.in); private static Employee employee; private static CashierMachine cashierMachine; public static void main(String[] args) { while (true) { login(); runMainLoop(); } } private static void runMainLoop() { boolean keepLoop = true; while (keepLoop) { printMainMenu(); if (employee instanceof Manager) { printManagerAdditionalMainMenu(); } printExitMenus(); System.out.print("Enter the number: "); String inputNumber = input.nextLine(); switch (inputNumber) { case "1": printAllMenu(); break; case "2": takeOrder(); break; case "3": markOrderComplete(); break; case "4": editUnfinishedOrder(); break; case "5": cancelUnfinishedOrder(); break; case "6": printUnfinishedOrders(); break; case "7": printNewFinishedOrders(); break; case "8": printAllOrderNewOrders(); break; case "9": saveOrderToRecord(); break; case "0": logout(); keepLoop = false; break; case "00": exit(); break; default: if (employee instanceof Manager) { switch (inputNumber) { case "10": printOrderRecord(); break; case "11": addMenu(); break; case "12": removeMenu(); break; case "13": editMenu(); break; } } else { System.out.println("Sorry, your input is not recognized, please input valid number"); } break; } } } private static void printMainMenu() { printBoldSeparator(); System.out.println("Cashier App"); printBoldSeparator(); System.out.println("1. Print All Menu"); System.out.println("2. Take Order"); System.out.println("3. Mark Order Done"); System.out.println("4. Edit Unfinished Order"); System.out.println("5. Cancel Unfinished Order"); // not mvp System.out.println("6. Print Unfinished Orders"); // not mvp System.out.println("7. Print New Finished Orders"); // not mvp System.out.println("8. Print All new Orders"); System.out.println("9. Save Order to Record"); // tiap take order, not mvp } private static void printManagerAdditionalMainMenu() { System.out.println("10. Print Order Record"); // not mvp System.out.println("11. Add Menu"); System.out.println("12. Remove Menu"); System.out.println("13. Edit Menu"); } private static void printExitMenus() { System.out.println("0. Logout"); // buat keluar loop System.out.println("00. Exit"); } private static void login() { while (employee == null) { System.out.print("Enter username: "); String username = input.nextLine(); System.out.print("Enter password: "); String password = input.nextLine(); employee = Auth.authenticate(username, password); if (employee == null) { System.out.println("Username or password mismatch"); } } cashierMachine = employee.getMachine(); } private static void logout() { employee = null; cashierMachine = null; } private static void exit() { System.exit(0); } private static void printAllMenu() { cashierMachine.printMenu(); } private static void takeOrder() {
List<MenuOrder> orderedMenuList = new ArrayList<>();
8
2023-11-09 05:26:20+00:00
8k
FallenDeity/GameEngine2DJava
src/main/java/engine/components/TurtleAI.java
[ { "identifier": "RigidBody2D", "path": "src/main/java/engine/physics2d/components/RigidBody2D.java", "snippet": "public class RigidBody2D extends Component {\n\tprivate float friction = 0.1f;\n\tprivate float gravityScale = 1.0f;\n\tprivate float angularVelocity = 0.0f;\n\tprivate Vector2f velocity = ne...
import engine.physics2d.components.RigidBody2D; import engine.renderer.Camera; import engine.ruby.Window; import engine.util.AssetPool; import engine.util.CONSTANTS; import org.jbox2d.dynamics.contacts.Contact; import org.joml.Vector2f;
5,465
package engine.components; public class TurtleAI extends Component { private final transient Vector2f velocity = new Vector2f(); private final transient Vector2f acceleration = new Vector2f(); private final transient Vector2f terminalVelocity = new Vector2f(2.1f, 3.1f); private transient boolean movingRight = false; private transient RigidBody2D rigidBody2D; private transient float walkSpeed = 0.6f; private transient boolean isGrounded = false; private transient boolean isDead = false; private transient boolean isMoving = false; private transient StateMachine stateMachine; private transient float debounceTimer = 0.32f; @Override public void update(float dt) { debounceTimer -= dt;
package engine.components; public class TurtleAI extends Component { private final transient Vector2f velocity = new Vector2f(); private final transient Vector2f acceleration = new Vector2f(); private final transient Vector2f terminalVelocity = new Vector2f(2.1f, 3.1f); private transient boolean movingRight = false; private transient RigidBody2D rigidBody2D; private transient float walkSpeed = 0.6f; private transient boolean isGrounded = false; private transient boolean isDead = false; private transient boolean isMoving = false; private transient StateMachine stateMachine; private transient float debounceTimer = 0.32f; @Override public void update(float dt) { debounceTimer -= dt;
Camera camera = Window.getScene().getCamera();
2
2023-11-04 13:19:21+00:00
8k
RezaGooner/University-food-ordering
Frames/Profile/NewUserFrame.java
[ { "identifier": "Gender", "path": "Classes/Roles/Gender.java", "snippet": "public enum Gender {\r\n MALE(\"مرد\"),\r\n FEMALE(\"زن\");\r\n\r\n Gender(String label) {\r\n }\r\n}\r" }, { "identifier": "Organization", "path": "Classes/Roles/Organization.java", "snippet": "public...
import java.awt.event.*; import java.io.*; import java.util.Scanner; import static Classes.Pathes.FilesPath.icon; import static Classes.Theme.SoundEffect.errorSound; import static Classes.Theme.SoundEffect.successSound; import static Frames.LoginFrame.isNumeric; import static Classes.Pathes.FilesPath.UserPassPath; import Classes.Roles.Gender; import Classes.Roles.Organization; import Classes.Theme.StyledButtonUI; import Frames.LoginFrame; import Frames.Order.BalanceHandler; import javax.swing.*; import java.awt.*;
6,448
package Frames.Profile; /* این کلاس برای ایجاد حساب کاربری جدید ساخته شده است در اغاز پنجره ای باز می شود با ورودی های firstNameField , lastNameField , idField , numberField و همچنین genderComboBox , organizationComboBox و گزینه های Student , VIPStudent و Employee . در ورودی های تعریف شده کاربر بایستی نام و نام خانوادگی ، شناسه و همچنین شماره همراه خود را وارد کند شناسه باید ده عددی ده رقمی باشد . همچنین بسته به نوع کاربر با انتخاب هر کدام از checkBox های دانشجو و کارمند و دانشجوی ویژه باید با عددی خاص شروع شود. شماره همراه نیز باید عددی یازده رقمی باشد. در ضمن همه فیلد های ورودی باید پر شوند. کاربر باید جنسیت خود را از genderComboBox انتخاب کرده و اگر تیک بخش VIPStudent را فعال کند بایستی وضعیت خود را در organizationComboBox مشخص کند تا تخفیف های خرید غذا شامل وی شود سپس بعد از وارد کردن و تایید شدن اطلاعات ، داده ها در مسیر فایل مشخص شده ، به صورت جداشده با کاما نوشته میشوند. */ public class NewUserFrame extends JFrame { private final JTextField firstNameField; private final JTextField lastNameField; private final JTextField idField; private final JTextField numberField; private final JComboBox<Gender> genderComboBox; private final JComboBox<Organization> organizationComboBox; private final JCheckBox employeeCheckBox; private final JCheckBox studentCheckBox; private final JCheckBox vipStudentCheckBox; private final JPasswordField passwordField; private final JPasswordField confirmPasswordField; private final JLabel statusLabel; private String organization ; public static Color colorButton = new Color(19,56,190); public static Color colorBackground = new Color(136,226,242); public NewUserFrame() { setTitle("ثبت نام");
package Frames.Profile; /* این کلاس برای ایجاد حساب کاربری جدید ساخته شده است در اغاز پنجره ای باز می شود با ورودی های firstNameField , lastNameField , idField , numberField و همچنین genderComboBox , organizationComboBox و گزینه های Student , VIPStudent و Employee . در ورودی های تعریف شده کاربر بایستی نام و نام خانوادگی ، شناسه و همچنین شماره همراه خود را وارد کند شناسه باید ده عددی ده رقمی باشد . همچنین بسته به نوع کاربر با انتخاب هر کدام از checkBox های دانشجو و کارمند و دانشجوی ویژه باید با عددی خاص شروع شود. شماره همراه نیز باید عددی یازده رقمی باشد. در ضمن همه فیلد های ورودی باید پر شوند. کاربر باید جنسیت خود را از genderComboBox انتخاب کرده و اگر تیک بخش VIPStudent را فعال کند بایستی وضعیت خود را در organizationComboBox مشخص کند تا تخفیف های خرید غذا شامل وی شود سپس بعد از وارد کردن و تایید شدن اطلاعات ، داده ها در مسیر فایل مشخص شده ، به صورت جداشده با کاما نوشته میشوند. */ public class NewUserFrame extends JFrame { private final JTextField firstNameField; private final JTextField lastNameField; private final JTextField idField; private final JTextField numberField; private final JComboBox<Gender> genderComboBox; private final JComboBox<Organization> organizationComboBox; private final JCheckBox employeeCheckBox; private final JCheckBox studentCheckBox; private final JCheckBox vipStudentCheckBox; private final JPasswordField passwordField; private final JPasswordField confirmPasswordField; private final JLabel statusLabel; private String organization ; public static Color colorButton = new Color(19,56,190); public static Color colorBackground = new Color(136,226,242); public NewUserFrame() { setTitle("ثبت نام");
setIconImage(icon.getImage());
5
2023-11-03 08:35:22+00:00
8k
EaindrayFromEarth/Collaborative_Blog_Version_Control_Management-System
java/com/we_write/controller/BlogController.java
[ { "identifier": "Blog", "path": "java/com/we_write/entity/Blog.java", "snippet": "@Entity\r\n@Getter\r\n@Setter\r\n@AllArgsConstructor\r\n@NoArgsConstructor\r\n\r\n\r\n@Table(\r\n name = \"blogs\", uniqueConstraints = {@UniqueConstraint(columnNames = {\"blog_id\"})}\r\n) \r\npublic class Blog {\r...
import java.security.Principal; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.we_write.entity.Blog; import com.we_write.entity.BlogVersion; import com.we_write.entity.Review; import com.we_write.entity.ReviewStatus; import com.we_write.entity.User; import com.we_write.payload.BlogDto; import com.we_write.payload.BlogVersionRequest; import com.we_write.payload.ReviewRequest; import com.we_write.repository.UserRepository; import com.we_write.service.BlogService; import com.we_write.service.ReviewService; import com.we_write.service.UserService; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid;
5,055
package com.we_write.controller; @RestController @RequestMapping("/api/blogs") @Tag( name = "CRUD REST APIs for Blogs" ) public class BlogController { @Autowired private BlogService blogService; @Autowired
package com.we_write.controller; @RestController @RequestMapping("/api/blogs") @Tag( name = "CRUD REST APIs for Blogs" ) public class BlogController { @Autowired private BlogService blogService; @Autowired
private ReviewService reviewService;
10
2023-11-05 05:44:23+00:00
8k
antoKeinanen/Serverselector
src/main/java/dev/antok/serverselector/Serverselector.java
[ { "identifier": "JoinCommand", "path": "src/main/java/dev/antok/serverselector/command/JoinCommand.java", "snippet": "public class JoinCommand implements CommandExecutor {\n\n final JoinInventory joinInventory;\n final Logger logger;\n final Config.ConfigFile configFile;\n\n public JoinComma...
import dev.antok.serverselector.command.JoinCommand; import dev.antok.serverselector.config.Config; import dev.antok.serverselector.inventory.JoinInventory; import dev.antok.serverselector.config.ConfigManager; import dev.antok.serverselector.util.SendPlayerToServer; import dev.antok.serverselector.util.ServerStarter; import net.kyori.adventure.text.minimessage.MiniMessage; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.HashMap; import java.util.logging.Logger;
3,931
package dev.antok.serverselector; public final class Serverselector extends JavaPlugin { public HashMap<Player, Integer> joiningPlayers = new HashMap<>(); @Override public void onEnable() { Logger logger = getLogger(); final Serverselector instance = this; Config.ConfigFile configFile = new ConfigManager(this).configFile; MiniMessage mm = MiniMessage.miniMessage(); final ServerStarter serverStarter = new ServerStarter(logger, configFile); final JoinInventory joinInventory = new JoinInventory(logger, serverStarter, this, configFile); this.getServer().getPluginManager().registerEvents(joinInventory, this);
package dev.antok.serverselector; public final class Serverselector extends JavaPlugin { public HashMap<Player, Integer> joiningPlayers = new HashMap<>(); @Override public void onEnable() { Logger logger = getLogger(); final Serverselector instance = this; Config.ConfigFile configFile = new ConfigManager(this).configFile; MiniMessage mm = MiniMessage.miniMessage(); final ServerStarter serverStarter = new ServerStarter(logger, configFile); final JoinInventory joinInventory = new JoinInventory(logger, serverStarter, this, configFile); this.getServer().getPluginManager().registerEvents(joinInventory, this);
this.getCommand("join").setExecutor(new JoinCommand(logger, joinInventory, configFile));
0
2023-11-09 14:38:55+00:00
8k
schadfield/shogi-explorer
src/main/java/com/chadfield/shogiexplorer/main/AnalysisManager.java
[ { "identifier": "Analysis", "path": "src/main/java/com/chadfield/shogiexplorer/objects/Analysis.java", "snippet": "public class Analysis {\n\n private List<List<Position>> analysisPositionList;\n private List<Object[]> tableRows;\n private List<Integer> scoreList;\n\n /**\n * @return the...
import com.chadfield.shogiexplorer.objects.Analysis; import com.chadfield.shogiexplorer.objects.AnalysisParameter; import com.chadfield.shogiexplorer.objects.Game; import com.chadfield.shogiexplorer.objects.Position; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import com.thoughtworks.xstream.security.AnyTypePermission; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JRadioButtonMenuItem; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.DefaultIntervalXYDataset;
5,122
/* Copyright © 2021, 2022 Stephen R Chadfield. This file is part of Shogi Explorer. Shogi Explorer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Shogi Explorer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Shogi Explorer. If not, see <https://www.gnu.org/licenses/>. */ package com.chadfield.shogiexplorer.main; public class AnalysisManager { private AnalysisManager() { throw new IllegalStateException("Utility class"); } public static void save(Analysis analysis, File kifFile) { File analysisFile = getAnalysisFile(kifFile); XStream xstream = new XStream(new DomDriver("UTF-8")); xstream.alias("analysis", Analysis.class); xstream.alias("position", Position.class); String dataXml = xstream.toXML(analysis); try ( FileWriter fileWriter = new FileWriter(analysisFile, false)) { fileWriter.write(dataXml); } catch (IOException ex) { Logger.getLogger(AnalysisManager.class.getName()).log(Level.SEVERE, null, ex); } }
/* Copyright © 2021, 2022 Stephen R Chadfield. This file is part of Shogi Explorer. Shogi Explorer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Shogi Explorer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Shogi Explorer. If not, see <https://www.gnu.org/licenses/>. */ package com.chadfield.shogiexplorer.main; public class AnalysisManager { private AnalysisManager() { throw new IllegalStateException("Utility class"); } public static void save(Analysis analysis, File kifFile) { File analysisFile = getAnalysisFile(kifFile); XStream xstream = new XStream(new DomDriver("UTF-8")); xstream.alias("analysis", Analysis.class); xstream.alias("position", Position.class); String dataXml = xstream.toXML(analysis); try ( FileWriter fileWriter = new FileWriter(analysisFile, false)) { fileWriter.write(dataXml); } catch (IOException ex) { Logger.getLogger(AnalysisManager.class.getName()).log(Level.SEVERE, null, ex); } }
public static void load(File kifFile, Game game, JTable analysisTable, AnalysisParameter analysisParameter, XYPlot plot) {
1
2023-11-08 09:24:57+00:00
8k
refrainsclub/npcs
src/main/java/nz/blair/npcs/NpcsApi.java
[ { "identifier": "Npc", "path": "src/main/java/nz/blair/npcs/npcs/Npc.java", "snippet": "@SuppressWarnings({\"unused\", \"UnusedReturnValue\"}) // This class is used by other plugins\npublic class Npc {\n private final JavaPlugin plugin;\n private final EntityPlayer entityPlayer;\n private final...
import nz.blair.npcs.npcs.Npc; import nz.blair.npcs.npcs.NpcFactory; import nz.blair.npcs.npcs.NpcManager; import org.bukkit.Location; import java.util.Set;
5,869
package nz.blair.npcs; /** * The API for the NPCs plugin. * This is the main class that you will use to interact with the plugin. */ @SuppressWarnings("unused") // This class is used by other plugins public class NpcsApi { private final NpcManager npcManager; private final NpcFactory npcFactory; /** * Create a new instance of the API. * Do not use this constructor, instead use {@link nz.blair.npcs.NpcsPlugin#getApi()}. * * @param npcManager The NPC manager * @param npcFactory The NPC factory */ public NpcsApi(NpcManager npcManager, NpcFactory npcFactory) { this.npcManager = npcManager; this.npcFactory = npcFactory; } /** * Create a new NPC with the given name and location. * This will automatically add the NPC to the NPC manager. * * @param name The name of the NPC * @param location The location of the NPC * @param global Whether the NPC should be visible to all players * @return The NPC */
package nz.blair.npcs; /** * The API for the NPCs plugin. * This is the main class that you will use to interact with the plugin. */ @SuppressWarnings("unused") // This class is used by other plugins public class NpcsApi { private final NpcManager npcManager; private final NpcFactory npcFactory; /** * Create a new instance of the API. * Do not use this constructor, instead use {@link nz.blair.npcs.NpcsPlugin#getApi()}. * * @param npcManager The NPC manager * @param npcFactory The NPC factory */ public NpcsApi(NpcManager npcManager, NpcFactory npcFactory) { this.npcManager = npcManager; this.npcFactory = npcFactory; } /** * Create a new NPC with the given name and location. * This will automatically add the NPC to the NPC manager. * * @param name The name of the NPC * @param location The location of the NPC * @param global Whether the NPC should be visible to all players * @return The NPC */
public Npc createNpc(String name, Location location, boolean global) {
0
2023-11-01 01:14:41+00:00
8k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/service/impl/ChatFriendRoomServiceImpl.java
[ { "identifier": "RoomAdapt", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/adapt/RoomAdapt.java", "snippet": "public class RoomAdapt {\n\n /**\n * 建立抽象的单聊房间\n *\n * @return {@link ChatRoom }\n * @author qingmeng\n * @createTime: 2023/11/28 17:55:18...
import com.qingmeng.config.adapt.RoomAdapt; import com.qingmeng.dao.ChatFriendRoomDao; import com.qingmeng.dao.ChatRoomDao; import com.qingmeng.entity.ChatFriendRoom; import com.qingmeng.entity.ChatRoom; import com.qingmeng.service.ChatFriendRoomService; import com.qingmeng.utils.AssertUtils; import com.qingmeng.utils.CommonUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List;
4,974
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月27日 10:29:00 */ @Service public class ChatFriendRoomServiceImpl implements ChatFriendRoomService { @Resource private ChatFriendRoomDao chatFriendRoomDao; @Resource private ChatRoomDao chatRoomDao; /** * 保存聊天好友室 * * @param ids IDS * @author qingmeng * @createTime: 2023/12/01 16:36:25 */ @Override @Transactional(rollbackFor = Exception.class) public void saveChatFriendRoom(List<Long> ids) { AssertUtils.isNotEmpty(ids, "房间创建失败,好友数量不对"); AssertUtils.equal(ids.size(), 2, "房间创建失败,好友数量不对"); // 新增抽象好友房间记录 ChatRoom chatRoom = RoomAdapt.buildDefaultFriendRoom(); chatRoomDao.save(chatRoom); // 新增好友房间记录
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月27日 10:29:00 */ @Service public class ChatFriendRoomServiceImpl implements ChatFriendRoomService { @Resource private ChatFriendRoomDao chatFriendRoomDao; @Resource private ChatRoomDao chatRoomDao; /** * 保存聊天好友室 * * @param ids IDS * @author qingmeng * @createTime: 2023/12/01 16:36:25 */ @Override @Transactional(rollbackFor = Exception.class) public void saveChatFriendRoom(List<Long> ids) { AssertUtils.isNotEmpty(ids, "房间创建失败,好友数量不对"); AssertUtils.equal(ids.size(), 2, "房间创建失败,好友数量不对"); // 新增抽象好友房间记录 ChatRoom chatRoom = RoomAdapt.buildDefaultFriendRoom(); chatRoomDao.save(chatRoom); // 新增好友房间记录
ChatFriendRoom chatFriendRoom = RoomAdapt.buildChatFriendRoom(chatRoom.getId(), ids, CommonUtils.getKeyBySort(ids));
3
2023-11-07 16:04:55+00:00
8k
TianqiCS/AIChatLib-Fabric
src/main/java/com/citrusmc/aichatlib/StreamChatGPT.java
[ { "identifier": "ChatGroup", "path": "src/main/java/com/citrusmc/aichatlib/client/ChatGroup.java", "snippet": "public class ChatGroup {\n private static final Config CONFIG = ClientConfig.getInstance();\n private static final Logger LOGGER = LoggerFactory.getLogger(\"ChatBot-ChatGroup\");\n pri...
import com.citrusmc.aichatlib.client.ChatGroup; import com.citrusmc.aichatlib.configs.ClientConfig; import com.citrusmc.aichatlib.configs.Config; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.launchdarkly.eventsource.ConnectStrategy; import com.launchdarkly.eventsource.EventSource; import com.launchdarkly.eventsource.MessageEvent; import com.launchdarkly.eventsource.background.BackgroundEventHandler; import com.launchdarkly.eventsource.background.BackgroundEventSource; import com.launchdarkly.eventsource.background.ConnectionErrorHandler; import okhttp3.Headers; import okhttp3.RequestBody; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.HashMap; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import static com.citrusmc.aichatlib.ChatGPTUtil.API_URL;
4,263
package com.citrusmc.aichatlib; /** * StreamChatGPT class * <p> * This class is used to get the response from ChatGPT with stream feature. * <p> * Stream feature is used to get the response from ChatGPT in real time. * However, it does not allow to control the max tokens. */ public class StreamChatGPT { private static final Logger LOGGER = LoggerFactory.getLogger("ChatBot-StreamChatGPT"); private static final Config CONFIG = ClientConfig.getInstance(); private static final HashMap<String, StringBuffer> messagesBuffer = new HashMap<>(); private BackgroundEventSource eventSource; private volatile boolean isClosed = false; private int retry = 3; // Retry 3 times if the connection is closed unexpectedly private final Consumer<String> onSucceed; private final Consumer<String> onTimeout; /** * Constructor with message only * @param message the message * @param onSucceed the callback function when receiving the response * @param onTimeout the callback function when the request times out */ @Deprecated // Consider using a chat group public StreamChatGPT(String message, Consumer<String> onSucceed, Consumer<String> onTimeout) { this.onSucceed = onSucceed; this.onTimeout = onTimeout; createEventSource(message); } /** * Constructor with chat group and message * @param chatGroup the chat group * @param message the message * @param onSucceed the callback function when receiving the response * @param onTimeout the callback function when the request times out */ public StreamChatGPT(ChatGroup chatGroup, String message, Consumer<String> onSucceed, Consumer<String> onTimeout) { this.onSucceed = onSucceed; this.onTimeout = onTimeout; createEventSource(chatGroup, message); } /** * Constructor with chat group and chat history * @param chatGroup the chat group * @param chatHistory the chat history * @param onSucceed the callback function when receiving the response * @param onTimeout the callback function when the request times out */ public StreamChatGPT(ChatGroup chatGroup, ChatHistory chatHistory, Consumer<String> onSucceed, Consumer<String> onTimeout) { this.onSucceed = onSucceed; this.onTimeout = onTimeout; createEventSource(chatGroup, chatHistory); } public void start() { eventSource.start(); } public void stop() { eventSource.close(); } /** * Create the server-sent events source * @param message the message */ @Deprecated // Consider using a chat group public void createEventSource(String message) { Headers headers = ChatGPTUtil.createHeaders(); RequestBody body = ChatGPTUtil.createBody(message); createEventSource(headers, body); } /** * Create the server-sent events source with chat group and message * @param chatGroup the chat group * @param message the message */ public void createEventSource(ChatGroup chatGroup, String message) { Headers headers = ChatGPTUtil.createHeaders(); RequestBody body = ChatGPTUtil.createBody(chatGroup, message); createEventSource(headers, body); } /** * Create the server-sent events source with chat group and chat history * @param chatGroup the chat group * @param chatHistory the chat history */ public void createEventSource(ChatGroup chatGroup, ChatHistory chatHistory) { Headers headers = ChatGPTUtil.createHeaders(); RequestBody body = ChatGPTUtil.createBody(chatGroup, chatHistory); createEventSource(headers, body); } /** * Create the server-sent events source * @param headers the headers * @param body the request body */ public void createEventSource(Headers headers, RequestBody body) { boolean debug = (boolean) CONFIG.get("Settings.debug"); BackgroundEventHandler myHandler = new BackgroundEventHandler() { @Override public void onOpen() throws Exception {} @Override public void onClosed() throws Exception { if (isClosed) { if (debug) LOGGER.info("Connection closed by server"); } else { if (debug) LOGGER.info("Connection closed unexpectedly"); } } public void onMessage(String event, MessageEvent messageEvent) { String data = messageEvent.getData(); // Check if the response is the end of the conversation if (data.equals("[DONE]")) { isClosed = true; eventSource.close(); return; } // Check if the response is the end of the conversation JsonObject response = new Gson().fromJson(data, JsonObject.class); JsonElement finishReason = response.get("choices").getAsJsonArray() .get(0).getAsJsonObject() .get("finish_reason"); if (!finishReason.isJsonNull()) { isClosed = true; eventSource.close(); } // Add the new stream text to the buffer String id = response.get("id").getAsString(); if (!messagesBuffer.containsKey(id)) { messagesBuffer.put(id, new StringBuffer()); } String content = getResponse(response); StringBuffer buffer = messagesBuffer.get(id); // The end of stream, activate the callback function if (content == null) { onSucceed.accept(buffer.toString()); messagesBuffer.remove(id); return; } buffer.append(content); // Check if the buffer contains a line break, if so, activate the callback function and send the message before the line break int linebreakIndex = buffer.indexOf("\n"); if (linebreakIndex > -1) { onSucceed.accept(buffer.substring(0, linebreakIndex)); buffer.delete(0, linebreakIndex + 1); } } @Override public void onComment(String comment) throws Exception {} @Override public void onError(Throwable t) {} }; // Connection error handler ConnectionErrorHandler errorHandler = t -> { // Retry 3 times if the connection is closed unexpectedly // Do not retry if the connection is closed by our end ConnectionErrorHandler.Action action = (isClosed || retry <= 0) ? ConnectionErrorHandler.Action.SHUTDOWN : ConnectionErrorHandler.Action.PROCEED; if (debug) LOGGER.info(String.format("Connection error [%s %d]: %s", action, retry, t.getMessage())); if (action == ConnectionErrorHandler.Action.SHUTDOWN && retry <= 0) { onTimeout.accept(t.getMessage()); } retry -= 1; return action; }; // Create the server-sent events source this.eventSource = new BackgroundEventSource.Builder(myHandler, new EventSource.Builder(
package com.citrusmc.aichatlib; /** * StreamChatGPT class * <p> * This class is used to get the response from ChatGPT with stream feature. * <p> * Stream feature is used to get the response from ChatGPT in real time. * However, it does not allow to control the max tokens. */ public class StreamChatGPT { private static final Logger LOGGER = LoggerFactory.getLogger("ChatBot-StreamChatGPT"); private static final Config CONFIG = ClientConfig.getInstance(); private static final HashMap<String, StringBuffer> messagesBuffer = new HashMap<>(); private BackgroundEventSource eventSource; private volatile boolean isClosed = false; private int retry = 3; // Retry 3 times if the connection is closed unexpectedly private final Consumer<String> onSucceed; private final Consumer<String> onTimeout; /** * Constructor with message only * @param message the message * @param onSucceed the callback function when receiving the response * @param onTimeout the callback function when the request times out */ @Deprecated // Consider using a chat group public StreamChatGPT(String message, Consumer<String> onSucceed, Consumer<String> onTimeout) { this.onSucceed = onSucceed; this.onTimeout = onTimeout; createEventSource(message); } /** * Constructor with chat group and message * @param chatGroup the chat group * @param message the message * @param onSucceed the callback function when receiving the response * @param onTimeout the callback function when the request times out */ public StreamChatGPT(ChatGroup chatGroup, String message, Consumer<String> onSucceed, Consumer<String> onTimeout) { this.onSucceed = onSucceed; this.onTimeout = onTimeout; createEventSource(chatGroup, message); } /** * Constructor with chat group and chat history * @param chatGroup the chat group * @param chatHistory the chat history * @param onSucceed the callback function when receiving the response * @param onTimeout the callback function when the request times out */ public StreamChatGPT(ChatGroup chatGroup, ChatHistory chatHistory, Consumer<String> onSucceed, Consumer<String> onTimeout) { this.onSucceed = onSucceed; this.onTimeout = onTimeout; createEventSource(chatGroup, chatHistory); } public void start() { eventSource.start(); } public void stop() { eventSource.close(); } /** * Create the server-sent events source * @param message the message */ @Deprecated // Consider using a chat group public void createEventSource(String message) { Headers headers = ChatGPTUtil.createHeaders(); RequestBody body = ChatGPTUtil.createBody(message); createEventSource(headers, body); } /** * Create the server-sent events source with chat group and message * @param chatGroup the chat group * @param message the message */ public void createEventSource(ChatGroup chatGroup, String message) { Headers headers = ChatGPTUtil.createHeaders(); RequestBody body = ChatGPTUtil.createBody(chatGroup, message); createEventSource(headers, body); } /** * Create the server-sent events source with chat group and chat history * @param chatGroup the chat group * @param chatHistory the chat history */ public void createEventSource(ChatGroup chatGroup, ChatHistory chatHistory) { Headers headers = ChatGPTUtil.createHeaders(); RequestBody body = ChatGPTUtil.createBody(chatGroup, chatHistory); createEventSource(headers, body); } /** * Create the server-sent events source * @param headers the headers * @param body the request body */ public void createEventSource(Headers headers, RequestBody body) { boolean debug = (boolean) CONFIG.get("Settings.debug"); BackgroundEventHandler myHandler = new BackgroundEventHandler() { @Override public void onOpen() throws Exception {} @Override public void onClosed() throws Exception { if (isClosed) { if (debug) LOGGER.info("Connection closed by server"); } else { if (debug) LOGGER.info("Connection closed unexpectedly"); } } public void onMessage(String event, MessageEvent messageEvent) { String data = messageEvent.getData(); // Check if the response is the end of the conversation if (data.equals("[DONE]")) { isClosed = true; eventSource.close(); return; } // Check if the response is the end of the conversation JsonObject response = new Gson().fromJson(data, JsonObject.class); JsonElement finishReason = response.get("choices").getAsJsonArray() .get(0).getAsJsonObject() .get("finish_reason"); if (!finishReason.isJsonNull()) { isClosed = true; eventSource.close(); } // Add the new stream text to the buffer String id = response.get("id").getAsString(); if (!messagesBuffer.containsKey(id)) { messagesBuffer.put(id, new StringBuffer()); } String content = getResponse(response); StringBuffer buffer = messagesBuffer.get(id); // The end of stream, activate the callback function if (content == null) { onSucceed.accept(buffer.toString()); messagesBuffer.remove(id); return; } buffer.append(content); // Check if the buffer contains a line break, if so, activate the callback function and send the message before the line break int linebreakIndex = buffer.indexOf("\n"); if (linebreakIndex > -1) { onSucceed.accept(buffer.substring(0, linebreakIndex)); buffer.delete(0, linebreakIndex + 1); } } @Override public void onComment(String comment) throws Exception {} @Override public void onError(Throwable t) {} }; // Connection error handler ConnectionErrorHandler errorHandler = t -> { // Retry 3 times if the connection is closed unexpectedly // Do not retry if the connection is closed by our end ConnectionErrorHandler.Action action = (isClosed || retry <= 0) ? ConnectionErrorHandler.Action.SHUTDOWN : ConnectionErrorHandler.Action.PROCEED; if (debug) LOGGER.info(String.format("Connection error [%s %d]: %s", action, retry, t.getMessage())); if (action == ConnectionErrorHandler.Action.SHUTDOWN && retry <= 0) { onTimeout.accept(t.getMessage()); } retry -= 1; return action; }; // Create the server-sent events source this.eventSource = new BackgroundEventSource.Builder(myHandler, new EventSource.Builder(
ConnectStrategy.http(URI.create(API_URL))
3
2023-11-06 00:04:54+00:00
8k
Griefed/AddEmAll
buildSrc/src/main/java/de/griefed/generation/generator/CodeGenerator.java
[ { "identifier": "BlockDefinition", "path": "buildSrc/src/main/java/de/griefed/generation/blocks/BlockDefinition.java", "snippet": "public class BlockDefinition {\n\n public BlockDefinition(String id,\n String translation,\n String material,\n ...
import com.fasterxml.jackson.databind.ObjectMapper; import de.griefed.generation.blocks.BlockDefinition; import de.griefed.generation.blocks.BlockDefinitionParser; import de.griefed.generation.blocks.TextureScaler; import org.gradle.api.Project; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.regex.Pattern;
3,799
"model": "MODID:block/generated/MATERIAL/BLOCKID_stairs", "y": 180, "uvlock": true }, "facing=west,half=top,shape=inner_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "x": 180, "y": 180, "uvlock": true }, "facing=west,half=top,shape=inner_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "x": 180, "y": 270, "uvlock": true }, "facing=west,half=top,shape=outer_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "x": 180, "y": 180, "uvlock": true }, "facing=west,half=top,shape=outer_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "x": 180, "y": 270, "uvlock": true }, "facing=west,half=top,shape=straight": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs", "x": 180, "y": 180, "uvlock": true } } } """; private static final String BLOCK_MODELS_CONTENT_TEMPLATE = """ { "parent": "block/cube_all", "textures": { "all": "%s:block/generated/%s/%s_block" } } """; private static final String BLOCK_MODELS_SLAB_CONTENT_TEMPLATE = """ { "parent": "minecraft:block/slab", "textures": { "bottom": "%s:block/generated/%s/%s_block", "top": "%s:block/generated/%s/%s_block", "side": "%s:block/generated/%s/%s_block" } } """; private static final String BLOCK_MODELS_STAIRS_TEMPLATE = """ { "parent": "minecraft:block/stairs", "textures": { "bottom": "%s:block/generated/%s/%s_block", "top": "%s:block/generated/%s/%s_block", "side": "%s:block/generated/%s/%s_block" } } """; private static final String BLOCK_MODELS_STAIRS_INNER_TEMPLATE = """ { "parent": "minecraft:block/inner_stairs", "textures": { "bottom": "%s:block/generated/%s/%s_block", "top": "%s:block/generated/%s/%s_block", "side": "%s:block/generated/%s/%s_block" } } """; private static final String BLOCK_MODELS_STAIRS_OUTER_TEMPLATE = """ { "parent": "minecraft:block/outer_stairs", "textures": { "bottom": "%s:block/generated/%s/%s_block", "top": "%s:block/generated/%s/%s_block", "side": "%s:block/generated/%s/%s_block" } } """; private static final String BLOCK_MODELS_SLAB_TOP_CONTENT_TEMPLATE = """ { "parent": "minecraft:block/slab_top", "textures": { "bottom": "%s:block/generated/%s/%s_block", "top": "%s:block/generated/%s/%s_block", "side": "%s:block/generated/%s/%s_block" } } """; private static final String BLOCK_MODELS_ITEM_CONTENT_TEMPLATE = """ { "parent": "%s:block/generated/%s/%s_block" } """; private static final String BLOCK_MODELS_SLAB_ITEM_CONTENT_TEMPLATE = """ { "parent": "%s:block/generated/%s/%s_slab" } """; private static final String BLOCK_MODELS_STAIRS_ITEM_CONTENT_TEMPLATE = """ { "parent": "%s:block/generated/%s/%s_stairs" } """; private static final String TRANSLATION_CONTENT_TEMPLATE = """ { "DO.NOT.EDIT.MANUALLY.BEGIN": "BEGIN", GENERATED_TRANSLATION_CODE "DO.NOT.EDIT.MANUALLY.END": "END" } """; private final Project project; private final String modName; private final String subName;
package de.griefed.generation.generator; @SuppressWarnings("unused") public abstract class CodeGenerator { public static final Pattern GENERATED_CODE_PATTERN = Pattern.compile("/\\*###GENERATED CODE - DO NOT EDIT - MANUALLY EDITED CODE WILL BE LOST###\\*/.*/\\*###GENERATED CODE - DO NOT EDIT - MANUALLY EDITED CODE WILL BE LOST###\\*/", Pattern.DOTALL); public static final Pattern LANG_REPLACE = Pattern.compile("\"DO\\.NOT\\.EDIT\\.MANUALLY\\.BEGIN\": \"BEGIN\".*\"DO\\.NOT\\.EDIT\\.MANUALLY\\.END\": \"END\"", Pattern.DOTALL); public static final String BLOCKSTATES_FILETEMPLATE = "generated/%s/%s_block.json"; public static final String BLOCKSTATES_SLAB_FILETEMPLATE = "generated/%s/%s_slab.json"; public static final String BLOCKSTATES_STAIRS_FILETEMPLATE = "generated/%s/%s_stairs.json"; public static final String BLOCK_MODEL_FILETEMPLATE = "generated/%s/%s_block.json"; public static final String BLOCK_MODEL_SLAB_FILETEMPLATE = "generated/%s/%s_slab.json"; public static final String BLOCK_MODEL_SLAB_TOP_FILETEMPLATE = "generated/%s/%s_slab_top.json"; public static final String BLOCK_MODEL_STAIRS_FILETEMPLATE = "generated/%s/%s_stairs.json"; public static final String BLOCK_MODEL_STAIRS_INNER_FILETEMPLATE = "generated/%s/%s_stairs_inner.json"; public static final String BLOCK_MODEL_STAIRS_OUTER_FILETEMPLATE = "generated/%s/%s_stairs_outer.json"; public static final String ITEM_BLOCK_MODEL_FILETEMPLATE = "generated/%s/%s.json"; public static final String ITEM_BLOCK_MODEL_SLAB_FILETEMPLATE = "generated/%s/%s_slab.json"; public static final String ITEM_BLOCK_MODEL_STAIRS_FILETEMPLATE = "generated/%s/%s_stairs.json"; public static final String BLOCK_TEXTURE_FILETEMPLATE = "generated/%s/%s_block.png"; public static final String ITEM_TRANSLATION_KEY_TEMPLATE = "item.%s.generated.%s.%s_block"; public static final String ITEM_SLAB_TRANSLATION_KEY_TEMPLATE = "item.%s.generated.%s.%s_slab"; public static final String ITEM_STAIRS_TRANSLATION_KEY_TEMPLATE = "item.%s.generated.%s.%s_stairs"; public static final String BLOCK_TRANSLATION_KEY_TEMPLATE = "block.%s.generated.%s.%s_block"; public static final String BLOCK_SLAB_TRANSLATION_KEY_TEMPLATE = "block.%s.generated.%s.%s_slab"; public static final String BLOCK_STAIRS_TRANSLATION_KEY_TEMPLATE = "block.%s.generated.%s.%s_stairs"; public static final String ANIMATION_CONTENT_TEMPLATE = """ { "animation": {} } """; private static final String BLOCKSTATE_CONTENT_TEMPLATE = """ { "variants": { "": { "model": "%s:block/generated/%s/%s_block" } } } """; private static final String BLOCKSTATE_SLAB_CONTENT_TEMPLATE = """ { "variants": { "type=bottom": { "model": "%s:block/generated/%s/%s_slab" }, "type=double": { "model": "%s:block/generated/%s/%s_block" }, "type=top": { "model": "%s:block/generated/%s/%s_slab_top" } } } """; private static final String BLOCKSTATE_STAIRS_CONTENT_TEMPLATE = """ { "variants": { "facing=east,half=bottom,shape=inner_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "y": 270, "uvlock": true }, "facing=east,half=bottom,shape=inner_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner" }, "facing=east,half=bottom,shape=outer_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "y": 270, "uvlock": true }, "facing=east,half=bottom,shape=outer_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer" }, "facing=east,half=bottom,shape=straight": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs" }, "facing=east,half=top,shape=inner_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "x": 180, "uvlock": true }, "facing=east,half=top,shape=inner_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "x": 180, "y": 90, "uvlock": true }, "facing=east,half=top,shape=outer_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "x": 180, "uvlock": true }, "facing=east,half=top,shape=outer_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "x": 180, "y": 90, "uvlock": true }, "facing=east,half=top,shape=straight": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs", "x": 180, "uvlock": true }, "facing=north,half=bottom,shape=inner_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "y": 180, "uvlock": true }, "facing=north,half=bottom,shape=inner_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "y": 270, "uvlock": true }, "facing=north,half=bottom,shape=outer_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "y": 180, "uvlock": true }, "facing=north,half=bottom,shape=outer_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "y": 270, "uvlock": true }, "facing=north,half=bottom,shape=straight": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs", "y": 270, "uvlock": true }, "facing=north,half=top,shape=inner_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "x": 180, "y": 270, "uvlock": true }, "facing=north,half=top,shape=inner_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "x": 180, "uvlock": true }, "facing=north,half=top,shape=outer_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "x": 180, "y": 270, "uvlock": true }, "facing=north,half=top,shape=outer_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "x": 180, "uvlock": true }, "facing=north,half=top,shape=straight": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs", "x": 180, "y": 270, "uvlock": true }, "facing=south,half=bottom,shape=inner_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner" }, "facing=south,half=bottom,shape=inner_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "y": 90, "uvlock": true }, "facing=south,half=bottom,shape=outer_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer" }, "facing=south,half=bottom,shape=outer_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "y": 90, "uvlock": true }, "facing=south,half=bottom,shape=straight": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs", "y": 90, "uvlock": true }, "facing=south,half=top,shape=inner_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "x": 180, "y": 90, "uvlock": true }, "facing=south,half=top,shape=inner_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "x": 180, "y": 180, "uvlock": true }, "facing=south,half=top,shape=outer_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "x": 180, "y": 90, "uvlock": true }, "facing=south,half=top,shape=outer_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "x": 180, "y": 180, "uvlock": true }, "facing=south,half=top,shape=straight": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs", "x": 180, "y": 90, "uvlock": true }, "facing=west,half=bottom,shape=inner_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "y": 90, "uvlock": true }, "facing=west,half=bottom,shape=inner_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "y": 180, "uvlock": true }, "facing=west,half=bottom,shape=outer_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "y": 90, "uvlock": true }, "facing=west,half=bottom,shape=outer_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "y": 180, "uvlock": true }, "facing=west,half=bottom,shape=straight": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs", "y": 180, "uvlock": true }, "facing=west,half=top,shape=inner_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "x": 180, "y": 180, "uvlock": true }, "facing=west,half=top,shape=inner_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_inner", "x": 180, "y": 270, "uvlock": true }, "facing=west,half=top,shape=outer_left": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "x": 180, "y": 180, "uvlock": true }, "facing=west,half=top,shape=outer_right": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs_outer", "x": 180, "y": 270, "uvlock": true }, "facing=west,half=top,shape=straight": { "model": "MODID:block/generated/MATERIAL/BLOCKID_stairs", "x": 180, "y": 180, "uvlock": true } } } """; private static final String BLOCK_MODELS_CONTENT_TEMPLATE = """ { "parent": "block/cube_all", "textures": { "all": "%s:block/generated/%s/%s_block" } } """; private static final String BLOCK_MODELS_SLAB_CONTENT_TEMPLATE = """ { "parent": "minecraft:block/slab", "textures": { "bottom": "%s:block/generated/%s/%s_block", "top": "%s:block/generated/%s/%s_block", "side": "%s:block/generated/%s/%s_block" } } """; private static final String BLOCK_MODELS_STAIRS_TEMPLATE = """ { "parent": "minecraft:block/stairs", "textures": { "bottom": "%s:block/generated/%s/%s_block", "top": "%s:block/generated/%s/%s_block", "side": "%s:block/generated/%s/%s_block" } } """; private static final String BLOCK_MODELS_STAIRS_INNER_TEMPLATE = """ { "parent": "minecraft:block/inner_stairs", "textures": { "bottom": "%s:block/generated/%s/%s_block", "top": "%s:block/generated/%s/%s_block", "side": "%s:block/generated/%s/%s_block" } } """; private static final String BLOCK_MODELS_STAIRS_OUTER_TEMPLATE = """ { "parent": "minecraft:block/outer_stairs", "textures": { "bottom": "%s:block/generated/%s/%s_block", "top": "%s:block/generated/%s/%s_block", "side": "%s:block/generated/%s/%s_block" } } """; private static final String BLOCK_MODELS_SLAB_TOP_CONTENT_TEMPLATE = """ { "parent": "minecraft:block/slab_top", "textures": { "bottom": "%s:block/generated/%s/%s_block", "top": "%s:block/generated/%s/%s_block", "side": "%s:block/generated/%s/%s_block" } } """; private static final String BLOCK_MODELS_ITEM_CONTENT_TEMPLATE = """ { "parent": "%s:block/generated/%s/%s_block" } """; private static final String BLOCK_MODELS_SLAB_ITEM_CONTENT_TEMPLATE = """ { "parent": "%s:block/generated/%s/%s_slab" } """; private static final String BLOCK_MODELS_STAIRS_ITEM_CONTENT_TEMPLATE = """ { "parent": "%s:block/generated/%s/%s_stairs" } """; private static final String TRANSLATION_CONTENT_TEMPLATE = """ { "DO.NOT.EDIT.MANUALLY.BEGIN": "BEGIN", GENERATED_TRANSLATION_CODE "DO.NOT.EDIT.MANUALLY.END": "END" } """; private final Project project; private final String modName; private final String subName;
private final BlockDefinitionParser blockDefinitionParser;
1
2023-11-06 12:50:10+00:00
8k
arunk140/ollm.chat
app/src/main/java/com/arunk140/ollmchat/ui/home/HomeFragment.java
[ { "identifier": "Chat", "path": "app/src/main/java/com/arunk140/ollmchat/Adapter/Chat.java", "snippet": "public class Chat extends\n RecyclerView.Adapter<Chat.ViewHolder>{\n ArrayList<Message> msgs;\n\n public Chat(ArrayList<Message> msgList) {\n msgs = msgList;\n }\n\n @NonNul...
import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.arunk140.ollmchat.Adapter.Chat; import com.arunk140.ollmchat.Config.Settings; import com.arunk140.ollmchat.DB.Manager; import com.arunk140.ollmchat.LLM.ChatCompletionChunk; import com.arunk140.ollmchat.LLM.ChatCompletionRequest; import com.arunk140.ollmchat.LLM.GPTViewModel; import com.arunk140.ollmchat.LLM.Message; import com.arunk140.ollmchat.MainActivity; import com.arunk140.ollmchat.R; import com.arunk140.ollmchat.SettingsActivity; import com.arunk140.ollmchat.databinding.FragmentHomeBinding; import java.util.ArrayList; import java.util.Collections; import java.util.Objects;
5,065
ViewGroup container, Bundle savedInstanceState) { binding = FragmentHomeBinding.inflate(inflater, container, false); View root = binding.getRoot(); disableSending = false; messages = new ArrayList<>(); chatAdapter = new Chat(messages); waitingForLLM = binding.waitingForLLM; chatListView = binding.chatList; msgText = binding.editTextText; settingsBtn = binding.settingsBtn; refreshBtn = binding.refreshBtn; drawerBtn = binding.drawerBtn; noMessages = binding.noMessages; actionBtn = binding.stopBtn; regenBtn = binding.regenBtn; manager = new Manager(getContext()); manager.open(); settings = manager.getSettings(); manager.close(); settingsBtn.setOnClickListener(v -> { Intent myIntent = new Intent(requireActivity(), SettingsActivity.class); requireActivity().startActivity(myIntent); }); drawerBtn.setOnClickListener(v -> { MainActivity x = (MainActivity)getActivity(); x.toggleDrawer(); }); refreshBtn.setOnClickListener(v -> { restart(); }); DividerItemDecoration dId = new DividerItemDecoration(requireActivity(), DividerItemDecoration.VERTICAL); dId.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(requireActivity(), R.drawable.spacer))); chatListView.addItemDecoration(dId); chatListView.setAdapter(chatAdapter); linearLayoutManager = new LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, true); chatListView.setLayoutManager(linearLayoutManager); mainHandler = new Handler(Looper.getMainLooper()); viewModel = new ViewModelProvider(this).get(GPTViewModel.class); viewModel.dataLiveData.observe(requireActivity(), this::updateTextView); viewModel.loadingLiveData.observe(requireActivity(), this::setLoaderState); viewModel.errorLiveData.observe(requireActivity(), this::checkErrors); actionBtn.setOnClickListener(v -> { if (currentInvocation != null) { currentInvocation.interrupt(); // Interrupt the thread } }); regenBtn.setOnClickListener(v -> { regenBtn.setVisibility(View.GONE); if (messages.size() > 1) { messages.remove(0); chatAdapter.notifyItemRemoved(0); sendToLLM(messages.get(0).getContent(), false); } }); msgText.setOnKeyListener((v, keyCode, event) -> { if (disableSending) { return true; } if (messages.size() > 0) { noMessages.setVisibility(View.GONE); } else { noMessages.setVisibility(View.VISIBLE); } if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { String inputMsg = msgText.getText().toString().trim(); sendToLLM(inputMsg, true); } return true; }); // final TextView textView = binding.textHome; // homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText); return root; } private void sendToLLM(String inputMsg, boolean addNewMessage) { if (inputMsg.equals("")) { return; } if (inputMsg.equals("clear")) { restart(); return; } if (addNewMessage) { if (messages.size() == 0 && settings.systemPrompt.length() > 0) { messages.add(0, new Message("user", inputMsg)); messages.add(1, new Message("system", settings.systemPrompt)); chatAdapter.notifyItemRangeInserted(0,2); } else { messages.add(0, new Message("user", inputMsg)); chatAdapter.notifyItemInserted(0); } } msgText.setText(""); currentRunnable = () -> { if (Thread.interrupted()) { return; } ChatCompletionRequest request = new ChatCompletionRequest(reorderMessages(messages), settings, true); viewModel.loadData(request, mainHandler, settings, getActivity()); }; currentInvocation = new Thread(currentRunnable); currentInvocation.start(); }
package com.arunk140.ollmchat.ui.home; public class HomeFragment extends Fragment { private FragmentHomeBinding binding; EditText msgText; TextView noMessages; boolean disableSending; ProgressBar waitingForLLM; ImageButton settingsBtn; ImageButton refreshBtn; ImageButton drawerBtn; ImageButton actionBtn; Button regenBtn; RecyclerView chatListView; LinearLayoutManager linearLayoutManager; ArrayList<Message> messages; Chat chatAdapter; private Handler mainHandler; private GPTViewModel viewModel; Manager manager; Settings settings; Thread currentInvocation; Runnable currentRunnable; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentHomeBinding.inflate(inflater, container, false); View root = binding.getRoot(); disableSending = false; messages = new ArrayList<>(); chatAdapter = new Chat(messages); waitingForLLM = binding.waitingForLLM; chatListView = binding.chatList; msgText = binding.editTextText; settingsBtn = binding.settingsBtn; refreshBtn = binding.refreshBtn; drawerBtn = binding.drawerBtn; noMessages = binding.noMessages; actionBtn = binding.stopBtn; regenBtn = binding.regenBtn; manager = new Manager(getContext()); manager.open(); settings = manager.getSettings(); manager.close(); settingsBtn.setOnClickListener(v -> { Intent myIntent = new Intent(requireActivity(), SettingsActivity.class); requireActivity().startActivity(myIntent); }); drawerBtn.setOnClickListener(v -> { MainActivity x = (MainActivity)getActivity(); x.toggleDrawer(); }); refreshBtn.setOnClickListener(v -> { restart(); }); DividerItemDecoration dId = new DividerItemDecoration(requireActivity(), DividerItemDecoration.VERTICAL); dId.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(requireActivity(), R.drawable.spacer))); chatListView.addItemDecoration(dId); chatListView.setAdapter(chatAdapter); linearLayoutManager = new LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, true); chatListView.setLayoutManager(linearLayoutManager); mainHandler = new Handler(Looper.getMainLooper()); viewModel = new ViewModelProvider(this).get(GPTViewModel.class); viewModel.dataLiveData.observe(requireActivity(), this::updateTextView); viewModel.loadingLiveData.observe(requireActivity(), this::setLoaderState); viewModel.errorLiveData.observe(requireActivity(), this::checkErrors); actionBtn.setOnClickListener(v -> { if (currentInvocation != null) { currentInvocation.interrupt(); // Interrupt the thread } }); regenBtn.setOnClickListener(v -> { regenBtn.setVisibility(View.GONE); if (messages.size() > 1) { messages.remove(0); chatAdapter.notifyItemRemoved(0); sendToLLM(messages.get(0).getContent(), false); } }); msgText.setOnKeyListener((v, keyCode, event) -> { if (disableSending) { return true; } if (messages.size() > 0) { noMessages.setVisibility(View.GONE); } else { noMessages.setVisibility(View.VISIBLE); } if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { String inputMsg = msgText.getText().toString().trim(); sendToLLM(inputMsg, true); } return true; }); // final TextView textView = binding.textHome; // homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText); return root; } private void sendToLLM(String inputMsg, boolean addNewMessage) { if (inputMsg.equals("")) { return; } if (inputMsg.equals("clear")) { restart(); return; } if (addNewMessage) { if (messages.size() == 0 && settings.systemPrompt.length() > 0) { messages.add(0, new Message("user", inputMsg)); messages.add(1, new Message("system", settings.systemPrompt)); chatAdapter.notifyItemRangeInserted(0,2); } else { messages.add(0, new Message("user", inputMsg)); chatAdapter.notifyItemInserted(0); } } msgText.setText(""); currentRunnable = () -> { if (Thread.interrupted()) { return; } ChatCompletionRequest request = new ChatCompletionRequest(reorderMessages(messages), settings, true); viewModel.loadData(request, mainHandler, settings, getActivity()); }; currentInvocation = new Thread(currentRunnable); currentInvocation.start(); }
private void updateTextView(ChatCompletionChunk chunk) {
3
2023-11-01 00:44:14+00:00
8k
MonstrousSoftware/Tut3D
core/src/main/java/com/monstrous/tut3d/GameScreen.java
[ { "identifier": "CookBehaviour", "path": "core/src/main/java/com/monstrous/tut3d/behaviours/CookBehaviour.java", "snippet": "public class CookBehaviour extends Behaviour {\n\n private static final float SHOOT_INTERVAL = 2f; // seconds between shots\n\n private float shootTimer;\n private fi...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.ScreenAdapter; import com.badlogic.gdx.controllers.Controllers; import com.badlogic.gdx.math.Vector3; import com.monstrous.tut3d.behaviours.CookBehaviour; import com.monstrous.tut3d.gui.GUI; import com.monstrous.tut3d.inputs.MyControllerAdapter; import com.monstrous.tut3d.physics.CollisionShapeType; import com.monstrous.tut3d.views.GameView; import com.monstrous.tut3d.views.GridView; import com.monstrous.tut3d.nav.NavMeshView; import com.monstrous.tut3d.physics.PhysicsView;
6,824
package com.monstrous.tut3d; public class GameScreen extends ScreenAdapter { private GameView gameView; private GridView gridView; private GameView gunView;
package com.monstrous.tut3d; public class GameScreen extends ScreenAdapter { private GameView gameView; private GridView gridView; private GameView gunView;
private PhysicsView physicsView;
7
2023-11-04 13:15:48+00:00
8k
Einzieg/EinziegCloud
src/main/java/com/cloud/util/interceptor/RepeatRequestIntercept.java
[ { "identifier": "IPUtil", "path": "src/main/java/com/cloud/util/IPUtil.java", "snippet": "@Slf4j\npublic class IPUtil {\n\tprivate static final String IP_UTILS_FLAG = \",\";\n\tprivate static final String UNKNOWN = \"unknown\";\n\tprivate static final String LOCALHOST_IP = \"0:0:0:0:0:0:0:1\";\n\tprivat...
import com.cloud.util.IPUtil; import com.cloud.util.RedisUtil; import com.cloud.util.msg.Msg; import com.cloud.util.msg.ResultCode; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import java.util.Objects;
6,540
package com.cloud.util.interceptor; /** * 接口防刷拦截器 * * @author Einzieg * @date 2023/11/21 */ @Slf4j @Component @RequiredArgsConstructor public class RepeatRequestIntercept implements HandlerInterceptor { private static final int MAX_REQUEST_COUNT = 60; private static final long EXPIRE_TIME = 60;
package com.cloud.util.interceptor; /** * 接口防刷拦截器 * * @author Einzieg * @date 2023/11/21 */ @Slf4j @Component @RequiredArgsConstructor public class RepeatRequestIntercept implements HandlerInterceptor { private static final int MAX_REQUEST_COUNT = 60; private static final long EXPIRE_TIME = 60;
private final RedisUtil redisUtil;
1
2023-11-07 07:27:53+00:00
8k
AbarcaJ/VisibilityToggle
src/dev/cleusgamer201/visibilitytoggle/database/DBManager.java
[ { "identifier": "Main", "path": "src/dev/cleusgamer201/visibilitytoggle/Main.java", "snippet": "public class Main extends JavaPlugin implements Listener {\n\n private static Main instance;\n public static Main getInstance() {\n return instance;\n }\n\n private static String prefix;\n ...
import java.sql.ResultSet; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import dev.cleusgamer201.visibilitytoggle.Main; import dev.cleusgamer201.visibilitytoggle.Utils; import dev.cleusgamer201.visibilitytoggle.utils.Config;
6,197
package dev.cleusgamer201.visibilitytoggle.database; public class DBManager implements Listener { private boolean shutdown = false; private final HashMap<Player, Cache> cached = new HashMap<>(); private DB db; private final Main plugin; public DBManager(Main plugin) { this.plugin = plugin; load(); } private void load() { final DBSettings.Builder builder = new DBSettings.Builder();
package dev.cleusgamer201.visibilitytoggle.database; public class DBManager implements Listener { private boolean shutdown = false; private final HashMap<Player, Cache> cached = new HashMap<>(); private DB db; private final Main plugin; public DBManager(Main plugin) { this.plugin = plugin; load(); } private void load() { final DBSettings.Builder builder = new DBSettings.Builder();
final Config config = plugin.getConfig();
2
2023-11-02 15:00:52+00:00
8k
1711680493/SPay
app/src/main/java/shendi/pay/activity/MainActivity.java
[ { "identifier": "Application", "path": "app/src/main/java/shendi/pay/Application.java", "snippet": "public class Application extends android.app.Application {\n\n /** 唯一实例 */\n private static Application instance;\n\n private static SLog log = SLog.getLogger(Application.class.getName());\n\n ...
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.core.app.NotificationManagerCompat; import shendi.pay.Application; import shendi.pay.R; import shendi.pay.SLog; import shendi.pay.service.NotifyPayService; import shendi.pay.util.ApiUtil;
5,215
package shendi.pay.activity; /** * 创建时间:2023/11/8 * @author Shendi */ public class MainActivity extends Activity { private static SLog log = SLog.getLogger(MainActivity.class.getName()); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initUI(); //启动服务
package shendi.pay.activity; /** * 创建时间:2023/11/8 * @author Shendi */ public class MainActivity extends Activity { private static SLog log = SLog.getLogger(MainActivity.class.getName()); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initUI(); //启动服务
startForegroundService(new Intent(this, NotifyPayService.class));
2
2023-11-09 14:00:45+00:00
8k
hlysine/create_power_loader
src/main/java/com/hlysine/create_power_loader/content/trains/StationChunkLoader.java
[ { "identifier": "CPLConfigs", "path": "src/main/java/com/hlysine/create_power_loader/config/CPLConfigs.java", "snippet": "@SuppressWarnings(\"unused\")\n@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)\npublic class CPLConfigs {\n\n public static void register(ModLoadingContext context) ...
import com.hlysine.create_power_loader.config.CPLConfigs; import com.hlysine.create_power_loader.content.ChunkLoadManager; import com.hlysine.create_power_loader.content.ChunkLoadManager.LoadedChunkPos; import com.hlysine.create_power_loader.content.ChunkLoader; import com.hlysine.create_power_loader.content.LoaderMode; import com.hlysine.create_power_loader.content.LoaderType; import com.simibubi.create.content.trains.graph.TrackGraph; import com.simibubi.create.content.trains.station.GlobalStation; import com.simibubi.create.foundation.utility.NBTHelper; import com.simibubi.create.foundation.utility.Pair; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtUtils; import net.minecraft.nbt.Tag; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.Level; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*;
4,686
package com.hlysine.create_power_loader.content.trains; public class StationChunkLoader implements ChunkLoader { private final GlobalStation station; public final Set<AttachedLoader> attachments = new HashSet<>(); private final Map<ResourceKey<Level>, Set<LoadedChunkPos>> reclaimedChunks = new HashMap<>(); public final Set<LoadedChunkPos> forcedChunks = new HashSet<>(); private boolean registered = false; public StationChunkLoader(GlobalStation station) { this.station = station; } @Override public @NotNull Set<LoadedChunkPos> getForcedChunks() { return forcedChunks; } @Override public LoaderMode getLoaderMode() { return LoaderMode.STATION; } @Override public LoaderType getLoaderType() { for (AttachedLoader attachment : attachments) { if (attachment.type() == LoaderType.BRASS) return LoaderType.BRASS; } return LoaderType.ANDESITE; } @Override public @Nullable Pair<ResourceLocation, BlockPos> getLocation() { return Pair.of( station.edgeLocation.getFirst().dimension.location(), BlockPos.containing(station.edgeLocation.getFirst().getLocation().add(station.edgeLocation.getSecond().getLocation()).scale(0.5)) ); } @Override public void addToManager() { if (!registered) { ChunkLoader.super.addToManager(); registered = true; } } public void tick(TrackGraph graph, boolean preTrains) { if (preTrains) return; Level level = ChunkLoadManager.tickLevel; if (level == null || level.isClientSide()) return; addToManager(); ChunkLoadManager.reclaimChunks(level, station.id, reclaimedChunks); if (attachments.isEmpty() || station.getPresentTrain() == null) { if (!forcedChunks.isEmpty()) ChunkLoadManager.unforceAllChunks(level.getServer(), station.id, forcedChunks); return; } // sanitize in case of read/write errors attachments.removeIf(a -> a.pos.distManhattan(station.blockEntityPos) > 1); Set<LoadedChunkPos> loadTargets = new HashSet<>(); for (AttachedLoader attachment : attachments) { if (isEnabledForStation(attachment.type())) loadTargets.add(new LoadedChunkPos(station.blockEntityDimension.location(), new ChunkPos(attachment.pos()))); } ChunkLoadManager.updateForcedChunks(level.getServer(), loadTargets, station.id, 2, forcedChunks); } public static boolean isEnabledForStation(LoaderType type) { if (type == LoaderType.ANDESITE)
package com.hlysine.create_power_loader.content.trains; public class StationChunkLoader implements ChunkLoader { private final GlobalStation station; public final Set<AttachedLoader> attachments = new HashSet<>(); private final Map<ResourceKey<Level>, Set<LoadedChunkPos>> reclaimedChunks = new HashMap<>(); public final Set<LoadedChunkPos> forcedChunks = new HashSet<>(); private boolean registered = false; public StationChunkLoader(GlobalStation station) { this.station = station; } @Override public @NotNull Set<LoadedChunkPos> getForcedChunks() { return forcedChunks; } @Override public LoaderMode getLoaderMode() { return LoaderMode.STATION; } @Override public LoaderType getLoaderType() { for (AttachedLoader attachment : attachments) { if (attachment.type() == LoaderType.BRASS) return LoaderType.BRASS; } return LoaderType.ANDESITE; } @Override public @Nullable Pair<ResourceLocation, BlockPos> getLocation() { return Pair.of( station.edgeLocation.getFirst().dimension.location(), BlockPos.containing(station.edgeLocation.getFirst().getLocation().add(station.edgeLocation.getSecond().getLocation()).scale(0.5)) ); } @Override public void addToManager() { if (!registered) { ChunkLoader.super.addToManager(); registered = true; } } public void tick(TrackGraph graph, boolean preTrains) { if (preTrains) return; Level level = ChunkLoadManager.tickLevel; if (level == null || level.isClientSide()) return; addToManager(); ChunkLoadManager.reclaimChunks(level, station.id, reclaimedChunks); if (attachments.isEmpty() || station.getPresentTrain() == null) { if (!forcedChunks.isEmpty()) ChunkLoadManager.unforceAllChunks(level.getServer(), station.id, forcedChunks); return; } // sanitize in case of read/write errors attachments.removeIf(a -> a.pos.distManhattan(station.blockEntityPos) > 1); Set<LoadedChunkPos> loadTargets = new HashSet<>(); for (AttachedLoader attachment : attachments) { if (isEnabledForStation(attachment.type())) loadTargets.add(new LoadedChunkPos(station.blockEntityDimension.location(), new ChunkPos(attachment.pos()))); } ChunkLoadManager.updateForcedChunks(level.getServer(), loadTargets, station.id, 2, forcedChunks); } public static boolean isEnabledForStation(LoaderType type) { if (type == LoaderType.ANDESITE)
return CPLConfigs.server().andesiteOnStation.get();
0
2023-11-09 04:29:33+00:00
8k
dingodb/dingo-expr
runtime/src/main/java/io/dingodb/expr/runtime/op/collection/ListConstructorOp.java
[ { "identifier": "EvalContext", "path": "runtime/src/main/java/io/dingodb/expr/runtime/EvalContext.java", "snippet": "public interface EvalContext extends Serializable {\n /**\n * Get the value of a variable by its id.\n *\n * @param id the id of the variable\n * @return the value of t...
import io.dingodb.expr.runtime.EvalContext; import io.dingodb.expr.runtime.ExprConfig; import io.dingodb.expr.runtime.expr.Expr; import io.dingodb.expr.runtime.type.ListType; import io.dingodb.expr.runtime.type.Type; import io.dingodb.expr.runtime.type.Types; import io.dingodb.expr.runtime.utils.ExceptionUtils; import lombok.Getter; import org.checkerframework.checker.nullness.qual.NonNull; import java.util.ArrayList; import java.util.List;
4,991
/* * Copyright 2021 DataCanvas * * 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.dingodb.expr.runtime.op.collection; public final class ListConstructorOp extends ListConstructorOpFactory { private static final long serialVersionUID = -7883906710460287752L; @Getter private final ListType type; ListConstructorOp(Type elementType) { super();
/* * Copyright 2021 DataCanvas * * 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.dingodb.expr.runtime.op.collection; public final class ListConstructorOp extends ListConstructorOpFactory { private static final long serialVersionUID = -7883906710460287752L; @Getter private final ListType type; ListConstructorOp(Type elementType) { super();
type = Types.list(elementType);
5
2023-11-04 08:43:49+00:00
8k
sesamecare/stripe-mock
src/main/java/com/sesame/oss/stripemock/http/StripeApiHttpHandler.java
[ { "identifier": "StripeMock", "path": "src/main/java/com/sesame/oss/stripemock/StripeMock.java", "snippet": "public class StripeMock {\n /**\n * When switching from using a normal stripe integration during testing, there might be \"known\" values, for example customers with a known\n * set of...
import com.sesame.oss.stripemock.StripeMock; import com.sesame.oss.stripemock.entities.StripeEntities; import com.sesame.oss.stripemock.http.EntityResponse.Multiple; import com.sesame.oss.stripemock.http.EntityResponse.Single; import com.sesame.oss.stripemock.util.Utilities; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger;
3,607
package com.sesame.oss.stripemock.http; public class StripeApiHttpHandler implements HttpHandler { private final IdempotencyManager idempotencyManager = new IdempotencyManager(); private final Parser parser = new Parser(); private final JsonResponseProducer jsonResponseProducer; private final EntityRequestHandler requestHandler; public StripeApiHttpHandler(StripeEntities stripeEntities) { this.jsonResponseProducer = new JsonResponseProducer(stripeEntities); this.requestHandler = new EntityRequestHandler(stripeEntities); } @Override public void handle(HttpExchange exchange) throws IOException {
package com.sesame.oss.stripemock.http; public class StripeApiHttpHandler implements HttpHandler { private final IdempotencyManager idempotencyManager = new IdempotencyManager(); private final Parser parser = new Parser(); private final JsonResponseProducer jsonResponseProducer; private final EntityRequestHandler requestHandler; public StripeApiHttpHandler(StripeEntities stripeEntities) { this.jsonResponseProducer = new JsonResponseProducer(stripeEntities); this.requestHandler = new EntityRequestHandler(stripeEntities); } @Override public void handle(HttpExchange exchange) throws IOException {
String requestId = Utilities.randomIdWithPrefix("req", 14);
2
2023-11-03 08:51:13+00:00
8k
Arborsm/ArborCore
src/main/java/org/arbor/gtnn/GTNNAddon.java
[ { "identifier": "GTNNElement", "path": "src/main/java/org/arbor/gtnn/data/GTNNElement.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class GTNNElement {\n public static final Element IF = GTElements.createAndRegister(999, 9999, -1, null, \"Infinity Catalyst\", \"If\", false);\n public st...
import com.gregtechceu.gtceu.api.addon.GTAddon; import com.gregtechceu.gtceu.api.addon.IGTAddon; import com.gregtechceu.gtceu.api.addon.events.KJSRecipeKeyEvent; import com.gregtechceu.gtceu.api.addon.events.MaterialCasingCollectionEvent; import com.lowdragmc.lowdraglib.LDLib; import com.lowdragmc.lowdraglib.Platform; import net.minecraft.data.recipes.FinishedRecipe; import net.minecraft.resources.ResourceLocation; import org.arbor.gtnn.data.GTNNElement; import org.arbor.gtnn.data.GTNNMaterials; import org.arbor.gtnn.data.GTNNRecipes; import org.arbor.gtnn.data.GTNNRecipesTypes; import org.arbor.gtnn.data.misc.adastra.AdAstraAddon; import org.arbor.gtnn.init.AddonProxy; import java.util.function.Consumer;
6,156
package org.arbor.gtnn; @GTAddon public class GTNNAddon implements IGTAddon { @Override public void initializeAddon() { org.arbor.gtnn.GTNN.LOGGER.info("GTNN Loaded!"); if (!Platform.isDatagen()){ AddonProxy.init(); } } @Override public String addonModId() { return GTNN.MODID; } @Override public void registerTagPrefixes() { IGTAddon.super.registerTagPrefixes(); if (LDLib.isModLoaded("ad_astra")) { AdAstraAddon.init(); } } @Override public void registerElements() { IGTAddon.super.registerElements(); GTNNElement.init(); } @Override public void registerMaterials() { IGTAddon.super.registerMaterials();
package org.arbor.gtnn; @GTAddon public class GTNNAddon implements IGTAddon { @Override public void initializeAddon() { org.arbor.gtnn.GTNN.LOGGER.info("GTNN Loaded!"); if (!Platform.isDatagen()){ AddonProxy.init(); } } @Override public String addonModId() { return GTNN.MODID; } @Override public void registerTagPrefixes() { IGTAddon.super.registerTagPrefixes(); if (LDLib.isModLoaded("ad_astra")) { AdAstraAddon.init(); } } @Override public void registerElements() { IGTAddon.super.registerElements(); GTNNElement.init(); } @Override public void registerMaterials() { IGTAddon.super.registerMaterials();
GTNNMaterials.init();
1
2023-11-04 07:59:02+00:00
8k
WebNetMC/WebNetBedwars
src/main/java/dev/foxikle/webnetbedwars/managers/GameManager.java
[ { "identifier": "WebNetBedWars", "path": "src/main/java/dev/foxikle/webnetbedwars/WebNetBedWars.java", "snippet": "public final class WebNetBedWars extends JavaPlugin {\n\n private GameManager gameManager;\n public static WebNetBedWars INSTANCE;\n private ItemAbilityDispatcher itemAbilityDispat...
import dev.foxikle.customnpcs.api.Action; import dev.foxikle.customnpcs.api.ActionType; import dev.foxikle.customnpcs.api.NPCApi; import dev.foxikle.customnpcs.api.conditions.Conditional; import dev.foxikle.webnetbedwars.WebNetBedWars; import dev.foxikle.webnetbedwars.data.enums.GameState; import dev.foxikle.webnetbedwars.data.objects.Team; import dev.foxikle.webnetbedwars.runnables.RespawnRunnable; import org.bukkit.*; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageEvent; import javax.annotation.Nullable; import java.util.*;
4,911
public MenuManager getMenuManager() { return menuManager; } public EconomyManager getEconomyManager() { return economyManager; } public List<Team> getTeamlist() { return teamlist; } public Map<Team, Boolean> getBeds() { return beds; } public ScoreboardManager getScoreboardManager() { return scoreboardManager; } public Map<Team, List<UUID>> getPlayerTeams() { return playerTeams; } public void cleanup(){ STARTED = false; setGameState(GameState.CLEANUP); mcTeams.values().forEach(org.bukkit.scoreboard.Team::unregister); npcs.forEach(NPCApi.NPC::remove); } @Nullable public Team getPlayerTeam(UUID uuid){ for (Team t : teamlist) { if(playerTeams.get(t).contains(uuid)) return t; } return null; } public void breakBed(Player player, Team t){ player.getWorld().playSound(player.getLocation(), Sound.ENTITY_WITHER_SPAWN, 1000f, 1f); Bukkit.broadcastMessage(getPlayerTeam(player.getUniqueId()).color() + player.getName() + ChatColor.YELLOW + " destroyed " + t.color() + t.displayName() + ChatColor.YELLOW + "'s bed!"); // todo: display animations, messages, etc. beds.put(t, false); } public void kill(Player dead, @Nullable Player killer, EntityDamageEvent.DamageCause cause) { alivePlayers.remove(dead.getUniqueId()); //todo: Death animation, not direct respawn! boolean finalkill = false; String message = ChatColor.translateAlternateColorCodes('&', getPlayerTeam(dead.getUniqueId()).prefix()) + dead.getName() + ChatColor.RESET; if(!beds.get(getPlayerTeam(dead.getUniqueId()))) { finalkill = true; } switch (cause) { case KILL -> { if(killer == null) { kill(dead, null, EntityDamageEvent.DamageCause.CUSTOM); } else { statsManager.addPlayerDeath(dead.getUniqueId()); statsManager.addPlayerKill(killer.getUniqueId()); message += ChatColor.GRAY + " was slain by " + ChatColor.translateAlternateColorCodes('&', getPlayerTeam(killer.getUniqueId()).prefix()) + killer.getName(); } } case FALL -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " has fallen to their death"; } case FIRE, FIRE_TICK -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " was roasted like a turkey"; } case LAVA -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " discovered lava is hot"; } case VOID -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " fell into the abyss"; } case FREEZE -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " turned into an ice cube"; } case DROWNING -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " forgot how to swim"; } case ENTITY_EXPLOSION, BLOCK_EXPLOSION -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " went " + ChatColor.RED + "" + ChatColor.BOLD + "BOOM!"; } case PROJECTILE -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " was remotley terminated"; } default -> { if(cause == EntityDamageEvent.DamageCause.ENTITY_ATTACK) return; statsManager.addPlayerDeath(dead.getUniqueId()); plugin.getLogger().info(String.valueOf(cause)); message += ChatColor.GRAY + " died under mysterious circumstances"; } } if(finalkill) { dead.sendTitle(ChatColor.RED + "" + ChatColor.BOLD + "You DIED!", ChatColor.YELLOW + "You won't repsawn", 5, 15, 5); message += ChatColor.DARK_RED + "" + ChatColor.BOLD + " FINAL KILL!"; dead.setGameMode(GameMode.SPECTATOR); Bukkit.broadcastMessage(message); return; } // respawn logic... Bukkit.broadcastMessage(message); dead.sendTitle(ChatColor.RED + "" + ChatColor.BOLD + "You DIED!", ChatColor.YELLOW + "You will repsawn soon", 5, 15, 5); dead.setGameMode(GameMode.SPECTATOR); dead.getInventory().clear(); dead.setHealth(20.0); dead.setFireTicks(0); // reset fire
package dev.foxikle.webnetbedwars.managers; public class GameManager { private final WebNetBedWars plugin; private List<Team> teamlist = new ArrayList<>(); private Map<Team, List<UUID>> playerTeams = new HashMap<>(); private List<UUID> alivePlayers = new ArrayList<>(); private Map<Team, Boolean> beds = new HashMap<>(); private final Map<Team, org.bukkit.scoreboard.Team> mcTeams = new HashMap<>(); private final List<NPCApi.NPC> npcs = new ArrayList<>(); public List<UUID> spectators = new ArrayList<>(); private GameState beforeFrozen; private GameState gameState; private static final String NPC_SKIN_VALUE = "ewogICJ0aW1lc3RhbXAiIDogMTY2MjQ2NzA5Njc1NywKICAicHJvZmlsZUlkIiA6ICJmNTgyNGRmNGIwMTU0MDA4OGRhMzUyYTQxODU1MDQ0NCIsCiAgInByb2ZpbGVOYW1lIiA6ICJGb3hHYW1lcjUzOTIiLAogICJzaWduYXR1cmVSZXF1aXJlZCIgOiB0cnVlLAogICJ0ZXh0dXJlcyIgOiB7CiAgICAiU0tJTiIgOiB7CiAgICAgICJ1cmwiIDogImh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNTI5YWI4YmRiMjI4ZTQ3MjZiNzQ1MzZhY2EwNTlhMTZjYWNjNzBjNThlNGEyZGFhMTQzZDIxOWYzNzRhOGI0YSIKICAgIH0KICB9Cn0="; private static final String NPC_SKIN_SIGNATURE = "yKToy4cFqIM5A3JWqXkeOaWjOd8MjAm+ECb1ga8tlBZzGvsLVHVaatVcvdYvLqxeUcWrrGLE8F4cqdVl+XyqUyILjmqw8elFwKCS28fIryuvAMaH28SRjDUsAVtTyt6xHSh2yx30IvuN+OmatcTTYQO0AmTzG6VlrOd4COzfrcOEteZb6yqh43hfxpawlavdQw7LQ3ecFXe5JPINNzXPEbbcAYeV9Gh9j6ej9n2P8KsMcTfEjb+UWh82fLegPt3pBQWdXUJVyh1SualBqVaX8hqk38KbfwtC7A9FWvycY7OacjXOyTeWEqZnGUNwc1YgXnS5EidzG/xXNJz2pgzOBlwtAv80jAXnVQcyJkuhSijSehKvMuEEd1gcY7O3itAdSb0636zjAhcKsqskzUhaRNK8QNpbIowBDA2t4EXaFkGSpBSRrOVthox6MhxDLC+ZKADNuiGEtVgpw6vY5gfulovaIX7wOWGLrxGrA6JsA9Fq7XuwHq8d8k8kI6XNRSxdKoKgHhdmlzjPax/GelXt6a9VkRoagtY8EmnliWyOorIMazjdDKq+QmddHH3sDAeahLtXoCf64Jus8bqqyNL4B0E3HwlKjQ2XZw1v/G9c70uJscaoUgpATwvHg2+dH0uxs2MSkN/GZM3GWbmyerFz+AapDjsZhBhylJ570jcbuS4="; private StatsManager statsManager; private ScoreboardManager scoreboardManager; private WorldManager worldManager; private MenuManager menuManager; private EconomyManager economyManager; public boolean STARTED = false; public GameManager(WebNetBedWars plugin) { this.plugin = plugin; statsManager = new StatsManager(); scoreboardManager = new ScoreboardManager(this, plugin); worldManager = new WorldManager(plugin, this); menuManager = new MenuManager(plugin); } public void setup() { worldManager.createSpawnPlatform(); scoreboardManager.init(); gameState = GameState.WAITING; FileConfiguration config = plugin.getConfig(); ConfigurationSection section = config.getConfigurationSection("Teams"); for (String key : section.getKeys(false)) { ConfigurationSection teamSection = section.getConfigurationSection(key); try { Bukkit.getScoreboardManager().getMainScoreboard().getTeam(key).unregister(); } catch (Exception ignored){} Team t = new Team( key, teamSection.getString("TAB_PREFIX"), ChatColor.valueOf(teamSection.getString("TEAM_COLOR")), Material.valueOf(teamSection.getString("BED_ITEM")), teamSection.getLocation("SPAWN_LOCATION"), teamSection.getLocation("GENERATOR_LOCATION"), teamSection.getLocation("ITEM_SHOP_LOCATION"), teamSection.getLocation("TEAM_SHOP_LOCATION"), teamSection.getLocation("TEAM_CHEST_LOCATION") ); teamlist.add(t); beds.put(t, true); } } public void freeze(){ beforeFrozen = gameState; gameState = GameState.FROZEN; } public void thaw(){ gameState = beforeFrozen; beforeFrozen = null; } public void start() { worldManager.removeSpawnPlatform(); STARTED = true; setGameState(GameState.PLAY); Bukkit.getOnlinePlayers().forEach(player -> statsManager.propagatePlayer(player.getUniqueId())); // split players into teams List<UUID> players = new ArrayList<>(); alivePlayers = players; Bukkit.getOnlinePlayers().forEach(player -> players.add(player.getUniqueId())); playerTeams = splitPlayersIntoTeams(players); playerTeams.keySet().forEach(team -> { List<UUID> uuids = playerTeams.get(team); uuids.forEach(uuid -> { Player p = Bukkit.getPlayer(uuid); if(p != null){ mcTeams.get(team).addEntry(p.getName()); p.teleport(team.spawnLocation()); } }); }); for (Team t : teamlist) { NPCApi.NPC teamShop = new NPCApi.NPC(t.teamShopLocation().getWorld()); teamShop.setHeading(t.teamShopLocation().getYaw()) .setPostion(t.teamShopLocation()) .setName("<aqua><bold>TEAM SHOP</bold></aqua>") .setSkin("shopkeeper", NPC_SKIN_SIGNATURE, NPC_SKIN_VALUE) .setInteractable(true) .setActions( List.of( new Action( ActionType.RUN_COMMAND, new ArrayList<>(List.of("openteamshop")), 0, Conditional.SelectionMode.ONE, List.of() ) ) ) .create(); npcs.add(teamShop); NPCApi.NPC itemShop = new NPCApi.NPC(t.itemShopLocation().getWorld()); itemShop.setHeading(t.itemShopLocation().getYaw()) .setPostion(t.itemShopLocation()) .setName("<GOLD><bold>ITEM SHOP</bold></gold>") .setSkin("shopkeeper", NPC_SKIN_SIGNATURE, NPC_SKIN_VALUE) .setInteractable(true) .setActions( List.of( new Action( ActionType.RUN_COMMAND, new ArrayList<>(List.of("openitemshop")), 0, Conditional.SelectionMode.ONE, List.of() ) ) ) .create(); npcs.add(itemShop); } } private Map<Team, List<UUID>> splitPlayersIntoTeams(List<UUID> players) { int numTeams = teamlist.size(); int teamSize = players.size() / numTeams; int remainingPlayers = players.size() % numTeams; Map<Team, List<UUID>> result = new HashMap<>(); int playerIndex = 0; for (Team team : teamlist) { org.bukkit.scoreboard.Team t = Bukkit.getScoreboardManager().getMainScoreboard().registerNewTeam(team.displayName()); t.setOption(org.bukkit.scoreboard.Team.Option.COLLISION_RULE, org.bukkit.scoreboard.Team.OptionStatus.FOR_OTHER_TEAMS); t.setCanSeeFriendlyInvisibles(true); t.setAllowFriendlyFire(false); t.setColor(team.color()); t.setPrefix(ChatColor.translateAlternateColorCodes('&', team.prefix())); mcTeams.put(team, t); List<UUID> teamPlayers = new ArrayList<>(); int currentTeamSize = teamSize + (remainingPlayers > 0 ? 1 : 0); for (int i = 0; i < currentTeamSize; i++) { if (playerIndex < players.size()) { teamPlayers.add(players.get(playerIndex)); playerIndex++; } } result.put(team, teamPlayers); if (remainingPlayers > 0) { remainingPlayers--; } } return result; } public GameState getGameState() { return gameState; } private void setGameState(GameState gameState) { this.gameState = gameState; } public StatsManager getStatsManager() { return statsManager; } public MenuManager getMenuManager() { return menuManager; } public EconomyManager getEconomyManager() { return economyManager; } public List<Team> getTeamlist() { return teamlist; } public Map<Team, Boolean> getBeds() { return beds; } public ScoreboardManager getScoreboardManager() { return scoreboardManager; } public Map<Team, List<UUID>> getPlayerTeams() { return playerTeams; } public void cleanup(){ STARTED = false; setGameState(GameState.CLEANUP); mcTeams.values().forEach(org.bukkit.scoreboard.Team::unregister); npcs.forEach(NPCApi.NPC::remove); } @Nullable public Team getPlayerTeam(UUID uuid){ for (Team t : teamlist) { if(playerTeams.get(t).contains(uuid)) return t; } return null; } public void breakBed(Player player, Team t){ player.getWorld().playSound(player.getLocation(), Sound.ENTITY_WITHER_SPAWN, 1000f, 1f); Bukkit.broadcastMessage(getPlayerTeam(player.getUniqueId()).color() + player.getName() + ChatColor.YELLOW + " destroyed " + t.color() + t.displayName() + ChatColor.YELLOW + "'s bed!"); // todo: display animations, messages, etc. beds.put(t, false); } public void kill(Player dead, @Nullable Player killer, EntityDamageEvent.DamageCause cause) { alivePlayers.remove(dead.getUniqueId()); //todo: Death animation, not direct respawn! boolean finalkill = false; String message = ChatColor.translateAlternateColorCodes('&', getPlayerTeam(dead.getUniqueId()).prefix()) + dead.getName() + ChatColor.RESET; if(!beds.get(getPlayerTeam(dead.getUniqueId()))) { finalkill = true; } switch (cause) { case KILL -> { if(killer == null) { kill(dead, null, EntityDamageEvent.DamageCause.CUSTOM); } else { statsManager.addPlayerDeath(dead.getUniqueId()); statsManager.addPlayerKill(killer.getUniqueId()); message += ChatColor.GRAY + " was slain by " + ChatColor.translateAlternateColorCodes('&', getPlayerTeam(killer.getUniqueId()).prefix()) + killer.getName(); } } case FALL -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " has fallen to their death"; } case FIRE, FIRE_TICK -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " was roasted like a turkey"; } case LAVA -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " discovered lava is hot"; } case VOID -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " fell into the abyss"; } case FREEZE -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " turned into an ice cube"; } case DROWNING -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " forgot how to swim"; } case ENTITY_EXPLOSION, BLOCK_EXPLOSION -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " went " + ChatColor.RED + "" + ChatColor.BOLD + "BOOM!"; } case PROJECTILE -> { statsManager.addPlayerDeath(dead.getUniqueId()); message += ChatColor.GRAY + " was remotley terminated"; } default -> { if(cause == EntityDamageEvent.DamageCause.ENTITY_ATTACK) return; statsManager.addPlayerDeath(dead.getUniqueId()); plugin.getLogger().info(String.valueOf(cause)); message += ChatColor.GRAY + " died under mysterious circumstances"; } } if(finalkill) { dead.sendTitle(ChatColor.RED + "" + ChatColor.BOLD + "You DIED!", ChatColor.YELLOW + "You won't repsawn", 5, 15, 5); message += ChatColor.DARK_RED + "" + ChatColor.BOLD + " FINAL KILL!"; dead.setGameMode(GameMode.SPECTATOR); Bukkit.broadcastMessage(message); return; } // respawn logic... Bukkit.broadcastMessage(message); dead.sendTitle(ChatColor.RED + "" + ChatColor.BOLD + "You DIED!", ChatColor.YELLOW + "You will repsawn soon", 5, 15, 5); dead.setGameMode(GameMode.SPECTATOR); dead.getInventory().clear(); dead.setHealth(20.0); dead.setFireTicks(0); // reset fire
new RespawnRunnable(plugin, 6, dead).runTaskTimer(plugin, 0, 20);
2
2023-11-04 00:18:20+00:00
8k
satisfyu/HerbalBrews
common/src/main/java/satisfyu/herbalbrews/registry/BlockEntityRegistry.java
[ { "identifier": "HerbalBrews", "path": "common/src/main/java/satisfyu/herbalbrews/HerbalBrews.java", "snippet": "public class HerbalBrews {\n public static final String MOD_ID = \"herbalbrews\";\n public static final Logger LOGGER = LogManager.getLogger(MOD_ID);\n\n public static void init() {\...
import dev.architectury.registry.registries.DeferredRegister; import dev.architectury.registry.registries.RegistrySupplier; import net.minecraft.core.registries.Registries; import net.minecraft.world.level.block.entity.BlockEntityType; import satisfyu.herbalbrews.HerbalBrews; import satisfyu.herbalbrews.entities.CauldronBlockEntity; import satisfyu.herbalbrews.entities.TeaKettleBlockEntity; import java.util.function.Supplier;
3,945
package satisfyu.herbalbrews.registry; public class BlockEntityRegistry { private static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITY_TYPES = DeferredRegister.create(HerbalBrews.MOD_ID, Registries.BLOCK_ENTITY_TYPE); public static final RegistrySupplier<BlockEntityType<TeaKettleBlockEntity>> TEA_KETTLE_BLOCK_ENTITY = create("tea_kettle", () -> BlockEntityType.Builder.of(TeaKettleBlockEntity::new, ObjectRegistry.TEA_KETTLE.get(), ObjectRegistry.COPPER_TEA_KETTLE.get()).build(null));
package satisfyu.herbalbrews.registry; public class BlockEntityRegistry { private static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITY_TYPES = DeferredRegister.create(HerbalBrews.MOD_ID, Registries.BLOCK_ENTITY_TYPE); public static final RegistrySupplier<BlockEntityType<TeaKettleBlockEntity>> TEA_KETTLE_BLOCK_ENTITY = create("tea_kettle", () -> BlockEntityType.Builder.of(TeaKettleBlockEntity::new, ObjectRegistry.TEA_KETTLE.get(), ObjectRegistry.COPPER_TEA_KETTLE.get()).build(null));
public static final RegistrySupplier<BlockEntityType<CauldronBlockEntity>> CAULDRON_BLOCK_ENTITY = create("cauldron", () -> BlockEntityType.Builder.of(CauldronBlockEntity::new, ObjectRegistry.CAULDRON.get()).build(null));
1
2023-11-05 16:46:52+00:00
8k
sizdshi/download-server
server/main/src/main/java/com/example/service/impl/DownloadServiceImpl.java
[ { "identifier": "ErrorCode", "path": "server/common/src/main/java/com/example/common/ErrorCode.java", "snippet": "public enum ErrorCode {\r\n /**\r\n * 成功\r\n */\r\n SUCCESS(0, \"ok\"),\r\n /**\r\n * 请求参数错误\r\n */\r\n PARAMS_ERROR(40000, \"请求参数错误\"),\r\n /**\r\n * 未登录\...
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.common.ErrorCode; import com.example.constant.CommonConstant; import com.example.model.dto.DownloadRequest; import com.example.model.dto.ThreadRequest; import com.example.model.entity.Download; import com.example.model.vo.DownloadVO; import com.example.utils.SqlUtils; import com.example.exception.BusinessException; import com.example.model.enums.DownloadStatus; import com.example.service.DownloadService; import com.example.mapper.DownloadMapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.Date; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils;
4,782
return resumeCount; } @Override public long delete(List<String> ids) { if(!CollectionUtils.isNotEmpty(ids)){ throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"传入数组为空"); } LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>(); invokeLambdaUpdateWrapper.in(Download::getId,ids); long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper); if(count<=0){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求数据不存在"); } invokeLambdaUpdateWrapper.set(Download::getStatus,DownloadStatus.STATUS_DELETE.getValue()); invokeLambdaUpdateWrapper.set(Download::getIs_delete,1); int deleteCount = downloadMapper.update(new Download(),invokeLambdaUpdateWrapper); System.out.println("删除成功"); if(deleteCount<=0){ throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 删除任务数失败 数据库异常"); } return deleteCount; } @Override public String submit(String url) { if(!StringUtils.isNotEmpty(url)){ throw new BusinessException(ErrorCode.NOT_FOUND_ERROR); } String urlPattern = "^(http|https):\\/\\/(www\\.)?([a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*|\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})(:\\d+)?(\\/\\S*)?$"; if(!Pattern.matches(urlPattern,url)){ throw new BusinessException(ErrorCode.PARAMS_ERROR, "不合法的URL"); } //todo 检查是否逻辑删除,如果是,改为否 LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>(); invokeLambdaUpdateWrapper.eq(Download::getUrl,url); long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper); if(count>0){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求文件已存在"); } String fileName = url.substring(url.lastIndexOf('/') + 1); Download download = new Download(); download.setUrl(url); download.setTask_type("http"); download.setFile_name(fileName); download.setUpdate_time(new Date()); download.setCreate_time(new Date()); download.setIs_delete(0); //todo 文件大小在哪里处理 boolean saveResult = this.save(download); if(!saveResult){ throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 提交任务失败 数据库异常"); } return Long.toString(download.getId()); } @Override public Page<DownloadVO> listDownloadVOByPage(DownloadRequest downloadRequest, HttpServletRequest request) { long current = downloadRequest.getCurrent(); long size = downloadRequest.getPageSize(); Page<Download> downloadPage = this.page(new Page<>(current,size),this.getQueryWrapper(downloadRequest)); return this.getDownloadVOPage(downloadPage,request); } @Override public Page<DownloadVO> getDownloadVOPage(Page<Download> downloadPage, HttpServletRequest request) { List<Download> downloadList = downloadPage.getRecords(); Page<DownloadVO> downloadVOPage = new Page<>(downloadPage.getCurrent(),downloadPage.getSize(),downloadPage.getTotal()); if (CollectionUtils.isEmpty(downloadList)) { return downloadVOPage; } List<DownloadVO> downloadVOList = downloadList.stream().map(DownloadVO::objToVo).collect(Collectors.toList()); downloadVOPage.setRecords(downloadVOList); return downloadVOPage; } @Override public QueryWrapper<Download> getQueryWrapper(DownloadRequest downloadRequest){ QueryWrapper<Download> downloadQueryWrapper = new QueryWrapper<>(); if(downloadRequest == null){ return downloadQueryWrapper; } String url = downloadRequest.getUrl(); String status = downloadRequest.getStatus(); String fileName = downloadRequest.getFile_name(); Long id = downloadRequest.getId(); String sortField = downloadRequest.getSortField(); String sortOrder = downloadRequest.getSortOrder(); downloadQueryWrapper.eq(ObjectUtils.isNotEmpty(url),"url",url); downloadQueryWrapper.eq(ObjectUtils.isNotEmpty(status),"status",status); downloadQueryWrapper.ne(ObjectUtils.isNotEmpty(id),"id",id); downloadQueryWrapper.eq(ObjectUtils.isNotEmpty(fileName),"file_name",fileName); if(status.equals(DownloadStatus.STATUS_DELETE.getValue())){ downloadQueryWrapper.eq("is_delete",1); }else{ downloadQueryWrapper.eq("is_delete",0); } // downloadQueryWrapper.eq("is_delete",false);
package com.example.service.impl; /** * @author sizd-shi * @description 针对表【download(上传下载表)】的数据库操作Service实现 * @createDate 2023-11-09 14:40:30 */ @Service @Slf4j public class DownloadServiceImpl extends ServiceImpl<DownloadMapper, Download> implements DownloadService { @Resource private DownloadMapper downloadMapper; @Override public long suspend(List<String> ids) { if(!CollectionUtils.isNotEmpty(ids)){ throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"传入数组为空"); } LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>(); invokeLambdaUpdateWrapper.in(Download::getId,ids); long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper); if(count<=0){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求数据不存在"); } invokeLambdaUpdateWrapper.set(Download::getStatus,DownloadStatus.STATUS_PAUSED.getValue()); int updateCount = downloadMapper.update(new Download(),invokeLambdaUpdateWrapper); List<Download> up = downloadMapper.selectList(invokeLambdaUpdateWrapper); if(updateCount<=0){ throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 暂停任务数失败 数据库异常"); } return up.get(1).getId(); } @Override public long changeThread(ThreadRequest threadRequest, HttpServletRequest request) { if (!StringUtils.isNotEmpty(threadRequest.getId()) || !StringUtils.isNotEmpty(String.valueOf(threadRequest.getCount()))) { throw new BusinessException(ErrorCode.NOT_FOUND_ERROR); } LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>(); invokeLambdaUpdateWrapper.eq(Download::getId,Long.parseLong(threadRequest.getId())); long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper); if(count<=0){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求文件不存在"); } invokeLambdaUpdateWrapper.set(Download::getCount,threadRequest.getCount()); int changeThread = downloadMapper.update(new Download(),invokeLambdaUpdateWrapper); if(changeThread<=0){ throw new BusinessException(ErrorCode.SYSTEM_ERROR,"修改任务数失败 数据库异常"); } return changeThread; } @Override public long start(List<String> ids,HttpServletRequest request) { if(!CollectionUtils.isNotEmpty(ids)){ throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"传入数组为空"); } LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>(); invokeLambdaUpdateWrapper.in(Download::getId,ids); long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper); if(count<=0){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求文件不存在"); } invokeLambdaUpdateWrapper.set(Download::getStatus,DownloadStatus.STATUS_DOWNLOADING.getValue()); int resumeCount = downloadMapper.update(new Download(),invokeLambdaUpdateWrapper); if(resumeCount<=0){ throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 开始下载任务数失败 数据库异常"); } return resumeCount; } @Override public long suspend(List<String> ids, HttpServletRequest request) { if(!CollectionUtils.isNotEmpty(ids)){ throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"传入数组为空"); } LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>(); invokeLambdaUpdateWrapper.in(Download::getId,ids); invokeLambdaUpdateWrapper.eq(Download::getIs_delete,0); long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper); if(count<=0){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求数据不存在"); } invokeLambdaUpdateWrapper.set(Download::getStatus,DownloadStatus.STATUS_PAUSED.getValue()); int updateCount = downloadMapper.update(new Download(),invokeLambdaUpdateWrapper); // List<Download> up = downloadMapper.selectList(invokeLambdaUpdateWrapper); if(updateCount<=0){ throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 暂停任务数失败 数据库异常"); } return updateCount; } @Override public long restart(List<String> ids, HttpServletRequest request) { if(!CollectionUtils.isNotEmpty(ids)){ throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"传入数组为空"); } LambdaUpdateWrapper<Download> resumeWrapper = new LambdaUpdateWrapper<>(); resumeWrapper.in(Download::getId,ids); resumeWrapper.eq(Download::getIs_delete,0); long count = downloadMapper.selectCount(resumeWrapper); if(count<=0){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求文件不存在"); } //todo 检查本地文件是否存在,存在则删除 resumeWrapper.set(Download::getStatus,DownloadStatus.STATUS_DOWNLOADING.getValue()); int resumeCount = downloadMapper.update(new Download(),resumeWrapper); if(resumeCount<=0){ throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 重新下载任务数失败 数据库异常"); } return resumeCount; } @Override public long delete(List<String> ids) { if(!CollectionUtils.isNotEmpty(ids)){ throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"传入数组为空"); } LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>(); invokeLambdaUpdateWrapper.in(Download::getId,ids); long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper); if(count<=0){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求数据不存在"); } invokeLambdaUpdateWrapper.set(Download::getStatus,DownloadStatus.STATUS_DELETE.getValue()); invokeLambdaUpdateWrapper.set(Download::getIs_delete,1); int deleteCount = downloadMapper.update(new Download(),invokeLambdaUpdateWrapper); System.out.println("删除成功"); if(deleteCount<=0){ throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 删除任务数失败 数据库异常"); } return deleteCount; } @Override public String submit(String url) { if(!StringUtils.isNotEmpty(url)){ throw new BusinessException(ErrorCode.NOT_FOUND_ERROR); } String urlPattern = "^(http|https):\\/\\/(www\\.)?([a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*|\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})(:\\d+)?(\\/\\S*)?$"; if(!Pattern.matches(urlPattern,url)){ throw new BusinessException(ErrorCode.PARAMS_ERROR, "不合法的URL"); } //todo 检查是否逻辑删除,如果是,改为否 LambdaUpdateWrapper<Download> invokeLambdaUpdateWrapper = new LambdaUpdateWrapper<>(); invokeLambdaUpdateWrapper.eq(Download::getUrl,url); long count = downloadMapper.selectCount(invokeLambdaUpdateWrapper); if(count>0){ throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求文件已存在"); } String fileName = url.substring(url.lastIndexOf('/') + 1); Download download = new Download(); download.setUrl(url); download.setTask_type("http"); download.setFile_name(fileName); download.setUpdate_time(new Date()); download.setCreate_time(new Date()); download.setIs_delete(0); //todo 文件大小在哪里处理 boolean saveResult = this.save(download); if(!saveResult){ throw new BusinessException(ErrorCode.SYSTEM_ERROR,"download 提交任务失败 数据库异常"); } return Long.toString(download.getId()); } @Override public Page<DownloadVO> listDownloadVOByPage(DownloadRequest downloadRequest, HttpServletRequest request) { long current = downloadRequest.getCurrent(); long size = downloadRequest.getPageSize(); Page<Download> downloadPage = this.page(new Page<>(current,size),this.getQueryWrapper(downloadRequest)); return this.getDownloadVOPage(downloadPage,request); } @Override public Page<DownloadVO> getDownloadVOPage(Page<Download> downloadPage, HttpServletRequest request) { List<Download> downloadList = downloadPage.getRecords(); Page<DownloadVO> downloadVOPage = new Page<>(downloadPage.getCurrent(),downloadPage.getSize(),downloadPage.getTotal()); if (CollectionUtils.isEmpty(downloadList)) { return downloadVOPage; } List<DownloadVO> downloadVOList = downloadList.stream().map(DownloadVO::objToVo).collect(Collectors.toList()); downloadVOPage.setRecords(downloadVOList); return downloadVOPage; } @Override public QueryWrapper<Download> getQueryWrapper(DownloadRequest downloadRequest){ QueryWrapper<Download> downloadQueryWrapper = new QueryWrapper<>(); if(downloadRequest == null){ return downloadQueryWrapper; } String url = downloadRequest.getUrl(); String status = downloadRequest.getStatus(); String fileName = downloadRequest.getFile_name(); Long id = downloadRequest.getId(); String sortField = downloadRequest.getSortField(); String sortOrder = downloadRequest.getSortOrder(); downloadQueryWrapper.eq(ObjectUtils.isNotEmpty(url),"url",url); downloadQueryWrapper.eq(ObjectUtils.isNotEmpty(status),"status",status); downloadQueryWrapper.ne(ObjectUtils.isNotEmpty(id),"id",id); downloadQueryWrapper.eq(ObjectUtils.isNotEmpty(fileName),"file_name",fileName); if(status.equals(DownloadStatus.STATUS_DELETE.getValue())){ downloadQueryWrapper.eq("is_delete",1); }else{ downloadQueryWrapper.eq("is_delete",0); } // downloadQueryWrapper.eq("is_delete",false);
downloadQueryWrapper.orderBy(SqlUtils.validSortField(sortField),sortOrder.equals(CommonConstant.SORT_ORDER_ASC)
6
2023-11-02 06:09:03+00:00
8k
SatyaRajAwasth1/smart-credit-manager
src/main/java/np/com/satyarajawasthi/smartcreditmanager/manager/UserManager.java
[ { "identifier": "ChangeCredentialsDialogController", "path": "src/main/java/np/com/satyarajawasthi/smartcreditmanager/controller/ChangeCredentialsDialogController.java", "snippet": "public class ChangeCredentialsDialogController {\n\n @FXML\n private TextField newUsernameField;\n\n @FXML\n p...
import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import np.com.satyarajawasthi.smartcreditmanager.controller.ChangeCredentialsDialogController; import np.com.satyarajawasthi.smartcreditmanager.model.User; import np.com.satyarajawasthi.smartcreditmanager.repository.CredentialRepository; import np.com.satyarajawasthi.smartcreditmanager.repository.UserRepository; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import static np.com.satyarajawasthi.smartcreditmanager.util.DatabaseUtil.closeConnection; import static np.com.satyarajawasthi.smartcreditmanager.util.DatabaseUtil.getConnection;
4,006
package np.com.satyarajawasthi.smartcreditmanager.manager; public class UserManager { private static final String CONFIG_URL = "/np/com/satyarajawasthi/smartcreditmanager/config.properties"; private static final Logger logger = Logger.getLogger(UserManager.class.getName()); public static boolean isFirstLogin() { try { // Check if it's the first login by reading from the properties file if (isFirstLoginInPropertiesFile()) { if (!UserRepository.isUserTableExists()) { return true; // Table doesn't exist yet, consider it as the first login } int passwordUpdatedValue = UserRepository.getPasswordUpdatedValue(); return (passwordUpdatedValue == 0); } } catch (SQLException e) { throw new RuntimeException(e); } return false; } public static void onFirstLogin () { Connection connection = null; try { connection = getConnection(); connection.setAutoCommit(false); // Start a transaction UserRepository.createUserTable(connection); UserRepository.insertInitialUserRecords(connection); UserRepository.restrictUserInsertion(connection);
package np.com.satyarajawasthi.smartcreditmanager.manager; public class UserManager { private static final String CONFIG_URL = "/np/com/satyarajawasthi/smartcreditmanager/config.properties"; private static final Logger logger = Logger.getLogger(UserManager.class.getName()); public static boolean isFirstLogin() { try { // Check if it's the first login by reading from the properties file if (isFirstLoginInPropertiesFile()) { if (!UserRepository.isUserTableExists()) { return true; // Table doesn't exist yet, consider it as the first login } int passwordUpdatedValue = UserRepository.getPasswordUpdatedValue(); return (passwordUpdatedValue == 0); } } catch (SQLException e) { throw new RuntimeException(e); } return false; } public static void onFirstLogin () { Connection connection = null; try { connection = getConnection(); connection.setAutoCommit(false); // Start a transaction UserRepository.createUserTable(connection); UserRepository.insertInitialUserRecords(connection); UserRepository.restrictUserInsertion(connection);
CredentialRepository.createCredentialTable(connection);
2
2023-11-05 03:53:02+00:00
8k
wqj666666/embyboot
src/main/java/com/emby/boot/telegram/TelegramBot.java
[ { "identifier": "MusicDownReq", "path": "src/main/java/com/emby/boot/dto/req/MusicDownReq.java", "snippet": "@Schema(description = \"muisc下载成员变量\")\n@Data\npublic class MusicDownReq {\n\n private String album;\n private String albumMid;\n private String extra;\n private String mid;\n priv...
import com.alibaba.fastjson.JSONObject; import com.emby.boot.dto.req.MusicDownReq; import com.emby.boot.dto.resp.EmbyUserInfoResp; import com.emby.boot.dto.resp.MusicUserInfoResp; import com.emby.boot.dto.resp.RestResp; import com.emby.boot.service.EmbyUserService; import com.emby.boot.service.MusicDownloaderService; import com.emby.boot.service.MusicUserService; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.telegram.telegrambots.bots.DefaultBotOptions; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.methods.groupadministration.GetChatMember; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMember; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import java.util.ArrayList; import java.util.Collections; import java.util.List;
5,057
Collections.addAll(rowList,deleteButtonRow); InlineKeyboardMarkup inlineKeyboardMarkup = InlineKeyboardMarkup.builder().keyboard(rowList).build(); sendMessagesendMessage(chatId,messageBuilder,inlineKeyboardMarkup); return; } //重置音乐服密码:/musicreset if ("/musicreset".equals(update.getMessage().getText())){ try { musicUserService.userPassword(String.valueOf(chatId)); StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("音乐服重置成功,初始密码为用户名,建议修改密码"); sendMessage(chatId, messageBuilder); return; } catch (Exception e) { StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("音乐服重置失败"); messageBuilder.append(e.getMessage()); sendMessage(chatId, messageBuilder); return; } } //查看音乐服线路:/musicurl if ("/musicurl".equals(update.getMessage().getText())){ StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("音乐服地址:\n"); messageBuilder.append("chunmusic.imetyou.top (落地服务器线路) \n"); messageBuilder.append("cfmusic.imetyou.top (cf线路,可以加https访问))\n"); messageBuilder.append("music.imetyou.top (国内网盘线路)\n"); sendMessage(chatId, messageBuilder); return; } //求片:/forum 片名 TMDB链接求片 if (update.getMessage().getText().startsWith("/forum ")){ String regex = "^/forum (.*?) https://www\\.themoviedb\\.org/.+"; String messageText= update.getMessage().getText(); //先判断求片是否符合规则 if (!messageText.matches(regex)){ StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("求片格式不正确,请检查格式,然后重新求"); //发送消息 sendMessage(chatId,messageBuilder); return; } String[] upText = messageText.split(" "); //发送给管理员求片信息 StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("#求片 \n"); messageBuilder.append("影片名:"+upText[1]+"\n"); messageBuilder.append("TMDB链接: \n"); messageBuilder.append(upText[2]+"\n"); messageBuilder.append("TGID:@"+update.getMessage().getFrom().getUserName()); //发送消息 sendMessage(Long.parseLong(adminId),messageBuilder); //发送给用户反馈 StringBuilder usermMessageBuilder = new StringBuilder(); usermMessageBuilder.append("求片已经提交给管理员"); sendMessage(chatId,usermMessageBuilder); return; } //反馈:/bug if (update.getMessage().getText().startsWith("/bug ")){ String messageText= update.getMessage().getText(); String[] upText = messageText.split(" "); //发送给管理员反馈信息 StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("#反馈 \n"); messageBuilder.append(upText[1]+"\n"); messageBuilder.append("TGID:@"+update.getMessage().getFrom().getUserName()); //发送消息 sendMessage(Long.parseLong(adminId),messageBuilder); //发送给用户反馈 StringBuilder usermMessageBuilder = new StringBuilder(); usermMessageBuilder.append("反馈已经提交给管理员,感谢反馈!"); sendMessage(chatId,usermMessageBuilder); return; } //音乐下载搜索 if (update.getMessage().getText().startsWith("/musicsearch ")){ //创建搜索结果显示内联按钮 String keywords = update.getMessage().getText().replace("/musicsearch ", "").trim(); JSONObject search = musicDownloaderService.search(keywords,1,5); int listSize = search.getJSONArray("list").size(); StringBuilder messageBuilder = new StringBuilder(); for (int i = 0; i < listSize; i++) { String messageList=i+1+"."+" "+search.getJSONArray("list").getJSONObject(i).getString("readableText"); messageBuilder.append(messageList).append("\n"); } messageBuilder.append("\n").append("现在是第 1 页数据"); List<List<InlineKeyboardButton>> rowList = new ArrayList<>(); Integer cur = search.getJSONObject("page").getInteger("cur"); //创建第一行按钮:确认搜索结果 List<InlineKeyboardButton> buttonRow1 = new ArrayList<>(); for (int i = 0; i < listSize; i++) { InlineKeyboardButton button = InlineKeyboardButton.builder().text(String.valueOf(i+1)).callbackData("musicOk_"+i+"_"+search.getJSONObject("page").getInteger("cur")+"_"+keywords).build(); buttonRow1.add(button); } //创建第二行按钮:说明 List<InlineKeyboardButton> buttonRow2 = new ArrayList<>(); InlineKeyboardButton button2 = InlineKeyboardButton.builder().text("↑确认搜索结果, ↓下一页数据").callbackData("dummy_data").build(); buttonRow2.add(button2); //创建第三行按钮:页码 List<InlineKeyboardButton> buttonRow3 = new ArrayList<>(); for (int i = 0; i < search.getJSONObject("page").getInteger("size")/5; i++) { InlineKeyboardButton button3 = InlineKeyboardButton.builder().text(String.valueOf(i+1)).callbackData("musicSearch_"+(i+1)+"_"+keywords).build(); buttonRow3.add(button3); } // 现在,为键盘创建一个列表,并将buttonRow添加为其行 Collections.addAll(rowList,buttonRow1,buttonRow2,buttonRow3); InlineKeyboardMarkup inlineKeyboardMarkup = InlineKeyboardMarkup.builder().keyboard(rowList).build(); //回复内联消息 sendMessagesendMessage(chatId,messageBuilder,inlineKeyboardMarkup); } //查询账号信息:/info if ("/info".equals(update.getMessage().getText())){ try {
package com.emby.boot.telegram; /** * @author laojian * @date 2023/8/27 */ @Component public class TelegramBot extends TelegramLongPollingBot { private final EmbyUserService embyUserService; private final MusicUserService musicUserService; private final MusicDownloaderService musicDownloaderService; //填你自己的token和username @Value("${spring.telegrambot.config.token}") private String token; @Value("${spring.telegrambot.config.username}") private String username; @Value("${spring.telegrambot.config.groupChatId}") private String groupChatId; @Value("${spring.telegrambot.config.adminId}") private String adminId; //调用的时候初始化 public TelegramBot(DefaultBotOptions botOptions,EmbyUserService embyUserService,MusicUserService musicUserService,MusicDownloaderService musicDownloaderService) { super(botOptions); this.embyUserService = embyUserService; this.musicUserService=musicUserService; this.musicDownloaderService=musicDownloaderService; } /** * 一对一的 * onUpdateReceived(Update update): 这个方法是当Telegram服务器向bot发送一个更新时调用的。 * Update是一个对象,包含了所有可能的信息,例如收到的消息、回调查询、新的聊天参与者等等。 * 大多数的单个交互,如接收消息或命令,会触发这个方法。 * @param update */ @Override public void onUpdateReceived(Update update) { // 判断是否是点击了内联菜单的按钮 if (update.hasCallbackQuery()){ Long chatId = update.getCallbackQuery().getFrom().getId(); // 获取回调数据 String callbackData = update.getCallbackQuery().getData(); //判断是否是删除emby的内联的按钮 if (callbackData.startsWith("embyDelete_")){ String[] parts = callbackData.split("_"); String embyDeleteText = parts[1]; if ("true".equals(embyDeleteText)){ //执行emby删除用户 try { embyUserService.userDelete(String.valueOf(chatId)); // 处理BusinessException的代码 StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("emby删除成功"); sendMessage(chatId, messageBuilder); return; } catch (Exception e) { // 处理BusinessException的代码 StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("emby删除失败:\n"); messageBuilder.append(e.getMessage()); sendMessage(chatId, messageBuilder); return; } } } //判断是否是删除音乐服的内联的按钮 if (callbackData.startsWith("musicDelete_")){ String[] parts = callbackData.split("_"); String embyDeleteText = parts[1]; if ("true".equals(embyDeleteText)){ //执行emby删除用户 try { musicUserService.userDelete(String.valueOf(chatId)); // 处理BusinessException的代码 StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("音乐服删除成功"); sendMessage(chatId, messageBuilder); return; } catch (Exception e) { // 处理BusinessException的代码 StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("音乐服删除失败:\n"); messageBuilder.append(e.getMessage()); sendMessage(chatId, messageBuilder); return; } } } //确认音乐下载结果 if (callbackData.startsWith("musicOk_")){ String[] parts = callbackData.split("_"); Integer num = Integer.valueOf(parts[1]); Integer cur = Integer.valueOf(parts[2]); String keywords = parts[3]; JSONObject jsonObject = musicDownloaderService.search(keywords, cur, 5).getJSONArray("list").getJSONObject(num); MusicDownReq musicDownReq = new MusicDownReq(); musicDownReq.setReadableText(jsonObject.getString("readableText")); musicDownReq.setSinger(jsonObject.getString("singer")); musicDownReq.setTime_publish(jsonObject.getString("time_publish")); musicDownReq.setAlbum(jsonObject.getString("album")); musicDownReq.setPrefix(jsonObject.getString("prefix")); musicDownReq.setSongmid(jsonObject.getString("songmid")); musicDownReq.setAlbumMid(jsonObject.getString("albumMid")); musicDownReq.setMid(jsonObject.getString("mid")); musicDownReq.setTitle(jsonObject.getString("title")); musicDownReq.setMusicid(jsonObject.getInteger("musicid")); musicDownReq.setSize(jsonObject.getString("size")); musicDownReq.setExtra(jsonObject.getString("extra")); musicDownReq.setNotice(jsonObject.getString("notice")); try { musicDownloaderService.download(musicDownReq, String.valueOf(chatId)); StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append(jsonObject.getString("readableText")+",下载成功,等待扫库"); //发送消息 sendMessage(chatId,messageBuilder); return; } catch (Exception e) { // 处理BusinessException的代码 StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("音乐下载失败:\n"); messageBuilder.append(e.getMessage()); // 假设BusinessException有getMessage方法返回错误信息 sendMessage(chatId, messageBuilder); return; } } //下一页搜索结果 if (callbackData.startsWith("musicSearch_")){ String[] parts = callbackData.split("_"); Integer cur = Integer.valueOf(parts[1]); String keywords =parts[2]; JSONObject search = musicDownloaderService.search(keywords, cur, 5); int listSize = search.getJSONArray("list").size(); StringBuilder messageBuilder = new StringBuilder(); for (int i = 0; i < listSize; i++) { String messageList=i+1+"."+" "+search.getJSONArray("list").getJSONObject(i).getString("readableText"); messageBuilder.append(messageList).append("\n"); } messageBuilder.append("\n").append("现在是第 "+cur+" 页数据"); List<List<InlineKeyboardButton>> rowList = new ArrayList<>(); //创建第一行按钮:确认搜索结果 List<InlineKeyboardButton> buttonRow1 = new ArrayList<>(); for (int i = 0; i < listSize; i++) { InlineKeyboardButton button = InlineKeyboardButton.builder().text(String.valueOf(i+1)).callbackData("musicOk_"+i+"_"+search.getJSONObject("page").getInteger("cur")+"_"+keywords).build(); buttonRow1.add(button); } //创建第二行按钮:说明 List<InlineKeyboardButton> buttonRow2 = new ArrayList<>(); InlineKeyboardButton button2 = InlineKeyboardButton.builder().text("↑确认搜索结果, ↓下一页数据").callbackData("dummy_data").build(); buttonRow2.add(button2); //创建第三行按钮:页码 List<InlineKeyboardButton> buttonRow3 = new ArrayList<>(); for (int i = 0; i < search.getJSONObject("page").getInteger("size")/5; i++) { if (cur==i+1){ InlineKeyboardButton button3 = InlineKeyboardButton.builder().text(String.valueOf(i+1+"✅")).callbackData("musicSearch_"+(i+1)+"_"+keywords).build(); buttonRow3.add(button3); }else { InlineKeyboardButton button3 = InlineKeyboardButton.builder().text(String.valueOf(i+1)).callbackData("musicSearch_"+(i+1)+"_"+keywords).build(); buttonRow3.add(button3); } } // 现在,为键盘创建一个列表,并将buttonRow添加为其行 Collections.addAll(rowList,buttonRow1,buttonRow2,buttonRow3); InlineKeyboardMarkup inlineKeyboardMarkup = InlineKeyboardMarkup.builder().keyboard(rowList).build(); Integer messageId = update.getCallbackQuery().getMessage().getMessageId(); //编辑回复内联消息 editMessageText(chatId,messageId,messageBuilder,inlineKeyboardMarkup); return; } return; } //电报用户id Long chatId = update.getMessage().getChatId(); //先判断是否在群组或者频道 if (checkUserInTheGroup(chatId)){ //组装回复消息 StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("你还未加入频道https://t.me/paulemby"); //发送消息 sendMessage(chatId,messageBuilder); return; } // /help命令 if ("/help".equals(update.getMessage().getText())) { //组装回复消息 StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("chatid: " + chatId + "\n\n"); // 添加chatid信息 messageBuilder.append("创建emby账号:/create + 用户名\n"); messageBuilder.append("e.g:/create helloworld\n\n"); messageBuilder.append("重置emby密码:/reset\n"); messageBuilder.append("删除emby账户:/delete\n\n"); messageBuilder.append("创建音乐服账号:/musiccreate + 用户名\n"); messageBuilder.append("e.g:/musiccreate helloworld\n\n"); messageBuilder.append("重置音乐服密码:/musicreset\n"); messageBuilder.append("删除音乐服账户: /musicdelete\n\n"); messageBuilder.append("查看emby线路:/embyurl\n"); messageBuilder.append("查看音乐服线路:/musicurl\n"); messageBuilder.append("求片:/forum 片名 TMDB链接求片\n"); messageBuilder.append("e.g:/forum 你的名字 https://www.themoviedb.org/movie/372058\n\n"); messageBuilder.append("反馈:/bug\n"); messageBuilder.append("e.g:/bug 你的名字缺少字幕\n\n"); messageBuilder.append("音乐服添加音乐:/musicsearch 关键字\n"); messageBuilder.append("e.g:/musicsearch 你好\n\n"); messageBuilder.append("查询账号信息:/info\n"); //发送消息 sendMessage(chatId, messageBuilder); return; } // 创建emby账号:/create + 用户名 if (update.getMessage().getText().startsWith("/create ")){ //创建emby账户 String username = update.getMessage().getText().replace("/create ", "").trim(); //先判断用户名是否符合规则 if (!username.matches("^[a-zA-Z0-9]+$")){ StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("emby注册的用户只能是数字或者英文,或者两个组合"); //发送消息 sendMessage(chatId,messageBuilder); return; } try { embyUserService.userNew(username,String.valueOf(chatId)); StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("emby注册成功,初始密码为空,登录不需要输入,建议修改密码\n"); messageBuilder.append("Emby用户名:"+username); //发送消息 sendMessage(chatId,messageBuilder); return; } catch (Exception e) { // 处理BusinessException的代码 StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("emby注册失败:\n"); messageBuilder.append(e.getMessage()); // 假设BusinessException有getMessage方法返回错误信息 sendMessage(chatId, messageBuilder); return; } } //删除emby账户:/delete if ("/delete".equals(update.getMessage().getText())){ //创建删除emby确定按钮 List<List<InlineKeyboardButton>> rowList = new ArrayList<>(); // 现在,为键盘创建一个列表,并将buttonRow添加为其行,第四个按钮 List<InlineKeyboardButton> deleteButtonRow = new ArrayList<>(); StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("请确认是否删除emby用户"); InlineKeyboardButton buttonA = InlineKeyboardButton.builder().text("是").callbackData("embyDelete_true").build(); InlineKeyboardButton buttonB = InlineKeyboardButton.builder().text("否").callbackData("embyDelete_false").build(); deleteButtonRow.add(buttonA); deleteButtonRow.add(buttonB); Collections.addAll(rowList,deleteButtonRow); InlineKeyboardMarkup inlineKeyboardMarkup = InlineKeyboardMarkup.builder().keyboard(rowList).build(); sendMessagesendMessage(chatId,messageBuilder,inlineKeyboardMarkup); return; } //重置emby密码:/reset if ("/reset".equals(update.getMessage().getText())){ try { embyUserService.userPassword(String.valueOf(chatId)); StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("emby重置成功,初始密码为空,登录不需要输入,建议修改密码"); sendMessage(chatId, messageBuilder); return; } catch (Exception e) { StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("emby重置失败"); messageBuilder.append(e.getMessage()); sendMessage(chatId, messageBuilder); return; } } //查看emby线路:/embyurl if ("/embyurl".equals(update.getMessage().getText())){ StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("emby服地址:\n"); messageBuilder.append("http://cf.imetyou.top (cf线路,可以加https访问)\n"); messageBuilder.append("http://emby.imetyou.top:8096 (随机线路)\n"); messageBuilder.append("http://fk.imetyou.top:8096 (落地机线路)\n"); messageBuilder.append("http://kr.imetyou.top:22333 (首尔中转)\n"); messageBuilder.append("http://sg.imetyou.top:22333 (新加坡中转)\n"); messageBuilder.append("http://chun.imetyou.top:22333 (春川中转)\n"); sendMessage(chatId, messageBuilder); return; } //创建音乐服账号:/musiccreate + 用户名 if (update.getMessage().getText().startsWith("/musiccreate ")){ //创建emby账户 String username = update.getMessage().getText().replace("/musiccreate ", "").trim(); //先判断用户名是否符合规则 if (!username.matches("^[a-zA-Z0-9]+$")){ StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("音乐服的注册的用户只能是数字或者英文,或者两个组合"); //发送消息 sendMessage(chatId,messageBuilder); return; } try { musicUserService.userNew(username,String.valueOf(chatId)); StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("音乐服成功,初始密码为用户名,建议修改密码\n"); messageBuilder.append("音乐服用户名:"+username); //发送消息 sendMessage(chatId,messageBuilder); return; } catch (Exception e) { // 处理BusinessException的代码 StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("音乐服注册失败:\n"); messageBuilder.append(e.getMessage()); // 假设BusinessException有getMessage方法返回错误信息 sendMessage(chatId, messageBuilder); return; } } //删除音乐服账户: /musicdelete if ("/musicdelete".equals(update.getMessage().getText())){ //创建删除音乐服确定按钮 List<List<InlineKeyboardButton>> rowList = new ArrayList<>(); // 现在,为键盘创建一个列表,并将buttonRow添加为其行 List<InlineKeyboardButton> deleteButtonRow = new ArrayList<>(); StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("请确认是否删除音乐服用户"); InlineKeyboardButton buttonA = InlineKeyboardButton.builder().text("是").callbackData("musicDelete_true").build(); InlineKeyboardButton buttonB = InlineKeyboardButton.builder().text("否").callbackData("musicDelete_false").build(); deleteButtonRow.add(buttonA); deleteButtonRow.add(buttonB); Collections.addAll(rowList,deleteButtonRow); InlineKeyboardMarkup inlineKeyboardMarkup = InlineKeyboardMarkup.builder().keyboard(rowList).build(); sendMessagesendMessage(chatId,messageBuilder,inlineKeyboardMarkup); return; } //重置音乐服密码:/musicreset if ("/musicreset".equals(update.getMessage().getText())){ try { musicUserService.userPassword(String.valueOf(chatId)); StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("音乐服重置成功,初始密码为用户名,建议修改密码"); sendMessage(chatId, messageBuilder); return; } catch (Exception e) { StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("音乐服重置失败"); messageBuilder.append(e.getMessage()); sendMessage(chatId, messageBuilder); return; } } //查看音乐服线路:/musicurl if ("/musicurl".equals(update.getMessage().getText())){ StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("音乐服地址:\n"); messageBuilder.append("chunmusic.imetyou.top (落地服务器线路) \n"); messageBuilder.append("cfmusic.imetyou.top (cf线路,可以加https访问))\n"); messageBuilder.append("music.imetyou.top (国内网盘线路)\n"); sendMessage(chatId, messageBuilder); return; } //求片:/forum 片名 TMDB链接求片 if (update.getMessage().getText().startsWith("/forum ")){ String regex = "^/forum (.*?) https://www\\.themoviedb\\.org/.+"; String messageText= update.getMessage().getText(); //先判断求片是否符合规则 if (!messageText.matches(regex)){ StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("求片格式不正确,请检查格式,然后重新求"); //发送消息 sendMessage(chatId,messageBuilder); return; } String[] upText = messageText.split(" "); //发送给管理员求片信息 StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("#求片 \n"); messageBuilder.append("影片名:"+upText[1]+"\n"); messageBuilder.append("TMDB链接: \n"); messageBuilder.append(upText[2]+"\n"); messageBuilder.append("TGID:@"+update.getMessage().getFrom().getUserName()); //发送消息 sendMessage(Long.parseLong(adminId),messageBuilder); //发送给用户反馈 StringBuilder usermMessageBuilder = new StringBuilder(); usermMessageBuilder.append("求片已经提交给管理员"); sendMessage(chatId,usermMessageBuilder); return; } //反馈:/bug if (update.getMessage().getText().startsWith("/bug ")){ String messageText= update.getMessage().getText(); String[] upText = messageText.split(" "); //发送给管理员反馈信息 StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("#反馈 \n"); messageBuilder.append(upText[1]+"\n"); messageBuilder.append("TGID:@"+update.getMessage().getFrom().getUserName()); //发送消息 sendMessage(Long.parseLong(adminId),messageBuilder); //发送给用户反馈 StringBuilder usermMessageBuilder = new StringBuilder(); usermMessageBuilder.append("反馈已经提交给管理员,感谢反馈!"); sendMessage(chatId,usermMessageBuilder); return; } //音乐下载搜索 if (update.getMessage().getText().startsWith("/musicsearch ")){ //创建搜索结果显示内联按钮 String keywords = update.getMessage().getText().replace("/musicsearch ", "").trim(); JSONObject search = musicDownloaderService.search(keywords,1,5); int listSize = search.getJSONArray("list").size(); StringBuilder messageBuilder = new StringBuilder(); for (int i = 0; i < listSize; i++) { String messageList=i+1+"."+" "+search.getJSONArray("list").getJSONObject(i).getString("readableText"); messageBuilder.append(messageList).append("\n"); } messageBuilder.append("\n").append("现在是第 1 页数据"); List<List<InlineKeyboardButton>> rowList = new ArrayList<>(); Integer cur = search.getJSONObject("page").getInteger("cur"); //创建第一行按钮:确认搜索结果 List<InlineKeyboardButton> buttonRow1 = new ArrayList<>(); for (int i = 0; i < listSize; i++) { InlineKeyboardButton button = InlineKeyboardButton.builder().text(String.valueOf(i+1)).callbackData("musicOk_"+i+"_"+search.getJSONObject("page").getInteger("cur")+"_"+keywords).build(); buttonRow1.add(button); } //创建第二行按钮:说明 List<InlineKeyboardButton> buttonRow2 = new ArrayList<>(); InlineKeyboardButton button2 = InlineKeyboardButton.builder().text("↑确认搜索结果, ↓下一页数据").callbackData("dummy_data").build(); buttonRow2.add(button2); //创建第三行按钮:页码 List<InlineKeyboardButton> buttonRow3 = new ArrayList<>(); for (int i = 0; i < search.getJSONObject("page").getInteger("size")/5; i++) { InlineKeyboardButton button3 = InlineKeyboardButton.builder().text(String.valueOf(i+1)).callbackData("musicSearch_"+(i+1)+"_"+keywords).build(); buttonRow3.add(button3); } // 现在,为键盘创建一个列表,并将buttonRow添加为其行 Collections.addAll(rowList,buttonRow1,buttonRow2,buttonRow3); InlineKeyboardMarkup inlineKeyboardMarkup = InlineKeyboardMarkup.builder().keyboard(rowList).build(); //回复内联消息 sendMessagesendMessage(chatId,messageBuilder,inlineKeyboardMarkup); } //查询账号信息:/info if ("/info".equals(update.getMessage().getText())){ try {
RestResp<EmbyUserInfoResp> userEmbyInfo = embyUserService.userInfo(String.valueOf(chatId));
3
2023-11-09 17:15:57+00:00
8k
AnhyDev/AnhyLingo
src/main/java/ink/anh/lingo/listeners/ItemsPacketListener.java
[ { "identifier": "AnhyLingo", "path": "src/main/java/ink/anh/lingo/AnhyLingo.java", "snippet": "public class AnhyLingo extends JavaPlugin {\n\n private static AnhyLingo instance;\n \n private boolean isSpigot;\n private boolean isPaper;\n private boolean isFolia;\n private boolean hasPa...
import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolManager; import com.comphenix.protocol.events.PacketAdapter; import com.comphenix.protocol.events.PacketEvent; import com.comphenix.protocol.events.ListenerPriority; import com.comphenix.protocol.reflect.StructureModifier; import com.comphenix.protocol.wrappers.nbt.NbtCompound; import com.comphenix.protocol.wrappers.nbt.NbtFactory; import ink.anh.api.utils.LangUtils; import ink.anh.lingo.AnhyLingo; import ink.anh.lingo.GlobalManager; import ink.anh.lingo.item.ItemLang; import java.util.Arrays; import java.util.List;
5,461
package ink.anh.lingo.listeners; /** * Listener for packet events related to items, handling the localization of ItemStacks based on player language settings. * This class intercepts and modifies packets to translate item names and lore for players. */ public class ItemsPacketListener { private AnhyLingo lingoPlugin;
package ink.anh.lingo.listeners; /** * Listener for packet events related to items, handling the localization of ItemStacks based on player language settings. * This class intercepts and modifies packets to translate item names and lore for players. */ public class ItemsPacketListener { private AnhyLingo lingoPlugin;
private GlobalManager globalManager;
1
2023-11-10 00:35:39+00:00
8k
Oselan/ExcelUtils
src/main/java/com/oselan/sample/UserService.java
[ { "identifier": "ConflictException", "path": "src/main/java/com/oselan/commons/exceptions/ConflictException.java", "snippet": "public class ConflictException extends BaseException {\n\tprivate static final long serialVersionUID = -8596472890741536409L;\n \n private static final String DEFAULT_ERROR_COD...
import java.io.IOException; import java.io.OutputStream; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import com.oselan.commons.exceptions.ConflictException; import com.oselan.excelexporter.ColumnDefinition; import com.oselan.excelexporter.ExcelExporter; import lombok.extern.slf4j.Slf4j;
5,263
package com.oselan.sample; @Service @Slf4j public class UserService { @Autowired private UserRepository userRepository; @Async // @SneakyThrows(InterruptedException.class) public void generateReport(OutputStream stream) throws ConflictException, IOException { log.info("Generating report ... "); List<ColumnDefinition> columnsDef = ColumnDefinition.listBuilder() .withColumn("Id", "id") .withColumn("First Name", "firstName") .withColumn("Last Name", "lastName") .build();
package com.oselan.sample; @Service @Slf4j public class UserService { @Autowired private UserRepository userRepository; @Async // @SneakyThrows(InterruptedException.class) public void generateReport(OutputStream stream) throws ConflictException, IOException { log.info("Generating report ... "); List<ColumnDefinition> columnsDef = ColumnDefinition.listBuilder() .withColumn("Id", "id") .withColumn("First Name", "firstName") .withColumn("Last Name", "lastName") .build();
ExcelExporter<UserDTO> exporter = new ExcelExporter<UserDTO>(stream, columnsDef, "User Sheet");
2
2023-11-03 20:17:51+00:00
8k
BaderTim/minecraft-measurement-mod
src/main/java/io/github/mmm/MMM.java
[ { "identifier": "DeviceController", "path": "src/main/java/io/github/mmm/measurement/device/DeviceController.java", "snippet": "public class DeviceController {\n\n private Boolean currentlyMeasuring;\n private int saveInterval;\n\n private String savePath;\n\n private boolean tickTimeWarning...
import com.mojang.logging.LogUtils; import io.github.mmm.measurement.device.DeviceController; import io.github.mmm.measurement.survey.SurveyController; import io.github.mmm.modconfig.Config; import net.minecraft.client.Minecraft; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.EntityJoinLevelEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import org.slf4j.Logger; import java.nio.file.Files; import java.nio.file.Paths;
7,019
package io.github.mmm; // The value here should match an entry in the META-INF/mods.toml file @Mod(MMM.MODID) public class MMM { // Define mod id in a common place for everything to reference public static final String MODID = "mmm"; // Directly reference a slf4j logger public static final Logger LOGGER = LogUtils.getLogger(); // Set file path public static final String MMM_ROOT_PATH = Minecraft.getInstance().gameDirectory.getPath() + "/mmm_data/"; // Create Device Controller object public static final DeviceController DEVICE_CONTROLLER = new DeviceController(); // Create Survey Controller object
package io.github.mmm; // The value here should match an entry in the META-INF/mods.toml file @Mod(MMM.MODID) public class MMM { // Define mod id in a common place for everything to reference public static final String MODID = "mmm"; // Directly reference a slf4j logger public static final Logger LOGGER = LogUtils.getLogger(); // Set file path public static final String MMM_ROOT_PATH = Minecraft.getInstance().gameDirectory.getPath() + "/mmm_data/"; // Create Device Controller object public static final DeviceController DEVICE_CONTROLLER = new DeviceController(); // Create Survey Controller object
public static final SurveyController SURVEY_CONTROLLER = new SurveyController();
1
2023-11-06 16:56:46+00:00
8k
KilianCollins/road-runner-quickstart-master
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/AutoLeague3/Auto_Test_path_hardcode.java
[ { "identifier": "SampleMecanumDrive", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java", "snippet": "@Config\n//@TeleOp(name=\"sample mechna drive \", group=\"Linear OpMode\")\npublic class SampleMecanumDrive extends MecanumDrive {\n public static PIDCoeffi...
import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.util.ElapsedTime; import org.checkerframework.checker.units.qual.A; import org.firstinspires.ftc.teamcode.drive.SampleMecanumDrive; import org.firstinspires.ftc.teamcode.util.Encoder;
3,747
package org.firstinspires.ftc.teamcode.drive.AutoLeague3; @Autonomous(name = "path test 12.19.23 back and forth stop") public class Auto_Test_path_hardcode extends LinearOpMode { private ElapsedTime runtime = new ElapsedTime(); private DcMotor leftFrontDrive, leftBackDrive, rightFrontDrive, rightBackDrive = null;
package org.firstinspires.ftc.teamcode.drive.AutoLeague3; @Autonomous(name = "path test 12.19.23 back and forth stop") public class Auto_Test_path_hardcode extends LinearOpMode { private ElapsedTime runtime = new ElapsedTime(); private DcMotor leftFrontDrive, leftBackDrive, rightFrontDrive, rightBackDrive = null;
private Encoder leftEncoder, rightEncoder = null;
1
2023-11-04 04:11:26+00:00
8k
InfantinoAndrea00/polimi-software-engineering-project-2022
src/main/java/it/polimi/ingsw/server/Server.java
[ { "identifier": "ViewObserver", "path": "src/main/java/it/polimi/ingsw/server/controller/ViewObserver.java", "snippet": "public class ViewObserver {\n private GameController gameController;\n private int counter;\n private boolean canAddPlayer;\n private CharacterCardHandler characterCardHan...
import it.polimi.ingsw.server.controller.ViewObserver; import it.polimi.ingsw.server.model.Game; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.atomic.AtomicBoolean;
4,551
package it.polimi.ingsw.server; public class Server { public static final int PORT = 5555; public static ViewObserver viewObserver; public static AtomicBoolean creatingGame;
package it.polimi.ingsw.server; public class Server { public static final int PORT = 5555; public static ViewObserver viewObserver; public static AtomicBoolean creatingGame;
public static Game game;
1
2023-11-06 00:50:18+00:00
8k
conductor-oss/conductor
java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/tasks/Javascript.java
[ { "identifier": "TaskType", "path": "common/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskType.java", "snippet": "@ProtoEnum\npublic enum TaskType {\n SIMPLE,\n DYNAMIC,\n FORK_JOIN,\n FORK_JOIN_DYNAMIC,\n DECISION,\n SWITCH,\n JOIN,\n DO_WHILE,\n SUB_WORKFLOW,...
import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.script.Bindings; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.sdk.workflow.def.ValidationError; import com.google.common.base.Strings;
6,947
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <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 com.netflix.conductor.sdk.workflow.def.tasks; /** * JQ Transformation task See https://stedolan.github.io/jq/ for how to form the queries to parse * JSON payloads */ public class Javascript extends Task<Javascript> { private static final Logger LOGGER = LoggerFactory.getLogger(Javascript.class); private static final String EXPRESSION_PARAMETER = "expression"; private static final String EVALUATOR_TYPE_PARAMETER = "evaluatorType"; private static final String ENGINE = "nashorn"; /** * Javascript tasks are executed on the Conductor server without having to write worker code * * <p>Use {@link Javascript#validate()} method to validate the javascript to ensure the script * is valid. * * @param taskReferenceName * @param script script to execute */ public Javascript(String taskReferenceName, String script) { super(taskReferenceName, TaskType.INLINE); if (Strings.isNullOrEmpty(script)) { throw new AssertionError("Null/Empty script"); } super.input(EVALUATOR_TYPE_PARAMETER, "javascript"); super.input(EXPRESSION_PARAMETER, script); } /** * Javascript tasks are executed on the Conductor server without having to write worker code * * <p>Use {@link Javascript#validate()} method to validate the javascript to ensure the script * is valid. * * @param taskReferenceName * @param stream stream to load the script file from */ public Javascript(String taskReferenceName, InputStream stream) { super(taskReferenceName, TaskType.INLINE); if (stream == null) { throw new AssertionError("Stream is empty"); } super.input(EVALUATOR_TYPE_PARAMETER, "javascript"); try { String script = new String(stream.readAllBytes()); super.input(EXPRESSION_PARAMETER, script); } catch (IOException e) { throw new RuntimeException(e); } }
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <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 com.netflix.conductor.sdk.workflow.def.tasks; /** * JQ Transformation task See https://stedolan.github.io/jq/ for how to form the queries to parse * JSON payloads */ public class Javascript extends Task<Javascript> { private static final Logger LOGGER = LoggerFactory.getLogger(Javascript.class); private static final String EXPRESSION_PARAMETER = "expression"; private static final String EVALUATOR_TYPE_PARAMETER = "evaluatorType"; private static final String ENGINE = "nashorn"; /** * Javascript tasks are executed on the Conductor server without having to write worker code * * <p>Use {@link Javascript#validate()} method to validate the javascript to ensure the script * is valid. * * @param taskReferenceName * @param script script to execute */ public Javascript(String taskReferenceName, String script) { super(taskReferenceName, TaskType.INLINE); if (Strings.isNullOrEmpty(script)) { throw new AssertionError("Null/Empty script"); } super.input(EVALUATOR_TYPE_PARAMETER, "javascript"); super.input(EXPRESSION_PARAMETER, script); } /** * Javascript tasks are executed on the Conductor server without having to write worker code * * <p>Use {@link Javascript#validate()} method to validate the javascript to ensure the script * is valid. * * @param taskReferenceName * @param stream stream to load the script file from */ public Javascript(String taskReferenceName, InputStream stream) { super(taskReferenceName, TaskType.INLINE); if (stream == null) { throw new AssertionError("Stream is empty"); } super.input(EVALUATOR_TYPE_PARAMETER, "javascript"); try { String script = new String(stream.readAllBytes()); super.input(EXPRESSION_PARAMETER, script); } catch (IOException e) { throw new RuntimeException(e); } }
Javascript(WorkflowTask workflowTask) {
1
2023-12-08 06:06:09+00:00
8k
10cks/fofaEX
src/main/java/plugins/CommonTemplate.java
[ { "identifier": "RightClickFunctions", "path": "src/main/java/tableInit/RightClickFunctions.java", "snippet": "public class RightClickFunctions {\n // 在类的成员变量中创建弹出菜单\n public static JPopupMenu popupMenu = new JPopupMenu();\n private static JMenuItem itemSelectColumn = new JMenuItem(\"选择当前整列\");...
import com.google.gson.*; import com.google.gson.stream.JsonReader; import org.json.JSONArray; import org.json.JSONObject; import tableInit.RightClickFunctions; import javax.swing.*; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.*; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.LinkedHashMap; import java.util.Map; import java.util.List; import java.util.Vector; import java.util.concurrent.atomic.AtomicBoolean; import static java.awt.BorderLayout.CENTER; import static tableInit.GetjTableHeader.adjustColumnWidths; import static tableInit.GetjTableHeader.getjTableHeader; import static tableInit.RightClickFunctions.popupMenu;
4,404
System.out.println("[+] Successfully saved JSON data to " + filename); } catch (IOException e) { e.printStackTrace(); } }); } // 用与保存 table 数据 private static JScrollPane findScrollPane(Container container) { for (Component comp : container.getComponents()) { if (comp instanceof JScrollPane) { return (JScrollPane) comp; } else if (comp instanceof Container) { JScrollPane scrollPane = findScrollPane((Container) comp); if (scrollPane != null) { return scrollPane; } } } return null; } // 动态创建子菜单,核心代码 public static void addMenuItemsFromFile(JMenu pluginMenu, JTabbedPane tabbedPane) { EventQueue.invokeLater(() -> { Path file = Paths.get(allPluginsPath + "AllPlugins.json"); if (!Files.exists(file)) { // 如果不存在这个文件,则新建这个文件 try { Files.createDirectories(file.getParent()); Files.createFile(file); } catch (IOException e) { e.printStackTrace(); } } try { // Create a new Gson Gson gson = new Gson(); if (Files.size(file) == 0) { System.out.println("[!] 当前无第三方插件"); return; } // Read the JSON from the file into a Map Map<String, Boolean> plugins = gson.fromJson( new FileReader(file.toFile()), Map.class); // Process each plugin for (Map.Entry<String, Boolean> plugin : plugins.entrySet()) { // Only process plugins that are enabled if (plugin.getValue()) { // 检查对应的插件的文件夹和json文件是否都存在 String pluginFolderPath = allPluginsPath + plugin.getKey(); String pluginJsonPath = pluginFolderPath + "/" + plugin.getKey() + "Setting.json"; if (!Files.exists(Paths.get(pluginFolderPath))) { System.out.println("[-] 当前插件 " + plugin.getKey() + " 缺失文件夹:" + pluginFolderPath); continue; } if (!Files.exists(Paths.get(pluginJsonPath))) { System.out.println("[-] 当前插件 " + plugin.getKey() + " 缺失文件:" + pluginJsonPath); continue; } // 创建插件的菜单项 JMenu submenu = new JMenu(plugin.getKey()); System.out.println("[+] 当前插件 " + plugin.getKey() + " 已加载"); // 为插件添加"运行"、"设置"、"关于"三个选项 JMenuItem runItem = new JMenuItem("运行"); JMenuItem settingItem = new JMenuItem("设置"); JMenuItem aboutItem = new JMenuItem("关于"); // 对菜单项添加相应的事件处理器 runItem.addActionListener(event -> { addPluginFrame(pluginJsonPath, plugin.getKey(), tabbedPane); // 弹出运行面板 }); settingItem.addActionListener(event -> { // 这里添加设置的事件处理代码 addPluginsSettingOpen(pluginJsonPath); }); aboutItem.addActionListener(event -> { // 这里添加关于的事件处理代码 addPluginAbout(pluginJsonPath); }); // 把菜单项添加到子菜单中 submenu.add(runItem); submenu.add(settingItem); submenu.add(aboutItem); // 把子菜单添加到主菜单中 pluginMenu.add(submenu); } } } catch (IOException e) { e.printStackTrace(); } }); } // 点击运行新增 tab 页 public static void addPluginTab(JTabbedPane tabbedPane, String pluginName, String pluginJsonPath) { // 检查标签是否已经存在 if (tabbedPane.indexOfTab(pluginName) != -1) { int existingTabIndex = tabbedPane.indexOfTab(pluginName); tabbedPane.removeTabAt(existingTabIndex); } //ActionListener在选择“关闭”时关闭标签页 ActionListener closeListener = event -> tabbedPane.removeTabAt(tabbedPane.indexOfTab(pluginName)); // 创建表格 JTable table = createTableFromJson(pluginJsonPath); // 清理可能已经添加的菜单项 // 初始化 table 右键
package plugins; public class CommonTemplate { private static String pluginName = ""; private static String allPluginsPath = "./plugins/"; private static Process runningProcess = null; static AtomicBoolean wasManuallyStopped = new AtomicBoolean(false); public static JLabel addBanner(String banner) { JLabel labelIcon = new JLabel(banner); labelIcon.setForeground(new Color(48, 49, 52)); Font iconFont = new Font("Times New Roman", Font.BOLD, 60); labelIcon.setFont(iconFont); return labelIcon; } // 保存 table 核心代码到对应 json 文件中 public static void saveTableData(JTabbedPane tabbedPane) { EventQueue.invokeLater(() -> { // 检查或创建coredata文件夹 File directory = new File("coredata"); if (!directory.exists()) { directory.mkdir(); } // 获取当前选中的标签索引 int selectedIndex = tabbedPane.getSelectedIndex(); if (selectedIndex == -1) { // 如果没有选中的标签,不执行任何操作 return; } // 获取当前选中的标签的标题 String tabName = tabbedPane.getTitleAt(selectedIndex); // 获取选中的标签对应的组件 Component selectedComponent = tabbedPane.getComponentAt(selectedIndex); if (!(selectedComponent instanceof JPanel)) { System.err.println("The selected component is not a JPanel."); return; } JPanel panel = (JPanel) selectedComponent; // 查找JScrollPane组件 JScrollPane scrollPane = findScrollPane(panel); if (scrollPane == null) { System.err.println("No JScrollPane found in the selected tab."); return; } // 获取JTable JTable table = (JTable) scrollPane.getViewport().getView(); // 转换表格数据为JSON JSONArray jsonArray = new JSONArray(); for (int row = 0; row < table.getRowCount(); row++) { JSONObject rowJson = new JSONObject(); for (int col = 0; col < table.getColumnCount(); col++) { rowJson.put(table.getColumnName(col), table.getValueAt(row, col)); } jsonArray.put(rowJson); } // 写入JSON文件 String filename = "coredata/" + tabName + ".json"; try (FileWriter file = new FileWriter(filename)) { file.write(jsonArray.toString(4)); // 缩进为4个空格 System.out.println("[+] Successfully saved JSON data to " + filename); } catch (IOException e) { e.printStackTrace(); } }); } // 用与保存 table 数据 private static JScrollPane findScrollPane(Container container) { for (Component comp : container.getComponents()) { if (comp instanceof JScrollPane) { return (JScrollPane) comp; } else if (comp instanceof Container) { JScrollPane scrollPane = findScrollPane((Container) comp); if (scrollPane != null) { return scrollPane; } } } return null; } // 动态创建子菜单,核心代码 public static void addMenuItemsFromFile(JMenu pluginMenu, JTabbedPane tabbedPane) { EventQueue.invokeLater(() -> { Path file = Paths.get(allPluginsPath + "AllPlugins.json"); if (!Files.exists(file)) { // 如果不存在这个文件,则新建这个文件 try { Files.createDirectories(file.getParent()); Files.createFile(file); } catch (IOException e) { e.printStackTrace(); } } try { // Create a new Gson Gson gson = new Gson(); if (Files.size(file) == 0) { System.out.println("[!] 当前无第三方插件"); return; } // Read the JSON from the file into a Map Map<String, Boolean> plugins = gson.fromJson( new FileReader(file.toFile()), Map.class); // Process each plugin for (Map.Entry<String, Boolean> plugin : plugins.entrySet()) { // Only process plugins that are enabled if (plugin.getValue()) { // 检查对应的插件的文件夹和json文件是否都存在 String pluginFolderPath = allPluginsPath + plugin.getKey(); String pluginJsonPath = pluginFolderPath + "/" + plugin.getKey() + "Setting.json"; if (!Files.exists(Paths.get(pluginFolderPath))) { System.out.println("[-] 当前插件 " + plugin.getKey() + " 缺失文件夹:" + pluginFolderPath); continue; } if (!Files.exists(Paths.get(pluginJsonPath))) { System.out.println("[-] 当前插件 " + plugin.getKey() + " 缺失文件:" + pluginJsonPath); continue; } // 创建插件的菜单项 JMenu submenu = new JMenu(plugin.getKey()); System.out.println("[+] 当前插件 " + plugin.getKey() + " 已加载"); // 为插件添加"运行"、"设置"、"关于"三个选项 JMenuItem runItem = new JMenuItem("运行"); JMenuItem settingItem = new JMenuItem("设置"); JMenuItem aboutItem = new JMenuItem("关于"); // 对菜单项添加相应的事件处理器 runItem.addActionListener(event -> { addPluginFrame(pluginJsonPath, plugin.getKey(), tabbedPane); // 弹出运行面板 }); settingItem.addActionListener(event -> { // 这里添加设置的事件处理代码 addPluginsSettingOpen(pluginJsonPath); }); aboutItem.addActionListener(event -> { // 这里添加关于的事件处理代码 addPluginAbout(pluginJsonPath); }); // 把菜单项添加到子菜单中 submenu.add(runItem); submenu.add(settingItem); submenu.add(aboutItem); // 把子菜单添加到主菜单中 pluginMenu.add(submenu); } } } catch (IOException e) { e.printStackTrace(); } }); } // 点击运行新增 tab 页 public static void addPluginTab(JTabbedPane tabbedPane, String pluginName, String pluginJsonPath) { // 检查标签是否已经存在 if (tabbedPane.indexOfTab(pluginName) != -1) { int existingTabIndex = tabbedPane.indexOfTab(pluginName); tabbedPane.removeTabAt(existingTabIndex); } //ActionListener在选择“关闭”时关闭标签页 ActionListener closeListener = event -> tabbedPane.removeTabAt(tabbedPane.indexOfTab(pluginName)); // 创建表格 JTable table = createTableFromJson(pluginJsonPath); // 清理可能已经添加的菜单项 // 初始化 table 右键
RightClickFunctions.table = table;
0
2023-12-07 13:46:27+00:00
8k
specmock/specmock
specmock/src/test/java/io/specmock/core/SpringWebTest.java
[ { "identifier": "Example1Request", "path": "specmock/src/test/java/io/specmock/core/example/Example1Request.java", "snippet": "public class Example1Request {\n private String stringValue;\n private Integer integerValue;\n private Long longValue;\n private BigDecimal bigDecimalValue;\n\n /...
import static org.assertj.core.api.Assertions.assertThat; import java.math.BigDecimal; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.kotlin.KotlinModule; import com.linecorp.armeria.client.WebClient; import io.specmock.core.example.Example1Request; import io.specmock.core.example.Example1Response; import io.specmock.core.example.Example2Response; import io.specmock.core.example.Example3Request; import io.specmock.core.example.Example3Response; import io.specmock.core.example.Example4Request; import io.specmock.core.example.Example4Response; import io.specmock.core.example.Example5Request; import io.specmock.core.example.Example5Response; import io.specmock.core.example.Example6Request; import io.specmock.core.example.Example6Response; import io.specmock.core.example.Example7Request; import io.specmock.core.example.Example7Response; import io.specmock.core.example.Example8Response; import io.specmock.core.example.ExampleApi;
5,827
/* * Copyright 2023 SpecMock * (c) 2023 SpecMock Contributors * SPDX-License-Identifier: Apache-2.0 * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.specmock.core; class SpringWebTest { private static final String RESPONSE_VALUE = "SUCCESS"; private final ObjectMapper mapper = new ObjectMapper().registerModule(new KotlinModule.Builder().build()); private final WebClient webClient = WebClient.of("http://localhost:18080"); private HttpSpecServer specServer; private Example1Request example1Request; private Example3Request example3Request; private Example4Request example4Request; private Example5Request example5Request; private Example6Request example6Request; private Example7Request example7Request; @BeforeEach void setUp() { example1Request = new Example1Request("EXAMPLE1", 10, 10L, BigDecimal.TEN); example3Request = new Example3Request("EXAMPLE3", 10, 10L, BigDecimal.TEN); example4Request = new Example4Request("EXAMPLE4", 10, 10L, BigDecimal.TEN); example5Request = new Example5Request("EXAMPLE5", 10, 10L, BigDecimal.TEN); example6Request = new Example6Request("EXAMPLE6", 10, 10L, BigDecimal.TEN); example7Request = new Example7Request("EXAMPLE7", 10, 10L, BigDecimal.TEN); final List<HttpSpec> specs = HttpSpec.springWebBuilder() .springWebBind(ExampleApi.class) .exchanges( HttpExchange.builder() .requestObject(example1Request) .responseObject( new Example1Response(RESPONSE_VALUE) ) .build(), HttpExchange.builder() .responseObject( new Example2Response(RESPONSE_VALUE) ) .build(), HttpExchange.builder() .requestObject(example3Request) .responseObject( new Example3Response(RESPONSE_VALUE) ) .build(), HttpExchange.builder() .requestObject(example4Request) .responseObject( new Example4Response(RESPONSE_VALUE) ) .build(), HttpExchange.builder() .requestObject(example5Request) .queryParamMap(example5_QueryMap()) .responseObject( new Example5Response(RESPONSE_VALUE) ) .build(), HttpExchange.builder() .requestObject(example6Request) .pathParamMap(example6_PathMap()) .responseObject(
/* * Copyright 2023 SpecMock * (c) 2023 SpecMock Contributors * SPDX-License-Identifier: Apache-2.0 * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.specmock.core; class SpringWebTest { private static final String RESPONSE_VALUE = "SUCCESS"; private final ObjectMapper mapper = new ObjectMapper().registerModule(new KotlinModule.Builder().build()); private final WebClient webClient = WebClient.of("http://localhost:18080"); private HttpSpecServer specServer; private Example1Request example1Request; private Example3Request example3Request; private Example4Request example4Request; private Example5Request example5Request; private Example6Request example6Request; private Example7Request example7Request; @BeforeEach void setUp() { example1Request = new Example1Request("EXAMPLE1", 10, 10L, BigDecimal.TEN); example3Request = new Example3Request("EXAMPLE3", 10, 10L, BigDecimal.TEN); example4Request = new Example4Request("EXAMPLE4", 10, 10L, BigDecimal.TEN); example5Request = new Example5Request("EXAMPLE5", 10, 10L, BigDecimal.TEN); example6Request = new Example6Request("EXAMPLE6", 10, 10L, BigDecimal.TEN); example7Request = new Example7Request("EXAMPLE7", 10, 10L, BigDecimal.TEN); final List<HttpSpec> specs = HttpSpec.springWebBuilder() .springWebBind(ExampleApi.class) .exchanges( HttpExchange.builder() .requestObject(example1Request) .responseObject( new Example1Response(RESPONSE_VALUE) ) .build(), HttpExchange.builder() .responseObject( new Example2Response(RESPONSE_VALUE) ) .build(), HttpExchange.builder() .requestObject(example3Request) .responseObject( new Example3Response(RESPONSE_VALUE) ) .build(), HttpExchange.builder() .requestObject(example4Request) .responseObject( new Example4Response(RESPONSE_VALUE) ) .build(), HttpExchange.builder() .requestObject(example5Request) .queryParamMap(example5_QueryMap()) .responseObject( new Example5Response(RESPONSE_VALUE) ) .build(), HttpExchange.builder() .requestObject(example6Request) .pathParamMap(example6_PathMap()) .responseObject(
new Example6Response(RESPONSE_VALUE)
10
2023-12-13 10:43:07+00:00
8k
Mahmud0808/ColorBlendr
app/src/main/java/com/drdisagree/colorblendr/utils/monet/hct/ViewingConditions.java
[ { "identifier": "ColorUtils", "path": "app/src/main/java/com/drdisagree/colorblendr/utils/monet/utils/ColorUtils.java", "snippet": "public class ColorUtils {\n static final double[][] SRGB_TO_XYZ =\n new double[][]{\n new double[]{0.41233895, 0.35762064, 0.18051042},\n ...
import com.drdisagree.colorblendr.utils.monet.utils.ColorUtils; import com.drdisagree.colorblendr.utils.monet.utils.MathUtils;
5,352
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.drdisagree.colorblendr.utils.monet.hct; /** * In traditional color spaces, a color can be identified solely by the observer's measurement of * the color. Color appearance models such as CAM16 also use information about the environment where * the color was observed, known as the viewing conditions. * * <p>For example, white under the traditional assumption of a midday sun white point is accurately * measured as a slightly chromatic blue by CAM16. (roughly, hue 203, chroma 3, lightness 100) * * <p>This class caches intermediate values of the CAM16 conversion process that depend only on * viewing conditions, enabling speed ups. */ public final class ViewingConditions { /** * sRGB-like viewing conditions. */ public static final ViewingConditions DEFAULT = ViewingConditions.defaultWithBackgroundLstar(50.0); private final double aw; private final double nbb; private final double ncb; private final double c; private final double nc; private final double n; private final double[] rgbD; private final double fl; private final double flRoot; private final double z; /** * Parameters are intermediate values of the CAM16 conversion process. Their names are shorthand * for technical color science terminology, this class would not benefit from documenting them * individually. A brief overview is available in the CAM16 specification, and a complete overview * requires a color science textbook, such as Fairchild's Color Appearance Models. */ private ViewingConditions( double n, double aw, double nbb, double ncb, double c, double nc, double[] rgbD, double fl, double flRoot, double z) { this.n = n; this.aw = aw; this.nbb = nbb; this.ncb = ncb; this.c = c; this.nc = nc; this.rgbD = rgbD; this.fl = fl; this.flRoot = flRoot; this.z = z; } /** * Create ViewingConditions from a simple, physically relevant, set of parameters. * * @param whitePoint White point, measured in the XYZ color space. default = D65, or sunny day * afternoon * @param adaptingLuminance The luminance of the adapting field. Informally, how bright it is in * the room where the color is viewed. Can be calculated from lux by multiplying lux by * 0.0586. default = 11.72, or 200 lux. * @param backgroundLstar The lightness of the area surrounding the color. measured by L* in * L*a*b*. default = 50.0 * @param surround A general description of the lighting surrounding the color. 0 is pitch dark, * like watching a movie in a theater. 1.0 is a dimly light room, like watching TV at home at * night. 2.0 means there is no difference between the lighting on the color and around it. * default = 2.0 * @param discountingIlluminant Whether the eye accounts for the tint of the ambient lighting, * such as knowing an apple is still red in green light. default = false, the eye does not * perform this process on self-luminous objects like displays. */ public static ViewingConditions make( double[] whitePoint, double adaptingLuminance, double backgroundLstar, double surround, boolean discountingIlluminant) { // A background of pure black is non-physical and leads to infinities that represent the idea // that any color viewed in pure black can't be seen. backgroundLstar = Math.max(0.1, backgroundLstar); // Transform white point XYZ to 'cone'/'rgb' responses double[][] matrix = Cam16.XYZ_TO_CAM16RGB; double[] xyz = whitePoint; double rW = (xyz[0] * matrix[0][0]) + (xyz[1] * matrix[0][1]) + (xyz[2] * matrix[0][2]); double gW = (xyz[0] * matrix[1][0]) + (xyz[1] * matrix[1][1]) + (xyz[2] * matrix[1][2]); double bW = (xyz[0] * matrix[2][0]) + (xyz[1] * matrix[2][1]) + (xyz[2] * matrix[2][2]); double f = 0.8 + (surround / 10.0); double c = (f >= 0.9) ? MathUtils.lerp(0.59, 0.69, ((f - 0.9) * 10.0)) : MathUtils.lerp(0.525, 0.59, ((f - 0.8) * 10.0)); double d = discountingIlluminant ? 1.0 : f * (1.0 - ((1.0 / 3.6) * Math.exp((-adaptingLuminance - 42.0) / 92.0))); d = MathUtils.clampDouble(0.0, 1.0, d); double nc = f; double[] rgbD = new double[]{ d * (100.0 / rW) + 1.0 - d, d * (100.0 / gW) + 1.0 - d, d * (100.0 / bW) + 1.0 - d }; double k = 1.0 / (5.0 * adaptingLuminance + 1.0); double k4 = k * k * k * k; double k4F = 1.0 - k4; double fl = (k4 * adaptingLuminance) + (0.1 * k4F * k4F * Math.cbrt(5.0 * adaptingLuminance));
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.drdisagree.colorblendr.utils.monet.hct; /** * In traditional color spaces, a color can be identified solely by the observer's measurement of * the color. Color appearance models such as CAM16 also use information about the environment where * the color was observed, known as the viewing conditions. * * <p>For example, white under the traditional assumption of a midday sun white point is accurately * measured as a slightly chromatic blue by CAM16. (roughly, hue 203, chroma 3, lightness 100) * * <p>This class caches intermediate values of the CAM16 conversion process that depend only on * viewing conditions, enabling speed ups. */ public final class ViewingConditions { /** * sRGB-like viewing conditions. */ public static final ViewingConditions DEFAULT = ViewingConditions.defaultWithBackgroundLstar(50.0); private final double aw; private final double nbb; private final double ncb; private final double c; private final double nc; private final double n; private final double[] rgbD; private final double fl; private final double flRoot; private final double z; /** * Parameters are intermediate values of the CAM16 conversion process. Their names are shorthand * for technical color science terminology, this class would not benefit from documenting them * individually. A brief overview is available in the CAM16 specification, and a complete overview * requires a color science textbook, such as Fairchild's Color Appearance Models. */ private ViewingConditions( double n, double aw, double nbb, double ncb, double c, double nc, double[] rgbD, double fl, double flRoot, double z) { this.n = n; this.aw = aw; this.nbb = nbb; this.ncb = ncb; this.c = c; this.nc = nc; this.rgbD = rgbD; this.fl = fl; this.flRoot = flRoot; this.z = z; } /** * Create ViewingConditions from a simple, physically relevant, set of parameters. * * @param whitePoint White point, measured in the XYZ color space. default = D65, or sunny day * afternoon * @param adaptingLuminance The luminance of the adapting field. Informally, how bright it is in * the room where the color is viewed. Can be calculated from lux by multiplying lux by * 0.0586. default = 11.72, or 200 lux. * @param backgroundLstar The lightness of the area surrounding the color. measured by L* in * L*a*b*. default = 50.0 * @param surround A general description of the lighting surrounding the color. 0 is pitch dark, * like watching a movie in a theater. 1.0 is a dimly light room, like watching TV at home at * night. 2.0 means there is no difference between the lighting on the color and around it. * default = 2.0 * @param discountingIlluminant Whether the eye accounts for the tint of the ambient lighting, * such as knowing an apple is still red in green light. default = false, the eye does not * perform this process on self-luminous objects like displays. */ public static ViewingConditions make( double[] whitePoint, double adaptingLuminance, double backgroundLstar, double surround, boolean discountingIlluminant) { // A background of pure black is non-physical and leads to infinities that represent the idea // that any color viewed in pure black can't be seen. backgroundLstar = Math.max(0.1, backgroundLstar); // Transform white point XYZ to 'cone'/'rgb' responses double[][] matrix = Cam16.XYZ_TO_CAM16RGB; double[] xyz = whitePoint; double rW = (xyz[0] * matrix[0][0]) + (xyz[1] * matrix[0][1]) + (xyz[2] * matrix[0][2]); double gW = (xyz[0] * matrix[1][0]) + (xyz[1] * matrix[1][1]) + (xyz[2] * matrix[1][2]); double bW = (xyz[0] * matrix[2][0]) + (xyz[1] * matrix[2][1]) + (xyz[2] * matrix[2][2]); double f = 0.8 + (surround / 10.0); double c = (f >= 0.9) ? MathUtils.lerp(0.59, 0.69, ((f - 0.9) * 10.0)) : MathUtils.lerp(0.525, 0.59, ((f - 0.8) * 10.0)); double d = discountingIlluminant ? 1.0 : f * (1.0 - ((1.0 / 3.6) * Math.exp((-adaptingLuminance - 42.0) / 92.0))); d = MathUtils.clampDouble(0.0, 1.0, d); double nc = f; double[] rgbD = new double[]{ d * (100.0 / rW) + 1.0 - d, d * (100.0 / gW) + 1.0 - d, d * (100.0 / bW) + 1.0 - d }; double k = 1.0 / (5.0 * adaptingLuminance + 1.0); double k4 = k * k * k * k; double k4F = 1.0 - k4; double fl = (k4 * adaptingLuminance) + (0.1 * k4F * k4F * Math.cbrt(5.0 * adaptingLuminance));
double n = (ColorUtils.yFromLstar(backgroundLstar) / whitePoint[1]);
0
2023-12-06 13:20:16+00:00
8k
bzvs1992/spring-boot-holiday-starter
src/main/java/cn/bzvs/holiday/service/HolidayService.java
[ { "identifier": "ConstantData", "path": "src/main/java/cn/bzvs/holiday/autoconfigure/ConstantData.java", "snippet": "public class ConstantData {\n\n /**\n * 所有日期数据\n */\n private static final Map<String, CalendarVO> ALL_DATE_MAP = new ConcurrentHashMap<>();\n\n /**\n * 初始化,并设置数据\n ...
import cn.bzvs.holiday.autoconfigure.ConstantData; import cn.bzvs.holiday.entity.vo.CalendarInfoVO; import cn.bzvs.holiday.entity.vo.CalendarVO; import cn.bzvs.holiday.util.HolidayUtil; import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateUtil; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Date; import java.util.Map;
3,632
package cn.bzvs.holiday.service; /** * 节假日相关的日历服务 * * @author bzvs * @date 2024/12/06 * @since 1.0.0 */ public class HolidayService { private static final String format = "yyyy-MM-dd"; /** * 获取指定日期的节假日信息 * @param date * @return HolidayVO */ public CalendarInfoVO getDate(Date date) { String day = DateUtil.format(date, format); return getDate(day); } /** * 获取指定日期的节假日信息 * @param localDate * @return HolidayVO */ public CalendarInfoVO getDate(LocalDate localDate) { String day = DateUtil.format(localDate.atStartOfDay(), format); return getDate(day); } /** * 获取指定日期的节假日信息 * @param localDateTime * @return HolidayVO */ public CalendarInfoVO getDate(LocalDateTime localDateTime) { String day = DateUtil.format(localDateTime, format); return getDate(day); } /** * 获取指定日期的节假日信息 * @param date 日期格式:yyyy-MM-dd * @return HolidayVO */ public CalendarInfoVO getDate(String date) { return getVo(date); } /** * 是否是节假日 * @param date * @return boolean */ public boolean isHoliday(Date date) { String day = DateUtil.format(date, format); return isHoliday(day); } /** * 是否是节假日 * @param localDate * @return boolean */ public boolean isHoliday(LocalDate localDate) { return isHoliday(localDate.atStartOfDay()); } /** * 是否是节假日 * @param localDateTime * @return boolean */ public boolean isHoliday(LocalDateTime localDateTime) { String day = DateUtil.format(localDateTime, format); return isHoliday(day); } /** * 是否是节假日 * @param day * @return boolean */ public boolean isHoliday(String day) { CalendarVO vo = getDate(day); return vo.getStatus() == 3; } /** * 是否是工作日或补班 * @param date * @return boolean */ public boolean isWorkDay(Date date) { String day = DateUtil.format(date, format); return isWorkDay(day); } /** * 是否是工作日或补班 * @param localDate * @return boolean */ public boolean isWorkDay(LocalDate localDate) { return isWorkDay(localDate.atStartOfDay()); } /** * 是否是工作日或补班 * @param localDateTime * @return boolean */ public boolean isWorkDay(LocalDateTime localDateTime) { String day = DateUtil.format(localDateTime, format); return isWorkDay(day); } /** * 是否是工作日或补班 * @param day * @return boolean */ public boolean isWorkDay(String day) { CalendarVO vo = getDate(day); return vo.getStatus() == 0 || vo.getStatus() == 2; } /** * 是否是周末 * @param date * @return boolean */ public boolean isWeekend(Date date) { String day = DateUtil.format(date, format); return isWeekend(day); } /** * 是否是周末 * @param localDate * @return boolean */ public boolean isWeekend(LocalDate localDate) { return isWeekend(localDate.atStartOfDay()); } /** * 是否是周末 * @param localDateTime * @return boolean */ public boolean isWeekend(LocalDateTime localDateTime) { String day = DateUtil.format(localDateTime, format); return isWeekend(day); } /** * 是否是周末 * @param day * @return boolean */ public boolean isWeekend(String day) { CalendarVO vo = getDate(day); return vo.getStatus() == 1; } private static CalendarInfoVO getVo(String date) { DateTime dateTime = DateUtil.parseDate(date); CalendarInfoVO infoVO;
package cn.bzvs.holiday.service; /** * 节假日相关的日历服务 * * @author bzvs * @date 2024/12/06 * @since 1.0.0 */ public class HolidayService { private static final String format = "yyyy-MM-dd"; /** * 获取指定日期的节假日信息 * @param date * @return HolidayVO */ public CalendarInfoVO getDate(Date date) { String day = DateUtil.format(date, format); return getDate(day); } /** * 获取指定日期的节假日信息 * @param localDate * @return HolidayVO */ public CalendarInfoVO getDate(LocalDate localDate) { String day = DateUtil.format(localDate.atStartOfDay(), format); return getDate(day); } /** * 获取指定日期的节假日信息 * @param localDateTime * @return HolidayVO */ public CalendarInfoVO getDate(LocalDateTime localDateTime) { String day = DateUtil.format(localDateTime, format); return getDate(day); } /** * 获取指定日期的节假日信息 * @param date 日期格式:yyyy-MM-dd * @return HolidayVO */ public CalendarInfoVO getDate(String date) { return getVo(date); } /** * 是否是节假日 * @param date * @return boolean */ public boolean isHoliday(Date date) { String day = DateUtil.format(date, format); return isHoliday(day); } /** * 是否是节假日 * @param localDate * @return boolean */ public boolean isHoliday(LocalDate localDate) { return isHoliday(localDate.atStartOfDay()); } /** * 是否是节假日 * @param localDateTime * @return boolean */ public boolean isHoliday(LocalDateTime localDateTime) { String day = DateUtil.format(localDateTime, format); return isHoliday(day); } /** * 是否是节假日 * @param day * @return boolean */ public boolean isHoliday(String day) { CalendarVO vo = getDate(day); return vo.getStatus() == 3; } /** * 是否是工作日或补班 * @param date * @return boolean */ public boolean isWorkDay(Date date) { String day = DateUtil.format(date, format); return isWorkDay(day); } /** * 是否是工作日或补班 * @param localDate * @return boolean */ public boolean isWorkDay(LocalDate localDate) { return isWorkDay(localDate.atStartOfDay()); } /** * 是否是工作日或补班 * @param localDateTime * @return boolean */ public boolean isWorkDay(LocalDateTime localDateTime) { String day = DateUtil.format(localDateTime, format); return isWorkDay(day); } /** * 是否是工作日或补班 * @param day * @return boolean */ public boolean isWorkDay(String day) { CalendarVO vo = getDate(day); return vo.getStatus() == 0 || vo.getStatus() == 2; } /** * 是否是周末 * @param date * @return boolean */ public boolean isWeekend(Date date) { String day = DateUtil.format(date, format); return isWeekend(day); } /** * 是否是周末 * @param localDate * @return boolean */ public boolean isWeekend(LocalDate localDate) { return isWeekend(localDate.atStartOfDay()); } /** * 是否是周末 * @param localDateTime * @return boolean */ public boolean isWeekend(LocalDateTime localDateTime) { String day = DateUtil.format(localDateTime, format); return isWeekend(day); } /** * 是否是周末 * @param day * @return boolean */ public boolean isWeekend(String day) { CalendarVO vo = getDate(day); return vo.getStatus() == 1; } private static CalendarInfoVO getVo(String date) { DateTime dateTime = DateUtil.parseDate(date); CalendarInfoVO infoVO;
Map<String, CalendarVO> voMap = ConstantData.getAllDateMap();
0
2023-12-05 10:59:02+00:00
8k
HelpChat/DeluxeMenus
src/main/java/com/extendedclip/deluxemenus/requirement/HasMetaRequirement.java
[ { "identifier": "DeluxeMenus", "path": "src/main/java/com/extendedclip/deluxemenus/DeluxeMenus.java", "snippet": "public class DeluxeMenus extends JavaPlugin {\r\n\r\n public final static Map<String, Material> MATERIALS\r\n = Arrays.stream(Material.values()).collect(Collectors.toUnmodifiableMa...
import com.extendedclip.deluxemenus.DeluxeMenus; import com.extendedclip.deluxemenus.menu.MenuHolder; import org.bukkit.entity.Player;
4,246
package com.extendedclip.deluxemenus.requirement; public class HasMetaRequirement extends Requirement { private final String key; private final String value; private final String type; private final boolean invert; public HasMetaRequirement(String key, String type, String value, boolean invert) { this.key = key; this.type = type.toUpperCase(); this.value = value; this.invert = invert; } @Override
package com.extendedclip.deluxemenus.requirement; public class HasMetaRequirement extends Requirement { private final String key; private final String value; private final String type; private final boolean invert; public HasMetaRequirement(String key, String type, String value, boolean invert) { this.key = key; this.type = type.toUpperCase(); this.value = value; this.invert = invert; } @Override
public boolean evaluate(MenuHolder holder) {
1
2023-12-14 23:41:07+00:00
8k
lxs2601055687/contextAdminRuoYi
ruoyi-demo/src/main/java/com/ruoyi/demo/controller/RedisCacheController.java
[ { "identifier": "CacheNames", "path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/CacheNames.java", "snippet": "public interface CacheNames {\n\n /**\n * 演示案例\n */\n String DEMO_CACHE = \"demo:cache#60s#10m#20\";\n\n /**\n * 系统配置\n */\n String SYS_CONFIG = \"sys_con...
import com.ruoyi.common.constant.CacheNames; import com.ruoyi.common.core.domain.R; import com.ruoyi.common.utils.redis.RedisUtils; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.time.Duration;
5,225
package com.ruoyi.demo.controller; /** * spring-cache 演示案例 * * @author Lion Li */ // 类级别 缓存统一配置 //@CacheConfig(cacheNames = CacheNames.DEMO_CACHE) @RequiredArgsConstructor @RestController @RequestMapping("/demo/cache") public class RedisCacheController { /** * 测试 @Cacheable * <p> * 表示这个方法有了缓存的功能,方法的返回值会被缓存下来 * 下一次调用该方法前,会去检查是否缓存中已经有值 * 如果有就直接返回,不调用方法 * 如果没有,就调用方法,然后把结果缓存起来 * 这个注解「一般用在查询方法上」 * <p> * 重点说明: 缓存注解严谨与其他筛选数据功能一起使用 * 例如: 数据权限注解 会造成 缓存击穿 与 数据不一致问题 * <p> * cacheNames 命名规则 查看 {@link CacheNames} 注释 支持多参数 */ @Cacheable(cacheNames = "demo:cache#60s#10m#20", key = "#key", condition = "#key != null") @GetMapping("/test1") public R<String> test1(String key, String value) { return R.ok("操作成功", value); } /** * 测试 @CachePut * <p> * 加了@CachePut注解的方法,会把方法的返回值put到缓存里面缓存起来,供其它地方使用 * 它「通常用在新增或者实时更新方法上」 * <p> * cacheNames 命名规则 查看 {@link CacheNames} 注释 支持多参数 */
package com.ruoyi.demo.controller; /** * spring-cache 演示案例 * * @author Lion Li */ // 类级别 缓存统一配置 //@CacheConfig(cacheNames = CacheNames.DEMO_CACHE) @RequiredArgsConstructor @RestController @RequestMapping("/demo/cache") public class RedisCacheController { /** * 测试 @Cacheable * <p> * 表示这个方法有了缓存的功能,方法的返回值会被缓存下来 * 下一次调用该方法前,会去检查是否缓存中已经有值 * 如果有就直接返回,不调用方法 * 如果没有,就调用方法,然后把结果缓存起来 * 这个注解「一般用在查询方法上」 * <p> * 重点说明: 缓存注解严谨与其他筛选数据功能一起使用 * 例如: 数据权限注解 会造成 缓存击穿 与 数据不一致问题 * <p> * cacheNames 命名规则 查看 {@link CacheNames} 注释 支持多参数 */ @Cacheable(cacheNames = "demo:cache#60s#10m#20", key = "#key", condition = "#key != null") @GetMapping("/test1") public R<String> test1(String key, String value) { return R.ok("操作成功", value); } /** * 测试 @CachePut * <p> * 加了@CachePut注解的方法,会把方法的返回值put到缓存里面缓存起来,供其它地方使用 * 它「通常用在新增或者实时更新方法上」 * <p> * cacheNames 命名规则 查看 {@link CacheNames} 注释 支持多参数 */
@CachePut(cacheNames = CacheNames.DEMO_CACHE, key = "#key", condition = "#key != null")
0
2023-12-07 12:06:21+00:00
8k
DHBin/isme-java-serve
src/main/java/cn/dhbin/isme/pms/service/impl/UserServiceImpl.java
[ { "identifier": "SaTokenConfigure", "path": "src/main/java/cn/dhbin/isme/common/auth/SaTokenConfigure.java", "snippet": "@Configuration\npublic class SaTokenConfigure implements WebMvcConfigurer {\n\n public static final String JWT_USER_ID_KEY = \"userId\";\n\n public static final String JWT_USERN...
import cn.dev33.satoken.stp.SaLoginConfig; import cn.dev33.satoken.stp.SaTokenInfo; import cn.dev33.satoken.stp.StpUtil; import cn.dhbin.isme.common.auth.SaTokenConfigure; import cn.dhbin.isme.common.exception.BizException; import cn.dhbin.isme.common.preview.PreviewProperties; import cn.dhbin.isme.common.response.BizResponseCode; import cn.dhbin.isme.common.response.Page; import cn.dhbin.isme.pms.domain.dto.LoginTokenDto; import cn.dhbin.isme.pms.domain.dto.ProfileDto; import cn.dhbin.isme.pms.domain.dto.RoleDto; import cn.dhbin.isme.pms.domain.dto.UserDetailDto; import cn.dhbin.isme.pms.domain.dto.UserPageDto; import cn.dhbin.isme.pms.domain.entity.Profile; import cn.dhbin.isme.pms.domain.entity.Role; import cn.dhbin.isme.pms.domain.entity.User; import cn.dhbin.isme.pms.domain.entity.UserRole; import cn.dhbin.isme.pms.domain.request.AddUserRolesRequest; import cn.dhbin.isme.pms.domain.request.ChangePasswordRequest; import cn.dhbin.isme.pms.domain.request.LoginRequest; import cn.dhbin.isme.pms.domain.request.RegisterUserProfileRequest; import cn.dhbin.isme.pms.domain.request.RegisterUserRequest; import cn.dhbin.isme.pms.domain.request.UpdatePasswordRequest; import cn.dhbin.isme.pms.domain.request.UpdateProfileRequest; import cn.dhbin.isme.pms.domain.request.UserPageRequest; import cn.dhbin.isme.pms.mapper.UserMapper; import cn.dhbin.isme.pms.service.CaptchaService; import cn.dhbin.isme.pms.service.ProfileService; import cn.dhbin.isme.pms.service.RoleService; import cn.dhbin.isme.pms.service.UserRoleService; import cn.dhbin.isme.pms.service.UserService; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.crypto.digest.BCrypt; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import java.util.List; import java.util.Optional; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
4,676
package cn.dhbin.isme.pms.service.impl; /** * User Service impl * * @author dhb */ @Service @RequiredArgsConstructor public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { private final RoleService roleService; private final ProfileService profileService; private final UserRoleService userRoleService; private final CaptchaService captchaService; private final PreviewProperties previewProperties; @Override
package cn.dhbin.isme.pms.service.impl; /** * User Service impl * * @author dhb */ @Service @RequiredArgsConstructor public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { private final RoleService roleService; private final ProfileService profileService; private final UserRoleService userRoleService; private final CaptchaService captchaService; private final PreviewProperties previewProperties; @Override
public LoginTokenDto login(LoginRequest request) {
16
2023-12-13 17:21:04+00:00
8k
Earthcomputer/ModCompatChecker
fabric/src/main/java/net/earthcomputer/modcompatchecker/fabric/AccessWidenerPlugin.java
[ { "identifier": "Config", "path": "root/src/main/java/net/earthcomputer/modcompatchecker/config/Config.java", "snippet": "public final class Config {\n static final Map<String, ConfigSectionType<?>> SECTION_TYPES = new HashMap<>();\n private final Map<String, Object> sections;\n\n Config(Map<St...
import net.earthcomputer.modcompatchecker.config.Config; import net.earthcomputer.modcompatchecker.config.Plugin; import net.earthcomputer.modcompatchecker.indexer.ClassIndex; import net.earthcomputer.modcompatchecker.indexer.Index; import net.earthcomputer.modcompatchecker.util.AccessFlags; import net.earthcomputer.modcompatchecker.util.ClassMember; import org.jetbrains.annotations.Nullable; import org.objectweb.asm.Opcodes; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.jar.JarEntry; import java.util.jar.JarFile;
5,388
package net.earthcomputer.modcompatchecker.fabric; public class AccessWidenerPlugin implements Plugin { private final Map<String, List<AccessWidenerOp>> widenedClasses = new HashMap<>(); private final Map<String, List<AccessWidenerOp>> widenedFields = new HashMap<>(); private final Map<String, List<AccessWidenerOp>> widenedMethods = new HashMap<>(); @Override public String id() { return "access_widener"; } @Override public void preIndexMod(Config config, Index index, Path modPath) throws IOException { readAccessWidener(config, modPath); } @Override public void preIndexLibrary(Config config, Index index, Path libraryPath) throws IOException { readAccessWidener(config, libraryPath); } private void readAccessWidener(Config config, Path modPath) throws IOException { try (JarFile modJar = new JarFile(modPath.toFile())) { FabricModJson modJson = FabricModJson.load(modJar); if (modJson == null) { return; } if (modJson.accessWidener != null) { JarEntry accessWidenerEntry = modJar.getJarEntry(modJson.accessWidener); if (accessWidenerEntry == null) { throw new IOException("Could not find specified access widener \"" + modJson.accessWidener + "\""); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(modJar.getInputStream(accessWidenerEntry), StandardCharsets.UTF_8))) { doReadAccessWidener(config, reader); } } } } private void doReadAccessWidener(Config config, BufferedReader reader) throws IOException { boolean readHeader = false; String line; while ((line = reader.readLine()) != null) { int hashIndex = line.indexOf('#'); if (hashIndex != -1) { line = line.substring(0, hashIndex); } if (line.isBlank()) { continue; } String[] parts = line.strip().split("\\s+"); if (!readHeader) { readHeader = true; if (parts.length != 3 || !"accessWidener".equals(parts[0]) || !parts[1].startsWith("v")) { throw new IOException("Access widener file did not start with \"accessWidener v<N> <namespace>\""); } int formatVersion; try { formatVersion = Integer.parseInt(parts[1].substring(1)); } catch (NumberFormatException e) { throw new IOException("Invalid number in access widener format version: " + parts[1]); } if (formatVersion > 2) { return; } if (!getRuntimeNamespace(config).equals(parts[2])) { return; } } else { if (parts.length < 3) { throw new IOException("Invalid access widener format"); } AccessWidenerOp widenerOps = switch (parts[0]) { case "accessible", "transitive-accessible" -> AccessWidenerOp.ACCESSIBLE; case "extendable", "transitive-extendable" -> AccessWidenerOp.EXTENDABLE; case "mutable", "transitive-mutable" -> AccessWidenerOp.MUTABLE; default -> throw new IOException("Invalid access widener directive " + parts[0]); }; switch (parts[1]) { case "class" -> { if (parts.length != 3) { throw new IOException("Invalid access widener format"); } widenedClasses.computeIfAbsent(parts[2], k -> new ArrayList<>(1)).add(widenerOps); } case "field" -> { if (parts.length != 5) { throw new IOException("Invalid access widener format"); } widenedFields.computeIfAbsent(parts[2] + " " + parts[3] + " " + parts[4], k -> new ArrayList<>(1)).add(widenerOps); } case "method" -> { if (parts.length != 5) { throw new IOException("Invalid access widener format"); } widenedMethods.computeIfAbsent(parts[2] + " " + parts[3] + " " + parts[4], k -> new ArrayList<>(1)).add(widenerOps); } default -> throw new IOException("Invalid access widener format"); } } } } private static String getRuntimeNamespace(Config config) { Properties props = config.getSection(FabricUtil.FABRIC_SECTION); return props == null ? "intermediary" : props.getProperty("runtimeNamespace", "intermediary"); } @Override @Nullable public ClassIndex onIndexClass(Index index, String className, ClassIndex clazz) { List<AccessWidenerOp> widenOps = widenedClasses.get(className); if (widenOps != null) { for (AccessWidenerOp widenOp : widenOps) {
package net.earthcomputer.modcompatchecker.fabric; public class AccessWidenerPlugin implements Plugin { private final Map<String, List<AccessWidenerOp>> widenedClasses = new HashMap<>(); private final Map<String, List<AccessWidenerOp>> widenedFields = new HashMap<>(); private final Map<String, List<AccessWidenerOp>> widenedMethods = new HashMap<>(); @Override public String id() { return "access_widener"; } @Override public void preIndexMod(Config config, Index index, Path modPath) throws IOException { readAccessWidener(config, modPath); } @Override public void preIndexLibrary(Config config, Index index, Path libraryPath) throws IOException { readAccessWidener(config, libraryPath); } private void readAccessWidener(Config config, Path modPath) throws IOException { try (JarFile modJar = new JarFile(modPath.toFile())) { FabricModJson modJson = FabricModJson.load(modJar); if (modJson == null) { return; } if (modJson.accessWidener != null) { JarEntry accessWidenerEntry = modJar.getJarEntry(modJson.accessWidener); if (accessWidenerEntry == null) { throw new IOException("Could not find specified access widener \"" + modJson.accessWidener + "\""); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(modJar.getInputStream(accessWidenerEntry), StandardCharsets.UTF_8))) { doReadAccessWidener(config, reader); } } } } private void doReadAccessWidener(Config config, BufferedReader reader) throws IOException { boolean readHeader = false; String line; while ((line = reader.readLine()) != null) { int hashIndex = line.indexOf('#'); if (hashIndex != -1) { line = line.substring(0, hashIndex); } if (line.isBlank()) { continue; } String[] parts = line.strip().split("\\s+"); if (!readHeader) { readHeader = true; if (parts.length != 3 || !"accessWidener".equals(parts[0]) || !parts[1].startsWith("v")) { throw new IOException("Access widener file did not start with \"accessWidener v<N> <namespace>\""); } int formatVersion; try { formatVersion = Integer.parseInt(parts[1].substring(1)); } catch (NumberFormatException e) { throw new IOException("Invalid number in access widener format version: " + parts[1]); } if (formatVersion > 2) { return; } if (!getRuntimeNamespace(config).equals(parts[2])) { return; } } else { if (parts.length < 3) { throw new IOException("Invalid access widener format"); } AccessWidenerOp widenerOps = switch (parts[0]) { case "accessible", "transitive-accessible" -> AccessWidenerOp.ACCESSIBLE; case "extendable", "transitive-extendable" -> AccessWidenerOp.EXTENDABLE; case "mutable", "transitive-mutable" -> AccessWidenerOp.MUTABLE; default -> throw new IOException("Invalid access widener directive " + parts[0]); }; switch (parts[1]) { case "class" -> { if (parts.length != 3) { throw new IOException("Invalid access widener format"); } widenedClasses.computeIfAbsent(parts[2], k -> new ArrayList<>(1)).add(widenerOps); } case "field" -> { if (parts.length != 5) { throw new IOException("Invalid access widener format"); } widenedFields.computeIfAbsent(parts[2] + " " + parts[3] + " " + parts[4], k -> new ArrayList<>(1)).add(widenerOps); } case "method" -> { if (parts.length != 5) { throw new IOException("Invalid access widener format"); } widenedMethods.computeIfAbsent(parts[2] + " " + parts[3] + " " + parts[4], k -> new ArrayList<>(1)).add(widenerOps); } default -> throw new IOException("Invalid access widener format"); } } } } private static String getRuntimeNamespace(Config config) { Properties props = config.getSection(FabricUtil.FABRIC_SECTION); return props == null ? "intermediary" : props.getProperty("runtimeNamespace", "intermediary"); } @Override @Nullable public ClassIndex onIndexClass(Index index, String className, ClassIndex clazz) { List<AccessWidenerOp> widenOps = widenedClasses.get(className); if (widenOps != null) { for (AccessWidenerOp widenOp : widenOps) {
clazz.setAccess(new AccessFlags(widenOp.apply(clazz.getAccess().toAsm(), false)));
4
2023-12-11 00:48:12+00:00
8k
wkgcass/jdkman
src/main/java/io/vproxy/jdkman/util/Utils.java
[ { "identifier": "JDKInfo", "path": "src/main/java/io/vproxy/jdkman/entity/JDKInfo.java", "snippet": "public class JDKInfo implements JSONObject, Comparable<JDKInfo> {\n private String id;\n private int majorVersion;\n private int minorVersion;\n private int patchVersion;\n private String ...
import io.vproxy.base.util.LogType; import io.vproxy.base.util.Logger; import io.vproxy.base.util.OS; import io.vproxy.jdkman.entity.JDKInfo; import io.vproxy.jdkman.entity.JDKInfoMatcher; import io.vproxy.jdkman.entity.JDKManConfig; import io.vproxy.jdkman.entity.MatchOptions; import io.vproxy.jdkman.ex.ErrorResult; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List;
3,645
var bin = Path.of(file.getAbsolutePath(), "bin"); file = bin.toFile(); if (!file.exists()) { return STR."\{javaHome} does not have bin/ subdirectory"; } if (!file.isDirectory()) { return STR."\{file.getAbsolutePath()} is not a directory"; } var java = Path.of(file.getAbsolutePath(), "java" + (OS.isWindows() ? ".exe" : "")); file = java.toFile(); if (!file.exists()) { return STR."\{javaHome} does not have bin/java executable"; } if (!file.isFile()) { return STR."\{file.getAbsoluteFile()} is not a file"; } if (!file.canExecute()) { return STR."\{file.getAbsoluteFile()} is not executable"; } return null; } public static String readInputStream(InputStream input) throws IOException { var sb = new StringBuilder(); var chars = new char[1024]; try (var reader = new InputStreamReader(input, StandardCharsets.UTF_8)) { while (true) { var len = reader.read(chars); if (len == -1) { break; } sb.append(chars, 0, len); } } return sb.toString(); } public static boolean isNonNegativeInteger(String s) { try { var n = Integer.parseInt(s); return n >= 0; } catch (NumberFormatException _) { return false; } } public static JDKInfoMatcher parseVersion(final String version) throws ErrorResult { String implementor = null; String versionPart; if (version.contains(":")) { implementor = version.substring(0, version.indexOf(":")); versionPart = version.substring(version.indexOf(":") + 1); } else { versionPart = version; } int major; Integer minor = null; Integer patch = null; String buildVersion = null; String versionStr; if (versionPart.contains("+")) { versionStr = versionPart.substring(0, versionPart.indexOf("+")); buildVersion = versionPart.substring(versionPart.indexOf("+") + 1); } else if (versionPart.contains("_")) { versionStr = versionPart.substring(0, versionPart.indexOf("_")); buildVersion = versionPart.substring(versionPart.indexOf("_") + 1); } else { versionStr = versionPart; } var split = versionStr.split("\\."); if (split.length == 0) { throw new ErrorResult(STR."\{versionStr} is not a valid version: empty string"); } if (!isNonNegativeInteger(split[0])) { throw new ErrorResult(STR."\{versionStr} is not a valid version: major version not valid: \{split[0]}"); } major = Integer.parseInt(split[0]); if (split.length >= 2) { if (!isNonNegativeInteger(split[1])) { throw new ErrorResult(STR."\{versionStr} is not a valid version: minor version not valid: \{split[1]}"); } minor = Integer.parseInt(split[1]); } if (split.length >= 3) { if (!isNonNegativeInteger(split[2])) { throw new ErrorResult(STR."\{versionStr} is not a valid version: patch version not valid: \{split[2]}"); } patch = Integer.parseInt(split[2]); } return new JDKInfoMatcher(implementor, major, minor, patch, buildVersion, version); } private static final String JAVA_VERSION = ".java-version"; public static JDKInfoMatcher currentVersion() { try { var dir = new File("").getCanonicalFile(); do { var path = Path.of(dir.getAbsolutePath(), JAVA_VERSION); if (path.toFile().exists() && path.toFile().isFile()) { var content = Files.readString(path).trim(); try { return parseVersion(content); } catch (ErrorResult e) { assert Logger.lowLevelDebug(STR."unable to parse file \{path}: \{content}"); } } dir = dir.getParentFile(); } while (dir != null); } catch (IOException e) { Logger.warn(LogType.FILE_ERROR, "failed to retrieve current version from file", e); return null; } return null; }
package io.vproxy.jdkman.util; public class Utils { private Utils() { } public static String validateJavaHome(String javaHome) { var file = new File(javaHome); if (!file.exists()) { return STR."\{javaHome} does not exist"; } if (!file.isDirectory()) { return STR."\{javaHome} is not a directory"; } var bin = Path.of(file.getAbsolutePath(), "bin"); file = bin.toFile(); if (!file.exists()) { return STR."\{javaHome} does not have bin/ subdirectory"; } if (!file.isDirectory()) { return STR."\{file.getAbsolutePath()} is not a directory"; } var java = Path.of(file.getAbsolutePath(), "java" + (OS.isWindows() ? ".exe" : "")); file = java.toFile(); if (!file.exists()) { return STR."\{javaHome} does not have bin/java executable"; } if (!file.isFile()) { return STR."\{file.getAbsoluteFile()} is not a file"; } if (!file.canExecute()) { return STR."\{file.getAbsoluteFile()} is not executable"; } return null; } public static String readInputStream(InputStream input) throws IOException { var sb = new StringBuilder(); var chars = new char[1024]; try (var reader = new InputStreamReader(input, StandardCharsets.UTF_8)) { while (true) { var len = reader.read(chars); if (len == -1) { break; } sb.append(chars, 0, len); } } return sb.toString(); } public static boolean isNonNegativeInteger(String s) { try { var n = Integer.parseInt(s); return n >= 0; } catch (NumberFormatException _) { return false; } } public static JDKInfoMatcher parseVersion(final String version) throws ErrorResult { String implementor = null; String versionPart; if (version.contains(":")) { implementor = version.substring(0, version.indexOf(":")); versionPart = version.substring(version.indexOf(":") + 1); } else { versionPart = version; } int major; Integer minor = null; Integer patch = null; String buildVersion = null; String versionStr; if (versionPart.contains("+")) { versionStr = versionPart.substring(0, versionPart.indexOf("+")); buildVersion = versionPart.substring(versionPart.indexOf("+") + 1); } else if (versionPart.contains("_")) { versionStr = versionPart.substring(0, versionPart.indexOf("_")); buildVersion = versionPart.substring(versionPart.indexOf("_") + 1); } else { versionStr = versionPart; } var split = versionStr.split("\\."); if (split.length == 0) { throw new ErrorResult(STR."\{versionStr} is not a valid version: empty string"); } if (!isNonNegativeInteger(split[0])) { throw new ErrorResult(STR."\{versionStr} is not a valid version: major version not valid: \{split[0]}"); } major = Integer.parseInt(split[0]); if (split.length >= 2) { if (!isNonNegativeInteger(split[1])) { throw new ErrorResult(STR."\{versionStr} is not a valid version: minor version not valid: \{split[1]}"); } minor = Integer.parseInt(split[1]); } if (split.length >= 3) { if (!isNonNegativeInteger(split[2])) { throw new ErrorResult(STR."\{versionStr} is not a valid version: patch version not valid: \{split[2]}"); } patch = Integer.parseInt(split[2]); } return new JDKInfoMatcher(implementor, major, minor, patch, buildVersion, version); } private static final String JAVA_VERSION = ".java-version"; public static JDKInfoMatcher currentVersion() { try { var dir = new File("").getCanonicalFile(); do { var path = Path.of(dir.getAbsolutePath(), JAVA_VERSION); if (path.toFile().exists() && path.toFile().isFile()) { var content = Files.readString(path).trim(); try { return parseVersion(content); } catch (ErrorResult e) { assert Logger.lowLevelDebug(STR."unable to parse file \{path}: \{content}"); } } dir = dir.getParentFile(); } while (dir != null); } catch (IOException e) { Logger.warn(LogType.FILE_ERROR, "failed to retrieve current version from file", e); return null; } return null; }
public static JDKInfo currentVersion(JDKManConfig config) {
2
2023-12-07 04:55:35+00:00
8k
DantSu/studio
core/src/main/java/studio/core/v1/reader/binary/BinaryStoryPackReader.java
[ { "identifier": "BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT", "path": "core/src/main/java/studio/core/v1/Constants.java", "snippet": "public static final int BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT = 16;" }, { "identifier": "BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT_PADDING", ...
import static studio.core.v1.Constants.BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT; import static studio.core.v1.Constants.BINARY_ENRICHED_METADATA_ACTION_NODE_ALIGNMENT_PADDING; import static studio.core.v1.Constants.BINARY_ENRICHED_METADATA_DESCRIPTION_TRUNCATE; import static studio.core.v1.Constants.BINARY_ENRICHED_METADATA_NODE_NAME_TRUNCATE; import static studio.core.v1.Constants.BINARY_ENRICHED_METADATA_SECTOR_1_ALIGNMENT_PADDING; import static studio.core.v1.Constants.BINARY_ENRICHED_METADATA_STAGE_NODE_ALIGNMENT_PADDING; import static studio.core.v1.Constants.BINARY_ENRICHED_METADATA_TITLE_TRUNCATE; import static studio.core.v1.Constants.SECTOR_SIZE; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.UUID; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import studio.core.v1.model.ActionNode; import studio.core.v1.model.ControlSettings; import studio.core.v1.model.StageNode; import studio.core.v1.model.StoryPack; import studio.core.v1.model.Transition; import studio.core.v1.model.asset.AudioAsset; import studio.core.v1.model.asset.AudioType; import studio.core.v1.model.asset.ImageAsset; import studio.core.v1.model.asset.ImageType; import studio.core.v1.model.enriched.EnrichedNodeMetadata; import studio.core.v1.model.enriched.EnrichedNodePosition; import studio.core.v1.model.enriched.EnrichedNodeType; import studio.core.v1.model.enriched.EnrichedPackMetadata; import studio.core.v1.model.metadata.StoryPackMetadata; import studio.core.v1.reader.StoryPackReader; import studio.core.v1.reader.binary.AssetAddr.AssetType; import studio.core.v1.utils.PackFormat;
6,185
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package studio.core.v1.reader.binary; public class BinaryStoryPackReader implements StoryPackReader { private static final Logger LOGGER = LogManager.getLogger(BinaryStoryPackReader.class); public StoryPackMetadata readMetadata(Path path) throws IOException { try(DataInputStream dis = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))){ // Pack metadata model StoryPackMetadata metadata = new StoryPackMetadata(PackFormat.RAW); // Read sector 1 dis.skipBytes(3); // Skip to version metadata.setVersion(dis.readShort()); // Read (optional) enriched pack metadata dis.skipBytes(BINARY_ENRICHED_METADATA_SECTOR_1_ALIGNMENT_PADDING); Optional<String> maybeTitle = readString(dis, BINARY_ENRICHED_METADATA_TITLE_TRUNCATE); metadata.setTitle(maybeTitle.orElse(null)); Optional<String> maybeDescription = readString(dis, BINARY_ENRICHED_METADATA_DESCRIPTION_TRUNCATE); metadata.setDescription(maybeDescription.orElse(null)); // TODO Thumbnail? dis.skipBytes(SECTOR_SIZE - 5 - BINARY_ENRICHED_METADATA_SECTOR_1_ALIGNMENT_PADDING - BINARY_ENRICHED_METADATA_TITLE_TRUNCATE*2 - BINARY_ENRICHED_METADATA_DESCRIPTION_TRUNCATE*2); // Skip to end of sector // Read main stage node long uuidLowBytes = dis.readLong(); long uuidHighBytes = dis.readLong(); String uuid = (new UUID(uuidLowBytes, uuidHighBytes)).toString(); metadata.setUuid(uuid); return metadata; } } public StoryPack read(Path path) throws IOException { try(DataInputStream dis = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))) { // Read sector 1 short stages = dis.readShort(); boolean factoryDisabled = dis.readByte() == 1; short version = dis.readShort(); // Read (optional) enriched pack metadata EnrichedPackMetadata enrichedPack = null; dis.skipBytes(BINARY_ENRICHED_METADATA_SECTOR_1_ALIGNMENT_PADDING); Optional<String> maybeTitle = readString(dis, BINARY_ENRICHED_METADATA_TITLE_TRUNCATE); Optional<String> maybeDescription = readString(dis, BINARY_ENRICHED_METADATA_DESCRIPTION_TRUNCATE); // TODO Thumbnail? if (maybeTitle.or(() -> maybeDescription).isPresent() ) { enrichedPack = new EnrichedPackMetadata(maybeTitle.orElse(null), maybeDescription.orElse(null)); } dis.skipBytes(SECTOR_SIZE - 5 - BINARY_ENRICHED_METADATA_SECTOR_1_ALIGNMENT_PADDING - BINARY_ENRICHED_METADATA_TITLE_TRUNCATE*2 - BINARY_ENRICHED_METADATA_DESCRIPTION_TRUNCATE*2); // Skip to end of sector // Read stage nodes (`stages` sectors, starting from sector 2) TreeMap<SectorAddr, StageNode> stageNodes = new TreeMap<>(); TreeMap<AssetAddr, List<StageNode>> stagesWithImage = new TreeMap<>(); // StageNodes must be updated with the actual ImageAsset TreeMap<AssetAddr, List<StageNode>> stagesWithAudio = new TreeMap<>(); // StageNodes must be updated with the actual AudioAsset TreeMap<SectorAddr, List<Transition>> transitionsWithAction = new TreeMap<>(); // Transitions must be updated with the actual ActionNode Set<SectorAddr> actionNodesToVisit = new TreeSet<>(); // Stage nodes / transitions reference action nodes, which are read after all stage nodes Set<AssetAddr> assetAddrsToVisit = new TreeSet<>(); // Stage nodes reference assets, which are read after all nodes for (int i = 0; i < stages; i++) { // Reading sector i+2 // UUID long uuidLowBytes = dis.readLong(); long uuidHighBytes = dis.readLong(); String uuid = (new UUID(uuidLowBytes, uuidHighBytes)).toString(); // Image asset int imageOffset = dis.readInt(); int imageSize = dis.readInt(); AssetAddr imageAssetAddr = null; if (imageOffset != -1) { // Asset must be visited imageAssetAddr = new AssetAddr(AssetType.IMAGE, imageOffset, imageSize); assetAddrsToVisit.add(imageAssetAddr); } // Audio asset int audioOffset = dis.readInt(); int audioSize = dis.readInt(); AssetAddr audioAssetAddr = null; if (audioOffset != -1) { // Asset must be visited audioAssetAddr = new AssetAddr(AssetType.AUDIO, audioOffset, audioSize); assetAddrsToVisit.add(audioAssetAddr); } // Transitions short okTransitionOffset = dis.readShort(); short okTransitionCount = dis.readShort(); short okTransitionIndex = dis.readShort(); SectorAddr okActionNodeAddr = null; if (okTransitionOffset != -1) { // Action node must be visited okActionNodeAddr = new SectorAddr(okTransitionOffset); actionNodesToVisit.add(okActionNodeAddr); } Transition okTransition = Optional.ofNullable(okActionNodeAddr) .map(h -> new Transition(null, okTransitionIndex)).orElse(null); short homeTransitionOffset = dis.readShort(); short homeTransitionCount = dis.readShort(); short homeTransitionIndex = dis.readShort(); SectorAddr homeActionNodeAddr = null; if (homeTransitionOffset != -1) { // Action node must be visited homeActionNodeAddr = new SectorAddr(homeTransitionOffset); actionNodesToVisit.add(homeActionNodeAddr); } Transition homeTransition = Optional.ofNullable(homeActionNodeAddr) .map(h -> new Transition(null, homeTransitionIndex)).orElse(null); LOGGER.trace("Transitions : {} ok, {} home", okTransitionCount, homeTransitionCount); // Control settings boolean wheelEnabled = dis.readShort() == 1; boolean okEnabled = dis.readShort() == 1; boolean homeEnabled = dis.readShort() == 1; boolean pauseEnabled = dis.readShort() == 1; boolean autoJumpEnabled = dis.readShort() == 1; ControlSettings ctrl = new ControlSettings(wheelEnabled, okEnabled, homeEnabled, pauseEnabled, autoJumpEnabled); // Read (optional) enriched node metadata
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package studio.core.v1.reader.binary; public class BinaryStoryPackReader implements StoryPackReader { private static final Logger LOGGER = LogManager.getLogger(BinaryStoryPackReader.class); public StoryPackMetadata readMetadata(Path path) throws IOException { try(DataInputStream dis = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))){ // Pack metadata model StoryPackMetadata metadata = new StoryPackMetadata(PackFormat.RAW); // Read sector 1 dis.skipBytes(3); // Skip to version metadata.setVersion(dis.readShort()); // Read (optional) enriched pack metadata dis.skipBytes(BINARY_ENRICHED_METADATA_SECTOR_1_ALIGNMENT_PADDING); Optional<String> maybeTitle = readString(dis, BINARY_ENRICHED_METADATA_TITLE_TRUNCATE); metadata.setTitle(maybeTitle.orElse(null)); Optional<String> maybeDescription = readString(dis, BINARY_ENRICHED_METADATA_DESCRIPTION_TRUNCATE); metadata.setDescription(maybeDescription.orElse(null)); // TODO Thumbnail? dis.skipBytes(SECTOR_SIZE - 5 - BINARY_ENRICHED_METADATA_SECTOR_1_ALIGNMENT_PADDING - BINARY_ENRICHED_METADATA_TITLE_TRUNCATE*2 - BINARY_ENRICHED_METADATA_DESCRIPTION_TRUNCATE*2); // Skip to end of sector // Read main stage node long uuidLowBytes = dis.readLong(); long uuidHighBytes = dis.readLong(); String uuid = (new UUID(uuidLowBytes, uuidHighBytes)).toString(); metadata.setUuid(uuid); return metadata; } } public StoryPack read(Path path) throws IOException { try(DataInputStream dis = new DataInputStream(new BufferedInputStream(Files.newInputStream(path)))) { // Read sector 1 short stages = dis.readShort(); boolean factoryDisabled = dis.readByte() == 1; short version = dis.readShort(); // Read (optional) enriched pack metadata EnrichedPackMetadata enrichedPack = null; dis.skipBytes(BINARY_ENRICHED_METADATA_SECTOR_1_ALIGNMENT_PADDING); Optional<String> maybeTitle = readString(dis, BINARY_ENRICHED_METADATA_TITLE_TRUNCATE); Optional<String> maybeDescription = readString(dis, BINARY_ENRICHED_METADATA_DESCRIPTION_TRUNCATE); // TODO Thumbnail? if (maybeTitle.or(() -> maybeDescription).isPresent() ) { enrichedPack = new EnrichedPackMetadata(maybeTitle.orElse(null), maybeDescription.orElse(null)); } dis.skipBytes(SECTOR_SIZE - 5 - BINARY_ENRICHED_METADATA_SECTOR_1_ALIGNMENT_PADDING - BINARY_ENRICHED_METADATA_TITLE_TRUNCATE*2 - BINARY_ENRICHED_METADATA_DESCRIPTION_TRUNCATE*2); // Skip to end of sector // Read stage nodes (`stages` sectors, starting from sector 2) TreeMap<SectorAddr, StageNode> stageNodes = new TreeMap<>(); TreeMap<AssetAddr, List<StageNode>> stagesWithImage = new TreeMap<>(); // StageNodes must be updated with the actual ImageAsset TreeMap<AssetAddr, List<StageNode>> stagesWithAudio = new TreeMap<>(); // StageNodes must be updated with the actual AudioAsset TreeMap<SectorAddr, List<Transition>> transitionsWithAction = new TreeMap<>(); // Transitions must be updated with the actual ActionNode Set<SectorAddr> actionNodesToVisit = new TreeSet<>(); // Stage nodes / transitions reference action nodes, which are read after all stage nodes Set<AssetAddr> assetAddrsToVisit = new TreeSet<>(); // Stage nodes reference assets, which are read after all nodes for (int i = 0; i < stages; i++) { // Reading sector i+2 // UUID long uuidLowBytes = dis.readLong(); long uuidHighBytes = dis.readLong(); String uuid = (new UUID(uuidLowBytes, uuidHighBytes)).toString(); // Image asset int imageOffset = dis.readInt(); int imageSize = dis.readInt(); AssetAddr imageAssetAddr = null; if (imageOffset != -1) { // Asset must be visited imageAssetAddr = new AssetAddr(AssetType.IMAGE, imageOffset, imageSize); assetAddrsToVisit.add(imageAssetAddr); } // Audio asset int audioOffset = dis.readInt(); int audioSize = dis.readInt(); AssetAddr audioAssetAddr = null; if (audioOffset != -1) { // Asset must be visited audioAssetAddr = new AssetAddr(AssetType.AUDIO, audioOffset, audioSize); assetAddrsToVisit.add(audioAssetAddr); } // Transitions short okTransitionOffset = dis.readShort(); short okTransitionCount = dis.readShort(); short okTransitionIndex = dis.readShort(); SectorAddr okActionNodeAddr = null; if (okTransitionOffset != -1) { // Action node must be visited okActionNodeAddr = new SectorAddr(okTransitionOffset); actionNodesToVisit.add(okActionNodeAddr); } Transition okTransition = Optional.ofNullable(okActionNodeAddr) .map(h -> new Transition(null, okTransitionIndex)).orElse(null); short homeTransitionOffset = dis.readShort(); short homeTransitionCount = dis.readShort(); short homeTransitionIndex = dis.readShort(); SectorAddr homeActionNodeAddr = null; if (homeTransitionOffset != -1) { // Action node must be visited homeActionNodeAddr = new SectorAddr(homeTransitionOffset); actionNodesToVisit.add(homeActionNodeAddr); } Transition homeTransition = Optional.ofNullable(homeActionNodeAddr) .map(h -> new Transition(null, homeTransitionIndex)).orElse(null); LOGGER.trace("Transitions : {} ok, {} home", okTransitionCount, homeTransitionCount); // Control settings boolean wheelEnabled = dis.readShort() == 1; boolean okEnabled = dis.readShort() == 1; boolean homeEnabled = dis.readShort() == 1; boolean pauseEnabled = dis.readShort() == 1; boolean autoJumpEnabled = dis.readShort() == 1; ControlSettings ctrl = new ControlSettings(wheelEnabled, okEnabled, homeEnabled, pauseEnabled, autoJumpEnabled); // Read (optional) enriched node metadata
dis.skipBytes(BINARY_ENRICHED_METADATA_STAGE_NODE_ALIGNMENT_PADDING);
5
2023-12-14 15:08:35+00:00
8k
conductor-oss/conductor-community
index/es7-persistence/src/main/java/com/netflix/conductor/es7/dao/query/parser/NameValue.java
[ { "identifier": "AbstractNode", "path": "index/es7-persistence/src/main/java/com/netflix/conductor/es7/dao/query/parser/internal/AbstractNode.java", "snippet": "public abstract class AbstractNode {\n\n public static final Pattern WHITESPACE = Pattern.compile(\"\\\\s\");\n\n protected static Set<Ch...
import java.io.InputStream; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import com.netflix.conductor.es7.dao.query.parser.internal.AbstractNode; import com.netflix.conductor.es7.dao.query.parser.internal.ComparisonOp; import com.netflix.conductor.es7.dao.query.parser.internal.ComparisonOp.Operators; import com.netflix.conductor.es7.dao.query.parser.internal.ConstValue; import com.netflix.conductor.es7.dao.query.parser.internal.ListConst; import com.netflix.conductor.es7.dao.query.parser.internal.Name; import com.netflix.conductor.es7.dao.query.parser.internal.ParserException; import com.netflix.conductor.es7.dao.query.parser.internal.Range;
4,246
/* * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <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 com.netflix.conductor.es7.dao.query.parser; /** * @author Viren * <pre> * Represents an expression of the form as below: * key OPR value * OPR is the comparison operator which could be on the following: * &gt;, &lt;, = , !=, IN, BETWEEN * </pre> */ public class NameValue extends AbstractNode implements FilterProvider { private Name name;
/* * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <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 com.netflix.conductor.es7.dao.query.parser; /** * @author Viren * <pre> * Represents an expression of the form as below: * key OPR value * OPR is the comparison operator which could be on the following: * &gt;, &lt;, = , !=, IN, BETWEEN * </pre> */ public class NameValue extends AbstractNode implements FilterProvider { private Name name;
private ComparisonOp op;
1
2023-12-08 06:06:20+00:00
8k
zhouyqxy/aurora_Lite
src/main/java/com/aurora/service/impl/UserAuthServiceImpl.java
[ { "identifier": "CommonConstant", "path": "src/main/java/com/aurora/constant/CommonConstant.java", "snippet": "public interface CommonConstant {\n\n int ONE = 1;\n\n int ZERO = 0;\n\n int FALSE = 0;\n\n int TRUE = 1;\n\n int BLOGGER_ID = 1;\n\n int DEFAULT_CONFIG_ID = 1;\n\n int DEF...
import com.alibaba.fastjson.JSON; import com.aurora.constant.CommonConstant; import com.aurora.entity.UserAuth; import com.aurora.entity.UserInfo; import com.aurora.entity.UserRole; import com.aurora.enums.LoginTypeEnum; import com.aurora.enums.RoleEnum; import com.aurora.exception.BizException; import com.aurora.mapper.UserAuthMapper; import com.aurora.mapper.UserInfoMapper; import com.aurora.mapper.UserRoleMapper; import com.aurora.model.dto.*; import com.aurora.model.vo.ConditionVO; import com.aurora.model.vo.PasswordVO; import com.aurora.model.vo.QQLoginVO; import com.aurora.model.vo.UserVO; import com.aurora.service.AuroraInfoService; import com.aurora.service.RedisService; import com.aurora.service.TokenService; import com.aurora.service.UserAuthService; import com.aurora.strategy.context.SocialLoginStrategyContext; import com.aurora.util.EmailUtil; import com.aurora.util.PageUtil; import com.aurora.util.UserUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.IdWorker; import lombok.SneakyThrows; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCrypt; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.*; import java.util.stream.Collectors; import static com.aurora.constant.RedisConstant.*; import static com.aurora.enums.UserAreaTypeEnum.getUserAreaType; import static com.aurora.util.CommonUtil.checkEmail; import static com.aurora.util.CommonUtil.getRandomCode;
4,471
package com.aurora.service.impl; @Service public class UserAuthServiceImpl implements UserAuthService { @Autowired private UserAuthMapper userAuthMapper; @Autowired private UserInfoMapper userInfoMapper; @Autowired private UserRoleMapper userRoleMapper; @Autowired private RedisService redisService; @Autowired private AuroraInfoService auroraInfoService; @Autowired private TokenService tokenService; @Autowired private SocialLoginStrategyContext socialLoginStrategyContext; @Resource EmailUtil emailUtil; @Override public void sendCode(String username) {
package com.aurora.service.impl; @Service public class UserAuthServiceImpl implements UserAuthService { @Autowired private UserAuthMapper userAuthMapper; @Autowired private UserInfoMapper userInfoMapper; @Autowired private UserRoleMapper userRoleMapper; @Autowired private RedisService redisService; @Autowired private AuroraInfoService auroraInfoService; @Autowired private TokenService tokenService; @Autowired private SocialLoginStrategyContext socialLoginStrategyContext; @Resource EmailUtil emailUtil; @Override public void sendCode(String username) {
if (!checkEmail(username)) {
23
2023-12-05 03:38:51+00:00
8k
Ispirer/COBOL-to-Java-Conversion-Samples
IspirerFramework/com/ispirer/sw/types/PictureType.java
[ { "identifier": "AlphanumericFormat", "path": "IspirerFramework/com/ispirer/sw/strings/AlphanumericFormat.java", "snippet": "public class AlphanumericFormat extends Format {\r\n\r\n\tpublic AlphanumericFormat(String format) {\r\n\t\tsuper(format);\r\n\t\tpattern = pattern.replaceAll(\"b\", \" \");\r\n\t...
import com.ispirer.sw.strings.AlphanumericFormat; import com.ispirer.sw.strings.DecimalFormat; import com.ispirer.sw.strings.Format; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.nio.charset.Charset; import java.sql.Clob; import java.sql.SQLException; import java.util.regex.Pattern; import static com.ispirer.sw.types.PictureType.DefaultValue.HighValues; import static com.ispirer.sw.types.PictureType.DefaultValue.Spaces; import static java.sql.Types.*;
6,638
return null; } if (type instanceof String) { return (T) getTrimmedValue(); } return value; } /** * set value with indicator if value is null indicator is -1 in other case * indicator is 0 * * @param value to set into variable */ public void setIndValue(Object value) { if (value == null) { indicator = -1; } else { indicator = 0; setValue(value); } } /** * this method for Pro*Cobol with ORACLE */ public void setIndValue(Object value, int columnType) { if (value == null) { indicator = -1; if (columnType == VARCHAR || columnType == CHAR || columnType == LONGNVARCHAR) { setValue("", columnType); } } else { indicator = 0; if (columnType == CLOB) { try { setValue(((Clob) value).getSubString(1, (int) ((Clob) value).length())); return; } catch (SQLException e) { LOGGER.info(String.valueOf(e)); } } setValue(value.toString(), columnType); } } private void initTrimmedValue(String value) { trimmedValue = value; initTrimmedValuebyString(value != null ? value : ""); } private void initTrimmedValuebyString(String value) { trimmedValue = value; if (trimmedValue.length() > getSize()) { trimmedValue = trimmedValue.substring(0, getSize()); } while (trimmedValue.length() > 0 && trimmedValue.substring(trimmedValue.length() - 1).equals(" ")) { trimmedValue = trimmedValue.substring(0, trimmedValue.length() - 1); } } /** * Use method tp get trimmedValue use Trimmed value only for String variables * * @return trimmed value */ public String getTrimmedValue() { return trimmedValue == null || trimmedValue.trim().isEmpty() ? "" : trimmedValue; } /** * this method for Pro*Cobol with ORACLE */ public void setValue(String value, int columnType) { if (value == null) { setValue(StringUtils.repeat(" ", getSize())); return; } if (columnType == VARCHAR || columnType == CHAR || columnType == LONGNVARCHAR) { setValue(value); } else { setValue(StringUtils.repeat(" ", getSize() - value.replaceAll("[-.]", "").length()) + value.replaceAll("[-.]", "")); } } /** * This enum declares all default values that can be used in cobol */ public enum DefaultValue { Spaces(" "), Zeroes("0"), HighValues(" "), LowValues(" "), Quotes(" "), Nulls(" "); private final String value; private DefaultValue(String s) { value = s; } public boolean equalsName(String otherName) { return value.equals(otherName); } @Override public String toString() { return this.value; } } /** * replace string in the current value to new string use for String PT variables * * @param from symbols to replace * @param to symbols to replace by */ @SuppressWarnings("unchecked") public void replaceAll(String from, String to) { formatedValue = formatedValue.replaceAll(from, to);
/* © 2021, Ispirer Systems OÜ. All rights reserved. NOTICE OF LICENSE This file\library is Ispirer Reusable Code (“IRC”) and you are granted a non-exclusive, worldwide, perpetual, irrevocable and fully paid up license to use, modify, adapt, sublicense and otherwise exploit this IRC as provided below and under the terms of Ispirer Systems OÜ. Reusable Code License Agreement (“License”), which can be found in supplementary LICENSE.txt file. By using this IRC, you acknowledge that you have read the License and agree with its terms as well as with the fact that IRC is the property of and belongs to Ispirer Systems OÜ only. IF YOU ARE NOT AGREE WITH THE TERMS OF THE LICENSE, PLEASE, STOP USING THIS IRC IMMEDIATELY! PLEASE, NOTE, THAT IRC IS DISTRIBUTED “AS IS” AND WITHOUT ANY WARRANTY. IN NO EVENT WILL ISPIRER BE LIABLE FOR ANY DAMAGES, CLAIMS OR COSTS WHATSOEVER OR ANY CONSEQUENTIAL, INDIRECT, INCIDENTAL DAMAGES, OR ANY LOST PROFITS OR LOST SAVINGS. Redistributions of this IRC must retain the above copyright notice and a list of significant changes made to this IRC with indication of its author(s) and date of changes. If you need more information, or you think that the License has been violated, please let us know by e-mail: legal.department@ispirer.com */ package com.ispirer.sw.types; public class PictureType<T extends Object> implements Comparable<Object> { private static Logger LOGGER = LoggerFactory.getLogger(PictureType.class); private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); private T value; // stores the value private T type; // indicates type of variables private String formatedValue = ""; // stores value in the display mood private Format format; // the format object. private int indicator = 0; public boolean hasDefVal = false; private String trimmedValue; // stores trimmed value. this value is used for getting and setting value to DB public static boolean isEBSDIC = false; private DefaultValue defaultValue; /** * Use this constructor if you need to make PT variable quickly. For example if * you have numeric constant and need to make it PT variable to use in the * calculations * * Do not use this constructor to declare PT variable that is going to be used * not just in the calculation. * * @param value value of PT variable */ public PictureType(T value) { // can be used only for calculation and value this.value = value; } /** * Default constructor for PT variable * * @param type indicates type of variable * @param format object that manage displaying of variables */ public PictureType(Type type, Format format) { this(type, format, Spaces); // bu default value is Spaces trimmedValue = null; } /** * Constructor for PT variable with value for initialization * * @param format object that manage displaying of variables * @param value value of PT variable. also indicates type variable. */ public PictureType(Format format, T value) { this.type = value; this.format = format; setValue(value); initTrimmedValue(value.toString()); } /** * Constructor for PT variable with defaultValue for initialization * * @param type indicates type of variable * @param format object that manage displaying of variables * @param defaultValue object for initialization. */ public PictureType(Type type, Format format, DefaultValue defaultValue) { this.format = format; getTypedValue(type); setDefaultValue(defaultValue); if (format instanceof DecimalFormat && ((DecimalFormat) format).getCompType() != null) { setValue(0); } } PictureType.DefaultValue getDefValue() { return defaultValue; } /** * This method adds addValue to current value This method is used for conversion * result. It changed a lot to get the correct implementation of calculation Now * it works the same way as add(Object addValue). And finalObject is not * necessary. * * @param finalObject object where the result of calculation will be placed * @param addValue value to add * @return the result of calculation in the PictureType<BigDecimal> variable. * You can use this object in next calculations */ public PictureType<BigDecimal> add(PictureType<?> finalObject, Object addValue) { return add(addValue); } /** * This method calculates rounded result of addition addValue to current value. * Scale value depends on finalObject's fractional size. Use this method to * round each calculation in whole expression separately * * @param finalObject object where the result of calculation will be placed * @param addValue value to add * @return the result of calculation in the PictureType<BigDecimal> variable. * You can use this object in next calculations */ public PictureType<BigDecimal> addTrunc(PictureType<?> finalObject, Object addValue) { return new PictureType<BigDecimal>( add(addValue).getValue().setScale(finalObject.getFractionalSize(), RoundingMode.FLOOR)); } /** * This method adds addValue to current value without rounding. * * @param addValue value to add * @return the result of calculation in the PictureType<BigDecimal> variable. * You can use this object in next calculations */ public PictureType<BigDecimal> add(Object addValue) { if (addValue == null) { return new PictureType<>(toBigDecimal(this.value)); // if addValue is null, this method will return current // value. } if (addValue instanceof PictureType) { if (((PictureType<?>) addValue).getValue() == null) { return new PictureType<>(toBigDecimal(this.value)); // if addValue is null, this method will return // current value. } return new PictureType<>( toBigDecimal(this.value).add(toBigDecimal(((PictureType<?>) addValue).getValue()))); } return new PictureType<>(toBigDecimal(this.value).add(toBigDecimal(addValue))); } /** * This method subtracts addValue from current value This method is used for * conversion result. It changed a lot to get the correct implementation of * calculation Now it works the same way as subtract(Object addValue). And * finalObject is not necessary. * * @param finalObject object where the result of calculation will be placed * @param addValue value to subtract * @return the result of calculation in the PictureType<BigDecimal> variable. * You can use this object in next calculations */ public PictureType<BigDecimal> subtract(PictureType<?> finalObject, Object addValue) { return new PictureType<BigDecimal>(subtract(addValue).getValue()); } /** * This method calculates rounded result of subtraction addValue to current * value. Scale value depends on finalObject's fractional size. Use this method * to round each calculation in whole expression separately * * @param finalObject object where the result of calculation will be placed * @param addValue value to subtract * @return the result of calculation in the PictureType<BigDecimal> variable. * You can use this object in next calculations */ public PictureType<BigDecimal> subtractTrunc(PictureType<?> finalObject, Object addValue) { return new PictureType<BigDecimal>( subtract(addValue).getValue().setScale(finalObject.getFractionalSize(), RoundingMode.FLOOR)); } /** * This method subtract addValue from variable without rounding. * * @param addValue value to subtract * @return the result of calculation in the PictureType<BigDecimal> variable. * You can use this object in next calculations */ public PictureType<BigDecimal> subtract(Object addValue) { if (addValue == null) { return new PictureType<>(toBigDecimal(this.value));// if addValue is null, this method will return current // value. } if (addValue instanceof PictureType) { if (((PictureType<?>) addValue).getValue() == null) { return new PictureType<>(toBigDecimal(this.value));// if addValue is null, this method will return // current value. } return new PictureType<>( toBigDecimal(this.value).subtract(toBigDecimal(((PictureType<?>) addValue).getValue()))); } return new PictureType<>(toBigDecimal(this.value).subtract(toBigDecimal(addValue))); } /** * This method divides current value by addValue object This method is used for * conversion result. It changed a lot to get the correct implementation of * calculation Now it works the same way as divide(Object addValue). And * finalObject is not necessary. * * @param finalObject object where the result of calculation will be placed * @param addValue value to divide by * @return the result of calculation in the PictureType<BigDecimal> variable. * You can use this object in next calculations */ public PictureType<BigDecimal> divide(PictureType<?> finalObject, Object addValue) { return new PictureType<BigDecimal>(divide(addValue).getValue()); } /** * This method calculates rounded result of division current value by addValue. * Scale value depends on finalObject's fractional size. Use this method to * round each calculation in whole expression separately * * @param finalObject object where the result of calculation will be placed * @param addValue value to divide by * @return the result of calculation in the PictureType<BigDecimal> variable. * You can use this object in next calculations */ public PictureType<BigDecimal> divideTrunc(PictureType<?> finalObject, Object addValue) { return new PictureType<BigDecimal>( divide(addValue).getValue().setScale(finalObject.getFractionalSize(), RoundingMode.FLOOR)); } /** * This method divides current value by addValue without rounding. * * @param addValue value to divide by * @return the result of calculation in the PictureType<BigDecimal> variable. * You can use this object in next calculations */ public PictureType<BigDecimal> divide(Object addValue) { try { if (addValue == null) { return new PictureType<>(toBigDecimal(this.value));// if addValue is null, this method will return // current value. } if (addValue instanceof PictureType) { if (((PictureType<?>) addValue).getValue() == null) { return new PictureType<>(toBigDecimal(this.value));// if addValue is null, this method will return // current value. } return new PictureType<>(toBigDecimal(this.value) .divide(toBigDecimal(((PictureType<?>) addValue).getValue()), 18, RoundingMode.HALF_UP)); // here // is // rounding // because // in // COBOL // the // biggest // length // of // numeric // variable // is // 18. } return new PictureType<>(toBigDecimal(this.value).divide(toBigDecimal(addValue), 18, RoundingMode.HALF_UP));// here // is // rounding // because // in // COBOL // the // biggest // length // of // numeric // variable // is // 18. // And // other } catch (Exception e) { // CHANGE 09/25/2018 added try/catch block to handle arithmetic errors. Now it // returns 0 if any error has been caught return new PictureType<>(new BigDecimal(0)); } } /** * calculates division of current value by addValue * * @param addValue value to divide by * @return integer part of division and remainder in the BigDecimal array. */ public BigDecimal[] divideAndRemainder(Object addValue) { try { if (addValue == null) { return new BigDecimal[] { new BigDecimal(0), new BigDecimal(0) };// if addValue is null, this method // will return current value. } if (addValue instanceof PictureType) { if (((PictureType<?>) addValue).getValue() == null) { return new BigDecimal[] { new BigDecimal(0), new BigDecimal(0) };// if addValue is null, this method // will return current value. } return toBigDecimal(this.value) .divideAndRemainder(toBigDecimal(((PictureType<?>) addValue).getValue())); } return toBigDecimal(this.value).divideAndRemainder(toBigDecimal(addValue)); } catch (Exception e) { // CHANGE 09/25/2018 added try/catch block to handle arithmetic errors. Now it // returns 0 if any error has been caught return new BigDecimal[] { new BigDecimal(0), new BigDecimal(0) }; } } /** * This method multiplies current value by addValue object This method is used * for conversion result. It changed a lot to get the correct implementation of * calculation Now it works the same way as multiply(Object addValue). And * finalObject is not necessary. * * @param finalObject object where the result of calculation will be placed * @param addValue value to multiply by * @return the result of calculation in the PictureType<BigDecimal> variable. * You can use this object in next calculations */ public PictureType<BigDecimal> multiply(PictureType<?> finalObject, Object addValue) { return new PictureType<BigDecimal>(multiply(addValue).getValue()); } /** * This method calculates rounded result of multiplying current value by * addValue. Scale value depends on finalObject's fractional size. Use this * method to round each calculation in whole expression separately * * @param finalObject object where the result of calculation will be placed * @param addValue value to multiply by * @return the result of calculation in the PictureType<BigDecimal> variable. * You can use this object in next calculations */ public PictureType<BigDecimal> multiplyTrunc(PictureType<?> finalObject, Object addValue) { return new PictureType<BigDecimal>( multiply(addValue).getValue().setScale(finalObject.getFractionalSize(), RoundingMode.FLOOR)); } /** * This method multiplies current value by addValue without rounding. * * @param addValue value to multiply by * @return the result of calculation in the PictureType<BigDecimal> variable. * You can use this object in next calculations */ public PictureType<BigDecimal> multiply(Object addValue) { if (addValue == null) { return new PictureType<>(toBigDecimal(this.value));// if addValue is null, this method will return current // value. } if (addValue instanceof PictureType) { if (((PictureType<?>) addValue).getValue() == null) { return new PictureType<>(toBigDecimal(this.value));// if addValue is null, this method will return // current value. } return new PictureType<>( toBigDecimal(this.value).multiply(toBigDecimal(((PictureType<?>) addValue).getValue()))); } return new PictureType<>(toBigDecimal(this.value).multiply(toBigDecimal(addValue))); } /** * rounds value scale size depends on the decimal size of this variable * * @param value value to round * @return rounded value */ private BigDecimal round(BigDecimal value) { if (value == null) { return value; } return value.setScale(((DecimalFormat) getFormat()).getDecimalSize(), BigDecimal.ROUND_HALF_UP); } /** * rounds value and set the result into this object * * @param value value to round and set */ public void setRoundedValue(PictureType<BigDecimal> value) { setValue(round(value.getValue())); } /** * rounds value and set the result into this object * * @param value value to round and set */ public void setRoundedValue(BigDecimal value) { setValue(round(value)); } private int getFractionalSize() { return ((DecimalFormat) format).getDecimalSize(); } private int comparePicTo(PictureType<?> comparisonvar) { return compareTo(comparisonvar.getValue()); } private int compareToDef(DefaultValue defaultValue) { switch (defaultValue) { case Spaces: return (format instanceof DecimalFormat ? formatedValue.replaceAll("[+-.,/ ]", "") : formatedValue.trim()) .isEmpty() ? 0 : 1; case Zeroes: try { if (value == null) { return 0; } return getCompareValue(Double.compare(Double.parseDouble(String.valueOf(value).trim()), 0.0)); } catch (NumberFormatException e) { return compareTo("0"); } case LowValues: return getCompareValue(formatedValue.compareTo(StringUtils.repeat((char) 0, getSize()))); case Quotes: return formatedValue.compareTo(StringUtils.repeat("\"", format.getLength())); case HighValues: if (format instanceof DecimalFormat) { return compareTo(StringUtils.repeat("9", getSize())); } else { return compareTo(StringUtils.repeat("\u00FF", getSize())); } default: return 0; } } /** * Compares two objects * * @param comparisonvar * @return 0, 1 or -1 if 0 this object is equal to comparisonvar if 1 this * object is biegger than comparisonvar if -1 this object is less than * comparisonvar */ public int compareTo(Object comparisonvar) { if (value == null && !(comparisonvar instanceof DefaultValue)) { return -1;// returns -1 if current value is null. It means that comparisonvar is bigger // than null. Except cases when comparison var is DefaultValue } if (comparisonvar instanceof PictureType) { if (type == null) { return -1 * ((PictureType<?>) comparisonvar).compareTo(value); // revert expression if this object's // type isn't specified to avoid // throwing NPE } return comparePicTo((PictureType<?>) comparisonvar); // call specific method for comparison with PT variable } if (comparisonvar instanceof DefaultValue) { return compareToDef((DefaultValue) comparisonvar);// call specific method for comparison with DefaultValue // variable } if (type instanceof Integer || type instanceof Long || type instanceof BigDecimal) { // comparison for numeric // values if (comparisonvar instanceof String) { int res = toString().trim().compareTo(comparisonvar.toString().trim()); // if comparisonvar is string // need to compare in the String // mood return getCompareValue(res); } else { return new BigDecimal(value.toString()).compareTo(new BigDecimal(comparisonvar.toString())); // if // comparison // value // is // numeric // need // to // compare // objects // as // BigDecimal // objects. // Because BigDecimal is the biggest numeric type that is used } } else if (type instanceof String) { // comparison for string values. always in String mood int res = toString().trim().compareTo(comparisonvar.toString().trim()); return getCompareValue(res); } else if (type == null && comparisonvar != null) { // if type isn't specified it will compare two objects as // BigDecimal. return ((BigDecimal) value).compareTo(new BigDecimal(comparisonvar.toString())); } return 0; } private int getCompareValue(int value) { int res = value; if (res > 0) { return 1; } else if (res < 0) { return -1; } else { return 0; } } @SuppressWarnings("unchecked") private void executeFormat() { if (value == null) { return; } if (value instanceof Integer) { if (!((DecimalFormat) format).isSigned()) { value = (T) (Integer) Math.abs((Integer) value); } value = (T) (Integer) new BigInteger(value.toString()) .divideAndRemainder(new BigInteger("1" + StringUtils.repeat("0", format.getSize())))[1].intValue(); } else if (value instanceof Long) { if (!((DecimalFormat) format).isSigned()) { value = (T) (Long) (Math.abs((Long) value)); } } else if (value instanceof BigDecimal) { if (!((DecimalFormat) format).isSigned()) { value = (T) ((BigDecimal) value).abs(); } if (((BigDecimal) value).compareTo(BigDecimal.ZERO) != 0) { if (String.valueOf(((BigDecimal) value).remainder(BigDecimal.ONE).doubleValue()).split("\\.")[1] .length() > ((DecimalFormat) format).getDecimalSize()) { value = (T) ((BigDecimal) value).setScale(((DecimalFormat) format).getDecimalSize(), RoundingMode.DOWN); } else { value = (T) ((BigDecimal) value).setScale(((DecimalFormat) format).getDecimalSize(), RoundingMode.UP); } } value = (T) ((BigDecimal) value).remainder(new BigDecimal("1" + StringUtils.repeat("0", format.getSize()))); } formatedValue = format != null ? format.toStringWithFormat(this.value) : this.value.toString(); if (this.type instanceof String) { value = (T) formatedValue; } } @SuppressWarnings("unchecked") private void getTypedValue(Type t) { switch (t) { case Integer: this.type = (T) (Integer) 0; break; case String: this.type = (T) ""; break; case BigDecimal: this.type = (T) new BigDecimal(0); break; case Long: this.type = (T) (Long) 0L; break; default: } } private Integer toInteger(Object value) { if (value == null) { return 0; } else if (value instanceof Integer) { return (Integer) value; } else if (value instanceof Long) { // return ((Long) value).intValue(); try { return java.lang.Math.toIntExact((Long) value); } catch (ArithmeticException e) { // if long value more them max integer return new Integer(value.toString().substring(value.toString().length() - this.getSize() - 1)); } } else if (value instanceof BigDecimal) { return ((BigDecimal) value).intValue(); } else if (value instanceof Double) { return ((Double) value).intValue(); } else if (value instanceof String || value instanceof StructureModel) { try { String str = value.toString(); if (str.trim().length() < getSize() && str.trim().length() > 0) { str = str.replace(" ", "0"); } return new BigInteger(str.trim()) .divideAndRemainder(new BigInteger("1" + StringUtils.repeat("0", format.getSize())))[1] .intValue(); } catch (NumberFormatException ex) { formatedValue = value.toString(); return null; } } return 0; } private Long toLong(Object value) { if (value == null) { return 0L; } else if (value instanceof Integer) { return Long.valueOf((Integer) value); } else if (value instanceof Long) { return (Long) value; } else if (value instanceof BigDecimal) { return ((BigDecimal) value).longValue(); } else if (value instanceof Double) { return ((Double) value).longValue(); } else if (value instanceof String || value instanceof StructureModel) { try { if (StringUtils.containsAny(value.toString(), '+', '-')) { throw new NumberFormatException(); } return new BigInteger(value.toString().trim()) .divideAndRemainder(new BigInteger("1" + StringUtils.repeat("0", format.getSize())))[1] .longValue(); } catch (NumberFormatException ex) { formatedValue = value.toString(); return null; } } return 0L; } private BigDecimal toBigDecimal(Object value) { if (value == null) { return new BigDecimal(0); } else if (value instanceof Integer || value instanceof Long || value instanceof Double) { return new BigDecimal(String.valueOf(value)); } else if (value instanceof BigDecimal) { return (BigDecimal) value; } else if (value instanceof String || value instanceof StructureModel) { try { return new BigDecimal(value.toString().trim()); } catch (NumberFormatException ex) { formatedValue = value.toString(); return null; } } return new BigDecimal(0); } private String toStringValue(Object value) { if (value == null) { return ""; } else if (value instanceof Integer) { return Integer.toString(Math.abs((Integer) value)); } else if (value instanceof Long) { return Long.toString(Math.abs((Long) value)); } else if (value instanceof BigDecimal) { return "" + ((BigDecimal) value).abs().toString().replaceAll("\\.", ""); } else if (value instanceof Double) { return Double.toString(Math.abs((Double) value)).replaceAll("\\.", ""); } else if (value instanceof String || value instanceof StructureModel) { return value.toString(); } return ""; } /** * get String view of object * * @return String view of object */ @Override public String toString() { if (this.type instanceof Integer || this.type instanceof Long || this.type instanceof BigDecimal || this.type instanceof String) { return formatedValue; // by default it should return formated value because it should store the // correct String view of PT object } else { return String.valueOf(value); } } /** * * @return value of PT variable */ public T getValue() { return value; } /** * sets value into this object * * @param value to set */ @SuppressWarnings("unchecked") public void setValue(Object value) { // initialize trimmed value that is used to set it into DB. // this logic works correct only for Stricng PT variables. if (value instanceof String) { initTrimmedValuebyString(value == null ? "" : (String) value); } else { initTrimmedValue(value == null ? "" : value.toString()); } if (value instanceof PictureType && ((PictureType<?>) value).getValue() instanceof String) { initTrimmedValuebyString(((PictureType<?>) value).getTrimmedValue() == null ? "" : ((PictureType<?>) value).getTrimmedValue()); } hasDefVal = false; // if new value is PT object need to call specific method for this case if (value instanceof PictureType) { setValueFromPT((PictureType<?>) value); executeFormat(); return; } // if new value is DevaultValue object need to call specific method for this // case if (value instanceof DefaultValue) { setDefaultValue((DefaultValue) value); return; } // if new value is other type need to cast it to the correct type // the correct type is specified in tyoe variable if (this.type instanceof Integer) { this.value = (T) toInteger(value); } else if (this.type instanceof Long) { this.value = (T) toLong(value); } else if (this.type instanceof BigDecimal) { this.value = (T) toBigDecimal(value); } else if (this.type instanceof String) { this.value = (T) toStringValue(value); } // The new value is successfully set // need to executes format to get correct formated value for this value executeFormat(); } private void setValueFromPT(PictureType<?> value) { if (value.format != null && value.format instanceof DecimalFormat && type instanceof String) { if (((DecimalFormat) value.format).getSign() == 's') { setValue(value.formatedValue.replaceAll("[+-]", "")); } else { setValue(value.formatedValue); } } else if (/* type instanceof String && */ value.type instanceof String) { // commented due to case /* * PictureType<Integer> LabLine2CtnNo = new * PictureType<>(PictureType.Type.Integer, new DecimalFormat("ZZ9")); * PictureType<String> TShipCtnNo = new PictureType<>(PictureType.Type.String, * new AlphanumericFormat("X(3)")); TShipCtnNo.setValue("7"); * System.out.println("|"+TShipCtnNo.toString()+"|"); * LabLine2CtnNo.setValue(TShipCtnNo); System.out.println(LabLine2CtnNo); */ setValue(value.getTrimmedValue()); } else { setValue(value.getValue()); } } /** * sets data from file. uses in the DataStructures. * * @param bytes value to set in bytes */ public void setDataFromFile(byte[] bytes) { hasDefVal = false; String str = new String(bytes); if (str.equals(StringUtils.repeat("\u00ff", str.length()))) { // if HighValues need to set DefaultValue // HighValues setDefaultValue(HighValues); return; } if (format instanceof DecimalFormat && ((DecimalFormat) format).getCompType() == DecimalFormat.CompType.Comp) { // proceed // string // for // COMP // variables str = setCompFromFile(bytes); } if (format instanceof DecimalFormat && ((DecimalFormat) format).getCompType() == DecimalFormat.CompType.Comp3) { // proceed // string // for // COMP3 // variables str = setComp3FromFile(bytes); } if (format instanceof DecimalFormat && /* ((DecimalFormat) format).isSigned() && */ ((DecimalFormat) format).getCompType() == null) { // adds // sign // for // non // comp // variables str = setSignedFromFile(str); } if (format instanceof DecimalFormat && str.isEmpty()) { // handles situation when str is empty. str = "0"; } if (format instanceof DecimalFormat && ((DecimalFormat) format).getDecimalSize() > 0) { // put comma on the // correct place try { BigDecimal.valueOf(Double.parseDouble(str)); // test if str is numeric if (((DecimalFormat) format).getCompType() == DecimalFormat.CompType.Comp3 && str.length() < ((DecimalFormat) format).getDecimalSize()) { // string is empty or only have // decimals String decNumber = ""; for (int j = str.length(); j < ((DecimalFormat) format).getDecimalSize(); j++) { decNumber = "0" + decNumber; } str = "." + decNumber + str; } else if (!str.contains(".")) { str = str.substring(0, str.length() - ((DecimalFormat) format).getDecimalSize()) + "." + str.substring(str.length() - ((DecimalFormat) format).getDecimalSize()); } } catch (NumberFormatException ex) { // do nothing in this case // exception throws when str is not numeric // but in COBOL data will be stored into variable in this case even if it isn't // numeric. } } if (format.getPattern().contains(",") && !str.contains(",")) { formatedValue = str; return; } // all previous steps was preparation for data from file to be set into this // object setValue(str); } private String setCompFromFile(byte[] bytes) { String str = bytesToHex(bytes); str = StringUtils.repeat(str.charAt(0) == 'F' ? 'F' : '0', 16 - str.length()) + str; return String.valueOf(new BigInteger(str, 16).longValue()); } private String setComp3FromFile(byte[] bytes) { String str; if (isEBSDIC) { str = bytesToHex(new String(bytes).getBytes(Charset.forName("IBM1047"))); } else { str = bytesToHex(bytes); } str = str.replaceAll("EFBE", ""); boolean isnegative = str.charAt(str.length() - 1) == 'D'; if (((str.charAt(str.length() - 1) == 'D' || str.charAt(str.length() - 1) == 'C') && ((DecimalFormat) format).isSigned()) || str.charAt(str.length() - 1) == 'F') { str = str.substring(0, str.length() - 1); try { str = String.valueOf(type instanceof BigDecimal && new Long(str).compareTo( Long.parseLong(StringUtils.repeat('9', ((DecimalFormat) format).getDecimalSize()))) == -1 ? new BigDecimal(str) .divide(new BigDecimal(Math.pow(10, ((DecimalFormat) format).getDecimalSize()) * (isnegative ? -1 : 1))) : new Long(str) * (isnegative ? -1 : 1)); // str = String.valueOf(new Long(str) * (isnegative ? -1 : 1)); } catch (Exception e) { str = new String(bytes); } } else { str = new String(bytes); } return str; } private String setSignedFromFile(String str) { if (!str.isEmpty() && Pattern.compile("[qrstuvwxyp}JKLMNOPQR]").matcher(str.substring(str.length() - 1)).matches()) { return "-" + trimZeroes(str.substring(0, str.length() - 1) + ((DecimalFormat) format).getNegativeInt(str.charAt(str.length() - 1))); } if (!str.isEmpty() && Pattern.compile("[\\{ABCDEFGHI]").matcher(str.substring(str.length() - 1)).matches()) { return str.substring(0, str.length() - 1) + ((DecimalFormat) format).getNegativeInt(str.charAt(str.length() - 1)); } return str; } private String trimZeroes(String str) { String res = str; while (!res.isEmpty() && res.charAt(0) == '0') { res = res.substring(1); } return res; } private static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_ARRAY[v >>> 4]; hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; } return new String(hexChars); } /** * set Defaultvalue variable into this PT object * * @param defaultValue to set */ @SuppressWarnings("unchecked") public void setDefaultValue(DefaultValue defaultValue) { switch (defaultValue) { case Spaces: formatedValue = StringUtils.repeat(" ", format.getLength()); // sets chain of spaces if defaultValue is // SPACES setValue(formatedValue); break; case Zeroes: formatedValue = StringUtils.repeat("0", format.getLength());// sets chain of zeroes if defaultValue is // ZEROES setValue(formatedValue); break; case LowValues: formatedValue = ""; value = format instanceof DecimalFormat ? null : (T) formatedValue; // sets empty String if defaultValue is // LowValues break; case Quotes: formatedValue = StringUtils.repeat("\"", format.getLength()); value = format instanceof DecimalFormat ? null : (T) formatedValue;// sets chain of quotes if defaultValue // is QUOTES break; case HighValues: if (format instanceof DecimalFormat) { setValue(StringUtils.repeat("9", getSize()));// sets chain of 9 if defaultValue is HighValues and format // instanceof DecimalFormat break; } else { setValue(StringUtils.repeat("\u00FF", getSize()));// sets chain of "\u00FF" if defaultValue is // HighValues and format instanceof // AlphanumericFormat } default: } this.defaultValue = defaultValue; hasDefVal = false; // set False to hasDefVal flag } /** * set Defaultvalue variable into this PT object from DataStructure. Uses only * for PT objects that are in structure * * @param defaultValue */ @SuppressWarnings("unchecked") public void setDefaultValueFromStructure(DefaultValue defaultValue) { switch (defaultValue) { case Spaces: formatedValue = StringUtils.repeat(" ", format.getLength()); value = format instanceof DecimalFormat ? null : (T) formatedValue;// sets chain of spaces if defaultValue // is SPACES break; case Zeroes: formatedValue = StringUtils.repeat("0", format.getLength()); value = format instanceof DecimalFormat ? (T) (Integer) 0 : (T) formatedValue;// sets chain of zeroes if // defaultValue is ZEROES break; case LowValues: formatedValue = ""; value = format instanceof DecimalFormat ? null : (T) formatedValue;// sets empty String if defaultValue is // LowValues break; case Quotes: formatedValue = StringUtils.repeat("\"", format.getLength()); value = format instanceof DecimalFormat ? null : (T) formatedValue;// sets chain of quotes if defaultValue // is QUOTES break; case HighValues: if (format instanceof DecimalFormat) { setValue(StringUtils.repeat("9", // sets chain of 9 if defaultValue is HighValues and format instanceof // DecimalFormat. put comma if needed ((DecimalFormat) format).getSize()) + ((((DecimalFormat) format).getDecimalSize()) != 0 ? "." + StringUtils.repeat("9", ((DecimalFormat) format).getDecimalSize()) : "")); } else { setValue(StringUtils.repeat("\u00FF", getSize()));// sets chain of "\u00FF" if defaultValue is // HighValues and format instanceof // AlphanumericFormat } default: } this.defaultValue = defaultValue; hasDefVal = true;// set True to hasDefVal flag initTrimmedValue(null); } /** * sets obejct to the initial state */ public void initialize() { initTrimmedValue(null); hasDefVal = false; if (this.type instanceof Integer) { setValue(0); } else if (this.type instanceof Long) { setValue(0L); } else if (this.type instanceof BigDecimal) { setValue(new BigDecimal(0)); } else if (this.type instanceof String) { setValue(""); } } public Format getFormat() { return format; } public void setFormat(Format format) { this.format = format; } /** * converts object to byte array to write it into file * * @return byte array to write into file */ public byte[] toFile() { return value == null || hasDefVal && (format instanceof DecimalFormat && value.equals(0)) || (hasDefVal && (defaultValue != HighValues && !(format instanceof DecimalFormat))) ? formatedValue.getBytes() : new String(byteArrToChar(format.toFileString(value))).getBytes(); } private char[] byteArrToChar(byte[] ba) { char[] chars = new char[ba.length]; for (int i = 0; i < ba.length; i++) { chars[i] = (char) ba[i]; } return chars; } /** * returns size of object. size depends on format. * * @return */ public int getSize() { if (format instanceof DecimalFormat) { if (((DecimalFormat) format).getCompType() == null) { return format.getLength(); } else if (((DecimalFormat) format).getCompType() == DecimalFormat.CompType.Comp) { return ((DecimalFormat) format).getCompSize(); } else { return (int) Math .round(((double) format.getSize() + ((DecimalFormat) format).getDecimalSize()) / 2 + 0.5); } } else { return format.getSize(); } } /** * Indicators are not supported in java. This method is used to implement Cobol * logic in the converted code. You don't have to use this logic. get method for * indicator * * @return indicator value */ public int getIndicator() { return indicator; } /** * Indicators are not supported in java. This method is used to implement Cobol * logic in the converted code. You don't have to use this logic. set method for * indicator * * @param indicator new value of indicator */ public void setIndicator(int indicator) { this.indicator = indicator; } /** * get value with indicator if indicator is -1 it returns null in other case it * returns current value * * @return value to set as a parameter for query */ @SuppressWarnings("unchecked") public T getIndValue() { if (indicator == -1) { return null; } if (type instanceof String) { return (T) getTrimmedValue(); } return value; } /** * set value with indicator if value is null indicator is -1 in other case * indicator is 0 * * @param value to set into variable */ public void setIndValue(Object value) { if (value == null) { indicator = -1; } else { indicator = 0; setValue(value); } } /** * this method for Pro*Cobol with ORACLE */ public void setIndValue(Object value, int columnType) { if (value == null) { indicator = -1; if (columnType == VARCHAR || columnType == CHAR || columnType == LONGNVARCHAR) { setValue("", columnType); } } else { indicator = 0; if (columnType == CLOB) { try { setValue(((Clob) value).getSubString(1, (int) ((Clob) value).length())); return; } catch (SQLException e) { LOGGER.info(String.valueOf(e)); } } setValue(value.toString(), columnType); } } private void initTrimmedValue(String value) { trimmedValue = value; initTrimmedValuebyString(value != null ? value : ""); } private void initTrimmedValuebyString(String value) { trimmedValue = value; if (trimmedValue.length() > getSize()) { trimmedValue = trimmedValue.substring(0, getSize()); } while (trimmedValue.length() > 0 && trimmedValue.substring(trimmedValue.length() - 1).equals(" ")) { trimmedValue = trimmedValue.substring(0, trimmedValue.length() - 1); } } /** * Use method tp get trimmedValue use Trimmed value only for String variables * * @return trimmed value */ public String getTrimmedValue() { return trimmedValue == null || trimmedValue.trim().isEmpty() ? "" : trimmedValue; } /** * this method for Pro*Cobol with ORACLE */ public void setValue(String value, int columnType) { if (value == null) { setValue(StringUtils.repeat(" ", getSize())); return; } if (columnType == VARCHAR || columnType == CHAR || columnType == LONGNVARCHAR) { setValue(value); } else { setValue(StringUtils.repeat(" ", getSize() - value.replaceAll("[-.]", "").length()) + value.replaceAll("[-.]", "")); } } /** * This enum declares all default values that can be used in cobol */ public enum DefaultValue { Spaces(" "), Zeroes("0"), HighValues(" "), LowValues(" "), Quotes(" "), Nulls(" "); private final String value; private DefaultValue(String s) { value = s; } public boolean equalsName(String otherName) { return value.equals(otherName); } @Override public String toString() { return this.value; } } /** * replace string in the current value to new string use for String PT variables * * @param from symbols to replace * @param to symbols to replace by */ @SuppressWarnings("unchecked") public void replaceAll(String from, String to) { formatedValue = formatedValue.replaceAll(from, to);
if (format instanceof AlphanumericFormat) {
0
2023-12-13 14:56:32+00:00
8k
blueokanna/ReverseCoin
src/main/java/ReverseCoinBlockChainGeneration/MiningReverseCoinBlock.java
[ { "identifier": "CommandCode", "path": "src/main/java/BlockModel/CommandCode.java", "snippet": "public enum CommandCode {\n /*\n 查询最后一个区块\n */\n CheckLastestBlock(100),\n /*\n 查询整个区块链\n */\n CheckWholeChain(101),\n /*\n 返回一个最新的区块\n */\n ReturnLastestBlock(102),\n...
import BlockModel.CommandCode; import BlockModel.PeerMessages; import BlockModel.PerformRingSign; import BlockModel.ReverseCoinBlock; import BlockModel.ReverseCoinTransaction; import BlockModel.TimeStampGenerator; import ReverseCoinChainNetwork.P2PNetwork; import com.google.gson.GsonBuilder; import java.security.SecureRandom; import java.util.Base64; import java.util.List; import java.util.concurrent.CompletionService; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import ConnectionAPI.NewReverseCoinBlockInterface; import ConnectionAPI.ReverseCoinChainConfigInterface;
5,809
package ReverseCoinBlockChainGeneration; public class MiningReverseCoinBlock { private volatile long times = new TimeStampGenerator().TimeToSync(); private volatile int numberGenerations; private volatile long nonce; private volatile ExecutorService executor; private volatile ReverseCoinBlock blocks = new ReverseCoinBlock(); public ReverseCoinBlock mineBlock(NewReverseCoinBlockInterface addnewblock, ReverseCoinChainConfigInterface config) { System.out.println("Mining New Block Now......"); try { String target = new String(new char[config.getDifficulty()]).replace('\0', '0'); int numThreads = Runtime.getRuntime().availableProcessors() / 2; executor = Executors.newFixedThreadPool(numThreads); CompletionService<ReverseCoinBlock> completionService = new ExecutorCompletionService<>(executor); CountDownLatch latch = new CountDownLatch((int) Math.pow(numThreads, numThreads)); for (int i = 0; i < (int) Math.pow(numThreads, numThreads); i++) { completionService.submit(() -> miningThread(addnewblock, config, target, latch)); } latch.await(); for (int i = 0; i < numThreads; i++) { Future<ReverseCoinBlock> future = completionService.poll(); if (future != null && future.get() != null) { blocks = future.get(); numThreads++; break; } } executor.shutdown(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); System.out.println("Mining was interrupted: " + e.getMessage()); } catch (ExecutionException e) { System.out.println("Error occurred during mining: " + e.getMessage()); } return blocks; } private ReverseCoinBlock miningThread(NewReverseCoinBlockInterface addnewblock, ReverseCoinChainConfigInterface config, String target, CountDownLatch latch) { try { while (true) { String transationHash = toTransJsonString(NewBlockTransData()); String text = config.getLatestBlock().getThisBlockHash() + transationHash + nonce; String localHash = config.SHA3with256Hash(config.SHA3with256Hash(text)); if (addnewblock.checkBlocksHash(localHash, target, config)) { final long currentNonceValue = nonce; String previousHash = config.getLatestBlock().getThisBlockHash(); ReverseCoinBlock newBlocks = addnewblock.generatedNewBlock(previousHash, NewBlockTransData(), transationHash, currentNonceValue, localHash, config); broadcastNewBlock(newBlocks, config); return newBlocks; } nonce++; } } catch (Exception e) { System.out.println("Error Message : " + e.getMessage()); } finally { latch.countDown(); } return null; } private void broadcastNewBlock(ReverseCoinBlock blocks, ReverseCoinChainConfigInterface config) { PeerMessages peermessageSend = new PeerMessages(); peermessageSend.setCommandCode(CommandCode.ReturnLastestBlock); peermessageSend.setMessage(new GsonBuilder().create().toJson(blocks)); new P2PNetwork().BroadCastBlockMessage(new GsonBuilder().setPrettyPrinting().create().toJson(peermessageSend), config); } private CopyOnWriteArrayList<ReverseCoinTransaction> NewBlockTransData() { SecureRandom secureRandom = new SecureRandom(); numberGenerations = Math.abs(secureRandom.nextInt()); while (numberGenerations > 100) { numberGenerations /= 2; } List<ReverseCoinTransaction> TransData = new CopyOnWriteArrayList<>(); TransData.add(new ReverseCoinTransaction("ReverseCoin_Sender1", "ReverseCoin_Receiver1", 1145141919810L, numberGenerations / 2)); String Sender = TransData.get(0).getSender(); String Receiver = TransData.get(0).getReceiver(); double Amount = TransData.get(0).getAmount(); double gasFee = TransData.get(0).getTxfee(); String data = Sender + Receiver + Amount + gasFee + times;
package ReverseCoinBlockChainGeneration; public class MiningReverseCoinBlock { private volatile long times = new TimeStampGenerator().TimeToSync(); private volatile int numberGenerations; private volatile long nonce; private volatile ExecutorService executor; private volatile ReverseCoinBlock blocks = new ReverseCoinBlock(); public ReverseCoinBlock mineBlock(NewReverseCoinBlockInterface addnewblock, ReverseCoinChainConfigInterface config) { System.out.println("Mining New Block Now......"); try { String target = new String(new char[config.getDifficulty()]).replace('\0', '0'); int numThreads = Runtime.getRuntime().availableProcessors() / 2; executor = Executors.newFixedThreadPool(numThreads); CompletionService<ReverseCoinBlock> completionService = new ExecutorCompletionService<>(executor); CountDownLatch latch = new CountDownLatch((int) Math.pow(numThreads, numThreads)); for (int i = 0; i < (int) Math.pow(numThreads, numThreads); i++) { completionService.submit(() -> miningThread(addnewblock, config, target, latch)); } latch.await(); for (int i = 0; i < numThreads; i++) { Future<ReverseCoinBlock> future = completionService.poll(); if (future != null && future.get() != null) { blocks = future.get(); numThreads++; break; } } executor.shutdown(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); System.out.println("Mining was interrupted: " + e.getMessage()); } catch (ExecutionException e) { System.out.println("Error occurred during mining: " + e.getMessage()); } return blocks; } private ReverseCoinBlock miningThread(NewReverseCoinBlockInterface addnewblock, ReverseCoinChainConfigInterface config, String target, CountDownLatch latch) { try { while (true) { String transationHash = toTransJsonString(NewBlockTransData()); String text = config.getLatestBlock().getThisBlockHash() + transationHash + nonce; String localHash = config.SHA3with256Hash(config.SHA3with256Hash(text)); if (addnewblock.checkBlocksHash(localHash, target, config)) { final long currentNonceValue = nonce; String previousHash = config.getLatestBlock().getThisBlockHash(); ReverseCoinBlock newBlocks = addnewblock.generatedNewBlock(previousHash, NewBlockTransData(), transationHash, currentNonceValue, localHash, config); broadcastNewBlock(newBlocks, config); return newBlocks; } nonce++; } } catch (Exception e) { System.out.println("Error Message : " + e.getMessage()); } finally { latch.countDown(); } return null; } private void broadcastNewBlock(ReverseCoinBlock blocks, ReverseCoinChainConfigInterface config) { PeerMessages peermessageSend = new PeerMessages(); peermessageSend.setCommandCode(CommandCode.ReturnLastestBlock); peermessageSend.setMessage(new GsonBuilder().create().toJson(blocks)); new P2PNetwork().BroadCastBlockMessage(new GsonBuilder().setPrettyPrinting().create().toJson(peermessageSend), config); } private CopyOnWriteArrayList<ReverseCoinTransaction> NewBlockTransData() { SecureRandom secureRandom = new SecureRandom(); numberGenerations = Math.abs(secureRandom.nextInt()); while (numberGenerations > 100) { numberGenerations /= 2; } List<ReverseCoinTransaction> TransData = new CopyOnWriteArrayList<>(); TransData.add(new ReverseCoinTransaction("ReverseCoin_Sender1", "ReverseCoin_Receiver1", 1145141919810L, numberGenerations / 2)); String Sender = TransData.get(0).getSender(); String Receiver = TransData.get(0).getReceiver(); double Amount = TransData.get(0).getAmount(); double gasFee = TransData.get(0).getTxfee(); String data = Sender + Receiver + Amount + gasFee + times;
byte[] Signature = new PerformRingSign().performRingSign(data, numberGenerations, numberGenerations / 2);
2
2023-12-11 05:18:04+00:00
8k
Patbox/PolyDecorations
src/main/java/eu/pb4/polydecorations/block/DecorationsBlockEntities.java
[ { "identifier": "ModInit", "path": "src/main/java/eu/pb4/polydecorations/ModInit.java", "snippet": "public class ModInit implements ModInitializer {\n\tpublic static final String ID = \"polydecorations\";\n\tpublic static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMet...
import eu.pb4.polydecorations.ModInit; import eu.pb4.polydecorations.block.item.ShelfBlock; import eu.pb4.polydecorations.block.item.ShelfBlockEntity; import eu.pb4.polydecorations.block.other.GenericSingleItemBlockEntity; import eu.pb4.polydecorations.block.extension.SignPostBlock; import eu.pb4.polydecorations.block.extension.SignPostBlockEntity; import eu.pb4.polymer.core.api.block.PolymerBlockUtils; import net.fabricmc.fabric.api.object.builder.v1.block.entity.FabricBlockEntityTypeBuilder; import net.minecraft.block.entity.BlockEntity; import net.minecraft.block.entity.BlockEntityType; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.util.Identifier;
6,812
package eu.pb4.polydecorations.block; public class DecorationsBlockEntities { public static final BlockEntityType<?> SHELF = register("shelf",
package eu.pb4.polydecorations.block; public class DecorationsBlockEntities { public static final BlockEntityType<?> SHELF = register("shelf",
FabricBlockEntityTypeBuilder.create(ShelfBlockEntity::new)
2
2023-12-10 16:20:36+00:00
8k
i-moonlight/Movie_Manager
backend/src/main/java/ch/xxx/moviemanager/adapter/repository/ActorRepositoryBean.java
[ { "identifier": "CommonUtils", "path": "backend/src/main/java/ch/xxx/moviemanager/domain/common/CommonUtils.java", "snippet": "public class CommonUtils {\n\n\tpublic static Date convert(LocalDate localDate) {\n\t\treturn Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());\n\t}\n\n\tpu...
import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; import org.hibernate.search.mapper.orm.Search; import org.hibernate.search.mapper.orm.session.SearchSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; import ch.xxx.moviemanager.domain.common.CommonUtils; import ch.xxx.moviemanager.domain.model.dto.ActorDto.Gender; import ch.xxx.moviemanager.domain.model.dto.ActorFilterCriteriaDto; import ch.xxx.moviemanager.domain.model.dto.SearchPhraseDto; import ch.xxx.moviemanager.domain.model.dto.SearchStringDto; import ch.xxx.moviemanager.domain.model.entity.Actor; import ch.xxx.moviemanager.domain.model.entity.ActorRepository; import ch.xxx.moviemanager.domain.model.entity.Cast; import ch.xxx.moviemanager.domain.model.entity.User; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; import jakarta.persistence.metamodel.EntityType; import jakarta.persistence.metamodel.Metamodel; import jakarta.validation.Valid;
4,313
/** * Copyright 2019 Sven Loesekann 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 ch.xxx.moviemanager.adapter.repository; @Repository public class ActorRepositoryBean implements ActorRepository { private static final Logger LOGGER = LoggerFactory.getLogger(ActorRepositoryBean.class); private static final String BIOGRAPHY = "biography"; private final JpaActorRepository jpaActorRepository; private final EntityManager entityManager; public ActorRepositoryBean(JpaActorRepository jpaActorRepository, EntityManagerFactory entityManagerFactory) { this.jpaActorRepository = jpaActorRepository; this.entityManager = entityManagerFactory.createEntityManager(); } public Optional<Actor> findById(Long id) { return this.jpaActorRepository.findById(id); } public Actor save(@Valid Actor actorEntity) { return this.jpaActorRepository.save(actorEntity); } public void deleteById(Long id) { this.jpaActorRepository.deleteById(id); } public List<Actor> findByActorName(String name, Long userId, Pageable pageable) { return this.jpaActorRepository.findByActorName(name, userId, pageable); } public Optional<Actor> findByActorId(Long actorId, Long userId) { return this.jpaActorRepository.findByActorId(actorId, userId); } public List<Actor> findActorsByPage(Long userId, Pageable pageble) { return this.findActorsByPage(userId, pageble); } @Override public List<Actor> findUnusedActors() { return this.jpaActorRepository.findUnusedActors(); } public List<Actor> findByFilterCriteria(ActorFilterCriteriaDto filterCriteriaDto, Long userId) { CriteriaQuery<Actor> cq = this.entityManager.getCriteriaBuilder().createQuery(Actor.class); Root<Actor> cActor = cq.from(Actor.class); List<Predicate> predicates = new ArrayList<>(); Optional.ofNullable(filterCriteriaDto.getBirthdayFrom()) .ifPresent(x -> predicates.add(this.entityManager.getCriteriaBuilder().greaterThanOrEqualTo( cActor.<Date>get("birthday"), CommonUtils.convert(filterCriteriaDto.getBirthdayFrom())))); Optional.ofNullable(filterCriteriaDto.getBirthdayTo()) .ifPresent(x -> predicates.add(this.entityManager.getCriteriaBuilder().lessThanOrEqualTo( cActor.<Date>get("birthday"), CommonUtils.convert(filterCriteriaDto.getBirthdayTo())))); Optional.ofNullable(filterCriteriaDto.getDead()).ifPresent( x -> predicates.add(this.entityManager.getCriteriaBuilder().isNotNull(cActor.<Date>get("deathday")))); Optional.ofNullable(filterCriteriaDto.getGender()).stream().filter(myGender -> !Gender.Unknown.equals(myGender)) .findFirst().ifPresent(x -> predicates.add(this.entityManager.getCriteriaBuilder() .equal(cActor.get("gender"), filterCriteriaDto.getGender().getCode()))); Optional.ofNullable(filterCriteriaDto.getName()).stream().filter(myName -> myName.trim().length() > 2) .findFirst() .ifPresent(x -> predicates.add(this.entityManager.getCriteriaBuilder().like( this.entityManager.getCriteriaBuilder().lower(cActor.get("name")), String.format("%%%s%%", filterCriteriaDto.getName().toLowerCase())))); if (filterCriteriaDto.getPopularity() > 0) { predicates.add(this.entityManager.getCriteriaBuilder().greaterThanOrEqualTo(cActor.get("popularity"), Double.valueOf(Integer.valueOf(filterCriteriaDto.getPopularity()).toString()))); } Optional.ofNullable(filterCriteriaDto.getMovieCharacter()).stream() .filter(myCharacter -> myCharacter.trim().length() > 2).findFirst().ifPresent(x -> { Metamodel m = this.entityManager.getMetamodel(); EntityType<Actor> actor_ = m.entity(Actor.class); predicates.add(this.entityManager.getCriteriaBuilder() .like(this.entityManager.getCriteriaBuilder()
/** * Copyright 2019 Sven Loesekann 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 ch.xxx.moviemanager.adapter.repository; @Repository public class ActorRepositoryBean implements ActorRepository { private static final Logger LOGGER = LoggerFactory.getLogger(ActorRepositoryBean.class); private static final String BIOGRAPHY = "biography"; private final JpaActorRepository jpaActorRepository; private final EntityManager entityManager; public ActorRepositoryBean(JpaActorRepository jpaActorRepository, EntityManagerFactory entityManagerFactory) { this.jpaActorRepository = jpaActorRepository; this.entityManager = entityManagerFactory.createEntityManager(); } public Optional<Actor> findById(Long id) { return this.jpaActorRepository.findById(id); } public Actor save(@Valid Actor actorEntity) { return this.jpaActorRepository.save(actorEntity); } public void deleteById(Long id) { this.jpaActorRepository.deleteById(id); } public List<Actor> findByActorName(String name, Long userId, Pageable pageable) { return this.jpaActorRepository.findByActorName(name, userId, pageable); } public Optional<Actor> findByActorId(Long actorId, Long userId) { return this.jpaActorRepository.findByActorId(actorId, userId); } public List<Actor> findActorsByPage(Long userId, Pageable pageble) { return this.findActorsByPage(userId, pageble); } @Override public List<Actor> findUnusedActors() { return this.jpaActorRepository.findUnusedActors(); } public List<Actor> findByFilterCriteria(ActorFilterCriteriaDto filterCriteriaDto, Long userId) { CriteriaQuery<Actor> cq = this.entityManager.getCriteriaBuilder().createQuery(Actor.class); Root<Actor> cActor = cq.from(Actor.class); List<Predicate> predicates = new ArrayList<>(); Optional.ofNullable(filterCriteriaDto.getBirthdayFrom()) .ifPresent(x -> predicates.add(this.entityManager.getCriteriaBuilder().greaterThanOrEqualTo( cActor.<Date>get("birthday"), CommonUtils.convert(filterCriteriaDto.getBirthdayFrom())))); Optional.ofNullable(filterCriteriaDto.getBirthdayTo()) .ifPresent(x -> predicates.add(this.entityManager.getCriteriaBuilder().lessThanOrEqualTo( cActor.<Date>get("birthday"), CommonUtils.convert(filterCriteriaDto.getBirthdayTo())))); Optional.ofNullable(filterCriteriaDto.getDead()).ifPresent( x -> predicates.add(this.entityManager.getCriteriaBuilder().isNotNull(cActor.<Date>get("deathday")))); Optional.ofNullable(filterCriteriaDto.getGender()).stream().filter(myGender -> !Gender.Unknown.equals(myGender)) .findFirst().ifPresent(x -> predicates.add(this.entityManager.getCriteriaBuilder() .equal(cActor.get("gender"), filterCriteriaDto.getGender().getCode()))); Optional.ofNullable(filterCriteriaDto.getName()).stream().filter(myName -> myName.trim().length() > 2) .findFirst() .ifPresent(x -> predicates.add(this.entityManager.getCriteriaBuilder().like( this.entityManager.getCriteriaBuilder().lower(cActor.get("name")), String.format("%%%s%%", filterCriteriaDto.getName().toLowerCase())))); if (filterCriteriaDto.getPopularity() > 0) { predicates.add(this.entityManager.getCriteriaBuilder().greaterThanOrEqualTo(cActor.get("popularity"), Double.valueOf(Integer.valueOf(filterCriteriaDto.getPopularity()).toString()))); } Optional.ofNullable(filterCriteriaDto.getMovieCharacter()).stream() .filter(myCharacter -> myCharacter.trim().length() > 2).findFirst().ifPresent(x -> { Metamodel m = this.entityManager.getMetamodel(); EntityType<Actor> actor_ = m.entity(Actor.class); predicates.add(this.entityManager.getCriteriaBuilder() .like(this.entityManager.getCriteriaBuilder()
.lower(cActor.join(actor_.getDeclaredList("casts", Cast.class)).get("movieChar")),
7
2023-12-11 13:53:51+00:00
8k
i-moonlight/Suricate
src/main/java/com/michelin/suricate/services/js/services/JsExecutionService.java
[ { "identifier": "JsExecutionDto", "path": "src/main/java/com/michelin/suricate/model/dto/js/JsExecutionDto.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@EqualsAndHashCode(callSuper = false)\n@ToString\npublic class JsExecutionDto extends AbstractDto {\n private String properties;\n pri...
import com.michelin.suricate.model.dto.js.JsExecutionDto; import com.michelin.suricate.model.entities.CategoryParameter; import com.michelin.suricate.model.entities.Project; import com.michelin.suricate.model.entities.ProjectGrid; import com.michelin.suricate.model.entities.ProjectWidget; import com.michelin.suricate.model.enums.WidgetStateEnum; import com.michelin.suricate.services.api.ProjectWidgetService; import com.michelin.suricate.utils.JsonUtils; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
6,249
/* * * * Copyright 2012-2021 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 * * * * 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.michelin.suricate.services.js.services; /** * Js execution service. */ @Slf4j @Service public class JsExecutionService { @Lazy @Autowired private ProjectWidgetService projectWidgetService; /** * Get the list of related Js execution for each widget of a project. * * @param project The project * @return The list of related Js executions */ @Transactional public List<JsExecutionDto> getJsExecutionsByProject(final Project project) { return project.getGrids() .stream() .map(ProjectGrid::getWidgets) .flatMap(Collection::stream) .map(this::createJsExecutionByProjectWidget) .toList(); } /** * Create a js execution by a project widget id. * * @param projectWidgetId The project widget id * @return The related Js execution */ public JsExecutionDto getJsExecutionByProjectWidgetId(final Long projectWidgetId) { Optional<ProjectWidget> projectWidgetOptional = projectWidgetService.getOne(projectWidgetId); return createJsExecutionByProjectWidget(projectWidgetOptional.orElse(new ProjectWidget())); } /** * Create a Js execution by a project widget. * * @param projectWidget The project widget * @return The related Js execution */ private JsExecutionDto createJsExecutionByProjectWidget(final ProjectWidget projectWidget) { String properties = getProjectWidgetConfigurationsWithGlobalOne(projectWidget, projectWidget.getWidget().getCategory().getConfigurations()); String script = projectWidget.getWidget().getBackendJs(); String previousData = projectWidget.getData(); Long projectId = projectWidget.getProjectGrid().getProject().getId(); Long technicalId = projectWidget.getId(); Long delay = projectWidget.getWidget().getDelay(); Long timeout = projectWidget.getWidget().getTimeout();
/* * * * Copyright 2012-2021 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 * * * * 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.michelin.suricate.services.js.services; /** * Js execution service. */ @Slf4j @Service public class JsExecutionService { @Lazy @Autowired private ProjectWidgetService projectWidgetService; /** * Get the list of related Js execution for each widget of a project. * * @param project The project * @return The list of related Js executions */ @Transactional public List<JsExecutionDto> getJsExecutionsByProject(final Project project) { return project.getGrids() .stream() .map(ProjectGrid::getWidgets) .flatMap(Collection::stream) .map(this::createJsExecutionByProjectWidget) .toList(); } /** * Create a js execution by a project widget id. * * @param projectWidgetId The project widget id * @return The related Js execution */ public JsExecutionDto getJsExecutionByProjectWidgetId(final Long projectWidgetId) { Optional<ProjectWidget> projectWidgetOptional = projectWidgetService.getOne(projectWidgetId); return createJsExecutionByProjectWidget(projectWidgetOptional.orElse(new ProjectWidget())); } /** * Create a Js execution by a project widget. * * @param projectWidget The project widget * @return The related Js execution */ private JsExecutionDto createJsExecutionByProjectWidget(final ProjectWidget projectWidget) { String properties = getProjectWidgetConfigurationsWithGlobalOne(projectWidget, projectWidget.getWidget().getCategory().getConfigurations()); String script = projectWidget.getWidget().getBackendJs(); String previousData = projectWidget.getData(); Long projectId = projectWidget.getProjectGrid().getProject().getId(); Long technicalId = projectWidget.getId(); Long delay = projectWidget.getWidget().getDelay(); Long timeout = projectWidget.getWidget().getTimeout();
WidgetStateEnum state = projectWidget.getState();
5
2023-12-11 11:28:37+00:00
8k
NaerQAQ/js4bukkit
src/main/java/org/js4bukkit/Js4Bukkit.java
[ { "identifier": "AnnotatedClassProcessor", "path": "src/main/java/org/js4bukkit/annotations/processors/AnnotatedClassProcessor.java", "snippet": "@UtilityClass\npublic class AnnotatedClassProcessor {\n /**\n * 获取带有指定注解的类集合。\n *\n * @param annotation 要查找的注解类的 Class 对象\n * @return 包含所有带...
import lombok.Getter; import lombok.Setter; import lombok.SneakyThrows; import org.apache.commons.lang3.StringUtils; import org.bukkit.plugin.java.JavaPlugin; import org.js4bukkit.annotations.processors.AnnotatedClassProcessor; import org.js4bukkit.io.config.ConfigManager; import org.js4bukkit.script.ScriptHandler; import org.js4bukkit.script.thirdparty.MavenDependencyLoader; import org.js4bukkit.script.thirdparty.ThirdPartyJarLoader; import org.js4bukkit.utils.common.text.QuickUtils; import org.js4bukkit.utils.common.text.enums.ConsoleMessageTypeEnum; import java.util.Arrays;
5,157
package org.js4bukkit; /** * 该类继承 {@link JavaPlugin},插件主类。 * * @author NaerQAQ / 2000000 * @version 1.0 * @since 2023/10/7 */ public class Js4Bukkit extends JavaPlugin { /** * 实例。 */ @Getter @Setter private static Js4Bukkit instance; /** * 服务器版本。 */ @Getter @Setter private static Double serverVersion; /** * 插件配置文件夹路径。 */ @Getter @Setter private static String dataFolderAbsolutePath; @Getter @Setter private static String nmsVersion; /** * 插件开启。 * * @author 2000000 */ @Override @SneakyThrows @SuppressWarnings("ResultOfMethodCallIgnored") public void onEnable() { setInstance(this); setDataFolderAbsolutePath(getDataFolder().getAbsolutePath()); String serverPackage = getServer().getClass().getPackage().getName(); setNmsVersion( serverPackage.replace(".", ",").split(",")[3] ); String[] arrayVersion = StringUtils.substringsBetween( serverPackage, ".v", "_R" ); String stringVersion = Arrays.toString(arrayVersion) .replace("_", "0") .replace("[", "") .replace("]", ""); setServerVersion( Double.parseDouble(stringVersion) ); // 配置文件与注解处理
package org.js4bukkit; /** * 该类继承 {@link JavaPlugin},插件主类。 * * @author NaerQAQ / 2000000 * @version 1.0 * @since 2023/10/7 */ public class Js4Bukkit extends JavaPlugin { /** * 实例。 */ @Getter @Setter private static Js4Bukkit instance; /** * 服务器版本。 */ @Getter @Setter private static Double serverVersion; /** * 插件配置文件夹路径。 */ @Getter @Setter private static String dataFolderAbsolutePath; @Getter @Setter private static String nmsVersion; /** * 插件开启。 * * @author 2000000 */ @Override @SneakyThrows @SuppressWarnings("ResultOfMethodCallIgnored") public void onEnable() { setInstance(this); setDataFolderAbsolutePath(getDataFolder().getAbsolutePath()); String serverPackage = getServer().getClass().getPackage().getName(); setNmsVersion( serverPackage.replace(".", ",").split(",")[3] ); String[] arrayVersion = StringUtils.substringsBetween( serverPackage, ".v", "_R" ); String stringVersion = Arrays.toString(arrayVersion) .replace("_", "0") .replace("[", "") .replace("]", ""); setServerVersion( Double.parseDouble(stringVersion) ); // 配置文件与注解处理
ConfigManager.getConfig();
1
2023-12-14 13:50:24+00:00
8k
keyboardcat1/Erosio
src/test/java/Demo.java
[ { "identifier": "Eroder", "path": "src/main/java/com/github/keyboardcat1/erosio/Eroder.java", "snippet": "public class Eroder {\n\n /**\n * Computes an eroded heightmap\n *\n * @param settings The parameters of the erosion algorithm\n * @param eroderGeometry The Voronoi tessell...
import com.github.keyboardcat1.erosio.Eroder; import com.github.keyboardcat1.erosio.EroderGeometry; import com.github.keyboardcat1.erosio.EroderResults; import com.github.keyboardcat1.erosio.EroderSettings; import com.github.keyboardcat1.erosio.geometries.EroderGeometryNatural; import com.github.keyboardcat1.erosio.interpolation.Interpolator; import com.github.keyboardcat1.erosio.interpolation.InterpolatorIDW; import org.kynosarges.tektosyne.geometry.RectI; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException;
6,139
public class Demo { public static void main(String[] args) throws IOException { RectI bounds = new RectI(-256, -256, 256, 256); EroderSettings settings = new EroderSettings( p -> 1.0, p -> 0.0, 2.0, 0.5, (p,h) -> 30.0, 1, 10, 1E-2 ); EroderGeometry eroderGeometry = new EroderGeometryNatural(bounds.toRectD(), 2, 2); EroderResults results = Eroder.erode(settings, eroderGeometry);
public class Demo { public static void main(String[] args) throws IOException { RectI bounds = new RectI(-256, -256, 256, 256); EroderSettings settings = new EroderSettings( p -> 1.0, p -> 0.0, 2.0, 0.5, (p,h) -> 30.0, 1, 10, 1E-2 ); EroderGeometry eroderGeometry = new EroderGeometryNatural(bounds.toRectD(), 2, 2); EroderResults results = Eroder.erode(settings, eroderGeometry);
Interpolator interpolator = new InterpolatorIDW(results, 2, 5);
4
2023-12-07 16:29:18+00:00
8k
litongjava/ai-server
paddle-ocr/paddle-ocr-service/src/main/java/com/litongjava/ai/djl/paddle/ocr/v4/OcrV4RecExample.java
[ { "identifier": "ImageUtils", "path": "paddle-ocr/paddle-ocr-service/src/main/java/com/litongjava/ai/djl/paddle/ocr/v4/common/ImageUtils.java", "snippet": "public class ImageUtils {\n\n /**\n * 保存BufferedImage图片\n *\n * @param img\n * @param name\n * @param path\n */\n public static void s...
import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.opencv.core.Mat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.litongjava.ai.djl.paddle.ocr.v4.common.ImageUtils; import com.litongjava.ai.djl.paddle.ocr.v4.common.RotatedBox; import com.litongjava.ai.djl.paddle.ocr.v4.common.RotatedBoxCompX; import com.litongjava.ai.djl.paddle.ocr.v4.detection.OcrV4Detection; import com.litongjava.ai.djl.paddle.ocr.v4.opencv.OpenCVUtils; import com.litongjava.ai.djl.paddle.ocr.v4.recognition.OcrV4Recognition; import ai.djl.ModelException; import ai.djl.inference.Predictor; import ai.djl.modality.cv.Image; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.opencv.OpenCVImageFactory; import ai.djl.repository.zoo.ModelZoo; import ai.djl.repository.zoo.ZooModel; import ai.djl.translate.TranslateException;
6,423
package com.litongjava.ai.djl.paddle.ocr.v4; /** * OCR V4模型 文字识别. 支持文本有旋转角度 * OCR V4 model for text recognition. Supports text with rotation angles. */ public final class OcrV4RecExample { private static final Logger logger = LoggerFactory.getLogger(OcrV4RecExample.class); private OcrV4RecExample() { } public static void main(String[] args) throws IOException, ModelException, TranslateException { // IDEA Path imageFile = Paths.get("E:\\code\\python\\project-litongjava\\cyg-v2\\img.png"); Image image = OpenCVImageFactory.getInstance().fromFile(imageFile); OcrV4Detection detection = new OcrV4Detection(); OcrV4Recognition recognition = new OcrV4Recognition(); try (ZooModel detectionModel = ModelZoo.loadModel(detection.chDetCriteria()); Predictor<Image, NDList> detector = detectionModel.newPredictor(); ZooModel recognitionModel = ModelZoo.loadModel(recognition.chRecCriteria()); Predictor<Image, String> recognizer = recognitionModel.newPredictor(); NDManager manager = NDManager.newBaseManager()) { long timeInferStart = System.currentTimeMillis(); List<RotatedBox> detections = recognition.predict(manager, image, detector, recognizer); // for (int i = 0; i < 1000; i++) { // detections = recognition.predict(image, detector, recognizer); // for (RotatedBox result : detections) { // System.out.println(result.getText()); // } // System.out.println("index : " + i); // } long timeInferEnd = System.currentTimeMillis(); System.out.println("time: " + (timeInferEnd - timeInferStart)); // 对检测结果根据坐标位置,根据从上到下,从做到右,重新排序,下面算法对图片倾斜旋转角度较小的情形适用 // 如果图片旋转角度较大,则需要自行改进算法,需要根据斜率校正计算位置。 // Reorder the detection results based on the coordinate positions, from top to bottom, from left to right. The algorithm below is suitable for situations where the image is slightly tilted or rotated. // If the image rotation angle is large, the algorithm needs to be improved, and the position needs to be calculated based on the slope correction. List<RotatedBox> initList = new ArrayList<>(); if (detections != null) { for (RotatedBox result : detections) { // put low Y value at the head of the queue. initList.add(result); } } Collections.sort(initList); List<ArrayList<RotatedBoxCompX>> lines = new ArrayList<>(); List<RotatedBoxCompX> line = new ArrayList<>(); if (initList.size() > 0) { RotatedBoxCompX firstBox = new RotatedBoxCompX(initList.get(0).getBox(), initList.get(0).getText()); line.add(firstBox); lines.add((ArrayList) line); for (int i = 1; i < initList.size(); i++) { RotatedBoxCompX tmpBox = new RotatedBoxCompX(initList.get(i).getBox(), initList.get(i).getText()); float y1 = firstBox.getBox().toFloatArray()[1]; float y2 = tmpBox.getBox().toFloatArray()[1]; float dis = Math.abs(y2 - y1); if (dis < 20) { // 认为是同 1 行 - Considered to be in the same line line.add(tmpBox); } else { // 换行 - Line break firstBox = tmpBox; Collections.sort(line); line = new ArrayList<>(); line.add(firstBox); lines.add((ArrayList) line); } } } String fullText = ""; for (int i = 0; i < lines.size(); i++) { for (int j = 0; j < lines.get(i).size(); j++) { String text = lines.get(i).get(j).getText(); if (text.trim().equals("")) continue; fullText += text + " "; } fullText += '\n'; } System.out.println(fullText); // 转 BufferedImage 解决 Imgproc.putText 中文乱码问题 Mat wrappedImage = (Mat) image.getWrappedImage(); BufferedImage bufferedImage = OpenCVUtils.mat2Image(wrappedImage); for (RotatedBox result : detections) {
package com.litongjava.ai.djl.paddle.ocr.v4; /** * OCR V4模型 文字识别. 支持文本有旋转角度 * OCR V4 model for text recognition. Supports text with rotation angles. */ public final class OcrV4RecExample { private static final Logger logger = LoggerFactory.getLogger(OcrV4RecExample.class); private OcrV4RecExample() { } public static void main(String[] args) throws IOException, ModelException, TranslateException { // IDEA Path imageFile = Paths.get("E:\\code\\python\\project-litongjava\\cyg-v2\\img.png"); Image image = OpenCVImageFactory.getInstance().fromFile(imageFile); OcrV4Detection detection = new OcrV4Detection(); OcrV4Recognition recognition = new OcrV4Recognition(); try (ZooModel detectionModel = ModelZoo.loadModel(detection.chDetCriteria()); Predictor<Image, NDList> detector = detectionModel.newPredictor(); ZooModel recognitionModel = ModelZoo.loadModel(recognition.chRecCriteria()); Predictor<Image, String> recognizer = recognitionModel.newPredictor(); NDManager manager = NDManager.newBaseManager()) { long timeInferStart = System.currentTimeMillis(); List<RotatedBox> detections = recognition.predict(manager, image, detector, recognizer); // for (int i = 0; i < 1000; i++) { // detections = recognition.predict(image, detector, recognizer); // for (RotatedBox result : detections) { // System.out.println(result.getText()); // } // System.out.println("index : " + i); // } long timeInferEnd = System.currentTimeMillis(); System.out.println("time: " + (timeInferEnd - timeInferStart)); // 对检测结果根据坐标位置,根据从上到下,从做到右,重新排序,下面算法对图片倾斜旋转角度较小的情形适用 // 如果图片旋转角度较大,则需要自行改进算法,需要根据斜率校正计算位置。 // Reorder the detection results based on the coordinate positions, from top to bottom, from left to right. The algorithm below is suitable for situations where the image is slightly tilted or rotated. // If the image rotation angle is large, the algorithm needs to be improved, and the position needs to be calculated based on the slope correction. List<RotatedBox> initList = new ArrayList<>(); if (detections != null) { for (RotatedBox result : detections) { // put low Y value at the head of the queue. initList.add(result); } } Collections.sort(initList); List<ArrayList<RotatedBoxCompX>> lines = new ArrayList<>(); List<RotatedBoxCompX> line = new ArrayList<>(); if (initList.size() > 0) { RotatedBoxCompX firstBox = new RotatedBoxCompX(initList.get(0).getBox(), initList.get(0).getText()); line.add(firstBox); lines.add((ArrayList) line); for (int i = 1; i < initList.size(); i++) { RotatedBoxCompX tmpBox = new RotatedBoxCompX(initList.get(i).getBox(), initList.get(i).getText()); float y1 = firstBox.getBox().toFloatArray()[1]; float y2 = tmpBox.getBox().toFloatArray()[1]; float dis = Math.abs(y2 - y1); if (dis < 20) { // 认为是同 1 行 - Considered to be in the same line line.add(tmpBox); } else { // 换行 - Line break firstBox = tmpBox; Collections.sort(line); line = new ArrayList<>(); line.add(firstBox); lines.add((ArrayList) line); } } } String fullText = ""; for (int i = 0; i < lines.size(); i++) { for (int j = 0; j < lines.get(i).size(); j++) { String text = lines.get(i).get(j).getText(); if (text.trim().equals("")) continue; fullText += text + " "; } fullText += '\n'; } System.out.println(fullText); // 转 BufferedImage 解决 Imgproc.putText 中文乱码问题 Mat wrappedImage = (Mat) image.getWrappedImage(); BufferedImage bufferedImage = OpenCVUtils.mat2Image(wrappedImage); for (RotatedBox result : detections) {
ImageUtils.drawImageRectWithText(bufferedImage, result.getBox(), result.getText());
0
2023-12-13 15:12:36+00:00
8k
i-moonlight/Beluga
server/src/main/java/com/amnesica/belugaproject/services/aircraft/FeederService.java
[ { "identifier": "Configuration", "path": "server/src/main/java/com/amnesica/belugaproject/config/Configuration.java", "snippet": "@Data\n@Slf4j\n@Validated\n@ConstructorBinding\n@org.springframework.context.annotation.Configuration\npublic class Configuration {\n\n @Autowired\n private Environment...
import com.amnesica.belugaproject.config.Configuration; import com.amnesica.belugaproject.config.Feeder; import com.amnesica.belugaproject.entities.aircraft.Aircraft; import com.amnesica.belugaproject.entities.aircraft.AircraftSuperclass; import com.amnesica.belugaproject.entities.aircraft.OpenskyAircraft; import com.amnesica.belugaproject.services.data.MapCatToShapeDataService; import com.amnesica.belugaproject.services.data.MapTypeToShapeDataService; import com.amnesica.belugaproject.services.data.ShapeDataService; import com.amnesica.belugaproject.services.helper.Request; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import java.util.*;
7,178
package com.amnesica.belugaproject.services.aircraft; @Slf4j @Service public class FeederService { @Autowired private LocalFeederService localFeederService; @Autowired private OpenskyService openskyService; @Autowired private SpacecraftService spacecraftService; @Autowired
package com.amnesica.belugaproject.services.aircraft; @Slf4j @Service public class FeederService { @Autowired private LocalFeederService localFeederService; @Autowired private OpenskyService openskyService; @Autowired private SpacecraftService spacecraftService; @Autowired
private MapCatToShapeDataService mapCatToShapeDataService;
5
2023-12-11 11:37:46+00:00
8k
fiber-net-gateway/fiber-net-gateway
fiber-gateway-server/src/main/java/io/fiber/net/server/HttpExchangeImpl.java
[ { "identifier": "FiberException", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/FiberException.java", "snippet": "public class FiberException extends Exception {\n private int code;\n private final String errorName;\n\n public FiberException(String message, int code, String er...
import io.fiber.net.common.FiberException; import io.fiber.net.common.HttpExchange; import io.fiber.net.common.HttpMethod; import io.fiber.net.common.async.Disposable; import io.fiber.net.common.async.Maybe; import io.fiber.net.common.async.Observable; import io.fiber.net.common.async.Scheduler; import io.fiber.net.common.async.internal.SerializeJsonObservable; import io.fiber.net.common.utils.BodyBufSubject; import io.fiber.net.common.utils.Headers; import io.fiber.net.common.utils.NoopBufObserver; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.handler.codec.http.*; import io.netty.util.AsciiString; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.util.Collection; import java.util.List;
4,731
package io.fiber.net.server; class HttpExchangeImpl extends HttpExchange { private static final InternalLogger logger = InternalLoggerFactory.getInstance(HttpExchangeImpl.class); private static final AsciiString APPLICATION_JSON_UTF8 = AsciiString.cached("application/json; charset=utf-8"); private final DefaultHttpHeaders headers = new DefaultHttpHeaders(); private final Channel ch; private final HttpRequest request; private final HttpMethod method; private final String uri; private boolean ioError; private boolean receiveCompleted; private boolean responseWrote; private final String path; private final String query; private final BodyBufSubject reqBufSubject;
package io.fiber.net.server; class HttpExchangeImpl extends HttpExchange { private static final InternalLogger logger = InternalLoggerFactory.getInstance(HttpExchangeImpl.class); private static final AsciiString APPLICATION_JSON_UTF8 = AsciiString.cached("application/json; charset=utf-8"); private final DefaultHttpHeaders headers = new DefaultHttpHeaders(); private final Channel ch; private final HttpRequest request; private final HttpMethod method; private final String uri; private boolean ioError; private boolean receiveCompleted; private boolean responseWrote; private final String path; private final String query; private final BodyBufSubject reqBufSubject;
public HttpExchangeImpl(Channel ch, HttpRequest request, Scheduler scheduler) {
6
2023-12-08 15:18:05+00:00
8k
lyswhut/react-native-local-media-metadata
android/src/main/java/org/jaudiotagger/tag/id3/framebody/AbstractFrameBodyPairs.java
[ { "identifier": "InvalidTagException", "path": "android/src/main/java/org/jaudiotagger/tag/InvalidTagException.java", "snippet": "public class InvalidTagException extends TagException\n{\n /**\n * Creates a new InvalidTagException datatype.\n */\n public InvalidTagException()\n {\n }...
import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.StringTokenizer; import org.jaudiotagger.tag.InvalidTagException; import org.jaudiotagger.tag.datatype.DataTypes; import org.jaudiotagger.tag.datatype.NumberHashMap; import org.jaudiotagger.tag.datatype.Pair; import org.jaudiotagger.tag.datatype.PairedTextEncodedStringNullTerminated; import org.jaudiotagger.tag.id3.valuepair.TextEncoding;
7,200
/** * @author : Paul Taylor * @author : Eric Farng * * Version @version:$Id$ * * MusicTag Copyright (C)2003,2004 * * 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, * you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Description: * People List * */ package org.jaudiotagger.tag.id3.framebody; /** * Used by frames that take a pair of values such as TIPL, IPLS and TMCL * */ public abstract class AbstractFrameBodyPairs extends AbstractID3v2FrameBody implements ID3v24FrameBody { /** * Creates a new AbstractFrameBodyPairs datatype. */ public AbstractFrameBodyPairs() { setObjectValue(DataTypes.OBJ_TEXT_ENCODING, TextEncoding.ISO_8859_1); } /** * Creates a new AbstractFrameBodyPairs data type. * * @param textEncoding * @param text */ public AbstractFrameBodyPairs(byte textEncoding, String text) { setObjectValue(DataTypes.OBJ_TEXT_ENCODING, textEncoding); setText(text); } /** * Creates a new AbstractFrameBodyPairs data type. * * @param byteBuffer * @param frameSize * @throws org.jaudiotagger.tag.InvalidTagException */ public AbstractFrameBodyPairs(ByteBuffer byteBuffer, int frameSize) throws InvalidTagException { super(byteBuffer, frameSize); } /** * The ID3v2 frame identifier * * @return the ID3v2 frame identifier for this frame type */ public abstract String getIdentifier(); /** * Set the text, decoded as pairs of involvee - involvement * * @param text */ public void setText(String text) { PairedTextEncodedStringNullTerminated.ValuePairs value = new PairedTextEncodedStringNullTerminated.ValuePairs(); StringTokenizer stz = new StringTokenizer(text, "\0"); while (stz.hasMoreTokens()) { String key =stz.nextToken(); if(stz.hasMoreTokens()) { value.add(key, stz.nextToken()); } } setObjectValue(DataTypes.OBJ_TEXT, value); } /** * Parse text as a null separated pairing of function and name * * @param text */ public void addPair(String text) { StringTokenizer stz = new StringTokenizer(text, "\0"); if (stz.countTokens()==2) { addPair(stz.nextToken(),stz.nextToken()); } else { addPair("", text); } } /** * Add pair * * @param function * @param name */ public void addPair(String function,String name) { PairedTextEncodedStringNullTerminated.ValuePairs value = ((PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT)).getValue(); value.add(function, name); } /** * Remove all Pairs */ public void resetPairs() { PairedTextEncodedStringNullTerminated.ValuePairs value = ((PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT)).getValue(); value.getMapping().clear(); } /** * Because have a text encoding we need to check the data values do not contain characters that cannot be encoded in * current encoding before we write data. If they do change the encoding. */ public void write(ByteArrayOutputStream tagBuffer) { if (!((PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT)).canBeEncoded()) { this.setTextEncoding(TextEncoding.UTF_16); } super.write(tagBuffer); } /** * Consists of a text encoding , and then a series of null terminated Strings, there should be an even number * of Strings as they are paired as involvement/involvee */ protected void setupObjectList() {
/** * @author : Paul Taylor * @author : Eric Farng * * Version @version:$Id$ * * MusicTag Copyright (C)2003,2004 * * 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, * you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Description: * People List * */ package org.jaudiotagger.tag.id3.framebody; /** * Used by frames that take a pair of values such as TIPL, IPLS and TMCL * */ public abstract class AbstractFrameBodyPairs extends AbstractID3v2FrameBody implements ID3v24FrameBody { /** * Creates a new AbstractFrameBodyPairs datatype. */ public AbstractFrameBodyPairs() { setObjectValue(DataTypes.OBJ_TEXT_ENCODING, TextEncoding.ISO_8859_1); } /** * Creates a new AbstractFrameBodyPairs data type. * * @param textEncoding * @param text */ public AbstractFrameBodyPairs(byte textEncoding, String text) { setObjectValue(DataTypes.OBJ_TEXT_ENCODING, textEncoding); setText(text); } /** * Creates a new AbstractFrameBodyPairs data type. * * @param byteBuffer * @param frameSize * @throws org.jaudiotagger.tag.InvalidTagException */ public AbstractFrameBodyPairs(ByteBuffer byteBuffer, int frameSize) throws InvalidTagException { super(byteBuffer, frameSize); } /** * The ID3v2 frame identifier * * @return the ID3v2 frame identifier for this frame type */ public abstract String getIdentifier(); /** * Set the text, decoded as pairs of involvee - involvement * * @param text */ public void setText(String text) { PairedTextEncodedStringNullTerminated.ValuePairs value = new PairedTextEncodedStringNullTerminated.ValuePairs(); StringTokenizer stz = new StringTokenizer(text, "\0"); while (stz.hasMoreTokens()) { String key =stz.nextToken(); if(stz.hasMoreTokens()) { value.add(key, stz.nextToken()); } } setObjectValue(DataTypes.OBJ_TEXT, value); } /** * Parse text as a null separated pairing of function and name * * @param text */ public void addPair(String text) { StringTokenizer stz = new StringTokenizer(text, "\0"); if (stz.countTokens()==2) { addPair(stz.nextToken(),stz.nextToken()); } else { addPair("", text); } } /** * Add pair * * @param function * @param name */ public void addPair(String function,String name) { PairedTextEncodedStringNullTerminated.ValuePairs value = ((PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT)).getValue(); value.add(function, name); } /** * Remove all Pairs */ public void resetPairs() { PairedTextEncodedStringNullTerminated.ValuePairs value = ((PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT)).getValue(); value.getMapping().clear(); } /** * Because have a text encoding we need to check the data values do not contain characters that cannot be encoded in * current encoding before we write data. If they do change the encoding. */ public void write(ByteArrayOutputStream tagBuffer) { if (!((PairedTextEncodedStringNullTerminated) getObject(DataTypes.OBJ_TEXT)).canBeEncoded()) { this.setTextEncoding(TextEncoding.UTF_16); } super.write(tagBuffer); } /** * Consists of a text encoding , and then a series of null terminated Strings, there should be an even number * of Strings as they are paired as involvement/involvee */ protected void setupObjectList() {
objectList.add(new NumberHashMap(DataTypes.OBJ_TEXT_ENCODING, this, TextEncoding.TEXT_ENCODING_FIELD_SIZE));
2
2023-12-11 05:58:19+00:00
8k
Ender-Cube/Endercube
Hub/src/main/java/net/endercube/Hub/HubMinigame.java
[ { "identifier": "EndercubeMinigame", "path": "Common/src/main/java/net/endercube/Common/EndercubeMinigame.java", "snippet": "public abstract class EndercubeMinigame {\n\n public static final Logger logger;\n private HoconConfigurationLoader configLoader;\n public CommentedConfigurationNode conf...
import net.endercube.Common.EndercubeMinigame; import net.endercube.Common.EndercubeServer; import net.endercube.Common.NPC; import net.endercube.Common.dimensions.FullbrightDimension; import net.endercube.Common.players.EndercubePlayer; import net.endercube.Hub.listeners.MinigamePlayerJoin; import net.endercube.Hub.listeners.PlayerMove; import net.endercube.Parkour.inventories.ParkourMapInventory; import net.hollowcube.polar.PolarLoader; import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.Command; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.PlayerSkin; import net.minestom.server.instance.InstanceContainer; import net.minestom.server.tag.Tag; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList;
6,705
package net.endercube.Hub; /** * This is the entrypoint for the Hub minigame */ public class HubMinigame extends EndercubeMinigame { public static HubMinigame hubMinigame; public HubMinigame(EndercubeServer endercubeServer) { super(endercubeServer); hubMinigame = this; // Create NPC(s) new NPC("Parkour", PlayerSkin.fromUsername("Jeb_"), getInstances().getFirst(), new Pos(0.5, 101, -5.5),
package net.endercube.Hub; /** * This is the entrypoint for the Hub minigame */ public class HubMinigame extends EndercubeMinigame { public static HubMinigame hubMinigame; public HubMinigame(EndercubeServer endercubeServer) { super(endercubeServer); hubMinigame = this; // Create NPC(s) new NPC("Parkour", PlayerSkin.fromUsername("Jeb_"), getInstances().getFirst(), new Pos(0.5, 101, -5.5),
player -> player.openInventory(ParkourMapInventory.getInventory(false)));
7
2023-12-10 12:08:18+00:00
8k
lukebemishprojects/Tempest
forge/src/main/java/dev/lukebemish/tempest/impl/forge/mixin/client/RebuildTaskMixin.java
[ { "identifier": "Services", "path": "common/src/main/java/dev/lukebemish/tempest/impl/Services.java", "snippet": "public final class Services {\n private Services() {}\n\n public static final Platform PLATFORM = load(Platform.class);\n\n private static final List<Snower> SNOWERS;\n private s...
import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.llamalad7.mixinextras.sugar.Share; import com.llamalad7.mixinextras.sugar.ref.LocalRef; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import dev.lukebemish.tempest.impl.Services; import dev.lukebemish.tempest.impl.client.LevelChunkHolder; import dev.lukebemish.tempest.impl.client.OverlaySpriteListener; import dev.lukebemish.tempest.impl.client.QuadHelper; import dev.lukebemish.tempest.impl.mixin.client.DispatchRenderChunkAccessor; import net.minecraft.client.renderer.ChunkBufferBuilderPack; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.block.BlockRenderDispatcher; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.chunk.ChunkRenderDispatcher; import net.minecraft.client.renderer.chunk.RenderChunkRegion; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.util.RandomSource; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.client.model.data.ModelData; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyVariable; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.List; import java.util.Set; import java.util.function.Function;
3,964
package dev.lukebemish.tempest.impl.forge.mixin.client; @Mixin(targets = "net.minecraft.client.renderer.chunk.ChunkRenderDispatcher$RenderChunk$RebuildTask") public class RebuildTaskMixin { @Shadow @Nullable protected RenderChunkRegion region; @Unique private ChunkRenderDispatcher.RenderChunk renderChunk; @Inject( method = "<init>(Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk;DLnet/minecraft/client/renderer/chunk/RenderChunkRegion;Z)V", at = @At("RETURN") ) private void tempest$init(ChunkRenderDispatcher.RenderChunk renderChunk, double distAtCreation, @Nullable RenderChunkRegion region, boolean isHighPriority, CallbackInfo ci) { this.renderChunk = renderChunk; } @Inject( method = "<init>(Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk;Lnet/minecraft/world/level/ChunkPos;DLnet/minecraft/client/renderer/chunk/RenderChunkRegion;Z)V", at = @At("RETURN") ) private void tempest$init(ChunkRenderDispatcher.RenderChunk renderChunk, @Nullable ChunkPos pos, double d, @Nullable RenderChunkRegion arg, boolean bl, CallbackInfo ci) { this.renderChunk = renderChunk; } @ModifyVariable( method = "compile(FFFLnet/minecraft/client/renderer/ChunkBufferBuilderPack;)Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask$CompileResults;", at = @At("STORE") ) private Set<RenderType> tempest$captureSet(Set<RenderType> set, @Share("set") LocalRef<Set<RenderType>> setRef) { setRef.set(set); return set; } @Inject( method = "compile(FFFLnet/minecraft/client/renderer/ChunkBufferBuilderPack;)Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask$CompileResults;", at = @At("HEAD") ) private void tempest$clearSet(float x, float y, float z, ChunkBufferBuilderPack buffers, CallbackInfoReturnable<?> ci, @Share("region") LocalRef<RenderChunkRegion> regionRef) { regionRef.set(region); } @WrapOperation( method = "compile(FFFLnet/minecraft/client/renderer/ChunkBufferBuilderPack;)Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask$CompileResults;", at = @At( value = "INVOKE", target = "Lnet/minecraft/client/renderer/block/BlockRenderDispatcher;renderBatched(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/BlockAndTintGetter;Lcom/mojang/blaze3d/vertex/PoseStack;Lcom/mojang/blaze3d/vertex/VertexConsumer;ZLnet/minecraft/util/RandomSource;Lnet/minecraftforge/client/model/data/ModelData;Lnet/minecraft/client/renderer/RenderType;)V" ) ) private void tempest$addBlackIceQuads( BlockRenderDispatcher blockRenderDispatcher, BlockState state, BlockPos pos, BlockAndTintGetter blockAndTintGetter, PoseStack poseStack, VertexConsumer vertexConsumer, boolean checkSides, RandomSource random, ModelData modelData, RenderType renderType, Operation<Void> operation, float x, float y, float z, ChunkBufferBuilderPack buffers, @Share("set") LocalRef<Set<RenderType>> setRef, @Share("region") LocalRef<RenderChunkRegion> regionRef ) { operation.call(blockRenderDispatcher, state, pos, blockAndTintGetter, poseStack, vertexConsumer, checkSides, random, modelData, renderType); var re = regionRef.get(); if (re != null) { TextureAtlasSprite sprite; var level = ((LevelChunkHolder) re).tempest$level(); var chunk = LevelChunkHolder.tempest$chunkAt(re, pos); var data = Services.PLATFORM.getChunkData(chunk); var blackIce = data.query(pos).blackIce(); if (blackIce < 1) { return; } else if (blackIce < 6) { sprite = OverlaySpriteListener.getBlackIce1(); } else if (blackIce < 11) { sprite = OverlaySpriteListener.getBlackIce2(); } else { sprite = OverlaySpriteListener.getBlackIce3(); } boolean frozenUp = data.query(pos).frozenUp(); if (frozenUp) { sprite = OverlaySpriteListener.getBlackIce3(); } var bakedModel = blockRenderDispatcher.getBlockModel(state); BufferBuilder translucentBuilder = buffers.builder(RenderType.translucent()); if (setRef.get().add(RenderType.translucent())) {
package dev.lukebemish.tempest.impl.forge.mixin.client; @Mixin(targets = "net.minecraft.client.renderer.chunk.ChunkRenderDispatcher$RenderChunk$RebuildTask") public class RebuildTaskMixin { @Shadow @Nullable protected RenderChunkRegion region; @Unique private ChunkRenderDispatcher.RenderChunk renderChunk; @Inject( method = "<init>(Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk;DLnet/minecraft/client/renderer/chunk/RenderChunkRegion;Z)V", at = @At("RETURN") ) private void tempest$init(ChunkRenderDispatcher.RenderChunk renderChunk, double distAtCreation, @Nullable RenderChunkRegion region, boolean isHighPriority, CallbackInfo ci) { this.renderChunk = renderChunk; } @Inject( method = "<init>(Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk;Lnet/minecraft/world/level/ChunkPos;DLnet/minecraft/client/renderer/chunk/RenderChunkRegion;Z)V", at = @At("RETURN") ) private void tempest$init(ChunkRenderDispatcher.RenderChunk renderChunk, @Nullable ChunkPos pos, double d, @Nullable RenderChunkRegion arg, boolean bl, CallbackInfo ci) { this.renderChunk = renderChunk; } @ModifyVariable( method = "compile(FFFLnet/minecraft/client/renderer/ChunkBufferBuilderPack;)Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask$CompileResults;", at = @At("STORE") ) private Set<RenderType> tempest$captureSet(Set<RenderType> set, @Share("set") LocalRef<Set<RenderType>> setRef) { setRef.set(set); return set; } @Inject( method = "compile(FFFLnet/minecraft/client/renderer/ChunkBufferBuilderPack;)Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask$CompileResults;", at = @At("HEAD") ) private void tempest$clearSet(float x, float y, float z, ChunkBufferBuilderPack buffers, CallbackInfoReturnable<?> ci, @Share("region") LocalRef<RenderChunkRegion> regionRef) { regionRef.set(region); } @WrapOperation( method = "compile(FFFLnet/minecraft/client/renderer/ChunkBufferBuilderPack;)Lnet/minecraft/client/renderer/chunk/ChunkRenderDispatcher$RenderChunk$RebuildTask$CompileResults;", at = @At( value = "INVOKE", target = "Lnet/minecraft/client/renderer/block/BlockRenderDispatcher;renderBatched(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/BlockAndTintGetter;Lcom/mojang/blaze3d/vertex/PoseStack;Lcom/mojang/blaze3d/vertex/VertexConsumer;ZLnet/minecraft/util/RandomSource;Lnet/minecraftforge/client/model/data/ModelData;Lnet/minecraft/client/renderer/RenderType;)V" ) ) private void tempest$addBlackIceQuads( BlockRenderDispatcher blockRenderDispatcher, BlockState state, BlockPos pos, BlockAndTintGetter blockAndTintGetter, PoseStack poseStack, VertexConsumer vertexConsumer, boolean checkSides, RandomSource random, ModelData modelData, RenderType renderType, Operation<Void> operation, float x, float y, float z, ChunkBufferBuilderPack buffers, @Share("set") LocalRef<Set<RenderType>> setRef, @Share("region") LocalRef<RenderChunkRegion> regionRef ) { operation.call(blockRenderDispatcher, state, pos, blockAndTintGetter, poseStack, vertexConsumer, checkSides, random, modelData, renderType); var re = regionRef.get(); if (re != null) { TextureAtlasSprite sprite; var level = ((LevelChunkHolder) re).tempest$level(); var chunk = LevelChunkHolder.tempest$chunkAt(re, pos); var data = Services.PLATFORM.getChunkData(chunk); var blackIce = data.query(pos).blackIce(); if (blackIce < 1) { return; } else if (blackIce < 6) { sprite = OverlaySpriteListener.getBlackIce1(); } else if (blackIce < 11) { sprite = OverlaySpriteListener.getBlackIce2(); } else { sprite = OverlaySpriteListener.getBlackIce3(); } boolean frozenUp = data.query(pos).frozenUp(); if (frozenUp) { sprite = OverlaySpriteListener.getBlackIce3(); } var bakedModel = blockRenderDispatcher.getBlockModel(state); BufferBuilder translucentBuilder = buffers.builder(RenderType.translucent()); if (setRef.get().add(RenderType.translucent())) {
((DispatchRenderChunkAccessor) renderChunk).tempest$beginLayer(translucentBuilder);
4
2023-12-06 23:23:31+00:00
8k
dractical/InventoryPagesModified
src/main/java/org/aidan/inventorypages/InventoryPages.java
[ { "identifier": "InventoryStringDeSerializer", "path": "src/main/java/org/aidan/inventorypages/InventoryStringDeSerializer.java", "snippet": "public class InventoryStringDeSerializer {\n public static String toBase64(Inventory inventory) {\n return toBase64(inventory.getContents());\n }\n\n...
import org.aidan.inventorypages.InventoryStringDeSerializer; import org.aidan.inventorypages.MetricsLite; import org.aidan.inventorypages.MySQLConnector; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.*; import org.bukkit.inventory.*; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitScheduler; import java.io.File; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.*; import java.util.Map.Entry;
5,180
package org.aidan.inventorypages; public class InventoryPages extends JavaPlugin implements Listener { File crashedFile = new File(getDataFolder() + "/backups/crashed.yml"); FileConfiguration crashedData = YamlConfiguration.loadConfiguration(crashedFile); private HashMap<String, org.aidan.inventorypages.CustomInventory> playerInvs = new HashMap<String, org.aidan.inventorypages.CustomInventory>(); org.aidan.inventorypages.ColorConverter colorConv = new org.aidan.inventorypages.ColorConverter(this); private ItemStack nextItem, prevItem, noPageItem; private Integer prevPos, nextPos; private List<String> clearCommands; private String noPermission, clear, clearAll, itemsMerged, itemsDropped; private Boolean logSavesEnabled; private String logSavesMessage;
package org.aidan.inventorypages; public class InventoryPages extends JavaPlugin implements Listener { File crashedFile = new File(getDataFolder() + "/backups/crashed.yml"); FileConfiguration crashedData = YamlConfiguration.loadConfiguration(crashedFile); private HashMap<String, org.aidan.inventorypages.CustomInventory> playerInvs = new HashMap<String, org.aidan.inventorypages.CustomInventory>(); org.aidan.inventorypages.ColorConverter colorConv = new org.aidan.inventorypages.ColorConverter(this); private ItemStack nextItem, prevItem, noPageItem; private Integer prevPos, nextPos; private List<String> clearCommands; private String noPermission, clear, clearAll, itemsMerged, itemsDropped; private Boolean logSavesEnabled; private String logSavesMessage;
private MySQLConnector mySQLConnector;
2
2023-12-13 03:39:32+00:00
8k
xhtcode/xht-cloud-parent
xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/oauth2/service/impl/Oauth2RegisteredClientServiceImpl.java
[ { "identifier": "PageResponse", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/api/response/PageResponse.java", "snippet": "@Data\n@Schema(description = \"分页信息响应实体\")\npublic class PageResponse<T> extends Response {\n\n /**\n * 当前页\n */\n @...
import com.baomidou.mybatisplus.core.metadata.IPage; import com.xht.cloud.framework.core.api.response.PageResponse; import com.xht.cloud.framework.exception.business.BizException; import com.xht.cloud.framework.mybatis.tool.PageTool; import com.xht.cloud.system.module.oauth2.controller.request.Oauth2RegisteredClientAddRequest; import com.xht.cloud.system.module.oauth2.controller.request.Oauth2RegisteredClientQueryRequest; import com.xht.cloud.system.module.oauth2.controller.request.Oauth2RegisteredClientUpdateRequest; import com.xht.cloud.system.module.oauth2.controller.response.Oauth2RegisteredClientResponse; import com.xht.cloud.system.module.oauth2.convert.Oauth2RegisteredClientConvert; import com.xht.cloud.system.module.oauth2.dao.dataobject.Oauth2RegisteredClientDO; import com.xht.cloud.system.module.oauth2.dao.mapper.Oauth2RegisteredClientMapper; import com.xht.cloud.system.module.oauth2.dao.wrapper.Oauth2RegisteredClientWrapper; import com.xht.cloud.system.module.oauth2.service.IOauth2RegisteredClientService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Objects;
5,746
package com.xht.cloud.system.module.oauth2.service.impl; /** * 描述 :oauth2 客户端信息 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class Oauth2RegisteredClientServiceImpl implements IOauth2RegisteredClientService { private final Oauth2RegisteredClientMapper oauth2RegisteredClientMapper; private final Oauth2RegisteredClientConvert oauth2RegisteredClientConvert; /** * 创建 * * @param addRequest {@link Oauth2RegisteredClientAddRequest} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class)
package com.xht.cloud.system.module.oauth2.service.impl; /** * 描述 :oauth2 客户端信息 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class Oauth2RegisteredClientServiceImpl implements IOauth2RegisteredClientService { private final Oauth2RegisteredClientMapper oauth2RegisteredClientMapper; private final Oauth2RegisteredClientConvert oauth2RegisteredClientConvert; /** * 创建 * * @param addRequest {@link Oauth2RegisteredClientAddRequest} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class)
public String create(Oauth2RegisteredClientAddRequest addRequest) {
3
2023-12-12 08:16:30+00:00
8k
Utils4J/JavaUtils
src/test/java/KeyTest.java
[ { "identifier": "KeyTestClass", "path": "src/test/java/data/KeyTestClass.java", "snippet": "public class KeyTestClass {\n\t@Column(autoincrement = true, key = true)\n\tpublic int id;\n\n\t@Column\n\tpublic String text;\n\n\tpublic KeyTestClass( String text) {\n\t\tid = 0;\n\t\tthis.text = text;\n\t}\n\n...
import data.KeyTestClass; import de.mineking.javautils.database.DatabaseManager; import de.mineking.javautils.database.Table; import de.mineking.javautils.database.Where; import org.junit.jupiter.api.Test;
3,633
public class KeyTest { public final DatabaseManager manager; public final Table<KeyTestClass> table; public KeyTest() { manager = new DatabaseManager("jdbc:postgresql://localhost:5433/test", "postgres", "test123"); table = manager.getTable(KeyTestClass.class, KeyTestClass::new, "key_test").createTable(); } @Test public void create() { } @Test public void insert() { System.out.println(table.insert(new KeyTestClass("Test"))); } @Test public void update() {
public class KeyTest { public final DatabaseManager manager; public final Table<KeyTestClass> table; public KeyTest() { manager = new DatabaseManager("jdbc:postgresql://localhost:5433/test", "postgres", "test123"); table = manager.getTable(KeyTestClass.class, KeyTestClass::new, "key_test").createTable(); } @Test public void create() { } @Test public void insert() { System.out.println(table.insert(new KeyTestClass("Test"))); } @Test public void update() {
table.selectOne(Where.equals("id", 1)).ifPresent(o -> {
3
2023-12-13 14:05:17+00:00
8k
serendipitk/LunarCore
src/main/java/emu/lunarcore/command/commands/AvatarCommand.java
[ { "identifier": "CommandArgs", "path": "src/main/java/emu/lunarcore/command/CommandArgs.java", "snippet": "@Getter\npublic class CommandArgs {\n private String raw;\n private List<String> list;\n private Player sender;\n private Player target;\n \n private int targetUid;\n private i...
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import emu.lunarcore.command.Command; import emu.lunarcore.command.CommandArgs; import emu.lunarcore.command.CommandHandler; import emu.lunarcore.game.avatar.GameAvatar; import emu.lunarcore.server.packet.send.PacketPlayerSyncScNotify;
6,605
package emu.lunarcore.command.commands; @Command(label = "avatar", aliases = {"a"}, requireTarget = true, permission = "player.avatar", desc = "/avatar {cur (当前角色) | all (所有角色) | lineup (当然队伍角色)} lv(等级) p(突破等级) r(星魂数量) s(技能等级). 设置角色属性.") public class AvatarCommand implements CommandHandler { @Override public void execute(CommandArgs args) { // Temp avatar list List<GameAvatar> changeList = new ArrayList<>(); // Handle optional arguments switch (args.get(0).toLowerCase()) { case "all": args.getTarget().getAvatars().forEach(changeList::add); break; case "lineup": args.getTarget().getCurrentLineup().forEachAvatar(changeList::add); break; case "cur": default: changeList.add(args.getTarget().getCurrentLeaderAvatar()); break; } // Try to set properties of avatars Iterator<GameAvatar> it = changeList.iterator(); while (it.hasNext()) { GameAvatar avatar = it.next(); if (args.setProperties(avatar)) { // Save avatar avatar.save(); } else { // Remove from list if nothing was changed it.remove(); } } if (changeList.size() > 0) { // Send packet
package emu.lunarcore.command.commands; @Command(label = "avatar", aliases = {"a"}, requireTarget = true, permission = "player.avatar", desc = "/avatar {cur (当前角色) | all (所有角色) | lineup (当然队伍角色)} lv(等级) p(突破等级) r(星魂数量) s(技能等级). 设置角色属性.") public class AvatarCommand implements CommandHandler { @Override public void execute(CommandArgs args) { // Temp avatar list List<GameAvatar> changeList = new ArrayList<>(); // Handle optional arguments switch (args.get(0).toLowerCase()) { case "all": args.getTarget().getAvatars().forEach(changeList::add); break; case "lineup": args.getTarget().getCurrentLineup().forEachAvatar(changeList::add); break; case "cur": default: changeList.add(args.getTarget().getCurrentLeaderAvatar()); break; } // Try to set properties of avatars Iterator<GameAvatar> it = changeList.iterator(); while (it.hasNext()) { GameAvatar avatar = it.next(); if (args.setProperties(avatar)) { // Save avatar avatar.save(); } else { // Remove from list if nothing was changed it.remove(); } } if (changeList.size() > 0) { // Send packet
args.getTarget().sendPacket(new PacketPlayerSyncScNotify(changeList.toArray(GameAvatar[]::new)));
3
2023-12-08 14:13:04+00:00
8k
adabox-aio/dextreme-sdk
src/main/java/io/adabox/dextreme/dex/Muesliswap.java
[ { "identifier": "MuesliSwapApi", "path": "src/main/java/io/adabox/dextreme/dex/api/MuesliSwapApi.java", "snippet": "@Slf4j\n@Getter\npublic class MuesliSwapApi extends Api {\n\n private final String marketOrderAddress = \"addr1zyq0kyrml023kwjk8zr86d5gaxrt5w8lxnah8r6m6s4jp4g3r6dxnzml343sx8jweqn4vn3fz2...
import co.nstant.in.cbor.model.ByteString; import com.bloxbean.cardano.client.address.Address; import com.bloxbean.cardano.client.address.AddressProvider; import com.bloxbean.cardano.client.common.CardanoConstants; import com.bloxbean.cardano.client.plutus.spec.*; import com.bloxbean.cardano.client.plutus.spec.serializers.PlutusDataJsonConverter; import com.bloxbean.cardano.client.util.HexUtil; import com.fasterxml.jackson.databind.JsonNode; import io.adabox.dextreme.dex.api.MuesliSwapApi; import io.adabox.dextreme.dex.base.Dex; import io.adabox.dextreme.dex.base.DexType; import io.adabox.dextreme.model.SwapDatumRequest; import io.adabox.dextreme.model.UTxO; import io.adabox.dextreme.provider.ApiProvider; import io.adabox.dextreme.provider.base.BaseProvider; import io.adabox.dextreme.provider.base.ClientProvider; import io.adabox.dextreme.utils.BigIntegerUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.List;
4,153
package io.adabox.dextreme.dex; /** * Muesliswap DEX */ @Slf4j public class Muesliswap extends Dex { public static final String FACTORY_TOKEN = "de9b756719341e79785aa13c164e7fe68c189ed04d61c9876b2fe53f4d7565736c69537761705f414d4d"; public static final String LP_TOKEN_POLICY_ID = "af3d70acf4bd5b3abb319a7d75c89fb3e56eafcdd46b2e9b57a2557f"; public static final List<String> POOL_NFT_POLICY_IDs = List.of("909133088303c49f3a30f1cc8ed553a73857a29779f6c6561cd8093f", "7a8041a0693e6605d010d5185b034d55c79eaf7ef878aae3bdcdbf67"); public static final String ORDER_ADDRESS = "addr1zyq0kyrml023kwjk8zr86d5gaxrt5w8lxnah8r6m6s4jp4g3r6dxnzml343sx8jweqn4vn3fz2kj8kgu9czghx0jrsyqqktyhv"; public static final boolean ALLOW_PARTIAL_FILL = true; /** * {@link Muesliswap} * Default Constructor */ public Muesliswap() { this(new ApiProvider()); } /** * {@link Muesliswap} * @param provider provider */ public Muesliswap(BaseProvider provider) { super(DexType.Muesliswap, provider, new MuesliSwapApi()); } @Override public String getFactoryToken() { return FACTORY_TOKEN; } @Override public List<String> getPoolNFTPolicyIds() { return POOL_NFT_POLICY_IDs; } @Override public String getLPTokenPolicyId() { return LP_TOKEN_POLICY_ID; } @Override public String getMarketOrderAddress() { return ORDER_ADDRESS; } @Override public String getLimitOrderAddress() { return ORDER_ADDRESS; } @Override
package io.adabox.dextreme.dex; /** * Muesliswap DEX */ @Slf4j public class Muesliswap extends Dex { public static final String FACTORY_TOKEN = "de9b756719341e79785aa13c164e7fe68c189ed04d61c9876b2fe53f4d7565736c69537761705f414d4d"; public static final String LP_TOKEN_POLICY_ID = "af3d70acf4bd5b3abb319a7d75c89fb3e56eafcdd46b2e9b57a2557f"; public static final List<String> POOL_NFT_POLICY_IDs = List.of("909133088303c49f3a30f1cc8ed553a73857a29779f6c6561cd8093f", "7a8041a0693e6605d010d5185b034d55c79eaf7ef878aae3bdcdbf67"); public static final String ORDER_ADDRESS = "addr1zyq0kyrml023kwjk8zr86d5gaxrt5w8lxnah8r6m6s4jp4g3r6dxnzml343sx8jweqn4vn3fz2kj8kgu9czghx0jrsyqqktyhv"; public static final boolean ALLOW_PARTIAL_FILL = true; /** * {@link Muesliswap} * Default Constructor */ public Muesliswap() { this(new ApiProvider()); } /** * {@link Muesliswap} * @param provider provider */ public Muesliswap(BaseProvider provider) { super(DexType.Muesliswap, provider, new MuesliSwapApi()); } @Override public String getFactoryToken() { return FACTORY_TOKEN; } @Override public List<String> getPoolNFTPolicyIds() { return POOL_NFT_POLICY_IDs; } @Override public String getLPTokenPolicyId() { return LP_TOKEN_POLICY_ID; } @Override public String getMarketOrderAddress() { return ORDER_ADDRESS; } @Override public String getLimitOrderAddress() { return ORDER_ADDRESS; } @Override
public double getPoolFeePercent(UTxO utxo) {
4
2023-12-10 12:14:48+00:00
8k
zhaw-iwi/promise
src/main/java/ch/zhaw/statefulconversation/model/commons/actions/DynamicExtractionAction.java
[ { "identifier": "Action", "path": "src/main/java/ch/zhaw/statefulconversation/model/Action.java", "snippet": "@Entity\npublic abstract class Action extends Prompt {\n\n protected Action() {\n\n }\n\n private String storageKeyTo;\n\n public Action(String actionPromp) {\n super(actionPr...
import java.util.Map; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import ch.zhaw.statefulconversation.model.Action; import ch.zhaw.statefulconversation.model.Storage; import ch.zhaw.statefulconversation.model.Utterances; import ch.zhaw.statefulconversation.spi.LMOpenAI; import ch.zhaw.statefulconversation.utils.NamedParametersFormatter; import jakarta.persistence.Entity;
4,072
package ch.zhaw.statefulconversation.model.commons.actions; @Entity public class DynamicExtractionAction extends Action { protected DynamicExtractionAction() { }
package ch.zhaw.statefulconversation.model.commons.actions; @Entity public class DynamicExtractionAction extends Action { protected DynamicExtractionAction() { }
public DynamicExtractionAction(String actionPromptTemplate, Storage storage, String storageKeyFrom,
1
2023-12-06 09:36:58+00:00
8k
SkyDynamic/QuickBackupM-Fabric
src/main/java/dev/skydynamic/quickbackupmulti/command/QuickBackupMultiCommand.java
[ { "identifier": "RestoreTask", "path": "src/main/java/dev/skydynamic/quickbackupmulti/backup/RestoreTask.java", "snippet": "public class RestoreTask extends TimerTask {\n\n private final EnvType env;\n private final List<ServerPlayerEntity> playerList;\n private final int slot;\n\n public Re...
import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.tree.LiteralCommandNode; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.arguments.StringArgumentType; import dev.skydynamic.quickbackupmulti.backup.RestoreTask; import dev.skydynamic.quickbackupmulti.i18n.LangSuggestionProvider; import dev.skydynamic.quickbackupmulti.i18n.Translate; import dev.skydynamic.quickbackupmulti.utils.Messenger; import net.fabricmc.api.EnvType; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.server.MinecraftServer; import net.minecraft.server.command.CommandManager; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.text.ClickEvent; import net.minecraft.text.HoverEvent; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import dev.skydynamic.quickbackupmulti.utils.config.Config; import org.quartz.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.SimpleDateFormat; import java.util.List; import java.util.Timer; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import static dev.skydynamic.quickbackupmulti.utils.QbmManager.*; import static dev.skydynamic.quickbackupmulti.i18n.Translate.tr; import static dev.skydynamic.quickbackupmulti.utils.schedule.CronUtil.*; import static net.minecraft.server.command.CommandManager.literal;
6,855
private static int switchMode(ServerCommandSource commandSource, String mode) { Config.INSTANCE.setScheduleMode(mode); try { if (Config.INSTANCE.getScheduleBackup()) { if (Config.TEMP_CONFIG.scheduler.isStarted()) Config.TEMP_CONFIG.scheduler.shutdown(); startSchedule(commandSource); } } catch (SchedulerException e) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.switch.fail", e))); return 0; } Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.switch.set", mode))); return 1; } private static int setScheduleCron(ServerCommandSource commandSource, String value) { try { if (cronIsValid(value)) { if (Config.TEMP_CONFIG.scheduler.isStarted()) Config.TEMP_CONFIG.scheduler.shutdown(); if (Config.INSTANCE.getScheduleBackup()) { Config.INSTANCE.setScheduleCron(value); startSchedule(commandSource); if (Config.INSTANCE.getScheduleMode().equals("cron")) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_custom_success", getNextExecutionTime(Config.INSTANCE.getScheduleCron(), false)))); } } else { Config.INSTANCE.setScheduleCron(value); Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_custom_success_only"))); } } else { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.expression_error"))); return 0; } return 1; } catch (SchedulerException e) { return 0; } } private static int setScheduleInterval(ServerCommandSource commandSource, int value, String type) { try { Config.TEMP_CONFIG.scheduler.shutdown(); switch (type) { case "s" -> Config.INSTANCE.setScheduleInterval(value); case "m" -> Config.INSTANCE.setScheduleInterval(getSeconds(value, 0, 0)); case "h" -> Config.INSTANCE.setScheduleInterval(getSeconds(0, value, 0)); case "d" -> Config.INSTANCE.setScheduleInterval(getSeconds(0, 0, value)); } if (Config.INSTANCE.getScheduleBackup()) { startSchedule(commandSource); if (Config.INSTANCE.getScheduleMode().equals("interval")) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_success", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis() + Config.INSTANCE.getScheduleInrerval() * 1000L)))); } } else { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_success_only"))); } return 1; } catch (SchedulerException e) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_fail", e))); return 0; } } private static int disableScheduleBackup(ServerCommandSource commandSource) { try { Config.TEMP_CONFIG.scheduler.shutdown(); Config.INSTANCE.setScheduleBackup(false); Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.disable.success"))); return 1; } catch (SchedulerException e) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.disable.fail", e))); return 0; } } private static int enableScheduleBackup(ServerCommandSource commandSource) { try { Config.INSTANCE.setScheduleBackup(true); if (Config.TEMP_CONFIG.scheduler != null) Config.TEMP_CONFIG.scheduler.shutdown(); startSchedule(commandSource); return 1; } catch (SchedulerException e) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.enable.fail", e))); return 0; } } public static int getScheduleMode(ServerCommandSource commandSource) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.schedule.mode.get", Config.INSTANCE.getScheduleMode()))); return 1; } public static int getNextBackupTime(ServerCommandSource commandSource) { if (Config.INSTANCE.getScheduleBackup()) { String nextBackupTimeString = ""; switch (Config.INSTANCE.getScheduleMode()) { case "cron" -> nextBackupTimeString = getNextExecutionTime(Config.INSTANCE.getScheduleCron(), false); case "interval" -> nextBackupTimeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Config.TEMP_CONFIG.latestScheduleExecuteTime + Config.INSTANCE.getScheduleInrerval() * 1000L); } Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.get", nextBackupTimeString))); return 1; } else { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.get_fail"))); return 0; } } private static int getLang(ServerCommandSource commandSource) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.lang.get", Config.INSTANCE.getLang()))); return 1; } private static int setLang(ServerCommandSource commandSource, String lang) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.lang.set", lang)));
package dev.skydynamic.quickbackupmulti.command; //#if MC<11900 //$$ import com.mojang.brigadier.exceptions.CommandSyntaxException; //#endif public class QuickBackupMultiCommand { private static final Logger logger = LoggerFactory.getLogger("Command"); public static void RegisterCommand(CommandDispatcher<ServerCommandSource> dispatcher) { LiteralCommandNode<ServerCommandSource> QuickBackupMultiShortCommand = dispatcher.register(literal("qb") .then(literal("list").executes(it -> listSaveBackups(it.getSource()))) .then(literal("make").requires(me -> me.hasPermissionLevel(2)) .executes(it -> makeSaveBackup(it.getSource(), -1, "")) .then(CommandManager.argument("slot", IntegerArgumentType.integer(1)) .executes(it -> makeSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot"), "")) .then(CommandManager.argument("desc", StringArgumentType.string()) .executes(it -> makeSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot"), StringArgumentType.getString(it, "desc")))) ) .then(CommandManager.argument("desc", StringArgumentType.string()) .executes(it -> makeSaveBackup(it.getSource(), -1, StringArgumentType.getString(it, "desc")))) ) .then(literal("back").requires(me -> me.hasPermissionLevel(2)) .executes(it -> restoreSaveBackup(it.getSource(), 1)) .then(CommandManager.argument("slot", IntegerArgumentType.integer(1)) .executes(it -> restoreSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot"))))) .then(literal("confirm").requires(me -> me.hasPermissionLevel(2)) .executes(it -> { try { executeRestore(it.getSource()); } catch (Exception e) { e.printStackTrace(); } return 0; })) .then(literal("cancel").requires(me -> me.hasPermissionLevel(2)) .executes(it -> cancelRestore(it.getSource()))) .then(literal("delete").requires(me -> me.hasPermissionLevel(2)) .then(CommandManager.argument("slot", IntegerArgumentType.integer(1)) .executes(it -> deleteSaveBackup(it.getSource(), IntegerArgumentType.getInteger(it, "slot"))))) .then(literal("setting").requires(me -> me.hasPermissionLevel(2)) .then(literal("lang") .then(literal("get").executes(it -> getLang(it.getSource()))) .then(literal("set").requires(me -> me.hasPermissionLevel(2)) .then(CommandManager.argument("lang", StringArgumentType.string()) .suggests(new LangSuggestionProvider()) .executes(it -> setLang(it.getSource(), StringArgumentType.getString(it, "lang")))))) .then(literal("schedule") .then(literal("enable").executes(it -> enableScheduleBackup(it.getSource()))) .then(literal("disable").executes(it -> disableScheduleBackup(it.getSource()))) .then(literal("set") .then(literal("interval") .then(literal("second") .then(CommandManager.argument("second", IntegerArgumentType.integer(1)) .executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "second"), "s")) ) ).then(literal("minute") .then(CommandManager.argument("minute", IntegerArgumentType.integer(1)) .executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "minute"), "m")) ) ).then(literal("hour") .then(CommandManager.argument("hour", IntegerArgumentType.integer(1)) .executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "hour"), "h")) ) ).then(literal("day") .then(CommandManager.argument("day", IntegerArgumentType.integer(1)) .executes(it -> setScheduleInterval(it.getSource(), IntegerArgumentType.getInteger(it, "day"), "d")) ) ) ) .then(literal("cron") .then(CommandManager.argument("cron", StringArgumentType.string()) .executes(it -> setScheduleCron(it.getSource(), StringArgumentType.getString(it, "cron"))))) .then(literal("mode") .then(literal("switch") .then(literal("interval") .executes(it -> switchMode(it.getSource(), "interval"))) .then(literal("cron") .executes(it -> switchMode(it.getSource(), "cron")))) .then(literal("get").executes(it -> getScheduleMode(it.getSource())))) ) .then(literal("get") .executes(it -> getNextBackupTime(it.getSource()))) ) ) ); dispatcher.register(literal("quickbackupm").redirect(QuickBackupMultiShortCommand)); } public static final ConcurrentHashMap<String, ConcurrentHashMap<String, Object>> QbDataHashMap = new ConcurrentHashMap<>(); private static int switchMode(ServerCommandSource commandSource, String mode) { Config.INSTANCE.setScheduleMode(mode); try { if (Config.INSTANCE.getScheduleBackup()) { if (Config.TEMP_CONFIG.scheduler.isStarted()) Config.TEMP_CONFIG.scheduler.shutdown(); startSchedule(commandSource); } } catch (SchedulerException e) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.switch.fail", e))); return 0; } Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.switch.set", mode))); return 1; } private static int setScheduleCron(ServerCommandSource commandSource, String value) { try { if (cronIsValid(value)) { if (Config.TEMP_CONFIG.scheduler.isStarted()) Config.TEMP_CONFIG.scheduler.shutdown(); if (Config.INSTANCE.getScheduleBackup()) { Config.INSTANCE.setScheduleCron(value); startSchedule(commandSource); if (Config.INSTANCE.getScheduleMode().equals("cron")) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_custom_success", getNextExecutionTime(Config.INSTANCE.getScheduleCron(), false)))); } } else { Config.INSTANCE.setScheduleCron(value); Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_custom_success_only"))); } } else { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.expression_error"))); return 0; } return 1; } catch (SchedulerException e) { return 0; } } private static int setScheduleInterval(ServerCommandSource commandSource, int value, String type) { try { Config.TEMP_CONFIG.scheduler.shutdown(); switch (type) { case "s" -> Config.INSTANCE.setScheduleInterval(value); case "m" -> Config.INSTANCE.setScheduleInterval(getSeconds(value, 0, 0)); case "h" -> Config.INSTANCE.setScheduleInterval(getSeconds(0, value, 0)); case "d" -> Config.INSTANCE.setScheduleInterval(getSeconds(0, 0, value)); } if (Config.INSTANCE.getScheduleBackup()) { startSchedule(commandSource); if (Config.INSTANCE.getScheduleMode().equals("interval")) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_success", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis() + Config.INSTANCE.getScheduleInrerval() * 1000L)))); } } else { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_success_only"))); } return 1; } catch (SchedulerException e) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.cron.set_fail", e))); return 0; } } private static int disableScheduleBackup(ServerCommandSource commandSource) { try { Config.TEMP_CONFIG.scheduler.shutdown(); Config.INSTANCE.setScheduleBackup(false); Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.disable.success"))); return 1; } catch (SchedulerException e) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.disable.fail", e))); return 0; } } private static int enableScheduleBackup(ServerCommandSource commandSource) { try { Config.INSTANCE.setScheduleBackup(true); if (Config.TEMP_CONFIG.scheduler != null) Config.TEMP_CONFIG.scheduler.shutdown(); startSchedule(commandSource); return 1; } catch (SchedulerException e) { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.enable.fail", e))); return 0; } } public static int getScheduleMode(ServerCommandSource commandSource) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.schedule.mode.get", Config.INSTANCE.getScheduleMode()))); return 1; } public static int getNextBackupTime(ServerCommandSource commandSource) { if (Config.INSTANCE.getScheduleBackup()) { String nextBackupTimeString = ""; switch (Config.INSTANCE.getScheduleMode()) { case "cron" -> nextBackupTimeString = getNextExecutionTime(Config.INSTANCE.getScheduleCron(), false); case "interval" -> nextBackupTimeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Config.TEMP_CONFIG.latestScheduleExecuteTime + Config.INSTANCE.getScheduleInrerval() * 1000L); } Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.get", nextBackupTimeString))); return 1; } else { Messenger.sendMessage(commandSource, Messenger.literal(tr("quickbackupmulti.schedule.get_fail"))); return 0; } } private static int getLang(ServerCommandSource commandSource) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.lang.get", Config.INSTANCE.getLang()))); return 1; } private static int setLang(ServerCommandSource commandSource, String lang) { Messenger.sendMessage(commandSource, Text.of(tr("quickbackupmulti.lang.set", lang)));
Translate.handleResourceReload(lang);
2
2023-12-09 13:51:17+00:00
8k
quentin452/Garden-Stuff-Continuation
src/main/resources/com/jaquadro/minecraft/gardencore/client/gui/GuiCompostBin.java
[ { "identifier": "TileEntityCompostBin", "path": "src/main/java/com/jaquadro/minecraft/gardencore/block/tile/TileEntityCompostBin.java", "snippet": "public class TileEntityCompostBin extends TileEntity implements ISidedInventory {\n\n private ItemStack[] compostItemStacks = new ItemStack[10];\n pub...
import com.jaquadro.minecraft.gardencore.block.tile.TileEntityCompostBin; import com.jaquadro.minecraft.gardencore.inventory.ContainerCompostBin; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11;
4,841
package com.jaquadro.minecraft.gardencore.client.gui; public class GuiCompostBin extends GuiContainer { private static final ResourceLocation compostBinGuiTextures = new ResourceLocation("gardencore", "textures/gui/compostBin.png");
package com.jaquadro.minecraft.gardencore.client.gui; public class GuiCompostBin extends GuiContainer { private static final ResourceLocation compostBinGuiTextures = new ResourceLocation("gardencore", "textures/gui/compostBin.png");
private TileEntityCompostBin tileCompost;
0
2023-12-12 08:13:16+00:00
8k
joyheros/realworld
app-article/src/main/java/io/zhifou/realworld/article/application/service/impl/CommentServiceImpl.java
[ { "identifier": "ProfileService", "path": "app-permission/src/main/java/io/zhifou/realworld/auth/application/service/ProfileService.java", "snippet": "public interface ProfileService {\r\n\tProfileData getProfile(User me, Long userId);\r\n\r\n\tProfileData getProfile(User me, String username);\r\n\r\n\t...
import java.util.List; import java.util.Optional; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import io.zhifou.realworld.auth.application.data.ProfileData; import io.zhifou.realworld.auth.application.service.ProfileService; import io.zhifou.realworld.auth.domain.User; import io.zhifou.realworld.exception.ResourceNotFoundException; import io.zhifou.realworld.article.application.data.CommentData; import io.zhifou.realworld.article.application.data.CommentPageSet; import io.zhifou.realworld.article.application.data.CommentParam; import io.zhifou.realworld.article.application.service.CommentService; import io.zhifou.realworld.article.domain.Article; import io.zhifou.realworld.article.domain.Comment; import io.zhifou.realworld.article.domain.support.ArticleProvider; import io.zhifou.realworld.article.domain.support.CommentProvider;
3,901
package io.zhifou.realworld.article.application.service.impl; @Service public class CommentServiceImpl implements CommentService { private final ArticleProvider articleProvider;
package io.zhifou.realworld.article.application.service.impl; @Service public class CommentServiceImpl implements CommentService { private final ArticleProvider articleProvider;
private final CommentProvider commentProvider;
10
2023-12-14 07:28:49+00:00
8k
Zergatul/java-scripting-language
src/main/java/com/zergatul/scripting/compiler/operations/UnaryOperation.java
[ { "identifier": "CompilerMethodVisitor", "path": "src/main/java/com/zergatul/scripting/compiler/CompilerMethodVisitor.java", "snippet": "public abstract class CompilerMethodVisitor {\r\n public abstract String getClassName();\r\n public abstract VariableContextStack getContextStack();\r\n publi...
import com.zergatul.scripting.compiler.CompilerMethodVisitor; import com.zergatul.scripting.compiler.ScriptCompileException; import com.zergatul.scripting.compiler.types.SBoolean; import com.zergatul.scripting.compiler.types.SFloatType; import com.zergatul.scripting.compiler.types.SIntType; import com.zergatul.scripting.compiler.types.SType; import org.objectweb.asm.Label; import org.objectweb.asm.Type; import java.lang.reflect.Method; import static org.objectweb.asm.Opcodes.*;
4,797
package com.zergatul.scripting.compiler.operations; public abstract class UnaryOperation { public abstract SType getType() throws ScriptCompileException;
package com.zergatul.scripting.compiler.operations; public abstract class UnaryOperation { public abstract SType getType() throws ScriptCompileException;
public abstract void apply(CompilerMethodVisitor visitor) throws ScriptCompileException;
0
2023-12-10 00:37:27+00:00
8k