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
lk-eternal/AI-Assistant-Plus
src/main/java/lk/eternal/ai/controller/LKController.java
[ { "identifier": "User", "path": "src/main/java/lk/eternal/ai/domain/User.java", "snippet": "public class User {\n\n private final String id;\n private final LinkedList<Message> messages;\n private final Map<String, Object> properties;\n private Status status;\n\n public User(String id) {\...
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import lk.eternal.ai.domain.User; import lk.eternal.ai.dto.req.QuestionReq; import lk.eternal.ai.dto.req.Message; import lk.eternal.ai.dto.resp.PluginResp; import lk.eternal.ai.exception.ApiUnauthorizedException; import lk.eternal.ai.exception.ApiValidationException; import lk.eternal.ai.model.ai.AiModel; import lk.eternal.ai.model.ai.ChatGPTAiModel; import lk.eternal.ai.model.ai.GeminiAiModel; import lk.eternal.ai.model.ai.TongYiQianWenAiModel; import lk.eternal.ai.model.plugin.*; import lk.eternal.ai.plugin.*; import lk.eternal.ai.util.Assert; import lk.eternal.ai.util.Mapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.net.ProxySelector; import java.util.*; import java.util.concurrent.*;
4,658
package lk.eternal.ai.controller; @RestController @RequestMapping("/api") public class LKController { private static final Logger LOGGER = LoggerFactory.getLogger(LKController.class); private final Map<String, User> userMap = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, ScheduledFuture<?>> autoRemoveUserMap = new ConcurrentHashMap<>(); private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); private final Map<String, Plugin> pluginsMap = new HashMap<>(); private final Map<String, PluginModel> pluginModelMap = new HashMap<>();
package lk.eternal.ai.controller; @RestController @RequestMapping("/api") public class LKController { private static final Logger LOGGER = LoggerFactory.getLogger(LKController.class); private final Map<String, User> userMap = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, ScheduledFuture<?>> autoRemoveUserMap = new ConcurrentHashMap<>(); private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); private final Map<String, Plugin> pluginsMap = new HashMap<>(); private final Map<String, PluginModel> pluginModelMap = new HashMap<>();
private final Map<String, AiModel> aiModelMap = new HashMap<>();
4
2023-11-23 01:12:34+00:00
8k
Neelesh-Janga/23-Java-Design-Patterns
src/com/neelesh/design/patterns/creational/builder/BuilderTest.java
[ { "identifier": "MobileBuilder", "path": "src/com/neelesh/design/patterns/creational/builder/builders/MobileBuilder.java", "snippet": "public class MobileBuilder implements Builder {\n private Battery battery;\n private Camera camera;\n private Display display;\n private Network network;\n\n...
import com.neelesh.design.patterns.creational.builder.builders.MobileBuilder; import com.neelesh.design.patterns.creational.builder.components.Battery; import com.neelesh.design.patterns.creational.builder.components.Camera; import com.neelesh.design.patterns.creational.builder.components.Display; import com.neelesh.design.patterns.creational.builder.components.Network; import com.neelesh.design.patterns.creational.builder.components.enums.BatteryHealth; import com.neelesh.design.patterns.creational.builder.components.enums.BatteryTechnology; import com.neelesh.design.patterns.creational.builder.components.enums.DisplayType; import com.neelesh.design.patterns.creational.builder.components.enums.NetworkTechnology; import com.neelesh.design.patterns.creational.builder.products.Mobile; import java.util.UUID;
3,639
package com.neelesh.design.patterns.creational.builder; public class BuilderTest { public static void main(String[] args) { Mobile oneplus = buildMobile(); oneplus.setColor("Glossy Black"); oneplus.setWaterResistant(false); oneplus.setHasScreenProtection(false); System.out.println("*** Mobile: OnePlus ***"); System.out.println("Color = " + oneplus.getColor()); System.out.println("Water Resistant = " + oneplus.isWaterResistant()); System.out.println("Screen Protection = " + oneplus.hasScreenProtection()); System.out.println("Battery = " + oneplus.getBattery()); System.out.println("Network = " + oneplus.getNetwork()); System.out.println("Camera = " + oneplus.getCamera()); System.out.println("Display = " + oneplus.getDisplay()); } public static Mobile buildMobile(){
package com.neelesh.design.patterns.creational.builder; public class BuilderTest { public static void main(String[] args) { Mobile oneplus = buildMobile(); oneplus.setColor("Glossy Black"); oneplus.setWaterResistant(false); oneplus.setHasScreenProtection(false); System.out.println("*** Mobile: OnePlus ***"); System.out.println("Color = " + oneplus.getColor()); System.out.println("Water Resistant = " + oneplus.isWaterResistant()); System.out.println("Screen Protection = " + oneplus.hasScreenProtection()); System.out.println("Battery = " + oneplus.getBattery()); System.out.println("Network = " + oneplus.getNetwork()); System.out.println("Camera = " + oneplus.getCamera()); System.out.println("Display = " + oneplus.getDisplay()); } public static Mobile buildMobile(){
MobileBuilder builder = new MobileBuilder();
0
2023-11-22 10:19:01+00:00
8k
angga7togk/LuckyCrates-PNX
src/main/java/angga7togk/luckycrates/menu/ChestMenu.java
[ { "identifier": "LuckyCrates", "path": "src/main/java/angga7togk/luckycrates/LuckyCrates.java", "snippet": "public class LuckyCrates extends PluginBase {\r\n\r\n @Getter\r\n private static LuckyCrates instance;\r\n public static Config crates, pos;\r\n public static int offsetIdEntity = 1;\r...
import angga7togk.luckycrates.LuckyCrates; import angga7togk.luckycrates.crates.Keys; import angga7togk.luckycrates.language.Languages; import angga7togk.luckycrates.task.InstantTask; import angga7togk.luckycrates.task.RouletteTask; import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.inventory.Inventory; import cn.nukkit.inventory.InventoryType; import cn.nukkit.item.Item; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.plugin.Plugin; import cn.nukkit.utils.ConfigSection; import cn.nukkit.utils.TextFormat; import me.iwareq.fakeinventories.FakeInventory; import java.util.ArrayList; import java.util.List; import java.util.Map;
6,645
package angga7togk.luckycrates.menu; public class ChestMenu { private final Map<String, String> lang; public ChestMenu() { this.lang = new Languages().getLanguage(); } public void mainMenu(Player player, String crateName) { LuckyCrates.crates.reload(); FakeInventory inv = new FakeInventory(InventoryType.DOUBLE_CHEST, TextFormat.BOLD + crateName); if (!LuckyCrates.crates.exists(crateName)) { player.sendMessage(LuckyCrates.prefix + lang.get("crate-notfound")); return; } ConfigSection crateSect = LuckyCrates.crates.getSection(crateName); List<Map<String, Object>> dropsList = crateSect.getList("drops"); int i = 0; for (Map<String, Object> drop : dropsList) { int id = (int) drop.get("id"); int meta = (int) drop.get("meta"); int amount = (int) drop.get("amount"); int chance = (int) drop.get("chance"); String customName = drop.containsKey("name") ? (String) drop.get("name") : null; String lore = drop.containsKey("lore") ? (String) drop.get("lore") : null; Item item = new Item(id, meta, amount); if (customName != null) { item.setCustomName(customName); } if (lore != null) { item.setLore(lore, "", "§eChance, §r" + chance); } else { item.setLore("", "§eChance, §r" + chance); } if (drop.containsKey("enchantments")) { List<Map<String, Object>> enchantList = (List<Map<String, Object>>) drop.get("enchantments"); for (Map<String, Object> enchant : enchantList) { String enchantName = (String) enchant.get("name"); int enchantLevel = (int) enchant.get("level"); Integer enchantId = LuckyCrates.getEnchantmentByName(enchantName); if (enchantId == null) { player.sendMessage("§cError Enchantment not found : " + enchantName); return; } item.addEnchantment(Enchantment.getEnchantment(enchantId).setLevel(enchantLevel)); } } inv.addItem(item); i++; if (i > 35) break; } inv.setItem(49, new Item(130, 0, 1) .setNamedTag(new CompoundTag() .putString("button", "openCrate")) .setCustomName("§l§aOpen Crates") .setLore("", "§eNeed Key, §r" + crateSect.getInt("amount"), "§eMy Key, §r" + getKeysCount(player, crateName))); inv.setDefaultItemHandler((item, event) -> { event.setCancelled(); Player target = event.getTransaction().getSource(); int myKey = getKeysCount(target, crateName); int needKey = crateSect.getInt("amount"); if (target.getInventory().isFull()) { target.sendMessage("<Inventory kamu full>"); return; } if (item.hasCompoundTag() && item.getNamedTag().exist("button")) { if (myKey >= needKey) { if (crateSect.exists("commands", true)) { for (String command : crateSect.getStringList("commands")) { Server.getInstance().executeCommand(Server.getInstance().getConsoleSender(), command.replace("{player}", target.getName())); } } reduceKey(target, crateName, needKey); String type = LuckyCrates.getInstance().getConfig().getString("crates.type", "roulette"); if (type.equalsIgnoreCase("instant")) { target.removeWindow(inv);
package angga7togk.luckycrates.menu; public class ChestMenu { private final Map<String, String> lang; public ChestMenu() { this.lang = new Languages().getLanguage(); } public void mainMenu(Player player, String crateName) { LuckyCrates.crates.reload(); FakeInventory inv = new FakeInventory(InventoryType.DOUBLE_CHEST, TextFormat.BOLD + crateName); if (!LuckyCrates.crates.exists(crateName)) { player.sendMessage(LuckyCrates.prefix + lang.get("crate-notfound")); return; } ConfigSection crateSect = LuckyCrates.crates.getSection(crateName); List<Map<String, Object>> dropsList = crateSect.getList("drops"); int i = 0; for (Map<String, Object> drop : dropsList) { int id = (int) drop.get("id"); int meta = (int) drop.get("meta"); int amount = (int) drop.get("amount"); int chance = (int) drop.get("chance"); String customName = drop.containsKey("name") ? (String) drop.get("name") : null; String lore = drop.containsKey("lore") ? (String) drop.get("lore") : null; Item item = new Item(id, meta, amount); if (customName != null) { item.setCustomName(customName); } if (lore != null) { item.setLore(lore, "", "§eChance, §r" + chance); } else { item.setLore("", "§eChance, §r" + chance); } if (drop.containsKey("enchantments")) { List<Map<String, Object>> enchantList = (List<Map<String, Object>>) drop.get("enchantments"); for (Map<String, Object> enchant : enchantList) { String enchantName = (String) enchant.get("name"); int enchantLevel = (int) enchant.get("level"); Integer enchantId = LuckyCrates.getEnchantmentByName(enchantName); if (enchantId == null) { player.sendMessage("§cError Enchantment not found : " + enchantName); return; } item.addEnchantment(Enchantment.getEnchantment(enchantId).setLevel(enchantLevel)); } } inv.addItem(item); i++; if (i > 35) break; } inv.setItem(49, new Item(130, 0, 1) .setNamedTag(new CompoundTag() .putString("button", "openCrate")) .setCustomName("§l§aOpen Crates") .setLore("", "§eNeed Key, §r" + crateSect.getInt("amount"), "§eMy Key, §r" + getKeysCount(player, crateName))); inv.setDefaultItemHandler((item, event) -> { event.setCancelled(); Player target = event.getTransaction().getSource(); int myKey = getKeysCount(target, crateName); int needKey = crateSect.getInt("amount"); if (target.getInventory().isFull()) { target.sendMessage("<Inventory kamu full>"); return; } if (item.hasCompoundTag() && item.getNamedTag().exist("button")) { if (myKey >= needKey) { if (crateSect.exists("commands", true)) { for (String command : crateSect.getStringList("commands")) { Server.getInstance().executeCommand(Server.getInstance().getConsoleSender(), command.replace("{player}", target.getName())); } } reduceKey(target, crateName, needKey); String type = LuckyCrates.getInstance().getConfig().getString("crates.type", "roulette"); if (type.equalsIgnoreCase("instant")) { target.removeWindow(inv);
Server.getInstance().getScheduler().scheduleDelayedTask(new InstantTask(target, crateName), 5, true);
3
2023-11-20 08:04:22+00:00
8k
ca-webdev/exchange-backed-java
src/main/java/ca/webdev/exchange/web/websocket/Publisher.java
[ { "identifier": "MatchingEngine", "path": "src/main/java/ca/webdev/exchange/matching/MatchingEngine.java", "snippet": "public class MatchingEngine {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(MatchingEngine.class);\n private final double tickSize;\n private final int tickS...
import ca.webdev.exchange.matching.MatchingEngine; import ca.webdev.exchange.matching.Order; import ca.webdev.exchange.web.model.OpenHighLowClose; import ca.webdev.exchange.web.model.OrderBookUpdate; import ca.webdev.exchange.web.model.OrderUpdate; import ca.webdev.exchange.web.model.RecentTrade; import ca.webdev.exchange.web.model.UserTrade; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Component; import java.util.Comparator; import java.util.Queue; import java.util.SortedMap; import java.util.TreeMap; import static ca.webdev.exchange.web.OrderBookUtil.sumSizes;
4,634
package ca.webdev.exchange.web.websocket; @Component public class Publisher { @Autowired private SimpMessagingTemplate template; public Publisher(MatchingEngine matchingEngine) { matchingEngine.registerOrderBookListener(this::handleOrderBook); matchingEngine.registerMarketTradeListener(this::handleMarketTrade); } public void handleOrderBook(SortedMap<Double, Queue<Order>> bidOrderBook, SortedMap<Double, Queue<Order>> askOrderBook) {
package ca.webdev.exchange.web.websocket; @Component public class Publisher { @Autowired private SimpMessagingTemplate template; public Publisher(MatchingEngine matchingEngine) { matchingEngine.registerOrderBookListener(this::handleOrderBook); matchingEngine.registerMarketTradeListener(this::handleMarketTrade); } public void handleOrderBook(SortedMap<Double, Queue<Order>> bidOrderBook, SortedMap<Double, Queue<Order>> askOrderBook) {
template.convertAndSend("/topic/orderbookupdates", new OrderBookUpdate(sumSizes(new TreeMap<>(Comparator.reverseOrder()), bidOrderBook), sumSizes(new TreeMap<>(), askOrderBook)));
3
2023-11-20 16:03:59+00:00
8k
FalkorDB/JFalkorDB
src/test/java/com/falkordb/GraphAPITest.java
[ { "identifier": "Label", "path": "src/main/java/com/falkordb/Statistics.java", "snippet": "enum Label{\n\tLABELS_ADDED(\"Labels added\"),\n\tINDICES_ADDED(\"Indices created\"),\n\tINDICES_DELETED(\"Indices deleted\"),\n\tNODES_CREATED(\"Nodes created\"),\n\tNODES_DELETED(\"Nodes deleted\"),\n\tRELATIONS...
import static org.junit.Assert.fail; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.falkordb.Statistics.Label; import com.falkordb.exceptions.GraphException; import com.falkordb.graph_entities.Edge; import com.falkordb.graph_entities.Node; import com.falkordb.graph_entities.Path; import com.falkordb.graph_entities.Point; import com.falkordb.graph_entities.Property; import com.falkordb.test.utils.PathBuilder;
5,780
Assert.assertFalse(deleteResult.iterator().hasNext()); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.PROPERTIES_SET)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.RELATIONSHIPS_CREATED)); Assert.assertEquals(1, deleteResult.getStatistics().relationshipsDeleted()); Assert.assertEquals(1, deleteResult.getStatistics().nodesDeleted()); Assert.assertNotNull(deleteResult.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); } @Test public void testDeleteRelationship() { Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); Assert.assertNotNull(client.query("CREATE (:person{name:'amit',age:30})")); Assert.assertNotNull(client.query( "MATCH (a:person), (b:person) WHERE (a.name = 'roi' AND b.name='amit') CREATE (a)-[:knows]->(a)")); ResultSet deleteResult = client.query("MATCH (a:person)-[e]->() WHERE (a.name = 'roi') DELETE e"); Assert.assertFalse(deleteResult.iterator().hasNext()); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.PROPERTIES_SET)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.RELATIONSHIPS_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_DELETED)); Assert.assertEquals(1, deleteResult.getStatistics().relationshipsDeleted()); Assert.assertNotNull(deleteResult.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); } @Test public void testIndex() { // Create both source and destination nodes Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); ResultSet createIndexResult = client.query("CREATE INDEX ON :person(age)"); Assert.assertFalse(createIndexResult.iterator().hasNext()); Assert.assertEquals(1, createIndexResult.getStatistics().indicesAdded()); // since RediSearch as index, those action are allowed ResultSet createNonExistingIndexResult = client.query("CREATE INDEX ON :person(age1)"); Assert.assertFalse(createNonExistingIndexResult.iterator().hasNext()); Assert.assertNotNull(createNonExistingIndexResult.getStatistics().getStringValue(Label.INDICES_ADDED)); Assert.assertEquals(1, createNonExistingIndexResult.getStatistics().indicesAdded()); try { client.query("CREATE INDEX ON :person(age)"); fail("Expected Exception was not thrown."); } catch (Exception e) { } ResultSet deleteExistingIndexResult = client.query("DROP INDEX ON :person(age)"); Assert.assertFalse(deleteExistingIndexResult.iterator().hasNext()); Assert.assertNotNull(deleteExistingIndexResult.getStatistics().getStringValue(Label.INDICES_DELETED)); Assert.assertEquals(1, deleteExistingIndexResult.getStatistics().indicesDeleted()); } @Test public void testHeader() { Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); Assert.assertNotNull(client.query("CREATE (:person{name:'amit',age:30})")); Assert.assertNotNull(client.query( "MATCH (a:person), (b:person) WHERE (a.name = 'roi' AND b.name='amit') CREATE (a)-[:knows]->(a)")); ResultSet queryResult = client.query("MATCH (a:person)-[r:knows]->(b:person) RETURN a,r, a.age"); Header header = queryResult.getHeader(); Assert.assertNotNull(header); Assert.assertEquals("HeaderImpl{" + "schemaTypes=[COLUMN_SCALAR, COLUMN_SCALAR, COLUMN_SCALAR], " + "schemaNames=[a, r, a.age]}", header.toString()); List<String> schemaNames = header.getSchemaNames(); Assert.assertNotNull(schemaNames); Assert.assertEquals(3, schemaNames.size()); Assert.assertEquals("a", schemaNames.get(0)); Assert.assertEquals("r", schemaNames.get(1)); Assert.assertEquals("a.age", schemaNames.get(2)); } @Test public void testRecord() { String name = "roi"; int age = 32; double doubleValue = 3.14; boolean boolValue = true; String place = "TLV"; int since = 2000; Property<String> nameProperty = new Property<>("name", name); Property<Integer> ageProperty = new Property<>("age", age); Property<Double> doubleProperty = new Property<>("doubleValue", doubleValue); Property<Boolean> trueBooleanProperty = new Property<>("boolValue", true); Property<Boolean> falseBooleanProperty = new Property<>("boolValue", false); Node expectedNode = new Node(); expectedNode.setId(0); expectedNode.addLabel("person"); expectedNode.addProperty(nameProperty); expectedNode.addProperty(ageProperty); expectedNode.addProperty(doubleProperty); expectedNode.addProperty(trueBooleanProperty); Assert.assertEquals( "Node{labels=[person], id=0, " + "propertyMap={name=Property{name='name', value=roi}, " + "boolValue=Property{name='boolValue', value=true}, " + "doubleValue=Property{name='doubleValue', value=3.14}, " + "age=Property{name='age', value=32}}}", expectedNode.toString()); Assert.assertEquals( 4, expectedNode.getNumberOfProperties());
package com.falkordb; public class GraphAPITest { private GraphContextGenerator client; @Before public void createApi() { client = FalkorDB.driver().graph("social"); } @After public void deleteGraph() { client.deleteGraph(); client.close(); } @Test public void testCreateNode() { // Create a node ResultSet resultSet = client.query("CREATE ({name:'roi',age:32})"); Assert.assertEquals(1, resultSet.getStatistics().nodesCreated()); Assert.assertNull(resultSet.getStatistics().getStringValue(Label.NODES_DELETED)); Assert.assertNull(resultSet.getStatistics().getStringValue(Label.RELATIONSHIPS_CREATED)); Assert.assertNull(resultSet.getStatistics().getStringValue(Label.RELATIONSHIPS_DELETED)); Assert.assertEquals(2, resultSet.getStatistics().propertiesSet()); Assert.assertNotNull(resultSet.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); Iterator<Record> iterator = resultSet.iterator(); Assert.assertFalse(iterator.hasNext()); try { iterator.next(); fail("Expected NoSuchElementException was not thrown."); } catch (NoSuchElementException ignored) { } } @Test public void testCreateLabeledNode() { // Create a node with a label ResultSet resultSet = client.query("CREATE (:human{name:'danny',age:12})"); Assert.assertFalse(resultSet.iterator().hasNext()); Assert.assertEquals("1", resultSet.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertEquals("2", resultSet.getStatistics().getStringValue(Label.PROPERTIES_SET)); Assert.assertNotNull(resultSet.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); } @Test public void testConnectNodes() { // Create both source and destination nodes Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); Assert.assertNotNull(client.query("CREATE (:person{name:'amit',age:30})")); // Connect source and destination nodes. ResultSet resultSet = client.query( "MATCH (a:person), (b:person) WHERE (a.name = 'roi' AND b.name='amit') CREATE (a)-[:knows]->(b)"); Assert.assertFalse(resultSet.iterator().hasNext()); Assert.assertNull(resultSet.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(resultSet.getStatistics().getStringValue(Label.PROPERTIES_SET)); Assert.assertEquals(1, resultSet.getStatistics().relationshipsCreated()); Assert.assertEquals(0, resultSet.getStatistics().relationshipsDeleted()); Assert.assertNotNull(resultSet.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); } @Test public void testDeleteNodes() { Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); Assert.assertNotNull(client.query("CREATE (:person{name:'amit',age:30})")); ResultSet deleteResult = client.query("MATCH (a:person) WHERE (a.name = 'roi') DELETE a"); Assert.assertFalse(deleteResult.iterator().hasNext()); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.PROPERTIES_SET)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.RELATIONSHIPS_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.RELATIONSHIPS_DELETED)); Assert.assertEquals(1, deleteResult.getStatistics().nodesDeleted()); Assert.assertNotNull(deleteResult.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); Assert.assertNotNull(client.query( "MATCH (a:person), (b:person) WHERE (a.name = 'roi' AND b.name='amit') CREATE (a)-[:knows]->(b)")); deleteResult = client.query("MATCH (a:person) WHERE (a.name = 'roi') DELETE a"); Assert.assertFalse(deleteResult.iterator().hasNext()); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.PROPERTIES_SET)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.RELATIONSHIPS_CREATED)); Assert.assertEquals(1, deleteResult.getStatistics().relationshipsDeleted()); Assert.assertEquals(1, deleteResult.getStatistics().nodesDeleted()); Assert.assertNotNull(deleteResult.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); } @Test public void testDeleteRelationship() { Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); Assert.assertNotNull(client.query("CREATE (:person{name:'amit',age:30})")); Assert.assertNotNull(client.query( "MATCH (a:person), (b:person) WHERE (a.name = 'roi' AND b.name='amit') CREATE (a)-[:knows]->(a)")); ResultSet deleteResult = client.query("MATCH (a:person)-[e]->() WHERE (a.name = 'roi') DELETE e"); Assert.assertFalse(deleteResult.iterator().hasNext()); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.PROPERTIES_SET)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.RELATIONSHIPS_CREATED)); Assert.assertNull(deleteResult.getStatistics().getStringValue(Label.NODES_DELETED)); Assert.assertEquals(1, deleteResult.getStatistics().relationshipsDeleted()); Assert.assertNotNull(deleteResult.getStatistics().getStringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); } @Test public void testIndex() { // Create both source and destination nodes Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); ResultSet createIndexResult = client.query("CREATE INDEX ON :person(age)"); Assert.assertFalse(createIndexResult.iterator().hasNext()); Assert.assertEquals(1, createIndexResult.getStatistics().indicesAdded()); // since RediSearch as index, those action are allowed ResultSet createNonExistingIndexResult = client.query("CREATE INDEX ON :person(age1)"); Assert.assertFalse(createNonExistingIndexResult.iterator().hasNext()); Assert.assertNotNull(createNonExistingIndexResult.getStatistics().getStringValue(Label.INDICES_ADDED)); Assert.assertEquals(1, createNonExistingIndexResult.getStatistics().indicesAdded()); try { client.query("CREATE INDEX ON :person(age)"); fail("Expected Exception was not thrown."); } catch (Exception e) { } ResultSet deleteExistingIndexResult = client.query("DROP INDEX ON :person(age)"); Assert.assertFalse(deleteExistingIndexResult.iterator().hasNext()); Assert.assertNotNull(deleteExistingIndexResult.getStatistics().getStringValue(Label.INDICES_DELETED)); Assert.assertEquals(1, deleteExistingIndexResult.getStatistics().indicesDeleted()); } @Test public void testHeader() { Assert.assertNotNull(client.query("CREATE (:person{name:'roi',age:32})")); Assert.assertNotNull(client.query("CREATE (:person{name:'amit',age:30})")); Assert.assertNotNull(client.query( "MATCH (a:person), (b:person) WHERE (a.name = 'roi' AND b.name='amit') CREATE (a)-[:knows]->(a)")); ResultSet queryResult = client.query("MATCH (a:person)-[r:knows]->(b:person) RETURN a,r, a.age"); Header header = queryResult.getHeader(); Assert.assertNotNull(header); Assert.assertEquals("HeaderImpl{" + "schemaTypes=[COLUMN_SCALAR, COLUMN_SCALAR, COLUMN_SCALAR], " + "schemaNames=[a, r, a.age]}", header.toString()); List<String> schemaNames = header.getSchemaNames(); Assert.assertNotNull(schemaNames); Assert.assertEquals(3, schemaNames.size()); Assert.assertEquals("a", schemaNames.get(0)); Assert.assertEquals("r", schemaNames.get(1)); Assert.assertEquals("a.age", schemaNames.get(2)); } @Test public void testRecord() { String name = "roi"; int age = 32; double doubleValue = 3.14; boolean boolValue = true; String place = "TLV"; int since = 2000; Property<String> nameProperty = new Property<>("name", name); Property<Integer> ageProperty = new Property<>("age", age); Property<Double> doubleProperty = new Property<>("doubleValue", doubleValue); Property<Boolean> trueBooleanProperty = new Property<>("boolValue", true); Property<Boolean> falseBooleanProperty = new Property<>("boolValue", false); Node expectedNode = new Node(); expectedNode.setId(0); expectedNode.addLabel("person"); expectedNode.addProperty(nameProperty); expectedNode.addProperty(ageProperty); expectedNode.addProperty(doubleProperty); expectedNode.addProperty(trueBooleanProperty); Assert.assertEquals( "Node{labels=[person], id=0, " + "propertyMap={name=Property{name='name', value=roi}, " + "boolValue=Property{name='boolValue', value=true}, " + "doubleValue=Property{name='doubleValue', value=3.14}, " + "age=Property{name='age', value=32}}}", expectedNode.toString()); Assert.assertEquals( 4, expectedNode.getNumberOfProperties());
Edge expectedEdge = new Edge();
2
2023-11-26 13:38:14+00:00
8k
EcoNetsTech/spore-spring-boot-starter
src/main/java/cn/econets/ximutech/spore/config/RetrofitAutoConfiguration.java
[ { "identifier": "GlobalInterceptor", "path": "src/main/java/cn/econets/ximutech/spore/GlobalInterceptor.java", "snippet": "public interface GlobalInterceptor extends Interceptor {\n}" }, { "identifier": "RetryInterceptor", "path": "src/main/java/cn/econets/ximutech/spore/retry/RetryIntercept...
import cn.econets.ximutech.spore.GlobalInterceptor; import cn.econets.ximutech.spore.retry.RetryInterceptor; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import cn.econets.ximutech.spore.okhttp.OkHttpClientRegistry; import cn.econets.ximutech.spore.decoder.ErrorDecoder; import cn.econets.ximutech.spore.decoder.ErrorDecoderInterceptor; import cn.econets.ximutech.spore.log.LoggingInterceptor; import cn.econets.ximutech.spore.okhttp.OkHttpClientRegistrar; import cn.econets.ximutech.spore.retrofit.converter.BaseTypeConverterFactory; import cn.econets.ximutech.spore.service.ServiceChooseInterceptor; import cn.econets.ximutech.spore.service.ServiceInstanceChooser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import retrofit2.converter.jackson.JacksonConverterFactory; import java.util.List;
3,827
package cn.econets.ximutech.spore.config; /** * @author ximu */ @AutoConfiguration @EnableConfigurationProperties(RetrofitProperties.class) public class RetrofitAutoConfiguration { private final RetrofitProperties retrofitProperties; public RetrofitAutoConfiguration(RetrofitProperties retrofitProperties) { this.retrofitProperties = retrofitProperties; } @Bean
package cn.econets.ximutech.spore.config; /** * @author ximu */ @AutoConfiguration @EnableConfigurationProperties(RetrofitProperties.class) public class RetrofitAutoConfiguration { private final RetrofitProperties retrofitProperties; public RetrofitAutoConfiguration(RetrofitProperties retrofitProperties) { this.retrofitProperties = retrofitProperties; } @Bean
public BaseTypeConverterFactory basicTypeConverterFactory() {
7
2023-11-21 18:00:50+00:00
8k
NBHZW/hnustDatabaseCourseDesign
ruoyi-test/src/main/java/com/ruoyi/system/service/impl/SysUserServiceImpl.java
[ { "identifier": "DateUtils", "path": "ruoyi-common/src/main/java/com/ruoyi/common/utils/DateUtils.java", "snippet": "public class DateUtils extends org.apache.commons.lang3.time.DateUtils\r\n{\r\n public static String YYYY = \"yyyy\";\r\n\r\n public static String YYYY_MM = \"yyyy-MM\";\r\n\r\n ...
import java.util.List; import com.ruoyi.common.utils.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.system.mapper.SysUserMapper; import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.service.ISysUserService;
5,045
package com.ruoyi.system.service.impl; /** * 用户信息Service业务层处理 * * @author ruoyi * @date 2023-10-24 */ @Service public class SysUserServiceImpl implements ISysUserService { @Autowired
package com.ruoyi.system.service.impl; /** * 用户信息Service业务层处理 * * @author ruoyi * @date 2023-10-24 */ @Service public class SysUserServiceImpl implements ISysUserService { @Autowired
private SysUserMapper sysUserMapper;
1
2023-11-25 02:50:45+00:00
8k
isXander/YetAnotherUILib
src/testmod/java/dev/isxander/yaul3/test/TestScreen.java
[ { "identifier": "Animation", "path": "src/main/java/dev/isxander/yaul3/api/animation/Animation.java", "snippet": "public non-sealed interface Animation extends Animatable {\n /**\n * Creates a new instance of an animation.\n * All methods that configure something about the animation are locke...
import dev.isxander.yaul3.api.animation.Animation; import dev.isxander.yaul3.api.ui.*; import dev.isxander.yaul3.impl.ui.AbstractLayoutWidget; import dev.isxander.yaul3.impl.widgets.DynamicGridWidget; import dev.isxander.yaul3.impl.widgets.ImageButtonWidget; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation;
5,357
package dev.isxander.yaul3.test; public class TestScreen extends Screen implements UnitHelper { public TestScreen(Component title) { super(title); } @Override protected void init() { super.init(); DynamicGridWidget grid = new DynamicGridWidget(0, 0, this.width - 20, this.height - 20); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp")), 4, 1); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp")), 2, 2); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.setPadding(5); //grid.visitWidgets(this::addRenderableWidget); // var layout = FlexWidget.create() // .setWidth(percentW(100)).setHeight(percentH(100)) // .setJustification(FlexJustification.CENTER) // .setAlign(FlexAlign.CENTER) // .addWidgets( // LayoutWidget.of(Component.literal("Screen Title"), font) // ); // while (layout.justify()) {} // layout.addToScreen(this::addWidget, this::addRenderableOnly); IntState width = px(200);
package dev.isxander.yaul3.test; public class TestScreen extends Screen implements UnitHelper { public TestScreen(Component title) { super(title); } @Override protected void init() { super.init(); DynamicGridWidget grid = new DynamicGridWidget(0, 0, this.width - 20, this.height - 20); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp")), 4, 1); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp")), 2, 2); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.addChild(new ImageButtonWidget(0, 0, 50, 50, Component.literal("Test"), new ResourceLocation("yaul_test", "textures/home.webp"))); grid.setPadding(5); //grid.visitWidgets(this::addRenderableWidget); // var layout = FlexWidget.create() // .setWidth(percentW(100)).setHeight(percentH(100)) // .setJustification(FlexJustification.CENTER) // .setAlign(FlexAlign.CENTER) // .addWidgets( // LayoutWidget.of(Component.literal("Screen Title"), font) // ); // while (layout.justify()) {} // layout.addToScreen(this::addWidget, this::addRenderableOnly); IntState width = px(200);
var animation = Animation.of(200)
0
2023-11-25 13:11:05+00:00
8k
DueWesternersProgramming/FRC-2023-Swerve-Offseason
src/main/java/frc/robot/OI/OperatorInterface.java
[ { "identifier": "EntechJoystick", "path": "src/main/java/entech/util/EntechJoystick.java", "snippet": "public class EntechJoystick extends CommandJoystick {\n private final Joystick hid;\n\n public EntechJoystick(int port) {\n super(port);\n hid = this.getHID();\n }\n\n public ...
import entech.util.EntechJoystick; import frc.robot.CommandFactory; import frc.robot.RobotConstants; import frc.robot.RobotContainer; import frc.robot.commands.DriveCommand; import frc.robot.commands.TwistCommand; import frc.robot.commands.XCommand;
3,923
package frc.robot.OI; public class OperatorInterface { private final EntechJoystick driveJoystick = new EntechJoystick(RobotConstants.Ports.CONTROLLER.JOYSTICK); //private final EntechJoystick operatorPanel = new EntechJoystick(RobotConstants.Ports.CONTROLLER.PANEL); public OperatorInterface(CommandFactory commandFactory, RobotContainer robotContainer) {
package frc.robot.OI; public class OperatorInterface { private final EntechJoystick driveJoystick = new EntechJoystick(RobotConstants.Ports.CONTROLLER.JOYSTICK); //private final EntechJoystick operatorPanel = new EntechJoystick(RobotConstants.Ports.CONTROLLER.PANEL); public OperatorInterface(CommandFactory commandFactory, RobotContainer robotContainer) {
driveJoystick.WhilePressed(1, new TwistCommand());
5
2023-11-21 01:49:41+00:00
8k
huangwei021230/memo
app/src/main/java/com/huawei/cloud/drive/MainActivity.java
[ { "identifier": "MemoAdapter", "path": "app/src/main/java/com/huawei/cloud/drive/adapter/MemoAdapter.java", "snippet": "public class MemoAdapter extends RecyclerView.Adapter<MemoAdapter.ViewHolder> {\n private List<MemoInfo> memoList;\n private OnItemClickListener onItemClickListener;\n\n publi...
import android.content.Intent; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.huawei.agconnect.cloud.database.CloudDBZone; import com.huawei.cloud.drive.adapter.MemoAdapter; import com.huawei.cloud.drive.bean.MemoInfo; import com.huawei.cloud.drive.hms.CloudDBManager; import com.huawei.cloud.drive.hms.CloudDBManager.UiCallBack; import java.util.ArrayList; import java.util.List; import boogiepop.memo.R;
4,115
package com.huawei.cloud.drive; /** * Main Activity */ public class MainActivity extends AppCompatActivity implements UiCallBack { // 假设有一个 Memo 类来表示备忘录项 private CloudDBManager cloudDBManager;
package com.huawei.cloud.drive; /** * Main Activity */ public class MainActivity extends AppCompatActivity implements UiCallBack { // 假设有一个 Memo 类来表示备忘录项 private CloudDBManager cloudDBManager;
private List<MemoInfo> memoList;
1
2023-11-25 07:44:41+00:00
8k
kkyesyes/Multi-userCommunicationSystem-Client
src/com/kk/qqclient/view/QQView.java
[ { "identifier": "FileClientService", "path": "src/com/kk/qqclient/service/FileClientService.java", "snippet": "public class FileClientService {\n public void sendFileToOne(String src, String senderId, String getterId) {\n // 读取src文件 -> message\n Message message = new Message();\n ...
import com.kk.qqclient.service.FileClientService; import com.kk.qqclient.service.UserClientService; import com.kk.qqclient.utils.Utility; import com.kk.qqcommon.Settings; import com.sun.xml.internal.ws.api.config.management.policy.ManagementAssertion;
4,126
package com.kk.qqclient.view; /** * 客户端菜单界面 * * @author KK * @version 1.0 */ public class QQView { // 循环控制 private boolean loop = true; // 接收用户键盘输入 private String key = ""; // 用户服务 private UserClientService userClientService = new UserClientService(); // 文件服务 private FileClientService fileClientService = new FileClientService(); public static void main(String[] args) { new QQView().mainMenu(); } // 显示主菜单 private void mainMenu() { while (loop) { System.out.println("==========欢迎登录网络通信系统=========="); System.out.println("\t\t1 登录系统"); System.out.println("\t\t9 退出系统"); System.out.print("请输入你的选择:"); key = Utility.readString(1); switch (key) { case "1": System.out.print("请输入用户号:"); String userId = Utility.readString(50); System.out.print("请输入密 码:"); String pwd = Utility.readString(50); // 验证用户是否合法 if (userClientService.checkUser(userId, pwd)) { System.out.println("==========欢迎用户(" + userId + ")登录成功=========="); // 二级菜单 while (loop) { System.out.println("\n==========网络通信系统二级菜单(用户" + userId + ")=========="); System.out.println("\t\t 1 显示在线用户列表"); System.out.println("\t\t 2 群发消息"); System.out.println("\t\t 3 私聊消息"); System.out.println("\t\t 4 发送文件"); System.out.println("\t\t 5 文件路径"); System.out.println("\t\t 9 退出系统"); System.out.print("请输入你的选择:"); key = Utility.readString(1); switch (key) { case "1": // System.out.println("显示在线用户列表"); userClientService.getOnlineFriends(); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } break; case "2": // System.out.println("群发消息"); while (true) { System.out.println("==========群发模式(quit退出)=========="); System.out.println("请输入内容(回车发送):"); String data = Utility.readString(500); if ("quit".equals(data)) break; userClientService.atAll(data); } break; case "3": System.out.print("请输入私聊对方的用户号:"); String ID = Utility.readString(50); while (true) { System.out.println("==========与 " + ID + " 私聊消息中(quit退出)=========="); System.out.println("请输入内容(回车发送):"); String data = Utility.readString(500); if ("quit".equals(data)) break; userClientService.talkTo(ID, data); } break; case "4": System.out.println("发送文件功能正在维护中"); // System.out.print("请输入文件接收方的用户号:"); // String getterId = Utility.readString(50); // System.out.println("即将向 " + getterId + " 发送文件"); // System.out.print("请输入本地文件绝对路径:"); // String filePath = Utility.readString(500); // fileClientService.sendFileToOne(filePath, userId, getterId); break; case "5":
package com.kk.qqclient.view; /** * 客户端菜单界面 * * @author KK * @version 1.0 */ public class QQView { // 循环控制 private boolean loop = true; // 接收用户键盘输入 private String key = ""; // 用户服务 private UserClientService userClientService = new UserClientService(); // 文件服务 private FileClientService fileClientService = new FileClientService(); public static void main(String[] args) { new QQView().mainMenu(); } // 显示主菜单 private void mainMenu() { while (loop) { System.out.println("==========欢迎登录网络通信系统=========="); System.out.println("\t\t1 登录系统"); System.out.println("\t\t9 退出系统"); System.out.print("请输入你的选择:"); key = Utility.readString(1); switch (key) { case "1": System.out.print("请输入用户号:"); String userId = Utility.readString(50); System.out.print("请输入密 码:"); String pwd = Utility.readString(50); // 验证用户是否合法 if (userClientService.checkUser(userId, pwd)) { System.out.println("==========欢迎用户(" + userId + ")登录成功=========="); // 二级菜单 while (loop) { System.out.println("\n==========网络通信系统二级菜单(用户" + userId + ")=========="); System.out.println("\t\t 1 显示在线用户列表"); System.out.println("\t\t 2 群发消息"); System.out.println("\t\t 3 私聊消息"); System.out.println("\t\t 4 发送文件"); System.out.println("\t\t 5 文件路径"); System.out.println("\t\t 9 退出系统"); System.out.print("请输入你的选择:"); key = Utility.readString(1); switch (key) { case "1": // System.out.println("显示在线用户列表"); userClientService.getOnlineFriends(); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } break; case "2": // System.out.println("群发消息"); while (true) { System.out.println("==========群发模式(quit退出)=========="); System.out.println("请输入内容(回车发送):"); String data = Utility.readString(500); if ("quit".equals(data)) break; userClientService.atAll(data); } break; case "3": System.out.print("请输入私聊对方的用户号:"); String ID = Utility.readString(50); while (true) { System.out.println("==========与 " + ID + " 私聊消息中(quit退出)=========="); System.out.println("请输入内容(回车发送):"); String data = Utility.readString(500); if ("quit".equals(data)) break; userClientService.talkTo(ID, data); } break; case "4": System.out.println("发送文件功能正在维护中"); // System.out.print("请输入文件接收方的用户号:"); // String getterId = Utility.readString(50); // System.out.println("即将向 " + getterId + " 发送文件"); // System.out.print("请输入本地文件绝对路径:"); // String filePath = Utility.readString(500); // fileClientService.sendFileToOne(filePath, userId, getterId); break; case "5":
System.out.println("默认文件保存路径为:" + Settings.getDownloadPath());
3
2023-11-22 16:29:22+00:00
8k
partypankes/ProgettoCalcolatrice2023
ProgrammableCalculator/src/test/java/group21/calculator/test/VariablesTest.java
[ { "identifier": "Variables", "path": "ProgrammableCalculator/src/main/java/group21/calculator/operation/Variables.java", "snippet": "public class Variables {\n\n private final Map<Character, ComplexNumber> variables;\n\n /**\n * Constructor for Variables.\n * Initializes a new HashMap to s...
import group21.calculator.operation.Variables; import group21.calculator.type.ComplexNumber; import group21.calculator.type.StackNumber; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*;
4,706
package group21.calculator.test; class VariablesTest { Variables variables;
package group21.calculator.test; class VariablesTest { Variables variables;
StackNumber numbers;
2
2023-11-19 16:11:56+00:00
8k
Staffilon/KestraDataOrchestrator
IoT Simulator/src/main/java/net/acesinc/data/json/generator/RandomJsonGenerator.java
[ { "identifier": "WorkflowConfig", "path": "IoT Simulator/src/main/java/net/acesinc/data/json/generator/config/WorkflowConfig.java", "snippet": "public class WorkflowConfig {\n\t//nome per il flusso di lavoro\n private String workflowName;\n //nome del flie di configurazione del flusso di lavoro da...
import java.io.IOException; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.json.Json; import javax.json.stream.JsonGenerator; import javax.json.stream.JsonGeneratorFactory; import org.apache.commons.math3.random.RandomDataGenerator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.fasterxml.jackson.databind.ObjectMapper; import net.acesinc.data.json.generator.config.WorkflowConfig; import net.acesinc.data.json.generator.types.TypeHandler; import net.acesinc.data.json.generator.types.TypeHandlerFactory; import net.acesinc.data.json.util.JsonUtils;
3,869
ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(json, List.class); } private javax.json.stream.JsonGenerator processProperties(javax.json.stream.JsonGenerator gen, Map<String, Object> props, String currentContext) { for (String propName : props.keySet()) { Object value = props.get(propName); if (value == null) { generatedValues.put(currentContext + propName, null); addValue(gen, propName, null); } else if (String.class.isAssignableFrom(value.getClass())) { String type = (String) value; handleStringGeneration(type, currentContext, gen, propName); } else if (Map.class.isAssignableFrom(value.getClass())) { //nested object Map<String, Object> nestedProps = (Map<String, Object>) value; if (propName == null) { gen.writeStartObject(); } else { gen.writeStartObject(propName); } String newContext = ""; if (propName != null) { if (currentContext.isEmpty()) { newContext = propName + "."; } else { newContext = currentContext + propName + "."; } } processProperties(gen, nestedProps, newContext); gen.writeEnd(); } else if (List.class.isAssignableFrom(value.getClass())) { //array List<Object> listOfItems = (List<Object>) value; String newContext = ""; if (propName != null) { gen.writeStartArray(propName); if (currentContext.isEmpty()) { newContext = propName; } else { newContext = currentContext + propName; } } else { gen.writeStartArray(); } if (!listOfItems.isEmpty()) { //Check if this is a special function at the start of the array boolean wasSpecialCase = false; if (String.class.isAssignableFrom(listOfItems.get(0).getClass()) && ((String) listOfItems.get(0)).contains("(")) { //special function in array String name = (String) listOfItems.get(0); String specialFunc = null; String[] specialFuncArgs = {}; specialFunc = name.substring(0, name.indexOf("(")); String args = name.substring(name.indexOf("(") + 1, name.indexOf(")")); if (!args.isEmpty()) { specialFuncArgs = args.split(","); } switch (specialFunc) { case "repeat": { int timesToRepeat = 1; if (specialFuncArgs.length == 1) { timesToRepeat = Integer.parseInt(specialFuncArgs[0]); } else { timesToRepeat = new RandomDataGenerator().nextInt(0, 10); } List<Object> subList = listOfItems.subList(1, listOfItems.size()); for (int i = 0; i < timesToRepeat; i++) { processList(subList, gen, newContext); } wasSpecialCase = true; break; } case "random": { //choose one of the items in the list at random List<Object> subList = listOfItems.subList(1, listOfItems.size()); Object item = subList.get(new RandomDataGenerator().nextInt(0, subList.size() - 1)); processItem(item, gen, newContext + "[0]"); wasSpecialCase = true; break; } } } if (!wasSpecialCase) { //it's not a special function, so process it like normal processList(listOfItems, gen, newContext); } } gen.writeEnd(); } else { //literals generatedValues.put(currentContext + propName, value); addValue(gen, propName, value); } } return gen; } protected void handleStringGeneration(String type, String currentContext, JsonGenerator gen, String propName) { if (type.startsWith("this.") || type.startsWith("cur.")) { String refPropName = null; if (type.startsWith("this.")) { refPropName = type.substring("this.".length(), type.length()); } else if (type.startsWith("cur.")) { refPropName = currentContext + type.substring("cur.".length(), type.length()); } Object refPropValue = generatedValues.get(refPropName); if (refPropValue != null) { addValue(gen, propName, refPropValue); } else { log.warn("Sorry, unable to reference property [ " + refPropName + " ]. Maybe it hasn't been generated yet?"); } } else { try {
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package net.acesinc.data.json.generator; /** * * @author andrewserff */ public class RandomJsonGenerator { private static final Logger log = LogManager.getLogger(RandomJsonGenerator.class); private SimpleDateFormat iso8601DF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); private Map<String, Object> config; private static JsonGeneratorFactory factory = Json.createGeneratorFactory(null); private Map<String, Object> generatedValues; private JsonUtils jsonUtils; private WorkflowConfig workflowConfig; public RandomJsonGenerator(Map<String, Object> config, WorkflowConfig workflowConfig) { this.config = config; this.workflowConfig = workflowConfig; jsonUtils = new JsonUtils(); TypeHandlerFactory.getInstance().configure(workflowConfig); } public String generateJson() { StringWriter w = new StringWriter(); javax.json.stream.JsonGenerator gen = factory.createGenerator(w); generatedValues = new LinkedHashMap<>(); processProperties(gen, config, ""); gen.flush(); return w.toString(); } public String generateFlattnedJson() throws IOException { String json = generateJson(); return jsonUtils.flattenJson(json); } @SuppressWarnings("unchecked") public Map<String, Object> generateJsonMap() throws IOException { String json = generateJson(); ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(json, Map.class); } public List<Map<String, Object>> generateJsonList() throws IOException { String json = generateJson(); ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(json, List.class); } private javax.json.stream.JsonGenerator processProperties(javax.json.stream.JsonGenerator gen, Map<String, Object> props, String currentContext) { for (String propName : props.keySet()) { Object value = props.get(propName); if (value == null) { generatedValues.put(currentContext + propName, null); addValue(gen, propName, null); } else if (String.class.isAssignableFrom(value.getClass())) { String type = (String) value; handleStringGeneration(type, currentContext, gen, propName); } else if (Map.class.isAssignableFrom(value.getClass())) { //nested object Map<String, Object> nestedProps = (Map<String, Object>) value; if (propName == null) { gen.writeStartObject(); } else { gen.writeStartObject(propName); } String newContext = ""; if (propName != null) { if (currentContext.isEmpty()) { newContext = propName + "."; } else { newContext = currentContext + propName + "."; } } processProperties(gen, nestedProps, newContext); gen.writeEnd(); } else if (List.class.isAssignableFrom(value.getClass())) { //array List<Object> listOfItems = (List<Object>) value; String newContext = ""; if (propName != null) { gen.writeStartArray(propName); if (currentContext.isEmpty()) { newContext = propName; } else { newContext = currentContext + propName; } } else { gen.writeStartArray(); } if (!listOfItems.isEmpty()) { //Check if this is a special function at the start of the array boolean wasSpecialCase = false; if (String.class.isAssignableFrom(listOfItems.get(0).getClass()) && ((String) listOfItems.get(0)).contains("(")) { //special function in array String name = (String) listOfItems.get(0); String specialFunc = null; String[] specialFuncArgs = {}; specialFunc = name.substring(0, name.indexOf("(")); String args = name.substring(name.indexOf("(") + 1, name.indexOf(")")); if (!args.isEmpty()) { specialFuncArgs = args.split(","); } switch (specialFunc) { case "repeat": { int timesToRepeat = 1; if (specialFuncArgs.length == 1) { timesToRepeat = Integer.parseInt(specialFuncArgs[0]); } else { timesToRepeat = new RandomDataGenerator().nextInt(0, 10); } List<Object> subList = listOfItems.subList(1, listOfItems.size()); for (int i = 0; i < timesToRepeat; i++) { processList(subList, gen, newContext); } wasSpecialCase = true; break; } case "random": { //choose one of the items in the list at random List<Object> subList = listOfItems.subList(1, listOfItems.size()); Object item = subList.get(new RandomDataGenerator().nextInt(0, subList.size() - 1)); processItem(item, gen, newContext + "[0]"); wasSpecialCase = true; break; } } } if (!wasSpecialCase) { //it's not a special function, so process it like normal processList(listOfItems, gen, newContext); } } gen.writeEnd(); } else { //literals generatedValues.put(currentContext + propName, value); addValue(gen, propName, value); } } return gen; } protected void handleStringGeneration(String type, String currentContext, JsonGenerator gen, String propName) { if (type.startsWith("this.") || type.startsWith("cur.")) { String refPropName = null; if (type.startsWith("this.")) { refPropName = type.substring("this.".length(), type.length()); } else if (type.startsWith("cur.")) { refPropName = currentContext + type.substring("cur.".length(), type.length()); } Object refPropValue = generatedValues.get(refPropName); if (refPropValue != null) { addValue(gen, propName, refPropValue); } else { log.warn("Sorry, unable to reference property [ " + refPropName + " ]. Maybe it hasn't been generated yet?"); } } else { try {
TypeHandler th = TypeHandlerFactory.getInstance().getTypeHandler(type, generatedValues, currentContext);
1
2023-11-26 10:57:17+00:00
8k
Invadermonky/JustEnoughMagiculture
src/main/java/com/invadermonky/justenoughmagiculture/integrations/jer/mods/JERGrimoireOfGaia.java
[ { "identifier": "JEMConfig", "path": "src/main/java/com/invadermonky/justenoughmagiculture/configs/JEMConfig.java", "snippet": "@LangKey(\"config.\" + JustEnoughMagiculture.MOD_ALIAS + \":\" + JustEnoughMagiculture.MOD_ALIAS)\n@Config(\n modid = JustEnoughMagiculture.MOD_ID,\n name = JustE...
import com.invadermonky.justenoughmagiculture.configs.JEMConfig; import com.invadermonky.justenoughmagiculture.configs.mods.JEMConfigGrimoireOfGaia; import com.invadermonky.justenoughmagiculture.integrations.jei.categories.lootbag.LootBagEntry; import com.invadermonky.justenoughmagiculture.integrations.jer.IJERIntegration; import com.invadermonky.justenoughmagiculture.integrations.jer.JERBase; import com.invadermonky.justenoughmagiculture.integrations.jer.conditionals.JEMConditional; import com.invadermonky.justenoughmagiculture.registry.LootBagRegistry; import com.invadermonky.justenoughmagiculture.util.BiomeHelper; import gaia.GaiaConfig; import gaia.entity.monster.*; import gaia.init.GaiaBlocks; import gaia.init.GaiaItems; import gaia.init.GaiaLootTables; import jeresources.api.conditionals.Conditional; import jeresources.api.conditionals.LightLevel; import jeresources.api.drop.LootDrop; import jeresources.util.LootTableHelper; import net.minecraft.block.Block; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.enchantment.EnchantmentData; import net.minecraft.entity.EntityLiving; import net.minecraft.init.Blocks; import net.minecraft.init.Enchantments; import net.minecraft.init.Items; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemEnchantedBook; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.storage.loot.*; import net.minecraft.world.storage.loot.conditions.LootCondition; import net.minecraft.world.storage.loot.functions.LootFunction; import net.minecraft.world.storage.loot.functions.SetCount; import net.minecraft.world.storage.loot.functions.SetMetadata; import net.minecraftforge.oredict.OreDictionary; import java.util.ArrayList; import java.util.List;
7,168
package com.invadermonky.justenoughmagiculture.integrations.jer.mods; public class JERGrimoireOfGaia extends JERBase implements IJERIntegration { private static JERGrimoireOfGaia instance;
package com.invadermonky.justenoughmagiculture.integrations.jer.mods; public class JERGrimoireOfGaia extends JERBase implements IJERIntegration { private static JERGrimoireOfGaia instance;
private final JEMConfigGrimoireOfGaia.JER jerConfig = JEMConfig.GRIMOIRE_OF_GAIA.JUST_ENOUGH_RESOURCES;
0
2023-11-19 23:09:14+00:00
8k
spring-cloud/spring-functions-catalog
supplier/spring-debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/debezium/DebeziumReactiveConsumerConfiguration.java
[ { "identifier": "DebeziumEngineBuilderAutoConfiguration", "path": "common/spring-debezium-autoconfigure/src/main/java/org/springframework/cloud/fn/common/debezium/DebeziumEngineBuilderAutoConfiguration.java", "snippet": "@AutoConfiguration\n@EnableConfigurationProperties(DebeziumProperties.class)\n@Cond...
import java.lang.reflect.Field; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Consumer; import java.util.function.Supplier; import io.debezium.engine.ChangeEvent; import io.debezium.engine.DebeziumEngine; import io.debezium.engine.DebeziumEngine.Builder; import io.debezium.engine.Header; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Sinks; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.fn.common.debezium.DebeziumEngineBuilderAutoConfiguration; import org.springframework.cloud.fn.common.debezium.DebeziumProperties; import org.springframework.context.annotation.Bean; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.ClassUtils; import org.springframework.util.MimeTypeUtils;
3,679
/* * Copyright 2023-2024 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.cloud.fn.supplier.debezium; /** * The Debezium supplier auto-configuration. * * @author Christian Tzolov * @author Artem Bilan */ @AutoConfiguration(after = DebeziumEngineBuilderAutoConfiguration.class) @EnableConfigurationProperties(DebeziumSupplierProperties.class) @ConditionalOnBean(DebeziumEngine.Builder.class) public class DebeziumReactiveConsumerConfiguration implements BeanClassLoaderAware { private static final Log LOGGER = LogFactory.getLog(DebeziumReactiveConsumerConfiguration.class); /** * ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL. */ public static final String ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL = "org.springframework.kafka.support.KafkaNull"; private Object kafkaNull = null; @Override public void setBeanClassLoader(ClassLoader classLoader) { try { Class<?> clazz = ClassUtils.forName(ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, classLoader); Field field = clazz.getDeclaredField("INSTANCE"); this.kafkaNull = field.get(null); } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException ex) { } } /** * Reactive Streams, single subscriber, sink used to push down the change event * signals received from the Debezium Engine. */ private final Sinks.Many<Message<?>> eventSink = Sinks.many().unicast().onBackpressureError(); /** * Debezium Engine is designed to be submitted to an {@link ExecutorService} for * execution by a single thread, and a running connector can be stopped either by * calling {@code stop()} from another thread or by interrupting the running thread * (e.g., as is the case with {@link ExecutorService#shutdownNow()}). */ private final ExecutorService debeziumExecutor = Executors.newSingleThreadExecutor(); @Bean public DebeziumEngine<ChangeEvent<byte[], byte[]>> debeziumEngine( Consumer<ChangeEvent<byte[], byte[]>> changeEventConsumer, Builder<ChangeEvent<byte[], byte[]>> debeziumEngineBuilder) { return debeziumEngineBuilder.notifying(changeEventConsumer).build(); } @Bean public Supplier<Flux<Message<?>>> debeziumSupplier(DebeziumEngine<ChangeEvent<byte[], byte[]>> debeziumEngine) { return () -> this.eventSink.asFlux() .doOnRequest((r) -> this.debeziumExecutor.execute(debeziumEngine)) .doOnTerminate(this.debeziumExecutor::shutdownNow); } @Bean @ConditionalOnMissingBean
/* * Copyright 2023-2024 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.cloud.fn.supplier.debezium; /** * The Debezium supplier auto-configuration. * * @author Christian Tzolov * @author Artem Bilan */ @AutoConfiguration(after = DebeziumEngineBuilderAutoConfiguration.class) @EnableConfigurationProperties(DebeziumSupplierProperties.class) @ConditionalOnBean(DebeziumEngine.Builder.class) public class DebeziumReactiveConsumerConfiguration implements BeanClassLoaderAware { private static final Log LOGGER = LogFactory.getLog(DebeziumReactiveConsumerConfiguration.class); /** * ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL. */ public static final String ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL = "org.springframework.kafka.support.KafkaNull"; private Object kafkaNull = null; @Override public void setBeanClassLoader(ClassLoader classLoader) { try { Class<?> clazz = ClassUtils.forName(ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, classLoader); Field field = clazz.getDeclaredField("INSTANCE"); this.kafkaNull = field.get(null); } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException ex) { } } /** * Reactive Streams, single subscriber, sink used to push down the change event * signals received from the Debezium Engine. */ private final Sinks.Many<Message<?>> eventSink = Sinks.many().unicast().onBackpressureError(); /** * Debezium Engine is designed to be submitted to an {@link ExecutorService} for * execution by a single thread, and a running connector can be stopped either by * calling {@code stop()} from another thread or by interrupting the running thread * (e.g., as is the case with {@link ExecutorService#shutdownNow()}). */ private final ExecutorService debeziumExecutor = Executors.newSingleThreadExecutor(); @Bean public DebeziumEngine<ChangeEvent<byte[], byte[]>> debeziumEngine( Consumer<ChangeEvent<byte[], byte[]>> changeEventConsumer, Builder<ChangeEvent<byte[], byte[]>> debeziumEngineBuilder) { return debeziumEngineBuilder.notifying(changeEventConsumer).build(); } @Bean public Supplier<Flux<Message<?>>> debeziumSupplier(DebeziumEngine<ChangeEvent<byte[], byte[]>> debeziumEngine) { return () -> this.eventSink.asFlux() .doOnRequest((r) -> this.debeziumExecutor.execute(debeziumEngine)) .doOnTerminate(this.debeziumExecutor::shutdownNow); } @Bean @ConditionalOnMissingBean
public Consumer<ChangeEvent<byte[], byte[]>> changeEventConsumer(DebeziumProperties engineProperties,
1
2023-11-21 04:03:30+00:00
8k
Provismet/ProviHealth
src/main/java/com/provismet/provihealth/hud/BorderRegistry.java
[ { "identifier": "ProviHealthClient", "path": "src/main/java/com/provismet/provihealth/ProviHealthClient.java", "snippet": "public class ProviHealthClient implements ClientModInitializer {\n public static final String MODID = \"provihealth\";\n public static final Logger LOGGER = LoggerFactory.getL...
import java.util.HashMap; import org.jetbrains.annotations.Nullable; import com.provismet.provihealth.ProviHealthClient; import com.provismet.provihealth.config.Options; import net.minecraft.entity.EntityGroup; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.Identifier;
5,117
package com.provismet.provihealth.hud; public class BorderRegistry { private static final HashMap<EntityGroup, Identifier> groupBorders = new HashMap<>(); private static final HashMap<EntityGroup, ItemStack> groupItems = new HashMap<>(); private static final HashMap<EntityType<?>, Identifier> overrideBorders = new HashMap<>(); private static final HashMap<EntityType<?>, ItemStack> overrideItems = new HashMap<>(); private static final Identifier DEFAULT = ProviHealthClient.identifier("textures/gui/healthbars/default.png"); public static boolean registerBorder (EntityGroup group, @Nullable Identifier border, boolean force) { if (group == null) { ProviHealthClient.LOGGER.error("Attempted to register a null object to the border registry."); return false; } else if (groupBorders.containsKey(group) && !force) { return false; } else { groupBorders.put(group, border); return false; } } public static boolean registerItem (EntityGroup group, @Nullable ItemStack item, boolean force) { if (group == null) { ProviHealthClient.LOGGER.error("Attempted to register a null EntityGroup to the icon registry."); return false; } else if (groupItems.containsKey(group) && !force) { return false; } else { groupItems.put(group, item); return true; } } public static boolean registerBorder (EntityType<?> type, @Nullable Identifier border, boolean force) { if (type == null) { ProviHealthClient.LOGGER.error("Attempted to register a null EntityType to the border registry."); return false; } else if (overrideBorders.containsKey(type) && !force) { return false; } else { overrideBorders.put(type, border); return true; } } public static boolean registerItem (EntityType<?> type, @Nullable ItemStack item, boolean force) { if (type == null) { ProviHealthClient.LOGGER.error("Attempted to register a null EntityType to the icon registry."); return false; } else if (overrideItems.containsKey(type) && !force) { return false; } else { overrideItems.put(type, item); return true; } } public static Identifier getBorder (@Nullable LivingEntity entity) {
package com.provismet.provihealth.hud; public class BorderRegistry { private static final HashMap<EntityGroup, Identifier> groupBorders = new HashMap<>(); private static final HashMap<EntityGroup, ItemStack> groupItems = new HashMap<>(); private static final HashMap<EntityType<?>, Identifier> overrideBorders = new HashMap<>(); private static final HashMap<EntityType<?>, ItemStack> overrideItems = new HashMap<>(); private static final Identifier DEFAULT = ProviHealthClient.identifier("textures/gui/healthbars/default.png"); public static boolean registerBorder (EntityGroup group, @Nullable Identifier border, boolean force) { if (group == null) { ProviHealthClient.LOGGER.error("Attempted to register a null object to the border registry."); return false; } else if (groupBorders.containsKey(group) && !force) { return false; } else { groupBorders.put(group, border); return false; } } public static boolean registerItem (EntityGroup group, @Nullable ItemStack item, boolean force) { if (group == null) { ProviHealthClient.LOGGER.error("Attempted to register a null EntityGroup to the icon registry."); return false; } else if (groupItems.containsKey(group) && !force) { return false; } else { groupItems.put(group, item); return true; } } public static boolean registerBorder (EntityType<?> type, @Nullable Identifier border, boolean force) { if (type == null) { ProviHealthClient.LOGGER.error("Attempted to register a null EntityType to the border registry."); return false; } else if (overrideBorders.containsKey(type) && !force) { return false; } else { overrideBorders.put(type, border); return true; } } public static boolean registerItem (EntityType<?> type, @Nullable ItemStack item, boolean force) { if (type == null) { ProviHealthClient.LOGGER.error("Attempted to register a null EntityType to the icon registry."); return false; } else if (overrideItems.containsKey(type) && !force) { return false; } else { overrideItems.put(type, item); return true; } } public static Identifier getBorder (@Nullable LivingEntity entity) {
if (entity == null || !Options.useCustomHudPortraits) return DEFAULT;
1
2023-11-26 02:46:37+00:00
8k
OysterRiverOverdrive/SwerveTemplate
src/main/java/frc/robot/subsystems/DrivetrainSubsystem.java
[ { "identifier": "DriveConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static class DriveConstants {\n // Controller Ports ---\n // Determined here but assigned in the driver station to determine and organize physical ports\n // the controllers are plug into\n public ...
import edu.wpi.first.math.filter.SlewRateLimiter; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.kinematics.ChassisSpeeds; import edu.wpi.first.math.kinematics.SwerveDriveKinematics; import edu.wpi.first.math.kinematics.SwerveModuleState; import edu.wpi.first.util.WPIUtilJNI; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants.DriveConstants; import frc.robot.Constants.RobotConstants; import frc.utils.SwerveModule; import frc.utils.SwerveUtils;
5,076
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems; public class DrivetrainSubsystem extends SubsystemBase { // Create SwerveModules private final SwerveModule m_frontLeft = new SwerveModule( RobotConstants.kFrontLeftDrivingCanId, RobotConstants.kFrontLeftTurningCanId, RobotConstants.kFrontLeftChassisAngularOffset); private final SwerveModule m_frontRight = new SwerveModule( RobotConstants.kFrontRightDrivingCanId, RobotConstants.kFrontRightTurningCanId, RobotConstants.kFrontRightChassisAngularOffset); private final SwerveModule m_rearLeft = new SwerveModule( RobotConstants.kRearLeftDrivingCanId, RobotConstants.kRearLeftTurningCanId, RobotConstants.kBackLeftChassisAngularOffset); private final SwerveModule m_rearRight = new SwerveModule( RobotConstants.kRearRightDrivingCanId, RobotConstants.kRearRightTurningCanId, RobotConstants.kBackRightChassisAngularOffset); // The gyro sensor // private AHRS m_gyro = new AHRS(SerialPort.Port.kUSB1); // Slew rate filter variables for controlling lateral acceleration private double m_currentRotation = 0.0; private double m_currentTranslationDir = 0.0; private double m_currentTranslationMag = 0.0; // Max Speeds private double maxSpeedDrive = DriveConstants.kMaxSpeedMetersPerSecond; private double maxSpeedTurn = DriveConstants.kMaxAngularSpeed; // Drop Down private final SendableChooser<String> m_drivemode = new SendableChooser<>(); private final String khigh = "High Speeds"; private final String kmedium = "Medium Speeds"; private final String kslow = "Low Speed"; private SlewRateLimiter m_magLimiter = new SlewRateLimiter(DriveConstants.kMagnitudeSlewRate); private SlewRateLimiter m_rotLimiter = new SlewRateLimiter(DriveConstants.kRotationalSlewRate); private double m_prevTime = WPIUtilJNI.now() * 1e-6; // Odometry class for tracking robot pose // SwerveDriveOdometry m_odometry = // new SwerveDriveOdometry( // DriveConstants.kDriveKinematics, // Rotation2d.fromDegrees(m_gyro.getAngle()), // new SwerveModulePosition[] { // m_frontLeft.getPosition(), // m_frontRight.getPosition(), // m_rearLeft.getPosition(), // m_rearRight.getPosition() // }); /** Creates a new DriveSubsystem. */ public DrivetrainSubsystem() { m_drivemode.setDefaultOption("Medium Speed", kmedium); m_drivemode.addOption("Slow Speeds (Demo Mode)", kslow); m_drivemode.addOption("High Speeds", khigh); SmartDashboard.putData("Driver Config", m_drivemode); } /** * Returns the currently-estimated pose of the robot. * * @return The pose. */ // public Pose2d getPose() { // return m_odometry.getPoseMeters(); // } /** * Resets the odometry to the specified pose. * * @param pose The pose to which to set the odometry. */ // public void resetOdometry(Pose2d pose) { // m_odometry.resetPosition( // Rotation2d.fromDegrees(m_gyro.getAngle()), // new SwerveModulePosition[] { // m_frontLeft.getPosition(), // m_frontRight.getPosition(), // m_rearLeft.getPosition(), // m_rearRight.getPosition() // }, // pose); // } /** * Method to drive the robot using joystick info. * * @param xSpeed Speed of the robot in the x direction (forward). * @param ySpeed Speed of the robot in the y direction (sideways). * @param rot Angular rate of the robot. * @param fieldRelative Whether the provided x and y speeds are relative to the field. * @param rateLimit Whether to enable rate limiting for smoother control. */ public void drive( double xSpeed, double ySpeed, double rot, boolean fieldRelative, boolean rateLimit) { double xSpeedCommanded; double ySpeedCommanded; if (rateLimit) { // Convert XY to polar for rate limiting double inputTranslationDir = Math.atan2(ySpeed, xSpeed); double inputTranslationMag = Math.sqrt(Math.pow(xSpeed, 2) + Math.pow(ySpeed, 2)); // Calculate the direction slew rate based on an estimate of the lateral acceleration double directionSlewRate; if (m_currentTranslationMag != 0.0) { directionSlewRate = Math.abs(DriveConstants.kDirectionSlewRate / m_currentTranslationMag); } else { directionSlewRate = 500.0; // some high number that means the slew rate is effectively instantaneous } double currentTime = WPIUtilJNI.now() * 1e-6; double elapsedTime = currentTime - m_prevTime;
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems; public class DrivetrainSubsystem extends SubsystemBase { // Create SwerveModules private final SwerveModule m_frontLeft = new SwerveModule( RobotConstants.kFrontLeftDrivingCanId, RobotConstants.kFrontLeftTurningCanId, RobotConstants.kFrontLeftChassisAngularOffset); private final SwerveModule m_frontRight = new SwerveModule( RobotConstants.kFrontRightDrivingCanId, RobotConstants.kFrontRightTurningCanId, RobotConstants.kFrontRightChassisAngularOffset); private final SwerveModule m_rearLeft = new SwerveModule( RobotConstants.kRearLeftDrivingCanId, RobotConstants.kRearLeftTurningCanId, RobotConstants.kBackLeftChassisAngularOffset); private final SwerveModule m_rearRight = new SwerveModule( RobotConstants.kRearRightDrivingCanId, RobotConstants.kRearRightTurningCanId, RobotConstants.kBackRightChassisAngularOffset); // The gyro sensor // private AHRS m_gyro = new AHRS(SerialPort.Port.kUSB1); // Slew rate filter variables for controlling lateral acceleration private double m_currentRotation = 0.0; private double m_currentTranslationDir = 0.0; private double m_currentTranslationMag = 0.0; // Max Speeds private double maxSpeedDrive = DriveConstants.kMaxSpeedMetersPerSecond; private double maxSpeedTurn = DriveConstants.kMaxAngularSpeed; // Drop Down private final SendableChooser<String> m_drivemode = new SendableChooser<>(); private final String khigh = "High Speeds"; private final String kmedium = "Medium Speeds"; private final String kslow = "Low Speed"; private SlewRateLimiter m_magLimiter = new SlewRateLimiter(DriveConstants.kMagnitudeSlewRate); private SlewRateLimiter m_rotLimiter = new SlewRateLimiter(DriveConstants.kRotationalSlewRate); private double m_prevTime = WPIUtilJNI.now() * 1e-6; // Odometry class for tracking robot pose // SwerveDriveOdometry m_odometry = // new SwerveDriveOdometry( // DriveConstants.kDriveKinematics, // Rotation2d.fromDegrees(m_gyro.getAngle()), // new SwerveModulePosition[] { // m_frontLeft.getPosition(), // m_frontRight.getPosition(), // m_rearLeft.getPosition(), // m_rearRight.getPosition() // }); /** Creates a new DriveSubsystem. */ public DrivetrainSubsystem() { m_drivemode.setDefaultOption("Medium Speed", kmedium); m_drivemode.addOption("Slow Speeds (Demo Mode)", kslow); m_drivemode.addOption("High Speeds", khigh); SmartDashboard.putData("Driver Config", m_drivemode); } /** * Returns the currently-estimated pose of the robot. * * @return The pose. */ // public Pose2d getPose() { // return m_odometry.getPoseMeters(); // } /** * Resets the odometry to the specified pose. * * @param pose The pose to which to set the odometry. */ // public void resetOdometry(Pose2d pose) { // m_odometry.resetPosition( // Rotation2d.fromDegrees(m_gyro.getAngle()), // new SwerveModulePosition[] { // m_frontLeft.getPosition(), // m_frontRight.getPosition(), // m_rearLeft.getPosition(), // m_rearRight.getPosition() // }, // pose); // } /** * Method to drive the robot using joystick info. * * @param xSpeed Speed of the robot in the x direction (forward). * @param ySpeed Speed of the robot in the y direction (sideways). * @param rot Angular rate of the robot. * @param fieldRelative Whether the provided x and y speeds are relative to the field. * @param rateLimit Whether to enable rate limiting for smoother control. */ public void drive( double xSpeed, double ySpeed, double rot, boolean fieldRelative, boolean rateLimit) { double xSpeedCommanded; double ySpeedCommanded; if (rateLimit) { // Convert XY to polar for rate limiting double inputTranslationDir = Math.atan2(ySpeed, xSpeed); double inputTranslationMag = Math.sqrt(Math.pow(xSpeed, 2) + Math.pow(ySpeed, 2)); // Calculate the direction slew rate based on an estimate of the lateral acceleration double directionSlewRate; if (m_currentTranslationMag != 0.0) { directionSlewRate = Math.abs(DriveConstants.kDirectionSlewRate / m_currentTranslationMag); } else { directionSlewRate = 500.0; // some high number that means the slew rate is effectively instantaneous } double currentTime = WPIUtilJNI.now() * 1e-6; double elapsedTime = currentTime - m_prevTime;
double angleDif = SwerveUtils.AngleDifference(inputTranslationDir, m_currentTranslationDir);
3
2023-11-19 18:40:10+00:00
8k
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,554
/* * 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;
/* * 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());
1
2023-12-28 09:13:24+00:00
8k
EnigmaGuest/fnk-server
service-common/service-common-db/src/main/java/fun/isite/service/common/db/impl/BaseService.java
[ { "identifier": "LogicException", "path": "service-common/service-common-bean/src/main/java/fun/isite/service/common/bean/exception/LogicException.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\npublic class LogicException extends RuntimeException{\n private String message;\n\n pri...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import fun.isite.service.common.bean.exception.LogicException; import fun.isite.service.common.db.dto.SplitPageDTO; import fun.isite.service.common.db.entity.BaseEntity; import fun.isite.service.common.db.interf.CustomBasicPageQuery; import fun.isite.service.common.db.service.IBaseService; import fun.isite.service.common.db.vo.PageVO; import fun.isite.service.common.tools.lang.AssertUtils; import fun.isite.service.common.tools.utils.RedisUtils; import jakarta.annotation.Nullable; import org.springframework.beans.BeanUtils; import org.springframework.transaction.annotation.Transactional; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer;
6,712
package fun.isite.service.common.db.impl; /** * @author Enigma */ public class BaseService<M extends BaseMapper<T>, T extends BaseEntity<T>> extends ServiceImpl<M, T> implements IBaseService<T> { public final static String[] BASE_ENTITY_FIELDS = {"id", "create_time", "update_time", "deleted"}; public final static String LIMIT_ONE = "limit 1"; @Override public T getFirst(QueryWrapper<T> queryWrapper) { if (queryWrapper != null) { queryWrapper.last(LIMIT_ONE); } return this.getOne(queryWrapper); } @Override public T getById(Serializable id, @Nullable Consumer<LambdaQueryWrapper<T>> wrapperConsumer) { LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass()) .eq(T::getId, id); if(wrapperConsumer!=null){ wrapperConsumer.accept(wrapper); } wrapper.last(LIMIT_ONE); return this.getOne(wrapper); } @Override public T getFirst(LambdaQueryWrapper<T> queryWrapper) { if (queryWrapper != null) { queryWrapper.last(LIMIT_ONE); } return this.getOne(queryWrapper); } @Override public T getByField(SFunction<T, ?> field, String value) { return this.getFirst(new LambdaQueryWrapper<T>().eq(field, value)); } @Override
package fun.isite.service.common.db.impl; /** * @author Enigma */ public class BaseService<M extends BaseMapper<T>, T extends BaseEntity<T>> extends ServiceImpl<M, T> implements IBaseService<T> { public final static String[] BASE_ENTITY_FIELDS = {"id", "create_time", "update_time", "deleted"}; public final static String LIMIT_ONE = "limit 1"; @Override public T getFirst(QueryWrapper<T> queryWrapper) { if (queryWrapper != null) { queryWrapper.last(LIMIT_ONE); } return this.getOne(queryWrapper); } @Override public T getById(Serializable id, @Nullable Consumer<LambdaQueryWrapper<T>> wrapperConsumer) { LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass()) .eq(T::getId, id); if(wrapperConsumer!=null){ wrapperConsumer.accept(wrapper); } wrapper.last(LIMIT_ONE); return this.getOne(wrapper); } @Override public T getFirst(LambdaQueryWrapper<T> queryWrapper) { if (queryWrapper != null) { queryWrapper.last(LIMIT_ONE); } return this.getOne(queryWrapper); } @Override public T getByField(SFunction<T, ?> field, String value) { return this.getFirst(new LambdaQueryWrapper<T>().eq(field, value)); } @Override
public PageVO<T> basicPage(SplitPageDTO dto, SFunction<T, ?> orderByField, CustomBasicPageQuery<T> customQuery) {
1
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,466
package org.wowtools.hppt.cc; /** * @author liuyu * @date 2023/12/20 */ @Slf4j public class StartCc {
package org.wowtools.hppt.cc; /** * @author liuyu * @date 2023/12/20 */ @Slf4j public class StartCc {
public static CcConfig config;
0
2023-12-22 14:14:27+00:00
8k
3arthqu4ke/phobot
src/main/java/me/earth/phobot/modules/combat/AutoTrap.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.SurroundService; import me.earth.phobot.services.inventory.InventoryContext; import me.earth.phobot.util.ResetUtil; import me.earth.phobot.util.entity.EntityUtil; 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.entity.player.Player; 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.Set; import java.util.concurrent.ConcurrentHashMap;
6,701
package me.earth.phobot.modules.combat; @Getter public class AutoTrap extends BlockPlacingModule implements TrapsPlayers { private final Setting<PacketRotationMode> packetRotations = constant("PacketRotations", PacketRotationMode.None, "Sends additional packets to rotate, might lag back," + "but allows you to place more blocks in one tick. With Mode Surrounded this will only happen when you are surrounded, so that you do not have to worry about lagbacks."); 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); private final SurroundService surroundService; public AutoTrap(Phobot phobot, SurroundService surroundService) { super(phobot, phobot.getBlockPlacer(), "AutoTrap", Categories.COMBAT, "Traps other players.", 5); this.surroundService = surroundService; listen(getBlackListClearListener()); ResetUtil.disableOnRespawnAndWorldChange(this, mc); } @Override protected void updatePlacements(InventoryContext context, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { Block block = context.findBlock(Blocks.OBSIDIAN, Blocks.CRYING_OBSIDIAN); if (block == null) { return; } Set<BlockPos> allCurrentPositions = new HashSet<>(); for (Player enemy : level.players()) {
package me.earth.phobot.modules.combat; @Getter public class AutoTrap extends BlockPlacingModule implements TrapsPlayers { private final Setting<PacketRotationMode> packetRotations = constant("PacketRotations", PacketRotationMode.None, "Sends additional packets to rotate, might lag back," + "but allows you to place more blocks in one tick. With Mode Surrounded this will only happen when you are surrounded, so that you do not have to worry about lagbacks."); 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); private final SurroundService surroundService; public AutoTrap(Phobot phobot, SurroundService surroundService) { super(phobot, phobot.getBlockPlacer(), "AutoTrap", Categories.COMBAT, "Traps other players.", 5); this.surroundService = surroundService; listen(getBlackListClearListener()); ResetUtil.disableOnRespawnAndWorldChange(this, mc); } @Override protected void updatePlacements(InventoryContext context, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) { Block block = context.findBlock(Blocks.OBSIDIAN, Blocks.CRYING_OBSIDIAN); if (block == null) { return; } Set<BlockPos> allCurrentPositions = new HashSet<>(); for (Player enemy : level.players()) {
if (EntityUtil.isEnemyInRange(getPingBypass(), player, enemy, 7.0)) {
7
2023-12-22 14:32:16+00:00
8k
ArmanKhanDev/FakepixelDungeonHelper
src/main/java/io/github/quantizr/handlers/OpenLink.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 net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.event.ClickEvent; import net.minecraft.util.ChatComponentText; import net.minecraft.util.EnumChatFormatting; import net.minecraftforge.client.ClientCommandHandler; import net.minecraftforge.fml.client.FMLClientHandler; import java.awt.*; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List;
5,523
/* 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.handlers; public class OpenLink { public static void checkForLink(String type){ Minecraft mc = Minecraft.getMinecraft(); EntityPlayerSP player = mc.thePlayer; if (!AutoRoom.chatToggled && !AutoRoom.guiToggled){ List<String> autoText = AutoRoom.autoText(); if (autoText != null) { AutoRoom.autoTextOutput = autoText; } } if (AutoRoom.lastRoomHash == null) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: You do not appear to be in a detected Dungeon room right now.")); return; } if (AutoRoom.lastRoomJson == null) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: This command does not work when the current room is detected as one of multiple.")); return; } if (AutoRoom.lastRoomJson.get("dsg").getAsString().equals("null") && AutoRoom.lastRoomJson.get("sbp") == null) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: There are no channels/images for this room.")); return; } switch (type) { case "gui":
/* 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.handlers; public class OpenLink { public static void checkForLink(String type){ Minecraft mc = Minecraft.getMinecraft(); EntityPlayerSP player = mc.thePlayer; if (!AutoRoom.chatToggled && !AutoRoom.guiToggled){ List<String> autoText = AutoRoom.autoText(); if (autoText != null) { AutoRoom.autoTextOutput = autoText; } } if (AutoRoom.lastRoomHash == null) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: You do not appear to be in a detected Dungeon room right now.")); return; } if (AutoRoom.lastRoomJson == null) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: This command does not work when the current room is detected as one of multiple.")); return; } if (AutoRoom.lastRoomJson.get("dsg").getAsString().equals("null") && AutoRoom.lastRoomJson.get("sbp") == null) { player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "FDH: There are no channels/images for this room.")); return; } switch (type) { case "gui":
DungeonRooms.guiToOpen = "link";
0
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,234
// 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, () -> chzzk.getFollowingStatus("FOLLOWED_CHANNEL_1")); } @Test void gettingFollowStatus() throws IOException { AtomicReference<ChzzkChannelFollowingData> followingStatus = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> followingStatus.set(loginChzzk.getFollowingStatus(FOLLOWED_CHANNEL_1))); System.out.println(followingStatus); Assertions.assertEquals(followingStatus.get().isFollowing(), true); Assertions.assertDoesNotThrow(() -> followingStatus.set(loginChzzk.getFollowingStatus(UNFOLLOWED_CHANNEL))); System.out.println(followingStatus); Assertions.assertEquals(followingStatus.get().isFollowing(), false); } @Test void gettingUserInfo() throws IOException, NotLoggedInException {
// 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, () -> chzzk.getFollowingStatus("FOLLOWED_CHANNEL_1")); } @Test void gettingFollowStatus() throws IOException { AtomicReference<ChzzkChannelFollowingData> followingStatus = new AtomicReference<>(); Assertions.assertDoesNotThrow(() -> followingStatus.set(loginChzzk.getFollowingStatus(FOLLOWED_CHANNEL_1))); System.out.println(followingStatus); Assertions.assertEquals(followingStatus.get().isFollowing(), true); Assertions.assertDoesNotThrow(() -> followingStatus.set(loginChzzk.getFollowingStatus(UNFOLLOWED_CHANNEL))); System.out.println(followingStatus); Assertions.assertEquals(followingStatus.get().isFollowing(), false); } @Test void gettingUserInfo() throws IOException, NotLoggedInException {
ChzzkUser currentUser = loginChzzk.getLoggedUser();
5
2023-12-30 20:01:23+00:00
8k
lonelytransistor/LauncherAndroidTV
app/src/main/java/net/lonelytransistor/launcher/LauncherBar.java
[ { "identifier": "MovieRepo", "path": "app/src/main/java/net/lonelytransistor/launcher/repos/MovieRepo.java", "snippet": "public class MovieRepo implements Serializable {\n private static final String TAG = \"MovieRepo\";\n private static final String PREFERENCE_KEY = \"MOVIE_REPO\";\n private s...
import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.drawable.Drawable; import android.net.Uri; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import net.lonelytransistor.commonlib.OutlinedTextView; import net.lonelytransistor.commonlib.ProgressDrawable; import net.lonelytransistor.launcher.repos.MovieRepo; import net.lonelytransistor.launcher.repos.MovieTitle; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit;
5,385
} else { currentlyVisible = v; ScheduledFuture<?> sch = delayedSchedule.put(v, delayedExecutor.schedule(new FutureTask<>( () -> { uiExecutor.execute(() -> animateFocus(v, true)); return null; }), DELAY, TimeUnit.MILLISECONDS)); if (sch != null) sch.cancel(true); } }; protected boolean onKey(View v, int keyCode, KeyEvent event) { return keyListenerRoot.onKey(v, keyCode, event); } private final Map<Integer, BarViewHolder> positionToViewHolder = new HashMap<>(); public boolean requestSelection(int position) { for (RecyclerView v : rootViews) { v.setDescendantFocusability(v == rootView ? FOCUS_AFTER_DESCENDANTS : FOCUS_BLOCK_DESCENDANTS); } rootView.smoothScrollToPosition(position); BarViewHolder vh = positionToViewHolder.get(Math.min(position, getItemCount()-1)); if (vh != null) { vh.itemView.requestFocus(); return vh.itemView.hasFocus(); } else { return false; } } @Override final public void onBindViewHolder(@NonNull BarViewHolder vh, int position) { positionToViewHolder.put(position, vh); vh.itemView.setScaleX(1.0f); vh.itemView.setScaleY(1.0f); onBindView(vh, position); } abstract public void onBindView(@NonNull BarViewHolder holder, int position); @NonNull @Override final public BarViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { BarViewHolder vh = onCreateViewHolder(parent); vh.itemView.setOnFocusChangeListener(focusListener); return vh; } @NonNull abstract public BarViewHolder onCreateViewHolder(@NonNull ViewGroup parent); } private static class TopBarViewHolder extends BarViewHolder { final ConstraintLayout parent; final ImageView mainImage; final ImageView statusIcon; final OutlinedTextView scoreText; final ImageView scoreIcon; final OutlinedTextView popularityText; final ImageView popularityIcon; final TextView primaryText; final TextView secondaryText; TopBarViewHolder(@NonNull View itemView) { super(itemView); mainImage = itemView.findViewById(R.id.main_image); statusIcon = itemView.findViewById(R.id.status_icon); scoreText = itemView.findViewById(R.id.score); scoreIcon = itemView.findViewById(R.id.score_icon); popularityText = itemView.findViewById(R.id.popularity); popularityIcon = itemView.findViewById(R.id.popularity_icon); primaryText = itemView.findViewById(R.id.primary_text); secondaryText = itemView.findViewById(R.id.secondary_text); parent = (ConstraintLayout) mainImage.getParent(); } } private class TopBarAdapter extends BarAdapter { private final int foldedCardHeight; private final int unfoldedCardHeight; private final Map<Integer, List<MovieCard>> rows = new HashMap<>(); private List<MovieCard> currentRow; private int currentRowIx = 0; private int globalCount = 0; private int lastActiveIx = 0; TopBarAdapter() { super(LauncherBar.this.getContext(), topBar); ConstraintLayout.LayoutParams lp; View card = LayoutInflater.from(LauncherBar.this.getContext()) .inflate(R.layout.top_card_view, null, false); lp = (ConstraintLayout.LayoutParams) card.findViewById(R.id.main_image).getLayoutParams(); int mainImageHeight = lp.height; lp = (ConstraintLayout.LayoutParams) card.findViewById(R.id.primary_text).getLayoutParams(); int primaryTextHeight = lp.height; lp = (ConstraintLayout.LayoutParams) card.findViewById(R.id.secondary_text).getLayoutParams(); int secondaryTextHeight = lp.height; foldedCardHeight = mainImageHeight + primaryTextHeight + card.getPaddingTop() + card.getPaddingBottom(); unfoldedCardHeight = foldedCardHeight + secondaryTextHeight; lp = (ConstraintLayout.LayoutParams) topBar.getLayoutParams(); lp.height = (int) ((foldedCardHeight + secondaryTextHeight) * 1.1f); topBar.setLayoutParams(lp); } private final OnKeyListener keyListenerInternal = (v, keyCode, event) -> { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_DOWN_LEFT: case KeyEvent.KEYCODE_DPAD_DOWN_RIGHT: case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_DOWN: case KeyEvent.KEYCODE_CHANNEL_DOWN: bottomBarAdapter.restoreFocus(); case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_UP_LEFT: case KeyEvent.KEYCODE_DPAD_UP_RIGHT: case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_UP: case KeyEvent.KEYCODE_CHANNEL_UP: return true; } return onKey(v, keyCode, event); }; private final OnClickListener clickListenerInternal = v -> { MovieCard card = currentRow.get(lastActiveIx); if (card.clickIntent != null && card.clickIntent.getAction() != null && !card.clickIntent.getAction().isEmpty()) { Log.i(TAG, "intent: " + card.clickIntent + card.clickIntent.getDataString());
package net.lonelytransistor.launcher; public class LauncherBar extends FrameLayout { private static final String TAG = "LauncherActivity"; private static final int DELAY = 200; private static final int ANIMATION_DURATION = 200; public LauncherBar(Context context) { super(context); constructor(); } public LauncherBar(Context context, @Nullable AttributeSet attrs) { super(context, attrs); constructor(); } public LauncherBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); constructor(); } public LauncherBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); constructor(); } private OnKeyListener keyListenerRoot = (v, keyCode, event) -> false; @Override public void setOnKeyListener(OnKeyListener l) { super.setOnKeyListener(l); keyListenerRoot = l; } private OnClickListener clickListenerRoot = (v) -> {}; @Override public void setOnClickListener(@Nullable OnClickListener l) { super.setOnClickListener(l); clickListenerRoot = l; } private static abstract class BarViewHolder extends RecyclerView.ViewHolder { BarViewHolder(@NonNull View itemView) { super(itemView); } } private abstract class BarAdapter extends RecyclerView.Adapter<BarViewHolder> { BarAdapter(Context ctx, RecyclerView v) { super(); uiExecutor = ctx.getMainExecutor(); rootView = v; rootViews.add(v); } private Executor uiExecutor; private final RecyclerView rootView; private static final List<RecyclerView> rootViews = new ArrayList<>(); View currentlyVisible = null; final ScheduledExecutorService delayedExecutor = Executors.newScheduledThreadPool(4); Map<View, ScheduledFuture<?>> delayedSchedule = new HashMap<>(); public void onFocused(BarViewHolder vh, boolean hasFocus) {} private void animateFocus(View v, boolean hasFocus) { animatedViews.add(v); v.animate() .scaleY(hasFocus ? 1.1f : 1.0f) .scaleX(hasFocus ? 1.1f : 1.0f) .setDuration(ANIMATION_DURATION) .setListener(new AnimatorListenerAdapter() { void reset() { v.setScaleX(hasFocus ? 1.1f : 1.0f); v.setScaleY(hasFocus ? 1.1f : 1.0f); animatedViews.remove(v); if (hasFocus && !v.hasFocus()) { animateFocus(v, false); } } @Override public void onAnimationCancel(Animator animation) { reset(); } @Override public void onAnimationEnd(Animator animation) { reset(); } @Override public void onAnimationPause(Animator animation) { reset(); } }) .start(); if ((hasFocus && v.getScaleY() == 1.0f) || (!hasFocus && v.getScaleY() == 1.1f)) { BarViewHolder vh; try { vh = (BarViewHolder) rootView.getChildViewHolder(v); } catch (Exception e) { Log.w(TAG, "Hover out of bounds."); return; } onFocused(vh, hasFocus); } } private final List<View> animatedViews = new ArrayList<>(); private final View.OnFocusChangeListener focusListener = (v, hasFocus) -> { int padding = v.getPaddingBottom(); v.setBackgroundResource(hasFocus ? R.drawable.border_hover: R.drawable.border_normal); v.setPadding(padding,padding,padding,padding); if (!hasFocus) { ScheduledFuture<?> sch = delayedSchedule.get(v); if (sch != null) sch.cancel(true); v.clearAnimation(); if (!animatedViews.contains(v)) { animateFocus(v, false); } } else { currentlyVisible = v; ScheduledFuture<?> sch = delayedSchedule.put(v, delayedExecutor.schedule(new FutureTask<>( () -> { uiExecutor.execute(() -> animateFocus(v, true)); return null; }), DELAY, TimeUnit.MILLISECONDS)); if (sch != null) sch.cancel(true); } }; protected boolean onKey(View v, int keyCode, KeyEvent event) { return keyListenerRoot.onKey(v, keyCode, event); } private final Map<Integer, BarViewHolder> positionToViewHolder = new HashMap<>(); public boolean requestSelection(int position) { for (RecyclerView v : rootViews) { v.setDescendantFocusability(v == rootView ? FOCUS_AFTER_DESCENDANTS : FOCUS_BLOCK_DESCENDANTS); } rootView.smoothScrollToPosition(position); BarViewHolder vh = positionToViewHolder.get(Math.min(position, getItemCount()-1)); if (vh != null) { vh.itemView.requestFocus(); return vh.itemView.hasFocus(); } else { return false; } } @Override final public void onBindViewHolder(@NonNull BarViewHolder vh, int position) { positionToViewHolder.put(position, vh); vh.itemView.setScaleX(1.0f); vh.itemView.setScaleY(1.0f); onBindView(vh, position); } abstract public void onBindView(@NonNull BarViewHolder holder, int position); @NonNull @Override final public BarViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { BarViewHolder vh = onCreateViewHolder(parent); vh.itemView.setOnFocusChangeListener(focusListener); return vh; } @NonNull abstract public BarViewHolder onCreateViewHolder(@NonNull ViewGroup parent); } private static class TopBarViewHolder extends BarViewHolder { final ConstraintLayout parent; final ImageView mainImage; final ImageView statusIcon; final OutlinedTextView scoreText; final ImageView scoreIcon; final OutlinedTextView popularityText; final ImageView popularityIcon; final TextView primaryText; final TextView secondaryText; TopBarViewHolder(@NonNull View itemView) { super(itemView); mainImage = itemView.findViewById(R.id.main_image); statusIcon = itemView.findViewById(R.id.status_icon); scoreText = itemView.findViewById(R.id.score); scoreIcon = itemView.findViewById(R.id.score_icon); popularityText = itemView.findViewById(R.id.popularity); popularityIcon = itemView.findViewById(R.id.popularity_icon); primaryText = itemView.findViewById(R.id.primary_text); secondaryText = itemView.findViewById(R.id.secondary_text); parent = (ConstraintLayout) mainImage.getParent(); } } private class TopBarAdapter extends BarAdapter { private final int foldedCardHeight; private final int unfoldedCardHeight; private final Map<Integer, List<MovieCard>> rows = new HashMap<>(); private List<MovieCard> currentRow; private int currentRowIx = 0; private int globalCount = 0; private int lastActiveIx = 0; TopBarAdapter() { super(LauncherBar.this.getContext(), topBar); ConstraintLayout.LayoutParams lp; View card = LayoutInflater.from(LauncherBar.this.getContext()) .inflate(R.layout.top_card_view, null, false); lp = (ConstraintLayout.LayoutParams) card.findViewById(R.id.main_image).getLayoutParams(); int mainImageHeight = lp.height; lp = (ConstraintLayout.LayoutParams) card.findViewById(R.id.primary_text).getLayoutParams(); int primaryTextHeight = lp.height; lp = (ConstraintLayout.LayoutParams) card.findViewById(R.id.secondary_text).getLayoutParams(); int secondaryTextHeight = lp.height; foldedCardHeight = mainImageHeight + primaryTextHeight + card.getPaddingTop() + card.getPaddingBottom(); unfoldedCardHeight = foldedCardHeight + secondaryTextHeight; lp = (ConstraintLayout.LayoutParams) topBar.getLayoutParams(); lp.height = (int) ((foldedCardHeight + secondaryTextHeight) * 1.1f); topBar.setLayoutParams(lp); } private final OnKeyListener keyListenerInternal = (v, keyCode, event) -> { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_DOWN_LEFT: case KeyEvent.KEYCODE_DPAD_DOWN_RIGHT: case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_DOWN: case KeyEvent.KEYCODE_CHANNEL_DOWN: bottomBarAdapter.restoreFocus(); case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_UP_LEFT: case KeyEvent.KEYCODE_DPAD_UP_RIGHT: case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_UP: case KeyEvent.KEYCODE_CHANNEL_UP: return true; } return onKey(v, keyCode, event); }; private final OnClickListener clickListenerInternal = v -> { MovieCard card = currentRow.get(lastActiveIx); if (card.clickIntent != null && card.clickIntent.getAction() != null && !card.clickIntent.getAction().isEmpty()) { Log.i(TAG, "intent: " + card.clickIntent + card.clickIntent.getDataString());
for (MovieTitle t : MovieRepo.getWatchNext()) {
1
2023-12-28 18:24:12+00:00
8k
Patbox/GlideAway
src/main/java/eu/pb4/glideaway/item/WindInABottleItem.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.factorytools.api.item.ModeledItem; import eu.pb4.glideaway.entity.GliderEntity; import eu.pb4.glideaway.mixin.ServerPlayNetworkHandlerAccessor; import net.fabricmc.fabric.api.event.player.UseEntityCallback; import net.minecraft.advancement.criterion.Criteria; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.projectile.SmallFireballEntity; import net.minecraft.entity.projectile.WindChargeEntity; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.particle.ParticleTypes; import net.minecraft.potion.PotionUtil; import net.minecraft.potion.Potions; import net.minecraft.resource.featuretoggle.FeatureFlags; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.world.ServerWorld; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.stat.Stats; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.TypedActionResult; import net.minecraft.util.hit.EntityHitResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraft.world.event.GameEvent;
5,011
package eu.pb4.glideaway.item; public class WindInABottleItem extends ModeledItem { private final boolean consume; public WindInABottleItem(Settings settings, boolean consume) { super(settings); this.consume = consume; } public ActionResult useOnEntityEvent(PlayerEntity user, World world, Hand hand, Entity entity, EntityHitResult result) { var stack = user.getStackInHand(hand); var hasWindCharge = world.getEnabledFeatures().contains(FeatureFlags.UPDATE_1_21); if (!world.isClient && hasWindCharge && entity instanceof WindChargeEntity windChargeEntity && stack.isOf(Items.GLASS_BOTTLE)) { world.playSound(null, user.getX(), user.getY(), user.getZ(), SoundEvents.ITEM_BOTTLE_FILL_DRAGONBREATH, SoundCategory.NEUTRAL, 1.0F, 1.0F); world.emitGameEvent(user, GameEvent.FLUID_PICKUP, user.getPos()); if (user instanceof ServerPlayerEntity serverPlayerEntity) { Criteria.PLAYER_INTERACTED_WITH_ENTITY.trigger(serverPlayerEntity, stack, windChargeEntity); serverPlayerEntity.incrementStat(Stats.USED.getOrCreateStat(this)); } stack.decrement(1); user.getInventory().offerOrDrop(new ItemStack(this)); windChargeEntity.discard(); return ActionResult.SUCCESS; } else if (!world.isClient && !hasWindCharge && entity instanceof SmallFireballEntity fireballEntity && stack.isOf(Items.POTION) && PotionUtil.getPotion(stack) == Potions.EMPTY) { world.playSound(null, user.getX(), user.getY(), user.getZ(), SoundEvents.ITEM_BOTTLE_FILL_DRAGONBREATH, SoundCategory.NEUTRAL, 1.0F, 1.0F); world.emitGameEvent(user, GameEvent.FLUID_PICKUP, user.getPos()); if (user instanceof ServerPlayerEntity serverPlayerEntity) { Criteria.PLAYER_INTERACTED_WITH_ENTITY.trigger(serverPlayerEntity, stack, fireballEntity); serverPlayerEntity.incrementStat(Stats.USED.getOrCreateStat(this)); } stack.decrement(1); user.getInventory().offerOrDrop(new ItemStack(this)); fireballEntity.discard(); return ActionResult.SUCCESS; } return ActionResult.PASS; } @Override public boolean hasGlint(ItemStack stack) { return !this.consume; } @Override public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
package eu.pb4.glideaway.item; public class WindInABottleItem extends ModeledItem { private final boolean consume; public WindInABottleItem(Settings settings, boolean consume) { super(settings); this.consume = consume; } public ActionResult useOnEntityEvent(PlayerEntity user, World world, Hand hand, Entity entity, EntityHitResult result) { var stack = user.getStackInHand(hand); var hasWindCharge = world.getEnabledFeatures().contains(FeatureFlags.UPDATE_1_21); if (!world.isClient && hasWindCharge && entity instanceof WindChargeEntity windChargeEntity && stack.isOf(Items.GLASS_BOTTLE)) { world.playSound(null, user.getX(), user.getY(), user.getZ(), SoundEvents.ITEM_BOTTLE_FILL_DRAGONBREATH, SoundCategory.NEUTRAL, 1.0F, 1.0F); world.emitGameEvent(user, GameEvent.FLUID_PICKUP, user.getPos()); if (user instanceof ServerPlayerEntity serverPlayerEntity) { Criteria.PLAYER_INTERACTED_WITH_ENTITY.trigger(serverPlayerEntity, stack, windChargeEntity); serverPlayerEntity.incrementStat(Stats.USED.getOrCreateStat(this)); } stack.decrement(1); user.getInventory().offerOrDrop(new ItemStack(this)); windChargeEntity.discard(); return ActionResult.SUCCESS; } else if (!world.isClient && !hasWindCharge && entity instanceof SmallFireballEntity fireballEntity && stack.isOf(Items.POTION) && PotionUtil.getPotion(stack) == Potions.EMPTY) { world.playSound(null, user.getX(), user.getY(), user.getZ(), SoundEvents.ITEM_BOTTLE_FILL_DRAGONBREATH, SoundCategory.NEUTRAL, 1.0F, 1.0F); world.emitGameEvent(user, GameEvent.FLUID_PICKUP, user.getPos()); if (user instanceof ServerPlayerEntity serverPlayerEntity) { Criteria.PLAYER_INTERACTED_WITH_ENTITY.trigger(serverPlayerEntity, stack, fireballEntity); serverPlayerEntity.incrementStat(Stats.USED.getOrCreateStat(this)); } stack.decrement(1); user.getInventory().offerOrDrop(new ItemStack(this)); fireballEntity.discard(); return ActionResult.SUCCESS; } return ActionResult.PASS; } @Override public boolean hasGlint(ItemStack stack) { return !this.consume; } @Override public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
if (user.getRootVehicle() instanceof GliderEntity glider) {
0
2023-12-22 11:00:52+00:00
8k
danielfeitopin/MUNICS-SAPP-P1
src/main/java/es/storeapp/web/interceptors/AutoLoginInterceptor.java
[ { "identifier": "User", "path": "src/main/java/es/storeapp/business/entities/User.java", "snippet": "@Entity(name = Constants.USER_ENTITY)\n@Table(name = Constants.USERS_TABLE)\npublic class User implements Serializable {\n\n private static final long serialVersionUID = 570528466125178223L;\n\n pu...
import es.storeapp.business.entities.User; import es.storeapp.business.services.UserService; import es.storeapp.common.Constants; import es.storeapp.web.cookies.UserInfo; import java.io.ByteArrayInputStream; import java.util.Base64; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor;
5,229
package es.storeapp.web.interceptors; public class AutoLoginInterceptor implements HandlerInterceptor { private final UserService userService; public AutoLoginInterceptor(UserService userService) { this.userService = userService; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(true); if (session.getAttribute(Constants.USER_SESSION) != null || request.getCookies() == null) { return true; } for (Cookie c : request.getCookies()) { if (Constants.PERSISTENT_USER_COOKIE.equals(c.getName())) { String cookieValue = c.getValue(); if (cookieValue == null) { continue; } Base64.Decoder decoder = Base64.getDecoder();
package es.storeapp.web.interceptors; public class AutoLoginInterceptor implements HandlerInterceptor { private final UserService userService; public AutoLoginInterceptor(UserService userService) { this.userService = userService; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(true); if (session.getAttribute(Constants.USER_SESSION) != null || request.getCookies() == null) { return true; } for (Cookie c : request.getCookies()) { if (Constants.PERSISTENT_USER_COOKIE.equals(c.getName())) { String cookieValue = c.getValue(); if (cookieValue == null) { continue; } Base64.Decoder decoder = Base64.getDecoder();
JAXBContext context = JAXBContext.newInstance(UserInfo.class);
3
2023-12-24 19:24:49+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,204
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
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"));
2
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,815
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();
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();
GuiTextures.register();
1
2023-12-28 23:01:30+00:00
8k
psobiech/opengr8on
lib/src/main/java/pl/psobiech/opengr8on/client/commands/SetIpCommand.java
[ { "identifier": "Command", "path": "lib/src/main/java/pl/psobiech/opengr8on/client/Command.java", "snippet": "public interface Command {\n int INITIAL_BUFFER_SIZE = 256;\n\n int MIN_IP_SIZE = 7;\n\n int IV_SIZE = 16;\n\n int KEY_SIZE = 16;\n\n int MAC_SIZE = 12;\n\n int MIN_SERIAL_NUMB...
import java.net.Inet4Address; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import pl.psobiech.opengr8on.client.Command; import pl.psobiech.opengr8on.util.HexUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil; import pl.psobiech.opengr8on.util.Util;
6,250
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client.commands; public class SetIpCommand { private static final int SERIAL_NUMBER_PART = 1; private static final int IP_ADDRESS_PART = 2; private static final int GATEWAY_IP_ADDRESS_PART = 3; private SetIpCommand() { // NOP } public static Request request(Long serialNumber, Inet4Address ipAddress, Inet4Address gatewayIpAddress) { return new Request(serialNumber, ipAddress, gatewayIpAddress); } public static Optional<Request> requestFromByteArray(byte[] buffer) { if (!requestMatches(buffer)) { return Optional.empty(); } final Optional<String[]> requestPartsOptional = Util.splitExact(Command.asString(buffer), ":", 4); if (requestPartsOptional.isEmpty()) { return Optional.empty(); } final String[] requestParts = requestPartsOptional.get(); final Long serialNumber = HexUtil.asLong(requestParts[SERIAL_NUMBER_PART]);
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client.commands; public class SetIpCommand { private static final int SERIAL_NUMBER_PART = 1; private static final int IP_ADDRESS_PART = 2; private static final int GATEWAY_IP_ADDRESS_PART = 3; private SetIpCommand() { // NOP } public static Request request(Long serialNumber, Inet4Address ipAddress, Inet4Address gatewayIpAddress) { return new Request(serialNumber, ipAddress, gatewayIpAddress); } public static Optional<Request> requestFromByteArray(byte[] buffer) { if (!requestMatches(buffer)) { return Optional.empty(); } final Optional<String[]> requestPartsOptional = Util.splitExact(Command.asString(buffer), ":", 4); if (requestPartsOptional.isEmpty()) { return Optional.empty(); } final String[] requestParts = requestPartsOptional.get(); final Long serialNumber = HexUtil.asLong(requestParts[SERIAL_NUMBER_PART]);
final Inet4Address ipAddress = IPv4AddressUtil.parseIPv4(requestParts[IP_ADDRESS_PART]);
2
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,917
// 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();
// 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();
private final Intake intake = new Intake();
8
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;
3,873
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");
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);
1
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.*;
7,142
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); throw new ServiceException(THIRD_PARTY_API_ERROR); } return FramifyResult.success(KD100Res); } @Override protected KD100Res queryTrack(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(QUERY_URL, KD100Req.getQueryTrackReq()); KD100QueryTrackRes KD100QueryTrackRes = JSONObject.parseObject(result, KD100QueryTrackRes.class); KD100Res kd100Res = KD100Res.builder() .queryTrackRes(KD100QueryTrackRes) .build(); return kd100Res; } @Override protected KD100Res placeOrder(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(B_ORDER_URL, KD100Req.getPlaceOrderReq()); KD100PlaceOrderRes KD100PlaceOrderRes = JSONObject.parseObject(result, KD100PlaceOrderRes.class); KD100Res kd100Res = KD100Res.builder() .placeOrderRes(KD100PlaceOrderRes) .build(); return kd100Res; } @Override protected KD100Res cancelOrder(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(B_ORDER_URL, KD100Req.getPlaceOrderReq()); KD100CancelOrderRes KD100CancelOrderRes = JSONObject.parseObject(result, KD100CancelOrderRes.class); KD100Res kd100Res = KD100Res.builder() .cancelOrderRes(KD100CancelOrderRes) .build(); return kd100Res; } @Override protected KD100Res queryCost(KD100Req KD100Req) { return null; } @Override protected KD100Res subscribeOrder(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(SUBSCRIBE_URL, KD100Req.getSubscribeReq()); KD100SubscribeRes KD100SubscribeRes = JSONObject.parseObject(result, KD100SubscribeRes.class); KD100Res kd100Res = KD100Res.builder() .subscribeRes(KD100SubscribeRes) .build(); return kd100Res; } @Override protected KD100Res queryCapacity(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(QUERY_URL, KD100Req.getQueryCapacityReq()); KD100QueryCapacityRes<KD100QueryCapacityResParam> KD100QueryCapacityRes = JSONObject .parseObject(result, new TypeReference<KD100QueryCapacityRes<KD100QueryCapacityResParam>>() { }); KD100Res kd100Res = KD100Res.builder() .queryCapacityRes(KD100QueryCapacityRes) .build(); return kd100Res; } @Override protected KD100Res getCode(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(QUERY_URL, KD100Req.getGetCodeReq()); KD100GetCodeRes<Map<String, String>> KD100GetCodeRes = JSONObject .parseObject(result, new TypeReference<KD100GetCodeRes<Map<String, String>>>() { }); KD100Res kd100Res = KD100Res.builder() .getCodeRes(KD100GetCodeRes) .build(); return kd100Res; } @Override protected KD100Res checkAddress(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(REACHABLE_URL, KD100Req.getCheckAddressReq()); KD100CheckAddressRes<KD100CheckAddressResParam> KD100GetCodeRes = JSONObject .parseObject(result, new TypeReference<KD100CheckAddressRes<KD100CheckAddressResParam>>() { }); KD100Res kd100Res = KD100Res.builder() .checkAddressRes(KD100GetCodeRes) .build(); return kd100Res; } @Override public KD100ApiConfig getApiConfig() { return KD100ApiConfigKit.getApiConfig(); } @Override protected String createSign(String signSource) {
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); throw new ServiceException(THIRD_PARTY_API_ERROR); } return FramifyResult.success(KD100Res); } @Override protected KD100Res queryTrack(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(QUERY_URL, KD100Req.getQueryTrackReq()); KD100QueryTrackRes KD100QueryTrackRes = JSONObject.parseObject(result, KD100QueryTrackRes.class); KD100Res kd100Res = KD100Res.builder() .queryTrackRes(KD100QueryTrackRes) .build(); return kd100Res; } @Override protected KD100Res placeOrder(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(B_ORDER_URL, KD100Req.getPlaceOrderReq()); KD100PlaceOrderRes KD100PlaceOrderRes = JSONObject.parseObject(result, KD100PlaceOrderRes.class); KD100Res kd100Res = KD100Res.builder() .placeOrderRes(KD100PlaceOrderRes) .build(); return kd100Res; } @Override protected KD100Res cancelOrder(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(B_ORDER_URL, KD100Req.getPlaceOrderReq()); KD100CancelOrderRes KD100CancelOrderRes = JSONObject.parseObject(result, KD100CancelOrderRes.class); KD100Res kd100Res = KD100Res.builder() .cancelOrderRes(KD100CancelOrderRes) .build(); return kd100Res; } @Override protected KD100Res queryCost(KD100Req KD100Req) { return null; } @Override protected KD100Res subscribeOrder(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(SUBSCRIBE_URL, KD100Req.getSubscribeReq()); KD100SubscribeRes KD100SubscribeRes = JSONObject.parseObject(result, KD100SubscribeRes.class); KD100Res kd100Res = KD100Res.builder() .subscribeRes(KD100SubscribeRes) .build(); return kd100Res; } @Override protected KD100Res queryCapacity(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(QUERY_URL, KD100Req.getQueryCapacityReq()); KD100QueryCapacityRes<KD100QueryCapacityResParam> KD100QueryCapacityRes = JSONObject .parseObject(result, new TypeReference<KD100QueryCapacityRes<KD100QueryCapacityResParam>>() { }); KD100Res kd100Res = KD100Res.builder() .queryCapacityRes(KD100QueryCapacityRes) .build(); return kd100Res; } @Override protected KD100Res getCode(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(QUERY_URL, KD100Req.getGetCodeReq()); KD100GetCodeRes<Map<String, String>> KD100GetCodeRes = JSONObject .parseObject(result, new TypeReference<KD100GetCodeRes<Map<String, String>>>() { }); KD100Res kd100Res = KD100Res.builder() .getCodeRes(KD100GetCodeRes) .build(); return kd100Res; } @Override protected KD100Res checkAddress(KD100Req KD100Req) throws ServiceException { DefaultKD100Client KD100Client = getApiConfig().getKD100Client(); String result = KD100Client.execute(REACHABLE_URL, KD100Req.getCheckAddressReq()); KD100CheckAddressRes<KD100CheckAddressResParam> KD100GetCodeRes = JSONObject .parseObject(result, new TypeReference<KD100CheckAddressRes<KD100CheckAddressResParam>>() { }); KD100Res kd100Res = KD100Res.builder() .checkAddressRes(KD100GetCodeRes) .build(); return kd100Res; } @Override public KD100ApiConfig getApiConfig() { return KD100ApiConfigKit.getApiConfig(); } @Override protected String createSign(String signSource) {
return SignUtils.sign(signSource);
11
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,220
package test; public class DisplayerTest { public static void main(String[] args) {
package test; public class DisplayerTest { public static void main(String[] args) {
Displayer displayer = new Displayer();
1
2023-12-23 13:51:12+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,667
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); } }
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); } }
public static void initHook(Hook hook, LoadPackageParam param) {
1
2023-12-24 13:57:39+00:00
8k
Prototik/TheConfigLib
common/src/main/java/dev/tcl/config/impl/autogen/LongFieldImpl.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.controller.ControllerBuilder; import dev.tcl.api.controller.LongFieldControllerBuilder; import dev.tcl.config.api.ConfigField; import dev.tcl.config.api.autogen.LongField; import dev.tcl.config.api.autogen.OptionAccess; import dev.tcl.config.api.autogen.SimpleOptionFactory; import net.minecraft.locale.Language; import net.minecraft.network.chat.Component;
3,630
package dev.tcl.config.impl.autogen; public class LongFieldImpl extends SimpleOptionFactory<LongField, Long> { @Override
package dev.tcl.config.impl.autogen; public class LongFieldImpl extends SimpleOptionFactory<LongField, Long> { @Override
protected ControllerBuilder<Long> createController(LongField annotation, ConfigField<Long> field, OptionAccess storage, Option<Long> option) {
4
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,441
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;
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;
2
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,887
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; @Override public void login(DeviceReq deviceReq) { DeviceDTO dto = DeviceDTO.req2dto(deviceReq); Long deviceId = deviceManager.saveOrUpdate(dto); log.info("login::deviceReq = {}, deviceId = {}", deviceReq, deviceId); DeviceCommandService deviceCommandService = deviceAgreementService.getCommandService(dto.getType()); DeviceQueryReq deviceQueryReq = new DeviceQueryReq(); deviceQueryReq.setDeviceId(dto.getDeviceId()); // 查下设备信息 deviceCommandService.queryDevice(deviceQueryReq); // 通道查查询 deviceCommandService.queryChannel(deviceQueryReq); } @Override
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; @Override public void login(DeviceReq deviceReq) { DeviceDTO dto = DeviceDTO.req2dto(deviceReq); Long deviceId = deviceManager.saveOrUpdate(dto); log.info("login::deviceReq = {}, deviceId = {}", deviceReq, deviceId); DeviceCommandService deviceCommandService = deviceAgreementService.getCommandService(dto.getType()); DeviceQueryReq deviceQueryReq = new DeviceQueryReq(); deviceQueryReq.setDeviceId(dto.getDeviceId()); // 查下设备信息 deviceCommandService.queryDevice(deviceQueryReq); // 通道查查询 deviceCommandService.queryChannel(deviceQueryReq); } @Override
public void addChannel(DeviceChannelReq req) {
0
2023-12-27 07:28:18+00:00
8k
GrailStack/grail-codegen
src/main/java/com/itgrail/grail/codegen/custom/grailframework/GrailFrameWorkTemplate.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.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.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.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 com.itgrail.grail.codegen.utils.CommonUtil; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import com.itgrail.grail.codegen.utils.PropertiesUtils; import java.util.List; import java.util.Map;
5,359
} subModules.add(moduleMetaData1); subModules.add(moduleMetaData2); subModules.add(moduleMetaData3); subModules.add(moduleMetaData4); subModules.add(moduleMetaData5); return subModules; } @Override public List<String> getSubModules() { return Lists.newArrayList("app","client","domain","start","infrastructure"); } @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.grailframework; /** * @author xujin * created at 2019/5/24 20:50 **/ @Component public class GrailFrameWorkTemplate extends CustomizedTemplate { @Override public String getTemplateName() { return "GrailFramework"; } @Override public List<ModuleMetaData> initSubModules() { List<ModuleMetaData> subModules = Lists.newArrayList(); ModuleMetaData moduleMetaData1=new ModuleMetaData().setSubModuleName("infrastructure").setPackagingTypes(Lists.newArrayList("jar")); ModuleMetaData moduleMetaData2=new ModuleMetaData().setSubModuleName("domain").setPackagingTypes(Lists.newArrayList("jar")); ModuleMetaData moduleMetaData3=new ModuleMetaData().setSubModuleName("client").setPackagingTypes(Lists.newArrayList("jar")); ModuleMetaData moduleMetaData4=new ModuleMetaData().setSubModuleName("app").setPackagingTypes(Lists.newArrayList("jar")); ModuleMetaData moduleMetaData5=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("infrastructure".equals(mo.getModulekey())){ moduleMetaData1.setDependencys(mo.getDependencyModels()); } if("domain".equals(mo.getModulekey())){ moduleMetaData2.setDependencys(mo.getDependencyModels()); } if("client".equals(mo.getModulekey())){ moduleMetaData3.setDependencys(mo.getDependencyModels()); } if("app".equals(mo.getModulekey())){ moduleMetaData4.setDependencys(mo.getDependencyModels()); } if("start".equals(mo.getModulekey())){ moduleMetaData5.setDependencys(mo.getDependencyModels()); } } } subModules.add(moduleMetaData1); subModules.add(moduleMetaData2); subModules.add(moduleMetaData3); subModules.add(moduleMetaData4); subModules.add(moduleMetaData5); return subModules; } @Override public List<String> getSubModules() { return Lists.newArrayList("app","client","domain","start","infrastructure"); } @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();
1
2023-12-30 15:32:55+00:00
8k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/tests/org/jfree/chart/renderer/category/StackedAreaRendererTest.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 static org.junit.Assert.assertNull; import org.jfree.chart.TestUtilities; import org.jfree.data.Range; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.util.PublicCloneable; import org.junit.Test;
7,028
/* =========================================================== * 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.] * * ---------------------------- * StackedAreaRendererTest.java * ---------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 25-Mar-2003 : Version 1 (DG); * 23-Apr-2008 : Added testPublicCloneable() (DG); * 04-Feb-2009 : Added testFindRangeBounds (DG); * */ package org.jfree.chart.renderer.category; /** * Tests for the {@link StackedAreaRenderer} class. */ public class StackedAreaRendererTest { /** * Some checks for the findRangeBounds() method. */ @Test public void testFindRangeBounds() { StackedAreaRenderer r = new StackedAreaRenderer(); assertNull(r.findRangeBounds(null)); // an empty dataset should return a null range
/* =========================================================== * 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.] * * ---------------------------- * StackedAreaRendererTest.java * ---------------------------- * (C) Copyright 2003-2013, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 25-Mar-2003 : Version 1 (DG); * 23-Apr-2008 : Added testPublicCloneable() (DG); * 04-Feb-2009 : Added testFindRangeBounds (DG); * */ package org.jfree.chart.renderer.category; /** * Tests for the {@link StackedAreaRenderer} class. */ public class StackedAreaRendererTest { /** * Some checks for the findRangeBounds() method. */ @Test public void testFindRangeBounds() { StackedAreaRenderer r = new StackedAreaRenderer(); assertNull(r.findRangeBounds(null)); // an empty dataset should return a null range
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
2
2023-12-24 12:36:47+00:00
8k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/mixin/render/MixinModelBiped.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.mixin.client.EntityPlayerSPAccessor; import com.github.may2beez.mayobees.mixin.client.MinecraftAccessor; import com.github.may2beez.mayobees.util.helper.RotationConfiguration; import net.minecraft.client.Minecraft; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
5,784
package com.github.may2beez.mayobees.mixin.render; @Mixin(value = ModelBiped.class, priority = Integer.MAX_VALUE) public class MixinModelBiped { @Unique private final Minecraft farmHelperV2$mc = Minecraft.getMinecraft(); @Shadow public ModelRenderer bipedHead; @Inject(method = {"setRotationAngles"}, at = {@At(value = "FIELD", target = "Lnet/minecraft/client/model/ModelBiped;swingProgress:F")}) public void onSetRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn, CallbackInfo ci) { if (!RotationHandler.getInstance().isRotating() || RotationHandler.getInstance().getConfiguration() != null && RotationHandler.getInstance().getConfiguration().getRotationType() != RotationConfiguration.RotationType.SERVER) return; if (entityIn != null && entityIn.equals(Minecraft.getMinecraft().thePlayer)) { this.bipedHead.rotateAngleX = ((EntityPlayerSPAccessor) entityIn).getLastReportedPitch() / 57.295776f;
package com.github.may2beez.mayobees.mixin.render; @Mixin(value = ModelBiped.class, priority = Integer.MAX_VALUE) public class MixinModelBiped { @Unique private final Minecraft farmHelperV2$mc = Minecraft.getMinecraft(); @Shadow public ModelRenderer bipedHead; @Inject(method = {"setRotationAngles"}, at = {@At(value = "FIELD", target = "Lnet/minecraft/client/model/ModelBiped;swingProgress:F")}) public void onSetRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn, CallbackInfo ci) { if (!RotationHandler.getInstance().isRotating() || RotationHandler.getInstance().getConfiguration() != null && RotationHandler.getInstance().getConfiguration().getRotationType() != RotationConfiguration.RotationType.SERVER) return; if (entityIn != null && entityIn.equals(Minecraft.getMinecraft().thePlayer)) { this.bipedHead.rotateAngleX = ((EntityPlayerSPAccessor) entityIn).getLastReportedPitch() / 57.295776f;
float partialTicks = ((MinecraftAccessor) farmHelperV2$mc).getTimer().renderPartialTicks;
2
2023-12-24 15:39:11+00:00
8k
viceice/verbrauchsapp
app/src/main/java/de/anipe/verbrauchsapp/tasks/ImportGDriveCar.java
[ { "identifier": "XMLHandler", "path": "app/src/main/java/de/anipe/verbrauchsapp/io/XMLHandler.java", "snippet": "public class XMLHandler {\n\n\tprivate Car car;\n\tprivate double cons;\n\tprivate List<Consumption> consumptions;\n\n\tprivate static ConsumptionDataSource dataSource;\n\n\tprivate SimpleDat...
import android.app.Activity; import android.app.ProgressDialog; import android.content.IntentSender; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.drive.Drive; import com.google.android.gms.drive.DriveContents; import com.google.android.gms.drive.DriveFile; import com.google.android.gms.drive.DriveId; import java.io.InputStream; import de.anipe.verbrauchsapp.io.XMLHandler; import de.anipe.verbrauchsapp.util.ResetableCountDownLatch; import static com.google.android.gms.common.api.GoogleApiClient.Builder; import static com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import static com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import static com.google.android.gms.drive.DriveApi.DriveContentsResult;
4,147
package de.anipe.verbrauchsapp.tasks; public class ImportGDriveCar extends AsyncTask<String, Void, Void> { private Activity mCon; private ProgressDialog myprogsdial; private int dataSets = -2; private GoogleApiClient mClient; private Throwable _error = null; public ImportGDriveCar(Activity con) { mCon = con; Builder builder = new Builder(con) .addApi(Drive.API) .addScope(Drive.SCOPE_FILE); mClient = builder.build(); } @Override protected void onPreExecute() { myprogsdial = ProgressDialog.show(mCon, "Datensatz-Import", "Bitte warten ...", true); } @Override protected Void doInBackground(String... params) { Log.d("ImportGDriveCar", "Importing gdrive file."); try {
package de.anipe.verbrauchsapp.tasks; public class ImportGDriveCar extends AsyncTask<String, Void, Void> { private Activity mCon; private ProgressDialog myprogsdial; private int dataSets = -2; private GoogleApiClient mClient; private Throwable _error = null; public ImportGDriveCar(Activity con) { mCon = con; Builder builder = new Builder(con) .addApi(Drive.API) .addScope(Drive.SCOPE_FILE); mClient = builder.build(); } @Override protected void onPreExecute() { myprogsdial = ProgressDialog.show(mCon, "Datensatz-Import", "Bitte warten ...", true); } @Override protected Void doInBackground(String... params) { Log.d("ImportGDriveCar", "Importing gdrive file."); try {
final ResetableCountDownLatch latch = new ResetableCountDownLatch(1);
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,971
package com.recondev; public class Main { public static void main(String[] args) { UserInteraction ui = new UserInteraction(); Enums.DatabaseType dbType = ui.getDatabaseType();
package com.recondev; public class Main { public static void main(String[] args) { UserInteraction ui = new UserInteraction(); Enums.DatabaseType dbType = ui.getDatabaseType();
DatabaseScriptGenerator scriptGenerator = ScriptGeneratorFactory.getScriptGenerator(dbType.getValue());
2
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;
6,016
/** * 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(); // telefone.setTipo(TipoTelefone.CELULAR); // telefone.setTelefone("(11) 98355-4235"); // telefone.setUsuarioid(1L); // telefone.setTipo(TipoTelefone.COMERCIAL); // telefone.setTelefone("(12) 98657-8745"); // telefone.setUsuarioid(1L); telefone.setTipo(TipoTelefone.CELULAR); telefone.setTelefone("(19) 98789-3456"); telefone.setUsuarioid(2L); if (dao.salvar(telefone)) { System.out.println("Telefone incluído com sucesso"); } else { System.out.println("Falha ao incluir o telefone"); } } /** * Listar todos os telefones da tabela Telefones */ public static void listarTelefones() { System.out.println("# Listar os telefones"); TelefonesDAO dao = new TelefonesDAO(); List<Telefones> listaTelefones = new ArrayList<Telefones>(); listaTelefones = dao.listar(); for (Telefones telefone : listaTelefones) { System.out.println(telefone.toString()); } } /** * Listar todos os usuários (tabela Usuários) com os telefones (tabela * Telefones) utilizando INNER JOIN */ public static void listarUsuariosComTelefones() { System.out.println("# Listar os usuários com telefones"); UsuariosDAO dao = new UsuariosDAO();
/** * 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(); // telefone.setTipo(TipoTelefone.CELULAR); // telefone.setTelefone("(11) 98355-4235"); // telefone.setUsuarioid(1L); // telefone.setTipo(TipoTelefone.COMERCIAL); // telefone.setTelefone("(12) 98657-8745"); // telefone.setUsuarioid(1L); telefone.setTipo(TipoTelefone.CELULAR); telefone.setTelefone("(19) 98789-3456"); telefone.setUsuarioid(2L); if (dao.salvar(telefone)) { System.out.println("Telefone incluído com sucesso"); } else { System.out.println("Falha ao incluir o telefone"); } } /** * Listar todos os telefones da tabela Telefones */ public static void listarTelefones() { System.out.println("# Listar os telefones"); TelefonesDAO dao = new TelefonesDAO(); List<Telefones> listaTelefones = new ArrayList<Telefones>(); listaTelefones = dao.listar(); for (Telefones telefone : listaTelefones) { System.out.println(telefone.toString()); } } /** * Listar todos os usuários (tabela Usuários) com os telefones (tabela * Telefones) utilizando INNER JOIN */ public static void listarUsuariosComTelefones() { System.out.println("# Listar os usuários com telefones"); UsuariosDAO dao = new UsuariosDAO();
List<UsuarioTelefone> listaUsuariosTelefones = new ArrayList<UsuarioTelefone>();
4
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;
4,253
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) { LabyModProtocol.sendLabyModMessage(player, "input_prompt", prompt.toJson()); } public static LabyModPlayer getLabyModPlayer(Player player) { if (!labyModPlayers.containsKey(player)) return null; return labyModPlayers.get(player); } public static LabyModPlayer getLabyModPlayer(UUID uuid) { for (Player player : labyModPlayers.keySet()) { if (player.getUniqueId().equals(uuid)) return labyModPlayers.get(player); } return null; } public static void executeLabyModJoin(Player player, String version, String json) { LabyModPlayer labyModPlayer = new LabyModPlayer(player, version); labyModPlayers.put(player, labyModPlayer); LabyModPlayerJoinEvent event = new LabyModPlayerJoinEvent(labyModPlayer, json); player.getServer().getPluginManager().callEvent(event); // Update existing players (if enabled) if (!updateExistingPlayersOnJoin) return; NewLabyPlugin.debug("Updating existing players for " + player.getName() + " (" + player.getUniqueId() + ")"); new BukkitRunnable() { @Override public void run() {
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) { LabyModProtocol.sendLabyModMessage(player, "input_prompt", prompt.toJson()); } public static LabyModPlayer getLabyModPlayer(Player player) { if (!labyModPlayers.containsKey(player)) return null; return labyModPlayers.get(player); } public static LabyModPlayer getLabyModPlayer(UUID uuid) { for (Player player : labyModPlayers.keySet()) { if (player.getUniqueId().equals(uuid)) return labyModPlayers.get(player); } return null; } public static void executeLabyModJoin(Player player, String version, String json) { LabyModPlayer labyModPlayer = new LabyModPlayer(player, version); labyModPlayers.put(player, labyModPlayer); LabyModPlayerJoinEvent event = new LabyModPlayerJoinEvent(labyModPlayer, json); player.getServer().getPluginManager().callEvent(event); // Update existing players (if enabled) if (!updateExistingPlayersOnJoin) return; NewLabyPlugin.debug("Updating existing players for " + player.getName() + " (" + player.getUniqueId() + ")"); new BukkitRunnable() { @Override public void run() {
List<LabyModPlayerSubtitle> subtitles = new ArrayList<>();
4
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,395
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()); sys.setComputerIp(IpUtils.getHostIp()); sys.setOsName(props.getProperty("os.name")); sys.setOsArch(props.getProperty("os.arch")); sys.setUserDir(props.getProperty("user.dir")); } /** * 设置Java虚拟机 */ private void setJvmInfo() throws UnknownHostException { Properties props = System.getProperties(); jvm.setTotal(Runtime.getRuntime().totalMemory()); jvm.setMax(Runtime.getRuntime().maxMemory()); jvm.setFree(Runtime.getRuntime().freeMemory()); jvm.setVersion(props.getProperty("java.version")); jvm.setHome(props.getProperty("java.home")); } /** * 设置磁盘信息 */ private void setSysFiles(OperatingSystem os) { FileSystem fileSystem = os.getFileSystem(); List<OSFileStore> fsArray = fileSystem.getFileStores(); for (OSFileStore fs : fsArray) { long free = fs.getUsableSpace(); long total = fs.getTotalSpace(); long used = total - free; SysFile sysFile = new SysFile(); sysFile.setDirName(fs.getMount()); sysFile.setSysTypeName(fs.getType()); sysFile.setTypeName(fs.getName()); sysFile.setTotal(convertFileSize(total)); sysFile.setFree(convertFileSize(free)); sysFile.setUsed(convertFileSize(used));
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()); sys.setComputerIp(IpUtils.getHostIp()); sys.setOsName(props.getProperty("os.name")); sys.setOsArch(props.getProperty("os.arch")); sys.setUserDir(props.getProperty("user.dir")); } /** * 设置Java虚拟机 */ private void setJvmInfo() throws UnknownHostException { Properties props = System.getProperties(); jvm.setTotal(Runtime.getRuntime().totalMemory()); jvm.setMax(Runtime.getRuntime().maxMemory()); jvm.setFree(Runtime.getRuntime().freeMemory()); jvm.setVersion(props.getProperty("java.version")); jvm.setHome(props.getProperty("java.home")); } /** * 设置磁盘信息 */ private void setSysFiles(OperatingSystem os) { FileSystem fileSystem = os.getFileSystem(); List<OSFileStore> fsArray = fileSystem.getFileStores(); for (OSFileStore fs : fsArray) { long free = fs.getUsableSpace(); long total = fs.getTotalSpace(); long used = total - free; SysFile sysFile = new SysFile(); sysFile.setDirName(fs.getMount()); sysFile.setSysTypeName(fs.getType()); sysFile.setTypeName(fs.getName()); sysFile.setTotal(convertFileSize(total)); sysFile.setFree(convertFileSize(free)); sysFile.setUsed(convertFileSize(used));
sysFile.setUsage(Arith.mul(Arith.div(used, total, 4), 100));
0
2023-12-30 13:42:53+00:00
8k
JIGerss/Salus
salus-web/src/main/java/team/glhf/salus/service/Impl/ArticleServiceImpl.java
[ { "identifier": "Article", "path": "salus-pojo/src/main/java/team/glhf/salus/entity/Article.java", "snippet": "@Data\r\n@Builder\r\n@TableName(\"tb_article\")\r\npublic class Article implements Serializable {\r\n @TableId(type = IdType.ASSIGN_ID)\r\n private String id;\r\n\r\n @TableField(\"ima...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.lang.Opt; import cn.hutool.core.util.RandomUtil; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.support.TransactionTemplate; import team.glhf.salus.dto.article.*; import team.glhf.salus.entity.Article; import team.glhf.salus.entity.relation.ArticleOwnComment; import team.glhf.salus.entity.relation.ArticleOwnTag; import team.glhf.salus.entity.relation.UserLikeArticle; import team.glhf.salus.entity.relation.UserOwnArticle; import team.glhf.salus.enumeration.FilePathEnum; import team.glhf.salus.enumeration.HttpCodeEnum; import team.glhf.salus.exception.ArticleException; import team.glhf.salus.mapper.*; import team.glhf.salus.service.ArticleService; import team.glhf.salus.service.CommonService; import team.glhf.salus.vo.ArticleVo; import team.glhf.salus.vo.CommentVo; import team.glhf.salus.vo.TagVo; import java.util.ArrayList; import java.util.List;
4,682
package team.glhf.salus.service.Impl; /** * @author Steveny * @since 2023/10/30 */ @Slf4j @Service public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService { private final CommonService commonService; private final TransactionTemplate transactionTemplate; private final UserOwnArticleMapper userOwnArticleMapper; private final UserLikeArticleMapper userLikeArticleMapper; private final ArticleOwnTagMapper articleOwnTagMapper; private final ArticleOwnCommentMapper articleOwnCommentMapper; public ArticleServiceImpl(UserOwnArticleMapper userOwnArticleMapper, TransactionTemplate transactionTemplate, UserLikeArticleMapper userLikeArticleMapper, ArticleOwnTagMapper articleOwnTagMapper, ArticleOwnCommentMapper articleOwnCommentMapper, CommonService commonService) { this.commonService = commonService; this.userOwnArticleMapper = userOwnArticleMapper; this.transactionTemplate = transactionTemplate; this.userLikeArticleMapper = userLikeArticleMapper; this.articleOwnTagMapper = articleOwnTagMapper; this.articleOwnCommentMapper = articleOwnCommentMapper; } @Override public CreateRes createArticle(CreateReq createReq) { // upload images List<String> urlList = new ArrayList<>(); if (null != createReq.getImages()) { urlList = commonService.uploadAllImages(createReq.getImages(), FilePathEnum.ARTICLE_IMAGE); } // generate new article instance Article article = Article.initedBuilder() .title(createReq.getTitle()) .images(JSONUtil.toJsonStr(urlList)) .content(createReq.getContent()) .position(createReq.getPosition()) .build(); // start a transaction transactionTemplate.execute((status) -> { save(article); UserOwnArticle userOwnArticle = UserOwnArticle.builder() .userId(createReq.getUserId()) .articleId(article.getId()) .build(); userOwnArticleMapper.insert(userOwnArticle); List<String> tagList = createReq.getTags().stream().distinct().toList(); for (String tag : tagList) { ArticleOwnTag articleOwnTag = ArticleOwnTag.builder() .articleId(article.getId()) .tag(tag) .build(); articleOwnTagMapper.insert(articleOwnTag); } return Boolean.TRUE; }); return CreateRes.builder().articleId(article.getId()).build(); } @Override public ArticleVo getArticleById(String articleId) { checkHasArticle(articleId, true); return article2ArticleVo(getById(articleId)); } @Override public List<ArticleVo> getRecommendArticles(List<String> articleIds) { // 排除已经推荐过的文章 articleIds = Opt.ofNullable(articleIds).orElseGet(ArrayList::new); LambdaQueryWrapper<Article> qw = Wrappers.lambdaQuery(Article.class) .notIn(!articleIds.isEmpty(), Article::getId, articleIds); List<ArticleVo> articleVoList = new ArrayList<>(10); Page<Article> page = new Page<>(1, 1); int count = (int) count(qw); for (int i = 0; i < 10 && count > 0; i++) { page.setCurrent(RandomUtil.randomInt(1, count + 1)); List<Article> oneArticleList = list(page, qw.notIn(!articleIds.isEmpty(), Article::getId, articleIds) ); Article oneArticle = oneArticleList.get(0); articleVoList.add(article2ArticleVo(oneArticle)); articleIds.add(oneArticle.getId()); count = count - 1; } return articleVoList; } @Override public List<ArticleVo> getLikedArticles(String userId) { List<UserLikeArticle> likeArticles = userLikeArticleMapper.selectList(Wrappers.lambdaQuery(UserLikeArticle.class) .eq(UserLikeArticle::getUserId, userId) ); List<String> idList = likeArticles.stream().map(UserLikeArticle::getArticleId).toList(); if (idList.isEmpty()) { return new ArrayList<>(); } else { List<Article> articles = listByIds(idList); return articles.stream().map(this::article2ArticleVo).toList(); } } @Override public List<ArticleVo> getOwnedArticles(String userId) { List<UserOwnArticle> ownArticles = userOwnArticleMapper.selectList(Wrappers.lambdaQuery(UserOwnArticle.class) .eq(UserOwnArticle::getUserId, userId) ); List<String> idList = ownArticles.stream().map(UserOwnArticle::getArticleId).toList(); if (idList.isEmpty()) { return new ArrayList<>(); } else { List<Article> articles = listByIds(idList); return articles.stream().map(this::article2ArticleVo).toList(); } } @Override
package team.glhf.salus.service.Impl; /** * @author Steveny * @since 2023/10/30 */ @Slf4j @Service public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService { private final CommonService commonService; private final TransactionTemplate transactionTemplate; private final UserOwnArticleMapper userOwnArticleMapper; private final UserLikeArticleMapper userLikeArticleMapper; private final ArticleOwnTagMapper articleOwnTagMapper; private final ArticleOwnCommentMapper articleOwnCommentMapper; public ArticleServiceImpl(UserOwnArticleMapper userOwnArticleMapper, TransactionTemplate transactionTemplate, UserLikeArticleMapper userLikeArticleMapper, ArticleOwnTagMapper articleOwnTagMapper, ArticleOwnCommentMapper articleOwnCommentMapper, CommonService commonService) { this.commonService = commonService; this.userOwnArticleMapper = userOwnArticleMapper; this.transactionTemplate = transactionTemplate; this.userLikeArticleMapper = userLikeArticleMapper; this.articleOwnTagMapper = articleOwnTagMapper; this.articleOwnCommentMapper = articleOwnCommentMapper; } @Override public CreateRes createArticle(CreateReq createReq) { // upload images List<String> urlList = new ArrayList<>(); if (null != createReq.getImages()) { urlList = commonService.uploadAllImages(createReq.getImages(), FilePathEnum.ARTICLE_IMAGE); } // generate new article instance Article article = Article.initedBuilder() .title(createReq.getTitle()) .images(JSONUtil.toJsonStr(urlList)) .content(createReq.getContent()) .position(createReq.getPosition()) .build(); // start a transaction transactionTemplate.execute((status) -> { save(article); UserOwnArticle userOwnArticle = UserOwnArticle.builder() .userId(createReq.getUserId()) .articleId(article.getId()) .build(); userOwnArticleMapper.insert(userOwnArticle); List<String> tagList = createReq.getTags().stream().distinct().toList(); for (String tag : tagList) { ArticleOwnTag articleOwnTag = ArticleOwnTag.builder() .articleId(article.getId()) .tag(tag) .build(); articleOwnTagMapper.insert(articleOwnTag); } return Boolean.TRUE; }); return CreateRes.builder().articleId(article.getId()).build(); } @Override public ArticleVo getArticleById(String articleId) { checkHasArticle(articleId, true); return article2ArticleVo(getById(articleId)); } @Override public List<ArticleVo> getRecommendArticles(List<String> articleIds) { // 排除已经推荐过的文章 articleIds = Opt.ofNullable(articleIds).orElseGet(ArrayList::new); LambdaQueryWrapper<Article> qw = Wrappers.lambdaQuery(Article.class) .notIn(!articleIds.isEmpty(), Article::getId, articleIds); List<ArticleVo> articleVoList = new ArrayList<>(10); Page<Article> page = new Page<>(1, 1); int count = (int) count(qw); for (int i = 0; i < 10 && count > 0; i++) { page.setCurrent(RandomUtil.randomInt(1, count + 1)); List<Article> oneArticleList = list(page, qw.notIn(!articleIds.isEmpty(), Article::getId, articleIds) ); Article oneArticle = oneArticleList.get(0); articleVoList.add(article2ArticleVo(oneArticle)); articleIds.add(oneArticle.getId()); count = count - 1; } return articleVoList; } @Override public List<ArticleVo> getLikedArticles(String userId) { List<UserLikeArticle> likeArticles = userLikeArticleMapper.selectList(Wrappers.lambdaQuery(UserLikeArticle.class) .eq(UserLikeArticle::getUserId, userId) ); List<String> idList = likeArticles.stream().map(UserLikeArticle::getArticleId).toList(); if (idList.isEmpty()) { return new ArrayList<>(); } else { List<Article> articles = listByIds(idList); return articles.stream().map(this::article2ArticleVo).toList(); } } @Override public List<ArticleVo> getOwnedArticles(String userId) { List<UserOwnArticle> ownArticles = userOwnArticleMapper.selectList(Wrappers.lambdaQuery(UserOwnArticle.class) .eq(UserOwnArticle::getUserId, userId) ); List<String> idList = ownArticles.stream().map(UserOwnArticle::getArticleId).toList(); if (idList.isEmpty()) { return new ArrayList<>(); } else { List<Article> articles = listByIds(idList); return articles.stream().map(this::article2ArticleVo).toList(); } } @Override
public List<TagVo> getRecommendTags() {
12
2023-12-23 15:03:37+00:00
8k
swsm/proxynet
proxynet-client/src/main/java/com/swsm/proxynet/client/handler/ClientServerChannelHandler.java
[ { "identifier": "ConfigUtil", "path": "proxynet-client/src/main/java/com/swsm/proxynet/client/config/ConfigUtil.java", "snippet": "@Component\n@Slf4j\npublic class ConfigUtil {\n \n @Autowired\n private ProxyConfig proxyConfig;\n \n private static ProxyConfig myProxyConfig;\n \n @Po...
import com.alibaba.fastjson.JSON; import com.swsm.proxynet.client.config.ConfigUtil; import com.swsm.proxynet.client.init.SpringInitRunner; import com.swsm.proxynet.common.Constants; import com.swsm.proxynet.common.cache.ChannelRelationCache; import com.swsm.proxynet.common.model.CommandInfoMessage; import com.swsm.proxynet.common.model.CommandMessage; import com.swsm.proxynet.common.model.ConnectMessage; import com.swsm.proxynet.common.model.ProxyNetMessage; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOption; import io.netty.channel.SimpleChannelInboundHandler; import lombok.extern.slf4j.Slf4j;
3,712
package com.swsm.proxynet.client.handler; /** * @author liujie * @date 2023-04-15 */ @Slf4j public class ClientServerChannelHandler extends SimpleChannelInboundHandler<ProxyNetMessage> { @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, ProxyNetMessage proxyNetMessage) throws Exception { if (proxyNetMessage.getType() == ProxyNetMessage.CONNECT) { executeConnect(proxyNetMessage, channelHandlerContext); } else if (proxyNetMessage.getType() == ProxyNetMessage.COMMAND) { executeCommand(proxyNetMessage, channelHandlerContext); } } private void executeCommand(ProxyNetMessage proxyNetMessage, ChannelHandlerContext channelHandlerContext) { Channel clientChannel = channelHandlerContext.channel(); CommandMessage commandMessage = JSON.parseObject(proxyNetMessage.getInfo(), CommandMessage.class); if (ProxyNetMessage.COMMAND_INFO.equals(commandMessage.getType())) { CommandInfoMessage commandInfoMessage = JSON.parseObject(commandMessage.getMessage(), CommandInfoMessage.class); Channel targetChannel = clientChannel.attr(Constants.NEXT_CHANNEL).get(); if (targetChannel == null) { log.info("targetInfo={}的客户端还未和代理客户端建立连接", commandInfoMessage.getTargetIp() + ":" + commandInfoMessage.getTargetPort()); return; } ByteBuf data = channelHandlerContext.alloc().buffer(proxyNetMessage.getData().length); data.writeBytes(proxyNetMessage.getData()); targetChannel.writeAndFlush(data); } } private void executeConnect(ProxyNetMessage proxyNetMessage, ChannelHandlerContext channelHandlerContext) { ConnectMessage connectMessage = JSON.parseObject(proxyNetMessage.getInfo(), ConnectMessage.class); log.info("收到服务端发送的connect消息:{}", proxyNetMessage); log.info("向目标服务={}发起连接...", proxyNetMessage); try { SpringInitRunner.bootstrapForTarget.connect(connectMessage.getTargetIp(), connectMessage.getTargetPort()) .addListener((ChannelFutureListener) future -> { Channel targetChannel = future.channel(); if (future.isSuccess()) { targetChannel.config().setOption(ChannelOption.AUTO_READ, false); log.info("向目标服务={}发起连接 成功...", proxyNetMessage);
package com.swsm.proxynet.client.handler; /** * @author liujie * @date 2023-04-15 */ @Slf4j public class ClientServerChannelHandler extends SimpleChannelInboundHandler<ProxyNetMessage> { @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, ProxyNetMessage proxyNetMessage) throws Exception { if (proxyNetMessage.getType() == ProxyNetMessage.CONNECT) { executeConnect(proxyNetMessage, channelHandlerContext); } else if (proxyNetMessage.getType() == ProxyNetMessage.COMMAND) { executeCommand(proxyNetMessage, channelHandlerContext); } } private void executeCommand(ProxyNetMessage proxyNetMessage, ChannelHandlerContext channelHandlerContext) { Channel clientChannel = channelHandlerContext.channel(); CommandMessage commandMessage = JSON.parseObject(proxyNetMessage.getInfo(), CommandMessage.class); if (ProxyNetMessage.COMMAND_INFO.equals(commandMessage.getType())) { CommandInfoMessage commandInfoMessage = JSON.parseObject(commandMessage.getMessage(), CommandInfoMessage.class); Channel targetChannel = clientChannel.attr(Constants.NEXT_CHANNEL).get(); if (targetChannel == null) { log.info("targetInfo={}的客户端还未和代理客户端建立连接", commandInfoMessage.getTargetIp() + ":" + commandInfoMessage.getTargetPort()); return; } ByteBuf data = channelHandlerContext.alloc().buffer(proxyNetMessage.getData().length); data.writeBytes(proxyNetMessage.getData()); targetChannel.writeAndFlush(data); } } private void executeConnect(ProxyNetMessage proxyNetMessage, ChannelHandlerContext channelHandlerContext) { ConnectMessage connectMessage = JSON.parseObject(proxyNetMessage.getInfo(), ConnectMessage.class); log.info("收到服务端发送的connect消息:{}", proxyNetMessage); log.info("向目标服务={}发起连接...", proxyNetMessage); try { SpringInitRunner.bootstrapForTarget.connect(connectMessage.getTargetIp(), connectMessage.getTargetPort()) .addListener((ChannelFutureListener) future -> { Channel targetChannel = future.channel(); if (future.isSuccess()) { targetChannel.config().setOption(ChannelOption.AUTO_READ, false); log.info("向目标服务={}发起连接 成功...", proxyNetMessage);
String serverIp = ConfigUtil.getServerIp();
0
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;
5,872
package com.trodev.scanhub.adapters; public class LocationAdapter extends RecyclerView.Adapter<LocationAdapter.MyViewHolder>{ private Context context;
package com.trodev.scanhub.adapters; public class LocationAdapter extends RecyclerView.Adapter<LocationAdapter.MyViewHolder>{ private Context context;
private ArrayList<LocationModel> list;
3
2023-12-26 05:10:38+00:00
8k
Deepennn/NetAPP
src/main/java/com/netapp/device/router/Router.java
[ { "identifier": "ArpEntry", "path": "src/main/java/com/netapp/device/ArpEntry.java", "snippet": "public class ArpEntry\n{\n\n /** 对应于MAC地址的IP地址 */\n private String ip;\n\n /** 对应于IP地址的MAC地址 */\n private String mac;\n\n /** 映射创建时的时间 */\n private long timeAdded;\n\n /**\n * 创建一个将I...
import com.netapp.device.ArpEntry; import com.netapp.device.Iface; import com.netapp.device.NetDevice; import com.netapp.device.NetIface; import com.netapp.packet.*; import java.util.Map; import java.util.Objects; import static com.netapp.config.DeviceConfig.ROUTE_TABLE_PREFFIX; import static com.netapp.config.DeviceConfig.ROUTE_TABLE_SUFFIX;
5,245
package com.netapp.device.router; public class Router extends NetDevice { /** 路由表 */ private RouteTable routeTable; /** * 创建路由器。 * @param hostname 设备的主机名 * @param interfaces 接口映射 */ public Router(String hostname, Map<String, Iface> interfaces) { super(hostname, interfaces); routeTable = new RouteTable(); this.loadRouteTable(ROUTE_TABLE_PREFFIX + this.hostname + ROUTE_TABLE_SUFFIX); } /** * 处理 IP 数据包。 * @param etherPacket 接收到的以太网数据包 * @param inIface 接收数据包的接口 */ @Override protected void handleIPPacket(Ethernet etherPacket, Iface inIface) { if (etherPacket.getEtherType() != Ethernet.TYPE_IPv4) { return; } IPv4 ipPacket = (IPv4) etherPacket.getPayload(); System.out.println(this.hostname + " is handling IP packet: " + ipPacket); // 检验校验和 int origCksum = ipPacket.getChecksum(); ipPacket.updateChecksum(); int calcCksum = ipPacket.getChecksum(); if (origCksum != calcCksum) { System.out.println(this.hostname + " found IP packet's checksum is wrong: "); return; } // TTL-1 ipPacket.setTtl((ipPacket.getTtl() - 1)); if (0 == ipPacket.getTtl()) { this.sendICMPPacket(etherPacket, inIface, 11, 0, false); return; } // 更新校验和 ipPacket.updateChecksum(); // 检查数据包的目的 IP 是否为接口 IP 之一 for (Iface iface : this.interfaces.values()) { if (Objects.equals(ipPacket.getDestinationIP(), ((NetIface) iface).getIpAddress())) { byte protocol = ipPacket.getProtocol(); // System.out.println("ipPacket protocol: " + protocol); if (protocol == IPv4.PROTOCOL_ICMP) { ICMP icmp = (ICMP) ipPacket.getPayload(); System.out.println(this.hostname + " accepted message: " + icmp); if (icmp.getIcmpType() == 8) { this.sendICMPPacket(etherPacket, inIface, 0, 0, true); } } else if (protocol == IPv4.PROTOCOL_DEFAULT){ Data data = (Data) ipPacket.getPayload(); System.out.println(this.hostname + " accepted message: " + data.getData()); } return; } } // 检查路由表并转发 this.forwardIPPacket(etherPacket, inIface); } /** * 转发 IP 数据包。 * @param etherPacket 接收到的以太网数据包 * @param inIface 接收数据包的接口 */ private void forwardIPPacket(Ethernet etherPacket, Iface inIface) { // 确保是 IP 数据包 if (etherPacket.getEtherType() != Ethernet.TYPE_IPv4) { return; } IPv4 ipPacket = (IPv4) etherPacket.getPayload(); System.out.println(this.hostname + " is forwarding IP packet: " + ipPacket); // 获取目的 IP String dstIp = ipPacket.getDestinationIP(); // 查找匹配的路由表项 RouteEntry bestMatch = this.routeTable.lookup(dstIp); // 这种情况会转发到默认网关 /* // 如果没有匹配的项,则发 ICMP if (null == bestMatch) { this.sendICMPPacket(etherPacket, inIface, 3, 0, false); return; } */ // 确保不将数据包发送回它进入的接口 Iface outIface = bestMatch.getInterface(); if (outIface == inIface) { return; } // 设置以太网头部中的源 MAC 地址 String srcMac = outIface.getMacAddress(); etherPacket.setSourceMAC(srcMac); // 如果没有网关,那么下一跳是目的地 IP ,设置目的 MAC 的时候可以直接设置目的地的MAC,否则设置网关的MAC String nextHop = bestMatch.getGatewayAddress(); if (IPv4.DEFAULT_IP.equals(nextHop)) { nextHop = dstIp; } // 设置以太网头部中的目标 MAC 地址
package com.netapp.device.router; public class Router extends NetDevice { /** 路由表 */ private RouteTable routeTable; /** * 创建路由器。 * @param hostname 设备的主机名 * @param interfaces 接口映射 */ public Router(String hostname, Map<String, Iface> interfaces) { super(hostname, interfaces); routeTable = new RouteTable(); this.loadRouteTable(ROUTE_TABLE_PREFFIX + this.hostname + ROUTE_TABLE_SUFFIX); } /** * 处理 IP 数据包。 * @param etherPacket 接收到的以太网数据包 * @param inIface 接收数据包的接口 */ @Override protected void handleIPPacket(Ethernet etherPacket, Iface inIface) { if (etherPacket.getEtherType() != Ethernet.TYPE_IPv4) { return; } IPv4 ipPacket = (IPv4) etherPacket.getPayload(); System.out.println(this.hostname + " is handling IP packet: " + ipPacket); // 检验校验和 int origCksum = ipPacket.getChecksum(); ipPacket.updateChecksum(); int calcCksum = ipPacket.getChecksum(); if (origCksum != calcCksum) { System.out.println(this.hostname + " found IP packet's checksum is wrong: "); return; } // TTL-1 ipPacket.setTtl((ipPacket.getTtl() - 1)); if (0 == ipPacket.getTtl()) { this.sendICMPPacket(etherPacket, inIface, 11, 0, false); return; } // 更新校验和 ipPacket.updateChecksum(); // 检查数据包的目的 IP 是否为接口 IP 之一 for (Iface iface : this.interfaces.values()) { if (Objects.equals(ipPacket.getDestinationIP(), ((NetIface) iface).getIpAddress())) { byte protocol = ipPacket.getProtocol(); // System.out.println("ipPacket protocol: " + protocol); if (protocol == IPv4.PROTOCOL_ICMP) { ICMP icmp = (ICMP) ipPacket.getPayload(); System.out.println(this.hostname + " accepted message: " + icmp); if (icmp.getIcmpType() == 8) { this.sendICMPPacket(etherPacket, inIface, 0, 0, true); } } else if (protocol == IPv4.PROTOCOL_DEFAULT){ Data data = (Data) ipPacket.getPayload(); System.out.println(this.hostname + " accepted message: " + data.getData()); } return; } } // 检查路由表并转发 this.forwardIPPacket(etherPacket, inIface); } /** * 转发 IP 数据包。 * @param etherPacket 接收到的以太网数据包 * @param inIface 接收数据包的接口 */ private void forwardIPPacket(Ethernet etherPacket, Iface inIface) { // 确保是 IP 数据包 if (etherPacket.getEtherType() != Ethernet.TYPE_IPv4) { return; } IPv4 ipPacket = (IPv4) etherPacket.getPayload(); System.out.println(this.hostname + " is forwarding IP packet: " + ipPacket); // 获取目的 IP String dstIp = ipPacket.getDestinationIP(); // 查找匹配的路由表项 RouteEntry bestMatch = this.routeTable.lookup(dstIp); // 这种情况会转发到默认网关 /* // 如果没有匹配的项,则发 ICMP if (null == bestMatch) { this.sendICMPPacket(etherPacket, inIface, 3, 0, false); return; } */ // 确保不将数据包发送回它进入的接口 Iface outIface = bestMatch.getInterface(); if (outIface == inIface) { return; } // 设置以太网头部中的源 MAC 地址 String srcMac = outIface.getMacAddress(); etherPacket.setSourceMAC(srcMac); // 如果没有网关,那么下一跳是目的地 IP ,设置目的 MAC 的时候可以直接设置目的地的MAC,否则设置网关的MAC String nextHop = bestMatch.getGatewayAddress(); if (IPv4.DEFAULT_IP.equals(nextHop)) { nextHop = dstIp; } // 设置以太网头部中的目标 MAC 地址
ArpEntry arpEntry = this.atomicCache.get().lookup(nextHop);
0
2023-12-23 13:03:07+00:00
8k
strokegmd/StrokeClient
stroke/client/clickgui/ClickGuiScreen.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.io.IOException; import java.util.ArrayList; import org.lwjgl.input.Keyboard; import net.minecraft.client.gui.GuiScreen; import net.stroke.client.StrokeClient; import net.stroke.client.clickgui.component.Component; import net.stroke.client.clickgui.component.Frame; import net.stroke.client.modules.ModuleCategory; import net.stroke.client.modules.render.ClickGui; import net.stroke.client.util.ParticleEngine;
3,690
package net.stroke.client.clickgui; public class ClickGuiScreen extends GuiScreen { public static ArrayList<Frame> frames; public static int color; public ParticleEngine particleEngine; public ClickGuiScreen() { this.frames = new ArrayList<Frame>(); int frameX = 10; int frameY = 10; for(ModuleCategory category : ModuleCategory.values()) { Frame frame = new Frame(category); frame.setY(frameY); frame.setX(frameX); frames.add(frame); frameX += 100; } } @Override public void initGui() { this.particleEngine = new ParticleEngine(); } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) {
package net.stroke.client.clickgui; public class ClickGuiScreen extends GuiScreen { public static ArrayList<Frame> frames; public static int color; public ParticleEngine particleEngine; public ClickGuiScreen() { this.frames = new ArrayList<Frame>(); int frameX = 10; int frameY = 10; for(ModuleCategory category : ModuleCategory.values()) { Frame frame = new Frame(category); frame.setY(frameY); frame.setX(frameX); frames.add(frame); frameX += 100; } } @Override public void initGui() { this.particleEngine = new ParticleEngine(); } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) {
boolean snow = StrokeClient.instance.settingsManager.getSettingByName("ClickGui", "Snow").getValBoolean();
0
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,611
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() { return MotivoEmissao.values(); } @ModelAttribute("motivosBaixa") public MotivoBaixa[] motivosBaixa() { return MotivoBaixa.values(); } @ModelAttribute("situacoes") public SituacaoCobranca[] situacoes() { return SituacaoCobranca.values(); } @ModelAttribute("moradias")
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() { return MotivoEmissao.values(); } @ModelAttribute("motivosBaixa") public MotivoBaixa[] motivosBaixa() { return MotivoBaixa.values(); } @ModelAttribute("situacoes") public SituacaoCobranca[] situacoes() { return SituacaoCobranca.values(); } @ModelAttribute("moradias")
public List<Moradia> moradias() {
1
2023-12-29 22:19:42+00:00
8k
HuXin0817/shop_api
framework/src/main/java/cn/lili/modules/distribution/service/DistributionOrderService.java
[ { "identifier": "DistributionOrder", "path": "framework/src/main/java/cn/lili/modules/distribution/entity/dos/DistributionOrder.java", "snippet": "@Data\n@ApiModel(value = \"分销订单\")\n@TableName(\"li_distribution_order\")\n@NoArgsConstructor\npublic class DistributionOrder extends BaseIdEntity {\n\n p...
import cn.hutool.core.date.DateTime; import cn.lili.modules.distribution.entity.dos.DistributionOrder; import cn.lili.modules.distribution.entity.vos.DistributionOrderSearchParams; import cn.lili.modules.order.aftersale.entity.dos.AfterSale; import cn.lili.modules.order.order.entity.dos.OrderItem; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List;
3,757
package cn.lili.modules.distribution.service; /** * 分销订单业务层 * * @author pikachu * @since 2020-03-15 10:46:33 */ public interface DistributionOrderService extends IService<DistributionOrder> { /** * 获取分销订单分页 * @param distributionOrderSearchParams 分销订单搜索参数 * @return 分销订单分页 */ IPage<DistributionOrder> getDistributionOrderPage(DistributionOrderSearchParams distributionOrderSearchParams); /** * 支付订单 * 记录分销订单 * * @param orderSn 订单编号 */ void calculationDistribution(String orderSn); /** * 取消订单 * 记录分销订单 * * @param orderSn 订单编号 */ void cancelOrder(String orderSn); /** * 订单退款 * 记录分销订单 * * @param afterSaleSn 售后单号 */ void refundOrder(AfterSale afterSale); /** * 分销订单状态修改 * * @param orderItems */
package cn.lili.modules.distribution.service; /** * 分销订单业务层 * * @author pikachu * @since 2020-03-15 10:46:33 */ public interface DistributionOrderService extends IService<DistributionOrder> { /** * 获取分销订单分页 * @param distributionOrderSearchParams 分销订单搜索参数 * @return 分销订单分页 */ IPage<DistributionOrder> getDistributionOrderPage(DistributionOrderSearchParams distributionOrderSearchParams); /** * 支付订单 * 记录分销订单 * * @param orderSn 订单编号 */ void calculationDistribution(String orderSn); /** * 取消订单 * 记录分销订单 * * @param orderSn 订单编号 */ void cancelOrder(String orderSn); /** * 订单退款 * 记录分销订单 * * @param afterSaleSn 售后单号 */ void refundOrder(AfterSale afterSale); /** * 分销订单状态修改 * * @param orderItems */
void updateDistributionOrderStatus(List<OrderItem> orderItems);
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,771
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("请选择菜单:");
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();
2
2023-12-28 04:26:15+00:00
8k
MuskStark/EasyECharts
src/main/java/com/github/muskstark/echart/model/bar/BarChart.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.alibaba.fastjson2.annotation.JSONField; import com.github.muskstark.echart.attribute.Legend; import com.github.muskstark.echart.attribute.Title; import com.github.muskstark.echart.attribute.ToolTip; 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.model.Charts; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.List;
3,643
package com.github.muskstark.echart.model.bar; @EqualsAndHashCode(callSuper = true) @Data public class BarChart extends Charts { @JSONField(name = "xAxis") private XAxis xAxis; @JSONField(name = "yAxis") private YAxis yAxis; private List<BarSeries> series; public Title defineTitle() { return this.getTitle(); } public XAxis defineXAxis() { return this.getXAxis(); } public YAxis defineYAxis() { return this.getYAxis(); }
package com.github.muskstark.echart.model.bar; @EqualsAndHashCode(callSuper = true) @Data public class BarChart extends Charts { @JSONField(name = "xAxis") private XAxis xAxis; @JSONField(name = "yAxis") private YAxis yAxis; private List<BarSeries> series; public Title defineTitle() { return this.getTitle(); } public XAxis defineXAxis() { return this.getXAxis(); } public YAxis defineYAxis() { return this.getYAxis(); }
public ToolTip defineToolTip() {
2
2023-12-25 08:03:42+00:00
8k
xyzell/OOP_UAS
Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/swing/ManageRoomReceptionist.java
[ { "identifier": "ExitConfirmation", "path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/swing/component/ExitConfirmation.java", "snippet": "public class ExitConfirmation extends javax.swing.JFrame {\n\n /**\n * Creates new form ExitConfirmation\n */\n public ExitConfirmation() {\n ...
import com.itenas.oop.org.uashotel.swing.component.ExitConfirmation; import com.itenas.oop.org.uashotel.utilities.ConnectionManager; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel;
5,630
jLabel6.setForeground(new java.awt.Color(173, 151, 79)); jLabel6.setText("___________________________________________________"); jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 160, 300, -1)); jLabel7.setForeground(new java.awt.Color(173, 151, 79)); jLabel7.setText("________________________________________________________"); jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 290, 300, -1)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void txtBadTotalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtBadTotalActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtBadTotalActionPerformed private void ShowRooms() { try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel", "root", "basdat2020"); st = con.createStatement(); rs = st.executeQuery("select * from hotel_room"); // Mendapatkan metadata dari ResultSet java.sql.ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); // Mengosongkan model tabel DefaultTableModel model = (DefaultTableModel) tabelRoom.getModel(); model.setRowCount(0); // Menambahkan baris ke model while (rs.next()) { Object[] rowData = new Object[columnCount]; for (int i = 1; i <= columnCount; i++) { rowData[i - 1] = rs.getObject(i); } model.addRow(rowData); } } catch (Exception e) { e.printStackTrace(); // Sebaiknya ditangani dengan lebih baik, minimal mencetak error stack trace } finally{ try { if (rs != null) rs.close(); if (st != null) st.close(); if (con != null) con.close(); } catch (Exception e) { e.printStackTrace(); } } } private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed if (txtIdRoom.getText().isEmpty() || cmbRoomType.getSelectedIndex() == -1 || txtRoomPrice.getText().isEmpty() || txtBadTotal.getText().isEmpty() || cmbStatus.getSelectedIndex() == -1) { JOptionPane.showMessageDialog(this, "Missing Data"); } else { try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel", "root", "basdat2020"); PreparedStatement Save = con.prepareStatement("INSERT INTO hotel_room VALUES(?, ?, ?, ?, ?)"); Save.setString(1, txtIdRoom.getText()); Save.setString(2, cmbRoomType.getSelectedItem().toString()); Save.setInt(3, Integer.valueOf(txtRoomPrice.getText())); Save.setInt(4, Integer.valueOf(txtBadTotal.getText())); Save.setString(5, cmbStatus.getSelectedItem().toString()); int row = Save.executeUpdate(); if (row > 0) { JOptionPane.showMessageDialog(this, "Room Added"); ShowRooms(); } else { JOptionPane.showMessageDialog(this, "Failed to add room"); } con.close(); } catch (SQLException ex) { ex.printStackTrace(); // Sebaiknya ditangani dengan lebih baik, minimal mencetak error stack trace JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage()); } } }//GEN-LAST:event_btnAddActionPerformed private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed txtIdRoom.setText(""); cmbRoomType.setSelectedIndex(-1); txtRoomPrice.setText(""); txtBadTotal.setText(""); cmbStatus.setSelectedIndex(-1); }//GEN-LAST:event_btnClearActionPerformed private void lblGuestMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblGuestMouseClicked // TODO add your handling code here: }//GEN-LAST:event_lblGuestMouseClicked private void lblLogOut2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblLogOut2MouseClicked // TODO add your handling code here: }//GEN-LAST:event_lblLogOut2MouseClicked private void lblReservationMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblReservationMouseClicked // TODO add your handling code here: }//GEN-LAST:event_lblReservationMouseClicked private void lblLogOutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblLogOutMouseClicked
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ package com.itenas.oop.org.uashotel.swing; /** * * @author acer */ public class ManageRoomReceptionist extends javax.swing.JFrame { Connection con = null; PreparedStatement pst = null; ResultSet rs = null; Statement st = null; public ManageRoomReceptionist() { initComponents(); setExtendedState(JFrame.MAXIMIZED_BOTH); txtIdRoom.setBackground(new java.awt.Color(0,0,0,1)); txtBadTotal.setBackground(new java.awt.Color(0,0,0,1)); txtRoomPrice.setBackground(new java.awt.Color(0,0,0,1)); cmbStatus.setBackground(new java.awt.Color(0,0,0,1)); ShowRooms(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); lblGuest = new javax.swing.JLabel(); lblLogOut2 = new javax.swing.JLabel(); lblReservation = new javax.swing.JLabel(); lblLogOut = new javax.swing.JLabel(); lblDashboard1 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); txtRoomPrice = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); lblSearch = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); txtBadTotal = new javax.swing.JTextField(); cmbStatus = new javax.swing.JComboBox<>(); cmbRoomType = new javax.swing.JComboBox<>(); jScrollPane1 = new javax.swing.JScrollPane(); tabelRoom = new javax.swing.JTable(); btnAdd = new javax.swing.JButton(); btnClear = new javax.swing.JButton(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); txtIdRoom = new javax.swing.JTextField(); btnSearch = new javax.swing.JButton(); btnDelete = new javax.swing.JButton(); btnEdit = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setForeground(new java.awt.Color(0, 0, 0)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel2.setBackground(new java.awt.Color(173, 151, 79)); lblGuest.setFont(new java.awt.Font("Segoe UI", 2, 18)); // NOI18N lblGuest.setForeground(new java.awt.Color(255, 255, 255)); lblGuest.setText("Guest"); lblGuest.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblGuest.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblGuestMouseClicked(evt); } }); lblLogOut2.setFont(new java.awt.Font("Segoe UI", 2, 18)); // NOI18N lblLogOut2.setForeground(new java.awt.Color(255, 255, 255)); lblLogOut2.setText("Rooms"); lblLogOut2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblLogOut2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblLogOut2MouseClicked(evt); } }); lblReservation.setFont(new java.awt.Font("Segoe UI", 2, 18)); // NOI18N lblReservation.setForeground(new java.awt.Color(255, 255, 255)); lblReservation.setText("Reservation"); lblReservation.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblReservation.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblReservationMouseClicked(evt); } }); lblLogOut.setFont(new java.awt.Font("Segoe UI", 2, 18)); // NOI18N lblLogOut.setForeground(new java.awt.Color(255, 255, 255)); lblLogOut.setText("Log Out"); lblLogOut.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblLogOut.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblLogOutMouseClicked(evt); } }); lblDashboard1.setFont(new java.awt.Font("Segoe UI", 2, 18)); // NOI18N lblDashboard1.setForeground(new java.awt.Color(255, 255, 255)); lblDashboard1.setText("Dashboard"); lblDashboard1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblDashboard1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblDashboard1MouseClicked(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(14, 14, 14) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblDashboard1) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblGuest) .addComponent(lblLogOut2) .addComponent(lblReservation) .addComponent(lblLogOut, javax.swing.GroupLayout.Alignment.TRAILING))) .addContainerGap(45, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(122, 122, 122) .addComponent(lblLogOut2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblGuest) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblReservation) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lblDashboard1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 356, Short.MAX_VALUE) .addComponent(lblLogOut) .addGap(91, 91, 91)) ); jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 150, 730)); jPanel3.setBackground(new java.awt.Color(190, 160, 90)); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel1.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(182, 0, 1216, -1)); txtRoomPrice.setBackground(new java.awt.Color(204, 204, 204)); txtRoomPrice.setBorder(null); txtRoomPrice.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtRoomPriceActionPerformed(evt); } }); jPanel1.add(txtRoomPrice, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 280, 300, 32)); jLabel2.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N jLabel2.setForeground(new java.awt.Color(173, 151, 79)); jLabel2.setText("ID Room"); jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 120, -1, -1)); lblSearch.setBackground(new java.awt.Color(204, 204, 204)); lblSearch.setBorder(null); lblSearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { lblSearchActionPerformed(evt); } }); jPanel1.add(lblSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(998, 79, 244, 32)); jLabel3.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N jLabel3.setForeground(new java.awt.Color(173, 151, 79)); jLabel3.setText("Room Type"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 190, -1, -1)); jLabel4.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N jLabel4.setForeground(new java.awt.Color(173, 151, 79)); jLabel4.setText("Bed Total"); jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 320, -1, -1)); jLabel5.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N jLabel5.setForeground(new java.awt.Color(173, 151, 79)); jLabel5.setText("Status"); jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 380, -1, -1)); txtBadTotal.setBackground(new java.awt.Color(204, 204, 204)); txtBadTotal.setBorder(null); txtBadTotal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtBadTotalActionPerformed(evt); } }); jPanel1.add(txtBadTotal, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 340, 300, 32)); cmbStatus.setBackground(new java.awt.Color(173, 151, 79)); cmbStatus.setForeground(new java.awt.Color(255, 255, 255)); cmbStatus.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Available", "Booked", " " })); jPanel1.add(cmbStatus, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 410, 300, 34)); cmbRoomType.setBackground(new java.awt.Color(173, 151, 79)); cmbRoomType.setForeground(new java.awt.Color(255, 255, 255)); cmbRoomType.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "VIP", "Double Bed", "Single Bad", "Family" })); cmbRoomType.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbRoomTypeActionPerformed(evt); } }); jPanel1.add(cmbRoomType, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 210, 300, 34)); tabelRoom.setBackground(new java.awt.Color(204, 204, 255)); tabelRoom.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "ID Room", "Room Type", "Room Price", "Bed Total", "Status" } )); tabelRoom.setGridColor(new java.awt.Color(190, 160, 90)); tabelRoom.setRowHeight(25); tabelRoom.setRowMargin(1); jScrollPane1.setViewportView(tabelRoom); jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(521, 119, 843, 530)); btnAdd.setBackground(new java.awt.Color(0, 204, 0)); btnAdd.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N btnAdd.setForeground(new java.awt.Color(255, 255, 255)); btnAdd.setText("Add"); btnAdd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddActionPerformed(evt); } }); jPanel1.add(btnAdd, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 470, 300, 35)); btnClear.setBackground(new java.awt.Color(3, 45, 137)); btnClear.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N btnClear.setForeground(new java.awt.Color(255, 255, 255)); btnClear.setText("Clear"); btnClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnClearActionPerformed(evt); } }); jPanel1.add(btnClear, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 620, 300, 35)); jLabel8.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jLabel8.setForeground(new java.awt.Color(173, 151, 79)); jLabel8.setText("Hotel Management System"); jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(657, 20, -1, -1)); jLabel9.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N jLabel9.setForeground(new java.awt.Color(173, 151, 79)); jLabel9.setText("Room Price"); jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 250, -1, -1)); jLabel10.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jLabel10.setForeground(new java.awt.Color(173, 151, 79)); jLabel10.setText("Manage Room"); jPanel1.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(711, 47, -1, -1)); txtIdRoom.setBackground(new java.awt.Color(204, 204, 204)); txtIdRoom.setBorder(null); txtIdRoom.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtIdRoomActionPerformed(evt); } }); jPanel1.add(txtIdRoom, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 140, 300, 30)); btnSearch.setBackground(new java.awt.Color(3, 45, 137)); btnSearch.setForeground(new java.awt.Color(255, 255, 255)); btnSearch.setText("Search"); btnSearch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSearchActionPerformed(evt); } }); jPanel1.add(btnSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(1260, 78, 104, 35)); btnDelete.setBackground(new java.awt.Color(255, 0, 0)); btnDelete.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N btnDelete.setForeground(new java.awt.Color(255, 255, 255)); btnDelete.setText("Delete"); btnDelete.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDeleteActionPerformed(evt); } }); jPanel1.add(btnDelete, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 570, 300, 35)); btnEdit.setBackground(new java.awt.Color(3, 45, 137)); btnEdit.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N btnEdit.setForeground(new java.awt.Color(255, 255, 255)); btnEdit.setText("Edit"); btnEdit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEditActionPerformed(evt); } }); jPanel1.add(btnEdit, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 520, 300, 35)); jLabel1.setForeground(new java.awt.Color(173, 151, 79)); jLabel1.setText("________________________________________________________"); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 350, 300, -1)); jLabel6.setForeground(new java.awt.Color(173, 151, 79)); jLabel6.setText("___________________________________________________"); jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 160, 300, -1)); jLabel7.setForeground(new java.awt.Color(173, 151, 79)); jLabel7.setText("________________________________________________________"); jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 290, 300, -1)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void txtBadTotalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtBadTotalActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtBadTotalActionPerformed private void ShowRooms() { try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel", "root", "basdat2020"); st = con.createStatement(); rs = st.executeQuery("select * from hotel_room"); // Mendapatkan metadata dari ResultSet java.sql.ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); // Mengosongkan model tabel DefaultTableModel model = (DefaultTableModel) tabelRoom.getModel(); model.setRowCount(0); // Menambahkan baris ke model while (rs.next()) { Object[] rowData = new Object[columnCount]; for (int i = 1; i <= columnCount; i++) { rowData[i - 1] = rs.getObject(i); } model.addRow(rowData); } } catch (Exception e) { e.printStackTrace(); // Sebaiknya ditangani dengan lebih baik, minimal mencetak error stack trace } finally{ try { if (rs != null) rs.close(); if (st != null) st.close(); if (con != null) con.close(); } catch (Exception e) { e.printStackTrace(); } } } private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed if (txtIdRoom.getText().isEmpty() || cmbRoomType.getSelectedIndex() == -1 || txtRoomPrice.getText().isEmpty() || txtBadTotal.getText().isEmpty() || cmbStatus.getSelectedIndex() == -1) { JOptionPane.showMessageDialog(this, "Missing Data"); } else { try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel", "root", "basdat2020"); PreparedStatement Save = con.prepareStatement("INSERT INTO hotel_room VALUES(?, ?, ?, ?, ?)"); Save.setString(1, txtIdRoom.getText()); Save.setString(2, cmbRoomType.getSelectedItem().toString()); Save.setInt(3, Integer.valueOf(txtRoomPrice.getText())); Save.setInt(4, Integer.valueOf(txtBadTotal.getText())); Save.setString(5, cmbStatus.getSelectedItem().toString()); int row = Save.executeUpdate(); if (row > 0) { JOptionPane.showMessageDialog(this, "Room Added"); ShowRooms(); } else { JOptionPane.showMessageDialog(this, "Failed to add room"); } con.close(); } catch (SQLException ex) { ex.printStackTrace(); // Sebaiknya ditangani dengan lebih baik, minimal mencetak error stack trace JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage()); } } }//GEN-LAST:event_btnAddActionPerformed private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed txtIdRoom.setText(""); cmbRoomType.setSelectedIndex(-1); txtRoomPrice.setText(""); txtBadTotal.setText(""); cmbStatus.setSelectedIndex(-1); }//GEN-LAST:event_btnClearActionPerformed private void lblGuestMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblGuestMouseClicked // TODO add your handling code here: }//GEN-LAST:event_lblGuestMouseClicked private void lblLogOut2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblLogOut2MouseClicked // TODO add your handling code here: }//GEN-LAST:event_lblLogOut2MouseClicked private void lblReservationMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblReservationMouseClicked // TODO add your handling code here: }//GEN-LAST:event_lblReservationMouseClicked private void lblLogOutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblLogOutMouseClicked
new ExitConfirmation().setVisible(true);
0
2023-12-24 11:39:51+00:00
8k
LeeKyeongYong/SBookStudy
src/main/java/com/multibook/bookorder/domain/member/member/service/MemberService.java
[ { "identifier": "GenFileService", "path": "src/main/java/com/multibook/bookorder/domain/base/genFile/service/GenFileService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class GenFileService {\n private final GenFileRepository genFileRepository;\n\n ...
import com.multibook.bookorder.domain.base.genFile.service.GenFileService; import com.multibook.bookorder.domain.cash.cash.entity.CashLog; import com.multibook.bookorder.domain.cash.cash.service.CashService; import com.multibook.bookorder.domain.member.member.entity.Member; import com.multibook.bookorder.domain.member.member.repository.MemberRepository; import com.multibook.bookorder.global.app.AppConfig; import com.multibook.bookorder.global.jpa.BaseEntity; import com.multibook.bookorder.global.rsData.RsData; import com.multibook.bookorder.util.UtZip; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import lombok.RequiredArgsConstructor; import com.multibook.bookorder.domain.base.genFile.entity.GenFile; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import java.util.Optional;
6,248
package com.multibook.bookorder.domain.member.member.service; @Service @RequiredArgsConstructor @Transactional(readOnly = true) public class MemberService { private final MemberRepository memberRepository; private final PasswordEncoder passwordEncoder; private final CashService cashService; private final GenFileService genFileService; @Transactional public RsData<Member> join(String username, String password, String nickname) { return join(username, password, nickname, ""); } @Transactional public RsData<Member> join(String username, String password, String nickname, MultipartFile profileImg) { String profileImgFilePath = UtZip.file.toFile(profileImg, AppConfig.getTempDirPath()); return join(username, password, nickname, profileImgFilePath); } @Transactional public RsData<Member> join(String username, String password, String nickname, String profileImgFilePath) { if (findByUsername(username).isPresent()) { return RsData.of("400-2", "이미 존재하는 회원입니다."); } Member member = Member.builder() .username(username) .password(passwordEncoder.encode(password)) .nickname(nickname) .build(); memberRepository.save(member); if (UtZip.str.hasLength(profileImgFilePath)) { saveProfileImg(member, profileImgFilePath); } return RsData.of("200", "%s님 환영합니다. 회원가입이 완료되었습니다. 로그인 후 이용해주세요.".formatted(member.getUsername()), member); } private void saveProfileImg(Member member, String profileImgFilePath) { genFileService.save(member.getModelName(), member.getId(), "common", "profileImg", 1, profileImgFilePath); } public Optional<Member> findByUsername(String username) { return memberRepository.findByUsername(username); } @Transactional
package com.multibook.bookorder.domain.member.member.service; @Service @RequiredArgsConstructor @Transactional(readOnly = true) public class MemberService { private final MemberRepository memberRepository; private final PasswordEncoder passwordEncoder; private final CashService cashService; private final GenFileService genFileService; @Transactional public RsData<Member> join(String username, String password, String nickname) { return join(username, password, nickname, ""); } @Transactional public RsData<Member> join(String username, String password, String nickname, MultipartFile profileImg) { String profileImgFilePath = UtZip.file.toFile(profileImg, AppConfig.getTempDirPath()); return join(username, password, nickname, profileImgFilePath); } @Transactional public RsData<Member> join(String username, String password, String nickname, String profileImgFilePath) { if (findByUsername(username).isPresent()) { return RsData.of("400-2", "이미 존재하는 회원입니다."); } Member member = Member.builder() .username(username) .password(passwordEncoder.encode(password)) .nickname(nickname) .build(); memberRepository.save(member); if (UtZip.str.hasLength(profileImgFilePath)) { saveProfileImg(member, profileImgFilePath); } return RsData.of("200", "%s님 환영합니다. 회원가입이 완료되었습니다. 로그인 후 이용해주세요.".formatted(member.getUsername()), member); } private void saveProfileImg(Member member, String profileImgFilePath) { genFileService.save(member.getModelName(), member.getId(), "common", "profileImg", 1, profileImgFilePath); } public Optional<Member> findByUsername(String username) { return memberRepository.findByUsername(username); } @Transactional
public void addCash(Member member, long price, CashLog.EvenType eventType, BaseEntity relEntity) {
6
2023-12-26 14:58:59+00:00
8k
huidongyin/kafka-2.7.2
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/WorkerMetricsGroup.java
[ { "identifier": "MetricName", "path": "clients/src/main/java/org/apache/kafka/common/MetricName.java", "snippet": "public final class MetricName {\n\n private final String name;\n private final String group;\n private final String description;\n private Map<String, String> tags;\n private...
import org.apache.kafka.common.MetricName; import org.apache.kafka.common.metrics.Sensor; import org.apache.kafka.common.metrics.stats.CumulativeSum; import org.apache.kafka.common.metrics.stats.Frequencies; import org.apache.kafka.connect.util.ConnectorTaskId; import java.util.Map;
6,051
/* * 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.connect.runtime; class WorkerMetricsGroup { private final ConnectMetrics.MetricGroup metricGroup; private final Sensor connectorStartupAttempts; private final Sensor connectorStartupSuccesses; private final Sensor connectorStartupFailures; private final Sensor connectorStartupResults; private final Sensor taskStartupAttempts; private final Sensor taskStartupSuccesses; private final Sensor taskStartupFailures; private final Sensor taskStartupResults; public WorkerMetricsGroup(final Map<String, WorkerConnector> connectors, Map<ConnectorTaskId, WorkerTask> tasks, ConnectMetrics connectMetrics) { ConnectMetricsRegistry registry = connectMetrics.registry(); metricGroup = connectMetrics.group(registry.workerGroupName()); metricGroup.addValueMetric(registry.connectorCount, now -> (double) connectors.size()); metricGroup.addValueMetric(registry.taskCount, now -> (double) tasks.size()); MetricName connectorFailurePct = metricGroup.metricName(registry.connectorStartupFailurePercentage); MetricName connectorSuccessPct = metricGroup.metricName(registry.connectorStartupSuccessPercentage);
/* * 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.connect.runtime; class WorkerMetricsGroup { private final ConnectMetrics.MetricGroup metricGroup; private final Sensor connectorStartupAttempts; private final Sensor connectorStartupSuccesses; private final Sensor connectorStartupFailures; private final Sensor connectorStartupResults; private final Sensor taskStartupAttempts; private final Sensor taskStartupSuccesses; private final Sensor taskStartupFailures; private final Sensor taskStartupResults; public WorkerMetricsGroup(final Map<String, WorkerConnector> connectors, Map<ConnectorTaskId, WorkerTask> tasks, ConnectMetrics connectMetrics) { ConnectMetricsRegistry registry = connectMetrics.registry(); metricGroup = connectMetrics.group(registry.workerGroupName()); metricGroup.addValueMetric(registry.connectorCount, now -> (double) connectors.size()); metricGroup.addValueMetric(registry.taskCount, now -> (double) tasks.size()); MetricName connectorFailurePct = metricGroup.metricName(registry.connectorStartupFailurePercentage); MetricName connectorSuccessPct = metricGroup.metricName(registry.connectorStartupSuccessPercentage);
Frequencies connectorStartupResultFrequencies = Frequencies.forBooleanValues(connectorFailurePct, connectorSuccessPct);
3
2023-12-23 07:12:18+00:00
8k
SDeVuyst/pingys-waddles-1.20.1
src/main/java/com/sdevuyst/pingyswaddles/entity/client/EmperorPenguinModel.java
[ { "identifier": "EmperorPenguinAnimationDefinitions", "path": "src/main/java/com/sdevuyst/pingyswaddles/animations/EmperorPenguinAnimationDefinitions.java", "snippet": "public class EmperorPenguinAnimationDefinitions\n{\n public static final AnimationDefinition WINGING = AnimationDefinition.Builder.w...
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import com.sdevuyst.pingyswaddles.animations.EmperorPenguinAnimationDefinitions; import com.sdevuyst.pingyswaddles.entity.custom.EmperorPenguinEntity; import net.minecraft.client.model.HierarchicalModel; import net.minecraft.client.model.geom.ModelPart; import net.minecraft.client.model.geom.PartPose; import net.minecraft.client.model.geom.builders.*; import net.minecraft.util.Mth; import net.minecraft.world.entity.Entity;
3,948
package com.sdevuyst.pingyswaddles.entity.client; public class EmperorPenguinModel<T extends Entity> extends HierarchicalModel<T> { private final ModelPart root; private final ModelPart head; public EmperorPenguinModel(ModelPart root) { this.root = root; this.head = root.getChild("emperor_penguin").getChild("top"); } public static LayerDefinition createBodyLayer() { MeshDefinition meshdefinition = new MeshDefinition(); PartDefinition partdefinition = meshdefinition.getRoot(); PartDefinition emperor_penguin = partdefinition.addOrReplaceChild("emperor_penguin", CubeListBuilder.create(), PartPose.offsetAndRotation(0.0F, 24.0F, 0.0F, 0.0F, 135F, 0.0F)); PartDefinition top = emperor_penguin.addOrReplaceChild("top", CubeListBuilder.create(), PartPose.offsetAndRotation(2.0F, -11.5F, 0.0F, -0.0349F, 0.0F, 0.0F)); PartDefinition head = top.addOrReplaceChild("head", CubeListBuilder.create().texOffs(2, 38).addBox(-7.0F, -18.5009F, -6.9477F, 14.0F, 10.0F, 14.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition beak = top.addOrReplaceChild("beak", CubeListBuilder.create().texOffs(50, 2).addBox(-1.0F, -12.5009F, 6.0523F, 2.0F, 2.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition body = emperor_penguin.addOrReplaceChild("body", CubeListBuilder.create().texOffs(0, 0).addBox(-8.0F, -20.0F, -8.0F, 16.0F, 20.0F, 16.0F, new CubeDeformation(0.0F)), PartPose.offset(2.0F, 0.0F, 0.0F)); PartDefinition wings = emperor_penguin.addOrReplaceChild("wings", CubeListBuilder.create(), PartPose.offset(2.0F, -1.5F, 0.0F)); PartDefinition rightwing = wings.addOrReplaceChild("rightwing", CubeListBuilder.create(), PartPose.offset(7.0F, -17.0F, 0.0F)); PartDefinition cube_r1 = rightwing.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(60, 58).addBox(15.0F, -14.0F, 11.0F, 2.0F, 16.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-12.7747F, 14.9515F, -13.0F, 0.0F, 0.0F, -0.1309F)); PartDefinition leftwing = wings.addOrReplaceChild("leftwing", CubeListBuilder.create(), PartPose.offset(-7.0F, -17.0F, 0.0F)); PartDefinition cube_r2 = leftwing.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(60, 32).addBox(-17.0F, -14.0F, 11.0F, 2.0F, 16.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(12.2192F, 15.1698F, -13.0F, 0.0F, 0.0F, 0.1309F)); PartDefinition feet = emperor_penguin.addOrReplaceChild("feet", CubeListBuilder.create(), PartPose.offset(2.0F, -2.0F, 0.0F)); PartDefinition rightfoot = feet.addOrReplaceChild("rightfoot", CubeListBuilder.create().texOffs(0, 7).addBox(2.0F, 0.0F, 6.0F, 3.0F, 2.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition leftfoot = feet.addOrReplaceChild("leftfoot", CubeListBuilder.create().texOffs(0, 0).addBox(-5.0F, 0.0F, 6.0F, 3.0F, 2.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition tail = emperor_penguin.addOrReplaceChild("tail", CubeListBuilder.create(), PartPose.offset(8.25F, -1.75F, 0.75F)); PartDefinition part1 = tail.addOrReplaceChild("part1", CubeListBuilder.create().texOffs(0, 36).addBox(-7.25F, 0.5F, -10.0F, 2.0F, 1.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition part2 = tail.addOrReplaceChild("part2", CubeListBuilder.create(), PartPose.offset(-6.25F, 0.25F, -0.75F)); PartDefinition cube_r3 = part2.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 0).addBox(0.5F, -1.0F, -13.0F, 1.0F, 1.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-1.0F, 1.25F, 2.75F, 0.0349F, 0.0F, 0.0F)); return LayerDefinition.create(meshdefinition, 128, 128); } @Override public void setupAnim(T entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) { this.root().getAllParts().forEach(ModelPart::resetPose); this.applyHeadRotation(entity, netHeadYaw, headPitch, ageInTicks); this.animateWalk(EmperorPenguinAnimationDefinitions.WALKING, limbSwing, limbSwingAmount, 2f, 2.5f);
package com.sdevuyst.pingyswaddles.entity.client; public class EmperorPenguinModel<T extends Entity> extends HierarchicalModel<T> { private final ModelPart root; private final ModelPart head; public EmperorPenguinModel(ModelPart root) { this.root = root; this.head = root.getChild("emperor_penguin").getChild("top"); } public static LayerDefinition createBodyLayer() { MeshDefinition meshdefinition = new MeshDefinition(); PartDefinition partdefinition = meshdefinition.getRoot(); PartDefinition emperor_penguin = partdefinition.addOrReplaceChild("emperor_penguin", CubeListBuilder.create(), PartPose.offsetAndRotation(0.0F, 24.0F, 0.0F, 0.0F, 135F, 0.0F)); PartDefinition top = emperor_penguin.addOrReplaceChild("top", CubeListBuilder.create(), PartPose.offsetAndRotation(2.0F, -11.5F, 0.0F, -0.0349F, 0.0F, 0.0F)); PartDefinition head = top.addOrReplaceChild("head", CubeListBuilder.create().texOffs(2, 38).addBox(-7.0F, -18.5009F, -6.9477F, 14.0F, 10.0F, 14.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition beak = top.addOrReplaceChild("beak", CubeListBuilder.create().texOffs(50, 2).addBox(-1.0F, -12.5009F, 6.0523F, 2.0F, 2.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition body = emperor_penguin.addOrReplaceChild("body", CubeListBuilder.create().texOffs(0, 0).addBox(-8.0F, -20.0F, -8.0F, 16.0F, 20.0F, 16.0F, new CubeDeformation(0.0F)), PartPose.offset(2.0F, 0.0F, 0.0F)); PartDefinition wings = emperor_penguin.addOrReplaceChild("wings", CubeListBuilder.create(), PartPose.offset(2.0F, -1.5F, 0.0F)); PartDefinition rightwing = wings.addOrReplaceChild("rightwing", CubeListBuilder.create(), PartPose.offset(7.0F, -17.0F, 0.0F)); PartDefinition cube_r1 = rightwing.addOrReplaceChild("cube_r1", CubeListBuilder.create().texOffs(60, 58).addBox(15.0F, -14.0F, 11.0F, 2.0F, 16.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-12.7747F, 14.9515F, -13.0F, 0.0F, 0.0F, -0.1309F)); PartDefinition leftwing = wings.addOrReplaceChild("leftwing", CubeListBuilder.create(), PartPose.offset(-7.0F, -17.0F, 0.0F)); PartDefinition cube_r2 = leftwing.addOrReplaceChild("cube_r2", CubeListBuilder.create().texOffs(60, 32).addBox(-17.0F, -14.0F, 11.0F, 2.0F, 16.0F, 4.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(12.2192F, 15.1698F, -13.0F, 0.0F, 0.0F, 0.1309F)); PartDefinition feet = emperor_penguin.addOrReplaceChild("feet", CubeListBuilder.create(), PartPose.offset(2.0F, -2.0F, 0.0F)); PartDefinition rightfoot = feet.addOrReplaceChild("rightfoot", CubeListBuilder.create().texOffs(0, 7).addBox(2.0F, 0.0F, 6.0F, 3.0F, 2.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition leftfoot = feet.addOrReplaceChild("leftfoot", CubeListBuilder.create().texOffs(0, 0).addBox(-5.0F, 0.0F, 6.0F, 3.0F, 2.0F, 5.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition tail = emperor_penguin.addOrReplaceChild("tail", CubeListBuilder.create(), PartPose.offset(8.25F, -1.75F, 0.75F)); PartDefinition part1 = tail.addOrReplaceChild("part1", CubeListBuilder.create().texOffs(0, 36).addBox(-7.25F, 0.5F, -10.0F, 2.0F, 1.0F, 2.0F, new CubeDeformation(0.0F)), PartPose.offset(0.0F, 0.0F, 0.0F)); PartDefinition part2 = tail.addOrReplaceChild("part2", CubeListBuilder.create(), PartPose.offset(-6.25F, 0.25F, -0.75F)); PartDefinition cube_r3 = part2.addOrReplaceChild("cube_r3", CubeListBuilder.create().texOffs(0, 0).addBox(0.5F, -1.0F, -13.0F, 1.0F, 1.0F, 1.0F, new CubeDeformation(0.0F)), PartPose.offsetAndRotation(-1.0F, 1.25F, 2.75F, 0.0349F, 0.0F, 0.0F)); return LayerDefinition.create(meshdefinition, 128, 128); } @Override public void setupAnim(T entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) { this.root().getAllParts().forEach(ModelPart::resetPose); this.applyHeadRotation(entity, netHeadYaw, headPitch, ageInTicks); this.animateWalk(EmperorPenguinAnimationDefinitions.WALKING, limbSwing, limbSwingAmount, 2f, 2.5f);
this.animate(((EmperorPenguinEntity) entity).idleAnimationState, EmperorPenguinAnimationDefinitions.WINGING, ageInTicks, 1f);
1
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,717
columnDecryptionSetup.getOrdinal(), -1); } } return ParquetMetadataConverter.fromParquetOffsetIndex( Util.readOffsetIndex(f, offsetIndexDecryptor, offsetIndexAAD)); } @Override public void close() throws IOException { try { if (f != null) { f.close(); } } finally { options.getCodecFactory().release(); } } public ParquetMetadata getFooter() { return footer; } /* * Builder to concatenate the buffers of the discontinuous parts for the same column. These parts are generated as a * result of the column-index based filtering when some pages might be skipped at reading. */ private class ChunkListBuilder { private class ChunkData { final List<ByteBuffer> buffers = new ArrayList<>(); OffsetIndex offsetIndex; } private final Map<ChunkDescriptor, ChunkData> map = new HashMap<>(); private ChunkDescriptor lastDescriptor; private final long rowCount; private SeekableInputStream f; public ChunkListBuilder(long rowCount) { this.rowCount = rowCount; } void add(ChunkDescriptor descriptor, List<ByteBuffer> buffers, SeekableInputStream f) { map.computeIfAbsent(descriptor, d -> new ChunkData()).buffers.addAll(buffers); lastDescriptor = descriptor; this.f = f; } void setOffsetIndex(ChunkDescriptor descriptor, OffsetIndex offsetIndex) { map.computeIfAbsent(descriptor, d -> new ChunkData()).offsetIndex = offsetIndex; } List<Chunk> build() { Set<Entry<ChunkDescriptor, ChunkData>> entries = map.entrySet(); List<Chunk> chunks = new ArrayList<>(entries.size()); for (Entry<ChunkDescriptor, ChunkData> entry : entries) { ChunkDescriptor descriptor = entry.getKey(); ChunkData data = entry.getValue(); if (descriptor.equals(lastDescriptor)) { // because of a bug, the last chunk might be larger than descriptor.size chunks.add( new WorkaroundChunk(lastDescriptor, data.buffers, f, data.offsetIndex, rowCount)); } else { chunks.add(new Chunk(descriptor, data.buffers, data.offsetIndex, rowCount)); } } return chunks; } } /** The data for a column chunk */ private class Chunk { protected final ChunkDescriptor descriptor; protected final ByteBufferInputStream stream; final OffsetIndex offsetIndex; final long rowCount; /** * @param descriptor descriptor for the chunk * @param buffers ByteBuffers that contain the chunk * @param offsetIndex the offset index for this column; might be null */ public Chunk( ChunkDescriptor descriptor, List<ByteBuffer> buffers, OffsetIndex offsetIndex, long rowCount) { this.descriptor = descriptor; this.stream = ByteBufferInputStream.wrap(buffers); this.offsetIndex = offsetIndex; this.rowCount = rowCount; } protected PageHeader readPageHeader() throws IOException { return readPageHeader(null, null); } protected PageHeader readPageHeader(BlockCipher.Decryptor blockDecryptor, byte[] pageHeaderAAD) throws IOException { return Util.readPageHeader(stream, blockDecryptor, pageHeaderAAD); } /** * Calculate checksum of input bytes, throw decoding exception if it does not match the provided * reference crc */ private void verifyCrc(int referenceCrc, byte[] bytes, String exceptionMsg) { crc.reset(); crc.update(bytes); if (crc.getValue() != ((long) referenceCrc & 0xffffffffL)) { throw new ParquetDecodingException(exceptionMsg); } } /** * Read all of the pages in a given column chunk. * * @return the list of pages */
/* * 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))) { long startingPos = range.getOffset(); // first part or not consecutive => new list if (currentParts == null || currentParts.endPos() != startingPos) { currentParts = new ConsecutivePartList(startingPos); allParts.add(currentParts); } ChunkDescriptor chunkDescriptor = new ChunkDescriptor(columnDescriptor, mc, startingPos, range.getLength()); currentParts.addChunk(chunkDescriptor); builder.setOffsetIndex(chunkDescriptor, filteredOffsetIndex); } } } // actually read all the chunks for (ConsecutivePartList consecutiveChunks : allParts) { consecutiveChunks.readAll(f, builder); } for (Chunk chunk : builder.build()) { readChunkPages(chunk, block, rowGroup); } return rowGroup; } private void readChunkPages(Chunk chunk, BlockMetaData block, ColumnChunkPageReadStore rowGroup) throws IOException { if (null == fileDecryptor || fileDecryptor.plaintextFile()) { rowGroup.addColumn(chunk.descriptor.col, chunk.readAllPages()); return; } // Encrypted file ColumnPath columnPath = ColumnPath.get(chunk.descriptor.col.getPath()); InternalColumnDecryptionSetup columnDecryptionSetup = fileDecryptor.getColumnSetup(columnPath); if (!columnDecryptionSetup.isEncrypted()) { // plaintext column rowGroup.addColumn(chunk.descriptor.col, chunk.readAllPages()); } else { // encrypted column rowGroup.addColumn( chunk.descriptor.col, chunk.readAllPages( columnDecryptionSetup.getMetaDataDecryptor(), columnDecryptionSetup.getDataDecryptor(), fileDecryptor.getFileAAD(), block.getOrdinal(), columnDecryptionSetup.getOrdinal())); } } public ColumnIndexStore getColumnIndexStore(int blockIndex) { ColumnIndexStore ciStore = blockIndexStores.get(blockIndex); if (ciStore == null) { ciStore = org.apache.parquet.local.ColumnIndexStoreImpl.create( this, blocks.get(blockIndex), paths.keySet()); blockIndexStores.set(blockIndex, ciStore); } return ciStore; } private RowRanges getRowRanges(int blockIndex) { assert FilterCompat.isFilteringRequired(options.getRecordFilter()) : "Should not be invoked if filter is null or NOOP"; RowRanges rowRanges = blockRowRanges.get(blockIndex); if (rowRanges == null) { rowRanges = ColumnIndexFilter.calculateRowRanges( options.getRecordFilter(), getColumnIndexStore(blockIndex), paths.keySet(), blocks.get(blockIndex).getRowCount()); blockRowRanges.set(blockIndex, rowRanges); } return rowRanges; } public boolean skipNextRowGroup() { return advanceToNextBlock(); } private boolean advanceToNextBlock() { if (currentBlock == blocks.size()) { return false; } // update the current block and instantiate a dictionary reader for it ++currentBlock; this.nextDictionaryReader = null; return true; } /** * Returns a {@link DictionaryPageReadStore} for the row group that would be returned by calling * {@link #readNextRowGroup()} or skipped by calling {@link #skipNextRowGroup()}. * * @return a DictionaryPageReadStore for the next row group */ public DictionaryPageReadStore getNextDictionaryReader() { if (nextDictionaryReader == null) { this.nextDictionaryReader = getDictionaryReader(currentBlock); } return nextDictionaryReader; } public DictionaryPageReader getDictionaryReader(int blockIndex) { if (blockIndex < 0 || blockIndex >= blocks.size()) { return null; } return new DictionaryPageReader(this, blocks.get(blockIndex)); } public DictionaryPageReader getDictionaryReader(BlockMetaData block) { return new DictionaryPageReader(this, block); } /** * Reads and decompresses a dictionary page for the given column chunk. * * <p>Returns null if the given column chunk has no dictionary page. * * @param meta a column's ColumnChunkMetaData to read the dictionary from * @return an uncompressed DictionaryPage or null * @throws IOException if there is an error while reading the dictionary */ DictionaryPage readDictionary(ColumnChunkMetaData meta) throws IOException { if (!meta.hasDictionaryPage()) { return null; } // TODO: this should use getDictionaryPageOffset() but it isn't reliable. if (f.getPos() != meta.getStartingPos()) { f.seek(meta.getStartingPos()); } boolean encryptedColumn = false; InternalColumnDecryptionSetup columnDecryptionSetup = null; byte[] dictionaryPageAAD = null; BlockCipher.Decryptor pageDecryptor = null; if (null != fileDecryptor && !fileDecryptor.plaintextFile()) { columnDecryptionSetup = fileDecryptor.getColumnSetup(meta.getPath()); if (columnDecryptionSetup.isEncrypted()) { encryptedColumn = true; } } PageHeader pageHeader; if (!encryptedColumn) { pageHeader = Util.readPageHeader(f); } else { byte[] dictionaryPageHeaderAAD = AesCipher.createModuleAAD( fileDecryptor.getFileAAD(), ModuleType.DictionaryPageHeader, meta.getRowGroupOrdinal(), columnDecryptionSetup.getOrdinal(), -1); pageHeader = Util.readPageHeader( f, columnDecryptionSetup.getMetaDataDecryptor(), dictionaryPageHeaderAAD); dictionaryPageAAD = AesCipher.createModuleAAD( fileDecryptor.getFileAAD(), ModuleType.DictionaryPage, meta.getRowGroupOrdinal(), columnDecryptionSetup.getOrdinal(), -1); pageDecryptor = columnDecryptionSetup.getDataDecryptor(); } if (!pageHeader.isSetDictionary_page_header()) { return null; // TODO: should this complain? } DictionaryPage compressedPage = readCompressedDictionary(pageHeader, f, pageDecryptor, dictionaryPageAAD); BytesInputDecompressor decompressor = options.getCodecFactory().getDecompressor(meta.getCodec()); return new DictionaryPage( decompressor.decompress(compressedPage.getBytes(), compressedPage.getUncompressedSize()), compressedPage.getDictionarySize(), compressedPage.getEncoding()); } private DictionaryPage readCompressedDictionary( PageHeader pageHeader, SeekableInputStream fin, BlockCipher.Decryptor pageDecryptor, byte[] dictionaryPageAAD) throws IOException { DictionaryPageHeader dictHeader = pageHeader.getDictionary_page_header(); int uncompressedPageSize = pageHeader.getUncompressed_page_size(); int compressedPageSize = pageHeader.getCompressed_page_size(); byte[] dictPageBytes = new byte[compressedPageSize]; fin.readFully(dictPageBytes); BytesInput bin = BytesInput.from(dictPageBytes); if (null != pageDecryptor) { bin = BytesInput.from(pageDecryptor.decrypt(bin.toByteArray(), dictionaryPageAAD)); } return new DictionaryPage( bin, uncompressedPageSize, dictHeader.getNum_values(), converter.getEncoding(dictHeader.getEncoding())); } public BloomFilterReader getBloomFilterDataReader(int blockIndex) { if (blockIndex < 0 || blockIndex >= blocks.size()) { return null; } return new BloomFilterReader(this, blocks.get(blockIndex)); } public BloomFilterReader getBloomFilterDataReader(BlockMetaData block) { return new BloomFilterReader(this, block); } /** * Reads Bloom filter data for the given column chunk. * * @param meta a column's ColumnChunkMetaData to read the dictionary from * @return an BloomFilter object. * @throws IOException if there is an error while reading the Bloom filter. */ public BloomFilter readBloomFilter(ColumnChunkMetaData meta) throws IOException { long bloomFilterOffset = meta.getBloomFilterOffset(); if (bloomFilterOffset < 0) { return null; } // Prepare to decrypt Bloom filter (for encrypted columns) BlockCipher.Decryptor bloomFilterDecryptor = null; byte[] bloomFilterHeaderAAD = null; byte[] bloomFilterBitsetAAD = null; if (null != fileDecryptor && !fileDecryptor.plaintextFile()) { InternalColumnDecryptionSetup columnDecryptionSetup = fileDecryptor.getColumnSetup(meta.getPath()); if (columnDecryptionSetup.isEncrypted()) { bloomFilterDecryptor = columnDecryptionSetup.getMetaDataDecryptor(); bloomFilterHeaderAAD = AesCipher.createModuleAAD( fileDecryptor.getFileAAD(), ModuleType.BloomFilterHeader, meta.getRowGroupOrdinal(), columnDecryptionSetup.getOrdinal(), -1); bloomFilterBitsetAAD = AesCipher.createModuleAAD( fileDecryptor.getFileAAD(), ModuleType.BloomFilterBitset, meta.getRowGroupOrdinal(), columnDecryptionSetup.getOrdinal(), -1); } } // Read Bloom filter data header. f.seek(bloomFilterOffset); BloomFilterHeader bloomFilterHeader; try { bloomFilterHeader = Util.readBloomFilterHeader(f, bloomFilterDecryptor, bloomFilterHeaderAAD); } catch (IOException e) { LOG.warn("read no bloom filter"); return null; } int numBytes = bloomFilterHeader.getNumBytes(); if (numBytes <= 0 || numBytes > BlockSplitBloomFilter.UPPER_BOUND_BYTES) { LOG.warn("the read bloom filter size is wrong, size is {}", bloomFilterHeader.getNumBytes()); return null; } if (!bloomFilterHeader.getHash().isSetXXHASH() || !bloomFilterHeader.getAlgorithm().isSetBLOCK() || !bloomFilterHeader.getCompression().isSetUNCOMPRESSED()) { LOG.warn( "the read bloom filter is not supported yet, algorithm = {}, hash = {}, compression = {}", bloomFilterHeader.getAlgorithm(), bloomFilterHeader.getHash(), bloomFilterHeader.getCompression()); return null; } byte[] bitset; if (null == bloomFilterDecryptor) { bitset = new byte[numBytes]; f.readFully(bitset); } else { bitset = bloomFilterDecryptor.decrypt(f, bloomFilterBitsetAAD); if (bitset.length != numBytes) { throw new ParquetCryptoRuntimeException("Wrong length of decrypted bloom filter bitset"); } } return new BlockSplitBloomFilter(bitset); } /** * @param column the column chunk which the column index is to be returned for * @return the column index for the specified column chunk or {@code null} if there is no index * @throws IOException if any I/O error occurs during reading the file */ @Private public ColumnIndex readColumnIndex(ColumnChunkMetaData column) throws IOException { IndexReference ref = column.getColumnIndexReference(); if (ref == null) { return null; } f.seek(ref.getOffset()); BlockCipher.Decryptor columnIndexDecryptor = null; byte[] columnIndexAAD = null; if (null != fileDecryptor && !fileDecryptor.plaintextFile()) { InternalColumnDecryptionSetup columnDecryptionSetup = fileDecryptor.getColumnSetup(column.getPath()); if (columnDecryptionSetup.isEncrypted()) { columnIndexDecryptor = columnDecryptionSetup.getMetaDataDecryptor(); columnIndexAAD = AesCipher.createModuleAAD( fileDecryptor.getFileAAD(), ModuleType.ColumnIndex, column.getRowGroupOrdinal(), columnDecryptionSetup.getOrdinal(), -1); } } return ParquetMetadataConverter.fromParquetColumnIndex( column.getPrimitiveType(), Util.readColumnIndex(f, columnIndexDecryptor, columnIndexAAD)); } /** * @param column the column chunk which the offset index is to be returned for * @return the offset index for the specified column chunk or {@code null} if there is no index * @throws IOException if any I/O error occurs during reading the file */ @Private public OffsetIndex readOffsetIndex(ColumnChunkMetaData column) throws IOException { IndexReference ref = column.getOffsetIndexReference(); if (ref == null) { return null; } f.seek(ref.getOffset()); BlockCipher.Decryptor offsetIndexDecryptor = null; byte[] offsetIndexAAD = null; if (null != fileDecryptor && !fileDecryptor.plaintextFile()) { InternalColumnDecryptionSetup columnDecryptionSetup = fileDecryptor.getColumnSetup(column.getPath()); if (columnDecryptionSetup.isEncrypted()) { offsetIndexDecryptor = columnDecryptionSetup.getMetaDataDecryptor(); offsetIndexAAD = AesCipher.createModuleAAD( fileDecryptor.getFileAAD(), ModuleType.OffsetIndex, column.getRowGroupOrdinal(), columnDecryptionSetup.getOrdinal(), -1); } } return ParquetMetadataConverter.fromParquetOffsetIndex( Util.readOffsetIndex(f, offsetIndexDecryptor, offsetIndexAAD)); } @Override public void close() throws IOException { try { if (f != null) { f.close(); } } finally { options.getCodecFactory().release(); } } public ParquetMetadata getFooter() { return footer; } /* * Builder to concatenate the buffers of the discontinuous parts for the same column. These parts are generated as a * result of the column-index based filtering when some pages might be skipped at reading. */ private class ChunkListBuilder { private class ChunkData { final List<ByteBuffer> buffers = new ArrayList<>(); OffsetIndex offsetIndex; } private final Map<ChunkDescriptor, ChunkData> map = new HashMap<>(); private ChunkDescriptor lastDescriptor; private final long rowCount; private SeekableInputStream f; public ChunkListBuilder(long rowCount) { this.rowCount = rowCount; } void add(ChunkDescriptor descriptor, List<ByteBuffer> buffers, SeekableInputStream f) { map.computeIfAbsent(descriptor, d -> new ChunkData()).buffers.addAll(buffers); lastDescriptor = descriptor; this.f = f; } void setOffsetIndex(ChunkDescriptor descriptor, OffsetIndex offsetIndex) { map.computeIfAbsent(descriptor, d -> new ChunkData()).offsetIndex = offsetIndex; } List<Chunk> build() { Set<Entry<ChunkDescriptor, ChunkData>> entries = map.entrySet(); List<Chunk> chunks = new ArrayList<>(entries.size()); for (Entry<ChunkDescriptor, ChunkData> entry : entries) { ChunkDescriptor descriptor = entry.getKey(); ChunkData data = entry.getValue(); if (descriptor.equals(lastDescriptor)) { // because of a bug, the last chunk might be larger than descriptor.size chunks.add( new WorkaroundChunk(lastDescriptor, data.buffers, f, data.offsetIndex, rowCount)); } else { chunks.add(new Chunk(descriptor, data.buffers, data.offsetIndex, rowCount)); } } return chunks; } } /** The data for a column chunk */ private class Chunk { protected final ChunkDescriptor descriptor; protected final ByteBufferInputStream stream; final OffsetIndex offsetIndex; final long rowCount; /** * @param descriptor descriptor for the chunk * @param buffers ByteBuffers that contain the chunk * @param offsetIndex the offset index for this column; might be null */ public Chunk( ChunkDescriptor descriptor, List<ByteBuffer> buffers, OffsetIndex offsetIndex, long rowCount) { this.descriptor = descriptor; this.stream = ByteBufferInputStream.wrap(buffers); this.offsetIndex = offsetIndex; this.rowCount = rowCount; } protected PageHeader readPageHeader() throws IOException { return readPageHeader(null, null); } protected PageHeader readPageHeader(BlockCipher.Decryptor blockDecryptor, byte[] pageHeaderAAD) throws IOException { return Util.readPageHeader(stream, blockDecryptor, pageHeaderAAD); } /** * Calculate checksum of input bytes, throw decoding exception if it does not match the provided * reference crc */ private void verifyCrc(int referenceCrc, byte[] bytes, String exceptionMsg) { crc.reset(); crc.update(bytes); if (crc.getValue() != ((long) referenceCrc & 0xffffffffL)) { throw new ParquetDecodingException(exceptionMsg); } } /** * Read all of the pages in a given column chunk. * * @return the list of pages */
public ColumnChunkPageReader readAllPages() throws IOException {
0
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,104
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; }
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;
1
2023-12-28 13:53:01+00:00
8k
Yanyutin753/PandoraNext-TokensTool
rearServer/src/main/java/com/tokensTool/pandoraNext/service/impl/poolServiceImpl.java
[ { "identifier": "poolToken", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/poolToken.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class poolToken {\n /**\n * pool_token 专属名(文件唯一)\n */\n private String poolName;\n\n /**\n * pool_token ...
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.tokensTool.pandoraNext.pojo.poolToken; import com.tokensTool.pandoraNext.pojo.systemSetting; import com.tokensTool.pandoraNext.pojo.token; import com.tokensTool.pandoraNext.service.poolService; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.regex.Pattern;
4,845
boolean b = addKey(poolToken, strings); if (b && poolToken.getPriority() != 0) { boolean b1 = getPriority(poolToken, strings); if (b1) { log.info("修改优先级成功!"); } } if (b) { log.info("pool_token进one-Api成功!"); } else { return "pool_token添加进one-api失败!"; } } String parent = selectFile(); File jsonFile = new File(parent); Path jsonFilePath = Paths.get(parent); ObjectMapper objectMapper = new ObjectMapper(); ObjectNode rootNode; // 如果 JSON 文件不存在,创建一个新的 JSON 对象 if (!jsonFile.exists()) { // 创建文件 Files.createFile(jsonFilePath); System.out.println("pool.json创建完成: " + jsonFilePath); rootNode = objectMapper.createObjectNode(); } else { if (Files.exists(jsonFilePath) && Files.size(jsonFilePath) > 0) { rootNode = objectMapper.readTree(jsonFile).deepCopy(); } else { rootNode = objectMapper.createObjectNode(); } } // 创建要添加的新数据 ObjectNode newData = objectMapper.createObjectNode(); newData.put("poolToken", resPoolToken); List<String> shareTokensList = poolToken.getShareTokens(); ArrayNode arrayNode = objectMapper.createArrayNode(); for (String value : shareTokensList) { arrayNode.add(value); } newData.set("shareTokens", arrayNode); //0.5.0 newData.put("checkPool", true); newData.put("intoOneApi", poolToken.isIntoOneApi()); newData.put("pandoraNextGpt4", poolToken.isPandoraNextGpt4()); newData.put("oneApi_pandoraUrl", poolToken.getOneApi_pandoraUrl()); LocalDateTime now = LocalDateTime.now(); newData.put("poolTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); // 将新数据添加到 JSON 树中 rootNode.put(poolToken.getPoolName(), newData); // 将修改后的数据写回到文件 objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFile, rootNode); log.info("数据成功添加到 JSON 文件中。"); return "pool_token数据添加成功"; } catch (IOException e) { e.printStackTrace(); return "添加失败!"; } } /** * 删除通过poolToken里的poolName删除poolToken * * @param poolToken * @return */ public String deletePoolToken(poolToken poolToken) { try { String name = poolToken.getPoolName(); String parent = selectFile(); String deletePoolToken = poolToken.getPoolToken(); //确保注销成功! if (deletePoolToken != null && deletePoolToken.contains("pk")) { String s = apiService.deletePoolToken(deletePoolToken); if (s == null) { log.info("删除失败,看看自己的poolToken是否合法"); } } if (poolToken.isIntoOneApi()) { String[] strings = systemService.selectOneAPi(); boolean b = deleteKeyId(poolToken, strings); if (!b) { return "删除oneApi中的poolToken失败!"; } } ObjectMapper objectMapper = new ObjectMapper(); // 读取JSON文件并获取根节点 JsonNode rootNode = objectMapper.readTree(new File(parent)); // 检查要删除的节点是否存在 JsonNode nodeToRemove = rootNode.get(name); if (nodeToRemove != null) { // 创建新的 ObjectNode,并复制原始节点内容 ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode(); newObjectNode.setAll((ObjectNode) rootNode); // 删除节点 newObjectNode.remove(name); // 将修改后的 newObjectNode 写回文件 objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode); log.info("删除成功"); return "删除成功!"; } else { System.out.println("Node not found: " + name); return "节点未找到!"; } } catch (IOException e) { e.printStackTrace(); } return "删除失败"; } /** * 从poolToken里拿到share_tokens的集合,传参给share_token * * @param shareName * @return */ public String getShareTokens(List<String> shareName) { try { StringBuffer resToken = new StringBuffer();
package com.tokensTool.pandoraNext.service.impl; /** * @author Yangyang * @create 2023-12-10 11:59 */ @Service @Slf4j public class poolServiceImpl implements poolService { private static final String gpt3Models = "gpt-3.5-turbo"; private static final String gpt4Models = "gpt-3.5-turbo,gpt-4"; private static final String openAiChat = "/v1/chat/completions"; private static final String oneApiSelect = "api/channel/?p=0"; private static final String oneAPiChannel = "api/channel/"; private final String deploy = "default"; @Value("${deployPosition}") private String deployPosition; @Autowired private apiServiceImpl apiService; @Autowired private systemServiceImpl systemService; /** * 遍历文件 * * @return */ public String selectFile() { String projectRoot; if (deploy.equals(deployPosition)) { projectRoot = System.getProperty("user.dir"); } else { projectRoot = deployPosition; } String parent = projectRoot + File.separator + "pool.json"; File jsonFile = new File(parent); Path jsonFilePath = Paths.get(parent); // 如果 JSON 文件不存在,创建一个新的 JSON 对象 if (!jsonFile.exists()) { try { // 创建文件pool.json Files.createFile(jsonFilePath); // 往 pool.json 文件中添加一个空数组,防止重启报错 Files.writeString(jsonFilePath, "{}"); log.info("新建pool.json,并初始化pool.json成功!"); } catch (IOException e) { throw new RuntimeException(e); } } return parent; } /** * 初始化pool.json * 添加checkPool变量,初始化为true * 启动的时候自动全部添加 */ public String initializeCheckPool() { try { String parent = selectFile(); ObjectMapper objectMapper = new ObjectMapper(); // 读取JSON文件并获取根节点 JsonNode rootNode = objectMapper.readTree(new File(parent)); // 遍历根节点的所有子节点 if (rootNode.isObject()) { ObjectNode rootObjectNode = (ObjectNode) rootNode; // 遍历所有子节点 Iterator<Map.Entry<String, JsonNode>> fields = rootObjectNode.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); // 获取子节点的名称 String nodeName = entry.getKey(); // 获取子节点 JsonNode nodeToModify = entry.getValue(); if (nodeToModify != null && nodeToModify.isObject()) { // 创建新的 ObjectNode,并复制原始节点内容 ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode(); newObjectNode.setAll(rootObjectNode); // 获取要修改的节点 ObjectNode nodeToModifyInNew = newObjectNode.with(nodeName); // 初始化checkSession的值为true if (!nodeToModifyInNew.has("checkPool")) { nodeToModifyInNew.put("checkPool", true); log.info("为节点 " + nodeName + " 添加 checkPool 变量成功!"); } // 初始化intoOneApi的值为false if (!nodeToModifyInNew.has("intoOneApi")) { nodeToModifyInNew.put("intoOneApi", false); log.info("为节点 " + nodeName + " 添加 intoOneApi 变量成功!"); } // 初始化pandoraNextGpt4的值为false if (!nodeToModifyInNew.has("pandoraNextGpt4")) { nodeToModifyInNew.put("pandoraNextGpt4", false); log.info("为节点 " + nodeName + " 添加 pandoraNextGpt4 变量成功!"); } // 初始化oneApi_pandoraUrl的值为"" if (!nodeToModifyInNew.has("oneApi_pandoraUrl")) { nodeToModifyInNew.put("oneApi_pandoraUrl", ""); log.info("为节点 " + nodeName + " 添加 oneApi_pandoraUrl 变量成功!"); } // 将修改后的 newObjectNode 写回文件 objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode); } } return "为所有子节点添加 checkPool 变量成功!"; } } catch (IOException e) { e.printStackTrace(); } return "为所有子节点添加 checkPool 变量失败!"; } /** * 通过name遍历poolToken * * @param name * @return */ public List<poolToken> selectPoolToken(String name) { List<poolToken> res = new ArrayList<>(); try { String parent = selectFile(); ObjectMapper objectMapper = new ObjectMapper(); // 读取JSON文件并获取根节点 JsonNode rootNode = objectMapper.readTree(new File(parent)); // 遍历所有字段 Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> entry = fields.next(); String nodeName = entry.getKey(); if (nodeName.contains(name)) { poolToken temRes = new poolToken(); temRes.setPoolName(nodeName); // 获取对应的节点 JsonNode temNode = rootNode.get(nodeName); temRes.setPoolToken(temNode.has("poolToken") ? temNode.get("poolToken").asText() : ""); temRes.setPoolTime(temNode.has("poolTime") ? temNode.get("poolTime").asText() : ""); // 将 JsonNode 转换为 List<String> List<String> sharedTokens = new ArrayList<>(); if (temNode.has("shareTokens") && temNode.get("shareTokens").isArray()) { for (JsonNode tokenNode : temNode.get("shareTokens")) { sharedTokens.add(tokenNode.asText()); } } temRes.setShareTokens(sharedTokens); temRes.setCheckPool(!temNode.has("checkPool") || temNode.get("checkPool").asBoolean()); //0.5.0 temRes.setIntoOneApi(temNode.has("intoOneApi") && temNode.get("intoOneApi").asBoolean()); temRes.setPandoraNextGpt4(temNode.has("pandoraNextGpt4") && temNode.get("pandoraNextGpt4").asBoolean()); temRes.setOneApi_pandoraUrl(temNode.has("oneApi_pandoraUrl") ? temNode.get("oneApi_pandoraUrl").asText() : ""); temRes.setPriority(temNode.has("priority") ? temNode.get("priority").asInt() : 0); res.add(temRes); } } } catch (Exception e) { e.printStackTrace(); return null; } return res; } /** * 仅支持修改poolToken的时间和值 * 修改poolToken的时间 * 修改poolToken的值 * * @param poolToken * @return 修改成功!or 节点未找到或不是对象! * @throws Exception */ public String requirePoolToken(poolToken poolToken) { try { String parent = selectFile(); ObjectMapper objectMapper = new ObjectMapper(); // 读取JSON文件并获取根节点 JsonNode rootNode = objectMapper.readTree(new File(parent)); // 要修改的节点名称 String nodeNameToModify = poolToken.getPoolName(); // 获取要修改的节点 JsonNode nodeToModify = rootNode.get(nodeNameToModify); if (nodeToModify != null && nodeToModify.isObject()) { // 创建新的 ObjectNode,并复制原始节点内容 ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode(); newObjectNode.setAll((ObjectNode) rootNode); // 获取要修改的节点 ObjectNode nodeToModifyInNew = newObjectNode.with(nodeNameToModify); //仅支持修改poolToken的时间和值 LocalDateTime now = LocalDateTime.now(); nodeToModifyInNew.put("checkPool", poolToken.isCheckPool()); nodeToModifyInNew.put("poolToken", poolToken.getPoolToken()); nodeToModifyInNew.put("poolTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); // 将修改后的 newObjectNode 写回文件 objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode); log.info("修改成功!"); return "修改成功!"; } else { log.info("节点未找到或不是对象,请检查pool.json! " + nodeNameToModify); return "节点未找到或不是对象!"; } } catch (Exception e) { throw new RuntimeException(e); } } public String requireCheckPoolToken(poolToken poolToken) { try { String parent = selectFile(); ObjectMapper objectMapper = new ObjectMapper(); // 读取JSON文件并获取根节点 JsonNode rootNode = objectMapper.readTree(new File(parent)); // 要修改的节点名称 String nodeNameToModify = poolToken.getPoolName(); // 获取要修改的节点 JsonNode nodeToModify = rootNode.get(nodeNameToModify); if (nodeToModify != null && nodeToModify.isObject()) { // 创建新的 ObjectNode,并复制原始节点内容 ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode(); newObjectNode.setAll((ObjectNode) rootNode); // 获取要修改的节点 ObjectNode nodeToModifyInNew = newObjectNode.with(nodeNameToModify); //仅支持修改poolToken的时间和值 LocalDateTime now = LocalDateTime.now(); nodeToModifyInNew.put("checkPool", poolToken.isCheckPool()); // 将修改后的 newObjectNode 写回文件 objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode); return "修改成功!"; } else { log.info("节点未找到或不是对象,请检查pool.json! " + nodeNameToModify); return "节点未找到或不是对象!"; } } catch (Exception e) { throw new RuntimeException(e); } } /** * 通过poolToken添加PoolToken * * @param poolToken * @return */ public String addPoolToken(poolToken poolToken) { String resPoolToken; try { String shareTokens = getShareTokens(poolToken.getShareTokens()); String temPoolToken = poolToken.getPoolToken(); if (temPoolToken != null && temPoolToken.contains("pk")) { resPoolToken = apiService.getPoolToken(temPoolToken, shareTokens); } else { resPoolToken = apiService.getPoolToken("", shareTokens); } } catch (Exception ex) { throw new RuntimeException(ex); } try { if (resPoolToken == null) { return "pool_token数据添加失败,请先按全部选择并生成,并确保url配对正确!"; } poolToken.setPoolToken(resPoolToken); if (poolToken.isIntoOneApi()) { String[] strings = systemService.selectOneAPi(); boolean b = addKey(poolToken, strings); if (b && poolToken.getPriority() != 0) { boolean b1 = getPriority(poolToken, strings); if (b1) { log.info("修改优先级成功!"); } } if (b) { log.info("pool_token进one-Api成功!"); } else { return "pool_token添加进one-api失败!"; } } String parent = selectFile(); File jsonFile = new File(parent); Path jsonFilePath = Paths.get(parent); ObjectMapper objectMapper = new ObjectMapper(); ObjectNode rootNode; // 如果 JSON 文件不存在,创建一个新的 JSON 对象 if (!jsonFile.exists()) { // 创建文件 Files.createFile(jsonFilePath); System.out.println("pool.json创建完成: " + jsonFilePath); rootNode = objectMapper.createObjectNode(); } else { if (Files.exists(jsonFilePath) && Files.size(jsonFilePath) > 0) { rootNode = objectMapper.readTree(jsonFile).deepCopy(); } else { rootNode = objectMapper.createObjectNode(); } } // 创建要添加的新数据 ObjectNode newData = objectMapper.createObjectNode(); newData.put("poolToken", resPoolToken); List<String> shareTokensList = poolToken.getShareTokens(); ArrayNode arrayNode = objectMapper.createArrayNode(); for (String value : shareTokensList) { arrayNode.add(value); } newData.set("shareTokens", arrayNode); //0.5.0 newData.put("checkPool", true); newData.put("intoOneApi", poolToken.isIntoOneApi()); newData.put("pandoraNextGpt4", poolToken.isPandoraNextGpt4()); newData.put("oneApi_pandoraUrl", poolToken.getOneApi_pandoraUrl()); LocalDateTime now = LocalDateTime.now(); newData.put("poolTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); // 将新数据添加到 JSON 树中 rootNode.put(poolToken.getPoolName(), newData); // 将修改后的数据写回到文件 objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFile, rootNode); log.info("数据成功添加到 JSON 文件中。"); return "pool_token数据添加成功"; } catch (IOException e) { e.printStackTrace(); return "添加失败!"; } } /** * 删除通过poolToken里的poolName删除poolToken * * @param poolToken * @return */ public String deletePoolToken(poolToken poolToken) { try { String name = poolToken.getPoolName(); String parent = selectFile(); String deletePoolToken = poolToken.getPoolToken(); //确保注销成功! if (deletePoolToken != null && deletePoolToken.contains("pk")) { String s = apiService.deletePoolToken(deletePoolToken); if (s == null) { log.info("删除失败,看看自己的poolToken是否合法"); } } if (poolToken.isIntoOneApi()) { String[] strings = systemService.selectOneAPi(); boolean b = deleteKeyId(poolToken, strings); if (!b) { return "删除oneApi中的poolToken失败!"; } } ObjectMapper objectMapper = new ObjectMapper(); // 读取JSON文件并获取根节点 JsonNode rootNode = objectMapper.readTree(new File(parent)); // 检查要删除的节点是否存在 JsonNode nodeToRemove = rootNode.get(name); if (nodeToRemove != null) { // 创建新的 ObjectNode,并复制原始节点内容 ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode(); newObjectNode.setAll((ObjectNode) rootNode); // 删除节点 newObjectNode.remove(name); // 将修改后的 newObjectNode 写回文件 objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode); log.info("删除成功"); return "删除成功!"; } else { System.out.println("Node not found: " + name); return "节点未找到!"; } } catch (IOException e) { e.printStackTrace(); } return "删除失败"; } /** * 从poolToken里拿到share_tokens的集合,传参给share_token * * @param shareName * @return */ public String getShareTokens(List<String> shareName) { try { StringBuffer resToken = new StringBuffer();
List<token> tokens = apiService.selectToken("");
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,111
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); }else if (anno instanceof AkaliHot){ AkaliRuleManager.registerHotRule((AkaliHot) anno, method); }else{ throw new RuntimeException("annotation type error"); }
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); }else if (anno instanceof AkaliHot){ AkaliRuleManager.registerHotRule((AkaliHot) anno, method); }else{ throw new RuntimeException("annotation type error"); }
return SphEngine.process(bean, method, args, methodStr, akaliStrategyEnum);
3
2023-11-10 07:28:38+00:00
8k
quarkiverse/quarkus-langchain4j
hugging-face/runtime/src/main/java/io/quarkiverse/langchain4j/huggingface/runtime/HuggingFaceRecorder.java
[ { "identifier": "firstOrDefault", "path": "core/runtime/src/main/java/io/quarkiverse/langchain4j/runtime/OptionalUtil.java", "snippet": "@SafeVarargs\npublic static <T> T firstOrDefault(T defaultValue, Optional<T>... values) {\n for (Optional<T> o : values) {\n if (o != null && o.isPresent()) ...
import static io.quarkiverse.langchain4j.runtime.OptionalUtil.firstOrDefault; import java.net.URL; import java.util.Optional; import java.util.function.Supplier; import io.quarkiverse.langchain4j.huggingface.QuarkusHuggingFaceChatModel; import io.quarkiverse.langchain4j.huggingface.QuarkusHuggingFaceEmbeddingModel; import io.quarkiverse.langchain4j.huggingface.runtime.config.ChatModelConfig; import io.quarkiverse.langchain4j.huggingface.runtime.config.EmbeddingModelConfig; import io.quarkiverse.langchain4j.huggingface.runtime.config.Langchain4jHuggingFaceConfig; import io.quarkus.runtime.annotations.Recorder; import io.smallrye.config.ConfigValidationException;
3,699
package io.quarkiverse.langchain4j.huggingface.runtime; @Recorder public class HuggingFaceRecorder { public Supplier<?> chatModel(Langchain4jHuggingFaceConfig runtimeConfig) { Optional<String> apiKeyOpt = runtimeConfig.apiKey(); URL url = runtimeConfig.chatModel().inferenceEndpointUrl(); if (apiKeyOpt.isEmpty() && url.toExternalForm().contains("api-inference.huggingface.co")) { // when using the default base URL an API key is required throw new ConfigValidationException(createApiKeyConfigProblems()); }
package io.quarkiverse.langchain4j.huggingface.runtime; @Recorder public class HuggingFaceRecorder { public Supplier<?> chatModel(Langchain4jHuggingFaceConfig runtimeConfig) { Optional<String> apiKeyOpt = runtimeConfig.apiKey(); URL url = runtimeConfig.chatModel().inferenceEndpointUrl(); if (apiKeyOpt.isEmpty() && url.toExternalForm().contains("api-inference.huggingface.co")) { // when using the default base URL an API key is required throw new ConfigValidationException(createApiKeyConfigProblems()); }
ChatModelConfig chatModelConfig = runtimeConfig.chatModel();
3
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;
4,972
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<>(); } //方法一:信任所有证书,不安全有风险
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();
2
2023-11-10 14:28:40+00:00
8k
noear/folkmq
folkmq-broker/src/main/java/org/noear/folkmq/broker/admin/AdminController.java
[ { "identifier": "LicenceUtils", "path": "folkmq-broker/src/main/java/org/noear/folkmq/broker/admin/dso/LicenceUtils.java", "snippet": "public class LicenceUtils {\n private static String licence = null;\n private static int isAuthorized = 0;\n private static String subscribeDate;\n private s...
import org.noear.folkmq.broker.admin.dso.LicenceUtils; import org.noear.folkmq.broker.admin.dso.ViewQueueService; import org.noear.folkmq.broker.admin.model.ServerVo; import org.noear.folkmq.broker.admin.model.TopicVo; import org.noear.folkmq.broker.mq.BrokerListenerFolkmq; import org.noear.folkmq.client.MqMessage; import org.noear.folkmq.common.MqConstants; import org.noear.snack.core.utils.DateUtil; import org.noear.socketd.transport.core.Session; import org.noear.socketd.transport.core.entity.StringEntity; import org.noear.solon.annotation.Controller; import org.noear.solon.annotation.Inject; import org.noear.solon.annotation.Mapping; import org.noear.solon.core.handle.ModelAndView; import org.noear.solon.core.handle.Result; import org.noear.solon.validation.annotation.Logined; import org.noear.solon.validation.annotation.NotEmpty; import org.noear.solon.validation.annotation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.util.*;
6,057
package org.noear.folkmq.broker.admin; /** * 管理控制器 * * @author noear * @since 1.0 */ @Logined @Valid @Controller public class AdminController extends BaseController { static final Logger log = LoggerFactory.getLogger(AdminController.class); @Inject BrokerListenerFolkmq brokerListener; @Inject ViewQueueService viewQueueService; @Mapping("/admin") public ModelAndView admin() { ModelAndView vm = view("admin"); vm.put("isValid", LicenceUtils.isValid()); if (LicenceUtils.isValid()) { switch (LicenceUtils.isAuthorized()) { case -1: vm.put("licenceBtn", "非法授权"); break; case 1: vm.put("licenceBtn", "正版授权"); break; default: vm.put("licenceBtn", "授权检测"); break; } } else { vm.put("licenceBtn", "非法授权"); } return vm; } @Mapping("/admin/licence") public ModelAndView licence() { ModelAndView vm = view("admin_licence"); vm.put("isAuthorized", false); if (LicenceUtils.isValid() == false) { vm.put("licence", "无效许可证(请购买正版授权:<a href='https://folkmq.noear.org' target='_blank'>https://folkmq.noear.org</a>)"); vm.put("checkBtnShow", false); } else { vm.put("licence", LicenceUtils.getLicence2()); if (LicenceUtils.isAuthorized() == 0) { vm.put("checkBtnShow", true); } else { vm.put("checkBtnShow", false); if (LicenceUtils.isAuthorized() == 1) { vm.put("isAuthorized", true); vm.put("subscribeDate", LicenceUtils.getSubscribeDate()); vm.put("subscribeMonths", LicenceUtils.getSubscribeMonths()); vm.put("consumer", LicenceUtils.getConsumer()); } else { vm.put("licence", "非法授权(请购买正版授权:<a href='https://folkmq.noear.org' target='_blank'>https://folkmq.noear.org</a>)"); } } } return vm; } @Mapping("/admin/licence/ajax/check") public Result licence_check() { if (LicenceUtils.isValid() == false) { return Result.failure(400, "无效许可证"); } return LicenceUtils.auth(); } @Mapping("/admin/topic") public ModelAndView topic() { Map<String, Set<String>> subscribeMap = brokerListener.getSubscribeMap();
package org.noear.folkmq.broker.admin; /** * 管理控制器 * * @author noear * @since 1.0 */ @Logined @Valid @Controller public class AdminController extends BaseController { static final Logger log = LoggerFactory.getLogger(AdminController.class); @Inject BrokerListenerFolkmq brokerListener; @Inject ViewQueueService viewQueueService; @Mapping("/admin") public ModelAndView admin() { ModelAndView vm = view("admin"); vm.put("isValid", LicenceUtils.isValid()); if (LicenceUtils.isValid()) { switch (LicenceUtils.isAuthorized()) { case -1: vm.put("licenceBtn", "非法授权"); break; case 1: vm.put("licenceBtn", "正版授权"); break; default: vm.put("licenceBtn", "授权检测"); break; } } else { vm.put("licenceBtn", "非法授权"); } return vm; } @Mapping("/admin/licence") public ModelAndView licence() { ModelAndView vm = view("admin_licence"); vm.put("isAuthorized", false); if (LicenceUtils.isValid() == false) { vm.put("licence", "无效许可证(请购买正版授权:<a href='https://folkmq.noear.org' target='_blank'>https://folkmq.noear.org</a>)"); vm.put("checkBtnShow", false); } else { vm.put("licence", LicenceUtils.getLicence2()); if (LicenceUtils.isAuthorized() == 0) { vm.put("checkBtnShow", true); } else { vm.put("checkBtnShow", false); if (LicenceUtils.isAuthorized() == 1) { vm.put("isAuthorized", true); vm.put("subscribeDate", LicenceUtils.getSubscribeDate()); vm.put("subscribeMonths", LicenceUtils.getSubscribeMonths()); vm.put("consumer", LicenceUtils.getConsumer()); } else { vm.put("licence", "非法授权(请购买正版授权:<a href='https://folkmq.noear.org' target='_blank'>https://folkmq.noear.org</a>)"); } } } return vm; } @Mapping("/admin/licence/ajax/check") public Result licence_check() { if (LicenceUtils.isValid() == false) { return Result.failure(400, "无效许可证"); } return LicenceUtils.auth(); } @Mapping("/admin/topic") public ModelAndView topic() { Map<String, Set<String>> subscribeMap = brokerListener.getSubscribeMap();
List<TopicVo> list = new ArrayList<>();
3
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,154
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);
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);
1
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,115
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 {
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();
1
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,677
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) public GlobalExceptionAdvice globalExceptionAdvice() { return new GlobalExceptionAdvice(); } @Bean @ConditionalOnMissingBean(value = ValidationExceptionAdvice.class) public ValidationExceptionAdvice validationExceptionAdvice() { return new ValidationExceptionAdvice(); } @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) public GlobalExceptionAdvice globalExceptionAdvice() { return new GlobalExceptionAdvice(); } @Bean @ConditionalOnMissingBean(value = ValidationExceptionAdvice.class) public ValidationExceptionAdvice validationExceptionAdvice() { return new ValidationExceptionAdvice(); } @Bean
@ConditionalOnMissingBean(NotVoidResponseBodyAdvice.class)
1
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;
4,104
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") .broadcast(CAMPAIGN_STATE_DESCRIPTOR); // 5.2 - main stream for events, use group ID to resume reading from topic final KafkaSource<String> eventSource = buildKafkaSource(kafkaBootstrapServers, eventTopic, kafkaGroupId); final SingleOutputStreamOperator<TrackingEvent> eventStream = env.fromSource(eventSource, WatermarkStrategy.noWatermarks(), eventTopic) .map(new StringToTrackingEvent()).name("parse-event"); // 6 - create and run pipeline eventStream .connect(campaignStream) .process(new EvaluateFilter()).name("evaluate-filter")
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") .broadcast(CAMPAIGN_STATE_DESCRIPTOR); // 5.2 - main stream for events, use group ID to resume reading from topic final KafkaSource<String> eventSource = buildKafkaSource(kafkaBootstrapServers, eventTopic, kafkaGroupId); final SingleOutputStreamOperator<TrackingEvent> eventStream = env.fromSource(eventSource, WatermarkStrategy.noWatermarks(), eventTopic) .map(new StringToTrackingEvent()).name("parse-event"); // 6 - create and run pipeline eventStream .connect(campaignStream) .process(new EvaluateFilter()).name("evaluate-filter")
.addSink(new TriggerCampaignSink()).name("trigger-campaign");
6
2023-11-12 17:52:45+00:00
8k
BlyznytsiaOrg/bring
core/src/main/java/io/github/blyznytsiaorg/bring/core/context/impl/BeanCreator.java
[ { "identifier": "ClassPathScannerFactory", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/context/scaner/ClassPathScannerFactory.java", "snippet": "@Slf4j\npublic class ClassPathScannerFactory {\n\n private final List<ClassPathScanner> classPathScanners;\n private final List<Annota...
import io.github.blyznytsiaorg.bring.core.context.scaner.ClassPathScannerFactory; import io.github.blyznytsiaorg.bring.core.domain.BeanDefinition; import io.github.blyznytsiaorg.bring.core.exception.NoSuchBeanException; import io.github.blyznytsiaorg.bring.core.utils.ReflectionUtils; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Supplier;
4,419
package io.github.blyznytsiaorg.bring.core.context.impl; /** * Responsible for creating beans and injecting dependencies into these beans based on provided definitions. * * @author Blyzhnytsia Team * @since 1.0 */ @Slf4j public class BeanCreator { private final AnnotationBringBeanRegistry beanRegistry; private final ConstructorBeanInjection createBeanUsingConstructor; private final FieldBeanInjection fieldBeanInjection; private final SetterBeanInjection setterBeanInjection; /** * Constructs a BeanCreator. * * @param beanRegistry The registry storing beans and their definitions. * @param classPathScannerFactory The factory for creating class path scanners. */ public BeanCreator(AnnotationBringBeanRegistry beanRegistry, ClassPathScannerFactory classPathScannerFactory) { this.beanRegistry = beanRegistry; this.createBeanUsingConstructor = new ConstructorBeanInjection(beanRegistry, classPathScannerFactory); this.fieldBeanInjection = new FieldBeanInjection(beanRegistry, classPathScannerFactory); this.setterBeanInjection = new SetterBeanInjection(beanRegistry, classPathScannerFactory); } /** * Creates a bean of the specified class and injects dependencies into it. * * @param clazz The class of the bean to be created. * @param beanName The name of the bean being created. * @param beanDefinition The definition of the bean being created. * @return The created bean object. */ public Object create(Class<?> clazz, String beanName, BeanDefinition beanDefinition) { log.debug("Creating Bean \"{}\" of [{}]", beanName, clazz.getName()); Object bean = createBeanUsingConstructor.create(clazz, beanName, beanDefinition); log.debug("Injecting dependencies to Bean \"{}\"", beanName); injectDependencies(clazz, bean); return bean; } /** * Registers a configuration bean in the context based on the provided bean name and definition. * Resolves dependencies and instantiates the configuration bean within the context. * * @param beanName The name of the configuration bean to be registered. * @param beanDefinition The definition of the configuration bean. * @return The registered configuration bean. */ public Object registerConfigurationBean(String beanName, BeanDefinition beanDefinition) { Object configObj = Optional.ofNullable(beanRegistry.getSingletonObjects().get(beanDefinition.getFactoryBeanName())) .orElseThrow(() -> { log.info("Unable to register Bean from Configuration class [{}]: " + "Configuration class not annotated or is not of Singleton scope.", beanName); return new NoSuchBeanException(beanDefinition.getBeanClass()); });
package io.github.blyznytsiaorg.bring.core.context.impl; /** * Responsible for creating beans and injecting dependencies into these beans based on provided definitions. * * @author Blyzhnytsia Team * @since 1.0 */ @Slf4j public class BeanCreator { private final AnnotationBringBeanRegistry beanRegistry; private final ConstructorBeanInjection createBeanUsingConstructor; private final FieldBeanInjection fieldBeanInjection; private final SetterBeanInjection setterBeanInjection; /** * Constructs a BeanCreator. * * @param beanRegistry The registry storing beans and their definitions. * @param classPathScannerFactory The factory for creating class path scanners. */ public BeanCreator(AnnotationBringBeanRegistry beanRegistry, ClassPathScannerFactory classPathScannerFactory) { this.beanRegistry = beanRegistry; this.createBeanUsingConstructor = new ConstructorBeanInjection(beanRegistry, classPathScannerFactory); this.fieldBeanInjection = new FieldBeanInjection(beanRegistry, classPathScannerFactory); this.setterBeanInjection = new SetterBeanInjection(beanRegistry, classPathScannerFactory); } /** * Creates a bean of the specified class and injects dependencies into it. * * @param clazz The class of the bean to be created. * @param beanName The name of the bean being created. * @param beanDefinition The definition of the bean being created. * @return The created bean object. */ public Object create(Class<?> clazz, String beanName, BeanDefinition beanDefinition) { log.debug("Creating Bean \"{}\" of [{}]", beanName, clazz.getName()); Object bean = createBeanUsingConstructor.create(clazz, beanName, beanDefinition); log.debug("Injecting dependencies to Bean \"{}\"", beanName); injectDependencies(clazz, bean); return bean; } /** * Registers a configuration bean in the context based on the provided bean name and definition. * Resolves dependencies and instantiates the configuration bean within the context. * * @param beanName The name of the configuration bean to be registered. * @param beanDefinition The definition of the configuration bean. * @return The registered configuration bean. */ public Object registerConfigurationBean(String beanName, BeanDefinition beanDefinition) { Object configObj = Optional.ofNullable(beanRegistry.getSingletonObjects().get(beanDefinition.getFactoryBeanName())) .orElseThrow(() -> { log.info("Unable to register Bean from Configuration class [{}]: " + "Configuration class not annotated or is not of Singleton scope.", beanName); return new NoSuchBeanException(beanDefinition.getBeanClass()); });
List<String> methodParamNames = ReflectionUtils.getParameterNames(beanDefinition.getMethod());
3
2023-11-10 13:42:05+00:00
8k
johndeweyzxc/AWPS-Command
app/src/main/java/com/johndeweydev/awps/view/autoarmafragment/AutoArmaFragment.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.graphics.drawable.Drawable; 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.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; 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.johndeweydev.awps.R; import com.johndeweydev.awps.databinding.FragmentAutoArmaBinding; import com.johndeweydev.awps.model.data.AccessPointData; import com.johndeweydev.awps.model.data.DeviceConnectionParamData; import com.johndeweydev.awps.model.data.HashInfoEntity; import com.johndeweydev.awps.model.repo.serial.sessionreposerial.SessionRepoSerial; import com.johndeweydev.awps.viewmodel.hashinfoviewmodel.HashInfoViewModel; import com.johndeweydev.awps.viewmodel.serial.sessionviewmodel.SessionAutoViewModel; import com.johndeweydev.awps.viewmodel.serial.sessionviewmodel.SessionAutoViewModelFactory; import java.util.Objects;
5,929
package com.johndeweydev.awps.view.autoarmafragment; public class AutoArmaFragment extends Fragment { private FragmentAutoArmaBinding binding; private AutoArmaArgs autoArmaArgs = null; private SessionAutoViewModel sessionAutoViewModel; private HashInfoViewModel hashInfoViewModel; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { SessionRepoSerial sessionRepoSerial = new SessionRepoSerial();
package com.johndeweydev.awps.view.autoarmafragment; public class AutoArmaFragment extends Fragment { private FragmentAutoArmaBinding binding; private AutoArmaArgs autoArmaArgs = null; private SessionAutoViewModel sessionAutoViewModel; private HashInfoViewModel hashInfoViewModel; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { SessionRepoSerial sessionRepoSerial = new SessionRepoSerial();
SessionAutoViewModelFactory sessionAutoViewModelFactory = new SessionAutoViewModelFactory(
7
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;
3,651
/* * 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")
/* * 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) {
3
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,922
package me.xidentified.devotions.managers; public class ShrineManager { @Getter private final Devotions plugin; private ShrineStorage shrineStorage;
package me.xidentified.devotions.managers; public class ShrineManager { @Getter private final Devotions plugin; private ShrineStorage shrineStorage;
private final List<Shrine> allShrinesList;
1
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,859
package appu26j; public enum Calculator { INSTANCE; private final int width = 445, height = 600; private float mouseX = 0, mouseY = 0; private GuiScreen currentScreen; private long window = 0; public void start() { this.initializeWindow(); this.setupOpenGL(); this.loop(); } private void initializeWindow() { Assets.loadAssets(); GLFWErrorCallback.createPrint(System.err).set(); if (!glfwInit()) { throw new IllegalStateException("Unable to initialize GLFW"); } glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); glfwWindowHint(GLFW_FOCUS_ON_SHOW, GLFW_TRUE); glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); this.window = glfwCreateWindow(this.width, this.height, "Calculator", 0, 0); glfwSetWindowPos(this.window, 50, 50); if (this.window == 0) { throw new IllegalStateException("Unable to create the GLFW window"); } glfwMakeContextCurrent(this.window); glfwSwapInterval(1); glfwSetCharCallback(this.window, new GLFWCharCallback() { @Override public void invoke(long window, int codepoint) { currentScreen.charTyped((char) codepoint, Calculator.this.mouseX, Calculator.this.mouseY); } }); glfwSetKeyCallback(this.window, new GLFWKeyCallback() { @Override public void invoke(long window, int key, int scancode, int action, int mods) { if (action == 1) { currentScreen.keyPressed(key, Calculator.this.mouseX, Calculator.this.mouseY); } } }); glfwSetMouseButtonCallback(this.window, new GLFWMouseButtonCallback() { public void invoke(long window, int button, int action, int mods) { if (action == 1) { currentScreen.mouseClicked(button, Calculator.this.mouseX, Calculator.this.mouseY); } else { currentScreen.mouseReleased(button, Calculator.this.mouseX, Calculator.this.mouseY); } } }); } private void setupOpenGL() { GL.createCapabilities(); glClearColor(0.875F, 0.875F, 0.875F, 1); glLoadIdentity(); glViewport(0, 0, this.width, this.height); glOrtho(0, this.width, this.height, 0, 1, 0); } private void loop() { this.currentScreen = new GuiCalculator(); this.currentScreen.initGUI(this.width, this.height); glfwShowWindow(this.window); while (!glfwWindowShouldClose(this.window)) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); try (MemoryStack memoryStack = MemoryStack.stackPush()) { DoubleBuffer mouseX = memoryStack.mallocDouble(1); DoubleBuffer mouseY = memoryStack.mallocDouble(1); glfwGetCursorPos(this.window, mouseX, mouseY); this.mouseX = (float) mouseX.get(); this.mouseY = (float) mouseY.get(); } this.currentScreen.drawScreen(this.mouseX, this.mouseY); glfwSwapBuffers(this.window); glfwPollEvents(); }
package appu26j; public enum Calculator { INSTANCE; private final int width = 445, height = 600; private float mouseX = 0, mouseY = 0; private GuiScreen currentScreen; private long window = 0; public void start() { this.initializeWindow(); this.setupOpenGL(); this.loop(); } private void initializeWindow() { Assets.loadAssets(); GLFWErrorCallback.createPrint(System.err).set(); if (!glfwInit()) { throw new IllegalStateException("Unable to initialize GLFW"); } glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); glfwWindowHint(GLFW_FOCUS_ON_SHOW, GLFW_TRUE); glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); this.window = glfwCreateWindow(this.width, this.height, "Calculator", 0, 0); glfwSetWindowPos(this.window, 50, 50); if (this.window == 0) { throw new IllegalStateException("Unable to create the GLFW window"); } glfwMakeContextCurrent(this.window); glfwSwapInterval(1); glfwSetCharCallback(this.window, new GLFWCharCallback() { @Override public void invoke(long window, int codepoint) { currentScreen.charTyped((char) codepoint, Calculator.this.mouseX, Calculator.this.mouseY); } }); glfwSetKeyCallback(this.window, new GLFWKeyCallback() { @Override public void invoke(long window, int key, int scancode, int action, int mods) { if (action == 1) { currentScreen.keyPressed(key, Calculator.this.mouseX, Calculator.this.mouseY); } } }); glfwSetMouseButtonCallback(this.window, new GLFWMouseButtonCallback() { public void invoke(long window, int button, int action, int mods) { if (action == 1) { currentScreen.mouseClicked(button, Calculator.this.mouseX, Calculator.this.mouseY); } else { currentScreen.mouseReleased(button, Calculator.this.mouseX, Calculator.this.mouseY); } } }); } private void setupOpenGL() { GL.createCapabilities(); glClearColor(0.875F, 0.875F, 0.875F, 1); glLoadIdentity(); glViewport(0, 0, this.width, this.height); glOrtho(0, this.width, this.height, 0, 1, 0); } private void loop() { this.currentScreen = new GuiCalculator(); this.currentScreen.initGUI(this.width, this.height); glfwShowWindow(this.window); while (!glfwWindowShouldClose(this.window)) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); try (MemoryStack memoryStack = MemoryStack.stackPush()) { DoubleBuffer mouseX = memoryStack.mallocDouble(1); DoubleBuffer mouseY = memoryStack.mallocDouble(1); glfwGetCursorPos(this.window, mouseX, mouseY); this.mouseX = (float) mouseX.get(); this.mouseY = (float) mouseY.get(); } this.currentScreen.drawScreen(this.mouseX, this.mouseY); glfwSwapBuffers(this.window); glfwPollEvents(); }
this.currentScreen.getFontRenderers().forEach(FontRenderer::shutdown);
1
2023-11-10 18:00:58+00:00
8k
SplitfireUptown/datalinkx
flinkx/flinkx-vertica/flinkx-vertica-reader/src/main/java/com/dtstack/flinkx/vertica/reader/VerticaReader.java
[ { "identifier": "DataTransferConfig", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/config/DataTransferConfig.java", "snippet": "public class DataTransferConfig extends AbstractConfig {\n\n JobConfig job;\n\n public DataTransferConfig(Map<String, Object> map) {\n super(map);\...
import com.dtstack.flinkx.config.DataTransferConfig; import com.dtstack.flinkx.constants.ConstantValue; import com.dtstack.flinkx.rdb.datareader.JdbcDataReader; import com.dtstack.flinkx.rdb.inputformat.JdbcInputFormatBuilder; import com.dtstack.flinkx.vertica.VerticaDatabaseMeta; import com.dtstack.flinkx.vertica.format.VerticaInputFormat; import org.apache.commons.lang3.StringUtils; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
5,217
/* * 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.vertica.reader; /** * Oracle reader plugin * * Company: www.dtstack.com * @author huyifan.zju@163.com */ public class VerticaReader extends JdbcDataReader { public VerticaReader(DataTransferConfig config, StreamExecutionEnvironment env) { super(config, env); String schema = config.getJob().getContent().get(0).getReader().getParameter().getConnection().get(0).getSchema(); if(StringUtils.isNotBlank(schema)){ table = schema + ConstantValue.POINT_SYMBOL + table; } setDatabaseInterface(new VerticaDatabaseMeta()); } @Override
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flinkx.vertica.reader; /** * Oracle reader plugin * * Company: www.dtstack.com * @author huyifan.zju@163.com */ public class VerticaReader extends JdbcDataReader { public VerticaReader(DataTransferConfig config, StreamExecutionEnvironment env) { super(config, env); String schema = config.getJob().getContent().get(0).getReader().getParameter().getConnection().get(0).getSchema(); if(StringUtils.isNotBlank(schema)){ table = schema + ConstantValue.POINT_SYMBOL + table; } setDatabaseInterface(new VerticaDatabaseMeta()); } @Override
protected JdbcInputFormatBuilder getBuilder() {
3
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,646
package com.uroria.betterflowers; @Getter public final class BetterFlowers extends JavaPlugin {
package com.uroria.betterflowers; @Getter public final class BetterFlowers extends JavaPlugin {
private final FlowerManager flowerManager;
2
2023-11-18 16:13:59+00:00
8k
Appu26J/Softuninstall
src/appu26j/gui/screens/GuiSoftuninstall.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.Registry; import appu26j.assets.Assets; import appu26j.gui.Gui; import appu26j.gui.textures.Texture; import appu26j.utils.AppUtil; import appu26j.utils.ScissorUtil; import appu26j.utils.apps.AppInfo; import org.lwjgl.opengl.GL11; import java.awt.*; import java.util.ArrayList;
4,027
package appu26j.gui.screens; public class GuiSoftuninstall extends GuiScreen { public static final ArrayList<AppInfo> apps = new ArrayList<>(); private String previousUninstalledApp = ""; private float scroll = 0, maxScroll = 0; private boolean dragging = false; public static int loading = 2; private Texture delete; @Override public void drawScreen(float mouseX, float mouseY) { if (!apps.isEmpty()) { if (this.dragging) { float progress = (mouseY - 15) / (this.height - 30); this.scroll = this.maxScroll * progress; if (this.scroll < 0) { this.scroll = 0; } if (this.scroll > this.maxScroll) { this.scroll = this.maxScroll; } } this.maxScroll = 0; float y = 15 - this.scroll; ArrayList<AppInfo> finalApps = new ArrayList<>(apps); for (AppInfo appInfo : finalApps) { Gui.drawRect(15, y, this.width - 40, y + 60, this.isInsideBox(mouseX, mouseY, 15, y, this.width - 40, y + 60) ? new Color(235, 235, 235) : new Color(245, 245, 245)); this.fontRenderer.drawString(appInfo.getName(), 25, y, new Color(50, 50, 50)); GL11.glEnable(GL11.GL_SCISSOR_TEST); ScissorUtil.scissor(0, 0, this.width - 100, this.height); this.fontRenderer.drawString(appInfo.getUninstallCmd(), this.fontRenderer.getStringWidth(appInfo.getPublisher()) + 30, y + 27, new Color(175, 175, 175)); GL11.glDisable(GL11.GL_SCISSOR_TEST); this.fontRenderer.drawString(appInfo.getPublisher(), 25, y + 27, new Color(125, 125, 125)); Gui.drawImage(this.delete, this.width - 95, y + 4, 0, 0, 48, 48, 48, 48); y += 75; this.maxScroll += 75; } this.maxScroll -= (loading == 0 ? 685 : 625); if (this.maxScroll < 0) { this.maxScroll = 0; } if (this.scroll > this.maxScroll) { this.scroll = this.maxScroll; } if (loading != 0) { this.fontRendererMid.drawString("Loading...", (this.width / 2) - (this.fontRendererMid.getStringWidth("Loading...") / 2), y - 10, new Color(100, 100, 100)); } Gui.drawRect(this.width - 27, 15, this.width - 13, this.height - 15, new Color(200, 200, 200)); float scrollProgress = (this.scroll / this.maxScroll); float yPos = ((this.height - 180) * scrollProgress) + 90; Gui.drawRect(this.width - 27, yPos - 75, this.width - 13, yPos + 75, new Color(245, 245, 245)); } } @Override public void mouseClicked(int mouseButton, float mouseX, float mouseY) { super.mouseClicked(mouseButton, mouseX, mouseY); float y = 15 - this.scroll; ArrayList<AppInfo> finalApps = new ArrayList<>(apps); for (AppInfo appInfo : finalApps) { if (this.isInsideBox(mouseX, mouseY, 15, y, this.width - 40, y + 60) && !this.previousUninstalledApp.equals(appInfo.getName())) { new Thread(() -> { try { Process process = Runtime.getRuntime().exec(appInfo.getUninstallCmd()); process.waitFor(); String output = Registry.execute("QUERY " + appInfo.getRegistryPath() + " /v DisplayName"); if (output.contains("ERROR: The system was unable to find the specified registry key or value.")) { GuiSoftuninstall.apps.remove(appInfo); } this.previousUninstalledApp = ""; } catch (Exception e) { ; } }).start(); this.previousUninstalledApp = appInfo.getName(); break; } y += 75; } if (this.isInsideBox(mouseX, mouseY, this.width - 37, 5, this.width - 3, this.height - 5) && mouseButton == 0) { this.dragging = true; } } @Override public void mouseReleased(int mouseButton, float mouseX, float mouseY) { super.mouseReleased(mouseButton, mouseX, mouseY); this.dragging = false; } @Override public void initGUI(float width, float height) { super.initGUI(width, height);
package appu26j.gui.screens; public class GuiSoftuninstall extends GuiScreen { public static final ArrayList<AppInfo> apps = new ArrayList<>(); private String previousUninstalledApp = ""; private float scroll = 0, maxScroll = 0; private boolean dragging = false; public static int loading = 2; private Texture delete; @Override public void drawScreen(float mouseX, float mouseY) { if (!apps.isEmpty()) { if (this.dragging) { float progress = (mouseY - 15) / (this.height - 30); this.scroll = this.maxScroll * progress; if (this.scroll < 0) { this.scroll = 0; } if (this.scroll > this.maxScroll) { this.scroll = this.maxScroll; } } this.maxScroll = 0; float y = 15 - this.scroll; ArrayList<AppInfo> finalApps = new ArrayList<>(apps); for (AppInfo appInfo : finalApps) { Gui.drawRect(15, y, this.width - 40, y + 60, this.isInsideBox(mouseX, mouseY, 15, y, this.width - 40, y + 60) ? new Color(235, 235, 235) : new Color(245, 245, 245)); this.fontRenderer.drawString(appInfo.getName(), 25, y, new Color(50, 50, 50)); GL11.glEnable(GL11.GL_SCISSOR_TEST); ScissorUtil.scissor(0, 0, this.width - 100, this.height); this.fontRenderer.drawString(appInfo.getUninstallCmd(), this.fontRenderer.getStringWidth(appInfo.getPublisher()) + 30, y + 27, new Color(175, 175, 175)); GL11.glDisable(GL11.GL_SCISSOR_TEST); this.fontRenderer.drawString(appInfo.getPublisher(), 25, y + 27, new Color(125, 125, 125)); Gui.drawImage(this.delete, this.width - 95, y + 4, 0, 0, 48, 48, 48, 48); y += 75; this.maxScroll += 75; } this.maxScroll -= (loading == 0 ? 685 : 625); if (this.maxScroll < 0) { this.maxScroll = 0; } if (this.scroll > this.maxScroll) { this.scroll = this.maxScroll; } if (loading != 0) { this.fontRendererMid.drawString("Loading...", (this.width / 2) - (this.fontRendererMid.getStringWidth("Loading...") / 2), y - 10, new Color(100, 100, 100)); } Gui.drawRect(this.width - 27, 15, this.width - 13, this.height - 15, new Color(200, 200, 200)); float scrollProgress = (this.scroll / this.maxScroll); float yPos = ((this.height - 180) * scrollProgress) + 90; Gui.drawRect(this.width - 27, yPos - 75, this.width - 13, yPos + 75, new Color(245, 245, 245)); } } @Override public void mouseClicked(int mouseButton, float mouseX, float mouseY) { super.mouseClicked(mouseButton, mouseX, mouseY); float y = 15 - this.scroll; ArrayList<AppInfo> finalApps = new ArrayList<>(apps); for (AppInfo appInfo : finalApps) { if (this.isInsideBox(mouseX, mouseY, 15, y, this.width - 40, y + 60) && !this.previousUninstalledApp.equals(appInfo.getName())) { new Thread(() -> { try { Process process = Runtime.getRuntime().exec(appInfo.getUninstallCmd()); process.waitFor(); String output = Registry.execute("QUERY " + appInfo.getRegistryPath() + " /v DisplayName"); if (output.contains("ERROR: The system was unable to find the specified registry key or value.")) { GuiSoftuninstall.apps.remove(appInfo); } this.previousUninstalledApp = ""; } catch (Exception e) { ; } }).start(); this.previousUninstalledApp = appInfo.getName(); break; } y += 75; } if (this.isInsideBox(mouseX, mouseY, this.width - 37, 5, this.width - 3, this.height - 5) && mouseButton == 0) { this.dragging = true; } } @Override public void mouseReleased(int mouseButton, float mouseX, float mouseY) { super.mouseReleased(mouseButton, mouseX, mouseY); this.dragging = false; } @Override public void initGUI(float width, float height) { super.initGUI(width, height);
AppUtil.loadApps();
3
2023-11-13 03:20:19+00:00
8k
12manel123/tsys-my-food-api-1011
src/main/java/com/myfood/controllers/OrderController.java
[ { "identifier": "Dish", "path": "src/main/java/com/myfood/dto/Dish.java", "snippet": "@Entity\n@Table(name = \"dishes\")\npublic class Dish {\n\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n \n\t@Column(name = \"name\", nullable =...
import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.data.domain.Pageable; import com.myfood.dto.Dish; import com.myfood.dto.ListOrder; import com.myfood.dto.Order; import com.myfood.dto.OrderCookDTO; import com.myfood.dto.OrderUserDTO; import com.myfood.dto.Slot; import com.myfood.dto.User; import com.myfood.services.OrderServiceImpl; import com.myfood.services.SlotServiceImpl; import com.myfood.services.UserServiceImpl; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import jakarta.transaction.Transactional;
6,217
package com.myfood.controllers; @RestController @RequestMapping("api/v1") public class OrderController { @Autowired
package com.myfood.controllers; @RestController @RequestMapping("api/v1") public class OrderController { @Autowired
private OrderServiceImpl orderService;
7
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,622
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;
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;
2
2023-11-18 16:37:27+00:00
8k
GoldenStack/minestom-ca
src/main/java/dev/goldenstack/minestom_ca/Program.java
[ { "identifier": "Parser", "path": "src/main/java/dev/goldenstack/minestom_ca/parser/Parser.java", "snippet": "public final class Parser {\r\n private int line;\r\n private List<Token> tokens;\r\n private int index;\r\n\r\n private final AtomicInteger stateCounter = new AtomicInteger(0);\r\n\...
import dev.goldenstack.minestom_ca.parser.Parser; import dev.goldenstack.minestom_ca.parser.Scanner; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Map;
3,861
package dev.goldenstack.minestom_ca; public record Program(List<Rule> rules, Map<String, Integer> variables) { public Program { rules = List.copyOf(rules); variables = Map.copyOf(variables); } public static Program fromFile(Path path) { final String program; try { program = Files.readAllLines(path).stream().reduce("", (a, b) -> a + "\n" + b); } catch (IOException e) { throw new RuntimeException(e); } return fromString(program); } public static Program fromString(String program) { List<String> lines = List.of(program.split("\n"));
package dev.goldenstack.minestom_ca; public record Program(List<Rule> rules, Map<String, Integer> variables) { public Program { rules = List.copyOf(rules); variables = Map.copyOf(variables); } public static Program fromFile(Path path) { final String program; try { program = Files.readAllLines(path).stream().reduce("", (a, b) -> a + "\n" + b); } catch (IOException e) { throw new RuntimeException(e); } return fromString(program); } public static Program fromString(String program) { List<String> lines = List.of(program.split("\n"));
Parser parser = new Parser();
0
2023-11-18 21:49:11+00:00
8k
kotmatross28729/EnviroMine-continuation
src/main/java/enviromine/world/features/mineshaft/MineSegment.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 static net.minecraftforge.common.ChestGenHooks.DUNGEON_CHEST; import java.util.ArrayList; import org.apache.logging.log4j.Level; import enviromine.core.EM_ConfigHandler.EnumLogVerbosity; import enviromine.core.EM_Settings; import enviromine.core.EnviroMine; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.util.WeightedRandomChestContent; import net.minecraft.world.World; import net.minecraftforge.common.ChestGenHooks;
5,447
package enviromine.world.features.mineshaft; public abstract class MineSegment { // Rotation = 90 * value (top-down clockwise direction)(+X = forward, +Z = right) int rot = 0; World world; int posX = 0; int posY = 0; int posZ = 0; int minX = 0; int minZ = 0; int minY = 0; int maxX = 0; int maxY = 0; int maxZ = 0; int chunkMinX = 0; int chunkMaxX = 0; int chunkMinZ = 0; int chunkMaxZ = 0; int decay = 0; MineshaftBuilder builder; public MineSegment(World world, int x, int y, int z, int rotation, MineshaftBuilder builder) { this.world = world; this.posX = x; this.posY = y; this.posZ = z; this.rot = rotation%4; this.builder = builder; } public abstract boolean build(); void setBlockBounds(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { this.minX = minX; this.minY = minY; this.minZ = minZ; this.maxX = maxX; this.maxY = maxY; this.maxZ = maxZ; } void setChunkBounds(int minX, int minZ, int maxX, int maxZ) { this.chunkMinX = minX; this.chunkMinZ = minZ; this.chunkMaxX = maxX; this.chunkMaxZ = maxZ; } public void setDecay(int decay) { this.decay = decay; } public int[] getExitPoint(int rotation) { return new int[]{posX,posY,posZ}; } public int[] getExitPoint(int rotation, int yDir) { int[] point = getExitPoint(rotation); return point; } public boolean canBuild() { if(posY + maxY > 255) { return false; } else if(posY - minY < 0) { return false; } return true; } public ArrayList<String> getRequiredChunks() { ArrayList<String> chunks = new ArrayList<String>(); int xOffMin = this.xOffset(chunkMinX, chunkMinZ)/16; int zOffMin = this.zOffset(chunkMinX, chunkMinX)/16; int xOffMax = this.xOffset(chunkMaxX, chunkMaxZ)/16; int zOffMax = this.zOffset(chunkMaxX, chunkMaxZ)/16; if(xOffMin > xOffMax) { int tmp = xOffMin; xOffMin = xOffMax; xOffMax = tmp; } if(zOffMin > zOffMax) { int tmp = zOffMin; zOffMin = zOffMax; zOffMax = tmp; } for(int i = xOffMin; i <= xOffMax; i++) { for(int k = zOffMin; k <= zOffMax; k++) { chunks.add("" + i + "," + k); } } return chunks; } public void linkChunksToBuilder() { ArrayList<String> chunks = this.getRequiredChunks(); if(chunks.size() <= 0) {
package enviromine.world.features.mineshaft; public abstract class MineSegment { // Rotation = 90 * value (top-down clockwise direction)(+X = forward, +Z = right) int rot = 0; World world; int posX = 0; int posY = 0; int posZ = 0; int minX = 0; int minZ = 0; int minY = 0; int maxX = 0; int maxY = 0; int maxZ = 0; int chunkMinX = 0; int chunkMaxX = 0; int chunkMinZ = 0; int chunkMaxZ = 0; int decay = 0; MineshaftBuilder builder; public MineSegment(World world, int x, int y, int z, int rotation, MineshaftBuilder builder) { this.world = world; this.posX = x; this.posY = y; this.posZ = z; this.rot = rotation%4; this.builder = builder; } public abstract boolean build(); void setBlockBounds(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { this.minX = minX; this.minY = minY; this.minZ = minZ; this.maxX = maxX; this.maxY = maxY; this.maxZ = maxZ; } void setChunkBounds(int minX, int minZ, int maxX, int maxZ) { this.chunkMinX = minX; this.chunkMinZ = minZ; this.chunkMaxX = maxX; this.chunkMaxZ = maxZ; } public void setDecay(int decay) { this.decay = decay; } public int[] getExitPoint(int rotation) { return new int[]{posX,posY,posZ}; } public int[] getExitPoint(int rotation, int yDir) { int[] point = getExitPoint(rotation); return point; } public boolean canBuild() { if(posY + maxY > 255) { return false; } else if(posY - minY < 0) { return false; } return true; } public ArrayList<String> getRequiredChunks() { ArrayList<String> chunks = new ArrayList<String>(); int xOffMin = this.xOffset(chunkMinX, chunkMinZ)/16; int zOffMin = this.zOffset(chunkMinX, chunkMinX)/16; int xOffMax = this.xOffset(chunkMaxX, chunkMaxZ)/16; int zOffMax = this.zOffset(chunkMaxX, chunkMaxZ)/16; if(xOffMin > xOffMax) { int tmp = xOffMin; xOffMin = xOffMax; xOffMax = tmp; } if(zOffMin > zOffMax) { int tmp = zOffMin; zOffMin = zOffMax; zOffMax = tmp; } for(int i = xOffMin; i <= xOffMax; i++) { for(int k = zOffMin; k <= zOffMax; k++) { chunks.add("" + i + "," + k); } } return chunks; } public void linkChunksToBuilder() { ArrayList<String> chunks = this.getRequiredChunks(); if(chunks.size() <= 0) {
if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.LOW.getLevel()) EnviroMine.logger.log(Level.WARN, "ERROR: MineSegment is registering 0 chunks! It will not generate!");
1
2023-11-16 18:15:29+00:00
8k
spring-projects/spring-rewrite-commons
spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/parsers/RewriteProjectParserIntegrationTest.java
[ { "identifier": "SbmSupportRewriteConfiguration", "path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/boot/autoconfigure/SbmSupportRewriteConfiguration.java", "snippet": "@AutoConfiguration\n@Import({ RecipeDiscoveryConfiguration.class, RewriteParserConfiguration.class, Pr...
import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; import org.junitpioneer.jupiter.Issue; import org.openrewrite.java.tree.J; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.rewrite.boot.autoconfigure.SbmSupportRewriteConfiguration; import org.springframework.rewrite.parsers.maven.RewriteMavenProjectParser; import org.springframework.rewrite.parsers.maven.SbmTestConfiguration; import org.springframework.rewrite.test.util.ParserParityTestHelper; import org.springframework.rewrite.test.util.TestProjectHelper; import java.nio.file.Path;
7,047
/* * 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; /** * @author Fabian Krüger */ @DisabledOnOs(value = OS.WINDOWS, disabledReason = "The repository URIs of dependencies differ.") @Issue("https://github.com/spring-projects/spring-rewrite-commons/issues/12") @SpringBootTest(classes = { SbmSupportRewriteConfiguration.class, SbmTestConfiguration.class }) public class RewriteProjectParserIntegrationTest { @Autowired RewriteProjectParser sut; @Autowired ProjectScanner projectScanner; @Autowired RewriteMavenProjectParser mavenProjectParser; @Test @DisplayName("testFailingProject") void testFailingProject() { Path baseDir = Path.of("./testcode/maven-projects/failing");
/* * 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; /** * @author Fabian Krüger */ @DisabledOnOs(value = OS.WINDOWS, disabledReason = "The repository URIs of dependencies differ.") @Issue("https://github.com/spring-projects/spring-rewrite-commons/issues/12") @SpringBootTest(classes = { SbmSupportRewriteConfiguration.class, SbmTestConfiguration.class }) public class RewriteProjectParserIntegrationTest { @Autowired RewriteProjectParser sut; @Autowired ProjectScanner projectScanner; @Autowired RewriteMavenProjectParser mavenProjectParser; @Test @DisplayName("testFailingProject") void testFailingProject() { Path baseDir = Path.of("./testcode/maven-projects/failing");
ParserParityTestHelper.scanProjectDir(baseDir).verifyParity((comparingParsingResult, testedParsingResult) -> {
3
2023-11-14 23:02:37+00:00
8k
giftorg/gift
gift-analyze/src/main/java/org/giftorg/analyze/entity/Repository.java
[ { "identifier": "BigModel", "path": "gift-common/src/main/java/org/giftorg/common/bigmodel/BigModel.java", "snippet": "public interface BigModel extends Serializable {\n\n /**\n * 大模型聊天接口\n */\n String chat(List<Message> messages) throws Exception;\n\n /**\n * 计算文本嵌入向量\n */\n ...
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.giftorg.common.bigmodel.BigModel; import org.giftorg.common.bigmodel.impl.ChatGPT; import org.giftorg.common.bigmodel.impl.XingHuo; import org.giftorg.common.tokenpool.TokenPool; import org.giftorg.common.utils.CharsetUtil; import org.giftorg.common.utils.MarkdownUtil; import org.giftorg.common.utils.StringUtil; import java.io.Serializable;
5,005
/** * Copyright 2023 GiftOrg Authors * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.giftorg.analyze.entity; @Slf4j @Data public class Repository implements Serializable, Cloneable { private Integer id; private Integer repoId; private String name; private String fullName; private Integer stars; private String author; private String url; private String description; private Integer size; private String defaultBranch; private String readme; private String readmeCn; private List<String> tags; private String hdfsPath; private boolean isTranslated = false; private boolean isTagged = false; private static final int CHUNK_SIZE = 1000; public Repository() { } public Repository(String name, String readme) { this.name = name; this.readme = readme; } @Override public Repository clone() throws CloneNotSupportedException { return (Repository) super.clone(); } private static final String REPOSITORY_TRANSLATION_PROMPT = "去除以上文档中任何链接、许可等无关内容,使用中文总结上面的内容,保留核心文字描述,且必须保留文档中的名词、相关的项目名称。"; /** * 翻译项目文档 */ public void translation() throws Exception { if (isTranslated) return; if (!CharsetUtil.isChinese(readme)) {
/** * Copyright 2023 GiftOrg Authors * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.giftorg.analyze.entity; @Slf4j @Data public class Repository implements Serializable, Cloneable { private Integer id; private Integer repoId; private String name; private String fullName; private Integer stars; private String author; private String url; private String description; private Integer size; private String defaultBranch; private String readme; private String readmeCn; private List<String> tags; private String hdfsPath; private boolean isTranslated = false; private boolean isTagged = false; private static final int CHUNK_SIZE = 1000; public Repository() { } public Repository(String name, String readme) { this.name = name; this.readme = readme; } @Override public Repository clone() throws CloneNotSupportedException { return (Repository) super.clone(); } private static final String REPOSITORY_TRANSLATION_PROMPT = "去除以上文档中任何链接、许可等无关内容,使用中文总结上面的内容,保留核心文字描述,且必须保留文档中的名词、相关的项目名称。"; /** * 翻译项目文档 */ public void translation() throws Exception { if (isTranslated) return; if (!CharsetUtil.isChinese(readme)) {
BigModel xingHuo = new ChatGPT();
0
2023-11-15 08:58:35+00:00
8k
exadel-inc/etoolbox-anydiff
core/src/main/java/com/exadel/etoolbox/anydiff/runner/FileRunner.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 java.util.List; import com.exadel.etoolbox.anydiff.Constants; import com.exadel.etoolbox.anydiff.ContentType; import com.exadel.etoolbox.anydiff.comparison.DiffTask; import com.exadel.etoolbox.anydiff.diff.Diff; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Date;
4,141
/* * 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.runner; /** * Extends {@link DiffRunner} to implement extracting data from file system files */ @RequiredArgsConstructor @Slf4j class FileRunner extends DiffRunner { private final Path left; private final Path right; @Override public List<Diff> runInternal() { ContentType contentType = getCommonTypeOrDefault( left.toAbsolutePath().toString(), right.toAbsolutePath().toString(), getContentType()); Object leftContent = contentType != ContentType.UNDEFINED ? getContent(left) : getMetadata(left); Object rightContent = contentType != ContentType.UNDEFINED ? getContent(right) : getMetadata(right); DiffTask diffTask = DiffTask .builder() .contentType(contentType) .leftId(left.toAbsolutePath().toString()) .leftLabel(getLeftLabel()) .leftContent(leftContent) .rightId(right.toAbsolutePath().toString()) .rightLabel(getRightLabel()) .rightContent(rightContent) .filter(getEntryFilter()) .taskParameters(getTaskParameters()) .build(); Diff diff = diffTask.run(); return Collections.singletonList(diff); } private static ContentType getCommonTypeOrDefault(String left, String right, ContentType defaultType) { ContentType commonContentTypeByMime = getCommonTypeByMime(left, right); if (commonContentTypeByMime != ContentType.UNDEFINED) { return commonContentTypeByMime; }
/* * 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.runner; /** * Extends {@link DiffRunner} to implement extracting data from file system files */ @RequiredArgsConstructor @Slf4j class FileRunner extends DiffRunner { private final Path left; private final Path right; @Override public List<Diff> runInternal() { ContentType contentType = getCommonTypeOrDefault( left.toAbsolutePath().toString(), right.toAbsolutePath().toString(), getContentType()); Object leftContent = contentType != ContentType.UNDEFINED ? getContent(left) : getMetadata(left); Object rightContent = contentType != ContentType.UNDEFINED ? getContent(right) : getMetadata(right); DiffTask diffTask = DiffTask .builder() .contentType(contentType) .leftId(left.toAbsolutePath().toString()) .leftLabel(getLeftLabel()) .leftContent(leftContent) .rightId(right.toAbsolutePath().toString()) .rightLabel(getRightLabel()) .rightContent(rightContent) .filter(getEntryFilter()) .taskParameters(getTaskParameters()) .build(); Diff diff = diffTask.run(); return Collections.singletonList(diff); } private static ContentType getCommonTypeOrDefault(String left, String right, ContentType defaultType) { ContentType commonContentTypeByMime = getCommonTypeByMime(left, right); if (commonContentTypeByMime != ContentType.UNDEFINED) { return commonContentTypeByMime; }
String leftExtension = StringUtils.substringAfterLast(left, Constants.DOT);
0
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,005
/* */ package nl.infcomtec.jllama; /** * * @author walter */ public class TextImage { public final JFrame frame;
/* */ package nl.infcomtec.jllama; /** * * @author walter */ public class TextImage { public final JFrame frame;
public final ImageObject imgObj;
0
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,525
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. */
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;
6
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,606
package com.ma.bitchgiveitback.app_process; public class Main { static PackageManager packageManager = ServiceManager.getPackageManager(); static NotificationManager notificationManager = ServiceManager.getNotificationManager();
package com.ma.bitchgiveitback.app_process; public class Main { static PackageManager packageManager = ServiceManager.getPackageManager(); static NotificationManager notificationManager = ServiceManager.getNotificationManager();
static MultiJarClassLoader multiJarClassLoader = MultiJarClassLoader.getInstance();
0
2023-11-17 09:58:57+00:00
8k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/items/attachments/mags/AssaultExpansionMag.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.tabs.CreativeTabs; import java.util.ArrayList; import java.util.Arrays;
5,007
package sheridan.gunscraft.items.attachments.mags; public class AssaultExpansionMag extends GenericMag { public AssaultExpansionMag() {
package sheridan.gunscraft.items.attachments.mags; public class AssaultExpansionMag extends GenericMag { public AssaultExpansionMag() {
super(new Properties().group(CreativeTabs.REGULAR_ATTACHMENTS).maxStackSize(1), AttachmentRegistry.getID("assault_expansion_mag"),
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,277
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; }
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;
5
2023-11-14 06:44:40+00:00
8k
Ouest-France/querydsl-postgrest
src/test/java/fr/ouestfrance/querydsl/postgrest/app/PostRepository.java
[ { "identifier": "PostgrestClient", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/PostgrestClient.java", "snippet": "public interface PostgrestClient {\n /**\n * Search method\n *\n * @param resource resource name\n * @param params query params\n * @param <T> retu...
import fr.ouestfrance.querydsl.postgrest.PostgrestClient; import fr.ouestfrance.querydsl.postgrest.PostgrestWebClient; import fr.ouestfrance.querydsl.postgrest.PostgrestRepository; import fr.ouestfrance.querydsl.postgrest.annotations.Header; import fr.ouestfrance.querydsl.postgrest.annotations.PostgrestConfiguration; import fr.ouestfrance.querydsl.postgrest.annotations.Select; import fr.ouestfrance.querydsl.postgrest.model.Prefer; import static fr.ouestfrance.querydsl.postgrest.annotations.Header.Method.UPSERT;
3,765
package fr.ouestfrance.querydsl.postgrest.app; @PostgrestConfiguration(resource = "posts") @Select("authors(*)") @Header(key = Prefer.HEADER, value = Prefer.Return.REPRESENTATION) @Header(key = Prefer.HEADER, value = Prefer.Resolution.MERGE_DUPLICATES, methods = UPSERT) public class PostRepository extends PostgrestRepository<Post> {
package fr.ouestfrance.querydsl.postgrest.app; @PostgrestConfiguration(resource = "posts") @Select("authors(*)") @Header(key = Prefer.HEADER, value = Prefer.Return.REPRESENTATION) @Header(key = Prefer.HEADER, value = Prefer.Resolution.MERGE_DUPLICATES, methods = UPSERT) public class PostRepository extends PostgrestRepository<Post> {
public PostRepository(PostgrestClient client) {
0
2023-11-14 10:45:54+00:00
8k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/utils/tasks/ClearAppSettings.java
[ { "identifier": "APKEditorUtils", "path": "app/src/main/java/com/threethan/questpatcher/utils/APKEditorUtils.java", "snippet": "public class APKEditorUtils {\n\n public static int getThemeAccentColor(Context context) {\n TypedValue value = new TypedValue();\n context.getTheme().resolveA...
import android.app.Activity; import android.app.ProgressDialog; import com.threethan.questpatcher.R; import com.threethan.questpatcher.utils.APKEditorUtils; import com.threethan.questpatcher.utils.AppSettings; import java.io.File; import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils; import in.sunilpaulmathew.sCommon.CommonUtils.sExecutor; import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils;
4,482
package com.threethan.questpatcher.utils.tasks; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on January 28, 2023 */ public class ClearAppSettings extends sExecutor { private final Activity mActivity; private ProgressDialog mProgressDialog; public ClearAppSettings(Activity activity) { mActivity = activity; } @Override public void onPreExecute() { mProgressDialog = new ProgressDialog(mActivity); mProgressDialog.setMessage(mActivity.getString(R.string.clearing_cache_message)); 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() { sFileUtils.delete(mActivity.getCacheDir()); sFileUtils.delete(mActivity.getFilesDir());
package com.threethan.questpatcher.utils.tasks; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on January 28, 2023 */ public class ClearAppSettings extends sExecutor { private final Activity mActivity; private ProgressDialog mProgressDialog; public ClearAppSettings(Activity activity) { mActivity = activity; } @Override public void onPreExecute() { mProgressDialog = new ProgressDialog(mActivity); mProgressDialog.setMessage(mActivity.getString(R.string.clearing_cache_message)); 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() { sFileUtils.delete(mActivity.getCacheDir()); sFileUtils.delete(mActivity.getFilesDir());
if (APKEditorUtils.isFullVersion(mActivity) && AppSettings.isCustomKey(mActivity)) {
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,668
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
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) {
2
2023-11-11 14:54:53+00:00
8k
Mapty231/SpawnFix
src/main/java/me/tye/spawnfix/PlayerRespawn.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.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.scheduler.BukkitTask; import java.util.logging.Level; import static me.tye.spawnfix.utils.Util.*;
5,661
package me.tye.spawnfix; public class PlayerRespawn implements Listener { @EventHandler public static void playerRespawn(PlayerRespawnEvent e) { Player player = e.getPlayer(); Location spawnLocation = e.getPlayer().getBedSpawnLocation();
package me.tye.spawnfix; public class PlayerRespawn implements Listener { @EventHandler public static void playerRespawn(PlayerRespawnEvent e) { Player player = e.getPlayer(); Location spawnLocation = e.getPlayer().getBedSpawnLocation();
if (Config.onSpawn.getOccurrenceConfig() == Config.Occurrence.NEVER) {
0
2023-11-13 23:53:25+00:00
8k
mike1226/SpringMVCExample-01
src/main/java/com/example/servingwebcontent/controller/CountryController.java
[ { "identifier": "CountryEntity", "path": "src/main/java/com/example/servingwebcontent/entity/CountryEntity.java", "snippet": "public class CountryEntity {\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.56668+09:00\", comments = \"Source field: public...
import java.util.List; import java.util.Optional; import org.mybatis.dynamic.sql.select.SelectDSLCompleter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.servlet.view.RedirectView; import com.example.servingwebcontent.entity.CountryEntity; import com.example.servingwebcontent.entity.Customer; import com.example.servingwebcontent.form.CountryForm; import com.example.servingwebcontent.form.CountrySearchForm; import com.example.servingwebcontent.form.TestForm; import com.example.servingwebcontent.repository.CountryEntityMapper; import com.google.gson.Gson;
4,701
package com.example.servingwebcontent.controller; @Controller public class CountryController { @Autowired private CountryEntityMapper mapper; /** * The String class represents character strings. */ @GetMapping("/list")
package com.example.servingwebcontent.controller; @Controller public class CountryController { @Autowired private CountryEntityMapper mapper; /** * The String class represents character strings. */ @GetMapping("/list")
public String list(TestForm testForm) {
4
2023-11-12 08:22:27+00:00
8k
wangxianhui111/xuechengzaixian
xuecheng-plus-learning/xuecheng-plus-learning-service/src/main/java/com/xuecheng/learning/service/impl/MyCourseTableServicesImpl.java
[ { "identifier": "CommonError", "path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/exception/CommonError.java", "snippet": "public enum CommonError {\n UNKNOWN_ERROR(\"执行过程异常,请重试。\"),\n PARAMS_ERROR(\"非法参数\"),\n OBJECT_NULL(\"对象为空\"),\n QUERY_NULL(\"查询结果为空\"),\n REQUEST_NULL(\"请求参...
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.xuecheng.base.exception.CommonError; import com.xuecheng.base.exception.XueChengPlusException; import com.xuecheng.base.model.PageResult; import com.xuecheng.content.model.po.CoursePublish; import com.xuecheng.learning.feignclient.ContentServiceClient; import com.xuecheng.learning.mapper.XcChooseCourseMapper; import com.xuecheng.learning.mapper.XcCourseTablesMapper; import com.xuecheng.learning.model.dto.MyCourseTableItemDto; import com.xuecheng.learning.model.dto.MyCourseTableParams; import com.xuecheng.learning.model.dto.XcChooseCourseDto; import com.xuecheng.learning.model.dto.XcCourseTablesDto; import com.xuecheng.learning.model.po.XcChooseCourse; import com.xuecheng.learning.model.po.XcCourseTables; import com.xuecheng.learning.service.MyCourseTablesService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.time.LocalDateTime; import java.util.List;
4,206
package com.xuecheng.learning.service.impl; /** * @author Wuxy * @version 1.0 * @ClassName MyCourseTableServiceImpl * @since 2023/2/2 11:54 */ @Service public class MyCourseTableServicesImpl implements MyCourseTablesService { @Resource private XcChooseCourseMapper chooseCourseMapper; @Resource
package com.xuecheng.learning.service.impl; /** * @author Wuxy * @version 1.0 * @ClassName MyCourseTableServiceImpl * @since 2023/2/2 11:54 */ @Service public class MyCourseTableServicesImpl implements MyCourseTablesService { @Resource private XcChooseCourseMapper chooseCourseMapper; @Resource
private XcCourseTablesMapper courseTablesMapper;
6
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,632
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() {
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");
5
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,066
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(" ")) {
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);
5
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/user/UserInfoController.java
[ { "identifier": "UserInfoVO", "path": "dubbo-api/dubbo-api-user/src/main/java/com/liyz/boot3/api/user/vo/user/UserInfoVO.java", "snippet": "@Getter\n@Setter\npublic class UserInfoVO implements Serializable {\n @Serial\n private static final long serialVersionUID = 3401036150852744531L;\n\n @Sch...
import com.github.xiaoymin.knife4j.annotations.ApiSort; import com.liyz.boot3.api.user.vo.user.UserInfoVO; import com.liyz.boot3.api.user.vo.user.UserLoginLogVO; import com.liyz.boot3.api.user.vo.user.UserLogoutLogVO; import com.liyz.boot3.common.api.dto.PageDTO; import com.liyz.boot3.common.api.result.PageResult; import com.liyz.boot3.common.api.result.Result; import com.liyz.boot3.common.remote.page.PageBO; import com.liyz.boot3.common.remote.page.RemotePage; import com.liyz.boot3.common.service.util.BeanUtil; import com.liyz.boot3.security.client.context.AuthContext; import com.liyz.boot3.service.auth.bo.AuthUserBO; import com.liyz.boot3.service.user.bo.UserLoginLogBO; import com.liyz.boot3.service.user.bo.UserLogoutLogBO; import com.liyz.boot3.service.user.remote.RemoteUserInfoService; import com.liyz.boot3.service.user.remote.RemoteUserLoginLogService; import com.liyz.boot3.service.user.remote.RemoteUserLogoutLogService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.extern.slf4j.Slf4j; import org.apache.dubbo.config.annotation.DubboReference; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Objects;
6,716
package com.liyz.boot3.api.user.controller.user; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/12/6 10:47 */ @ApiSort(3) @Tag(name = "用户信息") @ApiResponses(value = { @ApiResponse(responseCode = "0", description = "成功"), @ApiResponse(responseCode = "1", description = "失败") }) @Slf4j @SecurityRequirement(name = HttpHeaders.AUTHORIZATION) @RestController @RequestMapping("/user") public class UserInfoController { @DubboReference private RemoteUserInfoService remoteUserInfoService; @DubboReference private RemoteUserLoginLogService remoteUserLoginLogService; @DubboReference private RemoteUserLogoutLogService remoteUserLogoutLogService; @Operation(summary = "查询当前登录用户信息") @GetMapping("/current") public Result<UserInfoVO> userInfo() { AuthUserBO authUserBO = AuthContext.getAuthUser(); return Result.success(BeanUtil.copyProperties(remoteUserInfoService.getByUserId(authUserBO.getAuthId()), UserInfoVO::new)); } @Operation(summary = "分页查询用户登录日志") @GetMapping("/loginLogs/page") public PageResult<UserLoginLogVO> pageLoginLogs(PageDTO page) { AuthUserBO authUserBO = AuthContext.getAuthUser(); page = Objects.nonNull(page) ? page : new PageDTO();
package com.liyz.boot3.api.user.controller.user; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/12/6 10:47 */ @ApiSort(3) @Tag(name = "用户信息") @ApiResponses(value = { @ApiResponse(responseCode = "0", description = "成功"), @ApiResponse(responseCode = "1", description = "失败") }) @Slf4j @SecurityRequirement(name = HttpHeaders.AUTHORIZATION) @RestController @RequestMapping("/user") public class UserInfoController { @DubboReference private RemoteUserInfoService remoteUserInfoService; @DubboReference private RemoteUserLoginLogService remoteUserLoginLogService; @DubboReference private RemoteUserLogoutLogService remoteUserLogoutLogService; @Operation(summary = "查询当前登录用户信息") @GetMapping("/current") public Result<UserInfoVO> userInfo() { AuthUserBO authUserBO = AuthContext.getAuthUser(); return Result.success(BeanUtil.copyProperties(remoteUserInfoService.getByUserId(authUserBO.getAuthId()), UserInfoVO::new)); } @Operation(summary = "分页查询用户登录日志") @GetMapping("/loginLogs/page") public PageResult<UserLoginLogVO> pageLoginLogs(PageDTO page) { AuthUserBO authUserBO = AuthContext.getAuthUser(); page = Objects.nonNull(page) ? page : new PageDTO();
RemotePage<UserLoginLogBO> remotePage = remoteUserLoginLogService.page(authUserBO.getAuthId(), BeanUtil.copyProperties(page, PageBO::new));
11
2023-11-13 01:28:21+00:00
8k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/system/rest/UserController.java
[ { "identifier": "RsaProperties", "path": "dimple-common/src/main/java/com/dimple/config/RsaProperties.java", "snippet": "@Data\n@Component\npublic class RsaProperties {\n\n public static String privateKey;\n\n @Value(\"${rsa.private_key}\")\n public void setPrivateKey(String privateKey) {\n ...
import com.dimple.annotation.OLog; import com.dimple.config.RsaProperties; import com.dimple.exception.BadRequestException; import com.dimple.modules.system.domain.User; import com.dimple.modules.system.domain.vo.UserPassVO; import com.dimple.modules.system.service.RoleService; import com.dimple.modules.system.service.UserService; import com.dimple.modules.system.service.VerifyService; import com.dimple.modules.system.service.dto.RoleSmallDTO; import com.dimple.modules.system.service.dto.UserDTO; import com.dimple.modules.system.service.dto.UserQueryCriteria; import com.dimple.utils.RsaUtils; import com.dimple.utils.SecurityUtils; import com.dimple.utils.enums.CodeEnum; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.validation.annotation.Validated; 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.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Collections; import java.util.Set; import java.util.stream.Collectors;
6,059
package com.dimple.modules.system.rest; /** * @className: UserController * @description: * @author: Dimple * @date: 06/17/20 */ @Api(tags = "系统:用户管理") @RestController @RequestMapping("/api/users") @RequiredArgsConstructor public class UserController { private final PasswordEncoder passwordEncoder; private final UserService userService; private final RoleService roleService; private final VerifyService verificationCodeService; @OLog("导出用户数据") @ApiOperation("导出用户数据") @GetMapping(value = "/download") @PreAuthorize("@ps.check('user:list')") public void download(HttpServletResponse response, UserQueryCriteria criteria) throws IOException { userService.download(userService.queryAll(criteria), response); } @OLog("查询用户") @ApiOperation("查询用户") @GetMapping @PreAuthorize("@ps.check('user:list')") public ResponseEntity<Object> query(UserQueryCriteria criteria, Pageable pageable) { return new ResponseEntity<>(userService.queryAll(criteria, pageable), HttpStatus.OK); } @OLog("新增用户") @ApiOperation("新增用户") @PostMapping @PreAuthorize("@ps.check('user:add')") public ResponseEntity<Object> create(@Validated @RequestBody User resources) { checkLevel(resources); // 默认密码 123456 resources.setPassword(passwordEncoder.encode("123456")); userService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); } @OLog("修改用户") @ApiOperation("修改用户") @PutMapping @PreAuthorize("@ps.check('user:edit')") public ResponseEntity<Object> update(@Validated(User.Update.class) @RequestBody User resources) { checkLevel(resources); userService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @OLog("修改用户:个人中心") @ApiOperation("修改用户:个人中心") @PutMapping(value = "center") public ResponseEntity<Object> center(@Validated(User.Update.class) @RequestBody User resources) { if (!resources.getId().equals(SecurityUtils.getCurrentUserId())) { throw new BadRequestException("不能修改他人资料"); } userService.updateCenter(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @OLog("删除用户") @ApiOperation("删除用户") @DeleteMapping @PreAuthorize("@ps.check('user:del')") public ResponseEntity<Object> delete(@RequestBody Set<Long> ids) { for (Long id : ids) { Integer currentLevel = Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList())); Integer optLevel = Collections.min(roleService.findByUsersId(id).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList())); if (currentLevel > optLevel) { throw new BadRequestException("角色权限不足,不能删除:" + userService.findById(id).getUsername()); } } userService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("修改密码") @PostMapping(value = "/updatePass") public ResponseEntity<Object> updatePass(@RequestBody UserPassVO passVo) throws Exception { String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, passVo.getOldPass()); String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, passVo.getNewPass()); UserDTO user = userService.findByName(SecurityUtils.getCurrentUsername()); if (!passwordEncoder.matches(oldPass, user.getPassword())) { throw new BadRequestException("修改失败,旧密码错误"); } if (passwordEncoder.matches(newPass, user.getPassword())) { throw new BadRequestException("新密码不能与旧密码相同"); } userService.updatePass(user.getUsername(), passwordEncoder.encode(newPass)); return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("修改头像") @PostMapping(value = "/updateAvatar") public ResponseEntity<Object> updateAvatar(@RequestParam MultipartFile avatar) { return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK); } @OLog("修改邮箱") @ApiOperation("修改邮箱") @PostMapping(value = "/updateEmail/{code}") public ResponseEntity<Object> updateEmail(@PathVariable String code, @RequestBody User user) throws Exception { String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, user.getPassword()); UserDTO userDto = userService.findByName(SecurityUtils.getCurrentUsername()); if (!passwordEncoder.matches(password, userDto.getPassword())) { throw new BadRequestException("密码错误"); }
package com.dimple.modules.system.rest; /** * @className: UserController * @description: * @author: Dimple * @date: 06/17/20 */ @Api(tags = "系统:用户管理") @RestController @RequestMapping("/api/users") @RequiredArgsConstructor public class UserController { private final PasswordEncoder passwordEncoder; private final UserService userService; private final RoleService roleService; private final VerifyService verificationCodeService; @OLog("导出用户数据") @ApiOperation("导出用户数据") @GetMapping(value = "/download") @PreAuthorize("@ps.check('user:list')") public void download(HttpServletResponse response, UserQueryCriteria criteria) throws IOException { userService.download(userService.queryAll(criteria), response); } @OLog("查询用户") @ApiOperation("查询用户") @GetMapping @PreAuthorize("@ps.check('user:list')") public ResponseEntity<Object> query(UserQueryCriteria criteria, Pageable pageable) { return new ResponseEntity<>(userService.queryAll(criteria, pageable), HttpStatus.OK); } @OLog("新增用户") @ApiOperation("新增用户") @PostMapping @PreAuthorize("@ps.check('user:add')") public ResponseEntity<Object> create(@Validated @RequestBody User resources) { checkLevel(resources); // 默认密码 123456 resources.setPassword(passwordEncoder.encode("123456")); userService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); } @OLog("修改用户") @ApiOperation("修改用户") @PutMapping @PreAuthorize("@ps.check('user:edit')") public ResponseEntity<Object> update(@Validated(User.Update.class) @RequestBody User resources) { checkLevel(resources); userService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @OLog("修改用户:个人中心") @ApiOperation("修改用户:个人中心") @PutMapping(value = "center") public ResponseEntity<Object> center(@Validated(User.Update.class) @RequestBody User resources) { if (!resources.getId().equals(SecurityUtils.getCurrentUserId())) { throw new BadRequestException("不能修改他人资料"); } userService.updateCenter(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @OLog("删除用户") @ApiOperation("删除用户") @DeleteMapping @PreAuthorize("@ps.check('user:del')") public ResponseEntity<Object> delete(@RequestBody Set<Long> ids) { for (Long id : ids) { Integer currentLevel = Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList())); Integer optLevel = Collections.min(roleService.findByUsersId(id).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList())); if (currentLevel > optLevel) { throw new BadRequestException("角色权限不足,不能删除:" + userService.findById(id).getUsername()); } } userService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("修改密码") @PostMapping(value = "/updatePass") public ResponseEntity<Object> updatePass(@RequestBody UserPassVO passVo) throws Exception { String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, passVo.getOldPass()); String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, passVo.getNewPass()); UserDTO user = userService.findByName(SecurityUtils.getCurrentUsername()); if (!passwordEncoder.matches(oldPass, user.getPassword())) { throw new BadRequestException("修改失败,旧密码错误"); } if (passwordEncoder.matches(newPass, user.getPassword())) { throw new BadRequestException("新密码不能与旧密码相同"); } userService.updatePass(user.getUsername(), passwordEncoder.encode(newPass)); return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("修改头像") @PostMapping(value = "/updateAvatar") public ResponseEntity<Object> updateAvatar(@RequestParam MultipartFile avatar) { return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK); } @OLog("修改邮箱") @ApiOperation("修改邮箱") @PostMapping(value = "/updateEmail/{code}") public ResponseEntity<Object> updateEmail(@PathVariable String code, @RequestBody User user) throws Exception { String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, user.getPassword()); UserDTO userDto = userService.findByName(SecurityUtils.getCurrentUsername()); if (!passwordEncoder.matches(password, userDto.getPassword())) { throw new BadRequestException("密码错误"); }
verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + user.getEmail(), code);
12
2023-11-10 03:30:36+00:00
8k
LazyCoder0101/LazyCoder
ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/formatedit/additional/AdditionalInputEditPane.java
[ { "identifier": "AdditionalInfo", "path": "database/src/main/java/com/lazycoder/database/model/AdditionalInfo.java", "snippet": "@Data\npublic class AdditionalInfo extends AbstractFormatInfo {\n\n\tprivate int additionalSerialNumber = 0;\n\n\tpublic AdditionalInfo() {\n\t\t// TODO Auto-generated constru...
import com.lazycoder.database.model.AdditionalInfo; import com.lazycoder.service.fileStructure.SysFileStructure; import com.lazycoder.service.vo.meta.AdditionalMetaModel; import com.lazycoder.service.vo.save.AdditionalFunctionNameInputData; import com.lazycoder.service.vo.save.AdditionalVariableInputData; import com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.format.operation.AdditionalFormatControlPane; import com.lazycoder.uidatasourceedit.moduleedit.CheckInterface; import com.lazycoder.uiutils.component.animatedcarousel.net.codemap.carousel.helpcarousel.OperatingTipButton; import com.lazycoder.uiutils.mycomponent.MyButton; import com.lazycoder.uiutils.utils.SysUtil; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import lombok.Getter;
5,315
package com.lazycoder.uidatasourceedit.formatedit.additional; public class AdditionalInputEditPane extends JPanel implements AdditionalPaneInterface, CheckInterface { /** * */ private static final long serialVersionUID = 8796634939292739650L; private MyButton addVarButton, delVarButton, addFuncitonButton, delFuncitionButton, restoreButton, clearBt; @Getter private AdditionalFormatControlPane additionalFormatControlPane; @Getter private AdditionalVariableTable additionalVariableTable; @Getter private AdditionalFuncitonTable additionalFuncitonTable; private JScrollPane additionalFormatControlScrollPane, additionalVariableTableScrollPane, additionalFuncitonTableScrollPane; private AdditionalFormatPane additionalFormatPane; private JLabel lblNewLabel; private JLabel label1; private OperatingTipButton additionalFormatOperatingTip, additionalVariableOperatingTip, additionalFunctionOperatingTip; /** * Create the panel. */ public AdditionalInputEditPane(int additionalSerialNumber, AdditionalFormatPane additionalFormatPane) { setLayout(null); this.additionalFormatPane = additionalFormatPane; JLabel label = new JLabel("格式:"); label.setBounds(30, 60, 72, 18); add(label); int width = (int) (SysUtil.SCREEN_SIZE.width * 0.27); additionalFormatControlPane = new AdditionalFormatControlPane(additionalSerialNumber); additionalFormatControlScrollPane = new JScrollPane(additionalFormatControlPane); additionalFormatControlPane.setUpdateScrollpane(additionalFormatControlScrollPane); additionalFormatControlScrollPane.setBounds(80, 50, width, 300); add(additionalFormatControlScrollPane); restoreButton = new MyButton("还原"); restoreButton.addActionListener(actionListener); restoreButton.setBounds(100, 360, 80, 30); add(restoreButton); clearBt = new MyButton("清空"); clearBt.setBounds(200, 360, 80, 30); add(clearBt); clearBt.addActionListener(actionListener);
package com.lazycoder.uidatasourceedit.formatedit.additional; public class AdditionalInputEditPane extends JPanel implements AdditionalPaneInterface, CheckInterface { /** * */ private static final long serialVersionUID = 8796634939292739650L; private MyButton addVarButton, delVarButton, addFuncitonButton, delFuncitionButton, restoreButton, clearBt; @Getter private AdditionalFormatControlPane additionalFormatControlPane; @Getter private AdditionalVariableTable additionalVariableTable; @Getter private AdditionalFuncitonTable additionalFuncitonTable; private JScrollPane additionalFormatControlScrollPane, additionalVariableTableScrollPane, additionalFuncitonTableScrollPane; private AdditionalFormatPane additionalFormatPane; private JLabel lblNewLabel; private JLabel label1; private OperatingTipButton additionalFormatOperatingTip, additionalVariableOperatingTip, additionalFunctionOperatingTip; /** * Create the panel. */ public AdditionalInputEditPane(int additionalSerialNumber, AdditionalFormatPane additionalFormatPane) { setLayout(null); this.additionalFormatPane = additionalFormatPane; JLabel label = new JLabel("格式:"); label.setBounds(30, 60, 72, 18); add(label); int width = (int) (SysUtil.SCREEN_SIZE.width * 0.27); additionalFormatControlPane = new AdditionalFormatControlPane(additionalSerialNumber); additionalFormatControlScrollPane = new JScrollPane(additionalFormatControlPane); additionalFormatControlPane.setUpdateScrollpane(additionalFormatControlScrollPane); additionalFormatControlScrollPane.setBounds(80, 50, width, 300); add(additionalFormatControlScrollPane); restoreButton = new MyButton("还原"); restoreButton.addActionListener(actionListener); restoreButton.setBounds(100, 360, 80, 30); add(restoreButton); clearBt = new MyButton("清空"); clearBt.setBounds(200, 360, 80, 30); add(clearBt); clearBt.addActionListener(actionListener);
additionalFormatOperatingTip = new OperatingTipButton(SysFileStructure.getOperatingTipImageFolder(
1
2023-11-16 11:55:06+00:00
8k