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
gunnarmorling/1brc
src/main/java/dev/morling/onebrc/CreateMeasurements2.java
[ { "identifier": "CheaperCharBuffer", "path": "src/main/java/org/rschwietzke/CheaperCharBuffer.java", "snippet": "public class CheaperCharBuffer implements CharSequence {\n // our data, can grow - that is not safe and has be altered from the original code\n // to allow speed\n public char[] data...
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.rschwietzke.CheaperCharBuffer; import org.rschwietzke.FastRandom;
6,682
/* * Copyright 2023 The original 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 dev.morling.onebrc; /** * Faster version with some data faking instead of a real Gaussian distribution * Good enough for our purppose I guess. */ public class CreateMeasurements2 { private static final String FILE = "./measurements2.txt"; static class WeatherStation { final static char[] NUMBERS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; final String id; final int meanTemperature; final char[] firstPart; final FastRandom r = new FastRandom(ThreadLocalRandom.current().nextLong()); WeatherStation(String id, double meanTemperature) { this.id = id; this.meanTemperature = (int) meanTemperature; // make it directly copyable this.firstPart = (id + ";").toCharArray(); } /** * We write out data into the buffer to avoid string conversion * We also no longer use double and gaussian, because for our * purpose, the fake numbers here will do it. Less * * @param buffer the buffer to append to */
/* * Copyright 2023 The original 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 dev.morling.onebrc; /** * Faster version with some data faking instead of a real Gaussian distribution * Good enough for our purppose I guess. */ public class CreateMeasurements2 { private static final String FILE = "./measurements2.txt"; static class WeatherStation { final static char[] NUMBERS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; final String id; final int meanTemperature; final char[] firstPart; final FastRandom r = new FastRandom(ThreadLocalRandom.current().nextLong()); WeatherStation(String id, double meanTemperature) { this.id = id; this.meanTemperature = (int) meanTemperature; // make it directly copyable this.firstPart = (id + ";").toCharArray(); } /** * We write out data into the buffer to avoid string conversion * We also no longer use double and gaussian, because for our * purpose, the fake numbers here will do it. Less * * @param buffer the buffer to append to */
void measurement(final CheaperCharBuffer buffer) {
0
2023-12-28 09:13:24+00:00
8k
EnigmaGuest/fnk-server
service-core/service-core-system/src/main/java/fun/isite/service/core/system/impl/AdminUserService.java
[ { "identifier": "BaseService", "path": "service-common/service-common-db/src/main/java/fun/isite/service/common/db/impl/BaseService.java", "snippet": "public class BaseService<M extends BaseMapper<T>, T extends BaseEntity<T>> extends ServiceImpl<M, T> implements IBaseService<T> {\n public final stati...
import cn.dev33.satoken.stp.StpUtil; import cn.hutool.crypto.SecureUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import fun.isite.service.common.db.impl.BaseService; import fun.isite.service.common.tools.lang.AssertUtils; import fun.isite.service.common.tools.utils.SaltUtils; import fun.isite.service.core.basic.enums.GenderType; import fun.isite.service.core.basic.vo.TokenVO; import fun.isite.service.core.system.dto.LoginAdminDTO; import fun.isite.service.core.system.entity.AdminUser; import fun.isite.service.core.system.mapper.AdminUserMapper; import fun.isite.service.core.system.service.IAdminUserService; import fun.isite.service.core.system.service.IUserRoleService; import fun.isite.service.core.system.vo.AdminUserVO; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List;
5,096
package fun.isite.service.core.system.impl; /** * 系统用户 服务实现层 * * @author Enigma * @since 2023-12-18 */ @Service @AllArgsConstructor
package fun.isite.service.core.system.impl; /** * 系统用户 服务实现层 * * @author Enigma * @since 2023-12-18 */ @Service @AllArgsConstructor
public class AdminUserService extends BaseService<AdminUserMapper, AdminUser> implements IAdminUserService {
6
2023-12-26 01:55:01+00:00
8k
codingmiao/hppt
cc/src/main/java/org/wowtools/hppt/cc/StartCc.java
[ { "identifier": "CcConfig", "path": "cc/src/main/java/org/wowtools/hppt/cc/pojo/CcConfig.java", "snippet": "public class CcConfig {\n /**\n * 客户端id,每个cc.jar用一个,不要重复\n */\n public String clientId;\n\n /**\n * 服务端http地址,可以填nginx转发过的地址\n */\n public String serverUrl;\n\n /**\...
import lombok.extern.slf4j.Slf4j; import okhttp3.Response; import org.apache.logging.log4j.core.config.Configurator; import org.wowtools.common.utils.ResourcesReader; import org.wowtools.hppt.cc.pojo.CcConfig; import org.wowtools.hppt.cc.service.ClientSessionService; import org.wowtools.hppt.common.util.AesCipherUtil; import org.wowtools.hppt.common.util.BytesUtil; import org.wowtools.hppt.common.util.Constant; import org.wowtools.hppt.common.util.HttpUtil; import java.io.File; import java.net.URLEncoder; import java.nio.charset.StandardCharsets;
6,474
package org.wowtools.hppt.cc; /** * @author liuyu * @date 2023/12/20 */ @Slf4j public class StartCc { public static CcConfig config;
package org.wowtools.hppt.cc; /** * @author liuyu * @date 2023/12/20 */ @Slf4j public class StartCc { public static CcConfig config;
public static AesCipherUtil aesCipherUtil;
2
2023-12-22 14:14:27+00:00
8k
3arthqu4ke/phobot
src/main/java/me/earth/phobot/modules/combat/SelfTrap.java
[ { "identifier": "Phobot", "path": "src/main/java/me/earth/phobot/Phobot.java", "snippet": "@Getter\n@RequiredArgsConstructor\n@SuppressWarnings(\"ClassCanBeRecord\")\npublic class Phobot {\n public static final String NAME = \"Phobot\";\n\n private final PingBypass pingBypass;\n private final E...
import lombok.Getter; import me.earth.phobot.Phobot; import me.earth.phobot.modules.BlockPlacingModule; import me.earth.phobot.pathfinder.blocks.BlockPathfinder; import me.earth.phobot.pathfinder.blocks.BlockPathfinderWithBlacklist; import me.earth.phobot.services.inventory.InventoryContext; import me.earth.phobot.util.ResetUtil; import me.earth.pingbypass.api.module.impl.Categories; import me.earth.pingbypass.api.setting.Setting; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.multiplayer.MultiPlayerGameMode; import net.minecraft.client.player.LocalPlayer; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import java.util.HashSet; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
5,732
package me.earth.phobot.modules.combat; @Getter public class SelfTrap extends BlockPlacingModule implements TrapsPlayers { private final Setting<Integer> maxHelping = number("Helping", 3, 1, 10, "Amount of helping blocks to use."); private final Map<BlockPos, Long> blackList = new ConcurrentHashMap<>(); private final BlockPathfinder blockPathfinder = new BlockPathfinderWithBlacklist(blackList); public SelfTrap(Phobot phobot) { super(phobot, phobot.getBlockPlacer(), "SelfTrap", Categories.COMBAT, "Traps you.", 0); listen(getBlackListClearListener()); ResetUtil.disableOnRespawnAndWorldChange(this, mc); } @Override
package me.earth.phobot.modules.combat; @Getter public class SelfTrap extends BlockPlacingModule implements TrapsPlayers { private final Setting<Integer> maxHelping = number("Helping", 3, 1, 10, "Amount of helping blocks to use."); private final Map<BlockPos, Long> blackList = new ConcurrentHashMap<>(); private final BlockPathfinder blockPathfinder = new BlockPathfinderWithBlacklist(blackList); public SelfTrap(Phobot phobot) { super(phobot, phobot.getBlockPlacer(), "SelfTrap", Categories.COMBAT, "Traps you.", 0); listen(getBlackListClearListener()); ResetUtil.disableOnRespawnAndWorldChange(this, mc); } @Override
protected void updatePlacements(InventoryContext context, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) {
4
2023-12-22 14:32:16+00:00
8k
ArmanKhanDev/FakepixelDungeonHelper
src/main/java/io/github/quantizr/gui/LinkGUI.java
[ { "identifier": "DungeonRooms", "path": "build/sources/main/java/io/github/quantizr/DungeonRooms.java", "snippet": "@Mod(modid = DungeonRooms.MODID, version = DungeonRooms.VERSION)\npublic class DungeonRooms\n{\n public static final String MODID = \"FDH\";\n public static final String VERSION = \"...
import io.github.quantizr.DungeonRooms; import io.github.quantizr.core.AutoRoom; import io.github.quantizr.handlers.OpenLink; import io.github.quantizr.handlers.TextRenderer; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.event.ClickEvent; import net.minecraft.util.ChatComponentText; import net.minecraft.util.EnumChatFormatting;
7,085
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.gui; public class LinkGUI extends GuiScreen { private GuiButton discordClient; private GuiButton discordBrowser; private GuiButton SBPSecrets; private GuiButton close; @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { super.initGui(); ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft()); int height = sr.getScaledHeight(); int width = sr.getScaledWidth(); discordClient = new GuiButton(0, width / 2 - 185, height / 6 + 96, 120, 20, "DSG Discord Client"); discordBrowser = new GuiButton(1, width / 2 - 60, height / 6 + 96, 120, 20, "DSG Discord Browser"); SBPSecrets = new GuiButton(2, width / 2 + 65, height / 6 + 96, 120, 20, "SBP Secrets Mod"); close = new GuiButton(3, width / 2 - 60, height / 6 + 136, 120, 20, "Close"); this.buttonList.add(discordClient); this.buttonList.add(discordBrowser); this.buttonList.add(SBPSecrets); this.buttonList.add(close); } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); Minecraft mc = Minecraft.getMinecraft(); String displayText; if (AutoRoom.lastRoomName == null) { displayText = "Where would you like to view secrets for: " + EnumChatFormatting.RED + "null"; } else { displayText = "Where would you like to view secrets for: " + EnumChatFormatting.GREEN + AutoRoom.lastRoomName; } int displayWidth = mc.fontRendererObj.getStringWidth(displayText);
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.gui; public class LinkGUI extends GuiScreen { private GuiButton discordClient; private GuiButton discordBrowser; private GuiButton SBPSecrets; private GuiButton close; @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { super.initGui(); ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft()); int height = sr.getScaledHeight(); int width = sr.getScaledWidth(); discordClient = new GuiButton(0, width / 2 - 185, height / 6 + 96, 120, 20, "DSG Discord Client"); discordBrowser = new GuiButton(1, width / 2 - 60, height / 6 + 96, 120, 20, "DSG Discord Browser"); SBPSecrets = new GuiButton(2, width / 2 + 65, height / 6 + 96, 120, 20, "SBP Secrets Mod"); close = new GuiButton(3, width / 2 - 60, height / 6 + 136, 120, 20, "Close"); this.buttonList.add(discordClient); this.buttonList.add(discordBrowser); this.buttonList.add(SBPSecrets); this.buttonList.add(close); } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); Minecraft mc = Minecraft.getMinecraft(); String displayText; if (AutoRoom.lastRoomName == null) { displayText = "Where would you like to view secrets for: " + EnumChatFormatting.RED + "null"; } else { displayText = "Where would you like to view secrets for: " + EnumChatFormatting.GREEN + AutoRoom.lastRoomName; } int displayWidth = mc.fontRendererObj.getStringWidth(displayText);
TextRenderer.drawText(mc, displayText, width / 2 - displayWidth / 2, height / 6 + 56, 1D, false);
3
2023-12-22 04:44:39+00:00
8k
R2turnTrue/chzzk4j
src/test/java/ChannelApiTest.java
[ { "identifier": "Chzzk", "path": "src/main/java/xyz/r2turntrue/chzzk4j/Chzzk.java", "snippet": "public class Chzzk {\n public static String API_URL = \"https://api.chzzk.naver.com\";\n public static String GAME_API_URL = \"https://comm-api.game.naver.com/nng_main\";\n\n public boolean isDebug =...
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import xyz.r2turntrue.chzzk4j.Chzzk; import xyz.r2turntrue.chzzk4j.ChzzkBuilder; import xyz.r2turntrue.chzzk4j.exception.ChannelNotExistsException; import xyz.r2turntrue.chzzk4j.exception.NotExistsException; import xyz.r2turntrue.chzzk4j.exception.NotLoggedInException; import xyz.r2turntrue.chzzk4j.types.ChzzkUser; import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannel; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Assertions; import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannelFollowingData; import xyz.r2turntrue.chzzk4j.types.channel.ChzzkChannelRules;
4,057
// 8e7a6f0a0b1f0612afee1a673e94027d - 레고칠칠 // c2186ca6edb3a663f137b15ed7346fac - 리얼진짜우왁굳 // 두 채널 모두 팔로우한 뒤 테스트 진행해주세요. // // 22bd842599735ae19e454983280f611e - ENCHANT // 위 채널은 팔로우 해제 후 테스트 진행해주세요. public class ChannelApiTest extends ChzzkTestBase { public final String FOLLOWED_CHANNEL_1 = "8e7a6f0a0b1f0612afee1a673e94027d"; // 레고칠칠 public final String FOLLOWED_CHANNEL_2 = "c2186ca6edb3a663f137b15ed7346fac"; // 리얼진짜우왁굳 public final String UNFOLLOWED_CHANNEL = "22bd842599735ae19e454983280f611e"; // ENCHANT @Test void gettingNormalChannelInfo() throws IOException { AtomicReference<ChzzkChannel> channel = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> channel.set(chzzk.getChannel(FOLLOWED_CHANNEL_2))); System.out.println(channel); } @Test void gettingInvalidChannelInfo() throws IOException { Assertions.assertThrowsExactly(ChannelNotExistsException.class, () -> { chzzk.getChannel("invalidchannelid"); }); } @Test void gettingNormalChannelRules() throws IOException { AtomicReference<ChzzkChannelRules> rule = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> rule.set(chzzk.getChannelChatRules(FOLLOWED_CHANNEL_1))); System.out.println(rule); } @Test void gettingInvalidChannelRules() throws IOException { Assertions.assertThrowsExactly(NotExistsException.class, () -> { chzzk.getChannelChatRules("invalidchannel or no rule channel"); }); } @Test void gettingFollowStatusAnonymous() throws IOException {
// 8e7a6f0a0b1f0612afee1a673e94027d - 레고칠칠 // c2186ca6edb3a663f137b15ed7346fac - 리얼진짜우왁굳 // 두 채널 모두 팔로우한 뒤 테스트 진행해주세요. // // 22bd842599735ae19e454983280f611e - ENCHANT // 위 채널은 팔로우 해제 후 테스트 진행해주세요. public class ChannelApiTest extends ChzzkTestBase { public final String FOLLOWED_CHANNEL_1 = "8e7a6f0a0b1f0612afee1a673e94027d"; // 레고칠칠 public final String FOLLOWED_CHANNEL_2 = "c2186ca6edb3a663f137b15ed7346fac"; // 리얼진짜우왁굳 public final String UNFOLLOWED_CHANNEL = "22bd842599735ae19e454983280f611e"; // ENCHANT @Test void gettingNormalChannelInfo() throws IOException { AtomicReference<ChzzkChannel> channel = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> channel.set(chzzk.getChannel(FOLLOWED_CHANNEL_2))); System.out.println(channel); } @Test void gettingInvalidChannelInfo() throws IOException { Assertions.assertThrowsExactly(ChannelNotExistsException.class, () -> { chzzk.getChannel("invalidchannelid"); }); } @Test void gettingNormalChannelRules() throws IOException { AtomicReference<ChzzkChannelRules> rule = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> rule.set(chzzk.getChannelChatRules(FOLLOWED_CHANNEL_1))); System.out.println(rule); } @Test void gettingInvalidChannelRules() throws IOException { Assertions.assertThrowsExactly(NotExistsException.class, () -> { chzzk.getChannelChatRules("invalidchannel or no rule channel"); }); } @Test void gettingFollowStatusAnonymous() throws IOException {
Assertions.assertThrowsExactly(NotLoggedInException.class, () ->
4
2023-12-30 20:01:23+00:00
8k
lonelytransistor/LauncherAndroidTV
app/src/main/java/net/lonelytransistor/launcher/RecentsWindow.java
[ { "identifier": "GenericWindow", "path": "app/src/main/java/net/lonelytransistor/launcher/generics/GenericWindow.java", "snippet": "public class GenericWindow {\n private static final String TAG = \"GenericWindow\";\n\n private static final int FADE_DURATION = 500;\n\n private static WindowMana...
import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.leanback.widget.HorizontalGridView; import androidx.recyclerview.widget.RecyclerView; import net.lonelytransistor.launcher.generics.GenericWindow; import net.lonelytransistor.launcher.repos.ApkRepo; import java.util.List;
5,198
package net.lonelytransistor.launcher; public class RecentsWindow extends GenericWindow { private static final String TAG = "RecentsWindow"; private static final int SCALE_DURATION = 200; private final View.OnKeyListener mKeyListener = (v, keyCode, event) -> { if (event.getAction() == KeyEvent.ACTION_UP) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_ESCAPE: hide(); return true; } } return false; }; private final HorizontalGridView mRecentsView; public RecentsWindow(Context ctx) { super(ctx, R.layout.activity_recents); mRecentsView = (HorizontalGridView) findViewById(R.id.recents_bar); mRecentsView.setAdapter(new RecentsBarAdapter()); getView().setOnKeyListener(mKeyListener); mRecentsView.setOnKeyListener(mKeyListener); } private class RecentsBarAdapter extends RecyclerView.Adapter<RecentsBarAdapter.ViewHolder> {
package net.lonelytransistor.launcher; public class RecentsWindow extends GenericWindow { private static final String TAG = "RecentsWindow"; private static final int SCALE_DURATION = 200; private final View.OnKeyListener mKeyListener = (v, keyCode, event) -> { if (event.getAction() == KeyEvent.ACTION_UP) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_ESCAPE: hide(); return true; } } return false; }; private final HorizontalGridView mRecentsView; public RecentsWindow(Context ctx) { super(ctx, R.layout.activity_recents); mRecentsView = (HorizontalGridView) findViewById(R.id.recents_bar); mRecentsView.setAdapter(new RecentsBarAdapter()); getView().setOnKeyListener(mKeyListener); mRecentsView.setOnKeyListener(mKeyListener); } private class RecentsBarAdapter extends RecyclerView.Adapter<RecentsBarAdapter.ViewHolder> {
private List<ApkRepo.App> apps;
1
2023-12-28 18:24:12+00:00
8k
HChenX/ClipboardList
app/src/main/java/com/hchen/clipboardlist/unlockIme/UnlockIme.java
[ { "identifier": "returnConstant", "path": "app/src/main/java/com/hchen/clipboardlist/hook/Hook.java", "snippet": "public static HookAction returnConstant(final Object result) {\n return new HookAction(PRIORITY_DEFAULT) {\n @Override\n protected void before(MethodHookParam param) throws ...
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; import static com.hchen.clipboardlist.hook.Hook.HookAction.returnConstant; import com.hchen.clipboardlist.hook.Hook; import java.util.List;
5,290
package com.hchen.clipboardlist.unlockIme; public class UnlockIme extends Hook { private final String[] miuiImeList = new String[]{ "com.iflytek.inputmethod.miui", "com.sohu.inputmethod.sogou.xiaomi", "com.baidu.input_mi", "com.miui.catcherpatch" }; private int navBarColor = 0; @Override public void init() { if (getProp("ro.miui.support_miui_ime_bottom", "0").equals("1")) { startHook(loadPackageParam); } } private void startHook(LoadPackageParam param) { // 检查是否为小米定制输入法 boolean isNonCustomize = true; for (String isMiui : miuiImeList) { if (isMiui.equals(param.packageName)) { isNonCustomize = false; break; } } if (isNonCustomize) { Class<?> sInputMethodServiceInjector = findClassIfExists("android.inputmethodservice.InputMethodServiceInjector"); if (sInputMethodServiceInjector == null) sInputMethodServiceInjector = findClassIfExists("android.inputmethodservice.InputMethodServiceStubImpl"); if (sInputMethodServiceInjector != null) { hookSIsImeSupport(sInputMethodServiceInjector); hookIsXiaoAiEnable(sInputMethodServiceInjector); setPhraseBgColor(sInputMethodServiceInjector); } else { logE(tag, "Class not found: InputMethodServiceInjector"); } } hookDeleteNotSupportIme("android.inputmethodservice.InputMethodServiceInjector$MiuiSwitchInputMethodListener", param.classLoader); // 获取常用语的ClassLoader boolean finalIsNonCustomize = isNonCustomize; findAndHookMethod("android.inputmethodservice.InputMethodModuleManager", "loadDex", ClassLoader.class, String.class, new HookAction() { @Override protected void after(MethodHookParam param) { getSupportIme((ClassLoader) param.args[0]); hookDeleteNotSupportIme("com.miui.inputmethod.InputMethodBottomManager$MiuiSwitchInputMethodListener", (ClassLoader) param.args[0]); if (finalIsNonCustomize) { Class<?> InputMethodBottomManager = findClassIfExists("com.miui.inputmethod.InputMethodBottomManager", (ClassLoader) param.args[0]); if (InputMethodBottomManager != null) { hookSIsImeSupport(InputMethodBottomManager); hookIsXiaoAiEnable(InputMethodBottomManager); } else { logE(tag, "Class not found: com.miui.inputmethod.InputMethodBottomManager"); } } } } ); } /** * 跳过包名检查,直接开启输入法优化 * * @param clazz 声明或继承字段的类 */ private void hookSIsImeSupport(Class<?> clazz) { try { setStaticObjectField(clazz, "sIsImeSupport", 1); } catch (Throwable throwable) { logE(tag, "Hook field sIsImeSupport: " + throwable); } } /** * 小爱语音输入按钮失效修复 * * @param clazz 声明或继承方法的类 */ private void hookIsXiaoAiEnable(Class<?> clazz) { try {
package com.hchen.clipboardlist.unlockIme; public class UnlockIme extends Hook { private final String[] miuiImeList = new String[]{ "com.iflytek.inputmethod.miui", "com.sohu.inputmethod.sogou.xiaomi", "com.baidu.input_mi", "com.miui.catcherpatch" }; private int navBarColor = 0; @Override public void init() { if (getProp("ro.miui.support_miui_ime_bottom", "0").equals("1")) { startHook(loadPackageParam); } } private void startHook(LoadPackageParam param) { // 检查是否为小米定制输入法 boolean isNonCustomize = true; for (String isMiui : miuiImeList) { if (isMiui.equals(param.packageName)) { isNonCustomize = false; break; } } if (isNonCustomize) { Class<?> sInputMethodServiceInjector = findClassIfExists("android.inputmethodservice.InputMethodServiceInjector"); if (sInputMethodServiceInjector == null) sInputMethodServiceInjector = findClassIfExists("android.inputmethodservice.InputMethodServiceStubImpl"); if (sInputMethodServiceInjector != null) { hookSIsImeSupport(sInputMethodServiceInjector); hookIsXiaoAiEnable(sInputMethodServiceInjector); setPhraseBgColor(sInputMethodServiceInjector); } else { logE(tag, "Class not found: InputMethodServiceInjector"); } } hookDeleteNotSupportIme("android.inputmethodservice.InputMethodServiceInjector$MiuiSwitchInputMethodListener", param.classLoader); // 获取常用语的ClassLoader boolean finalIsNonCustomize = isNonCustomize; findAndHookMethod("android.inputmethodservice.InputMethodModuleManager", "loadDex", ClassLoader.class, String.class, new HookAction() { @Override protected void after(MethodHookParam param) { getSupportIme((ClassLoader) param.args[0]); hookDeleteNotSupportIme("com.miui.inputmethod.InputMethodBottomManager$MiuiSwitchInputMethodListener", (ClassLoader) param.args[0]); if (finalIsNonCustomize) { Class<?> InputMethodBottomManager = findClassIfExists("com.miui.inputmethod.InputMethodBottomManager", (ClassLoader) param.args[0]); if (InputMethodBottomManager != null) { hookSIsImeSupport(InputMethodBottomManager); hookIsXiaoAiEnable(InputMethodBottomManager); } else { logE(tag, "Class not found: com.miui.inputmethod.InputMethodBottomManager"); } } } } ); } /** * 跳过包名检查,直接开启输入法优化 * * @param clazz 声明或继承字段的类 */ private void hookSIsImeSupport(Class<?> clazz) { try { setStaticObjectField(clazz, "sIsImeSupport", 1); } catch (Throwable throwable) { logE(tag, "Hook field sIsImeSupport: " + throwable); } } /** * 小爱语音输入按钮失效修复 * * @param clazz 声明或继承方法的类 */ private void hookIsXiaoAiEnable(Class<?> clazz) { try {
hookAllMethods(clazz, "isXiaoAiEnable", returnConstant(false));
0
2023-12-22 15:07:33+00:00
8k
Patbox/GlideAway
src/main/java/eu/pb4/glideaway/mixin/LivingEntityMixin.java
[ { "identifier": "GliderEntity", "path": "src/main/java/eu/pb4/glideaway/entity/GliderEntity.java", "snippet": "public class GliderEntity extends Entity implements PolymerEntity {\n private static final TrackedData<Float> ROLL = DataTracker.registerData(GliderEntity.class, TrackedDataHandlerRegistry.F...
import eu.pb4.glideaway.entity.GliderEntity; import eu.pb4.glideaway.util.GlideGamerules; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.Hand; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
4,754
package eu.pb4.glideaway.mixin; @Mixin(LivingEntity.class) public abstract class LivingEntityMixin extends Entity { @Shadow protected abstract void initDataTracker(); public LivingEntityMixin(EntityType<?> type, World world) { super(type, world); } @SuppressWarnings("ConstantValue") @Inject(method = "onDismounted", at = @At("HEAD")) private void returnGlider(Entity vehicle, CallbackInfo ci) {
package eu.pb4.glideaway.mixin; @Mixin(LivingEntity.class) public abstract class LivingEntityMixin extends Entity { @Shadow protected abstract void initDataTracker(); public LivingEntityMixin(EntityType<?> type, World world) { super(type, world); } @SuppressWarnings("ConstantValue") @Inject(method = "onDismounted", at = @At("HEAD")) private void returnGlider(Entity vehicle, CallbackInfo ci) {
if (vehicle instanceof GliderEntity entity) {
0
2023-12-22 11:00:52+00:00
8k
danielfeitopin/MUNICS-SAPP-P1
src/main/java/es/storeapp/web/controller/ShoppingCartController.java
[ { "identifier": "Product", "path": "src/main/java/es/storeapp/business/entities/Product.java", "snippet": "@Entity(name = Constants.PRODUCT_ENTITY)\n@Table(name = Constants.PRODUCTS_TABLE)\npublic class Product implements Serializable{ \n\n private static final long serialVersionUID = 700798763125...
import es.storeapp.business.entities.Product; import es.storeapp.business.exceptions.InstanceNotFoundException; import es.storeapp.business.services.ProductService; import es.storeapp.common.Constants; import es.storeapp.web.exceptions.ErrorHandlingUtils; import es.storeapp.web.session.ShoppingCart; import java.text.MessageFormat; import java.util.List; import java.util.Locale; import es.storeapp.common.EscapingLoggerWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.SessionAttribute; import org.springframework.web.servlet.mvc.support.RedirectAttributes;
4,981
package es.storeapp.web.controller; @Controller public class ShoppingCartController { private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(ShoppingCartController.class); @Autowired private ProductService productService; @Autowired private MessageSource messageSource; @Autowired ErrorHandlingUtils exceptionHandlingUtils; @GetMapping(value = {Constants.CART_ENDPOINT})
package es.storeapp.web.controller; @Controller public class ShoppingCartController { private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(ShoppingCartController.class); @Autowired private ProductService productService; @Autowired private MessageSource messageSource; @Autowired ErrorHandlingUtils exceptionHandlingUtils; @GetMapping(value = {Constants.CART_ENDPOINT})
public String doGetCartPage(@SessionAttribute(Constants.SHOPPING_CART_SESSION) ShoppingCart shoppingCart,
5
2023-12-24 19:24:49+00:00
8k
Brath1024/SensiCheck
src/main/java/cn/brath/sensicheck/strategy/SensiHolder.java
[ { "identifier": "SenKey", "path": "src/main/java/cn/brath/sensicheck/core/SenKey.java", "snippet": "public class SenKey implements Serializable {\n private static final long serialVersionUID = -8879895979621579720L;\n /** The beginning index, inclusive. */\n private final int begin;\n /** Th...
import cn.brath.sensicheck.core.SenKey; import cn.brath.sensicheck.core.SenKeys; import cn.brath.sensicheck.core.SenTrie; import cn.brath.sensicheck.utils.StringUtil; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.stream.Collectors;
3,725
package cn.brath.sensicheck.strategy; /** * 敏感词处理 * * @author Brath * @since 2023-07-28 14:17:54 * <p> * 使用AC自动机实现敏感词处理 * </p> */ public class SensiHolder { private static final Logger logger = LoggerFactory.getLogger(SensiHolder.class); //默认敏感词地址 private String filepath = "/senwords.txt"; //核心Trie结构 private SenTrie senTrie; //当前敏感词列表 private List<String> lines; /** * 默认构造 */ public SensiHolder() { try { List<String> lines = readLines(); this.senTrie = new SenTrie(new HashSet<>(lines)); this.lines = lines; } catch (IOException e) { logger.error("Failed to initialize the sensitive word instance - {}", e.getMessage()); e.printStackTrace(); } } /** * 自定义FilePath * * @param filepath */ public SensiHolder(String filepath) { this.filepath = filepath; try { List<String> lines = readLines(); this.senTrie = new SenTrie(new HashSet<>(lines)); this.lines = lines; logger.info("The current sensitive word text source comes from - {}", filepath); } catch (IOException e) { logger.error("Failed to initialize the sensitive word instance - {}", e.getMessage()); e.printStackTrace(); } } /** * 读取敏感词Base64文本 * * @return * @throws IOException */ private List<String> readLines() throws IOException { List<String> lines = new ArrayList<>(); try (InputStream inputStream = getClass().getResourceAsStream(filepath)) { assert inputStream != null; try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = reader.readLine()) != null) { byte[] decode = Base64.getDecoder().decode(line); String decodedString = new String(decode, StandardCharsets.UTF_8); lines.add(decodedString); } } } return lines; } /** * 是否存在敏感词 * * @param input * @param ifLog * @return */ public boolean exists(String input, boolean ifLog) { input = standardizeInput(input); SenKeys senKeys = this.senTrie.findAll(input); if (!senKeys.isEmpty() && ifLog) { logger.warn("存在敏感词:{}", String.join(",", senKeys.stream().map(SenKey::getKeyword).collect(Collectors.toList()))); } return !senKeys.isEmpty(); } /** * 是否存在敏感词 * * @param input * @return */ public String existsStr(String input) { SenKeys senKeys = this.senTrie.findAll(input); if (!senKeys.isEmpty()) { return senKeys.stream().map(SenKey::getKeyword).collect(Collectors.joining(",")); } return null; } /** * 是否存在敏感词 * * @param input * @return */ public boolean exists(String input) { return exists(input, true); } /** * 是否存在敏感词 * * @param data * @return */ public boolean exists(Object data) { Objects.requireNonNull(data, "Data cannot be null"); return exists(JSON.toJSONString(data)); } /** * 替换 * * @param input * @param replaceValue * @return */ public String replace(String input, String replaceValue) { input = standardizeInput(input); SenKeys senKeys = this.senTrie.findAllIgnoreCase(input); if (senKeys.isEmpty()) { return input; }
package cn.brath.sensicheck.strategy; /** * 敏感词处理 * * @author Brath * @since 2023-07-28 14:17:54 * <p> * 使用AC自动机实现敏感词处理 * </p> */ public class SensiHolder { private static final Logger logger = LoggerFactory.getLogger(SensiHolder.class); //默认敏感词地址 private String filepath = "/senwords.txt"; //核心Trie结构 private SenTrie senTrie; //当前敏感词列表 private List<String> lines; /** * 默认构造 */ public SensiHolder() { try { List<String> lines = readLines(); this.senTrie = new SenTrie(new HashSet<>(lines)); this.lines = lines; } catch (IOException e) { logger.error("Failed to initialize the sensitive word instance - {}", e.getMessage()); e.printStackTrace(); } } /** * 自定义FilePath * * @param filepath */ public SensiHolder(String filepath) { this.filepath = filepath; try { List<String> lines = readLines(); this.senTrie = new SenTrie(new HashSet<>(lines)); this.lines = lines; logger.info("The current sensitive word text source comes from - {}", filepath); } catch (IOException e) { logger.error("Failed to initialize the sensitive word instance - {}", e.getMessage()); e.printStackTrace(); } } /** * 读取敏感词Base64文本 * * @return * @throws IOException */ private List<String> readLines() throws IOException { List<String> lines = new ArrayList<>(); try (InputStream inputStream = getClass().getResourceAsStream(filepath)) { assert inputStream != null; try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = reader.readLine()) != null) { byte[] decode = Base64.getDecoder().decode(line); String decodedString = new String(decode, StandardCharsets.UTF_8); lines.add(decodedString); } } } return lines; } /** * 是否存在敏感词 * * @param input * @param ifLog * @return */ public boolean exists(String input, boolean ifLog) { input = standardizeInput(input); SenKeys senKeys = this.senTrie.findAll(input); if (!senKeys.isEmpty() && ifLog) { logger.warn("存在敏感词:{}", String.join(",", senKeys.stream().map(SenKey::getKeyword).collect(Collectors.toList()))); } return !senKeys.isEmpty(); } /** * 是否存在敏感词 * * @param input * @return */ public String existsStr(String input) { SenKeys senKeys = this.senTrie.findAll(input); if (!senKeys.isEmpty()) { return senKeys.stream().map(SenKey::getKeyword).collect(Collectors.joining(",")); } return null; } /** * 是否存在敏感词 * * @param input * @return */ public boolean exists(String input) { return exists(input, true); } /** * 是否存在敏感词 * * @param data * @return */ public boolean exists(Object data) { Objects.requireNonNull(data, "Data cannot be null"); return exists(JSON.toJSONString(data)); } /** * 替换 * * @param input * @param replaceValue * @return */ public String replace(String input, String replaceValue) { input = standardizeInput(input); SenKeys senKeys = this.senTrie.findAllIgnoreCase(input); if (senKeys.isEmpty()) { return input; }
if (StringUtil.isEmpty(replaceValue)) {
3
2023-12-28 04:50:04+00:00
8k
RoderickQiu/SUSTech_CSE_Projects
CS109_2022_Fall/Chess/view/RankFrame.java
[ { "identifier": "Main", "path": "CS109_2022_Fall/Chess/Main.java", "snippet": "public class Main {\r\n private static ChessGameFrame gameFrame = null;\r\n private static StartFrame startFrame = null;\r\n public static Font titleFont, sansFont, serifFont;\r\n public static String theme = \"像素...
import Chess.Main; import Chess.utils.ImageUtils; import com.google.gson.Gson; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import static Chess.Main.*; import static javax.swing.ListSelectionModel.SINGLE_SELECTION;
4,230
package Chess.view; public class RankFrame extends JFrame { private final int WIDTH; private final int HEIGHT; private Gson gson = new Gson(); public RankFrame(int width, int height) { setTitle("本地玩家排行"); this.WIDTH = width; this.HEIGHT = height; setSize(WIDTH, HEIGHT); setResizable(false); setLocationRelativeTo(null); // Center the window. getContentPane().setBackground(Color.WHITE); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(null); addBackButton(); addList(); addBg(); } private void addList() { ArrayList<String> arr = new ArrayList<>(); for (int i = 0; i < scoresList.size(); i++) { arr.add(" " + userList.get(i) + " " + scoresList.get(i)); } arr.sort((o1, o2) -> Integer.compare(Integer.parseInt(o2.split(" ")[2]), Integer.parseInt(o1.split(" ")[2]))); for (int i = 0; i < arr.size(); i++) { arr.set(i, " " + arr.get(i)); } JList<String> list = new JList<>(arr.toArray(new String[0])); list.setBackground(new Color(0, 0, 0, 0)); list.setOpaque(false);//workaround keep opaque after repainted list.setFont(sansFont.deriveFont(Font.PLAIN, 18)); list.setBounds(HEIGHT / 13, HEIGHT / 13 + 12, HEIGHT * 2 / 5, HEIGHT * 4 / 5); add(list); // chess board as bg workaround InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource("board")); JLabel lbBg = null; try {
package Chess.view; public class RankFrame extends JFrame { private final int WIDTH; private final int HEIGHT; private Gson gson = new Gson(); public RankFrame(int width, int height) { setTitle("本地玩家排行"); this.WIDTH = width; this.HEIGHT = height; setSize(WIDTH, HEIGHT); setResizable(false); setLocationRelativeTo(null); // Center the window. getContentPane().setBackground(Color.WHITE); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(null); addBackButton(); addList(); addBg(); } private void addList() { ArrayList<String> arr = new ArrayList<>(); for (int i = 0; i < scoresList.size(); i++) { arr.add(" " + userList.get(i) + " " + scoresList.get(i)); } arr.sort((o1, o2) -> Integer.compare(Integer.parseInt(o2.split(" ")[2]), Integer.parseInt(o1.split(" ")[2]))); for (int i = 0; i < arr.size(); i++) { arr.set(i, " " + arr.get(i)); } JList<String> list = new JList<>(arr.toArray(new String[0])); list.setBackground(new Color(0, 0, 0, 0)); list.setOpaque(false);//workaround keep opaque after repainted list.setFont(sansFont.deriveFont(Font.PLAIN, 18)); list.setBounds(HEIGHT / 13, HEIGHT / 13 + 12, HEIGHT * 2 / 5, HEIGHT * 4 / 5); add(list); // chess board as bg workaround InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource("board")); JLabel lbBg = null; try {
lbBg = new JLabel(ImageUtils.changeToOriginalSize(new ImageIcon(stream.readAllBytes()), HEIGHT * 2 / 5, HEIGHT * 4 / 5));
1
2023-12-31 05:50:13+00:00
8k
Patbox/serveruifix
src/main/java/eu/pb4/serveruifix/ModInit.java
[ { "identifier": "PolydexCompat", "path": "src/main/java/eu/pb4/serveruifix/polydex/PolydexCompat.java", "snippet": "public class PolydexCompat {\n private static final boolean IS_PRESENT = FabricLoader.getInstance().isModLoaded(\"polydex2\");\n\n\n public static void register() {\n if (IS_P...
import eu.pb4.serveruifix.polydex.PolydexCompat; import eu.pb4.serveruifix.util.GuiTextures; import eu.pb4.serveruifix.util.UiResourceCreator; import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils; import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
3,808
package eu.pb4.serveruifix; public class ModInit implements ModInitializer { public static final String ID = "serveruifix"; public static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMetadata().getVersion().getFriendlyString(); public static final Logger LOGGER = LoggerFactory.getLogger("Server Ui Fix"); public static final boolean DEV_ENV = FabricLoader.getInstance().isDevelopmentEnvironment(); public static final boolean DEV_MODE = VERSION.contains("-dev.") || DEV_ENV; @SuppressWarnings("PointlessBooleanExpression") public static final boolean DYNAMIC_ASSETS = true && DEV_ENV; public static Identifier id(String path) { return new Identifier(ID, path); } @Override public void onInitialize() { if (VERSION.contains("-dev.")) { LOGGER.warn("====================================================="); LOGGER.warn("You are using development version of ServerUiFix!"); LOGGER.warn("Support is limited, as features might be unfinished!"); LOGGER.warn("You are on your own!"); LOGGER.warn("====================================================="); }
package eu.pb4.serveruifix; public class ModInit implements ModInitializer { public static final String ID = "serveruifix"; public static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMetadata().getVersion().getFriendlyString(); public static final Logger LOGGER = LoggerFactory.getLogger("Server Ui Fix"); public static final boolean DEV_ENV = FabricLoader.getInstance().isDevelopmentEnvironment(); public static final boolean DEV_MODE = VERSION.contains("-dev.") || DEV_ENV; @SuppressWarnings("PointlessBooleanExpression") public static final boolean DYNAMIC_ASSETS = true && DEV_ENV; public static Identifier id(String path) { return new Identifier(ID, path); } @Override public void onInitialize() { if (VERSION.contains("-dev.")) { LOGGER.warn("====================================================="); LOGGER.warn("You are using development version of ServerUiFix!"); LOGGER.warn("Support is limited, as features might be unfinished!"); LOGGER.warn("You are on your own!"); LOGGER.warn("====================================================="); }
UiResourceCreator.setup();
2
2023-12-28 23:01:30+00:00
8k
psobiech/opengr8on
tftp/src/main/java/pl/psobiech/opengr8on/tftp/transfer/TFTPReceivingTransfer.java
[ { "identifier": "TFTP", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/TFTP.java", "snippet": "public class TFTP implements Closeable {\n private static final Logger LOGGER = LoggerFactory.getLogger(TFTP.class);\n\n public static final int DEFAULT_PORT = 69;\n\n static final int MIN_PAC...
import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.nio.file.Files; import java.nio.file.Path; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.psobiech.opengr8on.tftp.TFTP; import pl.psobiech.opengr8on.tftp.TFTPTransferMode; import pl.psobiech.opengr8on.tftp.exceptions.TFTPException; import pl.psobiech.opengr8on.tftp.exceptions.TFTPPacketException; import pl.psobiech.opengr8on.tftp.packets.TFTPAckPacket; import pl.psobiech.opengr8on.tftp.packets.TFTPDataPacket; import pl.psobiech.opengr8on.tftp.packets.TFTPErrorPacket; import pl.psobiech.opengr8on.tftp.packets.TFTPErrorType; import pl.psobiech.opengr8on.tftp.packets.TFTPPacket; import pl.psobiech.opengr8on.tftp.packets.TFTPRequestPacket; import pl.psobiech.opengr8on.util.FileUtil;
7,143
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.tftp.transfer; public abstract class TFTPReceivingTransfer extends TFTPTransfer { private static final Logger LOGGER = LoggerFactory.getLogger(TFTPReceivingTransfer.class); protected void incomingTransfer( TFTP tftp, boolean server, TFTPTransferMode mode, InetAddress requestAddress, int requestPort, Path targetPath
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.tftp.transfer; public abstract class TFTPReceivingTransfer extends TFTPTransfer { private static final Logger LOGGER = LoggerFactory.getLogger(TFTPReceivingTransfer.class); protected void incomingTransfer( TFTP tftp, boolean server, TFTPTransferMode mode, InetAddress requestAddress, int requestPort, Path targetPath
) throws IOException, TFTPPacketException {
3
2023-12-23 09:56:14+00:00
8k
Pigmice2733/frc-2024
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "DrivetrainConfig", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final static class DrivetrainConfig {\n public static final double MAX_DRIVE_SPEED = 4.5; // max meters / second\n public static final double MAX_TURN_SPEED = 5; // max radians / second\n pu...
import com.pigmice.frc.lib.controller_rumbler.ControllerRumbler; import com.pigmice.frc.lib.drivetrain.swerve.SwerveDrivetrain; import com.pigmice.frc.lib.drivetrain.swerve.commands.DriveWithJoysticksSwerve; import edu.wpi.first.wpilibj.GenericHID; import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj.XboxController.Button; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Commands; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.button.JoystickButton; import frc.robot.Constants.DrivetrainConfig; import frc.robot.Constants.ArmConfig.ArmState; import frc.robot.Constants.ClimberConfig.ClimberState; import frc.robot.Constants.IntakeConfig.IntakeState; import frc.robot.commands.actions.FireShooter; import frc.robot.commands.actions.HandoffToShooter; import frc.robot.subsystems.Arm; import frc.robot.subsystems.ClimberExtension; import frc.robot.subsystems.Intake; import frc.robot.subsystems.Shooter; import frc.robot.subsystems.Vision;
3,902
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since * Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in * the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of * the robot (including * subsystems, commands, and button mappings) should be declared here. */ public class RobotContainer { private final SwerveDrivetrain drivetrain = new SwerveDrivetrain(DrivetrainConfig.SWERVE_CONFIG); private final Arm arm = new Arm();
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since * Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in * the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of * the robot (including * subsystems, commands, and button mappings) should be declared here. */ public class RobotContainer { private final SwerveDrivetrain drivetrain = new SwerveDrivetrain(DrivetrainConfig.SWERVE_CONFIG); private final Arm arm = new Arm();
private final ClimberExtension climberExtension = new ClimberExtension();
7
2023-12-30 06:06:45+00:00
8k
fatorius/DUCO-Android-Miner
DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/services/MinerBackgroundService.java
[ { "identifier": "MiningActivity", "path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/activities/MiningActivity.java", "snippet": "public class MiningActivity extends AppCompatActivity { //implements UIThreadMethods {\n RequestQueue requestQueue;\n JsonObjectRequest getMiningPool...
import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.ServiceInfo; import android.os.Build; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import com.fatorius.duinocoinminer.R; import com.fatorius.duinocoinminer.activities.MiningActivity; import com.fatorius.duinocoinminer.activities.ServiceNotificationActivity; import com.fatorius.duinocoinminer.threads.MiningThread; import com.fatorius.duinocoinminer.threads.ServiceCommunicationMethods; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map;
4,112
package com.fatorius.duinocoinminer.services; public class MinerBackgroundService extends Service implements ServiceCommunicationMethods { public static final String ACTION_STOP_BACKGROUND_MINING = "com.fatorius.duinocoinminer.STOP_BACKGROUND_MINING"; private static final int NOTIFICATION_INTERVAL = 30_000; private PowerManager.WakeLock wakeLock; List<Thread> miningThreads; List<Integer> threadsHashrate; int numberOfMiningThreads; int sentShares = 0; int acceptedShares = 0; float acceptedPercetage = 0.0f; long lastNotificationSent = 0; NotificationChannel channel; PendingIntent pendingIntent; private static final int NOTIFICATION_ID = 1; @Override public void onCreate(){ super.onCreate(); channel = new NotificationChannel( "duinoCoinAndroidMinerChannel", "MinerServicesNotification", NotificationManager.IMPORTANCE_MIN ); getSystemService(NotificationManager.class).createNotificationChannel(channel); miningThreads = new ArrayList<>(); threadsHashrate = new ArrayList<>(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { assert intent != null; String action = intent.getAction(); if (MinerBackgroundService.ACTION_STOP_BACKGROUND_MINING.equals(action)) { Log.d("Miner Service", "Finishing"); stopForegroundService(); stopForeground(true); stopSelf(); return START_STICKY; } PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DuinoCoinMiner::MinerServiceWaveLock"); wakeLock.acquire(); String poolIp = intent.getStringExtra("poolIp"); String ducoUsername = intent.getStringExtra("ducoUsername"); numberOfMiningThreads = intent.getIntExtra("numberOfThreads", 0); int poolPort = intent.getIntExtra("poolPort", 0); float efficiency = intent.getFloatExtra("efficiency", 0); Log.d("Mining service", "Mining service started"); Intent notificationIntent = new Intent(this, ServiceNotificationActivity.class); pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE); Notification notification = new NotificationCompat.Builder(this, "duinoCoinAndroidMinerChannel") .setContentTitle("Duino Coin Android Miner") .setContentText("The Miner is running in the background") .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentIntent(pendingIntent) .addAction(R.drawable.ic_launcher_foreground, "Stop mining", pendingIntent) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setTicker("The Miner is running") .setOngoing(true) .setOnlyAlertOnce(true) .build(); int type = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){ type = ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC; } startForeground(NOTIFICATION_ID, notification, type); miningThreads = new ArrayList<>(); threadsHashrate = new ArrayList<>(); for (int t = 0; t < numberOfMiningThreads; t++){ Thread miningThread; try {
package com.fatorius.duinocoinminer.services; public class MinerBackgroundService extends Service implements ServiceCommunicationMethods { public static final String ACTION_STOP_BACKGROUND_MINING = "com.fatorius.duinocoinminer.STOP_BACKGROUND_MINING"; private static final int NOTIFICATION_INTERVAL = 30_000; private PowerManager.WakeLock wakeLock; List<Thread> miningThreads; List<Integer> threadsHashrate; int numberOfMiningThreads; int sentShares = 0; int acceptedShares = 0; float acceptedPercetage = 0.0f; long lastNotificationSent = 0; NotificationChannel channel; PendingIntent pendingIntent; private static final int NOTIFICATION_ID = 1; @Override public void onCreate(){ super.onCreate(); channel = new NotificationChannel( "duinoCoinAndroidMinerChannel", "MinerServicesNotification", NotificationManager.IMPORTANCE_MIN ); getSystemService(NotificationManager.class).createNotificationChannel(channel); miningThreads = new ArrayList<>(); threadsHashrate = new ArrayList<>(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { assert intent != null; String action = intent.getAction(); if (MinerBackgroundService.ACTION_STOP_BACKGROUND_MINING.equals(action)) { Log.d("Miner Service", "Finishing"); stopForegroundService(); stopForeground(true); stopSelf(); return START_STICKY; } PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DuinoCoinMiner::MinerServiceWaveLock"); wakeLock.acquire(); String poolIp = intent.getStringExtra("poolIp"); String ducoUsername = intent.getStringExtra("ducoUsername"); numberOfMiningThreads = intent.getIntExtra("numberOfThreads", 0); int poolPort = intent.getIntExtra("poolPort", 0); float efficiency = intent.getFloatExtra("efficiency", 0); Log.d("Mining service", "Mining service started"); Intent notificationIntent = new Intent(this, ServiceNotificationActivity.class); pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE); Notification notification = new NotificationCompat.Builder(this, "duinoCoinAndroidMinerChannel") .setContentTitle("Duino Coin Android Miner") .setContentText("The Miner is running in the background") .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentIntent(pendingIntent) .addAction(R.drawable.ic_launcher_foreground, "Stop mining", pendingIntent) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setTicker("The Miner is running") .setOngoing(true) .setOnlyAlertOnce(true) .build(); int type = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){ type = ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC; } startForeground(NOTIFICATION_ID, notification, type); miningThreads = new ArrayList<>(); threadsHashrate = new ArrayList<>(); for (int t = 0; t < numberOfMiningThreads; t++){ Thread miningThread; try {
miningThread = new Thread(new MiningThread(poolIp, poolPort, ducoUsername, efficiency, t, this), MiningThread.MINING_THREAD_NAME_ID);
2
2023-12-27 06:00:05+00:00
8k
fanxiaoning/framifykit
framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/executor/KD100Executor.java
[ { "identifier": "ServiceException", "path": "framifykit-starter/framifykit-common/src/main/java/com/famifykit/starter/common/exception/ServiceException.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic final class ServiceException extends RuntimeException {\n\n /**\n * 错误码\n ...
import cn.hutool.core.lang.TypeReference; import cn.hutool.core.util.ReflectUtil; import com.alibaba.fastjson.JSONObject; import com.famifykit.starter.common.exception.ServiceException; import com.famifykit.starter.common.result.FramifyResult; import com.framifykit.starter.logistics.executor.constant.LogisticsTypeEnum; import com.framifykit.starter.logistics.executor.config.ILogisticsGetConfig; import com.framifykit.starter.logistics.executor.domain.req.KD100Req; import com.framifykit.starter.logistics.executor.domain.res.KD100Res; import com.framifykit.starter.logistics.platform.kd100.client.DefaultKD100Client; import com.framifykit.starter.logistics.platform.kd100.config.KD100ApiConfig; import com.framifykit.starter.logistics.platform.kd100.config.KD100ApiConfigKit; import com.framifykit.starter.logistics.platform.kd100.domain.res.*; import com.framifykit.starter.logistics.platform.kd100.domain.res.dto.KD100CheckAddressResParam; import com.framifykit.starter.logistics.platform.kd100.domain.res.dto.KD100QueryCapacityResParam; import com.framifykit.starter.logistics.platform.kd100.util.SignUtils; import lombok.extern.slf4j.Slf4j; import java.util.Map; import static com.framifykit.starter.logistics.common.constant.LogisticsErrorCodeConstants.THIRD_PARTY_API_ERROR; import static com.framifykit.starter.logistics.platform.kd100.constant.KD100ApiConstant.*;
6,112
package com.framifykit.starter.logistics.executor; /** * <p> * 调用快递100接口执行器 * </p> * * @author fxn * @since 1.0.0 **/ @Slf4j public class KD100Executor extends AbstractLogisticsExecutor<KD100Req, KD100Res> implements ILogisticsExecutor<KD100Req, FramifyResult<KD100Res>>, ILogisticsGetConfig<KD100ApiConfig> { @Override public FramifyResult<KD100Res> execute(KD100Req KD100Req) throws ServiceException { KD100Res KD100Res; try { String methodType = KD100Req.getMethodType(); KD100Res = ReflectUtil.invoke(this, methodType, KD100Req); } catch (Exception e) {
package com.framifykit.starter.logistics.executor; /** * <p> * 调用快递100接口执行器 * </p> * * @author fxn * @since 1.0.0 **/ @Slf4j public class KD100Executor extends AbstractLogisticsExecutor<KD100Req, KD100Res> implements ILogisticsExecutor<KD100Req, FramifyResult<KD100Res>>, ILogisticsGetConfig<KD100ApiConfig> { @Override public FramifyResult<KD100Res> execute(KD100Req KD100Req) throws ServiceException { KD100Res KD100Res; try { String methodType = KD100Req.getMethodType(); KD100Res = ReflectUtil.invoke(this, methodType, KD100Req); } catch (Exception e) {
log.error("第三方物流平台:{}调用系统异常", LogisticsTypeEnum.KD_100.getName(), e);
2
2023-12-31 03:48:33+00:00
8k
yangpluseven/Simulate-Something
simulation/src/test/DisplayerTest.java
[ { "identifier": "Painter", "path": "simulation/src/interfaces/Painter.java", "snippet": "@FunctionalInterface\npublic interface Painter {\n\tpublic abstract void paint(Graphics g, int x, int y, int w, int h);\n}" }, { "identifier": "Displayer", "path": "simulation/src/simulator/Displayer.jav...
import java.awt.Color; import entities.*; import entities.painters.*; import interfaces.Painter; import simulator.Displayer; import simulator.GridMap;
4,469
package test; public class DisplayerTest { public static void main(String[] args) { Displayer displayer = new Displayer(); Line line = new Line(); line.addDirection(0, -1); line.addDirection(1, 0); SimuObject simuObjA = new Obj(Color.BLACK, line, displayer.getGridMap()); Location locationA = new Location(0, 0); simuObjA.moveTo(locationA); displayer.addObjectAt(simuObjA, locationA); SimuObject simuObjB = new Obj(Color.BLUE, new Rectangle(), displayer.getGridMap()); Location locationB = new Location(49, 29); simuObjB.moveTo(locationB); displayer.addObjectAt(simuObjB, locationB); SimuObject simuObjC = new Obj(Color.RED, new Oval(), displayer.getGridMap()); Location locationC = new Location(49, 29); simuObjC.moveTo(locationC); displayer.addObjectAt(simuObjC, locationC); simuObjA.moveTo(new Location(10, 10)); displayer.display(); } } class Obj extends SimuObject {
package test; public class DisplayerTest { public static void main(String[] args) { Displayer displayer = new Displayer(); Line line = new Line(); line.addDirection(0, -1); line.addDirection(1, 0); SimuObject simuObjA = new Obj(Color.BLACK, line, displayer.getGridMap()); Location locationA = new Location(0, 0); simuObjA.moveTo(locationA); displayer.addObjectAt(simuObjA, locationA); SimuObject simuObjB = new Obj(Color.BLUE, new Rectangle(), displayer.getGridMap()); Location locationB = new Location(49, 29); simuObjB.moveTo(locationB); displayer.addObjectAt(simuObjB, locationB); SimuObject simuObjC = new Obj(Color.RED, new Oval(), displayer.getGridMap()); Location locationC = new Location(49, 29); simuObjC.moveTo(locationC); displayer.addObjectAt(simuObjC, locationC); simuObjA.moveTo(new Location(10, 10)); displayer.display(); } } class Obj extends SimuObject {
public Obj(Color color, Painter painter, GridMap gridMap) {
0
2023-12-23 13:51:12+00:00
8k
bmarwell/sipper
impl/src/main/java/io/github/bmarwell/sipper/impl/proto/SipMessageFactory.java
[ { "identifier": "SipConfiguration", "path": "api/src/main/java/io/github/bmarwell/sipper/api/SipConfiguration.java", "snippet": "@Value.Immutable\n@Value.Style(jdkOnly = true, stagedBuilder = true)\npublic interface SipConfiguration {\n\n /**\n * Registrar is the domain of your SIP endpoint.\n ...
import io.github.bmarwell.sipper.api.SipConfiguration; import io.github.bmarwell.sipper.impl.internal.ConnectedSipConnection; import io.github.bmarwell.sipper.impl.internal.DefaultRegisteredSipConnection; import java.net.InetAddress; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.HexFormat; import java.util.Locale; import java.util.random.RandomGeneratorFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
4,065
final var cnonceBytes = new byte[12]; RandomGeneratorFactory.getDefault().create().nextBytes(cnonceBytes); final var cnonce = base64enc.encodeToString(cnonceBytes); try { // hash1: base64(md5(user:realm:pw)) final var h1md5 = MessageDigest.getInstance( sipAuthenticationRequest.algorithm().toLowerCase(Locale.ROOT)); final var hash1Contents = (loginUserId + ":" + sipAuthenticationRequest.realm() + ":" + loginPassword) .getBytes(StandardCharsets.UTF_8); final var hash1 = base64enc.encodeToString(h1md5.digest(hash1Contents)); // hash2: base64(md5(sipmethod:uri)) final var h2md5 = MessageDigest.getInstance( sipAuthenticationRequest.algorithm().toLowerCase(Locale.ROOT)); final var hash2Contents = ("REGISTER:" + uri).getBytes(StandardCharsets.UTF_8); final var hash2 = base64enc.encodeToString(h2md5.digest(hash2Contents)); // hash3: base64(md5(hash1:nonce:nc:cnonce:qop:hash2)) final var h3md5 = MessageDigest.getInstance( sipAuthenticationRequest.algorithm().toLowerCase(Locale.ROOT)); final var h3Contents = (hash1 + ":" + sipAuthenticationRequest.nonce() + ":" + ncHex + ":" + cnonce + ":" + qop + ":" + hash2) .getBytes(StandardCharsets.UTF_8); final var hashResponse = base64enc.encodeToString(h3md5.digest(h3Contents)); return new AuthorizationResponse(hashResponse, cnonce); } catch (NoSuchAlgorithmException nsae) { LOG.error("Problem with login algorithm", nsae); throw new IllegalArgumentException( "Problem with login algorithm: " + sipAuthenticationRequest.algorithm(), nsae); } } public LoginRequest getLogin( SipAuthenticationRequest sipAuthenticationRequest, ConnectedSipConnection sipConnection, String loginUserId, String loginPassword) { final var qop = "auth"; final var nc = 1L; final var ncHex = HexFormat.of().toHexDigits(nc, 8); final var authorizationResponse = getAuthorizationString(sipAuthenticationRequest, this.registrar, nc, qop, loginUserId, loginPassword); final var authValue = String.format( Locale.ROOT, "Digest realm=\"%1$s\", nonce=\"%2$s\", algorithm=%3$s, username=\"%4$s\", uri=\"sip:%5$s\", response=\"%6$s\", cnonce=\"%8$s\", nc=%8$s, qop=%9$s", // 1 - realm sipAuthenticationRequest.realm(), // 2 - nonce sipAuthenticationRequest.nonce(), // 3 - algorithm sipAuthenticationRequest.algorithm(), // 4 - username loginUserId, // 5 - registrar this.registrar, // 6 - response (see #getAuthorizationString) authorizationResponse.response(), // 7 - client nonce authorizationResponse.clientNonce(), // 8 - nc ncHex, // 9 - qop qop // end ); String template = """ %1$s sip:%2$s SIP/2.0 Via: SIP/2.0/TCP %8$s:%7$s;alias;branch=z9hG4bK.8i7nkaF9s;rport From: <sip:%3$s@%2$s>;tag=%4$s To: sip:%3$s@%2$s CSeq: %9$s %1$s Call-ID: %5$s Max-Forwards: 70 Supported: replaces, outbound, gruu, path, record-aware Contact: <sip:%3$s@%6$s:%7$s;transport=tcp> Expires: 600 User-Agent: SIPper/0.1.0 Content-Length: 0 Authorization: %10$s """; final var register = String.format( // Locale.ROOT, template, // 1 - method "REGISTER", // 2- registrar this.registrar, // 3 - sipID this.sipId, // 4 - tag sipConnection.getTag(), // 5 - CallId sipConnection.getCallId(), // 6 - public IP sipConnection.getPublicIp().getHostAddress(), // 7 - socket local port sipConnection.getSocket().getLocalPort(), // 8 - socket local address sipConnection.getSocket().getLocalAddress().getHostAddress(), // 9 - CSeq sipConnection.getAndUpdateCseq(), // 10 - authValue authValue // end ); return new LoginRequest(register, authValue); }
/* * Copyright (C) 2023-2024 The SIPper project team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.bmarwell.sipper.impl.proto; public class SipMessageFactory { private static final Logger LOG = LoggerFactory.getLogger(SipMessageFactory.class); private final String registrar; private final String sipId; public SipMessageFactory(SipConfiguration conf) { this.registrar = conf.getRegistrar(); this.sipId = conf.getSipId(); } public SipMessageFactory(String registrar, String sipId) { this.registrar = registrar; this.sipId = sipId; } public String getRegisterPreflight(ConnectedSipConnection sipConnection) { final var template = """ %1$s sip:%2$s SIP/2.0 CSeq: %9$s %1$s Via: SIP/2.0/TCP %8$s:%7$s;alias;branch=z9hG4bK.8i7nkaF9s;rport From: <sip:%3$s@%2$s>;tag=%4$s To: sip:%3$s@%2$s Call-ID: %5$s Max-Forwards: 70 Supported: replaces, outbound, gruu, path, record-aware Contact: <sip:%3$s@%6$s:%7$s;transport=tcp>;q=1 Expires: 600 User-Agent: SIPper/0.1.0 Content-Length: 0 """; return String.format( // Locale.ROOT, template, // 1 - method "REGISTER", // 2- registrar this.registrar, // 3 - sipID this.sipId, // 4 - tag sipConnection.getTag(), // 5 - CallId sipConnection.getCallId(), // 6 - public IP sipConnection.getPublicIp().getHostAddress(), // 7 - socket local port sipConnection.getSocket().getLocalPort(), // 8 - socket local address sipConnection.getSocket().getLocalAddress().getHostAddress(), // 9 - CSeq sipConnection.getAndUpdateCseq()); } private AuthorizationResponse getAuthorizationString( SipAuthenticationRequest sipAuthenticationRequest, String uri, long nc, String qop, String loginUserId, String loginPassword) { final var ncHex = HexFormat.of().toHexDigits(nc, 6); final var base64enc = Base64.getEncoder(); final var cnonceBytes = new byte[12]; RandomGeneratorFactory.getDefault().create().nextBytes(cnonceBytes); final var cnonce = base64enc.encodeToString(cnonceBytes); try { // hash1: base64(md5(user:realm:pw)) final var h1md5 = MessageDigest.getInstance( sipAuthenticationRequest.algorithm().toLowerCase(Locale.ROOT)); final var hash1Contents = (loginUserId + ":" + sipAuthenticationRequest.realm() + ":" + loginPassword) .getBytes(StandardCharsets.UTF_8); final var hash1 = base64enc.encodeToString(h1md5.digest(hash1Contents)); // hash2: base64(md5(sipmethod:uri)) final var h2md5 = MessageDigest.getInstance( sipAuthenticationRequest.algorithm().toLowerCase(Locale.ROOT)); final var hash2Contents = ("REGISTER:" + uri).getBytes(StandardCharsets.UTF_8); final var hash2 = base64enc.encodeToString(h2md5.digest(hash2Contents)); // hash3: base64(md5(hash1:nonce:nc:cnonce:qop:hash2)) final var h3md5 = MessageDigest.getInstance( sipAuthenticationRequest.algorithm().toLowerCase(Locale.ROOT)); final var h3Contents = (hash1 + ":" + sipAuthenticationRequest.nonce() + ":" + ncHex + ":" + cnonce + ":" + qop + ":" + hash2) .getBytes(StandardCharsets.UTF_8); final var hashResponse = base64enc.encodeToString(h3md5.digest(h3Contents)); return new AuthorizationResponse(hashResponse, cnonce); } catch (NoSuchAlgorithmException nsae) { LOG.error("Problem with login algorithm", nsae); throw new IllegalArgumentException( "Problem with login algorithm: " + sipAuthenticationRequest.algorithm(), nsae); } } public LoginRequest getLogin( SipAuthenticationRequest sipAuthenticationRequest, ConnectedSipConnection sipConnection, String loginUserId, String loginPassword) { final var qop = "auth"; final var nc = 1L; final var ncHex = HexFormat.of().toHexDigits(nc, 8); final var authorizationResponse = getAuthorizationString(sipAuthenticationRequest, this.registrar, nc, qop, loginUserId, loginPassword); final var authValue = String.format( Locale.ROOT, "Digest realm=\"%1$s\", nonce=\"%2$s\", algorithm=%3$s, username=\"%4$s\", uri=\"sip:%5$s\", response=\"%6$s\", cnonce=\"%8$s\", nc=%8$s, qop=%9$s", // 1 - realm sipAuthenticationRequest.realm(), // 2 - nonce sipAuthenticationRequest.nonce(), // 3 - algorithm sipAuthenticationRequest.algorithm(), // 4 - username loginUserId, // 5 - registrar this.registrar, // 6 - response (see #getAuthorizationString) authorizationResponse.response(), // 7 - client nonce authorizationResponse.clientNonce(), // 8 - nc ncHex, // 9 - qop qop // end ); String template = """ %1$s sip:%2$s SIP/2.0 Via: SIP/2.0/TCP %8$s:%7$s;alias;branch=z9hG4bK.8i7nkaF9s;rport From: <sip:%3$s@%2$s>;tag=%4$s To: sip:%3$s@%2$s CSeq: %9$s %1$s Call-ID: %5$s Max-Forwards: 70 Supported: replaces, outbound, gruu, path, record-aware Contact: <sip:%3$s@%6$s:%7$s;transport=tcp> Expires: 600 User-Agent: SIPper/0.1.0 Content-Length: 0 Authorization: %10$s """; final var register = String.format( // Locale.ROOT, template, // 1 - method "REGISTER", // 2- registrar this.registrar, // 3 - sipID this.sipId, // 4 - tag sipConnection.getTag(), // 5 - CallId sipConnection.getCallId(), // 6 - public IP sipConnection.getPublicIp().getHostAddress(), // 7 - socket local port sipConnection.getSocket().getLocalPort(), // 8 - socket local address sipConnection.getSocket().getLocalAddress().getHostAddress(), // 9 - CSeq sipConnection.getAndUpdateCseq(), // 10 - authValue authValue // end ); return new LoginRequest(register, authValue); }
public String getUnregister(DefaultRegisteredSipConnection registeredSipConnection) {
2
2023-12-28 13:13:07+00:00
8k
HChenX/HideCleanUp
app/src/main/java/com/hchen/hidecleanup/HookMain.java
[ { "identifier": "HideCleanUp", "path": "app/src/main/java/com/hchen/hidecleanup/hideCleanUp/HideCleanUp.java", "snippet": "public class HideCleanUp extends Hook {\n\n @Override\n public void init() {\n hookAllMethods(\"com.miui.home.recents.views.RecentsContainer\",\n \"onFin...
import com.hchen.hidecleanup.hideCleanUp.HideCleanUp; import com.hchen.hidecleanup.hook.Hook; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
4,651
package com.hchen.hidecleanup; public class HookMain implements IXposedHookLoadPackage { @Override public void handleLoadPackage(LoadPackageParam lpparam) { if ("com.miui.home".equals(lpparam.packageName)) {
package com.hchen.hidecleanup; public class HookMain implements IXposedHookLoadPackage { @Override public void handleLoadPackage(LoadPackageParam lpparam) { if ("com.miui.home".equals(lpparam.packageName)) {
initHook(new HideCleanUp(), lpparam);
0
2023-12-24 13:57:39+00:00
8k
Prototik/TheConfigLib
common/src/main/java/dev/tcl/gui/controllers/dropdown/EnumDropdownController.java
[ { "identifier": "Option", "path": "common/src/main/java/dev/tcl/api/Option.java", "snippet": "public interface Option<T> {\n /**\n * Name of the option\n */\n @NotNull Component name();\n\n @NotNull OptionDescription description();\n\n /**\n * Widget provider for a type of option...
import dev.tcl.api.Option; import dev.tcl.api.utils.Dimension; import dev.tcl.api.controller.ValueFormatter; import dev.tcl.gui.AbstractWidget; import dev.tcl.gui.TCLScreen; import net.minecraft.network.chat.Component; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Collection; import java.util.stream.Stream;
6,111
package dev.tcl.gui.controllers.dropdown; public class EnumDropdownController<E extends Enum<E>> extends AbstractDropdownController<E> { /** * The function used to convert enum constants to strings used for display, suggestion, and validation. Defaults to {@link Enum#toString}. */ protected final ValueFormatter<E> formatter; public EnumDropdownController(Option<E> option, ValueFormatter<E> formatter, Collection<? extends E> values) { super(option, (values == null ? Arrays.stream(option.pendingValue().getDeclaringClass().getEnumConstants()) : values.stream()).map(formatter::format).map(Component::getString).toList()); this.formatter = formatter; } @Override public String getString() { return formatter.format(option().pendingValue()).getString(); } @Override public void setFromString(String value) { option().requestSet(getEnumFromString(value)); } /** * Searches through enum constants for one whose {@link #formatter} result equals {@code value} * * @return The enum constant associated with the {@code value} or the pending value if none are found * @implNote The return value of {@link #formatter} on each enum constant should be unique in order to ensure accuracy */ private E getEnumFromString(String value) { value = value.toLowerCase(); for (E constant : option().pendingValue().getDeclaringClass().getEnumConstants()) { if (formatter.format(constant).getString().toLowerCase().equals(value)) return constant; } return option().pendingValue(); } @Override public boolean isValueValid(String value) { value = value.toLowerCase(); for (String constant : getAllowedValues()) { if (constant.equals(value)) return true; } return false; } @Override protected String getValidValue(String value, int offset) { return getValidEnumConstants(value) .skip(offset) .findFirst() .orElseGet(this::getString); } /** * Filters and sorts through enum constants for those whose {@link #formatter} result equals {@code value} * * @return a sorted stream containing enum constants associated with the {@code value} * @implNote The return value of {@link #formatter} on each enum constant should be unique in order to ensure accuracy */ @NotNull protected Stream<String> getValidEnumConstants(String value) { String valueLowerCase = value.toLowerCase(); return getAllowedValues().stream() .filter(constant -> constant.toLowerCase().contains(valueLowerCase)) .sorted((s1, s2) -> { String s1LowerCase = s1.toLowerCase(); String s2LowerCase = s2.toLowerCase(); if (s1LowerCase.startsWith(valueLowerCase) && !s2LowerCase.startsWith(valueLowerCase)) return -1; if (!s1LowerCase.startsWith(valueLowerCase) && s2LowerCase.startsWith(valueLowerCase)) return 1; return s1.compareTo(s2); }); } @Override
package dev.tcl.gui.controllers.dropdown; public class EnumDropdownController<E extends Enum<E>> extends AbstractDropdownController<E> { /** * The function used to convert enum constants to strings used for display, suggestion, and validation. Defaults to {@link Enum#toString}. */ protected final ValueFormatter<E> formatter; public EnumDropdownController(Option<E> option, ValueFormatter<E> formatter, Collection<? extends E> values) { super(option, (values == null ? Arrays.stream(option.pendingValue().getDeclaringClass().getEnumConstants()) : values.stream()).map(formatter::format).map(Component::getString).toList()); this.formatter = formatter; } @Override public String getString() { return formatter.format(option().pendingValue()).getString(); } @Override public void setFromString(String value) { option().requestSet(getEnumFromString(value)); } /** * Searches through enum constants for one whose {@link #formatter} result equals {@code value} * * @return The enum constant associated with the {@code value} or the pending value if none are found * @implNote The return value of {@link #formatter} on each enum constant should be unique in order to ensure accuracy */ private E getEnumFromString(String value) { value = value.toLowerCase(); for (E constant : option().pendingValue().getDeclaringClass().getEnumConstants()) { if (formatter.format(constant).getString().toLowerCase().equals(value)) return constant; } return option().pendingValue(); } @Override public boolean isValueValid(String value) { value = value.toLowerCase(); for (String constant : getAllowedValues()) { if (constant.equals(value)) return true; } return false; } @Override protected String getValidValue(String value, int offset) { return getValidEnumConstants(value) .skip(offset) .findFirst() .orElseGet(this::getString); } /** * Filters and sorts through enum constants for those whose {@link #formatter} result equals {@code value} * * @return a sorted stream containing enum constants associated with the {@code value} * @implNote The return value of {@link #formatter} on each enum constant should be unique in order to ensure accuracy */ @NotNull protected Stream<String> getValidEnumConstants(String value) { String valueLowerCase = value.toLowerCase(); return getAllowedValues().stream() .filter(constant -> constant.toLowerCase().contains(valueLowerCase)) .sorted((s1, s2) -> { String s1LowerCase = s1.toLowerCase(); String s2LowerCase = s2.toLowerCase(); if (s1LowerCase.startsWith(valueLowerCase) && !s2LowerCase.startsWith(valueLowerCase)) return -1; if (!s1LowerCase.startsWith(valueLowerCase) && s2LowerCase.startsWith(valueLowerCase)) return 1; return s1.compareTo(s2); }); } @Override
public AbstractWidget provideWidget(TCLScreen screen, Dimension<Integer> widgetDimension) {
3
2023-12-25 14:48:27+00:00
8k
behnamnasehi/playsho
app/src/main/java/com/playsho/android/base/BaseActivity.java
[ { "identifier": "ActivityLauncher", "path": "app/src/main/java/com/playsho/android/component/ActivityLauncher.java", "snippet": "public class ActivityLauncher<Input, Result> {\n /**\n * Register activity result using a {@link ActivityResultContract} and an in-place activity result callback like\n...
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.os.Bundle; import androidx.activity.OnBackPressedCallback; import androidx.activity.result.ActivityResult; import androidx.annotation.ColorRes; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import com.playsho.android.component.ActivityLauncher; import com.playsho.android.db.SessionStorage; import com.playsho.android.utils.NetworkListener; import com.playsho.android.utils.SystemUtilities;
4,880
package com.playsho.android.base; /** * A base activity class that provides common functionality and structure for other activities. * * @param <B> The type of ViewDataBinding used by the activity. */ public abstract class BaseActivity<B extends ViewDataBinding> extends AppCompatActivity { // Flag to enable or disable the custom back press callback private boolean isBackPressCallbackEnable = false; /** * Abstract method to get the layout resource ID for the activity. * * @return The layout resource ID. */ protected abstract int getLayoutResourceId(); /** * Abstract method to handle custom behavior on back press. */ protected abstract void onBackPress(); // View binding instance protected B binding; protected NetworkListener networkListener; // Activity launcher instance protected final ActivityLauncher<Intent, ActivityResult> activityLauncher = ActivityLauncher.registerActivityForResult(this); // Tag for logging protected String TAG = this.getClass().getSimpleName(); /** * Gets a String extra from the Intent. * * @param key The key of the extra. * @return The String extra value. */ protected String getIntentStringExtra(String key) { return getIntent().getStringExtra(key); } /** * Gets the name of the current activity. * * @return The name of the activity. */ protected String getClassName() { return this.getClass().getSimpleName(); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); binding = DataBindingUtil.setContentView(this, getLayoutResourceId()); networkListener = new NetworkListener(); getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback); } @Override protected void onDestroy() { super.onDestroy(); onBackPressedCallback.remove(); } private final OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(isBackPressCallbackEnable) { @Override public void handleOnBackPressed() { // Call the abstract method for custom back press handling onBackPress(); } }; /** * Sets whether the custom back press callback is enabled or disabled. * * @param isBackPressCallbackEnable {@code true} to enable the callback, {@code false} to disable it. */ public void setBackPressedCallBackEnable(boolean isBackPressCallbackEnable) { this.isBackPressCallbackEnable = isBackPressCallbackEnable; } /** * Sets the status bar color using the SystemUtilities class. * * @param color The color resource ID. * @param isDark {@code true} if the status bar icons should be dark, {@code false} otherwise. */ protected void setStatusBarColor(@ColorRes int color, boolean isDark) {
package com.playsho.android.base; /** * A base activity class that provides common functionality and structure for other activities. * * @param <B> The type of ViewDataBinding used by the activity. */ public abstract class BaseActivity<B extends ViewDataBinding> extends AppCompatActivity { // Flag to enable or disable the custom back press callback private boolean isBackPressCallbackEnable = false; /** * Abstract method to get the layout resource ID for the activity. * * @return The layout resource ID. */ protected abstract int getLayoutResourceId(); /** * Abstract method to handle custom behavior on back press. */ protected abstract void onBackPress(); // View binding instance protected B binding; protected NetworkListener networkListener; // Activity launcher instance protected final ActivityLauncher<Intent, ActivityResult> activityLauncher = ActivityLauncher.registerActivityForResult(this); // Tag for logging protected String TAG = this.getClass().getSimpleName(); /** * Gets a String extra from the Intent. * * @param key The key of the extra. * @return The String extra value. */ protected String getIntentStringExtra(String key) { return getIntent().getStringExtra(key); } /** * Gets the name of the current activity. * * @return The name of the activity. */ protected String getClassName() { return this.getClass().getSimpleName(); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); binding = DataBindingUtil.setContentView(this, getLayoutResourceId()); networkListener = new NetworkListener(); getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback); } @Override protected void onDestroy() { super.onDestroy(); onBackPressedCallback.remove(); } private final OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(isBackPressCallbackEnable) { @Override public void handleOnBackPressed() { // Call the abstract method for custom back press handling onBackPress(); } }; /** * Sets whether the custom back press callback is enabled or disabled. * * @param isBackPressCallbackEnable {@code true} to enable the callback, {@code false} to disable it. */ public void setBackPressedCallBackEnable(boolean isBackPressCallbackEnable) { this.isBackPressCallbackEnable = isBackPressCallbackEnable; } /** * Sets the status bar color using the SystemUtilities class. * * @param color The color resource ID. * @param isDark {@code true} if the status bar icons should be dark, {@code false} otherwise. */ protected void setStatusBarColor(@ColorRes int color, boolean isDark) {
SystemUtilities.changeStatusBarBackgroundColor(activity(), color, isDark);
3
2023-12-26 08:14:29+00:00
8k
lunasaw/voglander
voglander-service/src/main/java/io/github/lunasaw/voglander/service/login/DeviceRegisterServiceImpl.java
[ { "identifier": "DeviceChannelReq", "path": "voglander-client/src/main/java/io/github/lunasaw/voglander/client/domain/qo/DeviceChannelReq.java", "snippet": "@Data\npublic class DeviceChannelReq {\n\n /**\n * 设备Id\n */\n private String deviceId;\n\n /**\n * 通道Id\n */\n private...
import io.github.lunasaw.voglander.client.domain.qo.DeviceChannelReq; import io.github.lunasaw.voglander.client.domain.qo.DeviceInfoReq; import io.github.lunasaw.voglander.client.domain.qo.DeviceQueryReq; import io.github.lunasaw.voglander.client.domain.qo.DeviceReq; import io.github.lunasaw.voglander.client.service.DeviceCommandService; import io.github.lunasaw.voglander.client.service.DeviceRegisterService; import io.github.lunasaw.voglander.common.constant.DeviceConstant; import io.github.lunasaw.voglander.manager.domaon.dto.DeviceChannelDTO; import io.github.lunasaw.voglander.manager.domaon.dto.DeviceDTO; import io.github.lunasaw.voglander.manager.manager.DeviceChannelManager; import io.github.lunasaw.voglander.manager.manager.DeviceManager; import io.github.lunasaw.voglander.service.command.DeviceAgreementService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import java.util.Date;
4,736
package io.github.lunasaw.voglander.service.login; /** * @author luna * @date 2023/12/29 */ @Slf4j @Service public class DeviceRegisterServiceImpl implements DeviceRegisterService { @Autowired private DeviceManager deviceManager; @Autowired private DeviceChannelManager deviceChannelManager; @Autowired
package io.github.lunasaw.voglander.service.login; /** * @author luna * @date 2023/12/29 */ @Slf4j @Service public class DeviceRegisterServiceImpl implements DeviceRegisterService { @Autowired private DeviceManager deviceManager; @Autowired private DeviceChannelManager deviceChannelManager; @Autowired
private DeviceAgreementService deviceAgreementService;
11
2023-12-27 07:28:18+00:00
8k
GrailStack/grail-codegen
src/main/java/com/itgrail/grail/codegen/custom/grailddd/GrailDddTemplate.java
[ { "identifier": "GrailFrameworkGenRequest", "path": "src/main/java/com/itgrail/grail/codegen/custom/grailframework/dto/GrailFrameworkGenRequest.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class GrailFrameworkGenRequest extends TemplateGenRequest {\n\n private String javaVersion;\n p...
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.itgrail.grail.codegen.custom.grailframework.dto.GrailFrameworkGenRequest; import com.itgrail.grail.codegen.custom.grailframework.dto.SubModuleDTO; import com.itgrail.grail.codegen.custom.grailframework.metadata.GrailFrameworkMetadata; import com.itgrail.grail.codegen.custom.grailframework.metadata.GrailVersionMetaData; import com.itgrail.grail.codegen.custom.grailframework.model.DomainDataModel; import com.itgrail.grail.codegen.custom.grailframework.model.GrailFrameworkDataModel; import com.itgrail.grail.codegen.utils.CommonUtil; import com.itgrail.grail.codegen.utils.PropertiesUtils; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import com.itgrail.grail.codegen.components.db.DbDataModel; import com.itgrail.grail.codegen.components.db.database.DBProperties; import com.itgrail.grail.codegen.components.db.database.Database; import com.itgrail.grail.codegen.components.db.database.DatabaseFactory; import com.itgrail.grail.codegen.components.db.database.DbMetaData; import com.itgrail.grail.codegen.components.db.model.Table; import com.itgrail.grail.codegen.template.custom.CustomizedTemplate; import com.itgrail.grail.codegen.template.custom.ModuleMetaData; import com.itgrail.grail.codegen.template.datamodel.CodeGenDataModel; import com.itgrail.grail.codegen.template.datamodel.MavenModuleDataModel; import com.itgrail.grail.codegen.template.datamodel.MavenProjectDataModel; import com.itgrail.grail.codegen.template.datamodel.ModuleDependencyModel; import java.util.List; import java.util.Map;
5,230
} } subModules.add(moduleMetaData1); subModules.add(moduleMetaData2); subModules.add(moduleMetaData3); return subModules; } @Override public List<String> getSubModules() { return Lists.newArrayList("client","core","start"); } @Override public ModuleMetaData getParentModule() { ModuleMetaData moduleMetaData = new ModuleMetaData(); String json=PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)){ List<ModuleDependencyModel> list = JSON.parseArray(json,ModuleDependencyModel.class); for (ModuleDependencyModel mo:list) { if("parent".equals(mo.getModulekey())){ moduleMetaData.setDependencys(mo.getDependencyModels()); moduleMetaData.setPackagingTypes(Lists.newArrayList("pom")); } } } return moduleMetaData; } @Override public String getTemplateLocatePath() { return getBasePath() + getTemplateName().toLowerCase(); } @Override public GrailFrameworkMetadata getTemplateMetadata() { GrailFrameworkMetadata metadata = new GrailFrameworkMetadata(); metadata.setTemplateName(getTemplateName()); metadata.setGrailVersions(getGrailVersionMetaDataList()); metadata.setSubModules(initSubModules()); metadata.setParentModule(getParentModule()); metadata.setDatabases(getDbMetaDataList()); return metadata; } protected List<DbMetaData> getDbMetaDataList() { DbMetaData dbMetaData = new DbMetaData(); dbMetaData.setDbType("MySql"); return Lists.newArrayList(dbMetaData); } protected List<GrailVersionMetaData> getGrailVersionMetaDataList() { GrailVersionMetaData grailVersionMetaData = new GrailVersionMetaData(); grailVersionMetaData.setGrailFrameworkVersion("1.0.0.RELEASE"); grailVersionMetaData.setJavaVersion("1.8"); grailVersionMetaData.setSpringBootVersion("2.4.1"); grailVersionMetaData.setSpringCloudVersion("2020.0.0"); GrailVersionMetaData grailVersionMetaData2 = new GrailVersionMetaData(); grailVersionMetaData2.setGrailFrameworkVersion("1.0.0-SNAPSHOT"); grailVersionMetaData2.setJavaVersion("1.8"); grailVersionMetaData2.setSpringBootVersion("2.4.1"); grailVersionMetaData2.setSpringCloudVersion("2020.0.0"); return Lists.newArrayList(grailVersionMetaData, grailVersionMetaData2); } @Override public CodeGenDataModel convert(Map<String, Object> request) throws IllegalArgumentException { GrailFrameworkGenRequest genRequest = check(request); GrailFrameworkDataModel dataModel = new GrailFrameworkDataModel(); dataModel.setTemplateName(genRequest.getTemplateName()); dataModel.setGrailFrameworkVersion(genRequest.getGrailFrameworkVersion()); dataModel.setJavaVersion("1.8"); MavenProjectDataModel project = new MavenProjectDataModel(); dataModel.setProject(project); project.setGroupId(genRequest.getGroupId()); project.setArtifactId(genRequest.getArtifactId()); project.setDescription(genRequest.getDescription()); project.setBasePackage(genRequest.getBasePackage()); if(null!=genRequest.getDbModel()){ project.setDbConfigure(true); } //处理依赖 List<ModuleDependencyModel> moduleDependencyModels=genRequest.getModuleDependencyModels(); if(null==moduleDependencyModels||moduleDependencyModels.isEmpty()){ String json=PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)) { List<ModuleDependencyModel> list = JSON.parseArray(json, ModuleDependencyModel.class); project.setDependencies(list); } }else{ project.setDependencies(moduleDependencyModels); } project.setSubModules(Maps.newHashMap()); for (SubModuleDTO subModuleDTO : genRequest.getSubModules()) { String subModuleName = subModuleDTO.getSubModuleName(); MavenModuleDataModel subModule = new MavenModuleDataModel(); subModule.setModuleName(subModuleName); subModule.setArtifactId(genRequest.getArtifactId() + "-" + subModuleName); subModule.setGroupId(genRequest.getGroupId()); subModule.setBasePackage(genRequest.getBasePackage() + "." + subModuleName); subModule.setPackaging(subModuleDTO.getPackaging()); project.getSubModules().put(subModuleName, subModule); } if (genRequest.getDomain() != null) { DomainDataModel domainDataModel = new DomainDataModel(); domainDataModel.setCode(genRequest.getDomain().getCode()); domainDataModel.setParentCode(genRequest.getDomain().getParentCode()); domainDataModel.setName(genRequest.getDomain().getName()); domainDataModel.setDesc(genRequest.getDomain().getDesc()); dataModel.setDomain(domainDataModel); } if (genRequest.getDbModel() != null) {
package com.itgrail.grail.codegen.custom.grailddd; /** * @author yage.luan * created at 2019/5/24 20:50 **/ @Component public class GrailDddTemplate extends CustomizedTemplate { @Override public String getTemplateName() { return "grailDdd"; } @Override public List<ModuleMetaData> initSubModules() { List<ModuleMetaData> subModules = Lists.newArrayList(); ModuleMetaData moduleMetaData1=new ModuleMetaData().setSubModuleName("client").setPackagingTypes(Lists.newArrayList("jar")); ModuleMetaData moduleMetaData2 = new ModuleMetaData().setSubModuleName("core").setPackagingTypes(Lists.newArrayList("jar")); ModuleMetaData moduleMetaData3= new ModuleMetaData().setSubModuleName("start").setPackagingTypes(Lists.newArrayList("jar", "war")); String json= PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)){ List<ModuleDependencyModel> list = JSON.parseArray(json,ModuleDependencyModel.class); for (ModuleDependencyModel mo:list) { if("client".equals(mo.getModulekey())){ moduleMetaData1.setDependencys(mo.getDependencyModels()); } if("core".equals(mo.getModulekey())){ moduleMetaData2.setDependencys(mo.getDependencyModels()); } if("start".equals(mo.getModulekey())){ moduleMetaData3.setDependencys(mo.getDependencyModels()); } } } subModules.add(moduleMetaData1); subModules.add(moduleMetaData2); subModules.add(moduleMetaData3); return subModules; } @Override public List<String> getSubModules() { return Lists.newArrayList("client","core","start"); } @Override public ModuleMetaData getParentModule() { ModuleMetaData moduleMetaData = new ModuleMetaData(); String json=PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)){ List<ModuleDependencyModel> list = JSON.parseArray(json,ModuleDependencyModel.class); for (ModuleDependencyModel mo:list) { if("parent".equals(mo.getModulekey())){ moduleMetaData.setDependencys(mo.getDependencyModels()); moduleMetaData.setPackagingTypes(Lists.newArrayList("pom")); } } } return moduleMetaData; } @Override public String getTemplateLocatePath() { return getBasePath() + getTemplateName().toLowerCase(); } @Override public GrailFrameworkMetadata getTemplateMetadata() { GrailFrameworkMetadata metadata = new GrailFrameworkMetadata(); metadata.setTemplateName(getTemplateName()); metadata.setGrailVersions(getGrailVersionMetaDataList()); metadata.setSubModules(initSubModules()); metadata.setParentModule(getParentModule()); metadata.setDatabases(getDbMetaDataList()); return metadata; } protected List<DbMetaData> getDbMetaDataList() { DbMetaData dbMetaData = new DbMetaData(); dbMetaData.setDbType("MySql"); return Lists.newArrayList(dbMetaData); } protected List<GrailVersionMetaData> getGrailVersionMetaDataList() { GrailVersionMetaData grailVersionMetaData = new GrailVersionMetaData(); grailVersionMetaData.setGrailFrameworkVersion("1.0.0.RELEASE"); grailVersionMetaData.setJavaVersion("1.8"); grailVersionMetaData.setSpringBootVersion("2.4.1"); grailVersionMetaData.setSpringCloudVersion("2020.0.0"); GrailVersionMetaData grailVersionMetaData2 = new GrailVersionMetaData(); grailVersionMetaData2.setGrailFrameworkVersion("1.0.0-SNAPSHOT"); grailVersionMetaData2.setJavaVersion("1.8"); grailVersionMetaData2.setSpringBootVersion("2.4.1"); grailVersionMetaData2.setSpringCloudVersion("2020.0.0"); return Lists.newArrayList(grailVersionMetaData, grailVersionMetaData2); } @Override public CodeGenDataModel convert(Map<String, Object> request) throws IllegalArgumentException { GrailFrameworkGenRequest genRequest = check(request); GrailFrameworkDataModel dataModel = new GrailFrameworkDataModel(); dataModel.setTemplateName(genRequest.getTemplateName()); dataModel.setGrailFrameworkVersion(genRequest.getGrailFrameworkVersion()); dataModel.setJavaVersion("1.8"); MavenProjectDataModel project = new MavenProjectDataModel(); dataModel.setProject(project); project.setGroupId(genRequest.getGroupId()); project.setArtifactId(genRequest.getArtifactId()); project.setDescription(genRequest.getDescription()); project.setBasePackage(genRequest.getBasePackage()); if(null!=genRequest.getDbModel()){ project.setDbConfigure(true); } //处理依赖 List<ModuleDependencyModel> moduleDependencyModels=genRequest.getModuleDependencyModels(); if(null==moduleDependencyModels||moduleDependencyModels.isEmpty()){ String json=PropertiesUtils.readJsonFile("json/"+getTemplateName()+".json"); if(StringUtils.isNotEmpty(json)) { List<ModuleDependencyModel> list = JSON.parseArray(json, ModuleDependencyModel.class); project.setDependencies(list); } }else{ project.setDependencies(moduleDependencyModels); } project.setSubModules(Maps.newHashMap()); for (SubModuleDTO subModuleDTO : genRequest.getSubModules()) { String subModuleName = subModuleDTO.getSubModuleName(); MavenModuleDataModel subModule = new MavenModuleDataModel(); subModule.setModuleName(subModuleName); subModule.setArtifactId(genRequest.getArtifactId() + "-" + subModuleName); subModule.setGroupId(genRequest.getGroupId()); subModule.setBasePackage(genRequest.getBasePackage() + "." + subModuleName); subModule.setPackaging(subModuleDTO.getPackaging()); project.getSubModules().put(subModuleName, subModule); } if (genRequest.getDomain() != null) { DomainDataModel domainDataModel = new DomainDataModel(); domainDataModel.setCode(genRequest.getDomain().getCode()); domainDataModel.setParentCode(genRequest.getDomain().getParentCode()); domainDataModel.setName(genRequest.getDomain().getName()); domainDataModel.setDesc(genRequest.getDomain().getDesc()); dataModel.setDomain(domainDataModel); } if (genRequest.getDbModel() != null) {
DbDataModel dbDataModel = new DbDataModel();
8
2023-12-30 15:32:55+00:00
8k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/tests/org/jfree/chart/urls/StandardCategoryURLGeneratorTest.java
[ { "identifier": "TestUtilities", "path": "lib/jfreechart-1.0.19/tests/org/jfree/chart/TestUtilities.java", "snippet": "public class TestUtilities {\n\n /**\n * Returns <code>true</code> if the collections contains any object that\n * is an instance of the specified class, and <code>false</cod...
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import org.jfree.chart.TestUtilities; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.util.PublicCloneable; import org.junit.Test;
3,694
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------------- * StandardCategoryURLGeneratorTest.java * ------------------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 13-Aug-2003 : Version 1 (DG); * 13-Dec-2007 : Added testGenerateURL() and testEquals() (DG); * 23-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.chart.urls; /** * Tests for the {@link StandardCategoryURLGenerator} class. */ public class StandardCategoryURLGeneratorTest { /** * Some tests for the generateURL() method. */ @Test public void testGenerateURL() { StandardCategoryURLGenerator g1 = new StandardCategoryURLGenerator();
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------------- * StandardCategoryURLGeneratorTest.java * ------------------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 13-Aug-2003 : Version 1 (DG); * 13-Dec-2007 : Added testGenerateURL() and testEquals() (DG); * 23-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.chart.urls; /** * Tests for the {@link StandardCategoryURLGenerator} class. */ public class StandardCategoryURLGeneratorTest { /** * Some tests for the generateURL() method. */ @Test public void testGenerateURL() { StandardCategoryURLGenerator g1 = new StandardCategoryURLGenerator();
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
1
2023-12-24 12:36:47+00:00
8k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/util/EntityUtils.java
[ { "identifier": "RotationHandler", "path": "src/main/java/com/github/may2beez/mayobees/handler/RotationHandler.java", "snippet": "public class RotationHandler {\n private static RotationHandler instance;\n private final Minecraft mc = Minecraft.getMinecraft();\n private final Rotation startRota...
import com.github.may2beez.mayobees.handler.RotationHandler; import com.github.may2beez.mayobees.util.helper.Rotation; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityOtherPlayerMP; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.scoreboard.Score; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.StringUtils; import net.minecraft.util.Vec3; import java.util.Collections; import java.util.Comparator; import java.util.List;
4,845
package com.github.may2beez.mayobees.util; public class EntityUtils { private final static Minecraft mc = Minecraft.getMinecraft(); public static boolean isPlayer(Entity entity, List<String> playerList) { if (!(entity instanceof EntityOtherPlayerMP)) { return false; } return playerList.stream().anyMatch(player -> player.toLowerCase().contains(entity.getName().toLowerCase())); } public static boolean isNPC(Entity entity) { if (!(entity instanceof EntityOtherPlayerMP)) { return false; } EntityLivingBase entityLivingBase = (EntityLivingBase) entity; if (StringUtils.stripControlCodes(entityLivingBase.getCustomNameTag()).startsWith("[NPC]")) { return true; } return entity.getUniqueID().version() == 2 && entityLivingBase.getHealth() == 20 && entityLivingBase.getMaxHealth() == 20; } private static boolean isOnTeam(EntityPlayer player) { for (Score score : Minecraft.getMinecraft().thePlayer.getWorldScoreboard().getScores()) { if (score.getObjective().getName().equals("health") && score.getPlayerName().contains(player.getName())) { return true; } } return false; } public static boolean isTeam(EntityLivingBase entity) { if (!(entity instanceof EntityPlayer) || entity.getDisplayName().getUnformattedText().length() < 4) { return false; } return isOnTeam((EntityPlayer) entity); } public static boolean isEntityInFOV(Entity entity, double fov) {
package com.github.may2beez.mayobees.util; public class EntityUtils { private final static Minecraft mc = Minecraft.getMinecraft(); public static boolean isPlayer(Entity entity, List<String> playerList) { if (!(entity instanceof EntityOtherPlayerMP)) { return false; } return playerList.stream().anyMatch(player -> player.toLowerCase().contains(entity.getName().toLowerCase())); } public static boolean isNPC(Entity entity) { if (!(entity instanceof EntityOtherPlayerMP)) { return false; } EntityLivingBase entityLivingBase = (EntityLivingBase) entity; if (StringUtils.stripControlCodes(entityLivingBase.getCustomNameTag()).startsWith("[NPC]")) { return true; } return entity.getUniqueID().version() == 2 && entityLivingBase.getHealth() == 20 && entityLivingBase.getMaxHealth() == 20; } private static boolean isOnTeam(EntityPlayer player) { for (Score score : Minecraft.getMinecraft().thePlayer.getWorldScoreboard().getScores()) { if (score.getObjective().getName().equals("health") && score.getPlayerName().contains(player.getName())) { return true; } } return false; } public static boolean isTeam(EntityLivingBase entity) { if (!(entity instanceof EntityPlayer) || entity.getDisplayName().getUnformattedText().length() < 4) { return false; } return isOnTeam((EntityPlayer) entity); } public static boolean isEntityInFOV(Entity entity, double fov) {
Rotation rotation = RotationHandler.getInstance().getRotation(entity);
1
2023-12-24 15:39:11+00:00
8k
viceice/verbrauchsapp
app/src/main/java/de/anipe/verbrauchsapp/PictureImportActivity.java
[ { "identifier": "ConsumptionDataSource", "path": "app/src/main/java/de/anipe/verbrauchsapp/db/ConsumptionDataSource.java", "snippet": "public class ConsumptionDataSource implements Serializable {\n\n\tprivate static ConsumptionDataSource dataSouce;\n\n\tprivate static final long serialVersionUID = 36801...
import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.io.File; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import de.anipe.verbrauchsapp.db.ConsumptionDataSource; import de.anipe.verbrauchsapp.io.FileSystemAccessor;
4,172
package de.anipe.verbrauchsapp; public class PictureImportActivity extends AppCompatActivity implements AdapterView.OnItemClickListener { private static final int MAX_FILE_SIZE = 6000000; private ConsumptionDataSource dataSource;
package de.anipe.verbrauchsapp; public class PictureImportActivity extends AppCompatActivity implements AdapterView.OnItemClickListener { private static final int MAX_FILE_SIZE = 6000000; private ConsumptionDataSource dataSource;
private FileSystemAccessor accessor;
1
2023-12-28 12:33:52+00:00
8k
PSButlerII/SqlScriptGen
src/main/java/com/recondev/Main.java
[ { "identifier": "Enums", "path": "src/main/java/com/recondev/helpers/Enums.java", "snippet": "public class Enums {\n\n public enum DatabaseType {\n POSTGRESQL(\"PostgreSQL\"),\n MYSQL(\"MySQL\"),\n MONGODB(\"MongoDB\");\n\n private final String type;\n\n DatabaseTyp...
import com.recondev.helpers.Enums; import com.recondev.interfaces.DatabaseScriptGenerator; import com.recondev.service.ScriptGeneratorFactory; import com.recondev.userinteraction.UserInteraction; import java.util.List; import java.util.Map;
4,959
package com.recondev; public class Main { public static void main(String[] args) { UserInteraction ui = new UserInteraction();
package com.recondev; public class Main { public static void main(String[] args) { UserInteraction ui = new UserInteraction();
Enums.DatabaseType dbType = ui.getDatabaseType();
0
2023-12-29 01:53:43+00:00
8k
drSolutions-OpenSource/Utilizar_JDBC
psql/src/main/java/Main.java
[ { "identifier": "TipoTelefone", "path": "psql/src/main/java/configuracoes/TipoTelefone.java", "snippet": "public class TipoTelefone {\n\tpublic static final String CELULAR = \"Celular\";\n\tpublic static final String FIXO = \"Fixo\";\n\tpublic static final String COMERCIAL = \"Comercial\";\n\tpublic sta...
import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.List; import configuracoes.TipoTelefone; import dao.TelefonesDAO; import dao.UsuariosDAO; import model.Telefones; import model.UsuarioTelefone; import model.Usuarios;
5,654
/** * Utilizar o JDBC (Java Database Connectivity) com o banco de dados PostgreSQL * 13.10 Utilizou-se a plataforma ElephantSQL - PostgreSQL as a Service como a * provedora do banco de dados Foram criadas 2 tabelas: - Usuarios: id (UNIQUE), * nome, email, login e senha - Telefones: id (PK), tipo, telefone e usuariosid * . O campo usuariosid é uma FK para a tabela Usuarios, com ON DELETE CASCADE . * No campo tipo, pode-se apenas preencher 'Celular', 'Fixo', 'Comercial' ou * 'Fax' * * @author Diego Mendes Rodrigues * @version 1.0 */ public class Main { public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException { // incluirUsuario(); // alterarUsuario(); listarUsuarios(); // incluirTelefone(); listarTelefones(); /* Listagens utilizando INNER JOIN */ listarUsuariosComTelefones(); listarUmUsuario(); } /** * Incluir um usuário na tabela Usuarios */ public static void incluirUsuario() { System.out.println("# Cadastrar um usuário"); UsuariosDAO dao = new UsuariosDAO(); Usuarios usuario = new Usuarios(); // usuario.setNome("Diego Rodrigues"); // usuario.setEmail("drodrigues@fake.io"); // usuario.setLogin("drodrigues"); // String senha = dao.gerarSenhaHash("senha2023"); // usuario.setSenha(senha); usuario.setNome("Bruna Mendes"); usuario.setEmail("bmendes@fake.io"); usuario.setLogin("bmendes"); String senha = dao.gerarSenhaHash("sapoFada"); usuario.setSenha(senha); if (dao.salvar(usuario)) { System.out.println("Usuário incluído com sucesso"); } else { System.out.println("Falha ao incluir o usuário"); } } /** * Alterar um usuário na tabela Usuarios */ public static void alterarUsuario() { System.out.println("# Alterar um usuário"); UsuariosDAO dao = new UsuariosDAO(); Usuarios usuario = new Usuarios(); System.out.println("# Cadastrar um usuário"); usuario.setId(2L); usuario.setNome("Bruna Mendes"); usuario.setEmail("bmendes@fake.io"); usuario.setLogin("bmendes"); String senha = dao.gerarSenhaHash("sapoF@da88"); usuario.setSenha(senha); if (dao.alterar(usuario)) { System.out.println("Usuário alterado com sucesso"); } else { System.out.println("Falha ao alterado o usuário"); } } /** * Listar todos os usuários da tabela Usuarios */ public static void listarUsuarios() { System.out.println("# Listar os usuários"); UsuariosDAO dao = new UsuariosDAO(); List<Usuarios> listaUsuarios = new ArrayList<Usuarios>(); listaUsuarios = dao.listar(); for (Usuarios usuario : listaUsuarios) { System.out.println(usuario.toString()); } } /** * Incluir um telefone na tabela Telefones */ public static void incluirTelefone() { System.out.println("# Cadastrar um telefone"); TelefonesDAO dao = new TelefonesDAO();
/** * Utilizar o JDBC (Java Database Connectivity) com o banco de dados PostgreSQL * 13.10 Utilizou-se a plataforma ElephantSQL - PostgreSQL as a Service como a * provedora do banco de dados Foram criadas 2 tabelas: - Usuarios: id (UNIQUE), * nome, email, login e senha - Telefones: id (PK), tipo, telefone e usuariosid * . O campo usuariosid é uma FK para a tabela Usuarios, com ON DELETE CASCADE . * No campo tipo, pode-se apenas preencher 'Celular', 'Fixo', 'Comercial' ou * 'Fax' * * @author Diego Mendes Rodrigues * @version 1.0 */ public class Main { public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException { // incluirUsuario(); // alterarUsuario(); listarUsuarios(); // incluirTelefone(); listarTelefones(); /* Listagens utilizando INNER JOIN */ listarUsuariosComTelefones(); listarUmUsuario(); } /** * Incluir um usuário na tabela Usuarios */ public static void incluirUsuario() { System.out.println("# Cadastrar um usuário"); UsuariosDAO dao = new UsuariosDAO(); Usuarios usuario = new Usuarios(); // usuario.setNome("Diego Rodrigues"); // usuario.setEmail("drodrigues@fake.io"); // usuario.setLogin("drodrigues"); // String senha = dao.gerarSenhaHash("senha2023"); // usuario.setSenha(senha); usuario.setNome("Bruna Mendes"); usuario.setEmail("bmendes@fake.io"); usuario.setLogin("bmendes"); String senha = dao.gerarSenhaHash("sapoFada"); usuario.setSenha(senha); if (dao.salvar(usuario)) { System.out.println("Usuário incluído com sucesso"); } else { System.out.println("Falha ao incluir o usuário"); } } /** * Alterar um usuário na tabela Usuarios */ public static void alterarUsuario() { System.out.println("# Alterar um usuário"); UsuariosDAO dao = new UsuariosDAO(); Usuarios usuario = new Usuarios(); System.out.println("# Cadastrar um usuário"); usuario.setId(2L); usuario.setNome("Bruna Mendes"); usuario.setEmail("bmendes@fake.io"); usuario.setLogin("bmendes"); String senha = dao.gerarSenhaHash("sapoF@da88"); usuario.setSenha(senha); if (dao.alterar(usuario)) { System.out.println("Usuário alterado com sucesso"); } else { System.out.println("Falha ao alterado o usuário"); } } /** * Listar todos os usuários da tabela Usuarios */ public static void listarUsuarios() { System.out.println("# Listar os usuários"); UsuariosDAO dao = new UsuariosDAO(); List<Usuarios> listaUsuarios = new ArrayList<Usuarios>(); listaUsuarios = dao.listar(); for (Usuarios usuario : listaUsuarios) { System.out.println(usuario.toString()); } } /** * Incluir um telefone na tabela Telefones */ public static void incluirTelefone() { System.out.println("# Cadastrar um telefone"); TelefonesDAO dao = new TelefonesDAO();
Telefones telefone = new Telefones();
3
2023-12-30 14:50:31+00:00
8k
JoshiCodes/NewLabyAPI
src/main/java/de/joshicodes/newlabyapi/api/LabyModAPI.java
[ { "identifier": "LabyModProtocol", "path": "src/main/java/de/joshicodes/newlabyapi/LabyModProtocol.java", "snippet": "public class LabyModProtocol {\n\n /**\n * Send a message to LabyMod\n * @param player Minecraft Client\n * @param key LabyMod message key\n * @param messageContent js...
import com.google.gson.JsonObject; import de.joshicodes.newlabyapi.LabyModProtocol; import de.joshicodes.newlabyapi.NewLabyPlugin; import de.joshicodes.newlabyapi.api.event.player.LabyModPlayerJoinEvent; import de.joshicodes.newlabyapi.api.object.InputPrompt; import de.joshicodes.newlabyapi.api.object.LabyModPlayerSubtitle; import de.joshicodes.newlabyapi.api.object.LabyProtocolObject; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.UUID;
3,973
package de.joshicodes.newlabyapi.api; public class LabyModAPI { private static final HashMap<Player, LabyModPlayer> labyModPlayers = new HashMap<>(); private static boolean updateExistingPlayersOnJoin = false; public static void init(NewLabyPlugin plugin) { updateExistingPlayersOnJoin = plugin.getConfig().getBoolean("updateExistingPlayersOnJoin", true); } public static void sendObject(Player player, String key, LabyProtocolObject obj) { LabyModProtocol.sendLabyModMessage(player, key, obj.toJson()); }
package de.joshicodes.newlabyapi.api; public class LabyModAPI { private static final HashMap<Player, LabyModPlayer> labyModPlayers = new HashMap<>(); private static boolean updateExistingPlayersOnJoin = false; public static void init(NewLabyPlugin plugin) { updateExistingPlayersOnJoin = plugin.getConfig().getBoolean("updateExistingPlayersOnJoin", true); } public static void sendObject(Player player, String key, LabyProtocolObject obj) { LabyModProtocol.sendLabyModMessage(player, key, obj.toJson()); }
public static void sendPrompt(Player player, InputPrompt prompt) {
3
2023-12-24 15:00:08+00:00
8k
1752597830/admin-common
qf-admin/back/admin-init-main/src/main/java/com/qf/server/Server.java
[ { "identifier": "Arith", "path": "qf-admin/back/admin-init-main/src/main/java/com/qf/server/util/Arith.java", "snippet": "public class Arith\n{\n\n /** 默认除法运算精度 */\n private static final int DEF_DIV_SCALE = 10;\n\n /** 这个类不能实例化 */\n private Arith()\n {\n }\n\n /**\n * 提供精确的加法运算。...
import com.qf.server.util.Arith; import com.qf.server.util.IpUtils; import lombok.ToString; import oshi.SystemInfo; import oshi.hardware.CentralProcessor; import oshi.hardware.CentralProcessor.TickType; import oshi.hardware.GlobalMemory; import oshi.hardware.HardwareAbstractionLayer; import oshi.software.os.FileSystem; import oshi.software.os.OSFileStore; import oshi.software.os.OperatingSystem; import oshi.util.Util; import java.net.UnknownHostException; import java.util.LinkedList; import java.util.List; import java.util.Properties;
5,093
package com.qf.server; /** * 服务器相关信息 * * @author ruoyi */ @ToString public class Server { private static final int OSHI_WAIT_SECOND = 1000; /** * CPU相关信息 */ private Cpu cpu = new Cpu(); /** * 內存相关信息 */ private Mem mem = new Mem(); /** * JVM相关信息 */ private Jvm jvm = new Jvm(); /** * 服务器相关信息 */ private Sys sys = new Sys(); /** * 磁盘相关信息 */ private List<SysFile> sysFiles = new LinkedList<SysFile>(); public Cpu getCpu() { return cpu; } public void setCpu(Cpu cpu) { this.cpu = cpu; } public Mem getMem() { return mem; } public void setMem(Mem mem) { this.mem = mem; } public Jvm getJvm() { return jvm; } public void setJvm(Jvm jvm) { this.jvm = jvm; } public Sys getSys() { return sys; } public void setSys(Sys sys) { this.sys = sys; } public List<SysFile> getSysFiles() { return sysFiles; } public void setSysFiles(List<SysFile> sysFiles) { this.sysFiles = sysFiles; } public void copyTo() throws Exception { SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); setCpuInfo(hal.getProcessor()); setMemInfo(hal.getMemory()); setSysInfo(); setJvmInfo(); setSysFiles(si.getOperatingSystem()); } /** * 设置CPU信息 */ private void setCpuInfo(CentralProcessor processor) { // CPU信息 long[] prevTicks = processor.getSystemCpuLoadTicks(); Util.sleep(OSHI_WAIT_SECOND); long[] ticks = processor.getSystemCpuLoadTicks(); long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()]; long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()]; long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()]; long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()]; long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()]; long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()]; long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()]; long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()]; long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal; cpu.setCpuNum(processor.getLogicalProcessorCount()); cpu.setTotal(totalCpu); cpu.setSys(cSys); cpu.setUsed(user); cpu.setWait(iowait); cpu.setFree(idle); } /** * 设置内存信息 */ private void setMemInfo(GlobalMemory memory) { mem.setTotal(memory.getTotal()); mem.setUsed(memory.getTotal() - memory.getAvailable()); mem.setFree(memory.getAvailable()); } /** * 设置服务器信息 */ private void setSysInfo() { Properties props = System.getProperties();
package com.qf.server; /** * 服务器相关信息 * * @author ruoyi */ @ToString public class Server { private static final int OSHI_WAIT_SECOND = 1000; /** * CPU相关信息 */ private Cpu cpu = new Cpu(); /** * 內存相关信息 */ private Mem mem = new Mem(); /** * JVM相关信息 */ private Jvm jvm = new Jvm(); /** * 服务器相关信息 */ private Sys sys = new Sys(); /** * 磁盘相关信息 */ private List<SysFile> sysFiles = new LinkedList<SysFile>(); public Cpu getCpu() { return cpu; } public void setCpu(Cpu cpu) { this.cpu = cpu; } public Mem getMem() { return mem; } public void setMem(Mem mem) { this.mem = mem; } public Jvm getJvm() { return jvm; } public void setJvm(Jvm jvm) { this.jvm = jvm; } public Sys getSys() { return sys; } public void setSys(Sys sys) { this.sys = sys; } public List<SysFile> getSysFiles() { return sysFiles; } public void setSysFiles(List<SysFile> sysFiles) { this.sysFiles = sysFiles; } public void copyTo() throws Exception { SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); setCpuInfo(hal.getProcessor()); setMemInfo(hal.getMemory()); setSysInfo(); setJvmInfo(); setSysFiles(si.getOperatingSystem()); } /** * 设置CPU信息 */ private void setCpuInfo(CentralProcessor processor) { // CPU信息 long[] prevTicks = processor.getSystemCpuLoadTicks(); Util.sleep(OSHI_WAIT_SECOND); long[] ticks = processor.getSystemCpuLoadTicks(); long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()]; long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()]; long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()]; long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()]; long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()]; long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()]; long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()]; long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()]; long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal; cpu.setCpuNum(processor.getLogicalProcessorCount()); cpu.setTotal(totalCpu); cpu.setSys(cSys); cpu.setUsed(user); cpu.setWait(iowait); cpu.setFree(idle); } /** * 设置内存信息 */ private void setMemInfo(GlobalMemory memory) { mem.setTotal(memory.getTotal()); mem.setUsed(memory.getTotal() - memory.getAvailable()); mem.setFree(memory.getAvailable()); } /** * 设置服务器信息 */ private void setSysInfo() { Properties props = System.getProperties();
sys.setComputerName(IpUtils.getHostName());
1
2023-12-30 13:42:53+00:00
8k
JIGerss/Salus
salus-web/src/main/java/team/glhf/salus/service/Impl/GameServiceImpl.java
[ { "identifier": "ConfigReq", "path": "salus-pojo/src/main/java/team/glhf/salus/dto/game/ConfigReq.java", "snippet": "@Data\r\n@Builder\r\npublic class ConfigReq implements Serializable {\r\n\r\n @Null(message = \"cannot use userId to access\")\r\n private String userId;\r\n\r\n @NotBlank(messag...
import cn.hutool.core.thread.ThreadUtil; import org.springframework.stereotype.Service; import team.glhf.salus.annotation.AutoOperateGame; import team.glhf.salus.dto.game.ConfigReq; import team.glhf.salus.dto.game.SelectReq; import team.glhf.salus.dto.game.StartGameReq; import team.glhf.salus.entity.User; import team.glhf.salus.enumeration.GameMessageType; import team.glhf.salus.enumeration.GameRoleEnum; import team.glhf.salus.enumeration.GameStageEnum; import team.glhf.salus.enumeration.HttpCodeEnum; import team.glhf.salus.exception.GameException; import team.glhf.salus.service.GameService; import team.glhf.salus.service.PlaceService; import team.glhf.salus.service.UserService; import team.glhf.salus.vo.game.*; import team.glhf.salus.websocket.Game; import team.glhf.salus.websocket.GameEndPoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
4,897
package team.glhf.salus.service.Impl; /** * @author Steveny * @since 2023/12/11 */ @Service public class GameServiceImpl implements GameService { private final UserService userService; private final PlaceService placeService; private final Map<String, Game> games = new ConcurrentHashMap<>(); public GameServiceImpl(UserService userService, PlaceService placeService) { this.userService = userService; this.placeService = placeService; } @Override public void joinOrCreateGame(GameEndPoint gameEndPoint) { String key = gameEndPoint.getKey(); Game game; if (hasGame(key)) { game = getGameByKey(key); game.addPlayer(gameEndPoint); } else { game = new Game(this); game.setKey(key); game.addPlayer(gameEndPoint);
package team.glhf.salus.service.Impl; /** * @author Steveny * @since 2023/12/11 */ @Service public class GameServiceImpl implements GameService { private final UserService userService; private final PlaceService placeService; private final Map<String, Game> games = new ConcurrentHashMap<>(); public GameServiceImpl(UserService userService, PlaceService placeService) { this.userService = userService; this.placeService = placeService; } @Override public void joinOrCreateGame(GameEndPoint gameEndPoint) { String key = gameEndPoint.getKey(); Game game; if (hasGame(key)) { game = getGameByKey(key); game.addPlayer(gameEndPoint); } else { game = new Game(this); game.setKey(key); game.addPlayer(gameEndPoint);
game.setGameStageEnum(GameStageEnum.PREPARE);
6
2023-12-23 15:03:37+00:00
8k
swsm/proxynet
proxynet-client/src/main/java/com/swsm/proxynet/client/init/SpringInitRunner.java
[ { "identifier": "ProxyConfig", "path": "proxynet-client/src/main/java/com/swsm/proxynet/client/config/ProxyConfig.java", "snippet": "@Configuration\n@Data\npublic class ProxyConfig {\n\n @Value(\"${proxynet.client.id}\")\n private Integer clientId;\n\n @Value(\"${proxynet.client.serverIp}\")\n ...
import com.swsm.proxynet.client.config.ProxyConfig; import com.swsm.proxynet.client.handler.ClientServerChannelHandler; import com.swsm.proxynet.client.handler.ClientTargetChannelHandler; import com.swsm.proxynet.common.handler.ProxyNetMessageDecoder; import com.swsm.proxynet.common.handler.ProxyNetMessageEncoder; import com.swsm.proxynet.common.model.ProxyNetMessage; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelInitializer; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.timeout.IdleStateHandler; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import static com.swsm.proxynet.common.Constants.ALL_IDLE_SECOND_TIME; import static com.swsm.proxynet.common.Constants.PROXY_MESSAGE_LENGTH_FILED_LENGTH; import static com.swsm.proxynet.common.Constants.PROXY_MESSAGE_LENGTH_FILED_OFFSET; import static com.swsm.proxynet.common.Constants.PROXY_MESSAGE_MAX_SIZE; import static com.swsm.proxynet.common.Constants.READ_IDLE_SECOND_TIME; import static com.swsm.proxynet.common.Constants.WRITE_IDLE_SECOND_TIME;
3,787
package com.swsm.proxynet.client.init; /** * @author liujie * @date 2023-04-15 */ @Component @Slf4j public class SpringInitRunner implements CommandLineRunner { @Autowired private ProxyConfig proxyConfig; public static Bootstrap bootstrapForTarget; public static Bootstrap bootstrapForServer; @Override public void run(String... args) throws Exception { log.info("proxyclient spring启动完成,接下来启动 连接代理服务器的客户端"); log.info("启动 连接代理服务器的客户端..."); bootstrapForServer = new Bootstrap(); bootstrapForServer.group(new NioEventLoopGroup(4)) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast( new ProxyNetMessageDecoder(PROXY_MESSAGE_MAX_SIZE, PROXY_MESSAGE_LENGTH_FILED_OFFSET, PROXY_MESSAGE_LENGTH_FILED_LENGTH)); socketChannel.pipeline().addLast(new ProxyNetMessageEncoder()); socketChannel.pipeline().addLast(new IdleStateHandler(READ_IDLE_SECOND_TIME, WRITE_IDLE_SECOND_TIME, ALL_IDLE_SECOND_TIME)); socketChannel.pipeline().addLast(new ClientServerChannelHandler()); } }); bootstrapForServer.connect(proxyConfig.getServerIp(), proxyConfig.getServerPort()) .addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { log.info("连接代理服务器的客户端 成功..."); // 向服务端发送 客户端id信息 future.channel().writeAndFlush( ProxyNetMessage.buildCommandMessage(ProxyNetMessage.COMMAND_AUTH, String.valueOf(proxyConfig.getClientId()))); } else { log.info("连接代理服务器的客户端 失败..."); System.exit(-1); } }).sync(); log.info("启动 连接代理服务器的客户端 成功..."); log.info("初始化 连接被代理服务器的客户端..."); bootstrapForTarget = new Bootstrap(); bootstrapForTarget.group(new NioEventLoopGroup(4)) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception {
package com.swsm.proxynet.client.init; /** * @author liujie * @date 2023-04-15 */ @Component @Slf4j public class SpringInitRunner implements CommandLineRunner { @Autowired private ProxyConfig proxyConfig; public static Bootstrap bootstrapForTarget; public static Bootstrap bootstrapForServer; @Override public void run(String... args) throws Exception { log.info("proxyclient spring启动完成,接下来启动 连接代理服务器的客户端"); log.info("启动 连接代理服务器的客户端..."); bootstrapForServer = new Bootstrap(); bootstrapForServer.group(new NioEventLoopGroup(4)) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast( new ProxyNetMessageDecoder(PROXY_MESSAGE_MAX_SIZE, PROXY_MESSAGE_LENGTH_FILED_OFFSET, PROXY_MESSAGE_LENGTH_FILED_LENGTH)); socketChannel.pipeline().addLast(new ProxyNetMessageEncoder()); socketChannel.pipeline().addLast(new IdleStateHandler(READ_IDLE_SECOND_TIME, WRITE_IDLE_SECOND_TIME, ALL_IDLE_SECOND_TIME)); socketChannel.pipeline().addLast(new ClientServerChannelHandler()); } }); bootstrapForServer.connect(proxyConfig.getServerIp(), proxyConfig.getServerPort()) .addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { log.info("连接代理服务器的客户端 成功..."); // 向服务端发送 客户端id信息 future.channel().writeAndFlush( ProxyNetMessage.buildCommandMessage(ProxyNetMessage.COMMAND_AUTH, String.valueOf(proxyConfig.getClientId()))); } else { log.info("连接代理服务器的客户端 失败..."); System.exit(-1); } }).sync(); log.info("启动 连接代理服务器的客户端 成功..."); log.info("初始化 连接被代理服务器的客户端..."); bootstrapForTarget = new Bootstrap(); bootstrapForTarget.group(new NioEventLoopGroup(4)) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new ClientTargetChannelHandler());
2
2023-12-25 03:25:38+00:00
8k
Trodev-IT/ScanHub
app/src/main/java/com/trodev/scanhub/adapters/LocationAdapter.java
[ { "identifier": "EmailQrFullActivity", "path": "app/src/main/java/com/trodev/scanhub/detail_activity/EmailQrFullActivity.java", "snippet": "public class EmailQrFullActivity extends AppCompatActivity {\n\n TextView from_tv, to_tv, text_tv;\n String from, to, text;\n Button generate, qr_download,...
import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.trodev.scanhub.R; import com.trodev.scanhub.detail_activity.EmailQrFullActivity; import com.trodev.scanhub.detail_activity.LocationQrFullActivity; import com.trodev.scanhub.models.EmailModel; import com.trodev.scanhub.models.LocationModel; import java.util.ArrayList;
6,067
package com.trodev.scanhub.adapters; public class LocationAdapter extends RecyclerView.Adapter<LocationAdapter.MyViewHolder>{ private Context context; private ArrayList<LocationModel> list; private String category; public LocationAdapter(Context context, ArrayList<LocationModel> list, String category) { this.context = context; this.list = list; this.category = category; } @NonNull @Override public LocationAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.location_qr_item, parent, false); return new LocationAdapter.MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull LocationAdapter.MyViewHolder holder, int position) { /*get data from database model*/ LocationModel models = list.get(position); holder.from.setText(models.getLoc_from()); holder.to.setText(models.getLoc_to()); holder.time.setText(models.getTime()); holder.date.setText(models.getDate()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
package com.trodev.scanhub.adapters; public class LocationAdapter extends RecyclerView.Adapter<LocationAdapter.MyViewHolder>{ private Context context; private ArrayList<LocationModel> list; private String category; public LocationAdapter(Context context, ArrayList<LocationModel> list, String category) { this.context = context; this.list = list; this.category = category; } @NonNull @Override public LocationAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.location_qr_item, parent, false); return new LocationAdapter.MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull LocationAdapter.MyViewHolder holder, int position) { /*get data from database model*/ LocationModel models = list.get(position); holder.from.setText(models.getLoc_from()); holder.to.setText(models.getLoc_to()); holder.time.setText(models.getTime()); holder.date.setText(models.getDate()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
Intent intent = new Intent(context, LocationQrFullActivity.class);
1
2023-12-26 05:10:38+00:00
8k
Deepennn/NetAPP
src/main/java/com/netapp/device/host/Host.java
[ { "identifier": "Iface", "path": "src/main/java/com/netapp/device/Iface.java", "snippet": "public class Iface\n{\n protected String iName; // 接口名称\n protected String macAddress; // MAC地址\n protected BlockingQueue<Ethernet> inputQueue; // 输入队列\n protected BlockingQueue<Ethernet> o...
import com.netapp.device.Iface; import com.netapp.device.NetDevice; import com.netapp.device.NetIface; import com.netapp.device.ArpEntry; import com.netapp.packet.*; import java.util.Map;
4,178
package com.netapp.device.host; public class Host extends NetDevice { protected String gatewayAddress; // 网关IP地址
package com.netapp.device.host; public class Host extends NetDevice { protected String gatewayAddress; // 网关IP地址
protected boolean isInSubnet(String dstIp, Iface outIface){
0
2023-12-23 13:03:07+00:00
8k
strokegmd/StrokeClient
stroke/client/modules/render/Hud.java
[ { "identifier": "StrokeClient", "path": "stroke/client/StrokeClient.java", "snippet": "public class StrokeClient {\r\n\tpublic static Minecraft mc;\r\n\t\r\n\tpublic static String dev_username = \"megao4ko\";\r\n\tpublic static String title = \"[stroke] client ・ v1.0.00 | Minecraft 1.12.2\";\r\n\tpubli...
import java.awt.Color; import net.minecraft.client.gui.Gui; import net.stroke.client.StrokeClient; import net.stroke.client.clickgui.Setting; import net.stroke.client.modules.BaseModule; import net.stroke.client.modules.ModuleCategory; import net.stroke.client.modules.ModuleManager; import net.stroke.client.util.ColorUtils;
3,848
package net.stroke.client.modules.render; public class Hud extends BaseModule { public StrokeClient client; public Hud() { super("Hud", "Shows enabled modules and important information", 0x00, ModuleCategory.Render, true); // totally not stolen from kami StrokeClient.instance.settingsManager.rSetting(new Setting("Coordinates", this, true)); StrokeClient.instance.settingsManager.rSetting(new Setting("Module List", this, true)); StrokeClient.instance.settingsManager.rSetting(new Setting("Username", this, true)); } public void onRender() { boolean coordinates = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Coordinates").getValBoolean(); boolean moduleList = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Module List").getValBoolean(); boolean username = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Username").getValBoolean(); int xBorder = StrokeClient.getScaledWidth() - 2; int yBorder = StrokeClient.getScaledHeight() - 10; int versionX = mc.fontRendererObj.getStringWidth(client.name); int usernameX = mc.fontRendererObj.getStringWidth("Hello, ") + 2; int markX = mc.fontRendererObj.getStringWidth("Hello, " + StrokeClient.getUsername()) + 2; double playerX = Math.round(mc.player.posX * 10.0) / 10.0; double playerY = Math.round(mc.player.posY * 10.0) / 10.0; double playerZ = Math.round(mc.player.posZ * 10.0) / 10.0; double playerNetherX = playerX / 8.0f; double playerNetherY = playerY; double playerNetherZ = playerZ / 8.0f; playerNetherX = Math.round(playerNetherX * 10.0) / 10.0; playerNetherZ = Math.round(playerNetherZ * 10.0) / 10.0; String coords = Double.toString(playerX) + ", " + Double.toString(playerY) + ", " + Double.toString(playerZ); String netherCoords = Double.toString(playerNetherX) + ", " + Double.toString(playerNetherY) + ", " + Double.toString(playerNetherZ); int xyzX = xBorder - 22 - mc.fontRendererObj.getStringWidth(coords); int coordsX = xBorder - 22 - mc.fontRendererObj.getStringWidth(coords) + mc.fontRendererObj.getStringWidth("XYZ "); int xyzY = yBorder - 10; int coordsY = xyzY; int netherX = xBorder - 37 - mc.fontRendererObj.getStringWidth(netherCoords); int netherCoordsX = xBorder - 37 - mc.fontRendererObj.getStringWidth(netherCoords) + mc.fontRendererObj.getStringWidth("Nether "); int netherY = yBorder; int netherCoordsY = netherY; int rainbowColor = ColorUtils.getRainbow(2.0f, 0.8f, 1.0f, 100); Gui.drawRect(3, 2, 124, 1, rainbowColor); Gui.drawRect(3, 2, 124, 14, Color.black.hashCode() * 100); mc.fontRendererObj.drawStringWithShadow(client.name, 4, 4, ColorUtils.primaryColor); mc.fontRendererObj.drawStringWithShadow(client.version, versionX, 4, ColorUtils.secondaryColor); if(username) { mc.fontRendererObj.drawStringWithShadow("Hello, ", 2, yBorder, ColorUtils.primaryColor); mc.fontRendererObj.drawStringWithShadow(StrokeClient.getUsername(), usernameX, yBorder, ColorUtils.secondaryColor); mc.fontRendererObj.drawStringWithShadow("!", markX, yBorder, ColorUtils. primaryColor); } if(coordinates) { mc.fontRendererObj.drawStringWithShadow("XYZ", xyzX, xyzY, ColorUtils.secondaryColor); mc.fontRendererObj.drawStringWithShadow(coords, coordsX, coordsY, ColorUtils.primaryColor); mc.fontRendererObj.drawStringWithShadow("Nether ", netherX, netherY, ColorUtils.secondaryColor); mc.fontRendererObj.drawStringWithShadow(netherCoords, netherCoordsX, netherCoordsY, ColorUtils.primaryColor); } int moduleNumber = 0;
package net.stroke.client.modules.render; public class Hud extends BaseModule { public StrokeClient client; public Hud() { super("Hud", "Shows enabled modules and important information", 0x00, ModuleCategory.Render, true); // totally not stolen from kami StrokeClient.instance.settingsManager.rSetting(new Setting("Coordinates", this, true)); StrokeClient.instance.settingsManager.rSetting(new Setting("Module List", this, true)); StrokeClient.instance.settingsManager.rSetting(new Setting("Username", this, true)); } public void onRender() { boolean coordinates = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Coordinates").getValBoolean(); boolean moduleList = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Module List").getValBoolean(); boolean username = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Username").getValBoolean(); int xBorder = StrokeClient.getScaledWidth() - 2; int yBorder = StrokeClient.getScaledHeight() - 10; int versionX = mc.fontRendererObj.getStringWidth(client.name); int usernameX = mc.fontRendererObj.getStringWidth("Hello, ") + 2; int markX = mc.fontRendererObj.getStringWidth("Hello, " + StrokeClient.getUsername()) + 2; double playerX = Math.round(mc.player.posX * 10.0) / 10.0; double playerY = Math.round(mc.player.posY * 10.0) / 10.0; double playerZ = Math.round(mc.player.posZ * 10.0) / 10.0; double playerNetherX = playerX / 8.0f; double playerNetherY = playerY; double playerNetherZ = playerZ / 8.0f; playerNetherX = Math.round(playerNetherX * 10.0) / 10.0; playerNetherZ = Math.round(playerNetherZ * 10.0) / 10.0; String coords = Double.toString(playerX) + ", " + Double.toString(playerY) + ", " + Double.toString(playerZ); String netherCoords = Double.toString(playerNetherX) + ", " + Double.toString(playerNetherY) + ", " + Double.toString(playerNetherZ); int xyzX = xBorder - 22 - mc.fontRendererObj.getStringWidth(coords); int coordsX = xBorder - 22 - mc.fontRendererObj.getStringWidth(coords) + mc.fontRendererObj.getStringWidth("XYZ "); int xyzY = yBorder - 10; int coordsY = xyzY; int netherX = xBorder - 37 - mc.fontRendererObj.getStringWidth(netherCoords); int netherCoordsX = xBorder - 37 - mc.fontRendererObj.getStringWidth(netherCoords) + mc.fontRendererObj.getStringWidth("Nether "); int netherY = yBorder; int netherCoordsY = netherY; int rainbowColor = ColorUtils.getRainbow(2.0f, 0.8f, 1.0f, 100); Gui.drawRect(3, 2, 124, 1, rainbowColor); Gui.drawRect(3, 2, 124, 14, Color.black.hashCode() * 100); mc.fontRendererObj.drawStringWithShadow(client.name, 4, 4, ColorUtils.primaryColor); mc.fontRendererObj.drawStringWithShadow(client.version, versionX, 4, ColorUtils.secondaryColor); if(username) { mc.fontRendererObj.drawStringWithShadow("Hello, ", 2, yBorder, ColorUtils.primaryColor); mc.fontRendererObj.drawStringWithShadow(StrokeClient.getUsername(), usernameX, yBorder, ColorUtils.secondaryColor); mc.fontRendererObj.drawStringWithShadow("!", markX, yBorder, ColorUtils. primaryColor); } if(coordinates) { mc.fontRendererObj.drawStringWithShadow("XYZ", xyzX, xyzY, ColorUtils.secondaryColor); mc.fontRendererObj.drawStringWithShadow(coords, coordsX, coordsY, ColorUtils.primaryColor); mc.fontRendererObj.drawStringWithShadow("Nether ", netherX, netherY, ColorUtils.secondaryColor); mc.fontRendererObj.drawStringWithShadow(netherCoords, netherCoordsX, netherCoordsY, ColorUtils.primaryColor); } int moduleNumber = 0;
for (BaseModule module : ModuleManager.modules) {
4
2023-12-31 10:56:59+00:00
8k
piovas-lu/condominio
src/main/java/app/condominio/controller/CobrancaController.java
[ { "identifier": "Cobranca", "path": "src/main/java/app/condominio/domain/Cobranca.java", "snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"cobrancas\")\r\npublic class Cobranca implements Serializable {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\r\n\t@Col...
import java.time.LocalDate; import java.util.List; import java.util.Optional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; 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.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import app.condominio.domain.Cobranca; import app.condominio.domain.Moradia; import app.condominio.domain.enums.MotivoBaixa; import app.condominio.domain.enums.MotivoEmissao; import app.condominio.domain.enums.SituacaoCobranca; import app.condominio.service.CobrancaService; import app.condominio.service.MoradiaService;
4,513
package app.condominio.controller; @Controller @RequestMapping("sindico/cobrancas") public class CobrancaController { @Autowired private CobrancaService cobrancaService; @Autowired MoradiaService moradiaService; @ModelAttribute("ativo") public String[] ativo() { return new String[] { "financeiro", "cobrancas" }; } @ModelAttribute("motivosEmissao")
package app.condominio.controller; @Controller @RequestMapping("sindico/cobrancas") public class CobrancaController { @Autowired private CobrancaService cobrancaService; @Autowired MoradiaService moradiaService; @ModelAttribute("ativo") public String[] ativo() { return new String[] { "financeiro", "cobrancas" }; } @ModelAttribute("motivosEmissao")
public MotivoEmissao[] motivosEmissao() {
3
2023-12-29 22:19:42+00:00
8k
HuXin0817/shop_api
buyer-api/src/test/java/cn/lili/buyer/test/cart/CartTest.java
[ { "identifier": "CategoryVO", "path": "framework/src/main/java/cn/lili/modules/goods/entity/vos/CategoryVO.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class CategoryVO extends Category {\n\n private static final long serialVersionUID = 3775766246075838410L;\n\n @ApiMo...
import cn.hutool.json.JSONUtil; import cn.lili.modules.goods.entity.vos.CategoryVO; import cn.lili.modules.goods.service.CategoryService; import cn.lili.modules.order.cart.entity.dto.TradeDTO; import cn.lili.modules.order.cart.entity.enums.CartTypeEnum; import cn.lili.modules.order.cart.entity.vo.TradeParams; import cn.lili.modules.order.cart.service.CartService; import cn.lili.modules.payment.service.PaymentService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.List;
4,562
package cn.lili.buyer.test.cart; /** * @author paulG * @since 2020/11/14 **/ @ExtendWith(SpringExtension.class) @SpringBootTest class CartTest { @Autowired private CartService cartService; @Autowired private CategoryService categoryService; @Autowired private PaymentService paymentService; @Test void getAll() { TradeDTO allTradeDTO = cartService.getAllTradeDTO(); Assertions.assertNotNull(allTradeDTO); System.out.println(JSONUtil.toJsonStr(allTradeDTO)); } @Test void deleteAll() { cartService.delete(new String[]{"1344220459059404800"}); Assertions.assertTrue(true); } @Test void createTrade() { // TradeDTO allTradeDTO = cartService.getAllTradeDTO(); // Assert.assertNotNull(allTradeDTO); // System.out.println(JsonUtil.objectToJson(allTradeDTO)); cartService.createTrade(new TradeParams()); } @Test void getAllCategory() { List<CategoryVO> allCategory = categoryService.categoryTree(); for (CategoryVO categoryVO : allCategory) { System.out.println(categoryVO); } Assertions.assertTrue(true); } @Test void storeCoupon() {
package cn.lili.buyer.test.cart; /** * @author paulG * @since 2020/11/14 **/ @ExtendWith(SpringExtension.class) @SpringBootTest class CartTest { @Autowired private CartService cartService; @Autowired private CategoryService categoryService; @Autowired private PaymentService paymentService; @Test void getAll() { TradeDTO allTradeDTO = cartService.getAllTradeDTO(); Assertions.assertNotNull(allTradeDTO); System.out.println(JSONUtil.toJsonStr(allTradeDTO)); } @Test void deleteAll() { cartService.delete(new String[]{"1344220459059404800"}); Assertions.assertTrue(true); } @Test void createTrade() { // TradeDTO allTradeDTO = cartService.getAllTradeDTO(); // Assert.assertNotNull(allTradeDTO); // System.out.println(JsonUtil.objectToJson(allTradeDTO)); cartService.createTrade(new TradeParams()); } @Test void getAllCategory() { List<CategoryVO> allCategory = categoryService.categoryTree(); for (CategoryVO categoryVO : allCategory) { System.out.println(categoryVO); } Assertions.assertTrue(true); } @Test void storeCoupon() {
cartService.selectCoupon("1333318596239843328", CartTypeEnum.CART.name(), true);
3
2023-12-24 19:45:18+00:00
8k
SocialPanda3578/OnlineShop
shop/src/shop/Panel/MainPanel.java
[ { "identifier": "Admin", "path": "shop/src/shop/Admin.java", "snippet": "public class Admin extends User{\n public Admin(){\n\n }\n public Admin(String name,String pass){\n setUsername(name);\n setPassword(pass);\n }\n \n public void login(){\n if (isLogin()) {\n ...
import shop.Admin; import shop.History; import shop.Main; import shop.Shop; import shop.User; import java.io.IOException; import java.sql.SQLException;
4,780
package shop.Panel; public class MainPanel { public void showMainMenu() throws SQLException, InterruptedException { System.out.println(" _ _ "); System.out.println(" | | / / "); System.out.println(" | /| / __ / __ __ _ _ __ "); System.out.println(" |/ |/ /___) / / ' / ) / / ) /___)"); System.out.println("_/__|___(___ _/___(___ _(___/_/_/__/_(___ _"); boolean flag = true; while (flag) { System.out.println("***************************"); System.out.println("\t1.注册"); System.out.println("\t2.登录"); System.out.println("\t3.退出登录"); System.out.println("\t4.查看商城"); System.out.println("\t5.查看我购买的商品"); System.out.println("\t6.管理员登录"); System.out.println("\t7.退出系统"); System.out.println("***************************"); System.out.print("请选择菜单:"); int choice = Main.sc.nextInt();
package shop.Panel; public class MainPanel { public void showMainMenu() throws SQLException, InterruptedException { System.out.println(" _ _ "); System.out.println(" | | / / "); System.out.println(" | /| / __ / __ __ _ _ __ "); System.out.println(" |/ |/ /___) / / ' / ) / / ) /___)"); System.out.println("_/__|___(___ _/___(___ _(___/_/_/__/_(___ _"); boolean flag = true; while (flag) { System.out.println("***************************"); System.out.println("\t1.注册"); System.out.println("\t2.登录"); System.out.println("\t3.退出登录"); System.out.println("\t4.查看商城"); System.out.println("\t5.查看我购买的商品"); System.out.println("\t6.管理员登录"); System.out.println("\t7.退出系统"); System.out.println("***************************"); System.out.print("请选择菜单:"); int choice = Main.sc.nextInt();
Admin admin = new Admin();
0
2023-12-28 04:26:15+00:00
8k
MuskStark/EasyECharts
src/main/java/com/github/muskstark/echart/factory/BarChartFactory.java
[ { "identifier": "Legend", "path": "src/main/java/com/github/muskstark/echart/attribute/Legend.java", "snippet": "@Getter\npublic class Legend {\n\n private String type;\n private String id;\n private Boolean show;\n private Double zLevel;\n private Double z;\n private Object left;\n ...
import com.github.muskstark.echart.attribute.Legend; import com.github.muskstark.echart.attribute.Title; import com.github.muskstark.echart.attribute.axis.XAxis; import com.github.muskstark.echart.attribute.axis.YAxis; import com.github.muskstark.echart.attribute.series.BarSeries; import com.github.muskstark.echart.enums.StyleOfBarChart; import com.github.muskstark.echart.model.bar.BarChart; import com.github.muskstark.echart.style.asix.AxisPointer; import com.github.muskstark.echart.style.background.BackgroundStyle; import java.util.ArrayList;
3,913
package com.github.muskstark.echart.factory; public abstract class BarChartFactory { private static final String TYPE = "bar"; public static BarChart createChart(){ return createBaseBarChart(); } public static BarChart createChart(StyleOfBarChart chartStyle) { BarChart chart = null; String styleOfChart = chartStyle.getStyleOfChart(); if(styleOfChart == null){ chart = createBaseBarChart(); return chart; } switch (styleOfChart) { case "base" -> { chart = createBaseBarChart(); chart.defineTitle().show(false); chart.defineXAxis().type("category"); chart.defineYAxis().type("value"); } case "Axis Align with Tick" -> { chart = createBaseBarChart(); chart.defineToolTip() .trigger("axis") .axisPointer(
package com.github.muskstark.echart.factory; public abstract class BarChartFactory { private static final String TYPE = "bar"; public static BarChart createChart(){ return createBaseBarChart(); } public static BarChart createChart(StyleOfBarChart chartStyle) { BarChart chart = null; String styleOfChart = chartStyle.getStyleOfChart(); if(styleOfChart == null){ chart = createBaseBarChart(); return chart; } switch (styleOfChart) { case "base" -> { chart = createBaseBarChart(); chart.defineTitle().show(false); chart.defineXAxis().type("category"); chart.defineYAxis().type("value"); } case "Axis Align with Tick" -> { chart = createBaseBarChart(); chart.defineToolTip() .trigger("axis") .axisPointer(
new AxisPointer()
7
2023-12-25 08:03:42+00:00
8k
xyzell/OOP_UAS
Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/swing/LoginForm.java
[ { "identifier": "PanelCover", "path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/swing/panel/PanelCover.java", "snippet": "public class PanelCover extends javax.swing.JPanel {\n\n private final DecimalFormat df = new DecimalFormat(\"##0.###\", DecimalFormatSymbols.getInstance(Locale.US));\n ...
import com.itenas.oop.org.uashotel.swing.panel.PanelCover; import com.itenas.oop.org.uashotel.swing.panel.PanelLoading; import com.itenas.oop.org.uashotel.swing.panel.PanelLoginDanRegister; import com.itenas.oop.org.uashotel.swing.component.ExitButton; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; import javax.swing.ImageIcon; import net.miginfocom.swing.MigLayout; import org.jdesktop.animation.timing.Animator; import org.jdesktop.animation.timing.TimingTarget; import org.jdesktop.animation.timing.TimingTargetAdapter;
4,100
package com.itenas.oop.org.uashotel.swing; public class LoginForm extends javax.swing.JFrame { private MigLayout layout;
package com.itenas.oop.org.uashotel.swing; public class LoginForm extends javax.swing.JFrame { private MigLayout layout;
private PanelCover cover;
0
2023-12-24 11:39:51+00:00
8k
LeeKyeongYong/SBookStudy
src/main/java/com/multibook/bookorder/global/initData/NotProd.java
[ { "identifier": "Book", "path": "src/main/java/com/multibook/bookorder/domain/book/book/entity/Book.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\npublic class Book extends BaseTime {\n...
import com.multibook.bookorder.domain.book.book.entity.Book; import com.multibook.bookorder.domain.book.book.service.BookService; import com.multibook.bookorder.domain.cash.cash.entity.CashLog; import com.multibook.bookorder.domain.cash.withdraw.service.WithdrawService; import com.multibook.bookorder.domain.member.member.entity.Member; import com.multibook.bookorder.domain.member.member.service.MemberService; import com.multibook.bookorder.domain.product.cart.service.CartService; import com.multibook.bookorder.domain.product.order.entity.Order; import com.multibook.bookorder.domain.product.order.service.OrderService; import com.multibook.bookorder.domain.product.product.entity.Product; import com.multibook.bookorder.domain.product.product.service.ProductService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import com.multibook.bookorder.domain.product.order.entity.Order; import org.springframework.transaction.annotation.Transactional;
7,074
package com.multibook.bookorder.global.initData; @Configuration @RequiredArgsConstructor public class NotProd { @Autowired @Lazy private NotProd self; private final MemberService memberService; private final BookService bookService;
package com.multibook.bookorder.global.initData; @Configuration @RequiredArgsConstructor public class NotProd { @Autowired @Lazy private NotProd self; private final MemberService memberService; private final BookService bookService;
private final ProductService productService;
10
2023-12-26 14:58:59+00:00
8k
huidongyin/kafka-2.7.2
clients/src/main/java/org/apache/kafka/clients/ClusterConnectionStates.java
[ { "identifier": "AuthenticationException", "path": "clients/src/main/java/org/apache/kafka/common/errors/AuthenticationException.java", "snippet": "public class AuthenticationException extends ApiException {\n\n private static final long serialVersionUID = 1L;\n\n public AuthenticationException(St...
import java.util.Map; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import org.apache.kafka.common.errors.AuthenticationException; import org.apache.kafka.common.utils.ExponentialBackoff; import org.apache.kafka.common.utils.LogContext; import org.slf4j.Logger; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collections; import java.util.HashMap; import java.util.List;
6,476
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.clients; /** * The state of our connection to each node in the cluster. * */ final class ClusterConnectionStates { final static int RECONNECT_BACKOFF_EXP_BASE = 2; final static double RECONNECT_BACKOFF_JITTER = 0.2; final static int CONNECTION_SETUP_TIMEOUT_EXP_BASE = 2; final static double CONNECTION_SETUP_TIMEOUT_JITTER = 0.2; private final Map<String, NodeConnectionState> nodeState; private final Logger log; private final HostResolver hostResolver; private Set<String> connectingNodes; private ExponentialBackoff reconnectBackoff; private ExponentialBackoff connectionSetupTimeout; public ClusterConnectionStates(long reconnectBackoffMs, long reconnectBackoffMaxMs, long connectionSetupTimeoutMs, long connectionSetupTimeoutMaxMs,
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.clients; /** * The state of our connection to each node in the cluster. * */ final class ClusterConnectionStates { final static int RECONNECT_BACKOFF_EXP_BASE = 2; final static double RECONNECT_BACKOFF_JITTER = 0.2; final static int CONNECTION_SETUP_TIMEOUT_EXP_BASE = 2; final static double CONNECTION_SETUP_TIMEOUT_JITTER = 0.2; private final Map<String, NodeConnectionState> nodeState; private final Logger log; private final HostResolver hostResolver; private Set<String> connectingNodes; private ExponentialBackoff reconnectBackoff; private ExponentialBackoff connectionSetupTimeout; public ClusterConnectionStates(long reconnectBackoffMs, long reconnectBackoffMaxMs, long connectionSetupTimeoutMs, long connectionSetupTimeoutMaxMs,
LogContext logContext, HostResolver hostResolver) {
2
2023-12-23 07:12:18+00:00
8k
SDeVuyst/pingys-waddles-1.20.1
src/main/java/com/sdevuyst/pingyswaddles/event/ModEventBusClientEvents.java
[ { "identifier": "PingysWaddles", "path": "src/main/java/com/sdevuyst/pingyswaddles/PingysWaddles.java", "snippet": "@Mod(PingysWaddles.MOD_ID)\npublic class PingysWaddles\n{\n // Define mod id in a common place for everything to reference\n public static final String MOD_ID = \"pingyswaddles\";\n ...
import com.sdevuyst.pingyswaddles.PingysWaddles; import com.sdevuyst.pingyswaddles.entity.client.BabyEmperorPenguinModel; import com.sdevuyst.pingyswaddles.entity.client.EmperorPenguinModel; import com.sdevuyst.pingyswaddles.entity.client.ModModelLayers; import com.sdevuyst.pingyswaddles.entity.client.SurfboardModel; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.EntityRenderersEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod;
5,516
package com.sdevuyst.pingyswaddles.event; @Mod.EventBusSubscriber(modid = PingysWaddles.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) public class ModEventBusClientEvents { @SubscribeEvent public static void registerLayer(EntityRenderersEvent.RegisterLayerDefinitions event) { event.registerLayerDefinition(ModModelLayers.EMPEROR_PENGUIN_LAYER, EmperorPenguinModel::createBodyLayer); event.registerLayerDefinition(ModModelLayers.BABY_EMPEROR_PENGUIN_LAYER, BabyEmperorPenguinModel::createBodyLayer);
package com.sdevuyst.pingyswaddles.event; @Mod.EventBusSubscriber(modid = PingysWaddles.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) public class ModEventBusClientEvents { @SubscribeEvent public static void registerLayer(EntityRenderersEvent.RegisterLayerDefinitions event) { event.registerLayerDefinition(ModModelLayers.EMPEROR_PENGUIN_LAYER, EmperorPenguinModel::createBodyLayer); event.registerLayerDefinition(ModModelLayers.BABY_EMPEROR_PENGUIN_LAYER, BabyEmperorPenguinModel::createBodyLayer);
event.registerLayerDefinition(ModModelLayers.OAK_SURFBOARD_LAYER, SurfboardModel::createBodyLayer);
4
2023-12-31 09:54:03+00:00
8k
IGinX-THU/Parquet
src/main/java/org/apache/parquet/local/ParquetFileReader.java
[ { "identifier": "ColumnChunkPageReader", "path": "src/main/java/org/apache/parquet/local/ColumnChunkPageReadStore.java", "snippet": "static final class ColumnChunkPageReader implements PageReader {\n\n private final BytesInputDecompressor decompressor;\n private final long valueCount;\n private final...
import org.apache.parquet.bytes.ByteBufferInputStream; import org.apache.parquet.bytes.BytesInput; import org.apache.parquet.column.ColumnDescriptor; import org.apache.parquet.column.page.*; import org.apache.parquet.column.values.bloomfilter.BlockSplitBloomFilter; import org.apache.parquet.column.values.bloomfilter.BloomFilter; import org.apache.parquet.compression.CompressionCodecFactory.BytesInputDecompressor; import org.apache.parquet.crypto.*; import org.apache.parquet.crypto.ModuleCipherFactory.ModuleType; import org.apache.parquet.filter2.compat.FilterCompat; import org.apache.parquet.format.*; import org.apache.parquet.hadoop.ParquetEmptyBlockException; import org.apache.parquet.hadoop.metadata.*; import org.apache.parquet.hadoop.metadata.FileMetaData; import org.apache.parquet.internal.column.columnindex.ColumnIndex; import org.apache.parquet.internal.column.columnindex.OffsetIndex; import org.apache.parquet.internal.filter2.columnindex.ColumnIndexFilter; import org.apache.parquet.internal.filter2.columnindex.ColumnIndexStore; import org.apache.parquet.internal.filter2.columnindex.RowRanges; import org.apache.parquet.internal.hadoop.metadata.IndexReference; import org.apache.parquet.io.InputFile; import org.apache.parquet.io.ParquetDecodingException; import org.apache.parquet.io.SeekableInputStream; import org.apache.parquet.local.ColumnChunkPageReadStore.ColumnChunkPageReader; import org.apache.parquet.local.ColumnIndexFilterUtils.OffsetRange; import org.apache.parquet.local.filter2.compat.RowGroupFilter; import org.apache.parquet.schema.MessageType; import org.apache.parquet.schema.PrimitiveType; import org.apache.yetus.audience.InterfaceAudience.Private; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.SequenceInputStream; import java.nio.ByteBuffer; import java.util.*; import java.util.Map.Entry; import java.util.zip.CRC32; import static org.apache.parquet.bytes.BytesUtils.readIntLittleEndian; import static org.apache.parquet.format.Util.readFileCryptoMetaData; import static org.apache.parquet.local.ColumnIndexFilterUtils.calculateOffsetRanges; import static org.apache.parquet.local.ColumnIndexFilterUtils.filterOffsetIndex; import static org.apache.parquet.local.ParquetFileWriter.EFMAGIC; import static org.apache.parquet.local.ParquetFileWriter.MAGIC;
5,912
throw new ParquetEmptyBlockException("Illegal row group of 0 rows"); } RowRanges rowRanges = getRowRanges(blockIndex); return readFilteredRowGroup(blockIndex, rowRanges); } /** * Reads all the columns requested from the specified row group. It may skip specific pages based * on the {@code rowRanges} passed in. As the rows are not aligned among the pages of the * different columns row synchronization might be required. See the documentation of the class * SynchronizingColumnReader for details. * * @param blockIndex the index of the requested block * @param rowRanges the row ranges to be read from the requested block * @return the PageReadStore which can provide PageReaders for each column or null if there are no * rows in this block * @throws IOException if an error occurs while reading * @throws IllegalArgumentException if the {@code blockIndex} is invalid or the {@code rowRanges} * is null */ public ColumnChunkPageReadStore readFilteredRowGroup(int blockIndex, RowRanges rowRanges) throws IOException { if (blockIndex < 0 || blockIndex >= blocks.size()) { throw new IllegalArgumentException( String.format( "Invalid block index %s, the valid block index range are: " + "[%s, %s]", blockIndex, 0, blocks.size() - 1)); } if (Objects.isNull(rowRanges)) { throw new IllegalArgumentException("RowRanges must not be null"); } BlockMetaData block = blocks.get(blockIndex); if (block.getRowCount() == 0L) { return null; } long rowCount = rowRanges.rowCount(); if (rowCount == 0) { // There are no matching rows -> returning null return null; } if (rowCount == block.getRowCount()) { // All rows are matching -> fall back to the non-filtering path return internalReadRowGroup(blockIndex); } return internalReadFilteredRowGroup(block, rowRanges, getColumnIndexStore(blockIndex)); } /** * Reads all the columns requested from the row group at the current file position. It may skip * specific pages based on the column indexes according to the actual filter. As the rows are not * aligned among the pages of the different columns row synchronization might be required. See the * documentation of the class SynchronizingColumnReader for details. * * @return the PageReadStore which can provide PageReaders for each column * @throws IOException if an error occurs while reading */ public PageReadStore readNextFilteredRowGroup() throws IOException { if (currentBlock == blocks.size()) { return null; } // Filtering not required -> fall back to the non-filtering path if (!options.useColumnIndexFilter() || !FilterCompat.isFilteringRequired(options.getRecordFilter())) { return readNextRowGroup(); } BlockMetaData block = blocks.get(currentBlock); if (block.getRowCount() == 0L) { LOG.warn("Read empty block at index {} from {}", currentBlock, getFile()); // Skip the empty block advanceToNextBlock(); return readNextFilteredRowGroup(); } RowRanges rowRanges = getRowRanges(currentBlock); long rowCount = rowRanges.rowCount(); if (rowCount == 0) { // There are no matching rows -> skipping this row-group advanceToNextBlock(); return readNextFilteredRowGroup(); } if (rowCount == block.getRowCount()) { // All rows are matching -> fall back to the non-filtering path return readNextRowGroup(); } this.currentRowGroup = internalReadFilteredRowGroup(block, rowRanges, getColumnIndexStore(currentBlock)); // avoid re-reading bytes the dictionary reader is used after this call if (nextDictionaryReader != null) { nextDictionaryReader.setRowGroup(currentRowGroup); } advanceToNextBlock(); return this.currentRowGroup; } private ColumnChunkPageReadStore internalReadFilteredRowGroup( BlockMetaData block, RowRanges rowRanges, ColumnIndexStore ciStore) throws IOException { ColumnChunkPageReadStore rowGroup = new ColumnChunkPageReadStore(rowRanges, block.getRowIndexOffset()); // prepare the list of consecutive parts to read them in one scan ChunkListBuilder builder = new ChunkListBuilder(block.getRowCount()); List<ConsecutivePartList> allParts = new ArrayList<>(); ConsecutivePartList currentParts = null; for (ColumnChunkMetaData mc : block.getColumns()) { ColumnPath pathKey = mc.getPath(); ColumnDescriptor columnDescriptor = paths.get(pathKey); if (columnDescriptor != null) { OffsetIndex offsetIndex = ciStore.getOffsetIndex(mc.getPath()); OffsetIndex filteredOffsetIndex = filterOffsetIndex(offsetIndex, rowRanges, block.getRowCount()); for (OffsetRange range :
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * copied from parquet-mr, updated by An Qi */ package org.apache.parquet.local; /** Internal implementation of the Parquet file reader as a block container */ public class ParquetFileReader implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(ParquetFileReader.class); private final ParquetMetadataConverter converter; private final CRC32 crc; public static ParquetMetadata readFooter( InputFile file, ParquetReadOptions options, SeekableInputStream f) throws IOException { ParquetMetadataConverter converter = new ParquetMetadataConverter(options); return readFooter(file, options, f, converter); } private static ParquetMetadata readFooter( InputFile file, ParquetReadOptions options, SeekableInputStream f, ParquetMetadataConverter converter) throws IOException { long fileLen = file.getLength(); String filePath = file.toString(); LOG.debug("File length {}", fileLen); int FOOTER_LENGTH_SIZE = 4; if (fileLen < MAGIC.length + FOOTER_LENGTH_SIZE + MAGIC.length) { // MAGIC + data + footer + footerIndex + MAGIC throw new RuntimeException( filePath + " is not a Parquet file (length is too low: " + fileLen + ")"); } // Read footer length and magic string - with a single seek byte[] magic = new byte[MAGIC.length]; long fileMetadataLengthIndex = fileLen - magic.length - FOOTER_LENGTH_SIZE; LOG.debug("reading footer index at {}", fileMetadataLengthIndex); f.seek(fileMetadataLengthIndex); int fileMetadataLength = readIntLittleEndian(f); f.readFully(magic); boolean encryptedFooterMode; if (Arrays.equals(MAGIC, magic)) { encryptedFooterMode = false; } else if (Arrays.equals(EFMAGIC, magic)) { encryptedFooterMode = true; } else { throw new RuntimeException( filePath + " is not a Parquet file. Expected magic number at tail, but found " + Arrays.toString(magic)); } long fileMetadataIndex = fileMetadataLengthIndex - fileMetadataLength; LOG.debug("read footer length: {}, footer index: {}", fileMetadataLength, fileMetadataIndex); if (fileMetadataIndex < magic.length || fileMetadataIndex >= fileMetadataLengthIndex) { throw new RuntimeException( "corrupted file: the footer index is not within the file: " + fileMetadataIndex); } f.seek(fileMetadataIndex); FileDecryptionProperties fileDecryptionProperties = options.getDecryptionProperties(); InternalFileDecryptor fileDecryptor = null; if (null != fileDecryptionProperties) { fileDecryptor = new InternalFileDecryptor(fileDecryptionProperties); } // Read all the footer bytes in one time to avoid multiple read operations, // since it can be pretty time consuming for a single read operation in HDFS. ByteBuffer footerBytesBuffer = ByteBuffer.allocate(fileMetadataLength); f.readFully(footerBytesBuffer); LOG.debug("Finished to read all footer bytes."); footerBytesBuffer.flip(); InputStream footerBytesStream = ByteBufferInputStream.wrap(footerBytesBuffer); // Regular file, or encrypted file with plaintext footer if (!encryptedFooterMode) { return converter.readParquetMetadata( footerBytesStream, options.getMetadataFilter(), fileDecryptor, false, fileMetadataLength); } // Encrypted file with encrypted footer if (null == fileDecryptor) { throw new ParquetCryptoRuntimeException( "Trying to read file with encrypted footer. No keys available"); } FileCryptoMetaData fileCryptoMetaData = readFileCryptoMetaData(footerBytesStream); fileDecryptor.setFileCryptoMetaData( fileCryptoMetaData.getEncryption_algorithm(), true, fileCryptoMetaData.getKey_metadata()); // footer length is required only for signed plaintext footers return converter.readParquetMetadata( footerBytesStream, options.getMetadataFilter(), fileDecryptor, true, 0); } protected final SeekableInputStream f; private final InputFile file; private final ParquetReadOptions options; private final Map<ColumnPath, ColumnDescriptor> paths = new HashMap<>(); private final FileMetaData fileMetaData; // may be null private final List<BlockMetaData> blocks; private final List<ColumnIndexStore> blockIndexStores; private final List<RowRanges> blockRowRanges; // not final. in some cases, this may be lazily loaded for backward-compat. private final ParquetMetadata footer; private int currentBlock = 0; private ColumnChunkPageReadStore currentRowGroup = null; private DictionaryPageReader nextDictionaryReader = null; private InternalFileDecryptor fileDecryptor = null; public ParquetFileReader(InputFile file, ParquetMetadata footer, ParquetReadOptions options) throws IOException { this.converter = new ParquetMetadataConverter(options); this.file = file; this.options = options; this.f = file.newStream(); try { this.footer = footer; this.fileMetaData = footer.getFileMetaData(); this.fileDecryptor = fileMetaData.getFileDecryptor(); // must be called before filterRowGroups! if (null != fileDecryptor && fileDecryptor.plaintextFile()) { this.fileDecryptor = null; // Plaintext file. No need in decryptor } this.blocks = filterRowGroups(footer.getBlocks()); this.blockIndexStores = listWithNulls(this.blocks.size()); this.blockRowRanges = listWithNulls(this.blocks.size()); for (ColumnDescriptor col : footer.getFileMetaData().getSchema().getColumns()) { paths.put(ColumnPath.get(col.getPath()), col); } this.crc = options.usePageChecksumVerification() ? new CRC32() : null; } catch (Exception e) { f.close(); throw e; } } private static <T> List<T> listWithNulls(int size) { return new ArrayList<>(Collections.nCopies(size, null)); } public FileMetaData getFileMetaData() { return fileMetaData; } public long getRecordCount() { long total = 0L; for (BlockMetaData block : blocks) { total += block.getRowCount(); } return total; } public long getFilteredRecordCount() { if (!options.useColumnIndexFilter() || !FilterCompat.isFilteringRequired(options.getRecordFilter())) { return getRecordCount(); } long total = 0L; for (int i = 0, n = blocks.size(); i < n; ++i) { total += getRowRanges(i).rowCount(); } return total; } public String getFile() { return file.toString(); } public List<BlockMetaData> filterRowGroups(List<BlockMetaData> blocks) throws IOException { FilterCompat.Filter recordFilter = options.getRecordFilter(); if (FilterCompat.isFilteringRequired(recordFilter)) { // set up data filters based on configured levels List<RowGroupFilter.FilterLevel> levels = new ArrayList<>(); if (options.useStatsFilter()) { levels.add(RowGroupFilter.FilterLevel.STATISTICS); } if (options.useDictionaryFilter()) { levels.add(RowGroupFilter.FilterLevel.DICTIONARY); } if (options.useBloomFilter()) { levels.add(RowGroupFilter.FilterLevel.BLOOMFILTER); } return RowGroupFilter.filterRowGroups(levels, recordFilter, blocks, this); } return blocks; } public List<BlockMetaData> getRowGroups() { return blocks; } private MessageType requestedSchema = null; public void setRequestedSchema(MessageType projection) { requestedSchema = projection; paths.clear(); for (ColumnDescriptor col : projection.getColumns()) { paths.put(ColumnPath.get(col.getPath()), col); } } public MessageType getRequestedSchema() { if (requestedSchema == null) { return fileMetaData.getSchema(); } return requestedSchema; } /** * Reads all the columns requested from the row group at the specified block. * * @param blockIndex the index of the requested block * @return the PageReadStore which can provide PageReaders for each column. * @throws IOException if an error occurs while reading */ public PageReadStore readRowGroup(int blockIndex) throws IOException { return internalReadRowGroup(blockIndex); } /** * Reads all the columns requested from the row group at the current file position. * * @return the PageReadStore which can provide PageReaders for each column. * @throws IOException if an error occurs while reading */ public PageReadStore readNextRowGroup() throws IOException { ColumnChunkPageReadStore rowGroup = null; try { rowGroup = internalReadRowGroup(currentBlock); } catch (ParquetEmptyBlockException e) { LOG.warn("Read empty block at index {} from {}", currentBlock, getFile()); advanceToNextBlock(); return readNextRowGroup(); } if (rowGroup == null) { return null; } this.currentRowGroup = rowGroup; // avoid re-reading bytes the dictionary reader is used after this call if (nextDictionaryReader != null) { nextDictionaryReader.setRowGroup(currentRowGroup); } advanceToNextBlock(); return currentRowGroup; } private ColumnChunkPageReadStore internalReadRowGroup(int blockIndex) throws IOException { if (blockIndex < 0 || blockIndex >= blocks.size()) { return null; } BlockMetaData block = blocks.get(blockIndex); if (block.getRowCount() == 0) { throw new ParquetEmptyBlockException("Illegal row group of 0 rows"); } org.apache.parquet.local.ColumnChunkPageReadStore rowGroup = new ColumnChunkPageReadStore(block.getRowCount(), block.getRowIndexOffset()); // prepare the list of consecutive parts to read them in one scan List<ConsecutivePartList> allParts = new ArrayList<ConsecutivePartList>(); ConsecutivePartList currentParts = null; for (ColumnChunkMetaData mc : block.getColumns()) { ColumnPath pathKey = mc.getPath(); ColumnDescriptor columnDescriptor = paths.get(pathKey); if (columnDescriptor != null) { long startingPos = mc.getStartingPos(); // first part or not consecutive => new list if (currentParts == null || currentParts.endPos() != startingPos) { currentParts = new ConsecutivePartList(startingPos); allParts.add(currentParts); } currentParts.addChunk( new ChunkDescriptor(columnDescriptor, mc, startingPos, mc.getTotalSize())); } } // actually read all the chunks ChunkListBuilder builder = new ChunkListBuilder(block.getRowCount()); for (ConsecutivePartList consecutiveChunks : allParts) { consecutiveChunks.readAll(f, builder); } for (Chunk chunk : builder.build()) { readChunkPages(chunk, block, rowGroup); } return rowGroup; } /** * Reads all the columns requested from the specified row group. It may skip specific pages based * on the column indexes according to the actual filter. As the rows are not aligned among the * pages of the different columns row synchronization might be required. See the documentation of * the class SynchronizingColumnReader for details. * * @param blockIndex the index of the requested block * @return the PageReadStore which can provide PageReaders for each column or null if there are no * rows in this block * @throws IOException if an error occurs while reading */ public PageReadStore readFilteredRowGroup(int blockIndex) throws IOException { if (blockIndex < 0 || blockIndex >= blocks.size()) { return null; } // Filtering not required -> fall back to the non-filtering path if (!options.useColumnIndexFilter() || !FilterCompat.isFilteringRequired(options.getRecordFilter())) { return internalReadRowGroup(blockIndex); } BlockMetaData block = blocks.get(blockIndex); if (block.getRowCount() == 0) { throw new ParquetEmptyBlockException("Illegal row group of 0 rows"); } RowRanges rowRanges = getRowRanges(blockIndex); return readFilteredRowGroup(blockIndex, rowRanges); } /** * Reads all the columns requested from the specified row group. It may skip specific pages based * on the {@code rowRanges} passed in. As the rows are not aligned among the pages of the * different columns row synchronization might be required. See the documentation of the class * SynchronizingColumnReader for details. * * @param blockIndex the index of the requested block * @param rowRanges the row ranges to be read from the requested block * @return the PageReadStore which can provide PageReaders for each column or null if there are no * rows in this block * @throws IOException if an error occurs while reading * @throws IllegalArgumentException if the {@code blockIndex} is invalid or the {@code rowRanges} * is null */ public ColumnChunkPageReadStore readFilteredRowGroup(int blockIndex, RowRanges rowRanges) throws IOException { if (blockIndex < 0 || blockIndex >= blocks.size()) { throw new IllegalArgumentException( String.format( "Invalid block index %s, the valid block index range are: " + "[%s, %s]", blockIndex, 0, blocks.size() - 1)); } if (Objects.isNull(rowRanges)) { throw new IllegalArgumentException("RowRanges must not be null"); } BlockMetaData block = blocks.get(blockIndex); if (block.getRowCount() == 0L) { return null; } long rowCount = rowRanges.rowCount(); if (rowCount == 0) { // There are no matching rows -> returning null return null; } if (rowCount == block.getRowCount()) { // All rows are matching -> fall back to the non-filtering path return internalReadRowGroup(blockIndex); } return internalReadFilteredRowGroup(block, rowRanges, getColumnIndexStore(blockIndex)); } /** * Reads all the columns requested from the row group at the current file position. It may skip * specific pages based on the column indexes according to the actual filter. As the rows are not * aligned among the pages of the different columns row synchronization might be required. See the * documentation of the class SynchronizingColumnReader for details. * * @return the PageReadStore which can provide PageReaders for each column * @throws IOException if an error occurs while reading */ public PageReadStore readNextFilteredRowGroup() throws IOException { if (currentBlock == blocks.size()) { return null; } // Filtering not required -> fall back to the non-filtering path if (!options.useColumnIndexFilter() || !FilterCompat.isFilteringRequired(options.getRecordFilter())) { return readNextRowGroup(); } BlockMetaData block = blocks.get(currentBlock); if (block.getRowCount() == 0L) { LOG.warn("Read empty block at index {} from {}", currentBlock, getFile()); // Skip the empty block advanceToNextBlock(); return readNextFilteredRowGroup(); } RowRanges rowRanges = getRowRanges(currentBlock); long rowCount = rowRanges.rowCount(); if (rowCount == 0) { // There are no matching rows -> skipping this row-group advanceToNextBlock(); return readNextFilteredRowGroup(); } if (rowCount == block.getRowCount()) { // All rows are matching -> fall back to the non-filtering path return readNextRowGroup(); } this.currentRowGroup = internalReadFilteredRowGroup(block, rowRanges, getColumnIndexStore(currentBlock)); // avoid re-reading bytes the dictionary reader is used after this call if (nextDictionaryReader != null) { nextDictionaryReader.setRowGroup(currentRowGroup); } advanceToNextBlock(); return this.currentRowGroup; } private ColumnChunkPageReadStore internalReadFilteredRowGroup( BlockMetaData block, RowRanges rowRanges, ColumnIndexStore ciStore) throws IOException { ColumnChunkPageReadStore rowGroup = new ColumnChunkPageReadStore(rowRanges, block.getRowIndexOffset()); // prepare the list of consecutive parts to read them in one scan ChunkListBuilder builder = new ChunkListBuilder(block.getRowCount()); List<ConsecutivePartList> allParts = new ArrayList<>(); ConsecutivePartList currentParts = null; for (ColumnChunkMetaData mc : block.getColumns()) { ColumnPath pathKey = mc.getPath(); ColumnDescriptor columnDescriptor = paths.get(pathKey); if (columnDescriptor != null) { OffsetIndex offsetIndex = ciStore.getOffsetIndex(mc.getPath()); OffsetIndex filteredOffsetIndex = filterOffsetIndex(offsetIndex, rowRanges, block.getRowCount()); for (OffsetRange range :
calculateOffsetRanges(filteredOffsetIndex, mc, offsetIndex.getOffset(0))) {
3
2023-12-29 01:48:28+00:00
8k
iamamritpalrandhawa/JChess
Engines/InitEngine.java
[ { "identifier": "ChessBoard", "path": "Chess/ChessBoard.java", "snippet": "public class ChessBoard {\r\n private JFrame frame;\r\n DbEngine db = new DbEngine();\r\n private BoardPanel boardPanel;\r\n private ChessEngine gameState;\r\n private static final int SQ_SIZE = 90;\r\n private ...
import Chess.ChessBoard; import Chess.InfoBoard; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane;
4,435
package Engines; public class InitEngine extends JFrame implements ActionListener { JButton startButton; public InitEngine() { setTitle("Start a Chess Game"); ImageIcon logo = new ImageIcon("Resources/Icons/logo-b.png"); setIconImage(logo.getImage()); setSize(600, 400); setResizable(false); getContentPane().setBackground(new Color(27, 27, 27)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(null); JLabel mainHeading = new JLabel("Chess", JLabel.CENTER); mainHeading.setForeground(Color.WHITE); mainHeading.setFont(new Font("OLD ENGLISH TEXT MT", Font.BOLD, 55)); mainHeading.setBounds(210, 60, 160, 39); add(mainHeading); String[] menuItems = { "Human", "Magnus (AI)" }; JComboBox<String> dropdown_w = new JComboBox<>(menuItems); dropdown_w.setBounds(80, 185, 100, 30); ImageIcon versus = new ImageIcon("Resources/Icons/vs.png"); JLabel versusLabel = new JLabel(versus); versusLabel.setBounds(180, 120, versus.getIconWidth(), versus.getIconHeight()); add(versusLabel); JComboBox<String> dropdown_b = new JComboBox<>(menuItems); dropdown_b.setBounds(410, 185, 100, 30); add(dropdown_w); add(dropdown_b); JLabel whiteLabel = new JLabel("White"); whiteLabel.setForeground(Color.WHITE); whiteLabel.setBounds(110, 225, 100, 30); add(whiteLabel); JLabel blackLabel = new JLabel("Black"); blackLabel.setForeground(Color.WHITE); blackLabel.setBounds(440, 225, 100, 30); add(blackLabel); startButton = new JButton("Start"); startButton.setBounds(245, 295, 100, 30); startButton.setFocusPainted(false); startButton.setBackground(new Color(255, 255, 255)); startButton.setForeground(new Color(27, 27, 27)); startButton.setFont(new Font("Arial", Font.BOLD, 14)); startButton.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(new Color(27, 27, 27), 2), BorderFactory.createEmptyBorder(5, 10, 5, 10))); startButton.setOpaque(true); startButton.setBorderPainted(false); startButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { startButton.setBackground(new Color(27, 27, 27)); startButton.setForeground(new Color(255, 255, 255)); } public void mouseExited(java.awt.event.MouseEvent evt) { startButton.setBackground(new Color(255, 255, 255)); startButton.setForeground(new Color(27, 27, 27)); } }); startButton.addActionListener(this); add(startButton); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == startButton) { boolean p1 = false, p2 = false; String whitePlayer = (String) ((JComboBox<?>) getContentPane().getComponent(2)).getSelectedItem(); String blackPlayer = (String) ((JComboBox<?>) getContentPane().getComponent(3)).getSelectedItem(); if (whitePlayer.length() == 5 && whitePlayer.substring(0, 5).equals("Human")) { p1 = true; } if (blackPlayer.length() == 5 && blackPlayer.substring(0, 5).equals("Human")) { p2 = true; } InfoBoard info = null; if (p1 && p2) { String p1Name = JOptionPane.showInputDialog(this, "Enter name of Player 1:"); while (p1Name == null || p1Name.trim().isEmpty()) { p1Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 1:"); } String p2Name = JOptionPane.showInputDialog(this, "Enter name of Player 2:"); while (p2Name == null || p2Name.trim().isEmpty()) { p2Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 2:"); } info = new InfoBoard(p1Name, p2Name); } else if (p1) { String p1Name = JOptionPane.showInputDialog(this, "Enter name of Player 1:"); while (p1Name == null || p1Name.trim().isEmpty()) { p1Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 1:"); } info = new InfoBoard(p1Name, blackPlayer); } else if (p2) { String p2Name = JOptionPane.showInputDialog(this, "Enter name of Player 2:"); while (p2Name == null || p2Name.trim().isEmpty()) { p2Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 2:"); } info = new InfoBoard(whitePlayer, p2Name); } else { info = new InfoBoard(whitePlayer, blackPlayer); }
package Engines; public class InitEngine extends JFrame implements ActionListener { JButton startButton; public InitEngine() { setTitle("Start a Chess Game"); ImageIcon logo = new ImageIcon("Resources/Icons/logo-b.png"); setIconImage(logo.getImage()); setSize(600, 400); setResizable(false); getContentPane().setBackground(new Color(27, 27, 27)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(null); JLabel mainHeading = new JLabel("Chess", JLabel.CENTER); mainHeading.setForeground(Color.WHITE); mainHeading.setFont(new Font("OLD ENGLISH TEXT MT", Font.BOLD, 55)); mainHeading.setBounds(210, 60, 160, 39); add(mainHeading); String[] menuItems = { "Human", "Magnus (AI)" }; JComboBox<String> dropdown_w = new JComboBox<>(menuItems); dropdown_w.setBounds(80, 185, 100, 30); ImageIcon versus = new ImageIcon("Resources/Icons/vs.png"); JLabel versusLabel = new JLabel(versus); versusLabel.setBounds(180, 120, versus.getIconWidth(), versus.getIconHeight()); add(versusLabel); JComboBox<String> dropdown_b = new JComboBox<>(menuItems); dropdown_b.setBounds(410, 185, 100, 30); add(dropdown_w); add(dropdown_b); JLabel whiteLabel = new JLabel("White"); whiteLabel.setForeground(Color.WHITE); whiteLabel.setBounds(110, 225, 100, 30); add(whiteLabel); JLabel blackLabel = new JLabel("Black"); blackLabel.setForeground(Color.WHITE); blackLabel.setBounds(440, 225, 100, 30); add(blackLabel); startButton = new JButton("Start"); startButton.setBounds(245, 295, 100, 30); startButton.setFocusPainted(false); startButton.setBackground(new Color(255, 255, 255)); startButton.setForeground(new Color(27, 27, 27)); startButton.setFont(new Font("Arial", Font.BOLD, 14)); startButton.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(new Color(27, 27, 27), 2), BorderFactory.createEmptyBorder(5, 10, 5, 10))); startButton.setOpaque(true); startButton.setBorderPainted(false); startButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { startButton.setBackground(new Color(27, 27, 27)); startButton.setForeground(new Color(255, 255, 255)); } public void mouseExited(java.awt.event.MouseEvent evt) { startButton.setBackground(new Color(255, 255, 255)); startButton.setForeground(new Color(27, 27, 27)); } }); startButton.addActionListener(this); add(startButton); setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == startButton) { boolean p1 = false, p2 = false; String whitePlayer = (String) ((JComboBox<?>) getContentPane().getComponent(2)).getSelectedItem(); String blackPlayer = (String) ((JComboBox<?>) getContentPane().getComponent(3)).getSelectedItem(); if (whitePlayer.length() == 5 && whitePlayer.substring(0, 5).equals("Human")) { p1 = true; } if (blackPlayer.length() == 5 && blackPlayer.substring(0, 5).equals("Human")) { p2 = true; } InfoBoard info = null; if (p1 && p2) { String p1Name = JOptionPane.showInputDialog(this, "Enter name of Player 1:"); while (p1Name == null || p1Name.trim().isEmpty()) { p1Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 1:"); } String p2Name = JOptionPane.showInputDialog(this, "Enter name of Player 2:"); while (p2Name == null || p2Name.trim().isEmpty()) { p2Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 2:"); } info = new InfoBoard(p1Name, p2Name); } else if (p1) { String p1Name = JOptionPane.showInputDialog(this, "Enter name of Player 1:"); while (p1Name == null || p1Name.trim().isEmpty()) { p1Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 1:"); } info = new InfoBoard(p1Name, blackPlayer); } else if (p2) { String p2Name = JOptionPane.showInputDialog(this, "Enter name of Player 2:"); while (p2Name == null || p2Name.trim().isEmpty()) { p2Name = JOptionPane.showInputDialog(this, "Please enter a valid name for Player 2:"); } info = new InfoBoard(whitePlayer, p2Name); } else { info = new InfoBoard(whitePlayer, blackPlayer); }
new ChessBoard(p1, p2, info, whitePlayer, blackPlayer);
0
2023-12-28 13:53:01+00:00
8k
Yanyutin753/PandoraNext-TokensTool
rearServer/src/main/java/com/tokensTool/pandoraNext/controller/taskController.java
[ { "identifier": "Result", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/Result.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Result {\n\n /**\n * 响应码,1 代表成功; 0 代表失败\n */\n\n private Integer code;\n /**\n * 响应信息 描述字符串\n */\n\n...
import com.tokensTool.pandoraNext.pojo.Result; import com.tokensTool.pandoraNext.pojo.systemSetting; import com.tokensTool.pandoraNext.service.impl.systemServiceImpl; import com.tokensTool.pandoraNext.util.MyTaskUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
5,491
package com.tokensTool.pandoraNext.controller; @RestController @RequestMapping("/api") public class taskController { private final MyTaskUtils myTaskUtils; @Autowired
package com.tokensTool.pandoraNext.controller; @RestController @RequestMapping("/api") public class taskController { private final MyTaskUtils myTaskUtils; @Autowired
private systemServiceImpl systemSetting;
2
2023-11-17 11:37:37+00:00
8k
bryan31/Akali
src/main/java/org/dromara/akali/proxy/AkaliByteBuddyProxy.java
[ { "identifier": "AkaliStrategyEnum", "path": "src/main/java/org/dromara/akali/enums/AkaliStrategyEnum.java", "snippet": "public enum AkaliStrategyEnum {\n\n FALLBACK, HOT_METHOD\n}" }, { "identifier": "AkaliMethodManager", "path": "src/main/java/org/dromara/akali/manager/AkaliMethodManage...
import cn.hutool.core.util.StrUtil; import com.alibaba.csp.sentinel.util.MethodUtil; import net.bytebuddy.implementation.attribute.MethodAttributeAppender; import org.dromara.akali.annotation.AkaliFallback; import org.dromara.akali.annotation.AkaliHot; import org.dromara.akali.enums.AkaliStrategyEnum; import org.dromara.akali.manager.AkaliMethodManager; import org.dromara.akali.manager.AkaliRuleManager; import org.dromara.akali.sph.SphEngine; import org.dromara.akali.util.SerialsUtil; import net.bytebuddy.ByteBuddy; import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; import net.bytebuddy.implementation.InvocationHandlerAdapter; import net.bytebuddy.matcher.ElementMatchers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method;
4,051
package org.dromara.akali.proxy; public class AkaliByteBuddyProxy { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final Object bean; private final Class<?> originalClazz; public AkaliByteBuddyProxy(Object bean, Class<?> originalClazz) { this.bean = bean; this.originalClazz = originalClazz; } public Object proxy() throws Exception{ return new ByteBuddy().subclass(originalClazz) .name(StrUtil.format("{}$ByteBuddy${}", bean.getClass().getName(), SerialsUtil.generateShortUUID())) .method(ElementMatchers.any()) .intercept(InvocationHandlerAdapter.of(new AopInvocationHandler())) .attribute(MethodAttributeAppender.ForInstrumentedMethod.INCLUDING_RECEIVER) .annotateType(bean.getClass().getAnnotations()) .make() .load(AkaliByteBuddyProxy.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION) .getLoaded() .newInstance(); } public class AopInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodStr = MethodUtil.resolveMethodName(method); if (AkaliMethodManager.contain(methodStr)){ AkaliStrategyEnum akaliStrategyEnum = AkaliMethodManager.getAnnoInfo(methodStr).r1; Annotation anno = AkaliMethodManager.getAnnoInfo(methodStr).r2; if (anno instanceof AkaliFallback){
package org.dromara.akali.proxy; public class AkaliByteBuddyProxy { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final Object bean; private final Class<?> originalClazz; public AkaliByteBuddyProxy(Object bean, Class<?> originalClazz) { this.bean = bean; this.originalClazz = originalClazz; } public Object proxy() throws Exception{ return new ByteBuddy().subclass(originalClazz) .name(StrUtil.format("{}$ByteBuddy${}", bean.getClass().getName(), SerialsUtil.generateShortUUID())) .method(ElementMatchers.any()) .intercept(InvocationHandlerAdapter.of(new AopInvocationHandler())) .attribute(MethodAttributeAppender.ForInstrumentedMethod.INCLUDING_RECEIVER) .annotateType(bean.getClass().getAnnotations()) .make() .load(AkaliByteBuddyProxy.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION) .getLoaded() .newInstance(); } public class AopInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodStr = MethodUtil.resolveMethodName(method); if (AkaliMethodManager.contain(methodStr)){ AkaliStrategyEnum akaliStrategyEnum = AkaliMethodManager.getAnnoInfo(methodStr).r1; Annotation anno = AkaliMethodManager.getAnnoInfo(methodStr).r2; if (anno instanceof AkaliFallback){
AkaliRuleManager.registerFallbackRule((AkaliFallback) anno, method);
2
2023-11-10 07:28:38+00:00
8k
quarkiverse/quarkus-langchain4j
openai/openai-vanilla/deployment/src/test/java/org/acme/examples/aiservices/AiServicesTest.java
[ { "identifier": "DEFAULT_TOKEN", "path": "openai/openai-vanilla/deployment/src/test/java/io/quarkiverse/langchain4j/openai/test/WiremockUtils.java", "snippet": "public static final String DEFAULT_TOKEN = \"whatever\";" }, { "identifier": "MessageAssertUtils", "path": "openai/openai-vanilla/d...
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; import static dev.langchain4j.data.message.ChatMessageDeserializer.messagesFromJson; import static dev.langchain4j.data.message.ChatMessageSerializer.messagesToJson; import static dev.langchain4j.data.message.ChatMessageType.AI; import static dev.langchain4j.data.message.ChatMessageType.SYSTEM; import static dev.langchain4j.data.message.ChatMessageType.USER; import static io.quarkiverse.langchain4j.openai.test.WiremockUtils.DEFAULT_TOKEN; import static java.time.Month.JULY; import static org.acme.examples.aiservices.MessageAssertUtils.*; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import java.io.IOException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import jakarta.validation.constraints.NotNull; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.stubbing.Scenario; import com.github.tomakehurst.wiremock.stubbing.ServeEvent; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import dev.langchain4j.agent.tool.Tool; import dev.langchain4j.data.message.ChatMessage; import dev.langchain4j.memory.chat.ChatMemoryProvider; import dev.langchain4j.memory.chat.MessageWindowChatMemory; import dev.langchain4j.model.input.structured.StructuredPrompt; import dev.langchain4j.model.openai.OpenAiChatModel; import dev.langchain4j.model.openai.OpenAiModerationModel; import dev.langchain4j.model.output.structured.Description; import dev.langchain4j.service.AiServices; import dev.langchain4j.service.MemoryId; import dev.langchain4j.service.Moderate; import dev.langchain4j.service.ModerationException; import dev.langchain4j.service.SystemMessage; import dev.langchain4j.service.UserMessage; import dev.langchain4j.service.V; import dev.langchain4j.store.memory.chat.ChatMemoryStore; import io.opentelemetry.instrumentation.annotations.SpanAttribute; import io.quarkiverse.langchain4j.openai.test.WiremockUtils; import io.quarkus.test.QuarkusUnitTest;
5,296
assertThat(result.title).isNotBlank(); assertThat(result.description).isNotBlank(); assertThat(result.steps).isNotEmpty(); assertThat(result.preparationTimeMinutes).isPositive(); assertSingleRequestMessage(getRequestAsMap(), "Create a recipe of a salad that can be prepared using only [cucumber, tomato, feta, onion, olives]\nYou must answer strictly in the following JSON format: {\n\"title\": (type: string),\n\"description\": (type: string),\n\"steps\": (each step should be described in 4 words, steps should rhyme; type: array of string),\n\"preparationTimeMinutes\": (type: integer),\n}"); } @Test void test_create_recipe_using_structured_prompt_and_system_message() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), // this is supposed to be a string inside a json string hence all the escaping... "{\\n\\\"title\\\": \\\"Greek Medley Salad\\\",\\n\\\"description\\\": \\\"A refreshing and tangy salad with a Mediterranean twist.\\\",\\n\\\"steps\\\": [\\n\\\"Slice and dice, precise!\\\",\\n\\\"Mix and toss, no loss!\\\",\\n\\\"Sprinkle feta, get betta!\\\",\\n\\\"Garnish with olives, no jives!\\\"\\n],\\n\\\"preparationTimeMinutes\\\": 15\\n}")); Chef chef = AiServices.create(Chef.class, createChatModel()); Recipe result = chef .createRecipeFrom(new CreateRecipePrompt("salad", List.of("cucumber", "tomato", "feta", "onion", "olives")), "funny"); assertThat(result.title).isEqualTo("Greek Medley Salad"); assertThat(result.description).isNotBlank(); assertThat(result.steps).hasSize(4).satisfies(strings -> { assertThat(strings[0]).contains("Slice and dice"); assertThat(strings[3]).contains("jives"); }); assertThat(result.preparationTimeMinutes).isEqualTo(15); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "You are a very funny chef"), new MessageContent("user", "Create a recipe of a salad that can be prepared using only [cucumber, tomato, feta, onion, olives]\nYou must answer strictly in the following JSON format: {\n\"title\": (type: string),\n\"description\": (type: string),\n\"steps\": (each step should be described in 4 words, steps should rhyme; type: array of string),\n\"preparationTimeMinutes\": (type: integer),\n}"))); } interface ProfessionalChef { @SystemMessage("You are a professional chef. You are friendly, polite and concise.") String answer(String question); } @Test void test_with_system_message() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "Grilling chicken typically takes around 10-15 minutes per side, depending on the thickness of the chicken. It's important to ensure the internal temperature reaches 165°F (74°C) for safe consumption.")); ProfessionalChef chef = AiServices.create(ProfessionalChef.class, createChatModel()); String result = chef.answer("How long should I grill chicken?"); assertThat(result).contains("Grilling chicken typically"); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "You are a professional chef. You are friendly, polite and concise."), new MessageContent("user", "How long should I grill chicken?"))); } interface Translator { @SystemMessage("You are a professional translator into {{lang}}") @UserMessage("Translate the following text: {{text}}") String translate(@V("text") String text, @V("lang") String language); } @Test void test_with_system_and_user_messages() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "Hallo, wie geht es dir?")); Translator translator = AiServices.create(Translator.class, createChatModel()); String translation = translator.translate("Hello, how are you?", "german"); assertThat(translation).isEqualTo("Hallo, wie geht es dir?"); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "You are a professional translator into german"), new MessageContent("user", "Translate the following text: Hello, how are you?"))); } interface Summarizer { @SystemMessage("Summarize every message from user in {{n}} bullet points. Provide only bullet points.") List<String> summarize(@UserMessage String text, int n); } @Test void test_with_system_message_and_user_message_as_argument() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "- AI is a branch of computer science\\n- AI aims to create machines that mimic human intelligence\\n- AI can perform tasks like recognizing patterns, making decisions, and predictions")); Summarizer summarizer = AiServices.create(Summarizer.class, createChatModel()); String text = "AI, or artificial intelligence, is a branch of computer science that aims to create " + "machines that mimic human intelligence. This can range from simple tasks such as recognizing " + "patterns or speech to more complex tasks like making decisions or predictions."; List<String> bulletPoints = summarizer.summarize(text, 3); assertThat(bulletPoints).hasSize(3).satisfies(list -> { assertThat(list.get(0)).contains("branch"); assertThat(list.get(2)).contains("predictions"); }); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "Summarize every message from user in 3 bullet points. Provide only bullet points."), new MessageContent("user", text + "\nYou must put every item on a separate line."))); } interface ChatWithModeration { @Moderate String chat(String message); } @Test void should_throw_when_text_is_flagged() {
package org.acme.examples.aiservices; public class AiServicesTest { @RegisterExtension static final QuarkusUnitTest unitTest = new QuarkusUnitTest() .setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class).addClasses(WiremockUtils.class, MessageAssertUtils.class)); static WireMockServer wireMockServer; static ObjectMapper mapper; private static OpenAiChatModel createChatModel() { return OpenAiChatModel.builder().baseUrl("http://localhost:8089/v1") .logRequests(true) .logResponses(true) .apiKey("whatever").build(); } private static OpenAiModerationModel createModerationModel() { return OpenAiModerationModel.builder().baseUrl("http://localhost:8089/v1") .logRequests(true) .logResponses(true) .apiKey("whatever").build(); } private static MessageWindowChatMemory createChatMemory() { return MessageWindowChatMemory.withMaxMessages(10); } @BeforeAll static void beforeAll() { wireMockServer = new WireMockServer(options().port(8089)); wireMockServer.start(); mapper = new ObjectMapper(); } @AfterAll static void afterAll() { wireMockServer.stop(); } @BeforeEach void setup() { wireMockServer.resetAll(); wireMockServer.stubFor(WiremockUtils.defaultChatCompletionsStub()); } interface Assistant { String chat(String message); } @Test public void test_simple_instruction_with_single_argument_and_no_annotations() throws IOException { String result = AiServices.create(Assistant.class, createChatModel()).chat("Tell me a joke about developers"); assertThat(result).isNotBlank(); assertSingleRequestMessage(getRequestAsMap(), "Tell me a joke about developers"); } interface Humorist { @UserMessage("Tell me a joke about {{wrapper.topic}}") String joke(@SpanAttribute @NotNull Wrapper wrapper); } public record Wrapper(String topic) { } @Test public void test_simple_instruction_with_single_argument() throws IOException { String result = AiServices.create(Humorist.class, createChatModel()).joke(new Wrapper("programmers")); assertThat(result).isNotBlank(); assertSingleRequestMessage(getRequestAsMap(), "Tell me a joke about programmers"); } interface DateTimeExtractor { @UserMessage("Extract date from {{it}}") LocalDate extractDateFrom(String text); @UserMessage("Extract time from {{it}}") LocalTime extractTimeFrom(String text); @UserMessage("Extract date and time from {{it}}") LocalDateTime extractDateTimeFrom(String text); } @Test void test_extract_date() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "1968-07-04")); DateTimeExtractor dateTimeExtractor = AiServices.create(DateTimeExtractor.class, createChatModel()); LocalDate result = dateTimeExtractor.extractDateFrom( "The tranquility pervaded the evening of 1968, just fifteen minutes shy of midnight, following the celebrations of Independence Day."); assertThat(result).isEqualTo(LocalDate.of(1968, JULY, 4)); assertSingleRequestMessage(getRequestAsMap(), "Extract date from The tranquility pervaded the evening of 1968, just fifteen minutes shy of midnight, following the celebrations of Independence Day.\nYou must answer strictly in the following format: 2023-12-31"); } @Test void test_extract_time() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "23:45:00")); DateTimeExtractor dateTimeExtractor = AiServices.create(DateTimeExtractor.class, createChatModel()); LocalTime result = dateTimeExtractor.extractTimeFrom( "The tranquility pervaded the evening of 1968, just fifteen minutes shy of midnight, following the celebrations of Independence Day."); assertThat(result).isEqualTo(LocalTime.of(23, 45, 0)); assertSingleRequestMessage(getRequestAsMap(), "Extract time from The tranquility pervaded the evening of 1968, just fifteen minutes shy of midnight, following the celebrations of Independence Day.\nYou must answer strictly in the following format: 23:59:59"); } @Test void test_extract_date_time() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "1968-07-04T23:45:00")); DateTimeExtractor dateTimeExtractor = AiServices.create(DateTimeExtractor.class, createChatModel()); LocalDateTime result = dateTimeExtractor.extractDateTimeFrom( "The tranquility pervaded the evening of 1968, just fifteen minutes shy of midnight, following the celebrations of Independence Day."); assertThat(result).isEqualTo(LocalDateTime.of(1968, JULY, 4, 23, 45, 0)); assertSingleRequestMessage(getRequestAsMap(), "Extract date and time from The tranquility pervaded the evening of 1968, just fifteen minutes shy of midnight, following the celebrations of Independence Day.\nYou must answer strictly in the following format: 2023-12-31T23:59:59"); } enum Sentiment { POSITIVE, NEUTRAL, NEGATIVE } interface SentimentAnalyzer { @UserMessage("Analyze sentiment of {{it}}") Sentiment analyzeSentimentOf(String text); } @Test void test_extract_enum() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "POSITIVE")); SentimentAnalyzer sentimentAnalyzer = AiServices.create(SentimentAnalyzer.class, createChatModel()); Sentiment sentiment = sentimentAnalyzer.analyzeSentimentOf( "This LaptopPro X15 is wicked fast and that 4K screen is a dream."); assertThat(sentiment).isEqualTo(Sentiment.POSITIVE); assertSingleRequestMessage(getRequestAsMap(), "Analyze sentiment of This LaptopPro X15 is wicked fast and that 4K screen is a dream.\nYou must answer strictly in the following format: one of [POSITIVE, NEUTRAL, NEGATIVE]"); } record Person(String firstName, String lastName, LocalDate birthDate) { @JsonCreator public Person { } } interface PersonExtractor { @UserMessage("Extract information about a person from {{it}}") Person extractPersonFrom(String text); } @Test void test_extract_custom_POJO() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), // this is supposed to be a string inside a json string hence all the escaping... "{\\n\\\"firstName\\\": \\\"John\\\",\\n\\\"lastName\\\": \\\"Doe\\\",\\n\\\"birthDate\\\": \\\"1968-07-04\\\"\\n}")); PersonExtractor personExtractor = AiServices.create(PersonExtractor.class, createChatModel()); String text = "In 1968, amidst the fading echoes of Independence Day, " + "a child named John arrived under the calm evening sky. " + "This newborn, bearing the surname Doe, marked the start of a new journey."; Person result = personExtractor.extractPersonFrom(text); assertThat(result.firstName).isEqualTo("John"); assertThat(result.lastName).isEqualTo("Doe"); assertThat(result.birthDate).isEqualTo(LocalDate.of(1968, JULY, 4)); assertSingleRequestMessage(getRequestAsMap(), "Extract information about a person from In 1968, amidst the fading echoes of Independence Day, a child named John arrived under the calm evening sky. This newborn, bearing the surname Doe, marked the start of a new journey.\nYou must answer strictly in the following JSON format: {\n\"firstName\": (type: string),\n\"lastName\": (type: string),\n\"birthDate\": (type: date string (2023-12-31)),\n}"); } static class Recipe { private String title; private String description; @Description("each step should be described in 4 words, steps should rhyme") private String[] steps; private Integer preparationTimeMinutes; } @StructuredPrompt("Create a recipe of a {{dish}} that can be prepared using only {{ingredients}}") static class CreateRecipePrompt { private final String dish; private final List<String> ingredients; public CreateRecipePrompt(String dish, List<String> ingredients) { this.dish = dish; this.ingredients = ingredients; } public String getDish() { return dish; } public List<String> getIngredients() { return ingredients; } } interface Chef { @UserMessage("Create recipe using only {{it}}") Recipe createRecipeFrom(String... ingredients); Recipe createRecipeFrom(CreateRecipePrompt prompt); @SystemMessage("You are a very {{character}} chef") Recipe createRecipeFrom(@UserMessage CreateRecipePrompt prompt, String character); } @Test void test_create_recipe_from_list_of_ingredients() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), // this is supposed to be a string inside a json string hence all the escaping... "{\\n\\\"title\\\": \\\"Greek Salad\\\",\\n\\\"description\\\": \\\"A refreshing and tangy salad with Mediterranean flavors.\\\",\\n\\\"steps\\\": [\\n\\\"Chop, dice, and slice.\\\",\\n\\\"Mix veggies with feta.\\\",\\n\\\"Drizzle with olive oil.\\\",\\n\\\"Toss gently, then serve.\\\"\\n],\\n\\\"preparationTimeMinutes\\\": 15\\n}")); Chef chef = AiServices.create(Chef.class, createChatModel()); Recipe result = chef.createRecipeFrom("cucumber", "tomato", "feta", "onion", "olives"); assertThat(result.title).isNotBlank(); assertThat(result.description).isNotBlank(); assertThat(result.steps).isNotEmpty(); assertThat(result.preparationTimeMinutes).isPositive(); assertSingleRequestMessage(getRequestAsMap(), "Create recipe using only [cucumber, tomato, feta, onion, olives]\nYou must answer strictly in the following JSON format: {\n\"title\": (type: string),\n\"description\": (type: string),\n\"steps\": (each step should be described in 4 words, steps should rhyme; type: array of string),\n\"preparationTimeMinutes\": (type: integer),\n}"); } @Test void test_create_recipe_using_structured_prompt() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), // this is supposed to be a string inside a json string hence all the escaping... "{\\n\\\"title\\\": \\\"Greek Salad\\\",\\n\\\"description\\\": \\\"A refreshing and tangy salad with Mediterranean flavors.\\\",\\n\\\"steps\\\": [\\n\\\"Chop, dice, and slice.\\\",\\n\\\"Mix veggies with feta.\\\",\\n\\\"Drizzle with olive oil.\\\",\\n\\\"Toss gently, then serve.\\\"\\n],\\n\\\"preparationTimeMinutes\\\": 15\\n}")); Chef chef = AiServices.create(Chef.class, createChatModel()); Recipe result = chef .createRecipeFrom(new CreateRecipePrompt("salad", List.of("cucumber", "tomato", "feta", "onion", "olives"))); assertThat(result.title).isNotBlank(); assertThat(result.description).isNotBlank(); assertThat(result.steps).isNotEmpty(); assertThat(result.preparationTimeMinutes).isPositive(); assertSingleRequestMessage(getRequestAsMap(), "Create a recipe of a salad that can be prepared using only [cucumber, tomato, feta, onion, olives]\nYou must answer strictly in the following JSON format: {\n\"title\": (type: string),\n\"description\": (type: string),\n\"steps\": (each step should be described in 4 words, steps should rhyme; type: array of string),\n\"preparationTimeMinutes\": (type: integer),\n}"); } @Test void test_create_recipe_using_structured_prompt_and_system_message() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), // this is supposed to be a string inside a json string hence all the escaping... "{\\n\\\"title\\\": \\\"Greek Medley Salad\\\",\\n\\\"description\\\": \\\"A refreshing and tangy salad with a Mediterranean twist.\\\",\\n\\\"steps\\\": [\\n\\\"Slice and dice, precise!\\\",\\n\\\"Mix and toss, no loss!\\\",\\n\\\"Sprinkle feta, get betta!\\\",\\n\\\"Garnish with olives, no jives!\\\"\\n],\\n\\\"preparationTimeMinutes\\\": 15\\n}")); Chef chef = AiServices.create(Chef.class, createChatModel()); Recipe result = chef .createRecipeFrom(new CreateRecipePrompt("salad", List.of("cucumber", "tomato", "feta", "onion", "olives")), "funny"); assertThat(result.title).isEqualTo("Greek Medley Salad"); assertThat(result.description).isNotBlank(); assertThat(result.steps).hasSize(4).satisfies(strings -> { assertThat(strings[0]).contains("Slice and dice"); assertThat(strings[3]).contains("jives"); }); assertThat(result.preparationTimeMinutes).isEqualTo(15); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "You are a very funny chef"), new MessageContent("user", "Create a recipe of a salad that can be prepared using only [cucumber, tomato, feta, onion, olives]\nYou must answer strictly in the following JSON format: {\n\"title\": (type: string),\n\"description\": (type: string),\n\"steps\": (each step should be described in 4 words, steps should rhyme; type: array of string),\n\"preparationTimeMinutes\": (type: integer),\n}"))); } interface ProfessionalChef { @SystemMessage("You are a professional chef. You are friendly, polite and concise.") String answer(String question); } @Test void test_with_system_message() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "Grilling chicken typically takes around 10-15 minutes per side, depending on the thickness of the chicken. It's important to ensure the internal temperature reaches 165°F (74°C) for safe consumption.")); ProfessionalChef chef = AiServices.create(ProfessionalChef.class, createChatModel()); String result = chef.answer("How long should I grill chicken?"); assertThat(result).contains("Grilling chicken typically"); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "You are a professional chef. You are friendly, polite and concise."), new MessageContent("user", "How long should I grill chicken?"))); } interface Translator { @SystemMessage("You are a professional translator into {{lang}}") @UserMessage("Translate the following text: {{text}}") String translate(@V("text") String text, @V("lang") String language); } @Test void test_with_system_and_user_messages() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "Hallo, wie geht es dir?")); Translator translator = AiServices.create(Translator.class, createChatModel()); String translation = translator.translate("Hello, how are you?", "german"); assertThat(translation).isEqualTo("Hallo, wie geht es dir?"); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "You are a professional translator into german"), new MessageContent("user", "Translate the following text: Hello, how are you?"))); } interface Summarizer { @SystemMessage("Summarize every message from user in {{n}} bullet points. Provide only bullet points.") List<String> summarize(@UserMessage String text, int n); } @Test void test_with_system_message_and_user_message_as_argument() throws IOException { wireMockServer.stubFor(WiremockUtils.chatCompletionsMessageContent(Optional.empty(), "- AI is a branch of computer science\\n- AI aims to create machines that mimic human intelligence\\n- AI can perform tasks like recognizing patterns, making decisions, and predictions")); Summarizer summarizer = AiServices.create(Summarizer.class, createChatModel()); String text = "AI, or artificial intelligence, is a branch of computer science that aims to create " + "machines that mimic human intelligence. This can range from simple tasks such as recognizing " + "patterns or speech to more complex tasks like making decisions or predictions."; List<String> bulletPoints = summarizer.summarize(text, 3); assertThat(bulletPoints).hasSize(3).satisfies(list -> { assertThat(list.get(0)).contains("branch"); assertThat(list.get(2)).contains("predictions"); }); assertMultipleRequestMessage(getRequestAsMap(), List.of( new MessageContent("system", "Summarize every message from user in 3 bullet points. Provide only bullet points."), new MessageContent("user", text + "\nYou must put every item on a separate line."))); } interface ChatWithModeration { @Moderate String chat(String message); } @Test void should_throw_when_text_is_flagged() {
wireMockServer.stubFor(WiremockUtils.moderationMapping(DEFAULT_TOKEN)
0
2023-11-13 09:10:27+00:00
8k
qiusunshine/xiu
VideoPlayModule-Lite/src/main/java/chuangyuan/ycj/videolibrary/factory/HttpDefaultDataSourceFactory.java
[ { "identifier": "DefaultDataSource", "path": "VideoPlayModule-Lite/src/main/java/chuangyuan/ycj/videolibrary/upstream/DefaultDataSource.java", "snippet": "public final class DefaultDataSource implements DataSource {\n\n private static final String TAG = \"DefaultDataSource\";\n\n private static final ...
import android.content.Context; import android.net.Uri; import com.google.android.exoplayer2.upstream.DataSource; import com.google.android.exoplayer2.util.Util; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import chuangyuan.ycj.videolibrary.upstream.DefaultDataSource; import chuangyuan.ycj.videolibrary.upstream.DefaultDataSourceFactory; import chuangyuan.ycj.videolibrary.upstream.HttpsUtils; import okhttp3.OkHttpClient; import okhttp3.brotli.BrotliInterceptor; import static chuangyuan.ycj.videolibrary.upstream.DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS;
5,111
package chuangyuan.ycj.videolibrary.factory; /** * 作者:By 15968 * 日期:On 2020/6/1 * 时间:At 23:08 */ public class HttpDefaultDataSourceFactory implements DataSource.Factory { private final Context context; private final DataSource.Factory baseDataSourceFactory; public static String DEFAULT_UA = "Mozilla/5.0 (Linux; Android 11; Mi 10 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.152 Mobile Safari/537.36"; /** * Instantiates a new J default data source factory. * * @param context A context. for {@link DefaultDataSource}. */ public HttpDefaultDataSourceFactory(Context context) { String userAgent = Util.getUserAgent(context, context.getPackageName()); Map<String, String> headers = new HashMap<>(); headers.put("User-Agent", userAgent); this.context = context.getApplicationContext(); this.baseDataSourceFactory = init(context, headers, null); } public HttpDefaultDataSourceFactory(Context context, Map<String, String> headers, Uri uri) { this.context = context.getApplicationContext(); this.baseDataSourceFactory = init(context, headers, uri); } private DataSource.Factory init(Context context, Map<String, String> headers, Uri uri) { // String userAgent = Util.getUserAgent(context, context.getPackageName()); String userAgent = DEFAULT_UA; if (headers != null) { if (headers.containsKey("User-Agent")) { userAgent = headers.get("User-Agent"); } else if (headers.containsKey("user-agent")) { userAgent = headers.get("user-agent"); } else if (headers.containsKey("user-Agent")) { userAgent = headers.get("user-Agent"); } headers = new HashMap<>(headers); headers.remove("User-Agent"); } if (headers == null) { headers = new HashMap<>(); } //方法一:信任所有证书,不安全有风险 HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory(); OkHttpClient okHttpClient = null; if (uri != null) { String url = uri.toString(); if (url.contains("://127.0.0.1") || url.contains("://192.168.") || url.contains("://0.0.0.") || url.contains("://10.")) { okHttpClient = new OkHttpClient.Builder() .addInterceptor(BrotliInterceptor.INSTANCE) .sslSocketFactory(sslParams1.sSLSocketFactory, HttpsUtils.UnSafeTrustManager) .hostnameVerifier(HttpsUtils.UnSafeHostnameVerifier)
package chuangyuan.ycj.videolibrary.factory; /** * 作者:By 15968 * 日期:On 2020/6/1 * 时间:At 23:08 */ public class HttpDefaultDataSourceFactory implements DataSource.Factory { private final Context context; private final DataSource.Factory baseDataSourceFactory; public static String DEFAULT_UA = "Mozilla/5.0 (Linux; Android 11; Mi 10 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.152 Mobile Safari/537.36"; /** * Instantiates a new J default data source factory. * * @param context A context. for {@link DefaultDataSource}. */ public HttpDefaultDataSourceFactory(Context context) { String userAgent = Util.getUserAgent(context, context.getPackageName()); Map<String, String> headers = new HashMap<>(); headers.put("User-Agent", userAgent); this.context = context.getApplicationContext(); this.baseDataSourceFactory = init(context, headers, null); } public HttpDefaultDataSourceFactory(Context context, Map<String, String> headers, Uri uri) { this.context = context.getApplicationContext(); this.baseDataSourceFactory = init(context, headers, uri); } private DataSource.Factory init(Context context, Map<String, String> headers, Uri uri) { // String userAgent = Util.getUserAgent(context, context.getPackageName()); String userAgent = DEFAULT_UA; if (headers != null) { if (headers.containsKey("User-Agent")) { userAgent = headers.get("User-Agent"); } else if (headers.containsKey("user-agent")) { userAgent = headers.get("user-agent"); } else if (headers.containsKey("user-Agent")) { userAgent = headers.get("user-Agent"); } headers = new HashMap<>(headers); headers.remove("User-Agent"); } if (headers == null) { headers = new HashMap<>(); } //方法一:信任所有证书,不安全有风险 HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory(); OkHttpClient okHttpClient = null; if (uri != null) { String url = uri.toString(); if (url.contains("://127.0.0.1") || url.contains("://192.168.") || url.contains("://0.0.0.") || url.contains("://10.")) { okHttpClient = new OkHttpClient.Builder() .addInterceptor(BrotliInterceptor.INSTANCE) .sslSocketFactory(sslParams1.sSLSocketFactory, HttpsUtils.UnSafeTrustManager) .hostnameVerifier(HttpsUtils.UnSafeHostnameVerifier)
.readTimeout(DEFAULT_READ_TIMEOUT_MILLIS * 2, TimeUnit.MILLISECONDS)
3
2023-11-10 14:28:40+00:00
8k
noear/folkmq
folkmq-test/src/test/java/features/cases/TestCase18_batch_subscribe.java
[ { "identifier": "MqClientDefault", "path": "folkmq/src/main/java/org/noear/folkmq/client/MqClientDefault.java", "snippet": "public class MqClientDefault implements MqClientInternal {\n private static final Logger log = LoggerFactory.getLogger(MqClientDefault.class);\n\n //服务端地址\n private final ...
import org.noear.folkmq.client.MqClientDefault; import org.noear.folkmq.client.MqMessage; import org.noear.folkmq.server.MqQueue; import org.noear.folkmq.server.MqServerDefault; import org.noear.folkmq.server.MqServiceInternal; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit;
4,145
package features.cases; /** * @author noear * @since 1.0 */ public class TestCase18_batch_subscribe extends BaseTestCase { public TestCase18_batch_subscribe(int port) { super(port); } @Override public void start() throws Exception { super.start(); //服务端 server = new MqServerDefault() .start(getPort()); //客户端 CountDownLatch countDownLatch = new CountDownLatch(1);
package features.cases; /** * @author noear * @since 1.0 */ public class TestCase18_batch_subscribe extends BaseTestCase { public TestCase18_batch_subscribe(int port) { super(port); } @Override public void start() throws Exception { super.start(); //服务端 server = new MqServerDefault() .start(getPort()); //客户端 CountDownLatch countDownLatch = new CountDownLatch(1);
client = new MqClientDefault("folkmq://127.0.0.1:" + getPort());
0
2023-11-18 19:09:28+00:00
8k
leluque/java2uml
src/main/java/br/com/luque/java2uml/plantuml/writer/classdiagram/PlantUMLWriter.java
[ { "identifier": "Rules", "path": "src/main/java/br/com/luque/java2uml/Rules.java", "snippet": "public class Rules {\n private final Set<String> packages;\n private final Set<String> classes;\n private final Set<String> ignorePackages;\n private final Set<String> ignoreClasses;\n\n public ...
import br.com.luque.java2uml.Rules; import br.com.luque.java2uml.core.classdiagram.classsearch.ClasspathSearcher; import br.com.luque.java2uml.core.classdiagram.reflection.model.Clazz; import br.com.luque.java2uml.core.classdiagram.reflection.model.ClazzPool; import br.com.luque.java2uml.core.classdiagram.reflection.model.RelationshipField; import br.com.luque.java2uml.core.classdiagram.reflection.model.ScopedClazz; import java.util.Objects;
4,177
package br.com.luque.java2uml.plantuml.writer.classdiagram; public class PlantUMLWriter { public static String generateClassDiagramUsing(PlantUMLClassWriter classWriter, PlantUMLRelationshipWriter relationshipWriter, Rules rules) { Objects.requireNonNull(classWriter); Objects.requireNonNull(relationshipWriter); Objects.requireNonNull(rules); ClasspathSearcher searcher = new ClasspathSearcher(rules); Class<?>[] classes = searcher.search();
package br.com.luque.java2uml.plantuml.writer.classdiagram; public class PlantUMLWriter { public static String generateClassDiagramUsing(PlantUMLClassWriter classWriter, PlantUMLRelationshipWriter relationshipWriter, Rules rules) { Objects.requireNonNull(classWriter); Objects.requireNonNull(relationshipWriter); Objects.requireNonNull(rules); ClasspathSearcher searcher = new ClasspathSearcher(rules); Class<?>[] classes = searcher.search();
ClazzPool clazzPool = new ClazzPool(rules);
3
2023-11-10 16:49:58+00:00
8k
javpower/JavaVision
src/main/java/com/github/javpower/javavision/detect/Yolov8sOnnxRuntimeDetect.java
[ { "identifier": "AbstractOnnxRuntimeTranslator", "path": "src/main/java/com/github/javpower/javavision/detect/translator/AbstractOnnxRuntimeTranslator.java", "snippet": "public abstract class AbstractOnnxRuntimeTranslator {\n\n public OrtEnvironment environment;\n public OrtSession session;\n p...
import ai.onnxruntime.OnnxTensor; import ai.onnxruntime.OrtException; import ai.onnxruntime.OrtSession; import com.github.javpower.javavision.detect.translator.AbstractOnnxRuntimeTranslator; import com.github.javpower.javavision.entity.Letterbox; import com.github.javpower.javavision.util.JarFileUtils; import com.github.javpower.javavision.util.PathConstants; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import java.io.IOException; import java.nio.FloatBuffer; import java.util.*;
4,805
package com.github.javpower.javavision.detect; public class Yolov8sOnnxRuntimeDetect extends AbstractOnnxRuntimeTranslator { public Yolov8sOnnxRuntimeDetect(String modelPath, float confThreshold, float nmsThreshold, String[] labels) throws OrtException { super(modelPath, labels,confThreshold,nmsThreshold); } // 实现加载图像的逻辑 @Override protected Mat loadImage(String imagePath) { return Imgcodecs.imread(imagePath); } // 实现图像预处理的逻辑 @Override protected void preprocessImage(Mat image) { Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2RGB); // 更改 image 尺寸及其他预处理逻辑 } // 实现推理的逻辑 @Override protected float[][] runInference(Mat image) throws OrtException { Letterbox letterbox = new Letterbox(); int rows = letterbox.getHeight(); int cols = letterbox.getWidth(); int channels = image.channels(); float[] pixels = new float[channels * rows * cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { double[] pixel = image.get(j, i); for (int k = 0; k < channels; k++) { pixels[rows * cols * k + j * cols + i] = (float) pixel[k] / 255.0f; } } } // 创建OnnxTensor对象 long[] shape = { 1L, (long)channels, (long)rows, (long)cols }; OnnxTensor tensor = OnnxTensor.createTensor(environment, FloatBuffer.wrap(pixels), shape); Map<String, OnnxTensor> inputs = new HashMap<>(); inputs.put(session.getInputNames().iterator().next(), tensor); OrtSession.Result output = session.run(inputs); float[][] outputData = ((float[][][]) output.get(0).getValue())[0]; return transposeMatrix(outputData); } // 实现输出后处理的逻辑 @Override protected Map<Integer, List<float[]>> postprocessOutput(float[][] outputData) { Map<Integer, List<float[]>> class2Bbox = new HashMap<>(); for (float[] bbox : outputData) { float[] conditionalProbabilities = Arrays.copyOfRange(bbox, 4, bbox.length); int label = argmax(conditionalProbabilities); float conf = conditionalProbabilities[label]; if (conf < confThreshold) continue; bbox[4] = conf; xywh2xyxy(bbox); if (bbox[0] >= bbox[2] || bbox[1] >= bbox[3]) continue; class2Bbox.putIfAbsent(label, new ArrayList<>()); class2Bbox.get(label).add(bbox); } return class2Bbox; } private static void xywh2xyxy(float[] bbox) { float x = bbox[0]; float y = bbox[1]; float w = bbox[2]; float h = bbox[3]; bbox[0] = x - w * 0.5f; bbox[1] = y - h * 0.5f; bbox[2] = x + w * 0.5f; bbox[3] = y + h * 0.5f; } private static int argmax(float[] a) { float re = -Float.MAX_VALUE; int arg = -1; for (int i = 0; i < a.length; i++) { if (a[i] >= re) { re = a[i]; arg = i; } } return arg; } public static Yolov8sOnnxRuntimeDetect criteria() throws OrtException, IOException { // 这里需要引入JAR包的拷贝逻辑,您可以根据自己的需要将其处理为合适的方式
package com.github.javpower.javavision.detect; public class Yolov8sOnnxRuntimeDetect extends AbstractOnnxRuntimeTranslator { public Yolov8sOnnxRuntimeDetect(String modelPath, float confThreshold, float nmsThreshold, String[] labels) throws OrtException { super(modelPath, labels,confThreshold,nmsThreshold); } // 实现加载图像的逻辑 @Override protected Mat loadImage(String imagePath) { return Imgcodecs.imread(imagePath); } // 实现图像预处理的逻辑 @Override protected void preprocessImage(Mat image) { Imgproc.cvtColor(image, image, Imgproc.COLOR_BGR2RGB); // 更改 image 尺寸及其他预处理逻辑 } // 实现推理的逻辑 @Override protected float[][] runInference(Mat image) throws OrtException { Letterbox letterbox = new Letterbox(); int rows = letterbox.getHeight(); int cols = letterbox.getWidth(); int channels = image.channels(); float[] pixels = new float[channels * rows * cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { double[] pixel = image.get(j, i); for (int k = 0; k < channels; k++) { pixels[rows * cols * k + j * cols + i] = (float) pixel[k] / 255.0f; } } } // 创建OnnxTensor对象 long[] shape = { 1L, (long)channels, (long)rows, (long)cols }; OnnxTensor tensor = OnnxTensor.createTensor(environment, FloatBuffer.wrap(pixels), shape); Map<String, OnnxTensor> inputs = new HashMap<>(); inputs.put(session.getInputNames().iterator().next(), tensor); OrtSession.Result output = session.run(inputs); float[][] outputData = ((float[][][]) output.get(0).getValue())[0]; return transposeMatrix(outputData); } // 实现输出后处理的逻辑 @Override protected Map<Integer, List<float[]>> postprocessOutput(float[][] outputData) { Map<Integer, List<float[]>> class2Bbox = new HashMap<>(); for (float[] bbox : outputData) { float[] conditionalProbabilities = Arrays.copyOfRange(bbox, 4, bbox.length); int label = argmax(conditionalProbabilities); float conf = conditionalProbabilities[label]; if (conf < confThreshold) continue; bbox[4] = conf; xywh2xyxy(bbox); if (bbox[0] >= bbox[2] || bbox[1] >= bbox[3]) continue; class2Bbox.putIfAbsent(label, new ArrayList<>()); class2Bbox.get(label).add(bbox); } return class2Bbox; } private static void xywh2xyxy(float[] bbox) { float x = bbox[0]; float y = bbox[1]; float w = bbox[2]; float h = bbox[3]; bbox[0] = x - w * 0.5f; bbox[1] = y - h * 0.5f; bbox[2] = x + w * 0.5f; bbox[3] = y + h * 0.5f; } private static int argmax(float[] a) { float re = -Float.MAX_VALUE; int arg = -1; for (int i = 0; i < a.length; i++) { if (a[i] >= re) { re = a[i]; arg = i; } } return arg; } public static Yolov8sOnnxRuntimeDetect criteria() throws OrtException, IOException { // 这里需要引入JAR包的拷贝逻辑,您可以根据自己的需要将其处理为合适的方式
JarFileUtils.copyFileFromJar("/onnx/models/yolov8s.onnx", PathConstants.ONNX,null,false,true);
2
2023-11-10 01:57:37+00:00
8k
feiniaojin/graceful-response-boot2
src/main/java/com/feiniaojin/gracefulresponse/AutoConfig.java
[ { "identifier": "GlobalExceptionAdvice", "path": "src/main/java/com/feiniaojin/gracefulresponse/advice/GlobalExceptionAdvice.java", "snippet": "@ControllerAdvice\n@Order(200)\npublic class GlobalExceptionAdvice implements ApplicationContextAware {\n\n private final Logger logger = LoggerFactory.getLo...
import com.feiniaojin.gracefulresponse.advice.GlobalExceptionAdvice; import com.feiniaojin.gracefulresponse.advice.NotVoidResponseBodyAdvice; import com.feiniaojin.gracefulresponse.advice.ValidationExceptionAdvice; import com.feiniaojin.gracefulresponse.advice.VoidResponseBodyAdvice; import com.feiniaojin.gracefulresponse.api.ResponseFactory; import com.feiniaojin.gracefulresponse.api.ResponseStatusFactory; import com.feiniaojin.gracefulresponse.defaults.DefaultResponseFactory; import com.feiniaojin.gracefulresponse.defaults.DefaultResponseStatusFactoryImpl; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
4,605
package com.feiniaojin.gracefulresponse; /** * 全局返回值处理的自动配置. * * @author <a href="mailto:943868899@qq.com">Yujie</a> * @version 0.1 * @since 0.1 */ @Configuration @EnableConfigurationProperties(GracefulResponseProperties.class) public class AutoConfig { @Bean
package com.feiniaojin.gracefulresponse; /** * 全局返回值处理的自动配置. * * @author <a href="mailto:943868899@qq.com">Yujie</a> * @version 0.1 * @since 0.1 */ @Configuration @EnableConfigurationProperties(GracefulResponseProperties.class) public class AutoConfig { @Bean
@ConditionalOnMissingBean(value = GlobalExceptionAdvice.class)
0
2023-11-15 10:54:19+00:00
8k
innogames/flink-real-time-crm
src/main/java/com/innogames/analytics/rtcrm/App.java
[ { "identifier": "Config", "path": "src/main/java/com/innogames/analytics/rtcrm/config/Config.java", "snippet": "@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)\npublic class Config {\n\n\tprivate int defaultParallelism;\n\tprivate int checkpointInterval;\n\tprivate String checkpointDir;\n\...
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.innogames.analytics.rtcrm.config.Config; import com.innogames.analytics.rtcrm.entity.Campaign; import com.innogames.analytics.rtcrm.entity.TrackingEvent; import com.innogames.analytics.rtcrm.function.EvaluateFilter; import com.innogames.analytics.rtcrm.map.StringToCampaign; import com.innogames.analytics.rtcrm.map.StringToTrackingEvent; import com.innogames.analytics.rtcrm.sink.TriggerCampaignSink; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.apache.flink.api.common.eventtime.WatermarkStrategy; import org.apache.flink.api.common.restartstrategy.RestartStrategies; import org.apache.flink.api.common.serialization.SimpleStringSchema; import org.apache.flink.api.common.state.MapStateDescriptor; import org.apache.flink.api.common.time.Time; import org.apache.flink.api.common.typeinfo.BasicTypeInfo; import org.apache.flink.api.common.typeinfo.TypeHint; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.configuration.Configuration; import org.apache.flink.connector.kafka.source.KafkaSource; import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer; import org.apache.flink.streaming.api.datastream.BroadcastStream; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.CheckpointConfig; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
3,952
package com.innogames.analytics.rtcrm; public class App { // pass config path via parameter or use config from resources as default private static final String configParameter = "config"; private static final String configResource = "config.json"; // state key: campaign ID // state value: campaign definition public static final MapStateDescriptor<Integer, Campaign> CAMPAIGN_STATE_DESCRIPTOR = new MapStateDescriptor<>( "CampaignState", BasicTypeInfo.INT_TYPE_INFO, TypeInformation.of(new TypeHint<>() {}) ); public static void main(String[] args) throws Exception { // 1 - parse config final ParameterTool parameterTool = ParameterTool.fromArgs(args); final Config config = readConfigFromFileOrResource(new ObjectMapper(), new TypeReference<>() {}, parameterTool); // 2 - create local env with web UI enabled, use StreamExecutionEnvironment.getExecutionEnvironment() for deployment final StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration()); // 3 - make config variables available to functions env.getConfig().setGlobalJobParameters(ParameterTool.fromMap(Map.of( "kafka_bootstrap_servers", config.getKafkaBootstrapServers(), "trigger_topic", config.getTriggerTopic() ))); // 4 - configure env env.setParallelism(config.getDefaultParallelism()); env.setRestartStrategy(RestartStrategies.fixedDelayRestart( 6, // number of restart attempts Time.of(10, TimeUnit.SECONDS) // delay )); // Checkpoints are a mechanism to recover from failures only(!) env.enableCheckpointing(config.getCheckpointInterval()); // If a checkpoint directory is configured FileSystemCheckpointStorage will be used, // otherwise the system will use the JobManagerCheckpointStorage env.getCheckpointConfig().setCheckpointStorage(config.getCheckpointDir()); // Checkpoint state is kept when the owning job is cancelled or fails env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION); // 5 - create and prepare streams final String kafkaBootstrapServers = config.getKafkaBootstrapServers(); final String kafkaGroupId = config.getKafkaGroupId(); final String eventTopic = config.getEventTopic(); final String campaignTopic = config.getCampaignTopic(); // 5.1 - broadcast stream for campaigns, without group ID to always consume all data from topic final KafkaSource<String> campaignSource = buildKafkaSource(kafkaBootstrapServers, campaignTopic, OffsetsInitializer.earliest()); final BroadcastStream<Campaign> campaignStream = env.fromSource(campaignSource, WatermarkStrategy.noWatermarks(), campaignTopic) .setParallelism(1).name("campaign-stream")
package com.innogames.analytics.rtcrm; public class App { // pass config path via parameter or use config from resources as default private static final String configParameter = "config"; private static final String configResource = "config.json"; // state key: campaign ID // state value: campaign definition public static final MapStateDescriptor<Integer, Campaign> CAMPAIGN_STATE_DESCRIPTOR = new MapStateDescriptor<>( "CampaignState", BasicTypeInfo.INT_TYPE_INFO, TypeInformation.of(new TypeHint<>() {}) ); public static void main(String[] args) throws Exception { // 1 - parse config final ParameterTool parameterTool = ParameterTool.fromArgs(args); final Config config = readConfigFromFileOrResource(new ObjectMapper(), new TypeReference<>() {}, parameterTool); // 2 - create local env with web UI enabled, use StreamExecutionEnvironment.getExecutionEnvironment() for deployment final StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration()); // 3 - make config variables available to functions env.getConfig().setGlobalJobParameters(ParameterTool.fromMap(Map.of( "kafka_bootstrap_servers", config.getKafkaBootstrapServers(), "trigger_topic", config.getTriggerTopic() ))); // 4 - configure env env.setParallelism(config.getDefaultParallelism()); env.setRestartStrategy(RestartStrategies.fixedDelayRestart( 6, // number of restart attempts Time.of(10, TimeUnit.SECONDS) // delay )); // Checkpoints are a mechanism to recover from failures only(!) env.enableCheckpointing(config.getCheckpointInterval()); // If a checkpoint directory is configured FileSystemCheckpointStorage will be used, // otherwise the system will use the JobManagerCheckpointStorage env.getCheckpointConfig().setCheckpointStorage(config.getCheckpointDir()); // Checkpoint state is kept when the owning job is cancelled or fails env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION); // 5 - create and prepare streams final String kafkaBootstrapServers = config.getKafkaBootstrapServers(); final String kafkaGroupId = config.getKafkaGroupId(); final String eventTopic = config.getEventTopic(); final String campaignTopic = config.getCampaignTopic(); // 5.1 - broadcast stream for campaigns, without group ID to always consume all data from topic final KafkaSource<String> campaignSource = buildKafkaSource(kafkaBootstrapServers, campaignTopic, OffsetsInitializer.earliest()); final BroadcastStream<Campaign> campaignStream = env.fromSource(campaignSource, WatermarkStrategy.noWatermarks(), campaignTopic) .setParallelism(1).name("campaign-stream")
.map(new StringToCampaign()).setParallelism(1).name("parse-campaign")
4
2023-11-12 17:52:45+00:00
8k
BlyznytsiaOrg/bring
core/src/main/java/io/github/blyznytsiaorg/bring/core/context/type/parameter/ParameterListValueTypeInjector.java
[ { "identifier": "AnnotationBringBeanRegistry", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/context/impl/AnnotationBringBeanRegistry.java", "snippet": "@Slf4j\npublic class AnnotationBringBeanRegistry extends DefaultBringBeanFactory implements BeanRegistry, BeanDefinitionRegistry {\n\n...
import io.github.blyznytsiaorg.bring.core.context.impl.AnnotationBringBeanRegistry; import io.github.blyznytsiaorg.bring.core.context.scaner.ClassPathScannerFactory; import io.github.blyznytsiaorg.bring.core.context.type.AbstractValueTypeInjector; import io.github.blyznytsiaorg.bring.core.utils.ReflectionUtils; import org.reflections.Reflections; import java.lang.annotation.Annotation; import java.lang.reflect.Parameter; import java.lang.reflect.ParameterizedType; import java.util.List; import static io.github.blyznytsiaorg.bring.core.utils.ReflectionUtils.extractImplClasses;
6,130
package io.github.blyznytsiaorg.bring.core.context.type.parameter; /** * The {@code ParameterListValueTypeInjector} class is responsible for handling parameter injections for types of List. * It extends the functionality of the AbstractValueTypeInjector and works in conjunction with a framework, * utilizing the bean registry and classpath scanner to recognize parameters of type List. The injector extracts * implementation classes based on the generic type of the List and injects the corresponding dependencies. * * @author Blyzhnytsia Team * @since 1.0 */ public class ParameterListValueTypeInjector extends AbstractValueTypeInjector implements ParameterValueTypeInjector{ private final Reflections reflections; /** * Constructs a new instance of {@code ParameterListValueTypeInjector}. * * @param reflections The Reflections instance for scanning annotated classes. * @param beanRegistry The bean registry for managing created beans. * @param classPathScannerFactory The factory for creating classpath scanners. */ public ParameterListValueTypeInjector(Reflections reflections, AnnotationBringBeanRegistry beanRegistry, ClassPathScannerFactory classPathScannerFactory) { super(beanRegistry, classPathScannerFactory); this.reflections = reflections; } /** * Checks if the specified parameter is annotated with a value. * * @param parameter The parameter to check. * @return {@code true} if the parameter is of type List, {@code false} otherwise. */ @Override public boolean hasAnnotatedWithValue(Parameter parameter) { return List.class.isAssignableFrom(parameter.getType()); } /** * Sets the value to the specified parameter by injecting dependencies based on the generic type of the List. * * @param parameter The parameter to inject value into. * @param createdBeanAnnotations The annotations used for creating the bean. * @return The result of injecting dependencies into the List parameter. */ @Override public Object setValueToSetter(Parameter parameter, String parameterName, List<Class<? extends Annotation>> createdBeanAnnotations) { ParameterizedType genericTypeOfField = (ParameterizedType) parameter.getParameterizedType();
package io.github.blyznytsiaorg.bring.core.context.type.parameter; /** * The {@code ParameterListValueTypeInjector} class is responsible for handling parameter injections for types of List. * It extends the functionality of the AbstractValueTypeInjector and works in conjunction with a framework, * utilizing the bean registry and classpath scanner to recognize parameters of type List. The injector extracts * implementation classes based on the generic type of the List and injects the corresponding dependencies. * * @author Blyzhnytsia Team * @since 1.0 */ public class ParameterListValueTypeInjector extends AbstractValueTypeInjector implements ParameterValueTypeInjector{ private final Reflections reflections; /** * Constructs a new instance of {@code ParameterListValueTypeInjector}. * * @param reflections The Reflections instance for scanning annotated classes. * @param beanRegistry The bean registry for managing created beans. * @param classPathScannerFactory The factory for creating classpath scanners. */ public ParameterListValueTypeInjector(Reflections reflections, AnnotationBringBeanRegistry beanRegistry, ClassPathScannerFactory classPathScannerFactory) { super(beanRegistry, classPathScannerFactory); this.reflections = reflections; } /** * Checks if the specified parameter is annotated with a value. * * @param parameter The parameter to check. * @return {@code true} if the parameter is of type List, {@code false} otherwise. */ @Override public boolean hasAnnotatedWithValue(Parameter parameter) { return List.class.isAssignableFrom(parameter.getType()); } /** * Sets the value to the specified parameter by injecting dependencies based on the generic type of the List. * * @param parameter The parameter to inject value into. * @param createdBeanAnnotations The annotations used for creating the bean. * @return The result of injecting dependencies into the List parameter. */ @Override public Object setValueToSetter(Parameter parameter, String parameterName, List<Class<? extends Annotation>> createdBeanAnnotations) { ParameterizedType genericTypeOfField = (ParameterizedType) parameter.getParameterizedType();
List<Class<?>> dependencies = ReflectionUtils.extractImplClasses(genericTypeOfField, reflections, createdBeanAnnotations);
3
2023-11-10 13:42:05+00:00
8k
johndeweyzxc/AWPS-Command
app/src/main/java/com/johndeweydev/awps/view/terminalfragment/TerminalFragment.java
[ { "identifier": "BAUD_RATE", "path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java", "snippet": "public static final int BAUD_RATE = 19200;" }, { "identifier": "DATA_BITS", "path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java", "snippet": "public static final i...
import static com.johndeweydev.awps.AppConstants.BAUD_RATE; import static com.johndeweydev.awps.AppConstants.DATA_BITS; import static com.johndeweydev.awps.AppConstants.PARITY_NONE; import static com.johndeweydev.awps.AppConstants.STOP_BITS; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.Navigation; import androidx.recyclerview.widget.LinearLayoutManager; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.textfield.TextInputEditText; import com.johndeweydev.awps.R; import com.johndeweydev.awps.databinding.FragmentTerminalBinding; import com.johndeweydev.awps.model.data.DeviceConnectionParamData; import com.johndeweydev.awps.model.data.LauncherOutputData; import com.johndeweydev.awps.viewmodel.serial.terminalviewmodel.TerminalViewModel; import com.johndeweydev.awps.view.autoarmafragment.AutoArmaArgs; import com.johndeweydev.awps.view.manualarmafragment.ManualArmaArgs;
3,706
if (terminalArgs == null) { Log.d("dev-log", "TerminalFragment.onViewCreated: Terminal args is null"); Navigation.findNavController(binding.getRoot()).popBackStack(); return; } binding.materialToolBarTerminal.setNavigationOnClickListener(v -> binding.drawerLayoutTerminal.open()); TerminalRVAdapter terminalRVAdapter = setupRecyclerView(); binding.navigationViewTerminal.setNavigationItemSelectedListener(item -> navItemSelected(item, terminalRVAdapter)); binding.buttonCreateCommandTerminal.setOnClickListener(v -> showDialogAskUserToEnterInstructionCode()); setupObservers(terminalRVAdapter); } private TerminalRVAdapter setupRecyclerView() { TerminalRVAdapter terminalRVAdapter = new TerminalRVAdapter(); LinearLayoutManager layout = new LinearLayoutManager(requireContext()); layout.setStackFromEnd(true); binding.recyclerViewLogsTerminal.setAdapter(terminalRVAdapter); binding.recyclerViewLogsTerminal.setLayoutManager(layout); return terminalRVAdapter; } private void showDialogAskUserToEnterInstructionCode() { View dialogCommandInput = LayoutInflater.from(requireContext()).inflate( R.layout.dialog_command_input, null); TextInputEditText textInputEditTextDialogCommandInput = dialogCommandInput.findViewById( R.id.textInputEditTextDialogCommandInput); textInputEditTextDialogCommandInput.requestFocus(); MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireContext()); builder.setTitle("Command Instruction Input"); builder.setMessage("Enter command instruction code that will be sent to the launcher module"); builder.setView(dialogCommandInput); builder.setPositiveButton("SEND", (dialog, which) -> { if (textInputEditTextDialogCommandInput.getText() == null) { dialog.dismiss(); } String instructionCode = textInputEditTextDialogCommandInput.getText().toString(); terminalViewModel.writeDataToDevice(instructionCode); }); builder.setNegativeButton("CANCEL", (dialog, which) -> dialog.dismiss()); AlertDialog dialog = builder.create(); if (dialog.getWindow() != null) { dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); } dialog.show(); } private void setupObservers(TerminalRVAdapter terminalRVAdapter) { final Observer<LauncherOutputData> currentSerialOutputObserver = s -> { if (s == null) { return; } terminalRVAdapter.appendNewTerminalLog(s); binding.recyclerViewLogsTerminal.scrollToPosition(terminalRVAdapter.getItemCount() - 1); }; terminalViewModel.currentSerialOutputRaw.observe(getViewLifecycleOwner(), currentSerialOutputObserver); terminalViewModel.currentSerialOutput.observe(getViewLifecycleOwner(), currentSerialOutputObserver); setupSerialInputErrorListener(); setupSerialOutputErrorListener(); } private void setupSerialInputErrorListener() { final Observer<String> writeErrorListener = s -> { if (s == null) { return; } terminalViewModel.currentSerialInputError.setValue(null); Log.d("dev-log", "TerminalFragment.setupSerialInputErrorListener: " + "Error on user input"); stopEventReadAndDisconnectFromDevice(); Toast.makeText(requireActivity(), "Error writing " + s, Toast.LENGTH_SHORT).show(); Log.d("dev-log", "TerminalFragment.setupSerialInputErrorListener: " + "Popping this fragment off the back stack"); Navigation.findNavController(binding.getRoot()).popBackStack(); }; terminalViewModel.currentSerialInputError.observe(getViewLifecycleOwner(), writeErrorListener); } private void setupSerialOutputErrorListener() { final Observer<String> onNewDataErrorListener = s -> { if (s == null) { return; } terminalViewModel.currentSerialOutputError.setValue(null); Log.d("dev-log", "TerminalFragment.setupSerialOutputErrorListener: " + "Error on serial output"); stopEventReadAndDisconnectFromDevice(); Toast.makeText(requireActivity(), "Error: " + s, Toast.LENGTH_SHORT).show(); Log.d("dev-log", "TerminalFragment.setupSerialOutputErrorListener: " + "Popping this fragment off the back stack"); Navigation.findNavController(binding.getRoot()).popBackStack(); }; terminalViewModel.currentSerialOutputError.observe( getViewLifecycleOwner(), onNewDataErrorListener); } @Override public void onResume() { super.onResume(); Log.d("dev-log", "TerminalFragment.onResume: Fragment resumed"); Log.d("dev-log", "TerminalFragment.onResume: Connecting to device"); connectToDevice(); terminalViewModel.setLauncherEventHandler(); } private void connectToDevice() { int deviceId = terminalArgs.getDeviceId(); int portNum = terminalArgs.getPortNum(); DeviceConnectionParamData deviceConnectionParamData = new DeviceConnectionParamData(
package com.johndeweydev.awps.view.terminalfragment; public class TerminalFragment extends Fragment { private FragmentTerminalBinding binding; private String selectedArmament; private TerminalViewModel terminalViewModel; private TerminalArgs terminalArgs = null; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { terminalViewModel = new ViewModelProvider(requireActivity()).get(TerminalViewModel.class); binding = FragmentTerminalBinding.inflate(inflater, container, false); if (getArguments() == null) { Log.d("dev-log", "TerminalFragment.onCreateView: Get arguments is null"); } else { Log.d("dev-log", "TerminalFragment.onCreateView: Initializing fragment args"); TerminalFragmentArgs terminalFragmentArgs; if (getArguments().isEmpty()) { Log.w("dev-log", "TerminalFragment.onCreateView: Terminal argument is missing, " + "using data in the view model"); terminalArgs = new TerminalArgs( terminalViewModel.deviceIdFromTerminalArgs, terminalViewModel.portNumFromTerminalArgs, terminalViewModel.baudRateFromTerminalArgs); } else { Log.d("dev-log", "TerminalFragment.onCreateView: Getting terminal argument " + "from bundle"); terminalFragmentArgs = TerminalFragmentArgs.fromBundle(getArguments()); terminalArgs = terminalFragmentArgs.getTerminalArgs(); terminalViewModel.deviceIdFromTerminalArgs = terminalArgs.getDeviceId(); terminalViewModel.portNumFromTerminalArgs = terminalArgs.getPortNum(); terminalViewModel.baudRateFromTerminalArgs = terminalArgs.getBaudRate(); } } return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (terminalArgs == null) { Log.d("dev-log", "TerminalFragment.onViewCreated: Terminal args is null"); Navigation.findNavController(binding.getRoot()).popBackStack(); return; } binding.materialToolBarTerminal.setNavigationOnClickListener(v -> binding.drawerLayoutTerminal.open()); TerminalRVAdapter terminalRVAdapter = setupRecyclerView(); binding.navigationViewTerminal.setNavigationItemSelectedListener(item -> navItemSelected(item, terminalRVAdapter)); binding.buttonCreateCommandTerminal.setOnClickListener(v -> showDialogAskUserToEnterInstructionCode()); setupObservers(terminalRVAdapter); } private TerminalRVAdapter setupRecyclerView() { TerminalRVAdapter terminalRVAdapter = new TerminalRVAdapter(); LinearLayoutManager layout = new LinearLayoutManager(requireContext()); layout.setStackFromEnd(true); binding.recyclerViewLogsTerminal.setAdapter(terminalRVAdapter); binding.recyclerViewLogsTerminal.setLayoutManager(layout); return terminalRVAdapter; } private void showDialogAskUserToEnterInstructionCode() { View dialogCommandInput = LayoutInflater.from(requireContext()).inflate( R.layout.dialog_command_input, null); TextInputEditText textInputEditTextDialogCommandInput = dialogCommandInput.findViewById( R.id.textInputEditTextDialogCommandInput); textInputEditTextDialogCommandInput.requestFocus(); MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireContext()); builder.setTitle("Command Instruction Input"); builder.setMessage("Enter command instruction code that will be sent to the launcher module"); builder.setView(dialogCommandInput); builder.setPositiveButton("SEND", (dialog, which) -> { if (textInputEditTextDialogCommandInput.getText() == null) { dialog.dismiss(); } String instructionCode = textInputEditTextDialogCommandInput.getText().toString(); terminalViewModel.writeDataToDevice(instructionCode); }); builder.setNegativeButton("CANCEL", (dialog, which) -> dialog.dismiss()); AlertDialog dialog = builder.create(); if (dialog.getWindow() != null) { dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); } dialog.show(); } private void setupObservers(TerminalRVAdapter terminalRVAdapter) { final Observer<LauncherOutputData> currentSerialOutputObserver = s -> { if (s == null) { return; } terminalRVAdapter.appendNewTerminalLog(s); binding.recyclerViewLogsTerminal.scrollToPosition(terminalRVAdapter.getItemCount() - 1); }; terminalViewModel.currentSerialOutputRaw.observe(getViewLifecycleOwner(), currentSerialOutputObserver); terminalViewModel.currentSerialOutput.observe(getViewLifecycleOwner(), currentSerialOutputObserver); setupSerialInputErrorListener(); setupSerialOutputErrorListener(); } private void setupSerialInputErrorListener() { final Observer<String> writeErrorListener = s -> { if (s == null) { return; } terminalViewModel.currentSerialInputError.setValue(null); Log.d("dev-log", "TerminalFragment.setupSerialInputErrorListener: " + "Error on user input"); stopEventReadAndDisconnectFromDevice(); Toast.makeText(requireActivity(), "Error writing " + s, Toast.LENGTH_SHORT).show(); Log.d("dev-log", "TerminalFragment.setupSerialInputErrorListener: " + "Popping this fragment off the back stack"); Navigation.findNavController(binding.getRoot()).popBackStack(); }; terminalViewModel.currentSerialInputError.observe(getViewLifecycleOwner(), writeErrorListener); } private void setupSerialOutputErrorListener() { final Observer<String> onNewDataErrorListener = s -> { if (s == null) { return; } terminalViewModel.currentSerialOutputError.setValue(null); Log.d("dev-log", "TerminalFragment.setupSerialOutputErrorListener: " + "Error on serial output"); stopEventReadAndDisconnectFromDevice(); Toast.makeText(requireActivity(), "Error: " + s, Toast.LENGTH_SHORT).show(); Log.d("dev-log", "TerminalFragment.setupSerialOutputErrorListener: " + "Popping this fragment off the back stack"); Navigation.findNavController(binding.getRoot()).popBackStack(); }; terminalViewModel.currentSerialOutputError.observe( getViewLifecycleOwner(), onNewDataErrorListener); } @Override public void onResume() { super.onResume(); Log.d("dev-log", "TerminalFragment.onResume: Fragment resumed"); Log.d("dev-log", "TerminalFragment.onResume: Connecting to device"); connectToDevice(); terminalViewModel.setLauncherEventHandler(); } private void connectToDevice() { int deviceId = terminalArgs.getDeviceId(); int portNum = terminalArgs.getPortNum(); DeviceConnectionParamData deviceConnectionParamData = new DeviceConnectionParamData(
BAUD_RATE, DATA_BITS, STOP_BITS, PARITY_NONE, deviceId, portNum);
3
2023-11-15 15:54:39+00:00
8k
Charles7c/continew-starter
continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/base/BaseController.java
[ { "identifier": "StringConstants", "path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/constant/StringConstants.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class StringConstants implements StrPool {\n\n /**\n * 空字符串\n */\n public...
import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.lang.tree.Tree; import cn.hutool.core.util.StrUtil; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.enums.ParameterIn; import jakarta.servlet.http.HttpServletResponse; import lombok.NoArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import top.charles7c.continew.starter.core.constant.StringConstants; import top.charles7c.continew.starter.extension.crud.annotation.CrudRequestMapping; import top.charles7c.continew.starter.extension.crud.enums.Api; import top.charles7c.continew.starter.extension.crud.model.query.PageQuery; import top.charles7c.continew.starter.extension.crud.model.query.SortQuery; import top.charles7c.continew.starter.extension.crud.model.resp.PageDataResp; import top.charles7c.continew.starter.extension.crud.model.resp.R; import java.util.List;
4,445
/* * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved. * <p> * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.gnu.org/licenses/lgpl.html * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.charles7c.continew.starter.extension.crud.base; /** * 控制器基类 * * @param <S> 业务接口 * @param <L> 列表信息 * @param <D> 详情信息 * @param <Q> 查询条件 * @param <C> 创建或修改信息 * @author Charles7c * @since 1.0.0 */ @NoArgsConstructor public abstract class BaseController<S extends BaseService<L, D, Q, C>, L, D, Q, C extends BaseReq> { @Autowired protected S baseService; /** * 分页查询列表 * * @param query 查询条件 * @param pageQuery 分页查询条件 * @return 分页信息 */ @Operation(summary = "分页查询列表", description = "分页查询列表") @ResponseBody @GetMapping public R<PageDataResp<L>> page(Q query, @Validated PageQuery pageQuery) { this.checkPermission(Api.LIST); PageDataResp<L> pageData = baseService.page(query, pageQuery); return R.ok(pageData); } /** * 查询树列表 * * @param query 查询条件 * @param sortQuery 排序查询条件 * @return 树列表信息 */ @Operation(summary = "查询树列表", description = "查询树列表") @ResponseBody @GetMapping("/tree") public R<List<Tree<Long>>> tree(Q query, SortQuery sortQuery) { this.checkPermission(Api.LIST); List<Tree<Long>> list = baseService.tree(query, sortQuery, false); return R.ok(list); } /** * 查询列表 * * @param query 查询条件 * @param sortQuery 排序查询条件 * @return 列表信息 */ @Operation(summary = "查询列表", description = "查询列表") @ResponseBody @GetMapping("/list") public R<List<L>> list(Q query, SortQuery sortQuery) { this.checkPermission(Api.LIST); List<L> list = baseService.list(query, sortQuery); return R.ok(list); } /** * 查看详情 * * @param id ID * @return 详情信息 */ @Operation(summary = "查看详情", description = "查看详情") @Parameter(name = "id", description = "ID", example = "1", in = ParameterIn.PATH) @ResponseBody @GetMapping("/{id}") public R<D> get(@PathVariable Long id) { this.checkPermission(Api.LIST); D detail = baseService.get(id); return R.ok(detail); } /** * 新增 * * @param req 创建信息 * @return 自增 ID */ @Operation(summary = "新增数据", description = "新增数据") @ResponseBody @PostMapping public R<Long> add(@Validated(ValidateGroup.Crud.Add.class) @RequestBody C req) { this.checkPermission(Api.ADD); Long id = baseService.add(req); return R.ok("新增成功", id); } /** * 修改 * * @param req 修改信息 * @param id ID * @return / */ @Operation(summary = "修改数据", description = "修改数据") @Parameter(name = "id", description = "ID", example = "1", in = ParameterIn.PATH) @ResponseBody @PutMapping("/{id}") public R update(@Validated(ValidateGroup.Crud.Update.class) @RequestBody C req, @PathVariable Long id) { this.checkPermission(Api.UPDATE); baseService.update(req, id); return R.ok("修改成功"); } /** * 删除 * * @param ids ID 列表 * @return / */ @Operation(summary = "删除数据", description = "删除数据") @Parameter(name = "ids", description = "ID 列表", example = "1,2", in = ParameterIn.PATH) @ResponseBody @DeleteMapping("/{ids}") public R delete(@PathVariable List<Long> ids) { this.checkPermission(Api.DELETE); baseService.delete(ids); return R.ok("删除成功"); } /** * 导出 * * @param query 查询条件 * @param sortQuery 排序查询条件 * @param response 响应对象 */ @Operation(summary = "导出数据", description = "导出数据") @GetMapping("/export") public void export(Q query, SortQuery sortQuery, HttpServletResponse response) { this.checkPermission(Api.EXPORT); baseService.export(query, sortQuery, response); } /** * 根据 API 类型进行权限验证 * * @param api API 类型 */ private void checkPermission(Api api) { CrudRequestMapping crudRequestMapping = this.getClass().getDeclaredAnnotation(CrudRequestMapping.class); String path = crudRequestMapping.value();
/* * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved. * <p> * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.gnu.org/licenses/lgpl.html * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.charles7c.continew.starter.extension.crud.base; /** * 控制器基类 * * @param <S> 业务接口 * @param <L> 列表信息 * @param <D> 详情信息 * @param <Q> 查询条件 * @param <C> 创建或修改信息 * @author Charles7c * @since 1.0.0 */ @NoArgsConstructor public abstract class BaseController<S extends BaseService<L, D, Q, C>, L, D, Q, C extends BaseReq> { @Autowired protected S baseService; /** * 分页查询列表 * * @param query 查询条件 * @param pageQuery 分页查询条件 * @return 分页信息 */ @Operation(summary = "分页查询列表", description = "分页查询列表") @ResponseBody @GetMapping public R<PageDataResp<L>> page(Q query, @Validated PageQuery pageQuery) { this.checkPermission(Api.LIST); PageDataResp<L> pageData = baseService.page(query, pageQuery); return R.ok(pageData); } /** * 查询树列表 * * @param query 查询条件 * @param sortQuery 排序查询条件 * @return 树列表信息 */ @Operation(summary = "查询树列表", description = "查询树列表") @ResponseBody @GetMapping("/tree") public R<List<Tree<Long>>> tree(Q query, SortQuery sortQuery) { this.checkPermission(Api.LIST); List<Tree<Long>> list = baseService.tree(query, sortQuery, false); return R.ok(list); } /** * 查询列表 * * @param query 查询条件 * @param sortQuery 排序查询条件 * @return 列表信息 */ @Operation(summary = "查询列表", description = "查询列表") @ResponseBody @GetMapping("/list") public R<List<L>> list(Q query, SortQuery sortQuery) { this.checkPermission(Api.LIST); List<L> list = baseService.list(query, sortQuery); return R.ok(list); } /** * 查看详情 * * @param id ID * @return 详情信息 */ @Operation(summary = "查看详情", description = "查看详情") @Parameter(name = "id", description = "ID", example = "1", in = ParameterIn.PATH) @ResponseBody @GetMapping("/{id}") public R<D> get(@PathVariable Long id) { this.checkPermission(Api.LIST); D detail = baseService.get(id); return R.ok(detail); } /** * 新增 * * @param req 创建信息 * @return 自增 ID */ @Operation(summary = "新增数据", description = "新增数据") @ResponseBody @PostMapping public R<Long> add(@Validated(ValidateGroup.Crud.Add.class) @RequestBody C req) { this.checkPermission(Api.ADD); Long id = baseService.add(req); return R.ok("新增成功", id); } /** * 修改 * * @param req 修改信息 * @param id ID * @return / */ @Operation(summary = "修改数据", description = "修改数据") @Parameter(name = "id", description = "ID", example = "1", in = ParameterIn.PATH) @ResponseBody @PutMapping("/{id}") public R update(@Validated(ValidateGroup.Crud.Update.class) @RequestBody C req, @PathVariable Long id) { this.checkPermission(Api.UPDATE); baseService.update(req, id); return R.ok("修改成功"); } /** * 删除 * * @param ids ID 列表 * @return / */ @Operation(summary = "删除数据", description = "删除数据") @Parameter(name = "ids", description = "ID 列表", example = "1,2", in = ParameterIn.PATH) @ResponseBody @DeleteMapping("/{ids}") public R delete(@PathVariable List<Long> ids) { this.checkPermission(Api.DELETE); baseService.delete(ids); return R.ok("删除成功"); } /** * 导出 * * @param query 查询条件 * @param sortQuery 排序查询条件 * @param response 响应对象 */ @Operation(summary = "导出数据", description = "导出数据") @GetMapping("/export") public void export(Q query, SortQuery sortQuery, HttpServletResponse response) { this.checkPermission(Api.EXPORT); baseService.export(query, sortQuery, response); } /** * 根据 API 类型进行权限验证 * * @param api API 类型 */ private void checkPermission(Api api) { CrudRequestMapping crudRequestMapping = this.getClass().getDeclaredAnnotation(CrudRequestMapping.class); String path = crudRequestMapping.value();
String permissionPrefix = String.join(StringConstants.COLON, StrUtil.splitTrim(path, StringConstants.SLASH));
0
2023-11-16 15:48:18+00:00
8k
xIdentified/Devotions
src/main/java/me/xidentified/devotions/managers/ShrineManager.java
[ { "identifier": "Devotions", "path": "src/main/java/me/xidentified/devotions/Devotions.java", "snippet": "@Getter\npublic class Devotions extends JavaPlugin {\n @Getter private static Devotions instance;\n private DevotionManager devotionManager;\n private RitualManager ritualManager;\n priv...
import lombok.Getter; import me.xidentified.devotions.Devotions; import me.xidentified.devotions.Shrine; import me.xidentified.devotions.storage.ShrineStorage; import org.bukkit.Location; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap;
6,915
package me.xidentified.devotions.managers; public class ShrineManager { @Getter private final Devotions plugin;
package me.xidentified.devotions.managers; public class ShrineManager { @Getter private final Devotions plugin;
private ShrineStorage shrineStorage;
2
2023-11-10 07:03:24+00:00
8k
Appu26J/Calculator
src/appu26j/Calculator.java
[ { "identifier": "Assets", "path": "src/appu26j/assets/Assets.java", "snippet": "public class Assets\n{\n\tprivate static final String tempDirectory = System.getProperty(\"java.io.tmpdir\");\n\tprivate static final ArrayList<String> assets = new ArrayList<>();\n\t\n\tstatic\n\t{\n\t\tassets.add(\"segoeui...
import appu26j.assets.Assets; import appu26j.gui.font.FontRenderer; import appu26j.gui.screens.GuiCalculator; import appu26j.gui.screens.GuiScreen; import org.lwjgl.glfw.GLFWCharCallback; import org.lwjgl.glfw.GLFWErrorCallback; import org.lwjgl.glfw.GLFWKeyCallback; import org.lwjgl.glfw.GLFWMouseButtonCallback; import org.lwjgl.opengl.GL; import org.lwjgl.system.MemoryStack; import java.nio.DoubleBuffer; import java.util.Objects; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL11.*;
5,179
package appu26j; public enum Calculator { INSTANCE; private final int width = 445, height = 600; private float mouseX = 0, mouseY = 0;
package appu26j; public enum Calculator { INSTANCE; private final int width = 445, height = 600; private float mouseX = 0, mouseY = 0;
private GuiScreen currentScreen;
3
2023-11-10 18:00:58+00:00
8k
SplitfireUptown/datalinkx
flinkx/flinkx-restapi/flinkx-restapi-reader/src/main/java/com/dtstack/flinkx/restapi/inputformat/HttpClient.java
[ { "identifier": "ConstantValue", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/constants/ConstantValue.java", "snippet": "public class ConstantValue {\n\n public static final String STAR_SYMBOL = \"*\";\n public static final String POINT_SYMBOL = \".\";\n public static final Stri...
import com.dtstack.flinkx.constants.ConstantValue; import com.dtstack.flinkx.reader.MetaColumn; import com.dtstack.flinkx.restapi.common.HttpUtil; import com.dtstack.flinkx.restapi.common.MapUtils; import com.dtstack.flinkx.restapi.common.RestContext; import com.dtstack.flinkx.restapi.common.exception.ReadRecordException; import com.dtstack.flinkx.restapi.common.exception.ResponseRetryException; import com.dtstack.flinkx.restapi.common.handler.DataHandler; import com.dtstack.flinkx.restapi.common.httprequestApi; import com.dtstack.flinkx.util.ExceptionUtil; import com.dtstack.flinkx.util.GsonUtil; import org.apache.commons.collections.CollectionUtils; import org.apache.flink.types.Row; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger;
6,129
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flinkx.restapi.inputformat; /** * httpClient * * @author by dujie@dtstack.com * @Date 2020/9/25 */ public class HttpClient { private static final Logger LOG = LoggerFactory.getLogger(HttpClient.class); private ScheduledExecutorService scheduledExecutorService; protected transient CloseableHttpClient httpClient; private final long intervalTime; private BlockingQueue<Row> queue; private RestContext restContext; private static final String THREAD_NAME = "restApiReader-thread"; private List<MetaColumn> metaColumns;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flinkx.restapi.inputformat; /** * httpClient * * @author by dujie@dtstack.com * @Date 2020/9/25 */ public class HttpClient { private static final Logger LOG = LoggerFactory.getLogger(HttpClient.class); private ScheduledExecutorService scheduledExecutorService; protected transient CloseableHttpClient httpClient; private final long intervalTime; private BlockingQueue<Row> queue; private RestContext restContext; private static final String THREAD_NAME = "restApiReader-thread"; private List<MetaColumn> metaColumns;
private List<DataHandler> handlers;
7
2023-11-16 02:22:52+00:00
8k
raphael-goetz/betterflowers
src/main/java/com/uroria/betterflowers/BetterFlowers.java
[ { "identifier": "CustomFlowerBrushListener", "path": "src/main/java/com/uroria/betterflowers/listeners/CustomFlowerBrushListener.java", "snippet": "public final class CustomFlowerBrushListener implements Listener {\n\n private final FlowerManager flowerManager;\n private final List<Block> flowerBl...
import com.uroria.betterflowers.commands.Flower; import com.uroria.betterflowers.commands.FlowerBrush; import com.uroria.betterflowers.commands.UndoFlower; import com.uroria.betterflowers.listeners.CustomFlowerBrushListener; import com.uroria.betterflowers.listeners.CustomFlowerPlaceListener; import com.uroria.betterflowers.managers.FlowerManager; import com.uroria.betterflowers.managers.LanguageManager; import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import java.util.List;
3,911
package com.uroria.betterflowers; @Getter public final class BetterFlowers extends JavaPlugin { private final FlowerManager flowerManager; private final LanguageManager languageManager; public BetterFlowers() { this.flowerManager = new FlowerManager(); this.languageManager = new LanguageManager(); } @Override public void onEnable() { registerCommands(); registerListener(); } private void registerCommands() { final var flowerCommand = getCommand("flower"); if (flowerCommand != null) { flowerCommand.setAliases(List.of("f", "F")); flowerCommand.setExecutor(new Flower(this)); } final var flowerBrushCommand = getCommand("flowerbrush"); if (flowerBrushCommand != null) { flowerBrushCommand.setAliases(List.of("fb", "Fb", "fB", "FB")); flowerBrushCommand.setExecutor(new FlowerBrush(this)); } final var undoFlowerCommand = getCommand("undoflower"); if (undoFlowerCommand != null) { undoFlowerCommand.setAliases(List.of("uf", "Uf", "uF", "UF")); undoFlowerCommand.setExecutor(new UndoFlower(this)); } } private void registerListener() { Bukkit.getPluginManager().registerEvents(new CustomFlowerPlaceListener(this), this);
package com.uroria.betterflowers; @Getter public final class BetterFlowers extends JavaPlugin { private final FlowerManager flowerManager; private final LanguageManager languageManager; public BetterFlowers() { this.flowerManager = new FlowerManager(); this.languageManager = new LanguageManager(); } @Override public void onEnable() { registerCommands(); registerListener(); } private void registerCommands() { final var flowerCommand = getCommand("flower"); if (flowerCommand != null) { flowerCommand.setAliases(List.of("f", "F")); flowerCommand.setExecutor(new Flower(this)); } final var flowerBrushCommand = getCommand("flowerbrush"); if (flowerBrushCommand != null) { flowerBrushCommand.setAliases(List.of("fb", "Fb", "fB", "FB")); flowerBrushCommand.setExecutor(new FlowerBrush(this)); } final var undoFlowerCommand = getCommand("undoflower"); if (undoFlowerCommand != null) { undoFlowerCommand.setAliases(List.of("uf", "Uf", "uF", "UF")); undoFlowerCommand.setExecutor(new UndoFlower(this)); } } private void registerListener() { Bukkit.getPluginManager().registerEvents(new CustomFlowerPlaceListener(this), this);
Bukkit.getPluginManager().registerEvents(new CustomFlowerBrushListener(this), this);
0
2023-11-18 16:13:59+00:00
8k
Appu26J/Softuninstall
src/appu26j/Softuninstall.java
[ { "identifier": "Assets", "path": "src/appu26j/assets/Assets.java", "snippet": "public class Assets\n{\n\tprivate static final String tempDirectory = System.getProperty(\"java.io.tmpdir\");\n\tprivate static final ArrayList<String> assets = new ArrayList<>();\n\t\n\tstatic\n\t{\n\t\tassets.add(\"segoeui...
import appu26j.assets.Assets; import appu26j.gui.font.FontRenderer; import appu26j.gui.screens.GuiScreen; import appu26j.gui.screens.GuiSoftuninstall; import org.lwjgl.glfw.*; import org.lwjgl.opengl.GL; import org.lwjgl.system.MemoryStack; import java.nio.DoubleBuffer; import java.util.Objects; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL11.*;
4,591
package appu26j; public enum Softuninstall { INSTANCE; private final int width = 900, height = 700; private float mouseX = 0, mouseY = 0;
package appu26j; public enum Softuninstall { INSTANCE; private final int width = 900, height = 700; private float mouseX = 0, mouseY = 0;
private GuiScreen currentScreen;
2
2023-11-13 03:20:19+00:00
8k
12manel123/tsys-my-food-api-1011
src/main/java/com/myfood/controllers/UserController.java
[ { "identifier": "Role", "path": "src/main/java/com/myfood/dto/Role.java", "snippet": "@Entity\n@Table(name = \"roles\")\npublic class Role {\n\n\n /** Unique identifier for the role. Automatically generated. */\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTI...
import java.time.LocalDateTime; import java.time.ZoneId; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.myfood.dto.Role; import com.myfood.dto.User; import com.myfood.dto.UserDTO; import com.myfood.services.RolServiceImpl; import com.myfood.services.UserServiceImpl; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
3,784
package com.myfood.controllers; /** * @author David Maza * */ /** * @author Davi Maza * */ /** * Controller class for handling user-related operations. * * This controller provides endpoints for basic CRUD operations on users. * * @RestController Indicates that this class is a Spring MVC Controller. * @RequestMapping("/api/v1") Base mapping for all endpoints in this controller. */ @RestController @RequestMapping("api/v1") public class UserController { @Autowired
package com.myfood.controllers; /** * @author David Maza * */ /** * @author Davi Maza * */ /** * Controller class for handling user-related operations. * * This controller provides endpoints for basic CRUD operations on users. * * @RestController Indicates that this class is a Spring MVC Controller. * @RequestMapping("/api/v1") Base mapping for all endpoints in this controller. */ @RestController @RequestMapping("api/v1") public class UserController { @Autowired
private UserServiceImpl userServ;
4
2023-11-10 16:09:43+00:00
8k
Artillex-Studios/AxGraves
src/main/java/com/artillexstudios/axgraves/listeners/DeathListener.java
[ { "identifier": "GravePreSpawnEvent", "path": "src/main/java/com/artillexstudios/axgraves/api/events/GravePreSpawnEvent.java", "snippet": "public class GravePreSpawnEvent extends Event implements Cancellable {\n private static final HandlerList handlerList = new HandlerList();\n private final Play...
import com.artillexstudios.axgraves.api.events.GravePreSpawnEvent; import com.artillexstudios.axgraves.api.events.GraveSpawnEvent; import com.artillexstudios.axgraves.grave.Grave; import com.artillexstudios.axgraves.grave.SpawnedGrave; import com.artillexstudios.axgraves.utils.ExperienceUtils; 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.entity.PlayerDeathEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import static com.artillexstudios.axgraves.AxGraves.CONFIG;
3,735
package com.artillexstudios.axgraves.listeners; public class DeathListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onDeath(@NotNull PlayerDeathEvent event) { if (CONFIG.getStringList("disabled-worlds") != null && CONFIG.getStringList("disabled-worlds").contains(event.getEntity().getWorld().getName())) return; if (!CONFIG.getBoolean("override-keep-inventory", true) && event.getKeepInventory()) return; final Player player = event.getEntity(); if (player.getInventory().isEmpty() && player.getTotalExperience() == 0) return; Grave grave = null; if (!event.getKeepInventory()) { grave = new Grave(player.getLocation(), player, event.getDrops().toArray(new ItemStack[0]), ExperienceUtils.getExp(player)); } else if (CONFIG.getBoolean("override-keep-inventory", true)) { grave = new Grave(player.getLocation(), player, player.getInventory().getContents(), ExperienceUtils.getExp(player)); player.setLevel(0); player.setTotalExperience(0); player.getInventory().clear(); } if (grave == null) return;
package com.artillexstudios.axgraves.listeners; public class DeathListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onDeath(@NotNull PlayerDeathEvent event) { if (CONFIG.getStringList("disabled-worlds") != null && CONFIG.getStringList("disabled-worlds").contains(event.getEntity().getWorld().getName())) return; if (!CONFIG.getBoolean("override-keep-inventory", true) && event.getKeepInventory()) return; final Player player = event.getEntity(); if (player.getInventory().isEmpty() && player.getTotalExperience() == 0) return; Grave grave = null; if (!event.getKeepInventory()) { grave = new Grave(player.getLocation(), player, event.getDrops().toArray(new ItemStack[0]), ExperienceUtils.getExp(player)); } else if (CONFIG.getBoolean("override-keep-inventory", true)) { grave = new Grave(player.getLocation(), player, player.getInventory().getContents(), ExperienceUtils.getExp(player)); player.setLevel(0); player.setTotalExperience(0); player.getInventory().clear(); } if (grave == null) return;
final GravePreSpawnEvent gravePreSpawnEvent = new GravePreSpawnEvent(player, grave);
0
2023-11-18 16:37:27+00:00
8k
GoldenStack/minestom-ca
src/main/java/dev/goldenstack/minestom_ca/server/Main.java
[ { "identifier": "AutomataWorld", "path": "src/main/java/dev/goldenstack/minestom_ca/AutomataWorld.java", "snippet": "public interface AutomataWorld {\n\n Map<Instance, AutomataWorld> WORLDS = new HashMap<>();\n\n static void register(AutomataWorld world) {\n final AutomataWorld prev = WORLD...
import dev.goldenstack.minestom_ca.AutomataWorld; import dev.goldenstack.minestom_ca.Program; import dev.goldenstack.minestom_ca.backends.lazy.LazyWorld; import dev.goldenstack.minestom_ca.server.commands.StartCommand; import dev.goldenstack.minestom_ca.server.commands.StateCommand; import dev.goldenstack.minestom_ca.server.commands.StopCommand; import net.kyori.adventure.text.Component; import net.minestom.server.MinecraftServer; import net.minestom.server.adventure.audience.Audiences; import net.minestom.server.coordinate.Point; import net.minestom.server.coordinate.Pos; import net.minestom.server.entity.GameMode; import net.minestom.server.entity.Player; import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.instance.InstanceChunkLoadEvent; import net.minestom.server.event.instance.InstanceChunkUnloadEvent; import net.minestom.server.event.instance.InstanceTickEvent; import net.minestom.server.event.player.PlayerBlockBreakEvent; import net.minestom.server.event.player.PlayerBlockInteractEvent; import net.minestom.server.event.player.PlayerBlockPlaceEvent; import net.minestom.server.event.player.PlayerLoginEvent; import net.minestom.server.instance.InstanceContainer; import net.minestom.server.instance.LightingChunk; import net.minestom.server.instance.block.Block; import net.minestom.server.inventory.PlayerInventory; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import org.jglrxavpok.hephaistos.nbt.NBT; import org.jglrxavpok.hephaistos.nbt.NBTCompound; import org.jglrxavpok.hephaistos.nbt.NBTInt; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean;
4,698
package dev.goldenstack.minestom_ca.server; public final class Main { public static final AtomicBoolean RUNNING = new AtomicBoolean(true); private static final Program FILE_PROGRAM = Program.fromFile(Path.of("rules/piston")); public static void main(String[] args) { MinecraftServer minecraftServer = MinecraftServer.init(); // Register commands MinecraftServer.getCommandManager().register(new StartCommand());
package dev.goldenstack.minestom_ca.server; public final class Main { public static final AtomicBoolean RUNNING = new AtomicBoolean(true); private static final Program FILE_PROGRAM = Program.fromFile(Path.of("rules/piston")); public static void main(String[] args) { MinecraftServer minecraftServer = MinecraftServer.init(); // Register commands MinecraftServer.getCommandManager().register(new StartCommand());
MinecraftServer.getCommandManager().register(new StopCommand());
4
2023-11-18 21:49:11+00:00
8k
kotmatross28729/EnviroMine-continuation
src/main/java/enviromine/world/EM_WorldData.java
[ { "identifier": "EnumLogVerbosity", "path": "src/main/java/enviromine/core/EM_ConfigHandler.java", "snippet": "public enum EnumLogVerbosity\n{\n\tNONE(0),\n\tLOW(1),\n\tNORMAL(2),\n\tALL(3);\n\n\tprivate final int level;\n\n\tprivate EnumLogVerbosity(int level)\n\t{\n\t\tthis.level = level;\n\t}\n\n\tpu...
import org.apache.logging.log4j.Level; import enviromine.core.EM_ConfigHandler.EnumLogVerbosity; import enviromine.core.EM_Settings; import enviromine.core.EnviroMine; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraft.world.WorldSavedData;
4,889
package enviromine.world; public class EM_WorldData extends WorldSavedData { private static final String IDENTIFIER = "EM_WorldData"; private String profile = "default"; public static EM_WorldData theWorldEM; public EM_WorldData() { super(IDENTIFIER); } public EM_WorldData(String identifier) { super(identifier); } @Override public void readFromNBT(NBTTagCompound nbt) { this.profile = nbt.getString("Profile"); } public boolean setProfile(String newProfile) { this.profile = newProfile; this.markDirty(); return true; } public String getProfile() { return profile; } public EM_WorldData getEMWorldData() { return theWorldEM; } @Override public void writeToNBT(NBTTagCompound nbt) { nbt.setString("Profile", profile); } public static EM_WorldData get(World world) { EM_WorldData data = (EM_WorldData)world.loadItemData(EM_WorldData.class, IDENTIFIER); if (data == null) { data = new EM_WorldData(); world.setItemData(IDENTIFIER, data);
package enviromine.world; public class EM_WorldData extends WorldSavedData { private static final String IDENTIFIER = "EM_WorldData"; private String profile = "default"; public static EM_WorldData theWorldEM; public EM_WorldData() { super(IDENTIFIER); } public EM_WorldData(String identifier) { super(identifier); } @Override public void readFromNBT(NBTTagCompound nbt) { this.profile = nbt.getString("Profile"); } public boolean setProfile(String newProfile) { this.profile = newProfile; this.markDirty(); return true; } public String getProfile() { return profile; } public EM_WorldData getEMWorldData() { return theWorldEM; } @Override public void writeToNBT(NBTTagCompound nbt) { nbt.setString("Profile", profile); } public static EM_WorldData get(World world) { EM_WorldData data = (EM_WorldData)world.loadItemData(EM_WorldData.class, IDENTIFIER); if (data == null) { data = new EM_WorldData(); world.setItemData(IDENTIFIER, data);
if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel()) EnviroMine.logger.log(Level.ERROR, "Enviromine World Data Doesn't Exist. Creating now");
1
2023-11-16 18:15:29+00:00
8k
spring-projects/spring-rewrite-commons
spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/parsers/maven/MavenProjectAnalyzer.java
[ { "identifier": "MavenProject", "path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/parsers/MavenProject.java", "snippet": "public class MavenProject {\n\n\tprivate final Path projectRoot;\n\n\tprivate final Resource pomFile;\n\n\t// FIXME: 945 temporary method, model shou...
import java.util.function.Predicate; import java.util.stream.Collectors; import org.apache.maven.model.*; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.jetbrains.annotations.NotNull; import org.openrewrite.maven.utilities.MavenArtifactDownloader; import org.springframework.core.io.Resource; import org.springframework.rewrite.parsers.MavenProject; import org.springframework.rewrite.parsers.ParserContext; import org.springframework.rewrite.utils.LinuxWindowsPathUnifier; import org.springframework.rewrite.utils.ResourceUtil; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.*;
4,023
/* * Copyright 2021 - 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.rewrite.parsers.maven; /** * Implements the ordering of Maven (reactor) build projects. See <a href= * "https://maven.apache.org/guides/mini/guide-multiple-modules.html#reactor-sorting">Reactor * Sorting</a> * * @author Fabian Krüger */ public class MavenProjectAnalyzer { private static final String POM_XML = "pom.xml"; private static final MavenXpp3Reader XPP_3_READER = new MavenXpp3Reader(); private final MavenArtifactDownloader rewriteMavenArtifactDownloader; public MavenProjectAnalyzer(MavenArtifactDownloader rewriteMavenArtifactDownloader) { this.rewriteMavenArtifactDownloader = rewriteMavenArtifactDownloader; }
/* * Copyright 2021 - 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.rewrite.parsers.maven; /** * Implements the ordering of Maven (reactor) build projects. See <a href= * "https://maven.apache.org/guides/mini/guide-multiple-modules.html#reactor-sorting">Reactor * Sorting</a> * * @author Fabian Krüger */ public class MavenProjectAnalyzer { private static final String POM_XML = "pom.xml"; private static final MavenXpp3Reader XPP_3_READER = new MavenXpp3Reader(); private final MavenArtifactDownloader rewriteMavenArtifactDownloader; public MavenProjectAnalyzer(MavenArtifactDownloader rewriteMavenArtifactDownloader) { this.rewriteMavenArtifactDownloader = rewriteMavenArtifactDownloader; }
public List<MavenProject> getSortedProjects(Path baseDir, List<Resource> resources) {
0
2023-11-14 23:02:37+00:00
8k
giftorg/gift
gift-analyze/src/main/java/org/giftorg/analyze/AnalyzeApplication.java
[ { "identifier": "AnalyzeTask", "path": "gift-analyze/src/main/java/org/giftorg/analyze/entity/AnalyzeTask.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\npublic class AnalyzeTask extends RetryTask {\n private Repository project;\n\n private Integer retryCount;\n\n public static ...
import org.giftorg.common.kafka.KafkaProducerClient; import org.giftorg.common.tokenpool.TokenPool; import cn.hutool.json.JSONUtil; import lombok.extern.slf4j.Slf4j; import org.apache.spark.SparkConf; import org.apache.spark.SparkContext; import org.giftorg.analyze.entity.AnalyzeTask; import org.giftorg.analyze.entity.Repository; import org.giftorg.analyze.service.AnalyzeService; import org.giftorg.analyze.service.impl.AnalyzeServiceImpl; import org.giftorg.common.config.Config; import org.giftorg.common.elasticsearch.Elasticsearch; import org.giftorg.common.kafka.KafkaConsumerClient;
6,218
/** * Copyright 2023 GiftOrg Authors * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.giftorg.analyze; @Slf4j public class AnalyzeApplication { public static void main(String[] args) { SparkConf conf = new SparkConf() .setAppName("GiftAnalyzer")
/** * Copyright 2023 GiftOrg Authors * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.giftorg.analyze; @Slf4j public class AnalyzeApplication { public static void main(String[] args) { SparkConf conf = new SparkConf() .setAppName("GiftAnalyzer")
.setMaster(Config.sparkConfig.getMaster());
4
2023-11-15 08:58:35+00:00
8k
exadel-inc/etoolbox-anydiff
core/src/main/java/com/exadel/etoolbox/anydiff/comparison/LineImpl.java
[ { "identifier": "Constants", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/Constants.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class Constants {\n\n public static final String ROOT_PACKAGE = \"com.exadel.etoolbox.anydiff\";\n\n public static final int DE...
import com.exadel.etoolbox.anydiff.Constants; import com.exadel.etoolbox.anydiff.OutputType; import com.exadel.etoolbox.anydiff.diff.Diff; import com.exadel.etoolbox.anydiff.diff.DiffEntry; import com.exadel.etoolbox.anydiff.diff.DiffState; import com.exadel.etoolbox.anydiff.diff.EntryHolder; import com.exadel.etoolbox.anydiff.diff.Fragment; import com.exadel.etoolbox.anydiff.diff.FragmentHolder; import com.exadel.etoolbox.anydiff.diff.PrintableEntry; import lombok.Getter; import lombok.Setter; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List;
4,909
if (fragmentPairs == null) { initFragmentsCache(); } return fragmentPairs; } @Override public String getLeft(boolean includeContext) { if (!includeContext && isContext) { return StringUtils.EMPTY; } return left.toString(); } @Override public String getRight(boolean includeContext) { if (!includeContext && isContext) { return StringUtils.EMPTY; } return right.toString(); } @Override public List<Fragment> getLeftFragments() { if (leftFragments == null) { initFragmentsCache(); } return leftFragments; } @Override public List<Fragment> getRightFragments() { if (rightFragments == null) { initFragmentsCache(); } return rightFragments; } /** * Gets the left side of the current line * @return A {@link MarkedString} instance */ MarkedString getLeftSide() { return left; } /** * Gets the right side of the current line * @return A {@link MarkedString} instance */ MarkedString getRightSide() { return right; } private void initFragmentsCache() { leftFragments = isMarkupType ? left.getMarkupFragments() : left.getFragments(); rightFragments = isMarkupType ? right.getMarkupFragments() : right.getFragments(); if (leftFragments.size() != rightFragments.size() || leftFragments.isEmpty() || ((FragmentImpl) leftFragments.get(0)).getLineOffset() != ((FragmentImpl) rightFragments.get(0)).getLineOffset()) { fragmentPairs = Collections.emptyList(); return; } Iterator<Fragment> leftIterator = leftFragments.iterator(); Iterator<Fragment> rightIterator = rightFragments.iterator(); fragmentPairs = new ArrayList<>(); while (leftIterator.hasNext()) { Fragment leftFragment = leftIterator.next(); Fragment rightFragment = rightIterator.next(); fragmentPairs.add(new FragmentPairImpl(this, leftFragment, rightFragment)); } } private void resetFragmentsCache() { leftFragments = null; rightFragments = null; fragmentPairs = null; } /* ---------- Operations ---------- */ @Override public void accept() { left.accept(); right.accept(); resetFragmentsCache(); } @Override public void accept(Fragment value) { left.accept(value); right.accept(value); resetFragmentsCache(); } @Override public void exclude(DiffEntry value) { if (!(value instanceof FragmentPairImpl)) { return; } FragmentPairImpl fragmentPair = (FragmentPairImpl) value; left.unmark(fragmentPair.getLeftFragment()); right.unmark(fragmentPair.getRightFragment()); resetFragmentsCache(); } @Override public void exclude(Fragment value) { left.unmark(value); right.unmark(value); resetFragmentsCache(); } /* ------ Output ------ */ @Override
/* * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exadel.etoolbox.anydiff.comparison; /** * Implements {@link DiffEntry} to represent a line within a block of text that either contains a difference or poses * a visual context * @see DiffEntry */ class LineImpl implements DiffEntry, FragmentHolder, EntryHolder, PrintableEntry { private static final MarkedString CONTEXT_ELLIPSIS = new MarkedString(Constants.ELLIPSIS, Marker.CONTEXT); private final MarkedString left; private final MarkedString right; /** * Gets whether the current line is a context line */ @Getter(value = lombok.AccessLevel.PACKAGE) private boolean isContext; private boolean isMarkupType; private List<Fragment> leftFragments; private List<Fragment> rightFragments; private List<FragmentPairImpl> fragmentPairs; /** * Assigns the reference to the block this line belongs to */ @Setter(value = lombok.AccessLevel.PACKAGE) private AbstractBlock block; /** * Initializes a new instance of {@link LineImpl} class * @param left The left side of the line * @param right The right side of the line */ LineImpl(MarkedString left, MarkedString right) { this.left = left != null ? left : new MarkedString(null); this.right = right != null ? right : new MarkedString(null); } /* --------------- State accessors --------------- */ /** * Gets the number of differences in the current line * @return An integer value */ int getCount() { if (getState() == DiffState.UNCHANGED) { return 0; } // Will sum up to X "unpaired" fragments + Y pairs (every pair count as 1) return getLeftFragments().size() + getRightFragments().size() - children().size(); } int getPendingCount() { if (getState() == DiffState.UNCHANGED) { return 0; } // Will sum up to X "unpaired" fragments + Y pairs (every pair count as 1) long result = getLeftFragments().stream().filter(Fragment::isPending).count() + getRightFragments().stream().filter(Fragment::isPending).count() - children().stream().filter(c -> ((FragmentPairImpl) c).isPending()).count(); return (int) result; } @Override public DiffState getState() { if (isContext) { return DiffState.UNCHANGED; } if (MarkedString.isEmpty(left) && !MarkedString.isEmpty(right)) { return right.hasChanges() ? DiffState.LEFT_MISSING : DiffState.UNCHANGED; } if (!MarkedString.isEmpty(left) && MarkedString.isEmpty(right)) { return left.hasChanges() ? DiffState.RIGHT_MISSING : DiffState.UNCHANGED; } if (MarkedString.isEmpty(left)) { return DiffState.UNCHANGED; } return left.hasChanges() || right.hasChanges() ? DiffState.CHANGE : DiffState.UNCHANGED; } /* --------------- Other accessors --------------- */ @Override public Diff getDiff() { return block != null ? block.getDiff() : null; } /** * Calculates the number of spaces that indent both the left and right sides of the current line * @return An integer value */ int getIndent() { int leftIndent = left.getIndent(); int rightIndent = right.getIndent(); if (leftIndent == 0 && left.toString().isEmpty()) { return rightIndent; } else if (rightIndent == 0 && right.toString().isEmpty()) { return leftIndent; } return Math.min(leftIndent, rightIndent); } /** * Sets the flag saying that the current line is a context line */ void setIsContext() { isContext = true; left.mark(Marker.CONTEXT); right.mark(Marker.CONTEXT); } /** * Sets the flag saying that the current line contains XML or HTML markup */ void setIsMarkup() { isMarkupType = true; } /** * Removes the specified number of characters from the left side of the current line. Used to trim leading spaces * and provide a more compact output */ void cutLeft(int count) { if (count == 0) { return; } left.cutLeft(count); right.cutLeft(count); } private int getColumnWidth() { return block != null ? block.getColumnWidth() : Constants.DEFAULT_COLUMN_WIDTH; } /* ------- Content ------- */ @Override public List<? extends DiffEntry> children() { if (fragmentPairs == null) { initFragmentsCache(); } return fragmentPairs; } @Override public String getLeft(boolean includeContext) { if (!includeContext && isContext) { return StringUtils.EMPTY; } return left.toString(); } @Override public String getRight(boolean includeContext) { if (!includeContext && isContext) { return StringUtils.EMPTY; } return right.toString(); } @Override public List<Fragment> getLeftFragments() { if (leftFragments == null) { initFragmentsCache(); } return leftFragments; } @Override public List<Fragment> getRightFragments() { if (rightFragments == null) { initFragmentsCache(); } return rightFragments; } /** * Gets the left side of the current line * @return A {@link MarkedString} instance */ MarkedString getLeftSide() { return left; } /** * Gets the right side of the current line * @return A {@link MarkedString} instance */ MarkedString getRightSide() { return right; } private void initFragmentsCache() { leftFragments = isMarkupType ? left.getMarkupFragments() : left.getFragments(); rightFragments = isMarkupType ? right.getMarkupFragments() : right.getFragments(); if (leftFragments.size() != rightFragments.size() || leftFragments.isEmpty() || ((FragmentImpl) leftFragments.get(0)).getLineOffset() != ((FragmentImpl) rightFragments.get(0)).getLineOffset()) { fragmentPairs = Collections.emptyList(); return; } Iterator<Fragment> leftIterator = leftFragments.iterator(); Iterator<Fragment> rightIterator = rightFragments.iterator(); fragmentPairs = new ArrayList<>(); while (leftIterator.hasNext()) { Fragment leftFragment = leftIterator.next(); Fragment rightFragment = rightIterator.next(); fragmentPairs.add(new FragmentPairImpl(this, leftFragment, rightFragment)); } } private void resetFragmentsCache() { leftFragments = null; rightFragments = null; fragmentPairs = null; } /* ---------- Operations ---------- */ @Override public void accept() { left.accept(); right.accept(); resetFragmentsCache(); } @Override public void accept(Fragment value) { left.accept(value); right.accept(value); resetFragmentsCache(); } @Override public void exclude(DiffEntry value) { if (!(value instanceof FragmentPairImpl)) { return; } FragmentPairImpl fragmentPair = (FragmentPairImpl) value; left.unmark(fragmentPair.getLeftFragment()); right.unmark(fragmentPair.getRightFragment()); resetFragmentsCache(); } @Override public void exclude(Fragment value) { left.unmark(value); right.unmark(value); resetFragmentsCache(); } /* ------ Output ------ */ @Override
public String toString(OutputType target) {
1
2023-11-16 14:29:45+00:00
8k
Walter-Stroebel/Jllama
src/main/java/nl/infcomtec/jllama/TextImage.java
[ { "identifier": "ImageObject", "path": "src/main/java/nl/infcomtec/simpleimage/ImageObject.java", "snippet": "public class ImageObject extends Image {\n\n private BufferedImage image;\n private final Semaphore lock = new Semaphore(0);\n private final List<ImageObjectListener> listeners = new Li...
import java.awt.BorderLayout; import java.awt.Container; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.util.concurrent.ExecutorService; import javax.swing.AbstractAction; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import nl.infcomtec.simpleimage.ImageObject; import nl.infcomtec.simpleimage.ImageViewer;
5,170
/* */ package nl.infcomtec.jllama; /** * * @author walter */ public class TextImage { public final JFrame frame; public final ImageObject imgObj; private final Modality worker; public TextImage(final ExecutorService pool, String title, Modality grpMod) throws Exception { worker = grpMod; frame = new JFrame(title); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); imgObj = new ImageObject(worker.getImage()); Container cp = frame.getContentPane(); cp.setLayout(new BorderLayout()); final JTextArea text = new JTextArea(60, 5); AbstractAction updateAction = new AbstractAction("Update") { @Override public void actionPerformed(ActionEvent ae) { worker.setCurrentText(pool, text.getText()); new Thread(new Runnable() { @Override public void run() { imgObj.putImage(worker.getImage()); } }).start(); } };
/* */ package nl.infcomtec.jllama; /** * * @author walter */ public class TextImage { public final JFrame frame; public final ImageObject imgObj; private final Modality worker; public TextImage(final ExecutorService pool, String title, Modality grpMod) throws Exception { worker = grpMod; frame = new JFrame(title); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); imgObj = new ImageObject(worker.getImage()); Container cp = frame.getContentPane(); cp.setLayout(new BorderLayout()); final JTextArea text = new JTextArea(60, 5); AbstractAction updateAction = new AbstractAction("Update") { @Override public void actionPerformed(ActionEvent ae) { worker.setCurrentText(pool, text.getText()); new Thread(new Runnable() { @Override public void run() { imgObj.putImage(worker.getImage()); } }).start(); } };
cp.add(new ImageViewer(imgObj).addButton(updateAction).getScalePanPanelTools(), BorderLayout.CENTER);
1
2023-11-16 00:37:47+00:00
8k
jimbro1000/DriveWire4Rebuild
src/main/java/org/thelair/dw4/drivewire/DWCore.java
[ { "identifier": "DWIPort", "path": "src/main/java/org/thelair/dw4/drivewire/ports/DWIPort.java", "snippet": "public interface DWIPort {\n /**\n * Open target port with given definition and register with port handler.\n * @param port definition record\n * @throws InvalidPortTypeDefinition on inval...
import lombok.Getter; import lombok.Setter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import org.thelair.dw4.drivewire.ports.DWIPort; import org.thelair.dw4.drivewire.ports.DWIPortManager; import org.thelair.dw4.drivewire.ports.DWIPortType; import org.thelair.dw4.drivewire.ports.InvalidPortTypeDefinition; import org.thelair.dw4.drivewire.ports.serial.SerialPortDef; import org.thelair.dw4.drivewire.transactions.Transaction; import org.thelair.dw4.drivewire.transactions.TransactionRouter; import org.thelair.dw4.drivewire.transactions.operations.DwInit; import org.thelair.dw4.drivewire.transactions.operations.DwNop; import org.thelair.dw4.drivewire.transactions.operations.DwReset; import org.thelair.dw4.drivewire.transactions.operations.DwTime;
4,925
package org.thelair.dw4.drivewire; /** * Core application to DriveWire. */ @Component public class DWCore implements ApplicationListener<ApplicationReadyEvent> { /** * Log appender. */ private static final Logger LOGGER = LogManager.getLogger(DWCore.class); /** * Enabled features. */ private static final int DW4_FEATURES = 0x00; /** * Default serial baud rate of 2400. */ public static final int DEFAULT_BAUD_RATE = 2400; /** * Default serial data bits. */ public static final int DEFAULT_DATA_BITS = 8; /** * port manager. */ private final DWIPortManager portManager; /** * transaction router. */ private final TransactionRouter router; /** * client version. */ @Getter @Setter private int clientVersion; /** * Create core service. * @param manager port manager */ public DWCore(final DWIPortManager manager) { this.router = new TransactionRouter(); this.portManager = manager; this.clientVersion = -1; LOGGER.info("Initialised core"); } private void populateRouter() { router.registerOperation(Transaction.OP_RESET1, new DwReset()); router.registerOperation(Transaction.OP_RESET2, new DwReset()); router.registerOperation(Transaction.OP_RESET3, new DwReset()); router.registerOperation(Transaction.OP_INIT, new DwInit()); router.registerOperation(Transaction.OP_DWINIT, new DwInit()); router.registerOperation(Transaction.OP_TIME, new DwTime()); router.registerOperation(Transaction.OP_NOP, new DwNop()); } /** * Handle application ready event. * * @param event ready event */ @Override public void onApplicationEvent(final ApplicationReadyEvent event) { populateRouter(); testPorts(); } /** * Report server capability. * @return register of enabled features */ public int reportCapability() { LOGGER.info("Reported server features: " + DW4_FEATURES); return DW4_FEATURES; } private void testPorts() { LOGGER.info("creating port"); final DWIPort serial = portManager.createPortInstance( DWIPortType.DWPortTypeIdentity.SERIAL_PORT ); LOGGER.info("serial port " + serial.toString()); try { serial.openWith( new SerialPortDef(DEFAULT_BAUD_RATE, DEFAULT_DATA_BITS, 1, 0, "com1", 1) ); LOGGER.info("port opened " + serial.getPortDefinition());
package org.thelair.dw4.drivewire; /** * Core application to DriveWire. */ @Component public class DWCore implements ApplicationListener<ApplicationReadyEvent> { /** * Log appender. */ private static final Logger LOGGER = LogManager.getLogger(DWCore.class); /** * Enabled features. */ private static final int DW4_FEATURES = 0x00; /** * Default serial baud rate of 2400. */ public static final int DEFAULT_BAUD_RATE = 2400; /** * Default serial data bits. */ public static final int DEFAULT_DATA_BITS = 8; /** * port manager. */ private final DWIPortManager portManager; /** * transaction router. */ private final TransactionRouter router; /** * client version. */ @Getter @Setter private int clientVersion; /** * Create core service. * @param manager port manager */ public DWCore(final DWIPortManager manager) { this.router = new TransactionRouter(); this.portManager = manager; this.clientVersion = -1; LOGGER.info("Initialised core"); } private void populateRouter() { router.registerOperation(Transaction.OP_RESET1, new DwReset()); router.registerOperation(Transaction.OP_RESET2, new DwReset()); router.registerOperation(Transaction.OP_RESET3, new DwReset()); router.registerOperation(Transaction.OP_INIT, new DwInit()); router.registerOperation(Transaction.OP_DWINIT, new DwInit()); router.registerOperation(Transaction.OP_TIME, new DwTime()); router.registerOperation(Transaction.OP_NOP, new DwNop()); } /** * Handle application ready event. * * @param event ready event */ @Override public void onApplicationEvent(final ApplicationReadyEvent event) { populateRouter(); testPorts(); } /** * Report server capability. * @return register of enabled features */ public int reportCapability() { LOGGER.info("Reported server features: " + DW4_FEATURES); return DW4_FEATURES; } private void testPorts() { LOGGER.info("creating port"); final DWIPort serial = portManager.createPortInstance( DWIPortType.DWPortTypeIdentity.SERIAL_PORT ); LOGGER.info("serial port " + serial.toString()); try { serial.openWith( new SerialPortDef(DEFAULT_BAUD_RATE, DEFAULT_DATA_BITS, 1, 0, "com1", 1) ); LOGGER.info("port opened " + serial.getPortDefinition());
} catch (InvalidPortTypeDefinition ex) {
3
2023-11-18 11:35:16+00:00
8k
sbmatch/miui_regain_runningserice
app/src/main/java/com/ma/bitchgiveitback/app_process/Main.java
[ { "identifier": "MultiJarClassLoader", "path": "app/src/main/java/com/ma/bitchgiveitback/utils/MultiJarClassLoader.java", "snippet": "public class MultiJarClassLoader extends ClassLoader {\n static MultiJarClassLoader multiJarClassLoader;\n List<DexClassLoader> dexClassLoaders = new ArrayList<>();...
import android.annotation.SuppressLint; import android.app.NotificationChannel; import android.os.Binder; import android.os.IBinder; import android.os.IInterface; import android.os.Looper; import android.util.Log; import com.ma.bitchgiveitback.utils.MultiJarClassLoader; import com.ma.bitchgiveitback.utils.Netd; import com.ma.bitchgiveitback.utils.NotificationManager; import com.ma.bitchgiveitback.utils.PackageManager; import com.ma.bitchgiveitback.utils.ServiceManager; import com.ma.bitchgiveitback.utils.ShellUtils; import com.ma.bitchgiveitback.utils.SystemPropertiesUtils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;
6,761
package com.ma.bitchgiveitback.app_process; public class Main { static PackageManager packageManager = ServiceManager.getPackageManager(); static NotificationManager notificationManager = ServiceManager.getNotificationManager(); static MultiJarClassLoader multiJarClassLoader = MultiJarClassLoader.getInstance(); public static void main(String[] args) { if (Looper.getMainLooper() == null) { Looper.prepareMainLooper(); } multiJarClassLoader.addJar("/system/framework/services.jar"); multiJarClassLoader.addJar("/system/system_ext/framework/miui-services.jar"); if (Binder.getCallingUid() == 0 || Binder.getCallingUid() == 1000 || Binder.getCallingUid() == 2000) { if (Binder.getCallingUid() == 2000){ if (packageManager.checkPermission("android.permission.MAINLINE_NETWORK_STACK", packageManager.getNameForUid(Binder.getCallingUid())) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
package com.ma.bitchgiveitback.app_process; public class Main { static PackageManager packageManager = ServiceManager.getPackageManager(); static NotificationManager notificationManager = ServiceManager.getNotificationManager(); static MultiJarClassLoader multiJarClassLoader = MultiJarClassLoader.getInstance(); public static void main(String[] args) { if (Looper.getMainLooper() == null) { Looper.prepareMainLooper(); } multiJarClassLoader.addJar("/system/framework/services.jar"); multiJarClassLoader.addJar("/system/system_ext/framework/miui-services.jar"); if (Binder.getCallingUid() == 0 || Binder.getCallingUid() == 1000 || Binder.getCallingUid() == 2000) { if (Binder.getCallingUid() == 2000){ if (packageManager.checkPermission("android.permission.MAINLINE_NETWORK_STACK", packageManager.getNameForUid(Binder.getCallingUid())) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
ShellUtils.execCommand("pidof cmdutils_server | xargs kill -9", false, false);
5
2023-11-17 09:58:57+00:00
8k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/items/attachments/mags/SmgExpMag.java
[ { "identifier": "Gunscraft", "path": "src/main/java/sheridan/gunscraft/Gunscraft.java", "snippet": "@Mod(\"gunscraft\")\npublic class Gunscraft {\n\n // Directly reference a log4j logger.\n private static final Logger LOGGER = LogManager.getLogger();\n\n public static IProxy proxy = DistExecuto...
import net.minecraft.util.ResourceLocation; import sheridan.gunscraft.Gunscraft; import sheridan.gunscraft.items.attachments.AttachmentRegistry; import sheridan.gunscraft.items.attachments.GenericAttachment; import sheridan.gunscraft.items.attachments.GenericMag; import sheridan.gunscraft.model.attachments.mags.ModelAssaultExpansionMag; import sheridan.gunscraft.model.attachments.mags.smgExpMag.ModelSmgExpMag; import sheridan.gunscraft.tabs.CreativeTabs; import java.util.ArrayList; import java.util.Arrays;
5,547
package sheridan.gunscraft.items.attachments.mags; public class SmgExpMag extends GenericMag { public SmgExpMag() { super(new Properties().group(CreativeTabs.REGULAR_ATTACHMENTS).maxStackSize(1), AttachmentRegistry.getID("smg_expansion_mag"), GenericAttachment.MAG, "smg_expansion_mag", 20); AttachmentRegistry.register(this.id, this); ArrayList<ResourceLocation> textures = new ArrayList<>(Arrays.asList(new ResourceLocation(Gunscraft.MOD_ID, "textures/attachments/mag/smg_exp_mag/smg_exp_mag_mp5.png")));
package sheridan.gunscraft.items.attachments.mags; public class SmgExpMag extends GenericMag { public SmgExpMag() { super(new Properties().group(CreativeTabs.REGULAR_ATTACHMENTS).maxStackSize(1), AttachmentRegistry.getID("smg_expansion_mag"), GenericAttachment.MAG, "smg_expansion_mag", 20); AttachmentRegistry.register(this.id, this); ArrayList<ResourceLocation> textures = new ArrayList<>(Arrays.asList(new ResourceLocation(Gunscraft.MOD_ID, "textures/attachments/mag/smg_exp_mag/smg_exp_mag_mp5.png")));
AttachmentRegistry.registerModel(this.id, new ModelSmgExpMag(textures));
5
2023-11-14 14:00:55+00:00
8k
zpascual/5419-Arm-Example
src/main/java/com/team5419/frc2023/DriverControls.java
[ { "identifier": "Loop", "path": "src/main/java/com/team5419/frc2023/loops/Loop.java", "snippet": "public interface Loop {\n\n public void onStart(double timestamp);\n\n public void onLoop(double timestamp);\n\n public void onStop(double timestamp);\n}" }, { "identifier": "Arm", "pat...
import com.team5419.frc2023.loops.Loop; import com.team5419.frc2023.subsystems.Arm; import com.team5419.frc2023.subsystems.Intake; import com.team5419.frc2023.subsystems.Superstructure; import com.team5419.frc2023.subsystems.Wrist; import com.team5419.lib.io.Xbox; import java.util.Arrays;
5,370
package com.team5419.frc2023; public class DriverControls implements Loop { public static DriverControls mInstance = null; public static DriverControls getInstance() { if (mInstance == null) { mInstance = new DriverControls(); } return mInstance; } Xbox driver, operator; private final Superstructure s = Superstructure.getInstance(); private final SubsystemManager subsystems; public SubsystemManager getSubsystems() {return subsystems;} public DriverControls() { driver = new Xbox(Ports.kDriver); operator = new Xbox(Ports.kOperator); driver.setDeadband(0.0); operator.setDeadband(0.6); Arm arm = Arm.getInstance();
package com.team5419.frc2023; public class DriverControls implements Loop { public static DriverControls mInstance = null; public static DriverControls getInstance() { if (mInstance == null) { mInstance = new DriverControls(); } return mInstance; } Xbox driver, operator; private final Superstructure s = Superstructure.getInstance(); private final SubsystemManager subsystems; public SubsystemManager getSubsystems() {return subsystems;} public DriverControls() { driver = new Xbox(Ports.kDriver); operator = new Xbox(Ports.kOperator); driver.setDeadband(0.0); operator.setDeadband(0.6); Arm arm = Arm.getInstance();
Wrist wrist = Wrist.getInstance();
4
2023-11-14 06:44:40+00:00
8k
Ouest-France/querydsl-postgrest
src/test/java/fr/ouestfrance/querydsl/postgrest/PostgrestRepositoryGetMockTest.java
[ { "identifier": "Page", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/Page.java", "snippet": "public interface Page<T> extends Iterable<T> {\n\n /**\n * Create simple page from items\n *\n * @param items items\n * @param <T> type of items\n * @return one page of...
import fr.ouestfrance.querydsl.postgrest.app.*; import fr.ouestfrance.querydsl.postgrest.model.Page; import fr.ouestfrance.querydsl.postgrest.model.Pageable; import fr.ouestfrance.querydsl.postgrest.model.Sort; import fr.ouestfrance.querydsl.postgrest.model.exceptions.PostgrestRequestException; import fr.ouestfrance.querydsl.postgrest.utils.QueryStringUtils; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMapAdapter; import java.time.LocalDate; import java.util.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.when;
3,905
package fr.ouestfrance.querydsl.postgrest; @Slf4j class PostgrestRepositoryGetMockTest extends AbstractRepositoryMockTest { @Mock private PostgrestWebClient webClient; private PostgrestRepository<Post> repository; @BeforeEach void beforeEach() { repository = new PostRepository(webClient); } @Test void shouldSearchAllPosts() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(null); assertNotNull(search); assertNotNull(search.iterator()); assertEquals(2, search.size()); } private ResponseEntity<List<Object>> ok(List<Object> data) { MultiValueMap<String, String> headers = new MultiValueMapAdapter<>(Map.of("Content-Range", List.of("0-" + data.size() + "/" + data.size()))); return new ResponseEntity<>(data, headers, HttpStatus.OK); } @Test void shouldSearchWithPaginate() { PostRequest request = new PostRequest(); request.setUserId(1); request.setId(1); request.setTitle("Test*"); request.setCodes(List.of("a", "b", "c")); request.setExcludes(List.of("z")); request.setValidDate(LocalDate.of(2023, 11, 10)); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.ofSize(10, Sort.by(Sort.Order.asc("id"), Sort.Order.desc("title").nullsFirst(), Sort.Order.asc("author").nullsLast()))); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue(); log.info("queries {}", queries); assertEquals("eq.1", queries.getFirst("userId")); assertEquals("neq.1", queries.getFirst("id")); assertEquals("lte.2023-11-10", queries.getFirst("startDate")); assertEquals("(endDate.gte.2023-11-10,endDate.is.null)", queries.getFirst("or")); assertEquals("like.Test*", queries.getFirst("title")); assertEquals("id,title.desc.nullsfirst,author.nullslast", queries.getFirst("order")); assertEquals("*,authors(*)", queries.getFirst("select")); assertEquals(2, queries.get("status").size()); // Assert headers captors MultiValueMap<String, String> value = headerArgs.getValue(); assertEquals("0-9", value.getFirst("Range")); assertEquals("items", value.getFirst("Range-Unit")); } @Test void shouldSearchWithoutOrder() { PostRequest request = new PostRequest(); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.ofSize(10)); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue(); log.info("queries {}", queries); assertNull(queries.getFirst("order")); // Assert headers captors MultiValueMap<String, String> value = headerArgs.getValue(); assertEquals("0-9", value.getFirst("Range")); assertEquals("items", value.getFirst("Range-Unit")); } @Test void shouldRaiseExceptionOnMultipleOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); assertThrows(PostgrestRequestException.class, () -> repository.findOne(null)); } @Test void shouldFindOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post())); Optional<Post> one = repository.findOne(null); assertNotNull(one); assertTrue(one.isPresent()); } @Test void shouldFindEmptyOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of()); Optional<Post> one = repository.findOne(null); assertNotNull(one); assertTrue(one.isEmpty()); } @Test void shouldGetOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post())); Post one = repository.getOne(null); assertNotNull(one); } @Test void shouldRaiseExceptionOnEmptyGetOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of()); assertThrows(PostgrestRequestException.class, () -> repository.getOne(null)); } @Test void shouldSearchWithJoin() { PostRequestWithSize request = new PostRequestWithSize(); request.setSize("25"); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.unPaged()); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue();
package fr.ouestfrance.querydsl.postgrest; @Slf4j class PostgrestRepositoryGetMockTest extends AbstractRepositoryMockTest { @Mock private PostgrestWebClient webClient; private PostgrestRepository<Post> repository; @BeforeEach void beforeEach() { repository = new PostRepository(webClient); } @Test void shouldSearchAllPosts() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(null); assertNotNull(search); assertNotNull(search.iterator()); assertEquals(2, search.size()); } private ResponseEntity<List<Object>> ok(List<Object> data) { MultiValueMap<String, String> headers = new MultiValueMapAdapter<>(Map.of("Content-Range", List.of("0-" + data.size() + "/" + data.size()))); return new ResponseEntity<>(data, headers, HttpStatus.OK); } @Test void shouldSearchWithPaginate() { PostRequest request = new PostRequest(); request.setUserId(1); request.setId(1); request.setTitle("Test*"); request.setCodes(List.of("a", "b", "c")); request.setExcludes(List.of("z")); request.setValidDate(LocalDate.of(2023, 11, 10)); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.ofSize(10, Sort.by(Sort.Order.asc("id"), Sort.Order.desc("title").nullsFirst(), Sort.Order.asc("author").nullsLast()))); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue(); log.info("queries {}", queries); assertEquals("eq.1", queries.getFirst("userId")); assertEquals("neq.1", queries.getFirst("id")); assertEquals("lte.2023-11-10", queries.getFirst("startDate")); assertEquals("(endDate.gte.2023-11-10,endDate.is.null)", queries.getFirst("or")); assertEquals("like.Test*", queries.getFirst("title")); assertEquals("id,title.desc.nullsfirst,author.nullslast", queries.getFirst("order")); assertEquals("*,authors(*)", queries.getFirst("select")); assertEquals(2, queries.get("status").size()); // Assert headers captors MultiValueMap<String, String> value = headerArgs.getValue(); assertEquals("0-9", value.getFirst("Range")); assertEquals("items", value.getFirst("Range-Unit")); } @Test void shouldSearchWithoutOrder() { PostRequest request = new PostRequest(); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.ofSize(10)); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue(); log.info("queries {}", queries); assertNull(queries.getFirst("order")); // Assert headers captors MultiValueMap<String, String> value = headerArgs.getValue(); assertEquals("0-9", value.getFirst("Range")); assertEquals("items", value.getFirst("Range-Unit")); } @Test void shouldRaiseExceptionOnMultipleOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); assertThrows(PostgrestRequestException.class, () -> repository.findOne(null)); } @Test void shouldFindOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post())); Optional<Post> one = repository.findOne(null); assertNotNull(one); assertTrue(one.isPresent()); } @Test void shouldFindEmptyOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of()); Optional<Post> one = repository.findOne(null); assertNotNull(one); assertTrue(one.isEmpty()); } @Test void shouldGetOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post())); Post one = repository.getOne(null); assertNotNull(one); } @Test void shouldRaiseExceptionOnEmptyGetOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of()); assertThrows(PostgrestRequestException.class, () -> repository.getOne(null)); } @Test void shouldSearchWithJoin() { PostRequestWithSize request = new PostRequestWithSize(); request.setSize("25"); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.unPaged()); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue();
String queryString = QueryStringUtils.toQueryString(queries);
4
2023-11-14 10:45:54+00:00
8k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/utils/tasks/ExportToStorage.java
[ { "identifier": "APKData", "path": "app/src/main/java/com/threethan/questpatcher/utils/APKData.java", "snippet": "public class APKData {\n\n public static List<String> getData(Context context) {\n List<String> mData = new ArrayList<>();\n for (File mFile : getAPKList(context)) {\n ...
import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; import android.os.Build; import com.threethan.questpatcher.R; import com.threethan.questpatcher.utils.APKData; import com.threethan.questpatcher.utils.Common; import com.threethan.questpatcher.utils.Projects; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import java.io.File; import java.util.List; import in.sunilpaulmathew.sCommon.CommonUtils.sExecutor; import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils;
4,419
package com.threethan.questpatcher.utils.tasks; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on January 28, 2023 */ public class ExportToStorage extends sExecutor { private final Context mContext; private final File mSourceFile; private final List<File> mSourceFiles; private ProgressDialog mProgressDialog; private final String mFolder; private String mExportPath = null; public ExportToStorage(File sourceFile, List<File> sourceFiles, String folder, Context context) { mSourceFile = sourceFile; mSourceFiles = sourceFiles; mFolder = folder; mContext = context; } @SuppressLint("StringFormatInvalid") @Override public void onPreExecute() { mProgressDialog = new ProgressDialog(mContext); mProgressDialog.setMessage(mContext.getString(R.string.exporting, mSourceFile != null && mSourceFile.exists() ? mSourceFile.getName() : "")); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setIcon(R.mipmap.ic_launcher); mProgressDialog.setTitle(R.string.app_name); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.show(); } @Override public void doInBackground() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { sFileUtils.mkdir(new File(Projects.getExportPath(mContext), mFolder));
package com.threethan.questpatcher.utils.tasks; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on January 28, 2023 */ public class ExportToStorage extends sExecutor { private final Context mContext; private final File mSourceFile; private final List<File> mSourceFiles; private ProgressDialog mProgressDialog; private final String mFolder; private String mExportPath = null; public ExportToStorage(File sourceFile, List<File> sourceFiles, String folder, Context context) { mSourceFile = sourceFile; mSourceFiles = sourceFiles; mFolder = folder; mContext = context; } @SuppressLint("StringFormatInvalid") @Override public void onPreExecute() { mProgressDialog = new ProgressDialog(mContext); mProgressDialog.setMessage(mContext.getString(R.string.exporting, mSourceFile != null && mSourceFile.exists() ? mSourceFile.getName() : "")); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setIcon(R.mipmap.ic_launcher); mProgressDialog.setTitle(R.string.app_name); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.show(); } @Override public void doInBackground() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { sFileUtils.mkdir(new File(Projects.getExportPath(mContext), mFolder));
mExportPath = Projects.getExportPath(mContext) + "/" + Common.getAppID();
1
2023-11-18 15:13:30+00:00
8k
jenkinsci/harbor-plugin
src/main/java/io/jenkins/plugins/harbor/client/HarborClientImpl.java
[ { "identifier": "HarborException", "path": "src/main/java/io/jenkins/plugins/harbor/HarborException.java", "snippet": "public class HarborException extends RuntimeException {\n public HarborException(String message) {\n super(message);\n }\n\n public HarborException(String message, Throw...
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import com.damnhandy.uri.template.UriTemplate; import edu.umd.cs.findbugs.annotations.Nullable; import hudson.cli.NoCheckTrustManager; import io.jenkins.plugins.harbor.HarborException; import io.jenkins.plugins.harbor.client.models.Artifact; import io.jenkins.plugins.harbor.client.models.NativeReportSummary; import io.jenkins.plugins.harbor.client.models.Repository; import io.jenkins.plugins.harbor.util.HarborConstants; import io.jenkins.plugins.harbor.util.JsonParser; import io.jenkins.plugins.okhttp.api.JenkinsOkHttpClient; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.*; import okhttp3.logging.HttpLoggingInterceptor;
3,782
package io.jenkins.plugins.harbor.client; public class HarborClientImpl implements HarborClient { private static final int DEFAULT_CONNECT_TIMEOUT_SECONDS = 30; private static final int DEFAULT_READ_TIMEOUT_SECONDS = 30; private static final int DEFAULT_WRITE_TIMEOUT_SECONDS = 30; private static final String API_PING_PATH = "/ping"; private static final String API_LIST_ALL_REPOSITORIES_PATH = "/repositories"; private static final String API_LIST_ARTIFACTS_PATH = "/projects/{project_name}/repositories/{repository_name}/artifacts"; private static final String API_GET_ARTIFACT_PATH = "/projects/{project_name}/repositories/{repository_name}/artifacts/{reference}"; private final String baseUrl; private final OkHttpClient httpClient; public HarborClientImpl( String baseUrl, StandardUsernamePasswordCredentials credentials, boolean isSkipTlsVerify, boolean debugLogging) throws NoSuchAlgorithmException, KeyManagementException { this.baseUrl = baseUrl; // Create Http client OkHttpClient.Builder httpClientBuilder = JenkinsOkHttpClient.newClientBuilder(new OkHttpClient()); addTimeout(httpClientBuilder); skipTlsVerify(httpClientBuilder, isSkipTlsVerify); addAuthenticator(httpClientBuilder, credentials); enableDebugLogging(httpClientBuilder, debugLogging); this.httpClient = httpClientBuilder.build(); } private OkHttpClient.Builder addTimeout(OkHttpClient.Builder httpClient) { httpClient.connectTimeout(DEFAULT_CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.readTimeout(DEFAULT_READ_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.writeTimeout(DEFAULT_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.setRetryOnConnectionFailure$okhttp(true); return httpClient; } @SuppressWarnings("lgtm[jenkins/unsafe-calls]") private OkHttpClient.Builder skipTlsVerify(OkHttpClient.Builder httpClient, boolean isSkipTlsVerify) throws NoSuchAlgorithmException, KeyManagementException { if (isSkipTlsVerify) { SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager[] trustManagers = new TrustManager[] {new NoCheckTrustManager()}; sslContext.init(null, trustManagers, new java.security.SecureRandom()); httpClient.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]); httpClient.setHostnameVerifier$okhttp((hostname, session) -> true); } return httpClient; } private OkHttpClient.Builder addAuthenticator( OkHttpClient.Builder httpClientBuilder, StandardUsernamePasswordCredentials credentials) { if (credentials != null) { HarborInterceptor harborInterceptor = new HarborInterceptor(credentials); httpClientBuilder.addInterceptor(harborInterceptor); } return httpClientBuilder; } private OkHttpClient.Builder enableDebugLogging(OkHttpClient.Builder httpClient, boolean debugLogging) { if (debugLogging) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(loggingInterceptor); } return httpClient; } private String getXAcceptVulnerabilities() { return String.format( "%s, %s", HarborConstants.HarborVulnerabilityReportV11MimeType, HarborConstants.HarborVulnReportv1MimeType); } @Override public NativeReportSummary getVulnerabilitiesAddition(String projectName, String repositoryName, String reference) { return null; } @Override public String getPing() throws IOException { UriTemplate template = UriTemplate.fromTemplate(baseUrl + API_PING_PATH); HttpUrl apiUrl = HttpUrl.parse(template.expand()); if (apiUrl != null) { return httpGet(apiUrl); } throw new HarborException(String.format("httpUrl is null, UriTemplate is %s.", template.expand())); } @Override
package io.jenkins.plugins.harbor.client; public class HarborClientImpl implements HarborClient { private static final int DEFAULT_CONNECT_TIMEOUT_SECONDS = 30; private static final int DEFAULT_READ_TIMEOUT_SECONDS = 30; private static final int DEFAULT_WRITE_TIMEOUT_SECONDS = 30; private static final String API_PING_PATH = "/ping"; private static final String API_LIST_ALL_REPOSITORIES_PATH = "/repositories"; private static final String API_LIST_ARTIFACTS_PATH = "/projects/{project_name}/repositories/{repository_name}/artifacts"; private static final String API_GET_ARTIFACT_PATH = "/projects/{project_name}/repositories/{repository_name}/artifacts/{reference}"; private final String baseUrl; private final OkHttpClient httpClient; public HarborClientImpl( String baseUrl, StandardUsernamePasswordCredentials credentials, boolean isSkipTlsVerify, boolean debugLogging) throws NoSuchAlgorithmException, KeyManagementException { this.baseUrl = baseUrl; // Create Http client OkHttpClient.Builder httpClientBuilder = JenkinsOkHttpClient.newClientBuilder(new OkHttpClient()); addTimeout(httpClientBuilder); skipTlsVerify(httpClientBuilder, isSkipTlsVerify); addAuthenticator(httpClientBuilder, credentials); enableDebugLogging(httpClientBuilder, debugLogging); this.httpClient = httpClientBuilder.build(); } private OkHttpClient.Builder addTimeout(OkHttpClient.Builder httpClient) { httpClient.connectTimeout(DEFAULT_CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.readTimeout(DEFAULT_READ_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.writeTimeout(DEFAULT_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS); httpClient.setRetryOnConnectionFailure$okhttp(true); return httpClient; } @SuppressWarnings("lgtm[jenkins/unsafe-calls]") private OkHttpClient.Builder skipTlsVerify(OkHttpClient.Builder httpClient, boolean isSkipTlsVerify) throws NoSuchAlgorithmException, KeyManagementException { if (isSkipTlsVerify) { SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager[] trustManagers = new TrustManager[] {new NoCheckTrustManager()}; sslContext.init(null, trustManagers, new java.security.SecureRandom()); httpClient.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]); httpClient.setHostnameVerifier$okhttp((hostname, session) -> true); } return httpClient; } private OkHttpClient.Builder addAuthenticator( OkHttpClient.Builder httpClientBuilder, StandardUsernamePasswordCredentials credentials) { if (credentials != null) { HarborInterceptor harborInterceptor = new HarborInterceptor(credentials); httpClientBuilder.addInterceptor(harborInterceptor); } return httpClientBuilder; } private OkHttpClient.Builder enableDebugLogging(OkHttpClient.Builder httpClient, boolean debugLogging) { if (debugLogging) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.addInterceptor(loggingInterceptor); } return httpClient; } private String getXAcceptVulnerabilities() { return String.format( "%s, %s", HarborConstants.HarborVulnerabilityReportV11MimeType, HarborConstants.HarborVulnReportv1MimeType); } @Override public NativeReportSummary getVulnerabilitiesAddition(String projectName, String repositoryName, String reference) { return null; } @Override public String getPing() throws IOException { UriTemplate template = UriTemplate.fromTemplate(baseUrl + API_PING_PATH); HttpUrl apiUrl = HttpUrl.parse(template.expand()); if (apiUrl != null) { return httpGet(apiUrl); } throw new HarborException(String.format("httpUrl is null, UriTemplate is %s.", template.expand())); } @Override
public Repository[] listAllRepositories() throws IOException {
3
2023-11-11 14:54:53+00:00
8k
Mapty231/SpawnFix
src/main/java/me/tye/spawnfix/PlayerJoin.java
[ { "identifier": "Config", "path": "src/main/java/me/tye/spawnfix/utils/Config.java", "snippet": "public enum Config {\n\n default_worldName(String.class),\n default_x(Double.class),\n default_y(Double.class),\n default_z(Double.class),\n default_yaw(Float.class),\n default_pitch(Float.class),\n\n ...
import me.tye.spawnfix.utils.Config; import me.tye.spawnfix.utils.Teleport; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.NamespacedKey; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.persistence.PersistentDataContainer; import org.bukkit.persistence.PersistentDataType; import org.bukkit.scheduler.BukkitTask; import java.util.ArrayList; import java.util.UUID; import java.util.logging.Level; import static me.tye.spawnfix.utils.Util.*;
5,687
package me.tye.spawnfix; public class PlayerJoin implements Listener { private static final ArrayList<UUID> joined = new ArrayList<>(); @EventHandler public static void PlayerSpawn(PlayerJoinEvent e) { Player player = e.getPlayer();
package me.tye.spawnfix; public class PlayerJoin implements Listener { private static final ArrayList<UUID> joined = new ArrayList<>(); @EventHandler public static void PlayerSpawn(PlayerJoinEvent e) { Player player = e.getPlayer();
Config.Occurrence login = Config.login.getOccurrenceConfig();
0
2023-11-13 23:53:25+00:00
8k
mike1226/SpringMVCExample-01
src/main/java/com/example/servingwebcontent/controller/ProvController.java
[ { "identifier": "ProvinceEntity", "path": "src/main/java/com/example/servingwebcontent/entity/ProvinceEntity.java", "snippet": "public class ProvinceEntity {\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.569715+09:00\", comments = \"Source field: pu...
import static org.mybatis.dynamic.sql.SqlBuilder.*; import java.util.List; import java.util.Optional; import org.mybatis.dynamic.sql.render.RenderingStrategies; import org.mybatis.dynamic.sql.select.render.SelectStatementProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.server.ResponseStatusException; import com.example.servingwebcontent.entity.ProvinceEntity; import com.example.servingwebcontent.form.CountrySearchForm; import com.example.servingwebcontent.repository.ProvinceEntityDynamicSqlSupport; import com.example.servingwebcontent.repository.ProvinceEntityMapper; import com.google.gson.Gson;
3,709
package com.example.servingwebcontent.controller; @Controller public class ProvController { @Autowired private ProvinceEntityMapper mapper; @GetMapping("/prov") public String init(CountrySearchForm countrySearchForm) { return "province/prov"; } @GetMapping("/prov/search/{countryId}") @ResponseBody public String search(@PathVariable("countryId") String countryId) { SelectStatementProvider selectStatement = select(ProvinceEntityMapper.selectList) .from(ProvinceEntityDynamicSqlSupport.provinceEntity) .where(ProvinceEntityDynamicSqlSupport.mstcountrycd, isEqualTo(countryId)) .build() .render(RenderingStrategies.MYBATIS3);
package com.example.servingwebcontent.controller; @Controller public class ProvController { @Autowired private ProvinceEntityMapper mapper; @GetMapping("/prov") public String init(CountrySearchForm countrySearchForm) { return "province/prov"; } @GetMapping("/prov/search/{countryId}") @ResponseBody public String search(@PathVariable("countryId") String countryId) { SelectStatementProvider selectStatement = select(ProvinceEntityMapper.selectList) .from(ProvinceEntityDynamicSqlSupport.provinceEntity) .where(ProvinceEntityDynamicSqlSupport.mstcountrycd, isEqualTo(countryId)) .build() .render(RenderingStrategies.MYBATIS3);
List<ProvinceEntity> list = mapper.selectMany(selectStatement);
0
2023-11-12 08:22:27+00:00
8k
wangxianhui111/xuechengzaixian
xuecheng-plus-orders/xuecheng-plus-orders-service/src/main/java/com/xuecheng/orders/service/impl/OrderServiceImpl.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.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.xuecheng.base.exception.XueChengPlusException; import com.xuecheng.base.utils.IdWorkerUtils; import com.xuecheng.base.utils.QRCodeUtil; import com.xuecheng.messagesdk.service.MqMessageService; import com.xuecheng.orders.config.PayNotifyConfig; import com.xuecheng.orders.mapper.XcOrdersGoodsMapper; import com.xuecheng.orders.mapper.XcOrdersMapper; import com.xuecheng.orders.mapper.XcPayRecordMapper; import com.xuecheng.orders.model.dto.AddOrderDto; import com.xuecheng.orders.model.dto.PayRecordDto; import com.xuecheng.orders.model.dto.PayStatusDto; import com.xuecheng.orders.model.po.XcOrders; import com.xuecheng.orders.model.po.XcOrdersGoods; import com.xuecheng.orders.model.po.XcPayRecord; import com.xuecheng.orders.service.OrderService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.time.LocalDateTime; import java.util.List;
5,463
package com.xuecheng.orders.service.impl; /** * 订单接口实现类 * * @author Wuxy * @version 1.0 * @since 2022/10/25 11:42 */ @Slf4j @Service public class OrderServiceImpl implements OrderService { @Autowired XcOrdersMapper ordersMapper; @Autowired XcOrdersGoodsMapper ordersGoodsMapper; @Autowired XcPayRecordMapper payRecordMapper; @Autowired
package com.xuecheng.orders.service.impl; /** * 订单接口实现类 * * @author Wuxy * @version 1.0 * @since 2022/10/25 11:42 */ @Slf4j @Service public class OrderServiceImpl implements OrderService { @Autowired XcOrdersMapper ordersMapper; @Autowired XcOrdersGoodsMapper ordersGoodsMapper; @Autowired XcPayRecordMapper payRecordMapper; @Autowired
MqMessageService mqMessageService;
3
2023-11-13 11:39:35+00:00
8k
KafeinDev/InteractiveNpcs
src/main/java/dev/kafein/interactivenpcs/InteractiveNpcs.java
[ { "identifier": "Command", "path": "src/main/java/dev/kafein/interactivenpcs/command/Command.java", "snippet": "public interface Command {\n CommandProperties getProperties();\n\n String getName();\n\n List<String> getAliases();\n\n boolean isAlias(@NotNull String alias);\n\n String getDe...
import com.google.common.collect.ImmutableSet; import dev.kafein.interactivenpcs.command.Command; import dev.kafein.interactivenpcs.commands.InteractionCommand; import dev.kafein.interactivenpcs.compatibility.Compatibility; import dev.kafein.interactivenpcs.compatibility.CompatibilityFactory; import dev.kafein.interactivenpcs.compatibility.CompatibilityType; import dev.kafein.interactivenpcs.configuration.Config; import dev.kafein.interactivenpcs.configuration.ConfigVariables; import dev.kafein.interactivenpcs.conversation.ConversationManager; import dev.kafein.interactivenpcs.conversation.text.font.CharWidthMap; import dev.kafein.interactivenpcs.plugin.AbstractBukkitPlugin; import dev.kafein.interactivenpcs.tasks.MovementControlTask; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.scheduler.BukkitScheduler; import java.util.Set;
3,654
package dev.kafein.interactivenpcs; public final class InteractiveNpcs extends AbstractBukkitPlugin { private ConversationManager conversationManager; private CharWidthMap charWidthMap; public InteractiveNpcs(Plugin plugin) { super(plugin); } @Override public void onLoad() {} @Override public void onEnable() { this.charWidthMap = new CharWidthMap(this); this.charWidthMap.initialize(); this.conversationManager = new ConversationManager(this); this.conversationManager.initialize(); PluginManager pluginManager = Bukkit.getPluginManager(); for (CompatibilityType compatibilityType : CompatibilityType.values()) { if (!pluginManager.isPluginEnabled(compatibilityType.getPluginName())) { continue; } Compatibility compatibility = CompatibilityFactory.createCompatibility(compatibilityType, this); if (compatibility != null) { compatibility.initialize(); } } } @Override public void onDisable() { } @Override public Set<Command> getCommands() { return ImmutableSet.of( new InteractionCommand(this) ); } @Override public Set<Class<?>> getListeners() { return ImmutableSet.of(); } @Override public void startTasks() { BukkitScheduler scheduler = Bukkit.getScheduler(); scheduler.scheduleSyncRepeatingTask(getPlugin(), new MovementControlTask(this), 0L, 10L); } @Override public void loadConfigs() { Config settingsConfig = getConfigManager().register("settings", getClass(), "/settings.yml", "settings.yml");
package dev.kafein.interactivenpcs; public final class InteractiveNpcs extends AbstractBukkitPlugin { private ConversationManager conversationManager; private CharWidthMap charWidthMap; public InteractiveNpcs(Plugin plugin) { super(plugin); } @Override public void onLoad() {} @Override public void onEnable() { this.charWidthMap = new CharWidthMap(this); this.charWidthMap.initialize(); this.conversationManager = new ConversationManager(this); this.conversationManager.initialize(); PluginManager pluginManager = Bukkit.getPluginManager(); for (CompatibilityType compatibilityType : CompatibilityType.values()) { if (!pluginManager.isPluginEnabled(compatibilityType.getPluginName())) { continue; } Compatibility compatibility = CompatibilityFactory.createCompatibility(compatibilityType, this); if (compatibility != null) { compatibility.initialize(); } } } @Override public void onDisable() { } @Override public Set<Command> getCommands() { return ImmutableSet.of( new InteractionCommand(this) ); } @Override public Set<Class<?>> getListeners() { return ImmutableSet.of(); } @Override public void startTasks() { BukkitScheduler scheduler = Bukkit.getScheduler(); scheduler.scheduleSyncRepeatingTask(getPlugin(), new MovementControlTask(this), 0L, 10L); } @Override public void loadConfigs() { Config settingsConfig = getConfigManager().register("settings", getClass(), "/settings.yml", "settings.yml");
getConfigManager().injectKeys(ConfigVariables.class, settingsConfig);
6
2023-11-18 10:12:16+00:00
8k
jensjeflensje/minecraft_typewriter
src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/BaseTypeWriter.java
[ { "identifier": "TypewriterPlugin", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/TypewriterPlugin.java", "snippet": "public final class TypewriterPlugin extends JavaPlugin {\n\n public static HashMap<Player, TypeWriter> playerWriters;\n\n @Getter\n private static TypewriterPlugin...
import com.destroystokyo.paper.profile.PlayerProfile; import com.destroystokyo.paper.profile.ProfileProperty; import dev.jensderuiter.minecrafttypewriter.TypewriterPlugin; import dev.jensderuiter.minecrafttypewriter.Util; import dev.jensderuiter.minecrafttypewriter.typewriter.component.TypeWriterComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.button.BarTypeWriterButtonComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.button.BaseTypeWriterButtonComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.button.CubeTypeWriterButtonComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.casing.MainTypeWriterCasingComponent; import dev.jensderuiter.minecrafttypewriter.typewriter.component.paper.PaperTypeWriterComponent; import lombok.Getter; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.TextColor; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.UUID;
4,082
package dev.jensderuiter.minecrafttypewriter.typewriter; public abstract class BaseTypeWriter implements TypeWriter { private final int MAX_LINES = 20; protected Location baseLocation; protected Vector playerDirection; protected float playerPitch; protected float playerYaw; protected float oppositeYaw; protected Player player; protected List<String> lines; protected String currentLine; protected List<TypeWriterComponent> components; protected HashMap<String, Vector> keyboardLayout; protected HashMap<String, String> keyboardTextures; protected HashMap<String, BaseTypeWriterButtonComponent> keyboardButtons; @Getter protected PaperTypeWriterComponent paperComponent; public BaseTypeWriter(Player player) { this.player = player; this.playerDirection = this.player.getLocation().getDirection().setY(0); // remove height this.playerPitch = this.player.getLocation().getPitch(); this.playerYaw = this.player.getLocation().getYaw(); this.oppositeYaw = this.playerYaw - 180; this.baseLocation = this.getBaseLocation(); this.components = new ArrayList<>(); this.keyboardLayout = this.getKeyboardLayout(); this.keyboardTextures = this.getKeyboardTextures(); this.keyboardButtons = new HashMap<>(); this.lines = new ArrayList<>(); this.currentLine = ""; TypewriterPlugin.playerWriters.put(player, this); } @Override public void setUp(Location location) { this.keyboardLayout.entrySet().forEach(entry -> { String texture = this.keyboardTextures.get(entry.getKey()); ItemStack skull = this.getSkull(texture); BaseTypeWriterButtonComponent component; if (!entry.getKey().equals(" ")) { component = new CubeTypeWriterButtonComponent(skull); } else {
package dev.jensderuiter.minecrafttypewriter.typewriter; public abstract class BaseTypeWriter implements TypeWriter { private final int MAX_LINES = 20; protected Location baseLocation; protected Vector playerDirection; protected float playerPitch; protected float playerYaw; protected float oppositeYaw; protected Player player; protected List<String> lines; protected String currentLine; protected List<TypeWriterComponent> components; protected HashMap<String, Vector> keyboardLayout; protected HashMap<String, String> keyboardTextures; protected HashMap<String, BaseTypeWriterButtonComponent> keyboardButtons; @Getter protected PaperTypeWriterComponent paperComponent; public BaseTypeWriter(Player player) { this.player = player; this.playerDirection = this.player.getLocation().getDirection().setY(0); // remove height this.playerPitch = this.player.getLocation().getPitch(); this.playerYaw = this.player.getLocation().getYaw(); this.oppositeYaw = this.playerYaw - 180; this.baseLocation = this.getBaseLocation(); this.components = new ArrayList<>(); this.keyboardLayout = this.getKeyboardLayout(); this.keyboardTextures = this.getKeyboardTextures(); this.keyboardButtons = new HashMap<>(); this.lines = new ArrayList<>(); this.currentLine = ""; TypewriterPlugin.playerWriters.put(player, this); } @Override public void setUp(Location location) { this.keyboardLayout.entrySet().forEach(entry -> { String texture = this.keyboardTextures.get(entry.getKey()); ItemStack skull = this.getSkull(texture); BaseTypeWriterButtonComponent component; if (!entry.getKey().equals(" ")) { component = new CubeTypeWriterButtonComponent(skull); } else {
component = new BarTypeWriterButtonComponent(skull, 10);
3
2023-11-18 20:44:30+00:00
8k
ZhiQinIsZhen/dubbo-springboot3
dubbo-api/dubbo-api-user/src/main/java/com/liyz/boot3/api/user/controller/search/investor/CompanyInvestorController.java
[ { "identifier": "CompanyInvestorDTO", "path": "dubbo-api/dubbo-api-user/src/main/java/com/liyz/boot3/api/user/dto/search/investor/CompanyInvestorDTO.java", "snippet": "@Getter\n@Setter\npublic class CompanyInvestorDTO extends PageDTO {\n @Serial\n private static final long serialVersionUID = 45805...
import com.liyz.boot3.api.user.dto.search.investor.CompanyInvestorDTO; import com.liyz.boot3.api.user.vo.search.investor.CompanyInvestorVO; import com.liyz.boot3.common.api.result.PageResult; import com.liyz.boot3.common.api.result.Result; import com.liyz.boot3.common.remote.page.RemotePage; import com.liyz.boot3.common.service.util.BeanUtil; import com.liyz.boot3.security.client.annotation.Anonymous; import com.liyz.boot3.service.search.bo.investor.CompanyInvestorBO; import com.liyz.boot3.service.search.query.PageQuery; import com.liyz.boot3.service.search.remote.investor.RemoteCompanyInvestorService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import org.apache.dubbo.config.annotation.DubboReference; import org.springdoc.core.annotations.ParameterObject; 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;
3,656
package com.liyz.boot3.api.user.controller.search.investor; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2024/1/8 13:48 */ @Tag(name = "投资机构") @RestController @RequestMapping("/search/investor") public class CompanyInvestorController { @DubboReference private RemoteCompanyInvestorService remoteCompanyInvestorService; @Anonymous @Operation(summary = "根据id查询投资机构信息") @GetMapping("/id") public Result<CompanyInvestorVO> getById(@RequestParam("id") String id) {
package com.liyz.boot3.api.user.controller.search.investor; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2024/1/8 13:48 */ @Tag(name = "投资机构") @RestController @RequestMapping("/search/investor") public class CompanyInvestorController { @DubboReference private RemoteCompanyInvestorService remoteCompanyInvestorService; @Anonymous @Operation(summary = "根据id查询投资机构信息") @GetMapping("/id") public Result<CompanyInvestorVO> getById(@RequestParam("id") String id) {
CompanyInvestorBO investorBO = remoteCompanyInvestorService.getById(id);
6
2023-11-13 01:28:21+00:00
8k
glowingstone124/QAPI3
src/main/java/org/qo/ApiApplication.java
[ { "identifier": "Algorithm", "path": "src/main/java/org/qo/Algorithm.java", "snippet": "public class Algorithm {\n public static String token(String player_name, long qq) {\n String charset = \"qazxswedcvfrtgbnhyujmkiolp0129384756_POILKJMNBUYTHGFVCXREWQDSAZ\";\n ArrayList<Integer> remix...
import com.fasterxml.jackson.annotation.JsonProperty; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.catalina.User; import org.jetbrains.annotations.NotNull; import org.json.JSONObject; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; import java.util.*; import static org.qo.Algorithm.*; import static org.qo.UserProcess.*;
6,479
package org.qo; @RestController @SpringBootApplication public class ApiApplication implements ErrorController { public static String status; public static String serverStatus; public static int serverAlive; public static long PackTime; public static String CreativeStatus; Path filePath = Paths.get("app/latest/QCommunity-3.0.3-Setup.exe"); Path webdlPath = Paths.get("webs/download.html"); public static String jdbcUrl = getDatabaseInfo("url"); public static String sqlusername = getDatabaseInfo("username"); public static String sqlpassword = getDatabaseInfo("password"); public static Map<String, Integer> SurvivalMsgList = new HashMap<String, Integer>(); public static Map<String, Integer> CreativeMsgList = new HashMap<String, Integer>(); String jsonData = "data/playermap.json"; public static String noticeData = "data/notice.json"; public ApiApplication() throws IOException { } @RequestMapping("/") public String root() { JSONObject returnObj = new JSONObject(); returnObj.put("code",0); returnObj.put("build", "202312081719"); return returnObj.toString(); } @RequestMapping("/error") public String error(HttpServletRequest request, HttpServletResponse response){ JSONObject returnObj = new JSONObject(); long timeStamp = System.currentTimeMillis(); returnObj.put("timestamp", timeStamp); returnObj.put("error", response.getStatus()); returnObj.put("code", -1); return returnObj.toString(); } @RequestMapping("/introduction") public String introductionMenu() { try { if ((Files.readString(Path.of("forum/introduction/main.json"), StandardCharsets.UTF_8) != null)) { return Files.readString(Path.of("forum/introduction/main.json")); } } catch (IOException e) { return ReturnInterface.failed("ERROR:CONFIGURATION NOT FOUND"); } return ReturnInterface.failed("ERROR"); } @RequestMapping("/introduction/server") public String serverIntros(@RequestParam(name = "articleID", required = true) int articleID) throws Exception { if (articleID == -1) { return Files.readString(Path.of("forum/introduction/server/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/server/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/server/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @PostMapping("/qo/apihook") public String webhook(@RequestBody String data) { System.out.println(data); return null; } @RequestMapping("/introduction/attractions") public String attractionIntros(@RequestParam(name = "articleID", required = true) int articleID) throws Exception{ if (articleID == -1){ return Files.readString(Path.of("forum/introduction/attractions/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/attractions/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/attractions/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @RequestMapping("/introduction/commands") public String commandIntros(@RequestParam(name = "articleID", required = true)int articleID) throws Exception{ if (articleID == -1){ return Files.readString(Path.of("forum/introduction/commands/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/commands/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/commands/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @RequestMapping("/introduction/notice") public String notice(@RequestParam(name = "articleID", required = true)int articleID) throws Exception{ if (articleID == -1){ return Files.readString(Path.of("forum/introduction/notices/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/notices/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/notices/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @GetMapping("/forum/login") public String userLogin(@RequestParam(name="username", required = true)String username, @RequestParam(name = "password", required = true)String password , HttpServletRequest request) {
package org.qo; @RestController @SpringBootApplication public class ApiApplication implements ErrorController { public static String status; public static String serverStatus; public static int serverAlive; public static long PackTime; public static String CreativeStatus; Path filePath = Paths.get("app/latest/QCommunity-3.0.3-Setup.exe"); Path webdlPath = Paths.get("webs/download.html"); public static String jdbcUrl = getDatabaseInfo("url"); public static String sqlusername = getDatabaseInfo("username"); public static String sqlpassword = getDatabaseInfo("password"); public static Map<String, Integer> SurvivalMsgList = new HashMap<String, Integer>(); public static Map<String, Integer> CreativeMsgList = new HashMap<String, Integer>(); String jsonData = "data/playermap.json"; public static String noticeData = "data/notice.json"; public ApiApplication() throws IOException { } @RequestMapping("/") public String root() { JSONObject returnObj = new JSONObject(); returnObj.put("code",0); returnObj.put("build", "202312081719"); return returnObj.toString(); } @RequestMapping("/error") public String error(HttpServletRequest request, HttpServletResponse response){ JSONObject returnObj = new JSONObject(); long timeStamp = System.currentTimeMillis(); returnObj.put("timestamp", timeStamp); returnObj.put("error", response.getStatus()); returnObj.put("code", -1); return returnObj.toString(); } @RequestMapping("/introduction") public String introductionMenu() { try { if ((Files.readString(Path.of("forum/introduction/main.json"), StandardCharsets.UTF_8) != null)) { return Files.readString(Path.of("forum/introduction/main.json")); } } catch (IOException e) { return ReturnInterface.failed("ERROR:CONFIGURATION NOT FOUND"); } return ReturnInterface.failed("ERROR"); } @RequestMapping("/introduction/server") public String serverIntros(@RequestParam(name = "articleID", required = true) int articleID) throws Exception { if (articleID == -1) { return Files.readString(Path.of("forum/introduction/server/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/server/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/server/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @PostMapping("/qo/apihook") public String webhook(@RequestBody String data) { System.out.println(data); return null; } @RequestMapping("/introduction/attractions") public String attractionIntros(@RequestParam(name = "articleID", required = true) int articleID) throws Exception{ if (articleID == -1){ return Files.readString(Path.of("forum/introduction/attractions/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/attractions/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/attractions/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @RequestMapping("/introduction/commands") public String commandIntros(@RequestParam(name = "articleID", required = true)int articleID) throws Exception{ if (articleID == -1){ return Files.readString(Path.of("forum/introduction/commands/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/commands/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/commands/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @RequestMapping("/introduction/notice") public String notice(@RequestParam(name = "articleID", required = true)int articleID) throws Exception{ if (articleID == -1){ return Files.readString(Path.of("forum/introduction/notices/menu.json"), StandardCharsets.UTF_8); } else { String returnFile = Files.readString(Path.of("forum/introduction/notices/" + articleID + ".html")); if (returnFile != null) { return ReturnInterface.success(Files.readString(Path.of("forum/introduction/notices/" + articleID + ".html"))); } return ReturnInterface.failed("NOT FOUND"); } } @GetMapping("/forum/login") public String userLogin(@RequestParam(name="username", required = true)String username, @RequestParam(name = "password", required = true)String password , HttpServletRequest request) {
return UserProcess.userLogin(username,password,request);
1
2023-11-15 13:38:53+00:00
8k
martin-bian/DimpleBlog
dimple-tools/src/main/java/com/dimple/service/impl/PictureServiceImpl.java
[ { "identifier": "Picture", "path": "dimple-tools/src/main/java/com/dimple/domain/Picture.java", "snippet": "@Data\n@Entity\n@Table(name = \"tool_picture\")\npublic class Picture implements Serializable {\n\n @Id\n @Column(name = \"picture_id\")\n @ApiModelProperty(value = \"ID\", hidden = true)...
import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpUtil; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSON; import com.dimple.domain.Picture; import com.dimple.exception.BadRequestException; import com.dimple.repository.PictureRepository; import com.dimple.service.PictureService; import com.dimple.service.dto.PictureQueryCriteria; import com.dimple.utils.Constant; import com.dimple.utils.FileUtil; import com.dimple.utils.PageUtil; import com.dimple.utils.QueryHelp; import com.dimple.utils.TranslatorUtil; import com.dimple.utils.ValidationUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map;
6,560
package com.dimple.service.impl; /** * @className: PictureServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Slf4j @RequiredArgsConstructor @Service(value = "pictureService") public class PictureServiceImpl implements PictureService { private static final String SUCCESS = "success"; private static final String CODE = "code"; private static final String MSG = "message"; private final PictureRepository pictureRepository; @Value("${smms.token}") private String token; @Override public Object queryAll(PictureQueryCriteria criteria, Pageable pageable) { return PageUtil.toPage(pictureRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable)); } @Override public List<Picture> queryAll(PictureQueryCriteria criteria) { return pictureRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)); } @Override @Transactional(rollbackFor = Throwable.class) public Picture upload(MultipartFile multipartFile, String username) { File file = FileUtil.toFile(multipartFile); // 验证是否重复上传 Picture picture = pictureRepository.findByMd5Code(FileUtil.getMd5(file)); if (picture != null) { return picture; } HashMap<String, Object> paramMap = new HashMap<>(1); paramMap.put("smfile", file); // 上传文件 String result = HttpRequest.post(Constant.Url.SM_MS_URL + "/v2/upload") .header("Authorization", token) .form(paramMap) .timeout(20000) .execute().body(); JSONObject jsonObject = JSONUtil.parseObj(result); if (!jsonObject.get(CODE).toString().equals(SUCCESS)) {
package com.dimple.service.impl; /** * @className: PictureServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Slf4j @RequiredArgsConstructor @Service(value = "pictureService") public class PictureServiceImpl implements PictureService { private static final String SUCCESS = "success"; private static final String CODE = "code"; private static final String MSG = "message"; private final PictureRepository pictureRepository; @Value("${smms.token}") private String token; @Override public Object queryAll(PictureQueryCriteria criteria, Pageable pageable) { return PageUtil.toPage(pictureRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable)); } @Override public List<Picture> queryAll(PictureQueryCriteria criteria) { return pictureRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)); } @Override @Transactional(rollbackFor = Throwable.class) public Picture upload(MultipartFile multipartFile, String username) { File file = FileUtil.toFile(multipartFile); // 验证是否重复上传 Picture picture = pictureRepository.findByMd5Code(FileUtil.getMd5(file)); if (picture != null) { return picture; } HashMap<String, Object> paramMap = new HashMap<>(1); paramMap.put("smfile", file); // 上传文件 String result = HttpRequest.post(Constant.Url.SM_MS_URL + "/v2/upload") .header("Authorization", token) .form(paramMap) .timeout(20000) .execute().body(); JSONObject jsonObject = JSONUtil.parseObj(result); if (!jsonObject.get(CODE).toString().equals(SUCCESS)) {
throw new BadRequestException(TranslatorUtil.translate(jsonObject.get(MSG).toString()));
9
2023-11-10 03:30:36+00:00
8k
LazyCoder0101/LazyCoder
service/src/main/java/com/lazycoder/service/service/impl/ModuleServiceImpl.java
[ { "identifier": "ModuleRelatedParam", "path": "database/src/main/java/com/lazycoder/database/common/ModuleRelatedParam.java", "snippet": "@Data\n@AllArgsConstructor\npublic class ModuleRelatedParam {\n\n @JSONField(deserializeUsing = ModuleDeserializer.class)\n private Module module = null;\n\n ...
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.lazycoder.database.common.ModuleRelatedParam; import com.lazycoder.database.dao.ModuleMapper; import com.lazycoder.database.model.Module; import com.lazycoder.database.model.ModuleInfo; import com.lazycoder.database.model.formodule.UsingObject; import com.lazycoder.service.ModuleUseSetting; import com.lazycoder.service.service.SysService; import com.lazycoder.service.vo.AssociatedModule; import com.lazycoder.utils.JsonUtil; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service;
5,436
package com.lazycoder.service.service.impl; @Service @Component(value = "ModuleServiceImpl") public class ModuleServiceImpl implements ModuleUseSetting { @Autowired private ModuleMapper dao;
package com.lazycoder.service.service.impl; @Service @Component(value = "ModuleServiceImpl") public class ModuleServiceImpl implements ModuleUseSetting { @Autowired private ModuleMapper dao;
public void addModule(Module module) {
2
2023-11-16 11:55:06+00:00
8k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/device/HouseMeter.java
[ { "identifier": "DeviceContextBase", "path": "app/src/main/java/kr/or/kashi/hde/DeviceContextBase.java", "snippet": "public abstract class DeviceContextBase implements DeviceStatePollee {\n private static final String TAG = DeviceContextBase.class.getSimpleName();\n private static final boolean DB...
import kr.or.kashi.hde.base.PropertyDef; import kr.or.kashi.hde.DeviceContextBase; import kr.or.kashi.hde.HomeDevice;
6,522
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.device; /** * A device class for probing meters in the house. */ public class HouseMeter extends HomeDevice { private static final String PROP_PREFIX = "hm."; /** * Types of meter */ public @interface MeterType { int UNKNOWN = 0; int WATER = 1; int GAS = 2; int ELECTRICITY = 3; int HOT_WATER = 4; int HEATING = 5; } /** * Units of measurement */ public @interface MeasureUnit { int UNKNOWN = 0; int m3 = 1; int W = 2; int MW = 3; int kWh = 4; } /** * Measure units of meter */ public static class MeterUnits { /** * One of {@link MeasureUnit} for current measurement * @see #getMeterUnits() * @see #getCurrentMeasure() */ public @MeasureUnit int current; /** * One of {@link MeasureUnit} for total measurement * @see #getMeterUnits() * @see #getTotalMeasure() */ public @MeasureUnit int total; } /** Property: Indicating what type of device */ @PropertyDef(valueClass=MeterType.class) public static final String PROP_METER_TYPE = PROP_PREFIX + "meter_type"; /** Property: The enabled state of meter */ @PropertyDef(valueClass=Boolean.class) public static final String PROP_METER_ENABLED = PROP_PREFIX + "meter_enabled"; /** Property: Unit for current measurement */ @PropertyDef(valueClass=MeasureUnit.class) public static final String PROP_CURRENT_METER_UNIT = PROP_PREFIX + "current_meter.unit"; /** Property: Current measurement value*/ @PropertyDef(valueClass=Double.class) public static final String PROP_CURRENT_METER_VALUE = PROP_PREFIX + "current_meter.value"; /** Property: Unit for total measurement */ @PropertyDef(valueClass=MeasureUnit.class) public static final String PROP_TOTAL_METER_UNIT = PROP_PREFIX + "total_meter.unit"; /** Property: Total measurement value */ @PropertyDef(valueClass=Double.class) public static final String PROP_TOTAL_METER_VALUE = PROP_PREFIX + "total_meter.value"; /** * Construct new instance. Don't call this directly. */
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.device; /** * A device class for probing meters in the house. */ public class HouseMeter extends HomeDevice { private static final String PROP_PREFIX = "hm."; /** * Types of meter */ public @interface MeterType { int UNKNOWN = 0; int WATER = 1; int GAS = 2; int ELECTRICITY = 3; int HOT_WATER = 4; int HEATING = 5; } /** * Units of measurement */ public @interface MeasureUnit { int UNKNOWN = 0; int m3 = 1; int W = 2; int MW = 3; int kWh = 4; } /** * Measure units of meter */ public static class MeterUnits { /** * One of {@link MeasureUnit} for current measurement * @see #getMeterUnits() * @see #getCurrentMeasure() */ public @MeasureUnit int current; /** * One of {@link MeasureUnit} for total measurement * @see #getMeterUnits() * @see #getTotalMeasure() */ public @MeasureUnit int total; } /** Property: Indicating what type of device */ @PropertyDef(valueClass=MeterType.class) public static final String PROP_METER_TYPE = PROP_PREFIX + "meter_type"; /** Property: The enabled state of meter */ @PropertyDef(valueClass=Boolean.class) public static final String PROP_METER_ENABLED = PROP_PREFIX + "meter_enabled"; /** Property: Unit for current measurement */ @PropertyDef(valueClass=MeasureUnit.class) public static final String PROP_CURRENT_METER_UNIT = PROP_PREFIX + "current_meter.unit"; /** Property: Current measurement value*/ @PropertyDef(valueClass=Double.class) public static final String PROP_CURRENT_METER_VALUE = PROP_PREFIX + "current_meter.value"; /** Property: Unit for total measurement */ @PropertyDef(valueClass=MeasureUnit.class) public static final String PROP_TOTAL_METER_UNIT = PROP_PREFIX + "total_meter.unit"; /** Property: Total measurement value */ @PropertyDef(valueClass=Double.class) public static final String PROP_TOTAL_METER_VALUE = PROP_PREFIX + "total_meter.value"; /** * Construct new instance. Don't call this directly. */
public HouseMeter(DeviceContextBase deviceContext) {
0
2023-11-10 01:19:44+00:00
8k
Bug1312/dm_locator
src/main/java/com/bug1312/dm_locator/Register.java
[ { "identifier": "LocatorDataWriterItem", "path": "src/main/java/com/bug1312/dm_locator/items/LocatorDataWriterItem.java", "snippet": "public class LocatorDataWriterItem extends Item {\n\n\tprivate static final Predicate<ItemStack> WRITABLE = (stack) -> (\n\t\tstack.getItem() instanceof DataModuleItem &&...
import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import com.bug1312.dm_locator.items.LocatorDataWriterItem; import com.bug1312.dm_locator.items.LocatorDataWriterItem.LocatorDataWriterMode; import com.bug1312.dm_locator.loot_modifiers.FlightPanelLootModifier; import com.bug1312.dm_locator.particle.LocateParticleData; import com.bug1312.dm_locator.tiles.FlightPanelTileEntity; import com.bug1312.dm_locator.triggers.UseLocatorTrigger; import com.bug1312.dm_locator.triggers.WriteModuleTrigger; import com.mojang.serialization.Codec; import com.swdteam.common.init.DMBlocks; import com.swdteam.common.init.DMTabs; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.client.settings.KeyBinding; import net.minecraft.item.Item; import net.minecraft.item.Item.Properties; import net.minecraft.particles.ParticleType; import net.minecraft.tileentity.TileEntityType; import net.minecraft.tileentity.TileEntityType.Builder; import net.minecraft.util.text.KeybindTextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraftforge.common.loot.GlobalLootModifierSerializer; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.IForgeRegistryEntry;
3,668
// Copyright 2023 Bug1312 (bug@bug1312.com) package com.bug1312.dm_locator; public class Register { // Items public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, ModMain.MOD_ID); public static final RegistryObject<Item> WRITER_ITEM = register(ITEMS, "locator_data_writer", () -> new LocatorDataWriterItem(new Properties().tab(DMTabs.DM_TARDIS).stacksTo(1))); public static final RegistryObject<Item> LOCATOR_ATTACHMENT_ITEM = register(ITEMS, "locator_attachment", () -> new Item(new Properties().tab(DMTabs.DM_TARDIS))); // Tiles public static final DeferredRegister<TileEntityType<?>> TILE_ENTITIES = DeferredRegister.create(ForgeRegistries.TILE_ENTITIES, ModMain.MOD_ID);
// Copyright 2023 Bug1312 (bug@bug1312.com) package com.bug1312.dm_locator; public class Register { // Items public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, ModMain.MOD_ID); public static final RegistryObject<Item> WRITER_ITEM = register(ITEMS, "locator_data_writer", () -> new LocatorDataWriterItem(new Properties().tab(DMTabs.DM_TARDIS).stacksTo(1))); public static final RegistryObject<Item> LOCATOR_ATTACHMENT_ITEM = register(ITEMS, "locator_attachment", () -> new Item(new Properties().tab(DMTabs.DM_TARDIS))); // Tiles public static final DeferredRegister<TileEntityType<?>> TILE_ENTITIES = DeferredRegister.create(ForgeRegistries.TILE_ENTITIES, ModMain.MOD_ID);
public static final RegistryObject<TileEntityType<?>> FLIGHT_PANEL_TILE = register(TILE_ENTITIES, "flight_panel", () -> Builder.of(FlightPanelTileEntity::new, DMBlocks.FLIGHT_PANEL.get()).build(null));
4
2023-11-13 03:42:37+00:00
8k
zizai-Shen/young-im
young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-registry/src/main/java/cn/young/im/springboot/starter/adapter/registry/adapter/NacosInstanceRegistryService.java
[ { "identifier": "YoungImException", "path": "young-im-common/src/main/java/cn/young/im/common/exception/YoungImException.java", "snippet": "public class YoungImException extends RuntimeException {\n public YoungImException(String errorMsg) {\n super(errorMsg);\n }\n\n public YoungImExcep...
import cn.young.im.common.exception.YoungImException; import cn.young.im.common.util.IpUtils; import cn.young.im.spi.Join; import cn.young.im.springboot.starter.adapter.registry.InstanceEntity; import cn.young.im.springboot.starter.adapter.registry.InstanceRegistryService; import cn.young.im.springboot.starter.adapter.registry.Status; import cn.young.im.springboot.starter.adapter.registry.annotation.AutomaticRegistry; import cn.young.im.springboot.starter.adapter.registry.config.NacosConfig; import cn.young.im.springboot.starter.adapter.registry.config.RegisterConfig; import cn.young.im.springboot.starter.extension.util.AnnotationScanner; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingFactory; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import static cn.young.im.common.constants.Const.COLONS; import static cn.young.im.common.constants.YoungConst.BASE_PACKAGE; import static cn.young.im.common.constants.YoungConst.DEFAULT;
4,247
package cn.young.im.springboot.starter.adapter.registry.adapter; /** * 作者:沈自在 <a href="https://www.szz.tax">Blog</a> * * @description Nacos 实例注册服务 * @date 2023/12/10 */ @Slf4j @Join public class NacosInstanceRegistryService implements InstanceRegistryService, EnvironmentAware { private ConfigurableEnvironment environment; private NamingService namingService; private String group; @Override public void init(RegisterConfig config) { // 1. 提取配置 NacosConfig nacos = config.getNacos(); this.group = nacos.getGroup(); // 2. 装填配置 Properties properties = new Properties(); properties.put("serverAddr", config.getServerLists()); properties.put("namespace", nacos.getNamespace()); properties.put("username", nacos.getUsername()); properties.put("password", nacos.getPassword()); properties.put("group", group); try { // 3. 实例化 this.namingService = NamingFactory.createNamingService(properties); } catch (NacosException e) { log.error("init nacos registry center occur error"); throw new YoungImException(e); } // 4. 提取注解发起注册 Map<Class<?>, Annotation> classAnnotationMap = AnnotationScanner.scanClassByAnnotation(BASE_PACKAGE, AutomaticRegistry.class); for (Annotation annotation : classAnnotationMap.values()) { AutomaticRegistry registry = (AutomaticRegistry) annotation; String serviceName = registry.serviceName().equals(DEFAULT) ? environment.getProperty("spring.application.name") : registry.serviceName(); String port = registry.port().equals(DEFAULT) ? environment.getProperty("local.server.port") : registry.port();
package cn.young.im.springboot.starter.adapter.registry.adapter; /** * 作者:沈自在 <a href="https://www.szz.tax">Blog</a> * * @description Nacos 实例注册服务 * @date 2023/12/10 */ @Slf4j @Join public class NacosInstanceRegistryService implements InstanceRegistryService, EnvironmentAware { private ConfigurableEnvironment environment; private NamingService namingService; private String group; @Override public void init(RegisterConfig config) { // 1. 提取配置 NacosConfig nacos = config.getNacos(); this.group = nacos.getGroup(); // 2. 装填配置 Properties properties = new Properties(); properties.put("serverAddr", config.getServerLists()); properties.put("namespace", nacos.getNamespace()); properties.put("username", nacos.getUsername()); properties.put("password", nacos.getPassword()); properties.put("group", group); try { // 3. 实例化 this.namingService = NamingFactory.createNamingService(properties); } catch (NacosException e) { log.error("init nacos registry center occur error"); throw new YoungImException(e); } // 4. 提取注解发起注册 Map<Class<?>, Annotation> classAnnotationMap = AnnotationScanner.scanClassByAnnotation(BASE_PACKAGE, AutomaticRegistry.class); for (Annotation annotation : classAnnotationMap.values()) { AutomaticRegistry registry = (AutomaticRegistry) annotation; String serviceName = registry.serviceName().equals(DEFAULT) ? environment.getProperty("spring.application.name") : registry.serviceName(); String port = registry.port().equals(DEFAULT) ? environment.getProperty("local.server.port") : registry.port();
String host = registry.host().equals(DEFAULT) ? IpUtils.getHost() : registry.host();
1
2023-11-10 06:21:17+00:00
8k
erhenjt/twoyi2
app/src/main/java/io/twoyi/ui/SettingsActivity.java
[ { "identifier": "AppKV", "path": "app/src/main/java/io/twoyi/utils/AppKV.java", "snippet": "public class AppKV {\n\n\n private static final String PREF_NAME = \"app_kv\";\n\n public static final String ADD_APP_NOT_SHOW_SYSTEM= \"add_app_not_show_system\";\n public static final String ADD_APP_NO...
import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentResolver; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.provider.DocumentsContract; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.core.util.Pair; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import io.twoyi.R; import io.twoyi.utils.AppKV; import io.twoyi.utils.RomManager; import io.twoyi.utils.UIHelper;
5,963
/* * 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 io.twoyi.ui; /** * @author weishu * @date 2022/1/2. */ public class SettingsActivity extends AppCompatActivity { private static final int REQUEST_GET_FILE = 1000; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); SettingsFragment settingsFragment = new SettingsFragment(); getFragmentManager().beginTransaction() .replace(R.id.settingsFrameLayout, settingsFragment) .commit(); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.colorPrimary)); actionBar.setTitle(R.string.title_settings); } } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } public static class SettingsFragment extends PreferenceFragment { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_settings); } private Preference findPreference(@StringRes int id) { String key = getString(id); return findPreference(key); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Preference importApp = findPreference(R.string.settings_key_import_app); Preference export = findPreference(R.string.settings_key_manage_files); Preference shutdown = findPreference(R.string.settings_key_shutdown); Preference reboot = findPreference(R.string.settings_key_reboot); Preference replaceRom = findPreference(R.string.settings_key_replace_rom); Preference factoryReset = findPreference(R.string.settings_key_factory_reset); Preference about = findPreference(R.string.settings_key_about); importApp.setOnPreferenceClickListener(preference -> {
/* * 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 io.twoyi.ui; /** * @author weishu * @date 2022/1/2. */ public class SettingsActivity extends AppCompatActivity { private static final int REQUEST_GET_FILE = 1000; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); SettingsFragment settingsFragment = new SettingsFragment(); getFragmentManager().beginTransaction() .replace(R.id.settingsFrameLayout, settingsFragment) .commit(); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.colorPrimary)); actionBar.setTitle(R.string.title_settings); } } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } public static class SettingsFragment extends PreferenceFragment { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_settings); } private Preference findPreference(@StringRes int id) { String key = getString(id); return findPreference(key); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Preference importApp = findPreference(R.string.settings_key_import_app); Preference export = findPreference(R.string.settings_key_manage_files); Preference shutdown = findPreference(R.string.settings_key_shutdown); Preference reboot = findPreference(R.string.settings_key_reboot); Preference replaceRom = findPreference(R.string.settings_key_replace_rom); Preference factoryReset = findPreference(R.string.settings_key_factory_reset); Preference about = findPreference(R.string.settings_key_about); importApp.setOnPreferenceClickListener(preference -> {
UIHelper.startActivity(getContext(), SelectAppActivity.class);
2
2023-11-11 22:08:20+00:00
8k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/plugin/Metadata.java
[ { "identifier": "PluginManager", "path": "src/main/java/io/xlorey/FluxLoader/shared/PluginManager.java", "snippet": "@UtilityClass\npublic class PluginManager {\n /**\n * General plugin loader\n */\n private static PluginClassLoader pluginClassLoader;\n\n /**\n * All loaded informat...
import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import io.xlorey.FluxLoader.shared.PluginManager; import io.xlorey.FluxLoader.utils.Logger; import lombok.Data; import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.jar.JarFile; import java.util.zip.ZipEntry;
5,659
package io.xlorey.FluxLoader.plugin; /** * The Metadata class represents plugin data loaded from the metadata.json file. */ @Data public class Metadata { /** * Tool for working with JSON files */ private static final Gson gson = new Gson(); /** * Plugin name */ private String name; /** * Description of the plugin */ private String description; /** * Unique identifier of the plugin */ private String id; /** * Plugin version */ private String version; /** * List of plugin authors */ private List<String> authors; /** * Contact information for the plugin authors */ private List<String> contact; /** * The license under which the plugin is distributed */ private String license; /** * Path to the plugin icon */ private String icon; /** * Plugin entry points for client and server parts */ private Map<String, List<String>> entrypoints; /** * Entry point for rendering controls in the plugin configuration menu */ private String controlsEntrypoint; /** * Plugin dependencies on other projects or libraries */ private Map<String, String> dependencies; /** * Returns a File object representing the configuration directory for this plugin. * The directory path is normalized to prevent problems with various file systems. * @return A File object pointing to the normalized path to the plugin configuration directory. */ public File getConfigFolder() {
package io.xlorey.FluxLoader.plugin; /** * The Metadata class represents plugin data loaded from the metadata.json file. */ @Data public class Metadata { /** * Tool for working with JSON files */ private static final Gson gson = new Gson(); /** * Plugin name */ private String name; /** * Description of the plugin */ private String description; /** * Unique identifier of the plugin */ private String id; /** * Plugin version */ private String version; /** * List of plugin authors */ private List<String> authors; /** * Contact information for the plugin authors */ private List<String> contact; /** * The license under which the plugin is distributed */ private String license; /** * Path to the plugin icon */ private String icon; /** * Plugin entry points for client and server parts */ private Map<String, List<String>> entrypoints; /** * Entry point for rendering controls in the plugin configuration menu */ private String controlsEntrypoint; /** * Plugin dependencies on other projects or libraries */ private Map<String, String> dependencies; /** * Returns a File object representing the configuration directory for this plugin. * The directory path is normalized to prevent problems with various file systems. * @return A File object pointing to the normalized path to the plugin configuration directory. */ public File getConfigFolder() {
File pluginsDirectory = PluginManager.getPluginsDirectory();
0
2023-11-16 09:05:44+00:00
8k
EmonerRobotics/2023Robot
src/main/java/frc/robot/poseestimation/PoseEstimation.java
[ { "identifier": "Constants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class Constants {\n\n public static class LimelightConstants{\n public static double goalHeightInches = 30.31496; //30.31496\n }\n\n public final class LiftMeasurements{\n public static final...
import edu.wpi.first.math.VecBuilder; import edu.wpi.first.math.estimator.SwerveDrivePoseEstimator; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.math.interpolation.TimeInterpolatableBuffer; import edu.wpi.first.math.kinematics.SwerveModulePosition; import edu.wpi.first.networktables.GenericEntry; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.shuffleboard.BuiltInWidgets; import frc.robot.Constants; import frc.robot.Robot; import frc.robot.RobotContainer; import frc.robot.Constants.DriveConstants;
6,709
package frc.robot.poseestimation; public class PoseEstimation { private PhotonVisionBackend photonVision; private SwerveDrivePoseEstimator poseEstimator; private GenericEntry usePhotonVisionEntry = RobotContainer.autoTab.add("Use PhotonVision", true).withWidget(BuiltInWidgets.kToggleButton).getEntry(); private TimeInterpolatableBuffer<Pose2d> poseHistory = TimeInterpolatableBuffer.createBuffer(1.5); private static final double DIFFERENTIATION_TIME = Robot.kDefaultPeriod; public PoseEstimation() { poseEstimator = new SwerveDrivePoseEstimator( DriveConstants.DRIVE_KINEMATICS, RobotContainer.drivetrain.getRotation(), RobotContainer.drivetrain.getModulePositions(), new Pose2d(),
package frc.robot.poseestimation; public class PoseEstimation { private PhotonVisionBackend photonVision; private SwerveDrivePoseEstimator poseEstimator; private GenericEntry usePhotonVisionEntry = RobotContainer.autoTab.add("Use PhotonVision", true).withWidget(BuiltInWidgets.kToggleButton).getEntry(); private TimeInterpolatableBuffer<Pose2d> poseHistory = TimeInterpolatableBuffer.createBuffer(1.5); private static final double DIFFERENTIATION_TIME = Robot.kDefaultPeriod; public PoseEstimation() { poseEstimator = new SwerveDrivePoseEstimator( DriveConstants.DRIVE_KINEMATICS, RobotContainer.drivetrain.getRotation(), RobotContainer.drivetrain.getModulePositions(), new Pose2d(),
Constants.DriveConstants.ODOMETRY_STD_DEV,
0
2023-11-18 14:02:20+00:00
8k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/core/items/types/end/armor/SuperiorHelmet.java
[ { "identifier": "Rarity", "path": "src/main/java/com/sweattypalms/skyblock/core/items/builder/Rarity.java", "snippet": "@Getter\npublic enum Rarity {\n COMMON(\"§f\"),\n UNCOMMON(\"§a\"),\n RARE(\"§9\"),\n EPIC(\"§5\"),\n LEGENDARY(\"§6\"),\n MYTHIC(\"§d\"),\n DIVINE(\"§b\"),\n S...
import com.sweattypalms.skyblock.core.items.builder.Rarity; import com.sweattypalms.skyblock.core.items.builder.SkyblockItem; import com.sweattypalms.skyblock.core.items.builder.SkyblockItemType; import com.sweattypalms.skyblock.core.items.builder.abilities.Ability; import com.sweattypalms.skyblock.core.items.builder.abilities.IHasAbility; import com.sweattypalms.skyblock.core.items.builder.armor.IHeadHelmet; import com.sweattypalms.skyblock.core.player.sub.stats.Stats; import org.bukkit.Material; import java.util.List; import java.util.Map;
5,689
package com.sweattypalms.skyblock.core.items.types.end.armor; public class SuperiorHelmet extends SkyblockItem implements IHasAbility, IHeadHelmet { public static final String ID = "superior_dragon_helmet";
package com.sweattypalms.skyblock.core.items.types.end.armor; public class SuperiorHelmet extends SkyblockItem implements IHasAbility, IHeadHelmet { public static final String ID = "superior_dragon_helmet";
private static final Map<Stats, Double> stats = Map.of(
6
2023-11-15 15:05:58+00:00
8k
microsphere-projects/microsphere-i18n
microsphere-i18n-core/src/main/java/io/microsphere/i18n/spring/context/I18nConfiguration.java
[ { "identifier": "CompositeServiceMessageSource", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/CompositeServiceMessageSource.java", "snippet": "public class CompositeServiceMessageSource extends AbstractServiceMessageSource implements SmartInitializingSingleton {\n\n private final ...
import io.microsphere.i18n.CompositeServiceMessageSource; import io.microsphere.i18n.ServiceMessageSource; import io.microsphere.i18n.constants.I18nConstants; import io.microsphere.i18n.spring.beans.factory.ServiceMessageSourceFactoryBean; import io.microsphere.i18n.util.I18nUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.core.env.Environment; import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver; import java.util.List; import java.util.Locale; import static io.microsphere.i18n.constants.I18nConstants.COMMON_SERVICE_MESSAGE_SOURCE_BEAN_NAME; import static io.microsphere.i18n.constants.I18nConstants.COMMON_SERVICE_MESSAGE_SOURCE_ORDER; import static io.microsphere.i18n.constants.I18nConstants.DEFAULT_ENABLED; import static io.microsphere.i18n.constants.I18nConstants.ENABLED_PROPERTY_NAME; import static io.microsphere.i18n.constants.I18nConstants.SERVICE_MESSAGE_SOURCE_BEAN_NAME;
3,832
package io.microsphere.i18n.spring.context; /** * Internationalization Configuration class * * @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/> * @since 1.0.0 */ public class I18nConfiguration implements DisposableBean { private static final Logger logger = LoggerFactory.getLogger(I18nConfiguration.class); @Autowired @Qualifier(I18nConstants.SERVICE_MESSAGE_SOURCE_BEAN_NAME) public void init(ServiceMessageSource serviceMessageSource) {
package io.microsphere.i18n.spring.context; /** * Internationalization Configuration class * * @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/> * @since 1.0.0 */ public class I18nConfiguration implements DisposableBean { private static final Logger logger = LoggerFactory.getLogger(I18nConfiguration.class); @Autowired @Qualifier(I18nConstants.SERVICE_MESSAGE_SOURCE_BEAN_NAME) public void init(ServiceMessageSource serviceMessageSource) {
I18nUtils.setServiceMessageSource(serviceMessageSource);
4
2023-11-17 11:35:59+00:00
8k
pyzpre/Create-Bicycles-Bitterballen
src/main/java/createbicyclesbitterballen/block/mechanicalfryer/MechanicalFryerEntity.java
[ { "identifier": "RecipeRegistry", "path": "src/main/java/createbicyclesbitterballen/index/RecipeRegistry.java", "snippet": "public enum RecipeRegistry implements IRecipeTypeInfo {\n\n DEEP_FRYING(DeepFryingRecipe::new);\n\n private final ResourceLocation id = new ResourceLocation(\"create_bic_bit\...
import java.util.List; import java.util.Optional; import com.simibubi.create.content.fluids.FluidFX; import com.simibubi.create.content.processing.basin.BasinBlockEntity; import com.simibubi.create.content.processing.basin.BasinOperatingBlockEntity; import com.simibubi.create.content.processing.recipe.ProcessingRecipe; import com.simibubi.create.foundation.blockEntity.behaviour.fluid.SmartFluidTankBehaviour; import com.simibubi.create.foundation.blockEntity.behaviour.fluid.SmartFluidTankBehaviour.TankSegment; import com.simibubi.create.foundation.utility.AnimationTickHolder; import com.simibubi.create.foundation.utility.Couple; import com.simibubi.create.foundation.utility.VecHelper; import createbicyclesbitterballen.index.RecipeRegistry; import createbicyclesbitterballen.index.SoundsRegistry; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction.Axis; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.nbt.CompoundTag; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.util.Mth; import net.minecraft.world.Container; import net.minecraft.world.item.crafting.Recipe; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.items.IItemHandler;
5,412
|| !tanks.getSecond() .isEmpty()) level.playSound(null, worldPosition, SoundEvents.BUBBLE_COLUMN_BUBBLE_POP, SoundSource.BLOCKS, .75f, 1.6f); } } else { processingTicks--; if (processingTicks == 0) { runningTicks++; processingTicks = -1; applyBasinRecipe(); sendData(); } } } if (runningTicks != 20) runningTicks++; } } public void renderParticles() { Optional<BasinBlockEntity> basin = getBasin(); if (!basin.isPresent() || level == null) return; for (SmartFluidTankBehaviour behaviour : basin.get() .getTanks()) { if (behaviour == null) continue; for (TankSegment tankSegment : behaviour.getTanks()) { if (tankSegment.isEmpty(0)) continue; spillParticle(FluidFX.getFluidParticle(tankSegment.getRenderedFluid())); } } } protected void spillParticle(ParticleOptions data) { float angle = level.random.nextFloat() * 360; Vec3 offset = new Vec3(0, 0, 0.25f); offset = VecHelper.rotate(offset, angle, Axis.Y); Vec3 target = VecHelper.rotate(offset, getSpeed() > 0 ? 25 : -25, Axis.Y) .add(0, .25f, 0); Vec3 center = offset.add(VecHelper.getCenterOf(worldPosition)); target = VecHelper.offsetRandomly(target.subtract(offset), level.random, 1 / 128f); level.addParticle(data, center.x, center.y - 1.75f, center.z, target.x, target.y, target.z); } @Override protected List<Recipe<?>> getMatchingRecipes() { List<Recipe<?>> matchingRecipes = super.getMatchingRecipes(); Optional<BasinBlockEntity> basin = getBasin(); if (!basin.isPresent()) return matchingRecipes; BasinBlockEntity basinBlockEntity = basin.get(); if (basin.isEmpty()) return matchingRecipes; IItemHandler availableItems = basinBlockEntity .getCapability(ForgeCapabilities.ITEM_HANDLER) .orElse(null); if (availableItems == null) return matchingRecipes; return matchingRecipes; } @Override protected <C extends Container> boolean matchStaticFilters(Recipe<C> recipe) { return recipe.getType() == RecipeRegistry.DEEP_FRYING.getType(); } @Override public void startProcessingBasin() { if (running && runningTicks <= 20) return; super.startProcessingBasin(); running = true; runningTicks = 0; } @Override public boolean continueWithPreviousRecipe() { runningTicks = 20; return true; } @Override protected void onBasinRemoved() { if (!running) return; runningTicks = 40; running = false; } @Override protected Object getRecipeCacheKey() { return DeepFryingRecipesKey; } @Override protected boolean isRunning() { return running; } @Override @OnlyIn(Dist.CLIENT) public void tickAudio() { super.tickAudio(); boolean slow = Math.abs(getSpeed()) < 65; if (slow && AnimationTickHolder.getTicks() % 2 == 0) return; if (runningTicks == 20)
package createbicyclesbitterballen.block.mechanicalfryer; public class MechanicalFryerEntity extends BasinOperatingBlockEntity { private static final Object DeepFryingRecipesKey = new Object(); public int runningTicks; public int processingTicks; public boolean running; public MechanicalFryerEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) { super(type, pos, state); } public float getRenderedHeadOffset(float partialTicks) { int localTick; float offset = 0; if (running) { if (runningTicks < 20) { localTick = runningTicks; float num = (localTick + partialTicks) / 20f; num = ((2 - Mth.cos((float) (num * Math.PI))) / 2); offset = num - .5f; } else if (runningTicks <= 20) { offset = 1; } else { localTick = 40 - runningTicks; float num = (localTick - partialTicks) / 20f; num = ((2 - Mth.cos((float) (num * Math.PI))) / 2); offset = num - .5f; } } return offset + 7 / 16f; } @Override protected AABB createRenderBoundingBox() { return new AABB(worldPosition).expandTowards(0, -1.5, 0); } @Override protected void read(CompoundTag compound, boolean clientPacket) { running = compound.getBoolean("Running"); runningTicks = compound.getInt("Ticks"); super.read(compound, clientPacket); if (clientPacket && hasLevel()) getBasin().ifPresent(bte -> bte.setAreFluidsMoving(running && runningTicks <= 20)); } @Override public void write(CompoundTag compound, boolean clientPacket) { compound.putBoolean("Running", running); compound.putInt("Ticks", runningTicks); super.write(compound, clientPacket); } @Override public void tick() { super.tick(); if (runningTicks >= 40) { running = false; runningTicks = 0; basinChecker.scheduleUpdate(); return; } float speed = Math.abs(getSpeed()); if (running && level != null) { if (level.isClientSide && runningTicks == 20) renderParticles(); if ((!level.isClientSide || isVirtual()) && runningTicks == 20) { if (processingTicks < 0) { float recipeSpeed = 1; if (currentRecipe instanceof ProcessingRecipe) { int t = ((ProcessingRecipe<?>) currentRecipe).getProcessingDuration(); if (t != 0) recipeSpeed = t / 100f; } processingTicks = Mth.clamp((Mth.log2((int) (512 / speed))) * Mth.ceil(recipeSpeed * 15) + 1, 1, 512); Optional<BasinBlockEntity> basin = getBasin(); if (basin.isPresent()) { Couple<SmartFluidTankBehaviour> tanks = basin.get() .getTanks(); if (!tanks.getFirst() .isEmpty() || !tanks.getSecond() .isEmpty()) level.playSound(null, worldPosition, SoundEvents.BUBBLE_COLUMN_BUBBLE_POP, SoundSource.BLOCKS, .75f, 1.6f); } } else { processingTicks--; if (processingTicks == 0) { runningTicks++; processingTicks = -1; applyBasinRecipe(); sendData(); } } } if (runningTicks != 20) runningTicks++; } } public void renderParticles() { Optional<BasinBlockEntity> basin = getBasin(); if (!basin.isPresent() || level == null) return; for (SmartFluidTankBehaviour behaviour : basin.get() .getTanks()) { if (behaviour == null) continue; for (TankSegment tankSegment : behaviour.getTanks()) { if (tankSegment.isEmpty(0)) continue; spillParticle(FluidFX.getFluidParticle(tankSegment.getRenderedFluid())); } } } protected void spillParticle(ParticleOptions data) { float angle = level.random.nextFloat() * 360; Vec3 offset = new Vec3(0, 0, 0.25f); offset = VecHelper.rotate(offset, angle, Axis.Y); Vec3 target = VecHelper.rotate(offset, getSpeed() > 0 ? 25 : -25, Axis.Y) .add(0, .25f, 0); Vec3 center = offset.add(VecHelper.getCenterOf(worldPosition)); target = VecHelper.offsetRandomly(target.subtract(offset), level.random, 1 / 128f); level.addParticle(data, center.x, center.y - 1.75f, center.z, target.x, target.y, target.z); } @Override protected List<Recipe<?>> getMatchingRecipes() { List<Recipe<?>> matchingRecipes = super.getMatchingRecipes(); Optional<BasinBlockEntity> basin = getBasin(); if (!basin.isPresent()) return matchingRecipes; BasinBlockEntity basinBlockEntity = basin.get(); if (basin.isEmpty()) return matchingRecipes; IItemHandler availableItems = basinBlockEntity .getCapability(ForgeCapabilities.ITEM_HANDLER) .orElse(null); if (availableItems == null) return matchingRecipes; return matchingRecipes; } @Override protected <C extends Container> boolean matchStaticFilters(Recipe<C> recipe) { return recipe.getType() == RecipeRegistry.DEEP_FRYING.getType(); } @Override public void startProcessingBasin() { if (running && runningTicks <= 20) return; super.startProcessingBasin(); running = true; runningTicks = 0; } @Override public boolean continueWithPreviousRecipe() { runningTicks = 20; return true; } @Override protected void onBasinRemoved() { if (!running) return; runningTicks = 40; running = false; } @Override protected Object getRecipeCacheKey() { return DeepFryingRecipesKey; } @Override protected boolean isRunning() { return running; } @Override @OnlyIn(Dist.CLIENT) public void tickAudio() { super.tickAudio(); boolean slow = Math.abs(getSpeed()) < 65; if (slow && AnimationTickHolder.getTicks() % 2 == 0) return; if (runningTicks == 20)
SoundsRegistry.FRYING.playAt(level, worldPosition, .75f, 1, true);
1
2023-11-12 13:05:18+00:00
8k
HanGyeolee/AndroidPdfWriter
android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/components/PDFGridLayout.java
[ { "identifier": "TableCellHaveNotIndexException", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/exceptions/TableCellHaveNotIndexException.java", "snippet": "public class TableCellHaveNotIndexException extends RuntimeException {\n public TableCellHaveNotIndexException() {\n...
import android.graphics.Canvas; import android.graphics.Rect; import com.hangyeolee.androidpdfwriter.exceptions.TableCellHaveNotIndexException; import com.hangyeolee.androidpdfwriter.utils.Border; import java.util.ArrayList; import com.hangyeolee.androidpdfwriter.listener.Action; import com.hangyeolee.androidpdfwriter.utils.Zoomable;
4,682
return this; } public PDFGridLayout setChildMargin(int left, int top, int right, int bottom) { this.childMargin.set( Math.round(left * Zoomable.getInstance().density), Math.round(top * Zoomable.getInstance().density), Math.round(right * Zoomable.getInstance().density), Math.round(bottom * Zoomable.getInstance().density) ); return this; } public PDFGridLayout setChildMargin(int all) { return setChildMargin(all, all, all, all); } public PDFGridLayout setChildMargin(int horizontal, int vertical) { return setChildMargin(horizontal, vertical, horizontal, vertical); } @Override @Deprecated public PDFGridLayout addChild(PDFComponent component) throws TableCellHaveNotIndexException { throw new TableCellHaveNotIndexException(); } /** * 레이아웃에 자식 추가 * @param component 자식 컴포넌트 * @param x x위치, 0부터 * @param y y위치, 0부터 * @return 자기자신 */ public PDFGridLayout addChild(int x, int y, PDFComponent component) throws ArrayIndexOutOfBoundsException{ return addChild(x, y, 1, 1, component); } /** * 레이아웃에 자식 추가 * @param component 자식 컴포넌트 * @param x x위치, 0부터 * @param y y위치, 0부터 * @return 자기자신 */ public PDFGridLayout addChild(int x, int y, int rowSpan, int columnSpan, PDFComponent component) throws ArrayIndexOutOfBoundsException{ int index = y*rows + x; component.setParent(this); if(index < child.size() && (y+columnSpan-1)*rows + x+rowSpan-1 < child.size()) { child.set(index, component); } else { throw new ArrayIndexOutOfBoundsException(); } return setChildSpan(x,y,rowSpan,columnSpan); } @Override public PDFGridLayout setSize(Float width, Float height) { super.setSize(width, height); return this; } @Override public PDFGridLayout setBackgroundColor(int color) { super.setBackgroundColor(color); return this; } @Override public PDFGridLayout setMargin(Rect margin) { super.setMargin(margin); return this; } @Override public PDFGridLayout setMargin(int left, int top, int right, int bottom) { super.setMargin(left, top, right, bottom); return this; } @Override public PDFGridLayout setMargin(int all) { super.setMargin(all); return this; } @Override public PDFGridLayout setMargin(int horizontal, int vertical) { super.setMargin(horizontal, vertical); return this; } @Override public PDFGridLayout setPadding(int all) { super.setPadding(all); return this; } @Override public PDFGridLayout setPadding(int horizontal, int vertical) { super.setPadding(horizontal, vertical); return this; } @Override public PDFGridLayout setPadding(Rect padding) { super.setPadding(padding); return this; } @Override public PDFGridLayout setPadding(int left, int top, int right, int bottom) { super.setPadding(left, top, right, bottom); return this; } @Override
package com.hangyeolee.androidpdfwriter.components; public class PDFGridLayout extends PDFLayout{ int rows, columns; ArrayList<Integer> span; final int[] gaps; final Rect childMargin = new Rect(0,0,0,0); public PDFGridLayout(int rows, int columns){ super(); if(rows < 1) rows = 1; if(columns < 1) columns = 1; this.rows = rows; this.columns = columns; int length = rows*columns; child = new ArrayList<>(length); span = new ArrayList<>(length); gaps = new int[rows]; for(int i = 0; i < length; i++){ child.add(PDFEmpty.build().setParent(this)); span.add(i); } } @Override public void measure(float x, float y) { super.measure(x, y); int i, j; float totalHeight = 0; int gapWidth = 0; int index; int zero_count = 0; int lastWidth = Math.round (measureWidth - border.size.left - padding.left - border.size.right - padding.right); // 가로 길이 자동 조절 for(i = 0; i < gaps.length ; i++) { if(gaps[i] > lastWidth) gaps[i] = 0; lastWidth -= childMargin.left + childMargin.right; if(lastWidth < 0) gaps[i] = 0; if(gaps[i] == 0){ zero_count += 1; }else{ lastWidth -= gaps[i]; } } for(i = 0; i < gaps.length; i++) { if(gaps[i] == 0){ gaps[i] = lastWidth/zero_count; lastWidth -= lastWidth/zero_count; zero_count -= 1; } } int[] maxHeights = new int[columns]; int columnSpanCount; // Cell 당 높이 계산 for(i = 0; i < columns; i++){ int totalWidth = 0; for(j = 0; j < rows; j++){ index = i*rows + j; gapWidth = gaps[j]; if(index == span.get(index)) { columnSpanCount = 1; // 가로 span for(int xx = j+1; xx < rows; xx++){ if(index == span.get(i*rows + xx)){ gapWidth += gaps[xx] + childMargin.left + childMargin.right; }else break; } // 세로 span 개수 for(int yy = i+1; yy < columns; yy++){ if(index == span.get((yy)*rows + j)){ columnSpanCount++; }else break; } child.get(index).width = gapWidth; // 자식 컴포넌트의 Margin 무시 child.get(i).margin.set(childMargin); if(columnSpanCount == 1) { child.get(index).measure(totalWidth, totalHeight); if (maxHeights[i] < child.get(index).measureHeight) { maxHeights[i] = child.get(index).measureHeight; } } totalWidth += gapWidth + childMargin.left + childMargin.right; }else{ index = span.get(index); int origin_x = index % rows; if(origin_x == j) { int origin_y = index / rows; // 가로 span for(int xx = j+1; xx < rows; xx++){ if(index == span.get(origin_y*rows + xx)){ gapWidth += gaps[xx] + childMargin.left + childMargin.right; }else break; } totalWidth += gapWidth + childMargin.left + childMargin.right; } } } totalHeight += maxHeights[i] + childMargin.top + childMargin.bottom; measureHeight = Math.round(totalHeight); } totalHeight = 0; int maxHeight; int maxSpanHeight = 0; float lastTotalHeight = 0; boolean repeatIfor = false; for(i = 0; i < columns; i++) { int totalWidth = 0; maxSpanHeight = 0; // 세로 Span 존재 탐지 for(j = 0; j < rows; j++){ index = i*rows + j; maxHeight = maxHeights[i]; for(int yy = i+1; yy < columns; yy++){ if(index == span.get((yy)*rows + j)){ maxHeight += maxHeights[yy] + childMargin.top + childMargin.bottom; }else break; } if(maxHeight > maxSpanHeight) maxSpanHeight = maxHeight; } // 페이지 넘기는 Grid Cell 이 있는 경우 다음 페이지로 float zoomHeight = Zoomable.getInstance().getZoomHeight(); float lastHeight = totalHeight + measureY; while(lastHeight > zoomHeight){ lastHeight -= zoomHeight; } lastTotalHeight = totalHeight; if(lastHeight < zoomHeight && zoomHeight < lastHeight + maxSpanHeight + childMargin.top + childMargin.bottom){ float gap = zoomHeight - lastHeight; if(i == 0) { margin.top += Math.round(gap); updateHeight(gap); int d = 0; if (parent != null) d += parent.measureY + parent.border.size.top + parent.padding.top; measureY = relativeY + margin.top + d; } else totalHeight += gap; } for(j = 0; j < rows; j++){ index = i*rows + j; gapWidth = gaps[j]; if(index == span.get(index)) { columnSpanCount = 1; //Span 계산 maxHeight = maxHeights[i]; for(int xx = j+1; xx < rows; xx++){ if(index == span.get(i*rows + xx)){ gapWidth += gaps[xx] + childMargin.left + childMargin.right; }else break; } for(int yy = i+1; yy < columns; yy++){ if(index == span.get((yy)*rows + j)){ columnSpanCount++; maxHeight += maxHeights[yy] + childMargin.top + childMargin.bottom; }else break; } child.get(index).width = gapWidth; //measure child.get(index).measure(totalWidth, totalHeight); //Span 이후 span 된 컴포넌트의 높이가 주어진 높이보다 클 경우 if(child.get(index).height > maxHeight){ int gapHeight = child.get(index).height - maxHeight; zero_count = columnSpanCount; for(int yy = i; yy < i+columnSpanCount; yy++) { maxHeights[yy] += gapHeight / zero_count; gapHeight -= gapHeight / zero_count; zero_count -= 1; } repeatIfor = true; break; } child.get(index).force(gapWidth, maxHeight, childMargin); totalWidth += gapWidth + childMargin.left + childMargin.right; }else{ index = span.get(index); int origin_x = index % rows; if(origin_x == j) { int origin_y = index / rows; // 가로 span for(int xx = j+1; xx < rows; xx++){ if(index == span.get(origin_y*rows + xx)){ gapWidth += gaps[xx] + childMargin.left + childMargin.right; }else break; } totalWidth += gapWidth + childMargin.left + childMargin.right; } } } if(repeatIfor){ i--; totalHeight = lastTotalHeight; repeatIfor = false; continue; } totalHeight += maxHeights[i] + childMargin.top + childMargin.bottom; } measureHeight = Math.round(totalHeight + border.size.top + border.size.bottom + padding.top + padding.bottom); } @Override public void draw(Canvas canvas) { super.draw(canvas); for(int i = 0; i < child.size(); i++) { // Span에 의해 늘어난 만큼 관련 없는 부분은 draw 하지 않는 다. if(i == span.get(i)) { child.get(i).draw(canvas); } } } /** * 자식 컴포넌트가 차지하는 가로 길이 설정 * @param xIndex 설정할 Row * @param width 가로 길이 * @return 자기자신 */ public PDFGridLayout setChildWidth(int xIndex, int width){ if(width < 0) width = 0; if(xIndex < gaps.length) gaps[xIndex] = Math.round(width * Zoomable.getInstance().density); return this; } public PDFGridLayout setChildSpan(int x, int y, int rowSpan, int columnSpan) throws ArrayIndexOutOfBoundsException{ int index = y*rows + x; if(index < child.size() && (y+columnSpan-1)*rows + x+rowSpan-1 < child.size()) { int spanIdx; for(int i = 0; i < columnSpan; i++){ for(int j = 0; j < rowSpan; j++){ spanIdx = (y+i)*rows + x+j; span.set(spanIdx, index); } } } else { throw new ArrayIndexOutOfBoundsException("Span Size is Out of Bounds"); } return this; } public PDFGridLayout setChildMargin(Rect margin) { this.childMargin.set(new Rect( Math.round(margin.left * Zoomable.getInstance().density), Math.round(margin.top * Zoomable.getInstance().density), Math.round(margin.right * Zoomable.getInstance().density), Math.round(margin.bottom * Zoomable.getInstance().density)) ); return this; } public PDFGridLayout setChildMargin(int left, int top, int right, int bottom) { this.childMargin.set( Math.round(left * Zoomable.getInstance().density), Math.round(top * Zoomable.getInstance().density), Math.round(right * Zoomable.getInstance().density), Math.round(bottom * Zoomable.getInstance().density) ); return this; } public PDFGridLayout setChildMargin(int all) { return setChildMargin(all, all, all, all); } public PDFGridLayout setChildMargin(int horizontal, int vertical) { return setChildMargin(horizontal, vertical, horizontal, vertical); } @Override @Deprecated public PDFGridLayout addChild(PDFComponent component) throws TableCellHaveNotIndexException { throw new TableCellHaveNotIndexException(); } /** * 레이아웃에 자식 추가 * @param component 자식 컴포넌트 * @param x x위치, 0부터 * @param y y위치, 0부터 * @return 자기자신 */ public PDFGridLayout addChild(int x, int y, PDFComponent component) throws ArrayIndexOutOfBoundsException{ return addChild(x, y, 1, 1, component); } /** * 레이아웃에 자식 추가 * @param component 자식 컴포넌트 * @param x x위치, 0부터 * @param y y위치, 0부터 * @return 자기자신 */ public PDFGridLayout addChild(int x, int y, int rowSpan, int columnSpan, PDFComponent component) throws ArrayIndexOutOfBoundsException{ int index = y*rows + x; component.setParent(this); if(index < child.size() && (y+columnSpan-1)*rows + x+rowSpan-1 < child.size()) { child.set(index, component); } else { throw new ArrayIndexOutOfBoundsException(); } return setChildSpan(x,y,rowSpan,columnSpan); } @Override public PDFGridLayout setSize(Float width, Float height) { super.setSize(width, height); return this; } @Override public PDFGridLayout setBackgroundColor(int color) { super.setBackgroundColor(color); return this; } @Override public PDFGridLayout setMargin(Rect margin) { super.setMargin(margin); return this; } @Override public PDFGridLayout setMargin(int left, int top, int right, int bottom) { super.setMargin(left, top, right, bottom); return this; } @Override public PDFGridLayout setMargin(int all) { super.setMargin(all); return this; } @Override public PDFGridLayout setMargin(int horizontal, int vertical) { super.setMargin(horizontal, vertical); return this; } @Override public PDFGridLayout setPadding(int all) { super.setPadding(all); return this; } @Override public PDFGridLayout setPadding(int horizontal, int vertical) { super.setPadding(horizontal, vertical); return this; } @Override public PDFGridLayout setPadding(Rect padding) { super.setPadding(padding); return this; } @Override public PDFGridLayout setPadding(int left, int top, int right, int bottom) { super.setPadding(left, top, right, bottom); return this; } @Override
public PDFGridLayout setBorder(Action<Border, Border> action) {
1
2023-11-15 08:05:28+00:00
8k
cometcake575/Origins-Reborn
src/main/java/com/starshootercity/abilities/NetherSpawn.java
[ { "identifier": "OriginSwapper", "path": "src/main/java/com/starshootercity/OriginSwapper.java", "snippet": "public class OriginSwapper implements Listener {\n private final static NamespacedKey displayKey = new NamespacedKey(OriginsReborn.getInstance(), \"display-item\");\n private final static N...
import com.starshootercity.OriginSwapper; import com.starshootercity.OriginsReborn; import net.kyori.adventure.key.Key; import org.bukkit.Bukkit; import org.bukkit.World; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List;
7,191
package com.starshootercity.abilities; public class NetherSpawn implements DefaultSpawnAbility, VisibleAbility { @Override public @NotNull Key getKey() { return Key.key("origins:nether_spawn"); } @Override public @Nullable World getWorld() {
package com.starshootercity.abilities; public class NetherSpawn implements DefaultSpawnAbility, VisibleAbility { @Override public @NotNull Key getKey() { return Key.key("origins:nether_spawn"); } @Override public @Nullable World getWorld() {
String nether = OriginsReborn.getInstance().getConfig().getString("worlds.world_nether");
1
2023-11-10 21:39:16+00:00
8k
SoBadFish/Report
src/main/java/org/sobadfish/report/command/ReportCommand.java
[ { "identifier": "ReportMainClass", "path": "src/main/java/org/sobadfish/report/ReportMainClass.java", "snippet": "public class ReportMainClass extends PluginBase {\n\n private static IDataManager dataManager;\n\n private static ReportMainClass mainClass;\n\n private ReportConfig reportConfig;\n...
import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.command.Command; import cn.nukkit.command.CommandSender; import org.sobadfish.report.ReportMainClass; import org.sobadfish.report.form.DisplayCustomForm; import org.sobadfish.report.form.DisplayForm; import org.sobadfish.report.form.DisplayHistoryForm; import java.util.List;
4,542
package org.sobadfish.report.command; /** * @author SoBadFish * 2022/1/21 */ public class ReportCommand extends Command { public ReportCommand(String name) { super(name); } @Override public boolean execute(CommandSender commandSender, String s, String[] strings) { if(strings.length == 0) { if (commandSender instanceof Player) { DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid()); displayCustomForm.disPlay((Player) commandSender,null); }else{ ReportMainClass.sendMessageToObject("&c请不要在控制台执行", commandSender); } return true; } String cmd = strings[0]; if("r".equalsIgnoreCase(cmd)){ if(strings.length > 1){ DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid()); displayCustomForm.disPlay((Player) commandSender,strings[1]); return true; } } if(commandSender.isOp() || ReportMainClass.getMainClass().getAdminPlayers().contains(commandSender.getName())){ switch (cmd){ case "a": if(commandSender instanceof Player){ DisplayForm displayFrom = new DisplayForm(DisplayForm.getRid()); displayFrom.disPlay((Player) commandSender); }else{ ReportMainClass.sendMessageToObject("&c请不要在控制台执行", commandSender); } break; case "p": if(commandSender.isOp()){ if(strings.length > 1){ String player = strings[1]; Player online = Server.getInstance().getPlayer(player); if(online != null){ player = online.getName(); } List<String> players = ReportMainClass.getMainClass().getAdminPlayers(); if(players.contains(player)){ players.remove(player); if(online != null){ ReportMainClass.sendMessageToObject("&c你已不是协管!",online); } ReportMainClass.sendMessageToObject("&a成功取消玩家 "+player+" 的协管身份", commandSender); ReportMainClass.getMainClass().saveAdminPlayers(); }else{ players.add(player); ReportMainClass.getMainClass().saveAdminPlayers(); if(online != null){ ReportMainClass.sendMessageToObject("&a你已成为协管!",online); ReportMainClass.sendMessageToObject("&a成功增加玩家 "+player+" 的协管身份", commandSender); } } } } break; case "m": if(strings.length > 2){ String player = strings[1]; String msg = strings[2]; Player online = Server.getInstance().getPlayer(player); if(online != null){ ReportMainClass.sendMessageToObject("&c您已被警告!&7 (&r"+msg+"&r&7)",online); } } break; case "h": if(commandSender instanceof Player){ String player = null; if(strings.length > 1){ player = strings[1]; }
package org.sobadfish.report.command; /** * @author SoBadFish * 2022/1/21 */ public class ReportCommand extends Command { public ReportCommand(String name) { super(name); } @Override public boolean execute(CommandSender commandSender, String s, String[] strings) { if(strings.length == 0) { if (commandSender instanceof Player) { DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid()); displayCustomForm.disPlay((Player) commandSender,null); }else{ ReportMainClass.sendMessageToObject("&c请不要在控制台执行", commandSender); } return true; } String cmd = strings[0]; if("r".equalsIgnoreCase(cmd)){ if(strings.length > 1){ DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid()); displayCustomForm.disPlay((Player) commandSender,strings[1]); return true; } } if(commandSender.isOp() || ReportMainClass.getMainClass().getAdminPlayers().contains(commandSender.getName())){ switch (cmd){ case "a": if(commandSender instanceof Player){ DisplayForm displayFrom = new DisplayForm(DisplayForm.getRid()); displayFrom.disPlay((Player) commandSender); }else{ ReportMainClass.sendMessageToObject("&c请不要在控制台执行", commandSender); } break; case "p": if(commandSender.isOp()){ if(strings.length > 1){ String player = strings[1]; Player online = Server.getInstance().getPlayer(player); if(online != null){ player = online.getName(); } List<String> players = ReportMainClass.getMainClass().getAdminPlayers(); if(players.contains(player)){ players.remove(player); if(online != null){ ReportMainClass.sendMessageToObject("&c你已不是协管!",online); } ReportMainClass.sendMessageToObject("&a成功取消玩家 "+player+" 的协管身份", commandSender); ReportMainClass.getMainClass().saveAdminPlayers(); }else{ players.add(player); ReportMainClass.getMainClass().saveAdminPlayers(); if(online != null){ ReportMainClass.sendMessageToObject("&a你已成为协管!",online); ReportMainClass.sendMessageToObject("&a成功增加玩家 "+player+" 的协管身份", commandSender); } } } } break; case "m": if(strings.length > 2){ String player = strings[1]; String msg = strings[2]; Player online = Server.getInstance().getPlayer(player); if(online != null){ ReportMainClass.sendMessageToObject("&c您已被警告!&7 (&r"+msg+"&r&7)",online); } } break; case "h": if(commandSender instanceof Player){ String player = null; if(strings.length > 1){ player = strings[1]; }
DisplayHistoryForm displayHistoryForm = new DisplayHistoryForm(DisplayHistoryForm.getRid());
3
2023-11-15 03:08:23+00:00
8k
toxicity188/InventoryAPI
plugin/src/main/java/kor/toxicity/inventory/InventoryAPIImpl.java
[ { "identifier": "InventoryAPI", "path": "api/src/main/java/kor/toxicity/inventory/api/InventoryAPI.java", "snippet": "@SuppressWarnings(\"unused\")\npublic abstract class InventoryAPI extends JavaPlugin {\n private static InventoryAPI api;\n\n private ImageManager imageManager;\n private FontMa...
import kor.toxicity.inventory.api.InventoryAPI; import kor.toxicity.inventory.api.event.PluginReloadEndEvent; import kor.toxicity.inventory.api.event.PluginReloadStartEvent; import kor.toxicity.inventory.api.gui.*; import kor.toxicity.inventory.api.manager.InventoryManager; import kor.toxicity.inventory.manager.FontManagerImpl; import kor.toxicity.inventory.manager.ImageManagerImpl; import kor.toxicity.inventory.manager.ResourcePackManagerImpl; import kor.toxicity.inventory.util.AdventureUtil; import kor.toxicity.inventory.util.PluginUtil; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextColor; import net.kyori.adventure.text.format.TextDecoration; import net.kyori.adventure.text.minimessage.Context; import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.tag.Tag; import net.kyori.adventure.text.minimessage.tag.resolver.ArgumentQueue; import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.*; import java.util.List; import java.util.jar.JarFile;
4,353
package kor.toxicity.inventory; @SuppressWarnings("unused") public final class InventoryAPIImpl extends InventoryAPI { private static final Tag NONE_TAG = Tag.selfClosingInserting(Component.text("")); private static final Tag ERROR_TAG = Tag.selfClosingInserting(Component.text("error!")); private static final MiniMessage MINI_MESSAGE = MiniMessage.builder() .tags(TagResolver.builder() .resolvers( TagResolver.standard(), TagResolver.resolver("space", (ArgumentQueue argumentQueue, Context context) -> { if (argumentQueue.hasNext()) { var next = argumentQueue.pop().value(); try { return Tag.selfClosingInserting(AdventureUtil.getSpaceFont(Integer.parseInt(next))); } catch (Exception e) { return ERROR_TAG; } } else return NONE_TAG; }) ) .build() ) .postProcessor(c -> { var style = c.style(); if (style.color() == null) style = style.color(NamedTextColor.WHITE); var deco = style.decorations(); var newDeco = new EnumMap<TextDecoration, TextDecoration.State>(TextDecoration.class); for (TextDecoration value : TextDecoration.values()) { var get = deco.get(value); if (get == null || get == TextDecoration.State.NOT_SET) { newDeco.put(value, TextDecoration.State.FALSE); } else newDeco.put(value, get); } style = style.decorations(newDeco); return c.style(style); }) .build(); private GuiFont font; private final List<InventoryManager> managers = new ArrayList<>(); private static final ItemStack AIR = new ItemStack(Material.AIR); @Override public void onEnable() { var pluginManager = Bukkit.getPluginManager();
package kor.toxicity.inventory; @SuppressWarnings("unused") public final class InventoryAPIImpl extends InventoryAPI { private static final Tag NONE_TAG = Tag.selfClosingInserting(Component.text("")); private static final Tag ERROR_TAG = Tag.selfClosingInserting(Component.text("error!")); private static final MiniMessage MINI_MESSAGE = MiniMessage.builder() .tags(TagResolver.builder() .resolvers( TagResolver.standard(), TagResolver.resolver("space", (ArgumentQueue argumentQueue, Context context) -> { if (argumentQueue.hasNext()) { var next = argumentQueue.pop().value(); try { return Tag.selfClosingInserting(AdventureUtil.getSpaceFont(Integer.parseInt(next))); } catch (Exception e) { return ERROR_TAG; } } else return NONE_TAG; }) ) .build() ) .postProcessor(c -> { var style = c.style(); if (style.color() == null) style = style.color(NamedTextColor.WHITE); var deco = style.decorations(); var newDeco = new EnumMap<TextDecoration, TextDecoration.State>(TextDecoration.class); for (TextDecoration value : TextDecoration.values()) { var get = deco.get(value); if (get == null || get == TextDecoration.State.NOT_SET) { newDeco.put(value, TextDecoration.State.FALSE); } else newDeco.put(value, get); } style = style.decorations(newDeco); return c.style(style); }) .build(); private GuiFont font; private final List<InventoryManager> managers = new ArrayList<>(); private static final ItemStack AIR = new ItemStack(Material.AIR); @Override public void onEnable() { var pluginManager = Bukkit.getPluginManager();
var fontManager = new FontManagerImpl();
4
2023-11-13 00:19:46+00:00
8k