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
Crydsch/the-one
src/core/DTNHost.java
[ { "identifier": "ConnectivityGrid", "path": "src/interfaces/ConnectivityGrid.java", "snippet": "public class ConnectivityGrid extends ConnectivityOptimizer {\n\n\t/**\n\t * Cell based optimization cell size multiplier -setting id ({@value}).\n\t * Used in {@link World#OPTIMIZATION_SETTINGS_NS} name spac...
import java.util.ArrayList; import java.util.Collection; import java.util.List; import interfaces.ConnectivityGrid; import movement.MovementEngine; import movement.MovementModel; import movement.Path; import routing.MessageRouter; import routing.util.RoutingInfo; import static core.Constants.DEBUG;
13,127
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package core; /** * A DTN capable host. */ public class DTNHost implements Comparable<DTNHost> { private static int count = 0; private int ID; private Coord destination; // where is it going
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package core; /** * A DTN capable host. */ public class DTNHost implements Comparable<DTNHost> { private static int count = 0; private int ID; private Coord destination; // where is it going
private MessageRouter router;
4
2023-12-10 15:51:41+00:00
16k
seleuco/MAME4droid-2024
android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/helpers/DialogHelper.java
[ { "identifier": "PRESS_WAIT", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/input/InputHandler.java", "snippet": "final static public int PRESS_WAIT = 100;" }, { "identifier": "Emulator", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/Emulator.jav...
import static com.seleuco.mame4droid.input.InputHandler.PRESS_WAIT; import android.app.AlertDialog; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.view.View; import com.seleuco.mame4droid.Emulator; import com.seleuco.mame4droid.MAME4droid; import com.seleuco.mame4droid.input.ControlCustomizer; import com.seleuco.mame4droid.views.IEmuView; import java.util.Arrays;
10,993
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * This program 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 2 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 * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.helpers; public class DialogHelper { public static int savedDialog = DialogHelper.DIALOG_NONE; public final static int DIALOG_NONE = -1; public final static int DIALOG_EXIT = 1; public final static int DIALOG_ERROR_WRITING = 2; public final static int DIALOG_INFO = 3; public final static int DIALOG_OPTIONS = 5; public final static int DIALOG_FULLSCREEN = 7; public final static int DIALOG_FINISH_CUSTOM_LAYOUT = 10; public final static int DIALOG_EMU_RESTART = 11; public final static int DIALOG_NO_PERMISSIONS = 12; public final static int DIALOG_ROMs = 13;
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * This program 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 2 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 * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.helpers; public class DialogHelper { public static int savedDialog = DialogHelper.DIALOG_NONE; public final static int DIALOG_NONE = -1; public final static int DIALOG_EXIT = 1; public final static int DIALOG_ERROR_WRITING = 2; public final static int DIALOG_INFO = 3; public final static int DIALOG_OPTIONS = 5; public final static int DIALOG_FULLSCREEN = 7; public final static int DIALOG_FINISH_CUSTOM_LAYOUT = 10; public final static int DIALOG_EMU_RESTART = 11; public final static int DIALOG_NO_PERMISSIONS = 12; public final static int DIALOG_ROMs = 13;
protected MAME4droid mm = null;
2
2023-12-18 11:16:18+00:00
16k
Swofty-Developments/HypixelSkyBlock
generic/src/main/java/net/swofty/types/generic/gui/inventory/inventories/sbmenu/profiles/GUIProfileCreate.java
[ { "identifier": "ServerType", "path": "commons/src/main/java/net/swofty/commons/ServerType.java", "snippet": "@Getter\npublic enum ServerType {\n ISLAND,\n VILLAGE,\n ;\n\n public static boolean isServerType(String type) {\n for (ServerType a : values())\n if (type.equalsIg...
import lombok.SneakyThrows; import net.minestom.server.MinecraftServer; import net.minestom.server.event.inventory.InventoryCloseEvent; import net.minestom.server.event.inventory.InventoryPreClickEvent; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryType; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import net.minestom.server.timer.TaskSchedule; import net.swofty.commons.ServerType; import net.swofty.types.generic.data.DataHandler; import net.swofty.types.generic.data.datapoints.DatapointString; import net.swofty.types.generic.data.datapoints.DatapointUUID; import net.swofty.types.generic.data.mongodb.ProfilesDatabase; import net.swofty.types.generic.data.mongodb.UserDatabase; import net.swofty.types.generic.gui.inventory.ItemStackCreator; import net.swofty.types.generic.gui.inventory.SkyBlockInventoryGUI; import net.swofty.types.generic.gui.inventory.item.GUIClickableItem; import net.swofty.types.generic.user.SkyBlockPlayer; import net.swofty.types.generic.user.UserProfiles; import org.bson.Document; import java.util.UUID;
13,703
package net.swofty.types.generic.gui.inventory.inventories.sbmenu.profiles; public class GUIProfileCreate extends SkyBlockInventoryGUI { public GUIProfileCreate() { super("Create a Profile", InventoryType.CHEST_3_ROW); } @SneakyThrows @Override public void onOpen(InventoryGUIOpenEvent e) { fill(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE)); String profileName = UserProfiles.getRandomName(); set(new GUIClickableItem(11) { @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStack("§aCreate New Profile", Material.GREEN_TERRACOTTA, (short) 0, 1, "§7You are creating a new SkyBlock", "§7profile.", "", "§7Profile name: §e" + profileName, "", "§7You won't lose any progress.", "§7You can switch between profiles.", "", "§bYou are creating a SOLO profile!", "§bUse /coop to play with friends!", "§eClick to confirm new profile!"); } @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { UserProfiles profiles = player.getProfiles(); UserProfiles toSet = new UserProfiles(); toSet.setProfiles(profiles.getProfiles()); UUID profileId = UUID.randomUUID(); DataHandler handler = DataHandler.initUserWithDefaultData(player.getUuid());
package net.swofty.types.generic.gui.inventory.inventories.sbmenu.profiles; public class GUIProfileCreate extends SkyBlockInventoryGUI { public GUIProfileCreate() { super("Create a Profile", InventoryType.CHEST_3_ROW); } @SneakyThrows @Override public void onOpen(InventoryGUIOpenEvent e) { fill(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE)); String profileName = UserProfiles.getRandomName(); set(new GUIClickableItem(11) { @Override public ItemStack.Builder getItem(SkyBlockPlayer player) { return ItemStackCreator.getStack("§aCreate New Profile", Material.GREEN_TERRACOTTA, (short) 0, 1, "§7You are creating a new SkyBlock", "§7profile.", "", "§7Profile name: §e" + profileName, "", "§7You won't lose any progress.", "§7You can switch between profiles.", "", "§bYou are creating a SOLO profile!", "§bUse /coop to play with friends!", "§eClick to confirm new profile!"); } @Override public void run(InventoryPreClickEvent e, SkyBlockPlayer player) { UserProfiles profiles = player.getProfiles(); UserProfiles toSet = new UserProfiles(); toSet.setProfiles(profiles.getProfiles()); UUID profileId = UUID.randomUUID(); DataHandler handler = DataHandler.initUserWithDefaultData(player.getUuid());
handler.get(DataHandler.Data.PROFILE_NAME, DatapointString.class).setValue(profileName);
2
2023-12-14 09:51:15+00:00
16k
litongjava/next-jfinal
src/main/java/com/jfinal/proxy/ProxyGenerator.java
[ { "identifier": "InterceptorManager", "path": "src/main/java/com/jfinal/aop/InterceptorManager.java", "snippet": "public class InterceptorManager {\n\t\n\tpublic static final Interceptor[] NULL_INTERS = new Interceptor[0];\n\t\n\t// 控制层与业务层全局拦截器\n\tprivate Interceptor[] globalActionInters = NULL_INTERS;...
import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jfinal.aop.Before; import com.jfinal.aop.Clear; import com.jfinal.aop.InterceptorManager; import com.jfinal.kit.Kv; import com.jfinal.template.Engine; import com.jfinal.template.Template;
13,796
/** * 获取子类泛型变量,也可用于获取方法泛型变量 */ @SuppressWarnings("rawtypes") protected String getTypeVars(TypeVariable[] typeVars) { if (typeVars == null || typeVars.length == 0) { return null; } StringBuilder ret = new StringBuilder(); ret.append('<'); for (int i = 0; i < typeVars.length; i++) { TypeVariable tv = typeVars[i]; if (i > 0) { ret.append(", "); } ret.append(tv.getName()); // T extends Map & List & Set Type[] bounds = tv.getBounds(); if (bounds.length == 1) { if (bounds[0] != Object.class) { ret.append(" extends ").append(bounds[0].getTypeName()); continue; } } else { for (int j = 0; j < bounds.length; j++) { String tn = bounds[j].getTypeName(); if (j > 0) { ret.append(" & ").append(tn); } else { ret.append(" extends ").append(tn); } } } } return ret.append('>').toString(); } /** * 获取父类泛型变量 * * 相对于 getTypeVars(...) 取消了 TypeVariable.getBounds() 内容的生成,否则编译错误 */ @SuppressWarnings("rawtypes") protected String getTargetTypeVars(TypeVariable[] typeVars) { if (typeVars == null || typeVars.length == 0) { return null; } StringBuilder ret = new StringBuilder(); ret.append('<'); for (int i = 0; i < typeVars.length; i++) { TypeVariable tv = typeVars[i]; if (i > 0) { ret.append(", "); } ret.append(tv.getName()); } return ret.append('>').toString(); } /** * 获取方法抛出的异常 */ protected String getThrows(Method method) { Class<?>[] throwTypes = method.getExceptionTypes(); if (throwTypes == null || throwTypes.length == 0) { return null; } StringBuilder ret = new StringBuilder().append("throws "); for (int i = 0; i < throwTypes.length; i++) { if (i > 0) { ret.append(", "); } ret.append(throwTypes[i].getName()); } return ret.append(' ').toString(); } /** * 跳过不能代理的方法 * 1:非 public * 2:final、static、abstract * 3:方法名为:toString、hashCode、equals */ protected boolean isSkipMethod(Method method) { int mod = method.getModifiers(); if (!Modifier.isPublic(mod)) { return true; } if (Modifier.isFinal(mod) || Modifier.isStatic(mod) || Modifier.isAbstract(mod)) { return true; } String n = method.getName(); if (n.equals("toString") || n.equals("hashCode") || n.equals("equals")) { return true; } return false; } /** * 获取 method 上层的拦截器,也即获取 global、class 这两层拦截器 * 注意:global 层拦截器已结合 class 层 @Clear 注解处理过 */ protected List<Class<?>> getMethodUpperInterceptors(ProxyClass proxyClass) { List<Class<?>> ret; // 结合 class 级 @Clear,得到 global 级拦截器 Clear clearOnClass = proxyClass.getTarget().getAnnotation(Clear.class); if (clearOnClass != null) { Class<?>[] clearIntersOnClass = clearOnClass.value(); if (clearIntersOnClass.length != 0) { // class 级 @clear 且带参
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.jfinal.proxy; /** * ProxyGenerator 用于生成代理类的源代码 * * 注意:业务层全局拦截器要在 ProxyGenerator 工作之前配置好,否则无法参与生成 * * 追求性能极致: * 1:禁止使用 JDK 的 Method.invoke(...) 调用被代理方法 * 2:method 存在有效的拦截器才生成代理方法 ProxyMethod * 3:目标类 target 存在 ProxyMethod 才生成代理类 ProxyClass * * 避免生成代理类的方法: * 1:类文件内部删掉 @Before 声明的拦截器 * 2:添加一个 class 层的 @Clear 注解 * 因此,proxy 模块设计可以覆盖掉 @Enhance 注解功能 */ public class ProxyGenerator { private Logger log = LoggerFactory.getLogger(this.getClass()); protected Engine engine = null; protected Template template = null; protected boolean printGeneratedClassToConsole = false; protected boolean printGeneratedClassToLog = true; public ProxyGenerator() { String filename = "com/litongjava/jfinal/proxy/proxy_class_template.jf"; engine = new Engine("forProxy").setToClassPathSourceFactory(); String baseTemplatePath = engine.getEngineConfig().getBaseTemplatePath(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); String finalFileName = buildFinalFileName(baseTemplatePath, filename); URL url = classLoader.getResource(finalFileName); if (url != null) { template = engine.getTemplate(filename); } else { // 创建proxy_class_template.jf文件 engine = new Engine("forProxy").setSourceFactory(new com.jfinal.template.source.FileSourceFactory()); new ProxyClassTemplate("proxy_class_template.jf").create(); template = engine.getTemplate("proxy_class_template.jf"); } } public String buildFinalFileName(String baseTemplatePath, String fileName) { String finalFileName; if (baseTemplatePath != null) { char firstChar = fileName.charAt(0); if (firstChar == '/' || firstChar == '\\') { finalFileName = baseTemplatePath + fileName; } else { finalFileName = baseTemplatePath + "/" + fileName; } } else { finalFileName = fileName; } if (finalFileName.charAt(0) == '/') { finalFileName = finalFileName.substring(1); } return finalFileName; } public ProxyClass generate(Class<?> target) { ProxyClass proxyClass = new ProxyClass(target); Kv clazz = Kv.create(); clazz.set("pkg", proxyClass.getPkg()); clazz.set("name", proxyClass.getName()); clazz.set("targetName", getTargetName(target)); @SuppressWarnings("rawtypes") TypeVariable[] tvs = target.getTypeParameters(); clazz.set("classTypeVars", getTypeVars(tvs)); clazz.set("targetTypeVars", getTargetTypeVars(tvs)); List<Class<?>> methodUpperInters = getMethodUpperInterceptors(proxyClass); List<Kv> methodList = new ArrayList<>(); clazz.set("methodList", methodList); Method[] methodArray = target.getMethods(); for (Method m : methodArray) { if (isSkipMethod(m)) { continue; } // 没有拦截器的 method 不生成 ProxyMethod if (!hasInterceptor(methodUpperInters, proxyClass, m)) { continue; } Kv method = Kv.create(); method.set("methodTypeVars", getTypeVars(m.getTypeParameters())); method.set("returnType", getReturnType(m)); method.set("name", m.getName()); method.set("throws", getThrows(m)); Parameter[] paras = m.getParameters(); List<String> paraTypes = Arrays.asList(paras).stream().map(x -> { // 参考 JDK Parameter StringBuilder sb = new StringBuilder(); Type type = x.getParameterizedType(); String typename = type.getTypeName(); if (x.isVarArgs()) { sb.append(typename.replaceFirst("\\[\\]$", "...")); } else { sb.append(typename); } return sb.toString(); }).collect(Collectors.toList()); method.set("paraTypes", paraTypes); // 缓存 ProxyMethod 的 key 值 Long proxyMethodKey = ProxyMethodCache.generateKey(); method.set("proxyMethodKey", proxyMethodKey); // 只有一个参数,且该参数是数组或者可变参数时传递 singleArrayPara = true if (paras.length == 1) { if (paras[0].getType().isArray() || paras[0].isVarArgs()) { method.set("singleArrayPara", true); } } if (m.getReturnType() != void.class) { method.set("frontReturn", "return "); } else { method.set("backReturn", "return null;"); } methodList.add(method); ProxyMethod proxyMethod = new ProxyMethod(); proxyClass.addProxyMethod(proxyMethod); proxyMethod.setKey(proxyMethodKey); proxyMethod.setTargetClass(target); proxyMethod.setMethod(m); } if (proxyClass.needProxy()) { String sourceCode = template.renderToString(clazz); proxyClass.setSourceCode(sourceCode); if (printGeneratedClassToConsole) { String msg = "Generate proxy class \"" + proxyClass.getPkg() + "." + proxyClass.getName() + "\":"; System.out.print(msg); System.out.println(sourceCode); } if (printGeneratedClassToLog && log.isDebugEnabled()) { String msg = "\nGenerate proxy class \"" + proxyClass.getPkg() + "." + proxyClass.getName() + "\":"; log.debug(msg + sourceCode); } } return proxyClass; } /** * 支持对 static 类的代理 */ protected String getTargetName(Class<?> target) { if (Modifier.isStatic(target.getModifiers())) { // 无法兼容主类类名中包含字符 '$',例如:com.xxx.My$Target&Inner // return target.getName().replace('$', '.'); // 静态类的 getName() 值为 com.xxx.Target&Inner 需要将字符 '$' 替换成 '.' String ret = target.getName(); int index = ret.lastIndexOf('$'); return ret.substring(0, index) + "." + ret.substring(index + 1); } else { return target.getSimpleName(); } } /** * 方法返回值为 int[] 时 method.getReturnType().getName() 返回值为: [I * 需要识别并转化 */ protected String getReturnType(Method method) { // return method.getReturnType().getName(); // return method.getAnnotatedReturnType().getType().getTypeName(); return method.getGenericReturnType().getTypeName(); } /** * 获取子类泛型变量,也可用于获取方法泛型变量 */ @SuppressWarnings("rawtypes") protected String getTypeVars(TypeVariable[] typeVars) { if (typeVars == null || typeVars.length == 0) { return null; } StringBuilder ret = new StringBuilder(); ret.append('<'); for (int i = 0; i < typeVars.length; i++) { TypeVariable tv = typeVars[i]; if (i > 0) { ret.append(", "); } ret.append(tv.getName()); // T extends Map & List & Set Type[] bounds = tv.getBounds(); if (bounds.length == 1) { if (bounds[0] != Object.class) { ret.append(" extends ").append(bounds[0].getTypeName()); continue; } } else { for (int j = 0; j < bounds.length; j++) { String tn = bounds[j].getTypeName(); if (j > 0) { ret.append(" & ").append(tn); } else { ret.append(" extends ").append(tn); } } } } return ret.append('>').toString(); } /** * 获取父类泛型变量 * * 相对于 getTypeVars(...) 取消了 TypeVariable.getBounds() 内容的生成,否则编译错误 */ @SuppressWarnings("rawtypes") protected String getTargetTypeVars(TypeVariable[] typeVars) { if (typeVars == null || typeVars.length == 0) { return null; } StringBuilder ret = new StringBuilder(); ret.append('<'); for (int i = 0; i < typeVars.length; i++) { TypeVariable tv = typeVars[i]; if (i > 0) { ret.append(", "); } ret.append(tv.getName()); } return ret.append('>').toString(); } /** * 获取方法抛出的异常 */ protected String getThrows(Method method) { Class<?>[] throwTypes = method.getExceptionTypes(); if (throwTypes == null || throwTypes.length == 0) { return null; } StringBuilder ret = new StringBuilder().append("throws "); for (int i = 0; i < throwTypes.length; i++) { if (i > 0) { ret.append(", "); } ret.append(throwTypes[i].getName()); } return ret.append(' ').toString(); } /** * 跳过不能代理的方法 * 1:非 public * 2:final、static、abstract * 3:方法名为:toString、hashCode、equals */ protected boolean isSkipMethod(Method method) { int mod = method.getModifiers(); if (!Modifier.isPublic(mod)) { return true; } if (Modifier.isFinal(mod) || Modifier.isStatic(mod) || Modifier.isAbstract(mod)) { return true; } String n = method.getName(); if (n.equals("toString") || n.equals("hashCode") || n.equals("equals")) { return true; } return false; } /** * 获取 method 上层的拦截器,也即获取 global、class 这两层拦截器 * 注意:global 层拦截器已结合 class 层 @Clear 注解处理过 */ protected List<Class<?>> getMethodUpperInterceptors(ProxyClass proxyClass) { List<Class<?>> ret; // 结合 class 级 @Clear,得到 global 级拦截器 Clear clearOnClass = proxyClass.getTarget().getAnnotation(Clear.class); if (clearOnClass != null) { Class<?>[] clearIntersOnClass = clearOnClass.value(); if (clearIntersOnClass.length != 0) { // class 级 @clear 且带参
ret = InterceptorManager.me().getGlobalServiceInterceptorClasses();
0
2023-12-19 10:58:33+00:00
16k
HypixelSkyblockmod/ChromaHud
src/java/xyz/apfelmus/cheeto/client/modules/movement/Pathfinding.java
[ { "identifier": "CF4M", "path": "src/java/xyz/apfelmus/cf4m/CF4M.java", "snippet": "public enum CF4M {\n INSTANCE;\n\n public String packName;\n public String dir;\n public IConfiguration configuration;\n public ClassManager classManager;\n public EventManager eventManager;\n public...
import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiChat; import net.minecraft.client.settings.KeyBinding; import net.minecraft.util.BlockPos; import net.minecraft.util.Vec3; import net.minecraft.util.Vec3i; import xyz.apfelmus.cf4m.CF4M; import xyz.apfelmus.cf4m.annotation.Event; import xyz.apfelmus.cf4m.annotation.Setting; import xyz.apfelmus.cf4m.annotation.module.Disable; import xyz.apfelmus.cf4m.annotation.module.Enable; import xyz.apfelmus.cf4m.annotation.module.Module; import xyz.apfelmus.cf4m.module.Category; import xyz.apfelmus.cheeto.client.events.ClientTickEvent; import xyz.apfelmus.cheeto.client.events.Render3DEvent; import xyz.apfelmus.cheeto.client.settings.IntegerSetting; import xyz.apfelmus.cheeto.client.utils.client.ChatUtils; import xyz.apfelmus.cheeto.client.utils.client.ColorUtils; import xyz.apfelmus.cheeto.client.utils.client.KeybindUtils; import xyz.apfelmus.cheeto.client.utils.client.Rotation; import xyz.apfelmus.cheeto.client.utils.client.RotationUtils; import xyz.apfelmus.cheeto.client.utils.math.TimeHelper; import xyz.apfelmus.cheeto.client.utils.math.VecUtils; import xyz.apfelmus.cheeto.client.utils.pathfinding.Pathfinder; import xyz.apfelmus.cheeto.client.utils.render.Render3DUtils;
12,718
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.client.Minecraft * net.minecraft.client.gui.GuiChat * net.minecraft.client.settings.KeyBinding * net.minecraft.util.BlockPos * net.minecraft.util.Vec3 * net.minecraft.util.Vec3i */ package xyz.apfelmus.cheeto.client.modules.movement; @Module(name="Pathfinding", description="Do not toggle this module, it won't work", category=Category.MOVEMENT) public class Pathfinding { @Setting(name="UnstuckTime") private IntegerSetting unstucktime = new IntegerSetting(3, 1, 10); @Setting(name="LookTime") private IntegerSetting lookTime = new IntegerSetting(150, 0, 1000); private static Minecraft mc = Minecraft.func_71410_x(); private static int stuckTicks = 0; private static BlockPos oldPos; private static BlockPos curPos; private static TimeHelper unstucker; @Enable public void onEnable() { stuckTicks = 0; oldPos = null; curPos = null; if (!Pathfinder.hasPath()) { ChatUtils.send("Pussy bitch, no path found", new String[0]);
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * net.minecraft.client.Minecraft * net.minecraft.client.gui.GuiChat * net.minecraft.client.settings.KeyBinding * net.minecraft.util.BlockPos * net.minecraft.util.Vec3 * net.minecraft.util.Vec3i */ package xyz.apfelmus.cheeto.client.modules.movement; @Module(name="Pathfinding", description="Do not toggle this module, it won't work", category=Category.MOVEMENT) public class Pathfinding { @Setting(name="UnstuckTime") private IntegerSetting unstucktime = new IntegerSetting(3, 1, 10); @Setting(name="LookTime") private IntegerSetting lookTime = new IntegerSetting(150, 0, 1000); private static Minecraft mc = Minecraft.func_71410_x(); private static int stuckTicks = 0; private static BlockPos oldPos; private static BlockPos curPos; private static TimeHelper unstucker; @Enable public void onEnable() { stuckTicks = 0; oldPos = null; curPos = null; if (!Pathfinder.hasPath()) { ChatUtils.send("Pussy bitch, no path found", new String[0]);
CF4M.INSTANCE.moduleManager.toggle(this);
0
2023-12-21 16:22:25+00:00
16k
emtee40/ApkSignatureKill-pc
app/src/main/java/org/jf/baksmali/Adaptors/EncodedValue/EncodedValueAdaptor.java
[ { "identifier": "ReferenceFormatter", "path": "app/src/main/java/org/jf/baksmali/Adaptors/ReferenceFormatter.java", "snippet": "public class ReferenceFormatter {\n public static void writeStringReference(IndentingWriter writer, String item) throws IOException {\n writer.write('\"');\n S...
import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.jf.baksmali.Adaptors.ReferenceFormatter; import org.jf.baksmali.Renderers.BooleanRenderer; import org.jf.baksmali.Renderers.ByteRenderer; import org.jf.baksmali.Renderers.CharRenderer; import org.jf.baksmali.Renderers.DoubleRenderer; import org.jf.baksmali.Renderers.FloatRenderer; import org.jf.baksmali.Renderers.IntegerRenderer; import org.jf.baksmali.Renderers.LongRenderer; import org.jf.baksmali.Renderers.ShortRenderer; import org.jf.dexlib2.ValueType; import org.jf.dexlib2.iface.value.AnnotationEncodedValue; import org.jf.dexlib2.iface.value.ArrayEncodedValue; import org.jf.dexlib2.iface.value.BooleanEncodedValue; import org.jf.dexlib2.iface.value.ByteEncodedValue; import org.jf.dexlib2.iface.value.CharEncodedValue; import org.jf.dexlib2.iface.value.DoubleEncodedValue; import org.jf.dexlib2.iface.value.EncodedValue; import org.jf.dexlib2.iface.value.EnumEncodedValue; import org.jf.dexlib2.iface.value.FieldEncodedValue; import org.jf.dexlib2.iface.value.FloatEncodedValue; import org.jf.dexlib2.iface.value.IntEncodedValue; import org.jf.dexlib2.iface.value.LongEncodedValue; import org.jf.dexlib2.iface.value.MethodEncodedValue; import org.jf.dexlib2.iface.value.ShortEncodedValue; import org.jf.dexlib2.iface.value.StringEncodedValue; import org.jf.dexlib2.iface.value.TypeEncodedValue; import org.jf.dexlib2.util.ReferenceUtil; import org.jf.util.IndentingWriter; import java.io.IOException;
11,630
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors.EncodedValue; public abstract class EncodedValueAdaptor { public static void writeTo(@NonNull IndentingWriter writer, @NonNull EncodedValue encodedValue, @Nullable String containingClass) throws IOException { switch (encodedValue.getValueType()) { case ValueType.ANNOTATION: AnnotationEncodedValueAdaptor.writeTo(writer, (AnnotationEncodedValue) encodedValue, containingClass); return; case ValueType.ARRAY: ArrayEncodedValueAdaptor.writeTo(writer, (ArrayEncodedValue) encodedValue, containingClass); return; case ValueType.BOOLEAN: BooleanRenderer.writeTo(writer, ((BooleanEncodedValue) encodedValue).getValue()); return; case ValueType.BYTE: ByteRenderer.writeTo(writer, ((ByteEncodedValue) encodedValue).getValue()); return; case ValueType.CHAR: CharRenderer.writeTo(writer, ((CharEncodedValue) encodedValue).getValue()); return; case ValueType.DOUBLE: DoubleRenderer.writeTo(writer, ((DoubleEncodedValue) encodedValue).getValue()); return; case ValueType.ENUM: EnumEncodedValue enumEncodedValue = (EnumEncodedValue) encodedValue; boolean useImplicitReference = false; if (enumEncodedValue.getValue().getDefiningClass().equals(containingClass)) { useImplicitReference = true; } writer.write(".enum "); ReferenceUtil.writeFieldDescriptor(writer, enumEncodedValue.getValue(), useImplicitReference); return; case ValueType.FIELD: FieldEncodedValue fieldEncodedValue = (FieldEncodedValue) encodedValue; useImplicitReference = false; if (fieldEncodedValue.getValue().getDefiningClass().equals(containingClass)) { useImplicitReference = true; } ReferenceUtil.writeFieldDescriptor(writer, fieldEncodedValue.getValue(), useImplicitReference); return; case ValueType.FLOAT:
/* * [The "BSD licence"] * Copyright (c) 2010 Ben Gruver (JesusFreke) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.baksmali.Adaptors.EncodedValue; public abstract class EncodedValueAdaptor { public static void writeTo(@NonNull IndentingWriter writer, @NonNull EncodedValue encodedValue, @Nullable String containingClass) throws IOException { switch (encodedValue.getValueType()) { case ValueType.ANNOTATION: AnnotationEncodedValueAdaptor.writeTo(writer, (AnnotationEncodedValue) encodedValue, containingClass); return; case ValueType.ARRAY: ArrayEncodedValueAdaptor.writeTo(writer, (ArrayEncodedValue) encodedValue, containingClass); return; case ValueType.BOOLEAN: BooleanRenderer.writeTo(writer, ((BooleanEncodedValue) encodedValue).getValue()); return; case ValueType.BYTE: ByteRenderer.writeTo(writer, ((ByteEncodedValue) encodedValue).getValue()); return; case ValueType.CHAR: CharRenderer.writeTo(writer, ((CharEncodedValue) encodedValue).getValue()); return; case ValueType.DOUBLE: DoubleRenderer.writeTo(writer, ((DoubleEncodedValue) encodedValue).getValue()); return; case ValueType.ENUM: EnumEncodedValue enumEncodedValue = (EnumEncodedValue) encodedValue; boolean useImplicitReference = false; if (enumEncodedValue.getValue().getDefiningClass().equals(containingClass)) { useImplicitReference = true; } writer.write(".enum "); ReferenceUtil.writeFieldDescriptor(writer, enumEncodedValue.getValue(), useImplicitReference); return; case ValueType.FIELD: FieldEncodedValue fieldEncodedValue = (FieldEncodedValue) encodedValue; useImplicitReference = false; if (fieldEncodedValue.getValue().getDefiningClass().equals(containingClass)) { useImplicitReference = true; } ReferenceUtil.writeFieldDescriptor(writer, fieldEncodedValue.getValue(), useImplicitReference); return; case ValueType.FLOAT:
FloatRenderer.writeTo(writer, ((FloatEncodedValue) encodedValue).getValue());
19
2023-12-16 11:11:16+00:00
16k
123yyh123/xiaofanshu
xfs-modules-server/xfs-user-server/src/main/java/com/yyh/xfs/user/service/impl/UserServiceImpl.java
[ { "identifier": "Result", "path": "xfs-common/common-base/src/main/java/com/yyh/xfs/common/domain/Result.java", "snippet": "@Setter\n@Getter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Result<T> implements Serializable {\n private Integer code;\n private String msg;\n priv...
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.yyh.xfs.common.domain.Result; import com.yyh.xfs.common.myEnum.ExceptionMsgEnum; import com.yyh.xfs.common.redis.constant.RedisConstant; import com.yyh.xfs.common.redis.utils.RedisCache; import com.yyh.xfs.common.redis.utils.RedisKey; import com.yyh.xfs.common.utils.CodeUtil; import com.yyh.xfs.common.utils.Md5Util; import com.yyh.xfs.common.utils.ResultUtil; import com.yyh.xfs.common.utils.TimeUtil; import com.yyh.xfs.common.web.exception.BusinessException; import com.yyh.xfs.common.web.exception.SystemException; import com.yyh.xfs.common.web.properties.JwtProperties; import com.yyh.xfs.common.web.utils.IPUtils; import com.yyh.xfs.common.web.utils.JWTUtil; import com.yyh.xfs.user.domain.UserAttentionDO; import com.yyh.xfs.user.domain.UserDO; import com.yyh.xfs.user.mapper.UserAttentionMapper; import com.yyh.xfs.user.mapper.UserFansMapper; import com.yyh.xfs.user.service.UserService; import com.yyh.xfs.user.mapper.UserMapper; import com.yyh.xfs.user.vo.RegisterInfoVO; import com.yyh.xfs.user.vo.UserTrtcVO; import com.yyh.xfs.user.vo.UserVO; import com.yyh.xfs.user.vo.ViewUserVO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import java.sql.Date; import java.util.HashMap; import java.util.Map; import java.util.Objects;
13,838
package com.yyh.xfs.user.service.impl; /** * @author yyh * @date 2023-12-11 * 用户服务实现 */ @Service @Slf4j public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService { private static final String DEFAULT_NICKNAME_PREFIX = "小番薯用户"; private final JwtProperties jwtProperties; private final RedisCache redisCache; private final HttpServletRequest request; private final UserAttentionMapper userAttentionMapper; private final UserFansMapper userFansMapper; public UserServiceImpl(RedisCache redisCache, JwtProperties jwtProperties, HttpServletRequest request, UserAttentionMapper userAttentionMapper, UserFansMapper userFansMapper) { this.redisCache = redisCache; this.jwtProperties = jwtProperties; this.request = request; this.userAttentionMapper = userAttentionMapper; this.userFansMapper = userFansMapper; } /** * 登录类型和数据库字段的映射 */ private static final Map<Integer, SFunction<UserDO, String>> LOGIN_TYPE_MAP = new HashMap<>(); /** * 初始化 */ @PostConstruct public void postConstruct() { LOGIN_TYPE_MAP.put(1, UserDO::getWxOpenId); LOGIN_TYPE_MAP.put(2, UserDO::getQqOpenId); LOGIN_TYPE_MAP.put(3, UserDO::getFacebookOpenId); } /** * 手机号登录 * * @param phoneNumber 手机号 * @param password 密码 * @return UserDO */ @Override public Result<UserVO> login(String phoneNumber, String password) { QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); // 利用MD5加密密码,并且通过手机号给密码加盐 // String md5Password = Md5Util.getMd5(phoneNumber + password); // TODO 暂时使用死密码,方便测试 String md5Password = "@yangyahao5036"; queryWrapper.lambda().eq(UserDO::getPhoneNumber, phoneNumber).eq(UserDO::getPassword, md5Password); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PASSWORD_ERROR); } return generateUserVO(userDO); } /** * 第三方登录验证 * * @param type 登录类型 * @param code 第三方账号的唯一标识 * @return UserDO */ @Override public Result<UserVO> otherLogin(Integer type, String code) { QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(LOGIN_TYPE_MAP.get(type), code); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { return ResultUtil.errorPost("该第三方账号未绑定"); } return generateUserVO(userDO); } /** * 第三方登录并绑定手机号 * * @param registerInfoVO 注册信息 * @return UserDO */ @Override public Result<UserVO> bindPhone(RegisterInfoVO registerInfoVO) { // 检验验证码是否正确 boolean b = checkSmsCode(
package com.yyh.xfs.user.service.impl; /** * @author yyh * @date 2023-12-11 * 用户服务实现 */ @Service @Slf4j public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService { private static final String DEFAULT_NICKNAME_PREFIX = "小番薯用户"; private final JwtProperties jwtProperties; private final RedisCache redisCache; private final HttpServletRequest request; private final UserAttentionMapper userAttentionMapper; private final UserFansMapper userFansMapper; public UserServiceImpl(RedisCache redisCache, JwtProperties jwtProperties, HttpServletRequest request, UserAttentionMapper userAttentionMapper, UserFansMapper userFansMapper) { this.redisCache = redisCache; this.jwtProperties = jwtProperties; this.request = request; this.userAttentionMapper = userAttentionMapper; this.userFansMapper = userFansMapper; } /** * 登录类型和数据库字段的映射 */ private static final Map<Integer, SFunction<UserDO, String>> LOGIN_TYPE_MAP = new HashMap<>(); /** * 初始化 */ @PostConstruct public void postConstruct() { LOGIN_TYPE_MAP.put(1, UserDO::getWxOpenId); LOGIN_TYPE_MAP.put(2, UserDO::getQqOpenId); LOGIN_TYPE_MAP.put(3, UserDO::getFacebookOpenId); } /** * 手机号登录 * * @param phoneNumber 手机号 * @param password 密码 * @return UserDO */ @Override public Result<UserVO> login(String phoneNumber, String password) { QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); // 利用MD5加密密码,并且通过手机号给密码加盐 // String md5Password = Md5Util.getMd5(phoneNumber + password); // TODO 暂时使用死密码,方便测试 String md5Password = "@yangyahao5036"; queryWrapper.lambda().eq(UserDO::getPhoneNumber, phoneNumber).eq(UserDO::getPassword, md5Password); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PASSWORD_ERROR); } return generateUserVO(userDO); } /** * 第三方登录验证 * * @param type 登录类型 * @param code 第三方账号的唯一标识 * @return UserDO */ @Override public Result<UserVO> otherLogin(Integer type, String code) { QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(LOGIN_TYPE_MAP.get(type), code); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { return ResultUtil.errorPost("该第三方账号未绑定"); } return generateUserVO(userDO); } /** * 第三方登录并绑定手机号 * * @param registerInfoVO 注册信息 * @return UserDO */ @Override public Result<UserVO> bindPhone(RegisterInfoVO registerInfoVO) { // 检验验证码是否正确 boolean b = checkSmsCode(
RedisKey.build(RedisConstant.REDIS_KEY_SMS_BIND_PHONE_CODE, registerInfoVO.getPhoneNumber()),
2
2023-12-15 08:13:42+00:00
16k
Blawuken/MicroG-Extended
play-services-core/src/main/java/org/microg/gms/auth/login/LoginActivity.java
[ { "identifier": "AuthConstants", "path": "play-services-basement/src/main/java/org/microg/gms/auth/AuthConstants.java", "snippet": "public class AuthConstants {\n public static final String DEFAULT_ACCOUNT = \"<<default account>>\";\n public static final String SCOPE_GET_ACCOUNT_ID = \"^^_account_...
import android.accounts.Account; import android.accounts.AccountManager; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.webkit.CookieManager; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.StringRes; import androidx.preference.PreferenceManager; import androidx.webkit.WebViewClientCompat; import com.google.android.gms.R; import org.json.JSONArray; import org.microg.gms.auth.AuthConstants; import org.microg.gms.auth.AuthManager; import org.microg.gms.auth.AuthRequest; import org.microg.gms.auth.AuthResponse; import org.microg.gms.checkin.CheckinManager; import org.microg.gms.checkin.LastCheckinInfo; import org.microg.gms.common.HttpFormClient; import org.microg.gms.common.Utils; import org.microg.gms.people.PeopleManager; import org.microg.gms.profile.Build; import org.microg.gms.profile.ProfileManager; import java.io.IOException; import java.security.MessageDigest; import java.util.Locale; import static android.accounts.AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE; import static android.accounts.AccountManager.VISIBILITY_USER_MANAGED_VISIBLE; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.GINGERBREAD_MR1; import static android.os.Build.VERSION_CODES.HONEYCOMB; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static android.telephony.TelephonyManager.SIM_STATE_UNKNOWN; import static android.view.KeyEvent.KEYCODE_BACK; import static android.view.View.INVISIBLE; import static android.view.View.VISIBLE; import static android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT; import static org.microg.gms.auth.AuthPrefs.isAuthVisible; import static org.microg.gms.checkin.CheckinPreferences.isSpoofingEnabled; import static org.microg.gms.checkin.CheckinPreferences.setSpoofingEnabled; import static org.microg.gms.common.Constants.GMS_PACKAGE_NAME; import static org.microg.gms.common.Constants.GMS_VERSION_CODE; import static org.microg.gms.common.Constants.GOOGLE_GMS_PACKAGE_NAME;
11,638
protected void onHuaweiButtonClicked() { super.onHuaweiButtonClicked(); state++; if (state == 1) { PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("pref_hide_launcher_icon", false).apply(); if (!isSpoofingEnabled(this)) { LastCheckinInfo.clear(this); setSpoofingEnabled(this, true); } init(); } else if (state == -1) { setResult(RESULT_CANCELED); finish(); } } private void init() { setTitle(R.string.just_a_sec); setSpoofButtonText(null); setNextButtonText(null); View loading = getLayoutInflater().inflate(R.layout.login_assistant_loading, authContent, false); authContent.removeAllViews(); authContent.addView(loading); setMessage(R.string.auth_connecting); CookieManager.getInstance().setAcceptCookie(true); if (SDK_INT >= LOLLIPOP) { CookieManager.getInstance().removeAllCookies(value -> start()); } else { //noinspection deprecation CookieManager.getInstance().removeAllCookie(); start(); } } private static WebView createWebView(Context context) { WebView webView = new WebView(context); if (SDK_INT < LOLLIPOP) { webView.setVisibility(VISIBLE); } else { webView.setVisibility(INVISIBLE); } webView.setLayoutParams(new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); webView.setBackgroundColor(Color.TRANSPARENT); prepareWebViewSettings(context, webView.getSettings()); return webView; } @SuppressLint("SetJavaScriptEnabled") private static void prepareWebViewSettings(Context context, WebSettings settings) { ProfileManager.ensureInitialized(context); settings.setUserAgentString(Build.INSTANCE.generateWebViewUserAgentString(settings.getUserAgentString()) + MAGIC_USER_AGENT); settings.setJavaScriptEnabled(true); settings.setSupportMultipleWindows(false); settings.setSaveFormData(false); settings.setAllowFileAccess(false); settings.setDatabaseEnabled(false); settings.setNeedInitialFocus(false); settings.setUseWideViewPort(false); settings.setSupportZoom(false); settings.setJavaScriptCanOpenWindowsAutomatically(false); } private void start() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { if (LastCheckinInfo.read(this).getAndroidId() == 0) { new Thread(() -> { Runnable next; next = checkin(false) ? this::loadLoginPage : () -> showError(R.string.auth_general_error_desc); LoginActivity.this.runOnUiThread(next); }).start(); } else { loadLoginPage(); } } else { showError(R.string.no_network_error_desc); } } private void showError(int errorRes) { setTitle(R.string.sorry); findViewById(R.id.progress_bar).setVisibility(View.INVISIBLE); setMessage(errorRes); } private void setMessage(@StringRes int res) { setMessage(getText(res)); } private void setMessage(CharSequence text) { ((TextView) findViewById(R.id.description_text)).setText(text); } private void loadLoginPage() { String tmpl = getIntent().hasExtra(EXTRA_TMPL) ? getIntent().getStringExtra(EXTRA_TMPL) : TMPL_NEW_ACCOUNT; webView.loadUrl(buildUrl(tmpl, Utils.getLocale(this))); } protected void runScript(String js) { runOnUiThread(() -> webView.loadUrl("javascript:" + js)); } private void closeWeb(boolean programmaticAuth) { setMessage(R.string.auth_finalize); runOnUiThread(() -> webView.setVisibility(INVISIBLE)); String cookies = CookieManager.getInstance().getCookie(programmaticAuth ? PROGRAMMATIC_AUTH_URL : EMBEDDED_SETUP_URL); String[] temp = cookies.split(";"); for (String ar1 : temp) { if (ar1.trim().startsWith(COOKIE_OAUTH_TOKEN + "=")) { String[] temp1 = ar1.split("="); retrieveRtToken(temp1[1]); return; } } showError(R.string.auth_general_error_desc); } private void retrieveRtToken(String oAuthToken) {
/* * Copyright (C) 2013-2017 microG Project Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.microg.gms.auth.login; public class LoginActivity extends AssistantActivity { public static final String TMPL_NEW_ACCOUNT = "new_account"; public static final String EXTRA_TMPL = "tmpl"; public static final String EXTRA_EMAIL = "email"; public static final String EXTRA_TOKEN = "masterToken"; public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; private static final String TAG = "GmsAuthLoginBrowser"; private static final String EMBEDDED_SETUP_URL = "https://accounts.google.com/EmbeddedSetup"; private static final String PROGRAMMATIC_AUTH_URL = "https://accounts.google.com/o/oauth2/programmatic_auth"; private static final String GOOGLE_SUITE_URL = "https://accounts.google.com/signin/continue"; private static final String MAGIC_USER_AGENT = " MinuteMaid"; private static final String COOKIE_OAUTH_TOKEN = "oauth_token"; private WebView webView; private String accountType; private AccountManager accountManager; private InputMethodManager inputMethodManager; private ViewGroup authContent; private int state = 0; @SuppressLint("AddJavascriptInterface") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); accountType = AuthConstants.DEFAULT_ACCOUNT_TYPE; accountManager = AccountManager.get(LoginActivity.this); inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); webView = createWebView(this); webView.addJavascriptInterface(new JsBridge(), "mm"); authContent = (ViewGroup) findViewById(R.id.auth_content); ((ViewGroup) findViewById(R.id.auth_root)).addView(webView); webView.setWebViewClient(new WebViewClientCompat() { @Override public void onPageFinished(WebView view, String url) { Log.d(TAG, "pageFinished: " + view.getUrl()); Uri uri = Uri.parse(view.getUrl()); // Begin login. // Only required if client code does not invoke showView() via JSBridge if ("identifier".equals(uri.getFragment()) || uri.getPath().endsWith("/identifier")) runOnUiThread(() -> webView.setVisibility(VISIBLE)); // Normal login. if ("close".equals(uri.getFragment())) closeWeb(false); // Google Suite login. if (url.startsWith(GOOGLE_SUITE_URL)) closeWeb(false); // IDK when this is called. if (url.startsWith(PROGRAMMATIC_AUTH_URL)) closeWeb(true); } }); if (getIntent().hasExtra(EXTRA_TOKEN)) { if (getIntent().hasExtra(EXTRA_EMAIL)) { AccountManager accountManager = AccountManager.get(this); Account account = new Account(getIntent().getStringExtra(EXTRA_EMAIL), accountType); accountManager.addAccountExplicitly(account, getIntent().getStringExtra(EXTRA_TOKEN), null); if (isAuthVisible(this) && SDK_INT >= 26) { accountManager.setAccountVisibility(account, PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE, VISIBILITY_USER_MANAGED_VISIBLE); } retrieveGmsToken(account); } else { retrieveRtToken(getIntent().getStringExtra(EXTRA_TOKEN)); } } else if (android.os.Build.VERSION.SDK_INT < 21) { init(); } else { setMessage(R.string.auth_before_connect); setSpoofButtonText(R.string.brand_spoof_button); setNextButtonText(R.string.auth_sign_in); } } @Override protected void onNextButtonClicked() { super.onNextButtonClicked(); state++; if (state == 1) { if (isSpoofingEnabled(this)) { LastCheckinInfo.clear(this); setSpoofingEnabled(this, false); } init(); } else if (state == -1) { setResult(RESULT_CANCELED); finish(); } } @Override protected void onHuaweiButtonClicked() { super.onHuaweiButtonClicked(); state++; if (state == 1) { PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("pref_hide_launcher_icon", false).apply(); if (!isSpoofingEnabled(this)) { LastCheckinInfo.clear(this); setSpoofingEnabled(this, true); } init(); } else if (state == -1) { setResult(RESULT_CANCELED); finish(); } } private void init() { setTitle(R.string.just_a_sec); setSpoofButtonText(null); setNextButtonText(null); View loading = getLayoutInflater().inflate(R.layout.login_assistant_loading, authContent, false); authContent.removeAllViews(); authContent.addView(loading); setMessage(R.string.auth_connecting); CookieManager.getInstance().setAcceptCookie(true); if (SDK_INT >= LOLLIPOP) { CookieManager.getInstance().removeAllCookies(value -> start()); } else { //noinspection deprecation CookieManager.getInstance().removeAllCookie(); start(); } } private static WebView createWebView(Context context) { WebView webView = new WebView(context); if (SDK_INT < LOLLIPOP) { webView.setVisibility(VISIBLE); } else { webView.setVisibility(INVISIBLE); } webView.setLayoutParams(new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); webView.setBackgroundColor(Color.TRANSPARENT); prepareWebViewSettings(context, webView.getSettings()); return webView; } @SuppressLint("SetJavaScriptEnabled") private static void prepareWebViewSettings(Context context, WebSettings settings) { ProfileManager.ensureInitialized(context); settings.setUserAgentString(Build.INSTANCE.generateWebViewUserAgentString(settings.getUserAgentString()) + MAGIC_USER_AGENT); settings.setJavaScriptEnabled(true); settings.setSupportMultipleWindows(false); settings.setSaveFormData(false); settings.setAllowFileAccess(false); settings.setDatabaseEnabled(false); settings.setNeedInitialFocus(false); settings.setUseWideViewPort(false); settings.setSupportZoom(false); settings.setJavaScriptCanOpenWindowsAutomatically(false); } private void start() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { if (LastCheckinInfo.read(this).getAndroidId() == 0) { new Thread(() -> { Runnable next; next = checkin(false) ? this::loadLoginPage : () -> showError(R.string.auth_general_error_desc); LoginActivity.this.runOnUiThread(next); }).start(); } else { loadLoginPage(); } } else { showError(R.string.no_network_error_desc); } } private void showError(int errorRes) { setTitle(R.string.sorry); findViewById(R.id.progress_bar).setVisibility(View.INVISIBLE); setMessage(errorRes); } private void setMessage(@StringRes int res) { setMessage(getText(res)); } private void setMessage(CharSequence text) { ((TextView) findViewById(R.id.description_text)).setText(text); } private void loadLoginPage() { String tmpl = getIntent().hasExtra(EXTRA_TMPL) ? getIntent().getStringExtra(EXTRA_TMPL) : TMPL_NEW_ACCOUNT; webView.loadUrl(buildUrl(tmpl, Utils.getLocale(this))); } protected void runScript(String js) { runOnUiThread(() -> webView.loadUrl("javascript:" + js)); } private void closeWeb(boolean programmaticAuth) { setMessage(R.string.auth_finalize); runOnUiThread(() -> webView.setVisibility(INVISIBLE)); String cookies = CookieManager.getInstance().getCookie(programmaticAuth ? PROGRAMMATIC_AUTH_URL : EMBEDDED_SETUP_URL); String[] temp = cookies.split(";"); for (String ar1 : temp) { if (ar1.trim().startsWith(COOKIE_OAUTH_TOKEN + "=")) { String[] temp1 = ar1.split("="); retrieveRtToken(temp1[1]); return; } } showError(R.string.auth_general_error_desc); } private void retrieveRtToken(String oAuthToken) {
new AuthRequest().fromContext(this)
2
2023-12-17 16:14:53+00:00
16k
Yolka5/FTC-Imu3
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java
[ { "identifier": "TrajectorySequence", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequence.java", "snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<SequenceSegment> se...
import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.drive.MecanumDrive; import com.acmerobotics.roadrunner.followers.HolonomicPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV;
11,521
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(2, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(1, 0, 0); public static double LATERAL_MULTIPLIER = 1; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private BNO055IMU imu; private VoltageSensor batteryVoltageSensor; public SampleMecanumDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // TODO: adjust the names of the following hardware devices to match your configuration imu = hardwareMap.get(BNO055IMU.class, "imu"); BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.RADIANS; imu.initialize(parameters); // TODO: If the hub containing the IMU you are using is mounted so that the "REV" logo does // not face up, remap the IMU axes so that the z-axis points upward (normal to the floor.) // // | +Z axis // | // | // | // _______|_____________ +Y axis // / |_____________/|__________ // / REV / EXPANSION // // / / HUB // // /_______/_____________// // |_______/_____________|/ // / // / +X axis // // This diagram is derived from the axes in section 3.4 https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bno055-ds000.pdf // and the placement of the dot/orientation from https://docs.revrobotics.com/rev-control-system/control-system-overview/dimensions#imu-location // // For example, if +Y in this diagram faces downwards, you would use AxisDirection.NEG_Y. // BNO055IMUUtil.remapZAxis(imu, AxisDirection.NEG_Y); leftFront = hardwareMap.get(DcMotorEx.class, "leftFront"); rightRear = hardwareMap.get(DcMotorEx.class, "rightRear"); leftRear = hardwareMap.get(DcMotorEx.class, "leftRear"); rightFront = hardwareMap.get(DcMotorEx.class, "rightFront"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); } if (RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (RUN_USING_ENCODER && MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, MOTOR_VELO_PID); } // TODO: reverse any motors using DcMotor.setDirection() leftFront.setDirection(DcMotorSimple.Direction.REVERSE); leftRear.setDirection(DcMotorSimple.Direction.REVERSE); // TODO: if desired, use setLocalizer() to change the localization method // for instance, setLocalizer(new ThreeTrackingWheelLocalizer(...)); // for instance, setLocalizer(new ThreeTrackingWheelLocalizer(...)); trajectorySequenceRunner = new TrajectorySequenceRunner(follower, HEADING_PID); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) { return new TrajectorySequenceBuilder( startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT,
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(2, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(1, 0, 0); public static double LATERAL_MULTIPLIER = 1; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private BNO055IMU imu; private VoltageSensor batteryVoltageSensor; public SampleMecanumDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // TODO: adjust the names of the following hardware devices to match your configuration imu = hardwareMap.get(BNO055IMU.class, "imu"); BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.RADIANS; imu.initialize(parameters); // TODO: If the hub containing the IMU you are using is mounted so that the "REV" logo does // not face up, remap the IMU axes so that the z-axis points upward (normal to the floor.) // // | +Z axis // | // | // | // _______|_____________ +Y axis // / |_____________/|__________ // / REV / EXPANSION // // / / HUB // // /_______/_____________// // |_______/_____________|/ // / // / +X axis // // This diagram is derived from the axes in section 3.4 https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bno055-ds000.pdf // and the placement of the dot/orientation from https://docs.revrobotics.com/rev-control-system/control-system-overview/dimensions#imu-location // // For example, if +Y in this diagram faces downwards, you would use AxisDirection.NEG_Y. // BNO055IMUUtil.remapZAxis(imu, AxisDirection.NEG_Y); leftFront = hardwareMap.get(DcMotorEx.class, "leftFront"); rightRear = hardwareMap.get(DcMotorEx.class, "rightRear"); leftRear = hardwareMap.get(DcMotorEx.class, "leftRear"); rightFront = hardwareMap.get(DcMotorEx.class, "rightFront"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); } if (RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (RUN_USING_ENCODER && MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, MOTOR_VELO_PID); } // TODO: reverse any motors using DcMotor.setDirection() leftFront.setDirection(DcMotorSimple.Direction.REVERSE); leftRear.setDirection(DcMotorSimple.Direction.REVERSE); // TODO: if desired, use setLocalizer() to change the localization method // for instance, setLocalizer(new ThreeTrackingWheelLocalizer(...)); // for instance, setLocalizer(new ThreeTrackingWheelLocalizer(...)); trajectorySequenceRunner = new TrajectorySequenceRunner(follower, HEADING_PID); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) { return new TrajectorySequenceBuilder( startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT,
MAX_ANG_VEL, MAX_ANG_ACCEL
5
2023-12-15 16:57:19+00:00
16k
Frig00/Progetto-Ing-Software
src/main/java/it/unipv/po/aioobe/trenissimo/model/user/Account.java
[ { "identifier": "CryptographyUtils", "path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/CryptographyUtils.java", "snippet": "public class CryptographyUtils {\n\n /**\n * See <a href=\"https://howtodoinjava.com/java/java-security/java-aes-encryption-example/\"></a>\n * Computa la strin...
import it.unipv.po.aioobe.trenissimo.model.CryptographyUtils; import it.unipv.po.aioobe.trenissimo.model.acquisto.Acquisto; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.AccountEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.DatiPersonaliEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.StoricoAcquistiEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.ViaggiPreferitiEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.service.AccountService; import it.unipv.po.aioobe.trenissimo.model.persistence.service.DatiPersonaliService; import it.unipv.po.aioobe.trenissimo.model.persistence.service.StoricoAcquistiService; import it.unipv.po.aioobe.trenissimo.model.persistence.service.ViaggiPreferitiService; import it.unipv.po.aioobe.trenissimo.model.viaggio.Viaggio; import javafx.beans.property.SimpleBooleanProperty; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.sql.Date; import java.time.LocalDate;
12,980
public DatiPersonaliEntity getDatiPersonali() { return this.datiPersonali; } public void setDatiPersonali(String user) { DatiPersonaliService datiPersonaliService = new DatiPersonaliService(); this.datiPersonali = datiPersonaliService.findByUsername(user); } public String getUsername() { return this.account.getUsername(); } public void setUsername(String username) { this.account.setUsername(username); } /** * Metodo che si occupa di prendere una "password" in chiaro come parametro (solitamente derivante da una TextField), * la cripta e la aggiorna sul database. * * @param password * @throws NoSuchPaddingException * @throws UnsupportedEncodingException * @throws IllegalBlockSizeException * @throws NoSuchAlgorithmException * @throws BadPaddingException * @throws InvalidKeyException * @see CryptographyUtils */ public void setPassword(String password) throws NoSuchPaddingException, IOException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException { this.account.setPassword(CryptographyUtils.encryptPassword(password)); AccountService accountService = new AccountService(); accountService.update(this.account); } public String getPuntiFedelta() { return this.account.getPuntiFedelta().toString(); } /** * Metodo che si occupa di prendere tutti i parametri (Dati personali) che gli vengono forniti e li aggiorna nel database. * * @param nome * @param cognome * @param dataNascita * @param mail * @param via * @param civico * @param citta * @param cap * @return "true" se il salvataggio dei dati personali è andato a buon fine. <br> * "false" altrimenti. */ public boolean salvaModificaDati(String nome, String cognome, LocalDate dataNascita, String mail, String via, String civico, String citta, String cap) { try { DatiPersonaliService datiPersonaliService = new DatiPersonaliService(); datiPersonali.setNome(nome); datiPersonali.setCognome(cognome); datiPersonali.setDataNascita(Date.valueOf(dataNascita)); datiPersonali.setMail(mail); datiPersonali.setVia(via); datiPersonali.setCivico(civico); datiPersonali.setCitta(citta); datiPersonali.setCap(Integer.valueOf(cap)); datiPersonaliService.update(datiPersonali); return true; } catch (Exception e) { return false; } } /** * Metodo che si occupa di prendere un Viaggio come parametro, e salvarlo come viaggio preferito all'interno del database. * * @param viaggio * @return "true" se l'aggiunta del viaggio preferito è andata a buon fine. <br> * "false" altrimenti. */ public boolean addViaggioPreferito(Viaggio viaggio) { try { ViaggiPreferitiEntity viaggioPreferito = new ViaggiPreferitiEntity(); ViaggiPreferitiService viaggiPreferitiService = new ViaggiPreferitiService(); viaggioPreferito = viaggioPreferito.toViaggiPreferitiEntity(viaggio); viaggioPreferito.setUsername(account.getUsername()); viaggiPreferitiService.persist(viaggioPreferito); return true; } catch (Exception e) { return false; } } /** * Metodo che si occupa di prendere un ViaggioPreferitoEntity come parametro e di eliminarlo dal database. * * @param viaggio ViaggioPreferitoEntity. * @return "true" se l'eliminazione del viaggio preferito è andata a buon fine. <br> * "false" altrimenti. */ public boolean deleteViaggioPreferito(ViaggiPreferitiEntity viaggio) { try { ViaggiPreferitiService viaggiPreferitiService = new ViaggiPreferitiService(); viaggiPreferitiService.deleteById(viaggio.getViaggioPreferitoId().toString()); return true; } catch (Exception e) { return false; } } /** * Metodo che si occupa di prendere un acquisto come parametro e salvarlo nel database. * * @param acquisto * @return "true" se l'aggiunta dell'acquisto al database, è andata a buon fine. <br> * "false" altrimenti. */ public boolean addAcquistoToStorico(Acquisto acquisto) { try {
package it.unipv.po.aioobe.trenissimo.model.user; /** * Classe singleton che modellizza un account. * * @author ArrayIndexOutOfBoundsException */ public class Account { public static SimpleBooleanProperty loggedInProperty = new SimpleBooleanProperty(false); private static Account instance; private AccountEntity account; private DatiPersonaliEntity datiPersonali; /** * Metodo utilizzato per conoscere lo stato del login. * * @return "true" se l'utente risulta loggato. <br> * "false" altrimenti. */ public static boolean getLoggedIn() { return loggedInProperty.get(); } /** * Metodo per settare lo stato del login * * @param loggedIn */ public static void setLoggedIn(boolean loggedIn) { loggedInProperty.set(loggedIn); } /** * Metodo per ottenere l'istanza di account. * * @return un'istanza di account. */ public static Account getInstance() { if (instance == null) instance = new Account(); return instance; } /** * Metodo utilizzato per verificare che la "password" inserita come parametro, corrisponda a quella presente nel database. * * @param user * @param password * @return "true" se la password dell'user, inserita come parametro, corrisponde a quella nel database. <br> * "false" altrimenti. * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws NoSuchAlgorithmException * @throws BadPaddingException * @throws InvalidKeyException * @throws UnsupportedEncodingException */ public static boolean checkUserPassword(String user, String password) throws NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException, IOException { var accountUser = new AccountService().findByUsername(user); return accountUser != null && CryptographyUtils.encryptPassword(password).equals(accountUser.getPassword()); } /** * Metodo utilizzato per effettuare il login con l'username inserito come parametro. * * @param user * @return Account */ public static Account login(String user) { Account account = Account.getInstance(); account.setAccount(user); account.setDatiPersonali(user); setLoggedIn(true); return account; } /** * Metodo utilizzato per fare la registrazione di un nuovo utente. Tutti i parametri che vengono passati al metodo, vengono salvati nel database. * * @param username * @param password * @param nome * @param cognome * @param dataDiNascita * @param mail * @param via * @param civico * @param citta * @param cap * @return "true" se la registrazione è andata a buon fine. <br> * "false" altrimenti. * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws NoSuchAlgorithmException * @throws BadPaddingException * @throws InvalidKeyException * @throws UnsupportedEncodingException */ public static boolean signUp(String username, String password, String nome, String cognome, LocalDate dataDiNascita, String mail, String via, String civico, String citta, String cap) throws NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException, UnsupportedEncodingException { try { AccountService accountService = new AccountService(); DatiPersonaliService datiPersonaliService = new DatiPersonaliService(); AccountEntity account = new AccountEntity(); DatiPersonaliEntity dati = new DatiPersonaliEntity(); account.setUsername(username); account.setPassword(CryptographyUtils.encryptPassword(password)); account.setPuntiFedelta(0); accountService.persist(account); dati.setUsername(username); dati.setNome(nome); dati.setCognome(cognome); dati.setDataNascita(Date.valueOf(dataDiNascita)); dati.setMail(mail); dati.setVia(via); dati.setCivico(civico); dati.setCitta(citta); dati.setCap(Integer.valueOf(cap)); datiPersonaliService.persist(dati); return true; } catch (Exception e) { return false; } } public AccountEntity getAccount() { return account; } public void setAccount(String accountId) { AccountService accountService = new AccountService(); this.account = accountService.findByUsername(accountId); } public DatiPersonaliEntity getDatiPersonali() { return this.datiPersonali; } public void setDatiPersonali(String user) { DatiPersonaliService datiPersonaliService = new DatiPersonaliService(); this.datiPersonali = datiPersonaliService.findByUsername(user); } public String getUsername() { return this.account.getUsername(); } public void setUsername(String username) { this.account.setUsername(username); } /** * Metodo che si occupa di prendere una "password" in chiaro come parametro (solitamente derivante da una TextField), * la cripta e la aggiorna sul database. * * @param password * @throws NoSuchPaddingException * @throws UnsupportedEncodingException * @throws IllegalBlockSizeException * @throws NoSuchAlgorithmException * @throws BadPaddingException * @throws InvalidKeyException * @see CryptographyUtils */ public void setPassword(String password) throws NoSuchPaddingException, IOException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException { this.account.setPassword(CryptographyUtils.encryptPassword(password)); AccountService accountService = new AccountService(); accountService.update(this.account); } public String getPuntiFedelta() { return this.account.getPuntiFedelta().toString(); } /** * Metodo che si occupa di prendere tutti i parametri (Dati personali) che gli vengono forniti e li aggiorna nel database. * * @param nome * @param cognome * @param dataNascita * @param mail * @param via * @param civico * @param citta * @param cap * @return "true" se il salvataggio dei dati personali è andato a buon fine. <br> * "false" altrimenti. */ public boolean salvaModificaDati(String nome, String cognome, LocalDate dataNascita, String mail, String via, String civico, String citta, String cap) { try { DatiPersonaliService datiPersonaliService = new DatiPersonaliService(); datiPersonali.setNome(nome); datiPersonali.setCognome(cognome); datiPersonali.setDataNascita(Date.valueOf(dataNascita)); datiPersonali.setMail(mail); datiPersonali.setVia(via); datiPersonali.setCivico(civico); datiPersonali.setCitta(citta); datiPersonali.setCap(Integer.valueOf(cap)); datiPersonaliService.update(datiPersonali); return true; } catch (Exception e) { return false; } } /** * Metodo che si occupa di prendere un Viaggio come parametro, e salvarlo come viaggio preferito all'interno del database. * * @param viaggio * @return "true" se l'aggiunta del viaggio preferito è andata a buon fine. <br> * "false" altrimenti. */ public boolean addViaggioPreferito(Viaggio viaggio) { try { ViaggiPreferitiEntity viaggioPreferito = new ViaggiPreferitiEntity(); ViaggiPreferitiService viaggiPreferitiService = new ViaggiPreferitiService(); viaggioPreferito = viaggioPreferito.toViaggiPreferitiEntity(viaggio); viaggioPreferito.setUsername(account.getUsername()); viaggiPreferitiService.persist(viaggioPreferito); return true; } catch (Exception e) { return false; } } /** * Metodo che si occupa di prendere un ViaggioPreferitoEntity come parametro e di eliminarlo dal database. * * @param viaggio ViaggioPreferitoEntity. * @return "true" se l'eliminazione del viaggio preferito è andata a buon fine. <br> * "false" altrimenti. */ public boolean deleteViaggioPreferito(ViaggiPreferitiEntity viaggio) { try { ViaggiPreferitiService viaggiPreferitiService = new ViaggiPreferitiService(); viaggiPreferitiService.deleteById(viaggio.getViaggioPreferitoId().toString()); return true; } catch (Exception e) { return false; } } /** * Metodo che si occupa di prendere un acquisto come parametro e salvarlo nel database. * * @param acquisto * @return "true" se l'aggiunta dell'acquisto al database, è andata a buon fine. <br> * "false" altrimenti. */ public boolean addAcquistoToStorico(Acquisto acquisto) { try {
StoricoAcquistiEntity storicoAcquisti = new StoricoAcquistiEntity();
4
2023-12-21 10:41:11+00:00
16k
pan2013e/ppt4j
framework/src/main/java/ppt4j/Main.java
[ { "identifier": "PatchAnalyzer", "path": "framework/src/main/java/ppt4j/analysis/patch/PatchAnalyzer.java", "snippet": "@Log4j\npublic class PatchAnalyzer {\n\n @Property(\"ppt4j.analysis.patch.presence_threshold\")\n private static double PATCH_PRESENCE_THRESHOLD;\n\n @Property(\"ppt4j.feature...
import ppt4j.analysis.patch.PatchAnalyzer; import ppt4j.database.Vulnerability; import ppt4j.factory.DatabaseFactory; import ppt4j.util.ExecDriver; import ppt4j.util.PropertyUtils; import ppt4j.util.ResourceUtils; import ppt4j.util.StringUtils; import lombok.AllArgsConstructor; import org.apache.commons.cli.*; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays;
11,018
package ppt4j; public final class Main { private static final String VM_OPTIONS = "-javaagent:lib/aspectjweaver-1.9.19.jar " + "-Xss2m -XX:CompilerThreadStackSize=2048 -XX:VMThreadStackSize=2048 " + "--add-opens java.base/java.lang=ALL-UNNAMED " + "--add-opens java.base/java.lang.reflect=ALL-UNNAMED"; private static final Options options = new Options(); private static final HelpFormatter formatter = new HelpFormatter(); private static final String cmdLineSyntax = "java -cp [...] ppt4j.Main "; @AllArgsConstructor public enum Command { ANALYZE("analyze"); public final String name; } private static String cmdLineSyntax() { return cmdLineSyntax + "[<options>] <command> <args>\n" + """ Commands: analyze <db-id> <gt-type> Analyze a binary for a vulnerability in the dataset Options: """; } private static String[] init(String[] args) { options.addOption("config", "config", true, "Set path to a custom *.properties file with ISO-8859-1 encoding"); options.addOption("h", "help", false, "Print help message and exit"); Option configs = Option.builder("X") .hasArgs() .valueSeparator('=') .desc("Add or override existing properties, e.g. -Xppt4j.database.root=~/database") .build(); options.addOption(configs); CommandLineParser parser = new DefaultParser(); try { CommandLine cmd = parser.parse(options, args, true); if (cmd.hasOption("h")) { formatter.printHelp(cmdLineSyntax(), options); System.exit(0); } if (cmd.hasOption("config")) { PropertyUtils.load( new FileInputStream(cmd.getOptionValue("config"))); } else { PropertyUtils.load(ResourceUtils.readProperties()); } PropertyUtils.override(cmd.getOptionProperties("X")); return cmd.getArgs(); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp(cmdLineSyntax(), options); System.exit(1); } catch (IOException e) { e.printStackTrace(); System.exit(1); } return null; } private static void dispatch(String[] args) { if (args.length == 0) { formatter.printHelp(cmdLineSyntax(), options); System.exit(1); } String command = args[0]; String[] commandArgs = Arrays.copyOfRange(args, 1, args.length); Command commandType = StringUtils.matchPrefix(command); //noinspection SwitchStatementWithTooFewBranches switch (commandType) { case ANALYZE -> { int id = Integer.parseInt(commandArgs[0]); Vulnerability vuln = DatabaseFactory.getByDatabaseId(id);
package ppt4j; public final class Main { private static final String VM_OPTIONS = "-javaagent:lib/aspectjweaver-1.9.19.jar " + "-Xss2m -XX:CompilerThreadStackSize=2048 -XX:VMThreadStackSize=2048 " + "--add-opens java.base/java.lang=ALL-UNNAMED " + "--add-opens java.base/java.lang.reflect=ALL-UNNAMED"; private static final Options options = new Options(); private static final HelpFormatter formatter = new HelpFormatter(); private static final String cmdLineSyntax = "java -cp [...] ppt4j.Main "; @AllArgsConstructor public enum Command { ANALYZE("analyze"); public final String name; } private static String cmdLineSyntax() { return cmdLineSyntax + "[<options>] <command> <args>\n" + """ Commands: analyze <db-id> <gt-type> Analyze a binary for a vulnerability in the dataset Options: """; } private static String[] init(String[] args) { options.addOption("config", "config", true, "Set path to a custom *.properties file with ISO-8859-1 encoding"); options.addOption("h", "help", false, "Print help message and exit"); Option configs = Option.builder("X") .hasArgs() .valueSeparator('=') .desc("Add or override existing properties, e.g. -Xppt4j.database.root=~/database") .build(); options.addOption(configs); CommandLineParser parser = new DefaultParser(); try { CommandLine cmd = parser.parse(options, args, true); if (cmd.hasOption("h")) { formatter.printHelp(cmdLineSyntax(), options); System.exit(0); } if (cmd.hasOption("config")) { PropertyUtils.load( new FileInputStream(cmd.getOptionValue("config"))); } else { PropertyUtils.load(ResourceUtils.readProperties()); } PropertyUtils.override(cmd.getOptionProperties("X")); return cmd.getArgs(); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp(cmdLineSyntax(), options); System.exit(1); } catch (IOException e) { e.printStackTrace(); System.exit(1); } return null; } private static void dispatch(String[] args) { if (args.length == 0) { formatter.printHelp(cmdLineSyntax(), options); System.exit(1); } String command = args[0]; String[] commandArgs = Arrays.copyOfRange(args, 1, args.length); Command commandType = StringUtils.matchPrefix(command); //noinspection SwitchStatementWithTooFewBranches switch (commandType) { case ANALYZE -> { int id = Integer.parseInt(commandArgs[0]); Vulnerability vuln = DatabaseFactory.getByDatabaseId(id);
ExecDriver exec = ExecDriver.getInstance();
3
2023-12-14 15:33:50+00:00
16k
f1den/MrCrayfishGunMod
src/main/java/com/mrcrayfish/guns/client/screen/WorkbenchScreen.java
[ { "identifier": "WorkbenchBlockEntity", "path": "src/main/java/com/mrcrayfish/guns/blockentity/WorkbenchBlockEntity.java", "snippet": "public class WorkbenchBlockEntity extends SyncedBlockEntity implements IStorageBlock\n{\n private NonNullList<ItemStack> inventory = NonNullList.withSize(1, ItemStack...
import com.google.common.collect.ImmutableList; import com.mojang.blaze3d.platform.Lighting; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Vector3f; import com.mrcrayfish.guns.blockentity.WorkbenchBlockEntity; import com.mrcrayfish.guns.client.util.RenderUtil; import com.mrcrayfish.guns.common.NetworkGunManager; import com.mrcrayfish.guns.common.container.WorkbenchContainer; import com.mrcrayfish.guns.crafting.WorkbenchIngredient; import com.mrcrayfish.guns.crafting.WorkbenchRecipe; import com.mrcrayfish.guns.crafting.WorkbenchRecipes; import com.mrcrayfish.guns.init.ModItems; import com.mrcrayfish.guns.item.GunItem; import com.mrcrayfish.guns.item.IAmmo; import com.mrcrayfish.guns.item.IColored; import com.mrcrayfish.guns.item.attachment.IAttachment; import com.mrcrayfish.guns.network.PacketHandler; import com.mrcrayfish.guns.network.message.C2SMessageCraft; import com.mrcrayfish.guns.util.InventoryUtil; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.block.model.ItemTransforms; import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.client.resources.sounds.SimpleSoundInstance; import net.minecraft.core.NonNullList; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvents; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.DyeItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraftforge.registries.ForgeRegistries; import org.lwjgl.opengl.GL11; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream;
14,388
package com.mrcrayfish.guns.client.screen; /** * Author: MrCrayfish */ public class WorkbenchScreen extends AbstractContainerScreen<WorkbenchContainer> { private static final ResourceLocation GUI_BASE = new ResourceLocation("cgm:textures/gui/workbench.png"); private static boolean showRemaining = false; private Tab currentTab; private List<Tab> tabs = new ArrayList<>(); private List<MaterialItem> materials; private List<MaterialItem> filteredMaterials; private Inventory playerInventory; private WorkbenchBlockEntity workbench; private Button btnCraft; private CheckBox checkBoxMaterials; private ItemStack displayStack; public WorkbenchScreen(WorkbenchContainer container, Inventory playerInventory, Component title) { super(container, playerInventory, title); this.playerInventory = playerInventory; this.workbench = container.getWorkbench(); this.imageWidth = 275; this.imageHeight = 184; this.materials = new ArrayList<>(); this.createTabs(WorkbenchRecipes.getAll(playerInventory.player.level)); if(!this.tabs.isEmpty()) { this.imageHeight += 28; } }
package com.mrcrayfish.guns.client.screen; /** * Author: MrCrayfish */ public class WorkbenchScreen extends AbstractContainerScreen<WorkbenchContainer> { private static final ResourceLocation GUI_BASE = new ResourceLocation("cgm:textures/gui/workbench.png"); private static boolean showRemaining = false; private Tab currentTab; private List<Tab> tabs = new ArrayList<>(); private List<MaterialItem> materials; private List<MaterialItem> filteredMaterials; private Inventory playerInventory; private WorkbenchBlockEntity workbench; private Button btnCraft; private CheckBox checkBoxMaterials; private ItemStack displayStack; public WorkbenchScreen(WorkbenchContainer container, Inventory playerInventory, Component title) { super(container, playerInventory, title); this.playerInventory = playerInventory; this.workbench = container.getWorkbench(); this.imageWidth = 275; this.imageHeight = 184; this.materials = new ArrayList<>(); this.createTabs(WorkbenchRecipes.getAll(playerInventory.player.level)); if(!this.tabs.isEmpty()) { this.imageHeight += 28; } }
private void createTabs(NonNullList<WorkbenchRecipe> recipes)
5
2023-12-18 15:04:35+00:00
16k
thebatmanfuture/fofa_search
src/main/java/org/fofaviewer/controllers/MainController.java
[ { "identifier": "SaveOptionCallback", "path": "src/main/java/org/fofaviewer/callback/SaveOptionCallback.java", "snippet": "public interface SaveOptionCallback{\n default void setProjectName(String name){}\n default String getProjectName(){\n return null;\n }\n}" }, { "identifier"...
import java.io.BufferedReader; import java.io.File; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.stage.FileChooser; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.HttpsURLConnection; import java.io.BufferedWriter; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import javafx.scene.control.Alert; import javafx.scene.control.Tab; import javafx.scene.control.TableView; import javafx.scene.layout.BorderPane; import javafx.stage.DirectoryChooser; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ProgressBar; import javafx.scene.control.Alert.AlertType; import javafx.scene.layout.Region; import javafx.stage.FileChooser; import javafx.stage.StageStyle; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.*; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.*; import javafx.scene.layout.*; import javafx.scene.text.Font; import org.controlsfx.control.StatusBar; import org.controlsfx.dialog.CommandLinksDialog; import org.controlsfx.dialog.ProgressDialog; import org.fofaviewer.bean.*; import org.fofaviewer.callback.SaveOptionCallback; import org.fofaviewer.controls.*; import org.fofaviewer.main.FofaConfig; import org.fofaviewer.callback.MainControllerCallback; import org.fofaviewer.request.Request; import org.fofaviewer.callback.RequestCallback; import org.fofaviewer.utils.DataUtil; import org.fofaviewer.utils.RequestUtil; import org.controlsfx.control.textfield.TextFields; import org.fofaviewer.utils.ResourceBundleUtil; import java.awt.*; import java.io.*; import java.math.BigInteger; import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import org.fofaviewer.utils.SQLiteUtils; import org.tinylog.Logger;
11,004
package org.fofaviewer.controllers; public class MainController { private Map<String, Object> projectInfo; private AutoHintTextField decoratedField;
package org.fofaviewer.controllers; public class MainController { private Map<String, Object> projectInfo; private AutoHintTextField decoratedField;
private static final RequestUtil helper = RequestUtil.getInstance();
6
2023-10-25 11:13:47+00:00
16k
sgware/sabre
src/edu/uky/cs/nil/sabre/search/Planner.java
[ { "identifier": "Action", "path": "src/edu/uky/cs/nil/sabre/Action.java", "snippet": "public class Action implements Event {\n\t\n\t/** Serial version ID */\n\tprivate static final long serialVersionUID = Settings.VERSION_UID;\n\t\n\t/** Identifies the action's name and arguments */\n\tpublic final Sign...
import java.io.Serializable; import edu.uky.cs.nil.sabre.Action; import edu.uky.cs.nil.sabre.Main; import edu.uky.cs.nil.sabre.Plan; import edu.uky.cs.nil.sabre.Problem; import edu.uky.cs.nil.sabre.Settings; import edu.uky.cs.nil.sabre.util.Worker.Status;
11,600
package edu.uky.cs.nil.sabre.search; /** * A planner is a configurable factory object for producing {@link Search * searches} that solve {@link Problem planning problems} by generating {@link * Plan plans}. A planner assumes that the space of possible solutions can be * represented as a graph such that counting the numbers of nodes visited and * generated by the search is a meaningful way to measure the amount of work * done by the planner. Different planning approaches may vary in what they * define as a node and how much work is required to visit or generate a node. * * @param <A> the type of {@link Action action} used in solution plans this * planner's {@link Search searches} produce * @author Stephen G. Ware */ public abstract class Planner<A extends Action> implements Serializable { /** The constant used to represent no limit on a number of nodes */ public static final long UNLIMITED_NODES = 0; /** The constant used to represent no limit on an amount of time */ public static final long UNLIMITED_TIME = 0; /** * The constant used to represent no limit on the {@link * Search#authorTemporalLimit author} and {@link * Search#characterTemporalLimit character temporal depths} and the {@link * Search#epistemicLimit epistemic depth} or a search */ public static final int UNLIMITED_DEPTH = -1; /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** The name of the planner */ public final String name; /** The {@link Search#searchLimit limit on nodes visited} */ private long searchLimit = UNLIMITED_NODES; /** The {@link Search#spaceLimit limit on nodes generated} */ private long spaceLimit = UNLIMITED_NODES; /** The {@link Search#timeLimit limit on time spent} */ private long timeLimit = UNLIMITED_TIME; /** * The {@link Search#authorTemporalLimit limit on number of actions in the * author's plan} */ private int authorTemporalLimit = UNLIMITED_DEPTH; /** * The {@link Search#characterTemporalLimit limit on number of actions in a * character's plan} */ private int characterTemporalLimit = UNLIMITED_DEPTH; /** * The {@link Search#epistemicLimit limit on how deeply theory of mind can * be searched} */ private int epistemicLimit = UNLIMITED_DEPTH; /** * Constructs a new planner with the given name. * * @param name the name of the planner */ public Planner(String name) { this.name = name; } @Override public String toString() { return "[" + toString(name) + "]"; } /** * Returns a string composed of a name and a description of the planner's * settings, primary for use in {@link #toString()}. * * @param name the name of the planner * @return a string of the name and planner's settings */ protected String toString(String name) { String string = name + ": "; string += Main.SEARCH_LIMIT_KEY.substring(1) + "=" + getSearchLimit(); string += "; sl=" + getSpaceLimit(); string += "; tl=" + getTimeLimit(); string += "; atl=" + getAuthorTemporalLimit(); string += "; ctl=" + getCharacterTemporalLimit(); string += "; el=" + getEpistemicLimit(); return string; } /** * Returns the maximum number of nodes that a {@link Search search} may * visit when {@link Search#get(Status) searching for a solution}. Visiting * a node generally means considering it and expanding its children nodes, * if any. The constant {@link #UNLIMITED_NODES} indicates no limit on how * many nodes may be visited. * * @return the max number of nodes to visit */ public long getSearchLimit() { return searchLimit; } /** * Sets the maximum number of nodes that a {@link Search search} may visit * when {@link Search#get(Status) searching for a solution}. Visiting a * node generally means considering it and expanding its children nodes, if * any. The constant {@link #UNLIMITED_NODES} may be used to impose no * limit on how many nodes may be visited. * * @param limit the new max number of nodes to visit */ public void setSearchLimit(long limit) { this.searchLimit = Math.max(limit, UNLIMITED_NODES); } /** * Returns the maximum number of nodes that a {@link Search search} may * generate while {@link Search#get(Status) searching for a solution}. The * number of generated nodes counts all nodes ever created during the * search for any purpose, regardless of whether they were ever visited. * The constant {@link #UNLIMITED_NODES} indicates no limit on how many * nodes may be generated. * * @return the max number of nodes to generate */ public long getSpaceLimit() { return spaceLimit; } /** * Sets the maximum number of nodes that a {@link Search search} may * generate while {@link Search#get(Status) searching for a solution}. The * number of generated nodes counts all nodes ever created during the * search for any purpose, regardless of whether they were ever visited. * The constant {@link #UNLIMITED_NODES} may be used to impose no limit on * how many nodes may be generated. * * @param limit the new max number of nodes to generate */ public void setSpaceLimit(long limit) { this.spaceLimit = Math.max(limit, UNLIMITED_NODES); } /** * Returns the maximum number of milliseconds which may elapse while {@link * Search#get(Status) searching for a solution}. The constant {@link * #UNLIMITED_TIME} indicates no limit on the amount of time that may be * taken. * * @return the max number of milliseconds to search */ public long getTimeLimit() { return timeLimit; } /** * Sets the maximum number of milliseconds which may elapse while {@link * Search#get(Status) searching for a solution}. The constant {@link * #UNLIMITED_TIME} may be used to impose no limit on the amount of time * that may be taken. * * @param limit the new max number of milliseconds to search */ public void setTimeLimit(long limit) { this.timeLimit = Math.max(limit, UNLIMITED_TIME); } /** * Returns the {@link Search#authorTemporalLimit author temporal limit} for * any {@link Search searches} created by this planner. The constant {@link * #UNLIMITED_DEPTH} represents no limit. * * @return the author temporal limit, or {@link #UNLIMITED_DEPTH} if there * is no limit */ public int getAuthorTemporalLimit() { return authorTemporalLimit; } /** * Sets the {@link Search#authorTemporalLimit author temporal limit} for any * {@link Search searches} created by this planner. The constant {@link * #UNLIMITED_DEPTH} represents no limit. * * @param limit the author temporal limit, or {@link #UNLIMITED_DEPTH} if * there should be no limit */ public void setAuthorTemporalLimit(int limit) { this.authorTemporalLimit = limit; } /** * Returns the {@link Search#characterTemporalLimit character temporal * limit} for any {@link Search searches} created by this planner. The * constant {@link #UNLIMITED_DEPTH} represents no limit. * * @return the character temporal limit, or {@link #UNLIMITED_DEPTH} if * there is no limit */ public int getCharacterTemporalLimit() { return characterTemporalLimit; } /** * Sets the {@link Search#characterTemporalLimit character temporal limit} * for any {@link Search searches} created by this planner. The constant * {@link #UNLIMITED_DEPTH} represents no limit. * * @param limit the character temporal limit, or {@link #UNLIMITED_DEPTH} if * there should be no limit */ public void setCharacterTemporalLimit(int limit) { this.characterTemporalLimit = limit; } /** * Returns the {@link Search#epistemicLimit epistemic limit} for any {@link * Search searches} created by this planner. The constant {@link * #UNLIMITED_DEPTH} represents no limit. * * @return the epistemic limit, or {@link #UNLIMITED_DEPTH} if there is no * limit */ public int getEpistemicLimit() { return epistemicLimit; } /** * Sets the {@link Search#epistemicLimit epistemic limit} for any {@link * Search searches} created by this planner. The constant {@link * #UNLIMITED_DEPTH} represents no limit. * * @param limit the epistemic limit, or {@link #UNLIMITED_DEPTH} if there * should be no limit */ public void setEpistemicLimit(int limit) { this.epistemicLimit = limit; } /** * Pre-processes a {@link Problem problem} in preparation for {@link * #getSearch(Problem, Status) creating a search} to solve that problem. * <p> * By default, this method returns the problem with no modifications. * * @param problem the problem to pre-process * @param status a status to update during the pre-processing * @return the pre-processed problem, or the original problem is not * pre-processing needs to be done */
package edu.uky.cs.nil.sabre.search; /** * A planner is a configurable factory object for producing {@link Search * searches} that solve {@link Problem planning problems} by generating {@link * Plan plans}. A planner assumes that the space of possible solutions can be * represented as a graph such that counting the numbers of nodes visited and * generated by the search is a meaningful way to measure the amount of work * done by the planner. Different planning approaches may vary in what they * define as a node and how much work is required to visit or generate a node. * * @param <A> the type of {@link Action action} used in solution plans this * planner's {@link Search searches} produce * @author Stephen G. Ware */ public abstract class Planner<A extends Action> implements Serializable { /** The constant used to represent no limit on a number of nodes */ public static final long UNLIMITED_NODES = 0; /** The constant used to represent no limit on an amount of time */ public static final long UNLIMITED_TIME = 0; /** * The constant used to represent no limit on the {@link * Search#authorTemporalLimit author} and {@link * Search#characterTemporalLimit character temporal depths} and the {@link * Search#epistemicLimit epistemic depth} or a search */ public static final int UNLIMITED_DEPTH = -1; /** Serial version ID */ private static final long serialVersionUID = Settings.VERSION_UID; /** The name of the planner */ public final String name; /** The {@link Search#searchLimit limit on nodes visited} */ private long searchLimit = UNLIMITED_NODES; /** The {@link Search#spaceLimit limit on nodes generated} */ private long spaceLimit = UNLIMITED_NODES; /** The {@link Search#timeLimit limit on time spent} */ private long timeLimit = UNLIMITED_TIME; /** * The {@link Search#authorTemporalLimit limit on number of actions in the * author's plan} */ private int authorTemporalLimit = UNLIMITED_DEPTH; /** * The {@link Search#characterTemporalLimit limit on number of actions in a * character's plan} */ private int characterTemporalLimit = UNLIMITED_DEPTH; /** * The {@link Search#epistemicLimit limit on how deeply theory of mind can * be searched} */ private int epistemicLimit = UNLIMITED_DEPTH; /** * Constructs a new planner with the given name. * * @param name the name of the planner */ public Planner(String name) { this.name = name; } @Override public String toString() { return "[" + toString(name) + "]"; } /** * Returns a string composed of a name and a description of the planner's * settings, primary for use in {@link #toString()}. * * @param name the name of the planner * @return a string of the name and planner's settings */ protected String toString(String name) { String string = name + ": "; string += Main.SEARCH_LIMIT_KEY.substring(1) + "=" + getSearchLimit(); string += "; sl=" + getSpaceLimit(); string += "; tl=" + getTimeLimit(); string += "; atl=" + getAuthorTemporalLimit(); string += "; ctl=" + getCharacterTemporalLimit(); string += "; el=" + getEpistemicLimit(); return string; } /** * Returns the maximum number of nodes that a {@link Search search} may * visit when {@link Search#get(Status) searching for a solution}. Visiting * a node generally means considering it and expanding its children nodes, * if any. The constant {@link #UNLIMITED_NODES} indicates no limit on how * many nodes may be visited. * * @return the max number of nodes to visit */ public long getSearchLimit() { return searchLimit; } /** * Sets the maximum number of nodes that a {@link Search search} may visit * when {@link Search#get(Status) searching for a solution}. Visiting a * node generally means considering it and expanding its children nodes, if * any. The constant {@link #UNLIMITED_NODES} may be used to impose no * limit on how many nodes may be visited. * * @param limit the new max number of nodes to visit */ public void setSearchLimit(long limit) { this.searchLimit = Math.max(limit, UNLIMITED_NODES); } /** * Returns the maximum number of nodes that a {@link Search search} may * generate while {@link Search#get(Status) searching for a solution}. The * number of generated nodes counts all nodes ever created during the * search for any purpose, regardless of whether they were ever visited. * The constant {@link #UNLIMITED_NODES} indicates no limit on how many * nodes may be generated. * * @return the max number of nodes to generate */ public long getSpaceLimit() { return spaceLimit; } /** * Sets the maximum number of nodes that a {@link Search search} may * generate while {@link Search#get(Status) searching for a solution}. The * number of generated nodes counts all nodes ever created during the * search for any purpose, regardless of whether they were ever visited. * The constant {@link #UNLIMITED_NODES} may be used to impose no limit on * how many nodes may be generated. * * @param limit the new max number of nodes to generate */ public void setSpaceLimit(long limit) { this.spaceLimit = Math.max(limit, UNLIMITED_NODES); } /** * Returns the maximum number of milliseconds which may elapse while {@link * Search#get(Status) searching for a solution}. The constant {@link * #UNLIMITED_TIME} indicates no limit on the amount of time that may be * taken. * * @return the max number of milliseconds to search */ public long getTimeLimit() { return timeLimit; } /** * Sets the maximum number of milliseconds which may elapse while {@link * Search#get(Status) searching for a solution}. The constant {@link * #UNLIMITED_TIME} may be used to impose no limit on the amount of time * that may be taken. * * @param limit the new max number of milliseconds to search */ public void setTimeLimit(long limit) { this.timeLimit = Math.max(limit, UNLIMITED_TIME); } /** * Returns the {@link Search#authorTemporalLimit author temporal limit} for * any {@link Search searches} created by this planner. The constant {@link * #UNLIMITED_DEPTH} represents no limit. * * @return the author temporal limit, or {@link #UNLIMITED_DEPTH} if there * is no limit */ public int getAuthorTemporalLimit() { return authorTemporalLimit; } /** * Sets the {@link Search#authorTemporalLimit author temporal limit} for any * {@link Search searches} created by this planner. The constant {@link * #UNLIMITED_DEPTH} represents no limit. * * @param limit the author temporal limit, or {@link #UNLIMITED_DEPTH} if * there should be no limit */ public void setAuthorTemporalLimit(int limit) { this.authorTemporalLimit = limit; } /** * Returns the {@link Search#characterTemporalLimit character temporal * limit} for any {@link Search searches} created by this planner. The * constant {@link #UNLIMITED_DEPTH} represents no limit. * * @return the character temporal limit, or {@link #UNLIMITED_DEPTH} if * there is no limit */ public int getCharacterTemporalLimit() { return characterTemporalLimit; } /** * Sets the {@link Search#characterTemporalLimit character temporal limit} * for any {@link Search searches} created by this planner. The constant * {@link #UNLIMITED_DEPTH} represents no limit. * * @param limit the character temporal limit, or {@link #UNLIMITED_DEPTH} if * there should be no limit */ public void setCharacterTemporalLimit(int limit) { this.characterTemporalLimit = limit; } /** * Returns the {@link Search#epistemicLimit epistemic limit} for any {@link * Search searches} created by this planner. The constant {@link * #UNLIMITED_DEPTH} represents no limit. * * @return the epistemic limit, or {@link #UNLIMITED_DEPTH} if there is no * limit */ public int getEpistemicLimit() { return epistemicLimit; } /** * Sets the {@link Search#epistemicLimit epistemic limit} for any {@link * Search searches} created by this planner. The constant {@link * #UNLIMITED_DEPTH} represents no limit. * * @param limit the epistemic limit, or {@link #UNLIMITED_DEPTH} if there * should be no limit */ public void setEpistemicLimit(int limit) { this.epistemicLimit = limit; } /** * Pre-processes a {@link Problem problem} in preparation for {@link * #getSearch(Problem, Status) creating a search} to solve that problem. * <p> * By default, this method returns the problem with no modifications. * * @param problem the problem to pre-process * @param status a status to update during the pre-processing * @return the pre-processed problem, or the original problem is not * pre-processing needs to be done */
public Problem compile(Problem problem, Status status) {
3
2023-10-26 18:14:19+00:00
16k
granny/Pl3xMap
core/src/main/java/net/pl3x/map/core/renderer/VanillaRenderer.java
[ { "identifier": "Pl3xMap", "path": "core/src/main/java/net/pl3x/map/core/Pl3xMap.java", "snippet": "public abstract class Pl3xMap {\n public static @NotNull Pl3xMap api() {\n return Provider.api();\n }\n\n private final boolean isBukkit;\n\n private final Attributes manifestAttributes...
import net.pl3x.map.core.world.Region; import org.jetbrains.annotations.NotNull; import net.pl3x.map.core.Pl3xMap; import net.pl3x.map.core.renderer.heightmap.Heightmap; import net.pl3x.map.core.renderer.task.RegionScanTask; import net.pl3x.map.core.util.Colors; import net.pl3x.map.core.world.BlockState; import net.pl3x.map.core.world.Chunk; import net.pl3x.map.core.world.EmptyChunk;
12,100
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.pl3x.map.core.renderer; public class VanillaRenderer extends Renderer { private final Heightmap heightmap; public VanillaRenderer(@NotNull RegionScanTask task, @NotNull Builder builder) { super(task, builder); this.heightmap = Pl3xMap.api().getHeightmapRegistry().get("old_school"); } @Override public @NotNull Heightmap getHeightmap() { return this.heightmap; } @Override public void scanData(@NotNull Region region) { int startX = region.getX() << 9; int startZ = region.getZ() << 9; for (int pixelX = 0; pixelX < 512; pixelX++) { int blockX = startX + pixelX; double lastBlockY = 0.0D; for (int pixelZ = -1; pixelZ < 512; pixelZ++) { int blockZ = startZ + pixelZ; if (!getWorld().visibleBlock(blockX, blockZ)) { continue; } Pl3xMap.api().getRegionProcessor().checkPaused(); Chunk chunk = region.getWorld().getChunk(region, blockX >> 4, blockZ >> 4); if (chunk instanceof EmptyChunk) { continue; } int blockY = chunk.noHeightmap() ? getWorld().getMaxBuildHeight() : chunk.getWorldSurfaceY(blockX, blockZ) + 1; int fluidY = 0;
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.pl3x.map.core.renderer; public class VanillaRenderer extends Renderer { private final Heightmap heightmap; public VanillaRenderer(@NotNull RegionScanTask task, @NotNull Builder builder) { super(task, builder); this.heightmap = Pl3xMap.api().getHeightmapRegistry().get("old_school"); } @Override public @NotNull Heightmap getHeightmap() { return this.heightmap; } @Override public void scanData(@NotNull Region region) { int startX = region.getX() << 9; int startZ = region.getZ() << 9; for (int pixelX = 0; pixelX < 512; pixelX++) { int blockX = startX + pixelX; double lastBlockY = 0.0D; for (int pixelZ = -1; pixelZ < 512; pixelZ++) { int blockZ = startZ + pixelZ; if (!getWorld().visibleBlock(blockX, blockZ)) { continue; } Pl3xMap.api().getRegionProcessor().checkPaused(); Chunk chunk = region.getWorld().getChunk(region, blockX >> 4, blockZ >> 4); if (chunk instanceof EmptyChunk) { continue; } int blockY = chunk.noHeightmap() ? getWorld().getMaxBuildHeight() : chunk.getWorldSurfaceY(blockX, blockZ) + 1; int fluidY = 0;
BlockState blockstate;
4
2023-10-26 01:14:31+00:00
16k
d0ge/sessionless
src/test/java/TornadoTest.java
[ { "identifier": "Attack", "path": "src/main/java/one/d4d/sessionless/itsdangerous/Attack.java", "snippet": "public enum Attack {\n @SerializedName(\"Known\")\n KNOWN(\"Known\"),\n @SerializedName(\"Fast\")\n FAST(\"Fast\"),\n @SerializedName(\"Balanced\")\n Balanced(\"Balanced\"),\n ...
import one.d4d.sessionless.itsdangerous.Attack; import one.d4d.sessionless.itsdangerous.BruteForce; import one.d4d.sessionless.itsdangerous.crypto.TornadoTokenSigner; import one.d4d.sessionless.itsdangerous.model.SignedToken; import one.d4d.sessionless.itsdangerous.model.SignedTokenObjectFinder; import one.d4d.sessionless.itsdangerous.model.TornadoSignedToken; import one.d4d.sessionless.keys.SecretKey; import one.d4d.sessionless.utils.Utils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Optional;
11,153
public class TornadoTest { @Test void TornadoParserTest() { byte[] secret ="secret".getBytes(); String value = "2|1:0|10:1686150202|7:session|4:e30=|5e05eeef41715bc4b109138f00a37bbc580ca7e94ba9a21d5ec062b7aebff557"; Optional<SignedToken> optionalToken = SignedTokenObjectFinder.parseTornadoSignedToken("test", value); if (optionalToken.isPresent()) { TornadoSignedToken token = (TornadoSignedToken) optionalToken.get(); TornadoTokenSigner s = new TornadoTokenSigner(secret, (byte)'|'); token.setSigner(s); Assertions.assertDoesNotThrow( ()-> { s.unsign(value.getBytes()); }); }else { Assertions.fail("Token not found."); } } @Test void BruteForceMultiThreatTornado() { String value = "2|1:0|10:1686150202|7:session|4:e30=|5e05eeef41715bc4b109138f00a37bbc580ca7e94ba9a21d5ec062b7aebff557"; Assertions.assertDoesNotThrow(() -> { Optional<SignedToken> optionalToken = SignedTokenObjectFinder.parseTornadoSignedToken("test", value); if (optionalToken.isPresent()) { TornadoTokenSigner s = new TornadoTokenSigner(); optionalToken.get().setSigner(s); final List<String> secrets = Utils.readResourceForClass("/secrets", this.getClass()); final List<String> salts = Utils.readResourceForClass("/salts", this.getClass()); final List<SecretKey> knownKeys = new ArrayList<>();
public class TornadoTest { @Test void TornadoParserTest() { byte[] secret ="secret".getBytes(); String value = "2|1:0|10:1686150202|7:session|4:e30=|5e05eeef41715bc4b109138f00a37bbc580ca7e94ba9a21d5ec062b7aebff557"; Optional<SignedToken> optionalToken = SignedTokenObjectFinder.parseTornadoSignedToken("test", value); if (optionalToken.isPresent()) { TornadoSignedToken token = (TornadoSignedToken) optionalToken.get(); TornadoTokenSigner s = new TornadoTokenSigner(secret, (byte)'|'); token.setSigner(s); Assertions.assertDoesNotThrow( ()-> { s.unsign(value.getBytes()); }); }else { Assertions.fail("Token not found."); } } @Test void BruteForceMultiThreatTornado() { String value = "2|1:0|10:1686150202|7:session|4:e30=|5e05eeef41715bc4b109138f00a37bbc580ca7e94ba9a21d5ec062b7aebff557"; Assertions.assertDoesNotThrow(() -> { Optional<SignedToken> optionalToken = SignedTokenObjectFinder.parseTornadoSignedToken("test", value); if (optionalToken.isPresent()) { TornadoTokenSigner s = new TornadoTokenSigner(); optionalToken.get().setSigner(s); final List<String> secrets = Utils.readResourceForClass("/secrets", this.getClass()); final List<String> salts = Utils.readResourceForClass("/salts", this.getClass()); final List<SecretKey> knownKeys = new ArrayList<>();
BruteForce bf = new BruteForce(secrets, salts, knownKeys, Attack.FAST, optionalToken.get());
1
2023-10-30 09:12:06+00:00
16k
LEAWIND/Third-Person
common/src/main/java/net/leawind/mc/thirdperson/event/ThirdPersonEvents.java
[ { "identifier": "ThirdPerson", "path": "common/src/main/java/net/leawind/mc/thirdperson/ThirdPerson.java", "snippet": "public class ThirdPerson {\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(ModConstants.MOD_ID);\n\tprivate static final ConfigManager CONFIG_MA...
import com.mojang.blaze3d.Blaze3D; import com.mojang.blaze3d.platform.Window; import dev.architectury.event.EventResult; import dev.architectury.event.events.client.ClientPlayerEvent; import dev.architectury.event.events.client.ClientRawInputEvent; import dev.architectury.event.events.client.ClientTickEvent; import net.leawind.mc.thirdperson.ThirdPerson; import net.leawind.mc.thirdperson.api.ModConstants; import net.leawind.mc.thirdperson.api.cameraoffset.CameraOffsetMode; import net.leawind.mc.thirdperson.api.cameraoffset.CameraOffsetScheme; import net.leawind.mc.thirdperson.core.CameraAgent; import net.leawind.mc.thirdperson.core.ModReferee; import net.leawind.mc.thirdperson.core.PlayerAgent; import net.leawind.mc.thirdperson.impl.config.Config; import net.leawind.mc.util.api.math.vector.Vector2d; import net.leawind.mc.util.math.LMath; import net.minecraft.client.CameraType; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; import net.minecraft.util.Mth; import net.minecraft.world.level.BlockGetter;
11,369
package net.leawind.mc.thirdperson.event; public interface ThirdPersonEvents { static void register () { ClientTickEvent.CLIENT_PRE.register(ThirdPersonEvents::onClientTickPre); ClientPlayerEvent.CLIENT_PLAYER_RESPAWN.register(ThirdPersonEvents::onClientPlayerRespawn); ClientPlayerEvent.CLIENT_PLAYER_JOIN.register(ThirdPersonEvents::onClientPlayerJoin); ClientRawInputEvent.MOUSE_SCROLLED.register(ThirdPersonEvents::onMouseScrolled); } private static void onClientTickPre (Minecraft mc) { if (mc.isPaused()) { return; }
package net.leawind.mc.thirdperson.event; public interface ThirdPersonEvents { static void register () { ClientTickEvent.CLIENT_PRE.register(ThirdPersonEvents::onClientTickPre); ClientPlayerEvent.CLIENT_PLAYER_RESPAWN.register(ThirdPersonEvents::onClientPlayerRespawn); ClientPlayerEvent.CLIENT_PLAYER_JOIN.register(ThirdPersonEvents::onClientPlayerJoin); ClientRawInputEvent.MOUSE_SCROLLED.register(ThirdPersonEvents::onMouseScrolled); } private static void onClientTickPre (Minecraft mc) { if (mc.isPaused()) { return; }
Config config = ThirdPerson.getConfig();
0
2023-10-31 05:52:36+00:00
16k
siam1026/siam-cloud
siam-goods/goods-provider/src/test/java/com/siam/package_goods/GoodsApplicationTest.java
[ { "identifier": "StoneCustomerException", "path": "siam-common/src/main/java/com/siam/package_common/exception/StoneCustomerException.java", "snippet": "public class StoneCustomerException extends RuntimeException{\n // 结果码\n private Integer code = BasicResultCode.ERR;\n\n // 结果码描述\n private...
import com.alibaba.fastjson.JSONObject; import com.google.gson.internal.LinkedTreeMap; import com.siam.package_common.exception.StoneCustomerException; import com.siam.package_common.util.*; import com.siam.package_goods.entity.Menu; import com.siam.package_goods.service.GoodsRawmaterialRelationService; import com.siam.package_goods.service.GoodsService; import com.siam.package_goods.service.MenuService; import com.siam.package_merchant.feign.MerchantFeignApi; import com.siam.package_merchant.feign.ShopFeignApi; import com.siam.package_order.feign.OrderDetailFeignApi; import com.siam.package_order.feign.OrderFeignApi; import com.siam.package_user.entity.Member; import com.siam.package_user.feign.AdminFeignApi; import com.siam.package_user.feign.MemberFeignApi; import com.siam.package_user.model.param.MemberParam; import com.siam.package_weixin_basic.service.WxNotifyService; import com.siam.package_weixin_basic.service.WxPublicPlatformNotifyService; import com.siam.package_weixin_basic.util.WxQrCodeUtils; import com.siam.package_weixin_basic.util.WxdecodeUtils; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.io.IOException; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.text.MessageFormat; import java.util.*; import java.util.stream.Collectors;
14,320
package com.siam.package_goods; @Slf4j @RunWith(SpringRunner.class) @SpringBootTest(classes = GoodsApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @EnableConfigurationProperties public class GoodsApplicationTest { @Autowired private AdminFeignApi adminFeignApi; @Autowired private MemberFeignApi memberFeignApi; @Autowired private OrderFeignApi orderFeignApi; @Autowired private OrderDetailFeignApi orderDetailFeignApi; @Autowired private GoodsRawmaterialRelationService rawmaterialRelationService; @Autowired private GoodsService goodsService; @Autowired
package com.siam.package_goods; @Slf4j @RunWith(SpringRunner.class) @SpringBootTest(classes = GoodsApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @EnableConfigurationProperties public class GoodsApplicationTest { @Autowired private AdminFeignApi adminFeignApi; @Autowired private MemberFeignApi memberFeignApi; @Autowired private OrderFeignApi orderFeignApi; @Autowired private OrderDetailFeignApi orderDetailFeignApi; @Autowired private GoodsRawmaterialRelationService rawmaterialRelationService; @Autowired private GoodsService goodsService; @Autowired
private WxNotifyService wxNotifyService;
13
2023-10-26 10:45:10+00:00
16k
oghenevovwerho/yaa
src/main/java/yaa/semantic/passes/fs2/F2NFun.java
[ { "identifier": "NewFun", "path": "src/main/java/yaa/ast/NewFun.java", "snippet": "public class NewFun extends Stmt {\r\n public MtdIsWhat itIsWhat = MtdIsWhat.stmtMtd;\r\n public YaaToken name;\r\n public List<Parameter> parameters;\r\n public Stmt stmt;\r\n public ObjectType type;\r\n public Lis...
import yaa.ast.NewFun; import yaa.pojos.BoundState; import yaa.pojos.MtdIsWhat; import yaa.pojos.YaaClz; import yaa.pojos.YaaError; import yaa.pojos.*; import static yaa.pojos.GlobalData.*;
13,288
package yaa.semantic.passes.fs2; public class F2NFun { public static void f2NewFunction(NewFun newFun) { //preventFunctionShadowing(newFun); fs2.pushTable(newFun); var newMtd = (YaaFun) fs2.getSymbol(newFun.placeOfUse()); if (newFun.itIsWhat == MtdIsWhat.topMtd) { newMtd.owner = topClzCodeName.get(fs2.path); } else if (newFun.itIsWhat == MtdIsWhat.staticMtd) { newMtd.owner = topClzCodeName.get(fs2.path); } int mtdInputIndex = 0; for (var type$param : newFun.typeParams) { var paramName = type$param.paramName.content;
package yaa.semantic.passes.fs2; public class F2NFun { public static void f2NewFunction(NewFun newFun) { //preventFunctionShadowing(newFun); fs2.pushTable(newFun); var newMtd = (YaaFun) fs2.getSymbol(newFun.placeOfUse()); if (newFun.itIsWhat == MtdIsWhat.topMtd) { newMtd.owner = topClzCodeName.get(fs2.path); } else if (newFun.itIsWhat == MtdIsWhat.staticMtd) { newMtd.owner = topClzCodeName.get(fs2.path); } int mtdInputIndex = 0; for (var type$param : newFun.typeParams) { var paramName = type$param.paramName.content;
var inputtedClz = new YaaClz(paramName);
3
2023-10-26 17:41:13+00:00
16k
quentin452/DangerRPG-Continuation
src/main/java/mixac1/dangerrpg/item/gem/Gem.java
[ { "identifier": "DangerRPG", "path": "src/main/java/mixac1/dangerrpg/DangerRPG.java", "snippet": "@Mod(\n modid = DangerRPG.MODID,\n name = DangerRPG.MODNAME,\n version = DangerRPG.VERSION,\n acceptedMinecraftVersions = DangerRPG.ACCEPTED_VERSION,\n dependencies = \"required-after:Forge\"...
import mixac1.dangerrpg.DangerRPG; import mixac1.dangerrpg.api.item.GemType; import mixac1.dangerrpg.api.item.IRPGItem; import mixac1.dangerrpg.capability.GemAttributes; import mixac1.dangerrpg.capability.ItemAttributes; import mixac1.dangerrpg.capability.data.RPGItemRegister.ItemType; import mixac1.dangerrpg.capability.data.RPGItemRegister.RPGItemData; import mixac1.dangerrpg.init.RPGConfig.ItemConfig; import mixac1.dangerrpg.init.RPGItems; import mixac1.dangerrpg.init.RPGOther.RPGCreativeTabs; import mixac1.dangerrpg.item.IHasBooksInfo; import mixac1.dangerrpg.util.IMultiplier.MultiplierAdd; import mixac1.dangerrpg.util.Utils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
13,717
package mixac1.dangerrpg.item.gem; public abstract class Gem extends Item implements IRPGItem, IHasBooksInfo { protected static final MultiplierAdd LVL_STEP = new MultiplierAdd((float) ItemConfig.d.gemLvlUpStep); /** * If empty, then it can be insert in all RPG items */
package mixac1.dangerrpg.item.gem; public abstract class Gem extends Item implements IRPGItem, IHasBooksInfo { protected static final MultiplierAdd LVL_STEP = new MultiplierAdd((float) ItemConfig.d.gemLvlUpStep); /** * If empty, then it can be insert in all RPG items */
public List<ItemType> itemTypes = new ArrayList<ItemType>();
5
2023-10-31 21:00:14+00:00
16k
simply-kel/AlinLib
src/main/java/ru/kelcuprum/alinlib/gui/screens/AlinaDemoScreen.java
[ { "identifier": "AlinLib", "path": "src/main/java/ru/kelcuprum/alinlib/AlinLib.java", "snippet": "public class AlinLib implements ClientModInitializer {\r\n public static final Logger LOG = LogManager.getLogger(\"AlinaLib\");\r\n public static Config bariumConfig = new Config(\"config/AlibLib/conf...
import net.minecraft.Util; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.AbstractWidget; import net.minecraft.client.gui.screens.*; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import ru.kelcuprum.alinlib.AlinLib; import ru.kelcuprum.alinlib.Colors; import ru.kelcuprum.alinlib.config.Localization; import ru.kelcuprum.alinlib.gui.InterfaceUtils; import ru.kelcuprum.alinlib.gui.components.buttons.ButtonSprite; import ru.kelcuprum.alinlib.gui.components.editbox.EditBoxString; import ru.kelcuprum.alinlib.gui.components.sliders.SliderInteger; import ru.kelcuprum.alinlib.gui.components.sliders.SliderPercent; import ru.kelcuprum.alinlib.gui.components.text.TextBox; import ru.kelcuprum.alinlib.gui.components.buttons.ButtonBoolean; import ru.kelcuprum.alinlib.gui.components.buttons.Button; import ru.kelcuprum.alinlib.gui.components.editbox.EditBoxColor; import ru.kelcuprum.alinlib.gui.components.selector.SelectorStringButton; import ru.kelcuprum.alinlib.gui.toast.AlinaToast; import java.util.ArrayList; import java.util.List;
13,178
package ru.kelcuprum.alinlib.gui.screens; public class AlinaDemoScreen extends Screen { private final Screen parent; private static final ResourceLocation icon = new ResourceLocation("alinlib", "textures/gui/widget/test/well.png"); private static final Component TITLE = Component.literal("AlinLib"); private static final Component CATEGORY = Component.literal("Example page"); private static final Component EDIT_BOX = Component.literal("Edit Box"); private static final Component SECRET_EDIT_BOX = Component.literal("Secret Edit Box"); private static final Component COLOR_EDIT_BOX = Component.literal("Color Edit Box"); private static final Component SLIDER_PERCENT = Component.literal("Slider Percent"); private static final Component SLIDER_INTEGER = Component.literal("Slider Integer"); private static final Component SOMETHING = Component.translatable("alinlib.something"); private static final Component GITHUB = Component.literal("GitHub"); private static final Component EXIT = Component.literal("Exit"); // private int scrolled = 0; // private InterfaceUtils.DesignType type = InterfaceUtils.DesignType.ALINA; // private List<AbstractWidget> widgetList = new ArrayList<AbstractWidget>(); private TextBox titleBox; private EditBoxString stringEditBox; private EditBoxString stringEditBoxSecret; private ButtonBoolean booleanButton; String[] hell = { "Hello", ",", "World", "!", "No...", "Welcome to Hell :)" }; private SelectorStringButton selectorStringButton; private EditBoxColor colorEditBox; private SliderPercent sliderPercent;
package ru.kelcuprum.alinlib.gui.screens; public class AlinaDemoScreen extends Screen { private final Screen parent; private static final ResourceLocation icon = new ResourceLocation("alinlib", "textures/gui/widget/test/well.png"); private static final Component TITLE = Component.literal("AlinLib"); private static final Component CATEGORY = Component.literal("Example page"); private static final Component EDIT_BOX = Component.literal("Edit Box"); private static final Component SECRET_EDIT_BOX = Component.literal("Secret Edit Box"); private static final Component COLOR_EDIT_BOX = Component.literal("Color Edit Box"); private static final Component SLIDER_PERCENT = Component.literal("Slider Percent"); private static final Component SLIDER_INTEGER = Component.literal("Slider Integer"); private static final Component SOMETHING = Component.translatable("alinlib.something"); private static final Component GITHUB = Component.literal("GitHub"); private static final Component EXIT = Component.literal("Exit"); // private int scrolled = 0; // private InterfaceUtils.DesignType type = InterfaceUtils.DesignType.ALINA; // private List<AbstractWidget> widgetList = new ArrayList<AbstractWidget>(); private TextBox titleBox; private EditBoxString stringEditBox; private EditBoxString stringEditBoxSecret; private ButtonBoolean booleanButton; String[] hell = { "Hello", ",", "World", "!", "No...", "Welcome to Hell :)" }; private SelectorStringButton selectorStringButton; private EditBoxColor colorEditBox; private SliderPercent sliderPercent;
private SliderInteger sliderInt;
6
2023-10-29 13:30:26+00:00
16k
LeoK99/swtw45WS21_reupload
src/main/java/com/buschmais/frontend/views/adrVote/ADRVoteView.java
[ { "identifier": "ADR", "path": "backup/java/com/buschmais/adr/ADR.java", "snippet": "@Document\n@Data\npublic final class ADR {\n\n\t@Getter(AccessLevel.PRIVATE)\n\t@Setter(AccessLevel.PRIVATE)\n\t@EqualsExclude\n\t@Id\n\tprivate String id;\n\n\t@Setter(AccessLevel.PRIVATE)\n\t@DBRef\n\tprivate ADRConta...
import com.buschmais.backend.adr.ADR; import com.buschmais.backend.adr.dataAccess.ADRDao; import com.buschmais.backend.adr.status.ADRStatusType; import com.buschmais.backend.adrAccess.dataAccess.ADRAccessDao; import com.buschmais.backend.image.ImageDao; import com.buschmais.backend.notifications.VotingPendingNotification; import com.buschmais.backend.users.User; import com.buschmais.backend.users.dataAccess.UserDao; import com.buschmais.backend.voting.ADRReview; import com.buschmais.backend.voting.UserIsNotInvitedException; import com.buschmais.backend.voting.VoteType; import com.buschmais.frontend.broadcasting.BroadcastListener; import com.buschmais.frontend.broadcasting.Broadcaster; import com.buschmais.frontend.components.*; import com.buschmais.frontend.vars.StringConstantsFrontend; import com.buschmais.frontend.views.adrCreate.ADRRichCreateView; import com.vaadin.collaborationengine.CollaborationMessageInput; import com.vaadin.collaborationengine.CollaborationMessageList; import com.vaadin.collaborationengine.CollaborationMessagePersister; import com.vaadin.collaborationengine.UserInfo; import com.vaadin.flow.component.DetachEvent; import com.vaadin.flow.component.Key; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.component.icon.Icon; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextArea; import com.vaadin.flow.router.*; import com.vaadin.flow.shared.Registration; import lombok.NonNull; import org.springframework.beans.factory.annotation.Autowired; import java.time.LocalDateTime; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger;
11,765
package com.buschmais.frontend.views.adrVote; //@Route(value = "vote", layout = MainLayout.class) @CssImport(value = "./themes/adr-workbench/adrVoting/label.css") @CssImport(value = "./themes/adr-workbench/adrVoting/comment-section.css") @CssImport(value = "./themes/adr-workbench/vaadin-components/buttons.css") @CssImport(value = "./themes/adr-workbench/adrVoting/adr-information.css") @PageTitle("ADR Details") public class ADRVoteView extends HorizontalLayout implements HasUrlParameter<String>, BroadcastListener, BeforeEnterObserver, BeforeLeaveObserver { /* ADR */ private String adrId;
package com.buschmais.frontend.views.adrVote; //@Route(value = "vote", layout = MainLayout.class) @CssImport(value = "./themes/adr-workbench/adrVoting/label.css") @CssImport(value = "./themes/adr-workbench/adrVoting/comment-section.css") @CssImport(value = "./themes/adr-workbench/vaadin-components/buttons.css") @CssImport(value = "./themes/adr-workbench/adrVoting/adr-information.css") @PageTitle("ADR Details") public class ADRVoteView extends HorizontalLayout implements HasUrlParameter<String>, BroadcastListener, BeforeEnterObserver, BeforeLeaveObserver { /* ADR */ private String adrId;
private final ADRDao adrDao;
1
2023-10-25 15:18:06+00:00
16k
Java-Game-Engine-Merger/Libgdx-Processing
framework0004/framework0004-terminal/src/main/java/com/jediterm/terminal/model/JediTerminal.java
[ { "identifier": "Color", "path": "framework0004/framework0004-terminal/src/main/java/com/jediterm/core/Color.java", "snippet": "public final class Color{\n private final int value;\n public Color(int r,int g,int b) {\n this(r,g,b,255);\n }\n public Color(int r,int g,int b,int a) {\n value=((a&...
import com.jediterm.core.Color; import com.jediterm.core.Platform; import com.jediterm.core.TerminalCoordinates; import com.jediterm.core.compatibility.Point; import com.jediterm.core.input.MouseEvent; import com.jediterm.core.input.MouseWheelEvent; import com.jediterm.core.util.TermSize; import com.jediterm.terminal.*; import com.jediterm.terminal.emulator.charset.CharacterSet; import com.jediterm.terminal.emulator.charset.GraphicSet; import com.jediterm.terminal.emulator.charset.GraphicSetState; import com.jediterm.terminal.emulator.mouse.*; import com.jediterm.terminal.model.hyperlinks.LinkResultItem; import com.jediterm.terminal.model.hyperlinks.TextProcessing; import com.jediterm.terminal.util.CharUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.text.Normalizer; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList;
13,528
package com.jediterm.terminal.model; /** * Terminal that reflects obtained commands and text at {@link TerminalDisplay}(handles change * of cursor position, screen size etc) and {@link TerminalTextBuffer}(stores printed text) * * @author traff */ public class JediTerminal implements Terminal,TerminalMouseListener,TerminalCoordinates{ private static final Logger LOG=LoggerFactory.getLogger(JediTerminal.class.getName()); private static final int MIN_COLUMNS=5; private static final int MIN_ROWS=2; private int myScrollRegionTop; private int myScrollRegionBottom; volatile private int myCursorX=0; volatile private int myCursorY=1; private int myTerminalWidth; private int myTerminalHeight; private final TerminalDisplay myDisplay; private final TerminalTextBuffer myTerminalTextBuffer; private final StyleState myStyleState; private StoredCursor myStoredCursor=null; private final EnumSet<TerminalMode> myModes=EnumSet.noneOf(TerminalMode.class); private final TerminalKeyEncoder myTerminalKeyEncoder; private final Stack<String> myWindowTitlesStack=new Stack<>(); private final Tabulator myTabulator; private final GraphicSetState myGraphicSetState; private MouseFormat myMouseFormat=MouseFormat.MOUSE_FORMAT_XTERM; @Nullable private TerminalOutputStream myTerminalOutput=null; private MouseMode myMouseMode=MouseMode.MOUSE_REPORTING_NONE;
package com.jediterm.terminal.model; /** * Terminal that reflects obtained commands and text at {@link TerminalDisplay}(handles change * of cursor position, screen size etc) and {@link TerminalTextBuffer}(stores printed text) * * @author traff */ public class JediTerminal implements Terminal,TerminalMouseListener,TerminalCoordinates{ private static final Logger LOG=LoggerFactory.getLogger(JediTerminal.class.getName()); private static final int MIN_COLUMNS=5; private static final int MIN_ROWS=2; private int myScrollRegionTop; private int myScrollRegionBottom; volatile private int myCursorX=0; volatile private int myCursorY=1; private int myTerminalWidth; private int myTerminalHeight; private final TerminalDisplay myDisplay; private final TerminalTextBuffer myTerminalTextBuffer; private final StyleState myStyleState; private StoredCursor myStoredCursor=null; private final EnumSet<TerminalMode> myModes=EnumSet.noneOf(TerminalMode.class); private final TerminalKeyEncoder myTerminalKeyEncoder; private final Stack<String> myWindowTitlesStack=new Stack<>(); private final Tabulator myTabulator; private final GraphicSetState myGraphicSetState; private MouseFormat myMouseFormat=MouseFormat.MOUSE_FORMAT_XTERM; @Nullable private TerminalOutputStream myTerminalOutput=null; private MouseMode myMouseMode=MouseMode.MOUSE_REPORTING_NONE;
private Point myLastMotionReport=null;
3
2023-10-27 05:47:39+00:00
16k
llllllxy/tinycloud
tinycloud-user/src/main/java/org/tinycloud/user/service/impl/UcUserServiceImpl.java
[ { "identifier": "UcUser", "path": "tinycloud-bean/src/main/java/org/tinycloud/bean/entity/UcUser.java", "snippet": "@TableName(\"t_uc_user\")\n@ApiModel(value = \"UcUser对象\", description = \"系统用户信息表\")\npublic class UcUser implements Serializable {\n private static final long serialVersionUID = 1L;\n...
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.tinycloud.bean.entity.UcUser; import org.tinycloud.bean.param.UcUserPageQuery; import org.tinycloud.bean.vo.UcUserVo; import org.tinycloud.common.consts.GlobalConstant; import org.tinycloud.common.model.PageModel; import org.tinycloud.common.utils.LambdaUtils; import org.tinycloud.common.utils.StringUtils; import org.tinycloud.common.utils.bean.BeanUtils; import org.tinycloud.user.mapper.UcUserMapper; import org.tinycloud.user.service.UcUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.stream.Collectors;
12,071
package org.tinycloud.user.service.impl; @Service public class UcUserServiceImpl implements UcUserService { @Autowired private UcUserMapper ucUserMapper; /** * 根据id查询详情 * @param userId * @return */ @Override public UcUserVo detail(String userId) { UcUser ucUser = this.ucUserMapper.selectOne(Wrappers.<UcUser>lambdaQuery() .eq(UcUser::getUserId, userId) .eq(UcUser::getDelFlag, GlobalConstant.NOT_DELETED)); if (ucUser != null) { return BeanUtils.transformBean(ucUser, UcUserVo.class); } return null; } /** * 第二种动态排序的方法 * @param pageQuery UcUserPageQuery * @return PageModel<UcUserVo> */ @Override public PageModel<UcUserVo> query(UcUserPageQuery pageQuery) { PageModel<UcUserVo> responsePage = new PageModel<>(pageQuery.getPageNo(), pageQuery.getPageSize()); LambdaQueryWrapper<UcUser> wrapper = new LambdaQueryWrapper<>(); boolean isAsc = false; if (GlobalConstant.ASC.equalsIgnoreCase(pageQuery.getSortType())) { isAsc = true; } wrapper.like(StringUtils.isNotEmpty(pageQuery.getUsername()), UcUser::getUsername, pageQuery.getUsername()); wrapper.like(StringUtils.isNotEmpty(pageQuery.getNickname()), UcUser::getNickname, pageQuery.getNickname()); wrapper.orderBy(StringUtils.isNotEmpty(pageQuery.getSortType()) && StringUtils.isNotEmpty(pageQuery.getSortFiled()), isAsc,
package org.tinycloud.user.service.impl; @Service public class UcUserServiceImpl implements UcUserService { @Autowired private UcUserMapper ucUserMapper; /** * 根据id查询详情 * @param userId * @return */ @Override public UcUserVo detail(String userId) { UcUser ucUser = this.ucUserMapper.selectOne(Wrappers.<UcUser>lambdaQuery() .eq(UcUser::getUserId, userId) .eq(UcUser::getDelFlag, GlobalConstant.NOT_DELETED)); if (ucUser != null) { return BeanUtils.transformBean(ucUser, UcUserVo.class); } return null; } /** * 第二种动态排序的方法 * @param pageQuery UcUserPageQuery * @return PageModel<UcUserVo> */ @Override public PageModel<UcUserVo> query(UcUserPageQuery pageQuery) { PageModel<UcUserVo> responsePage = new PageModel<>(pageQuery.getPageNo(), pageQuery.getPageSize()); LambdaQueryWrapper<UcUser> wrapper = new LambdaQueryWrapper<>(); boolean isAsc = false; if (GlobalConstant.ASC.equalsIgnoreCase(pageQuery.getSortType())) { isAsc = true; } wrapper.like(StringUtils.isNotEmpty(pageQuery.getUsername()), UcUser::getUsername, pageQuery.getUsername()); wrapper.like(StringUtils.isNotEmpty(pageQuery.getNickname()), UcUser::getNickname, pageQuery.getNickname()); wrapper.orderBy(StringUtils.isNotEmpty(pageQuery.getSortType()) && StringUtils.isNotEmpty(pageQuery.getSortFiled()), isAsc,
LambdaUtils.getLambdaGetter(UcUser.class, pageQuery.getSortFiled()));
5
2023-10-28 02:05:15+00:00
16k
llllllxy/bluewind-base
src/main/java/com/bluewind/base/common/config/auth/filter/AuthClientAuthenticationFilter.java
[ { "identifier": "Result", "path": "src/main/java/com/bluewind/base/common/base/Result.java", "snippet": "public class Result implements Serializable {\n private static final long serialVersionUID = -1491499610244557029L;\n\n private Integer code;\n\n private String msg;\n\n private Object da...
import com.bluewind.base.common.base.Result; import com.bluewind.base.common.config.auth.constant.AuthConstant; import com.bluewind.base.common.config.auth.util.AuthUtil; import com.bluewind.base.common.consts.HttpStatus; import com.bluewind.base.common.util.redis.RedisUtils; import com.bluewind.base.common.util.spring.SpringContextUtil; import com.bluewind.base.common.util.web.CookieUtils; import com.bluewind.base.common.util.web.ResponseUtil; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.apache.shiro.web.filter.authc.AuthenticationFilter; import org.apache.shiro.web.util.WebUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest;
11,854
package com.bluewind.base.common.config.auth.filter; /** * @author liuxingyu01 * @date 2022-08-26 14:33 * @description 自定义会话过滤器(支持redis会话共享) **/ public class AuthClientAuthenticationFilter extends AuthenticationFilter { private static final Logger logger = LoggerFactory.getLogger(AuthClientAuthenticationFilter.class); private static RedisUtils redisUtils; private static RedisUtils getRedisUtils() { if (redisUtils == null) { Object bean = SpringContextUtil.getBean("redisUtils"); if (bean == null) { logger.error("redisUtils bean is null!"); } redisUtils = (RedisUtils) bean; } return redisUtils; } @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { return this.validateClient(request, response); } @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) { ResponseUtil.sendJson(response, Result.create(HttpStatus.UNAUTHORIZED, "会话已失效,请重新登录")); return false; } /** * 检查登录状态 * * @param request ServletRequest * @return true or false */ private boolean validateClient(ServletRequest request, ServletResponse response) { HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
package com.bluewind.base.common.config.auth.filter; /** * @author liuxingyu01 * @date 2022-08-26 14:33 * @description 自定义会话过滤器(支持redis会话共享) **/ public class AuthClientAuthenticationFilter extends AuthenticationFilter { private static final Logger logger = LoggerFactory.getLogger(AuthClientAuthenticationFilter.class); private static RedisUtils redisUtils; private static RedisUtils getRedisUtils() { if (redisUtils == null) { Object bean = SpringContextUtil.getBean("redisUtils"); if (bean == null) { logger.error("redisUtils bean is null!"); } redisUtils = (RedisUtils) bean; } return redisUtils; } @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { return this.validateClient(request, response); } @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) { ResponseUtil.sendJson(response, Result.create(HttpStatus.UNAUTHORIZED, "会话已失效,请重新登录")); return false; } /** * 检查登录状态 * * @param request ServletRequest * @return true or false */ private boolean validateClient(ServletRequest request, ServletResponse response) { HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
String token = httpServletRequest.getHeader(AuthConstant.BLUEWIND_TOKEN_KEY);
1
2023-10-26 10:02:07+00:00
16k
danielbatres/orthodontic-dentistry-clinical-management
src/com/view/appointmentsView/FacturaData.java
[ { "identifier": "ApplicationContext", "path": "src/com/context/ApplicationContext.java", "snippet": "public class ApplicationContext {\r\n public static SesionUsuario sesionUsuario;\r\n public static LoadingApp loading = new LoadingApp();\r\n public static LoadingApplication loadingApplication ...
import com.context.ApplicationContext; import com.context.ChoosedPalette; import com.helper.FacturaHelper; import com.model.FacturaModel; import com.model.MontosModel; import com.utils.Tools; import java.util.ArrayList; import javax.swing.JTextField; import javax.swing.border.LineBorder;
12,380
jPanel4.add(container12, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 380, 320, 40)); nombre.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 18)); // NOI18N nombre.setText("Nombre del paciente"); jPanel4.add(nombre, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 60, 420, 30)); text.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N text.setText("Consulta"); jPanel4.add(text, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 40, -1, -1)); jPanel2.add(jPanel4, java.awt.BorderLayout.CENTER); add(jPanel2, java.awt.BorderLayout.CENTER); jPanel1.setMinimumSize(new java.awt.Dimension(0, 100)); jPanel1.setOpaque(false); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); container6.setkEndColor(new java.awt.Color(0, 0, 0)); container6.setkStartColor(new java.awt.Color(0, 0, 0)); container6.setOpaque(false); container6.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { container6MouseClicked(evt); } }); jLabel1.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Guardar"); jLabel1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); javax.swing.GroupLayout container6Layout = new javax.swing.GroupLayout(container6); container6.setLayout(container6Layout); container6Layout.setHorizontalGroup( container6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(container6Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE) .addContainerGap()) ); container6Layout.setVerticalGroup( container6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(container6Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE) .addContainerGap()) ); jPanel1.add(container6, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 30, 140, 40)); jPanel3.setOpaque(false); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 140, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 30, Short.MAX_VALUE) ); jPanel1.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 70, 140, 30)); jPanel5.setOpaque(false); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 140, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 30, Short.MAX_VALUE) ); jPanel1.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 70, 140, 30)); container7.setkEndColor(new java.awt.Color(0, 0, 0)); container7.setkFillBackground(false); container7.setkStartColor(new java.awt.Color(0, 0, 0)); container7.setOpaque(false); container7.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { container7MouseClicked(evt); } }); cancelText.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N cancelText.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); cancelText.setText("Cancelar"); cancelText.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); javax.swing.GroupLayout container7Layout = new javax.swing.GroupLayout(container7); container7.setLayout(container7Layout); container7Layout.setHorizontalGroup( container7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(container7Layout.createSequentialGroup() .addContainerGap() .addComponent(cancelText, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE) .addContainerGap()) ); container7Layout.setVerticalGroup( container7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(container7Layout.createSequentialGroup() .addContainerGap() .addComponent(cancelText, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE) .addContainerGap()) ); jPanel1.add(container7, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 30, 140, 40)); add(jPanel1, java.awt.BorderLayout.PAGE_END); }// </editor-fold>//GEN-END:initComponents private void crossMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_crossMouseClicked
package com.view.appointmentsView; /** * * @author Daniel Batres */ public class FacturaData extends FacturaContext { private final ArrayList<JTextField> VALORES_MONTO = new ArrayList<>(4); private final ArrayList<JTextField> ANOTACIONES_MONTO = new ArrayList<>(4); private int id = 0; private String state; private FacturaModel factura; /** * Creates new form FacturaData */ public FacturaData() { initComponents(); styleMyComponentBaby(); } public void setPacientName(String name, int idConsulta) { nombre.setText(name); id = idConsulta; } public void setState(String state) { this.state = state; } public void setValues(FacturaModel factura) { this.factura = factura; textField3.setText(String.valueOf(factura.getSaldo())); textField2.setText(String.valueOf(factura.getTotales())); for (int i = 0; i < 4; i++) { VALORES_MONTO.get(i).setText(String.valueOf(factura.getMontos().get(i).getMonto())); ANOTACIONES_MONTO.get(i).setText(factura.getMontos().get(i).getAnotaciones()); } } public void setStaticValues() { textField3.setText("Ingresar saldo"); textField2.setText("Ingresar total"); for (int i = 0; i < 4; i++) { VALORES_MONTO.get(i).setText("$0.00"); ANOTACIONES_MONTO.get(i).setText("Ingresar anotaciones"); } } @Override public void colorBasics() { setBorder(new LineBorder(ChoosedPalette.getGray())); setBackground(ChoosedPalette.getSecondaryBackground()); Tools.setImageLabel(cross, "src/com/assets/cruz.png", 15, 15, ChoosedPalette.getDarkColor()); } @Override public void addTitlesAndSubtitles() { TITLES_AND_SUBTITLES.add(title2); TITLES_AND_SUBTITLES.add(title3); TITLES_AND_SUBTITLES.add(title4); TITLES_AND_SUBTITLES.add(nombre); } @Override public void addPlainText() { PLAIN_TEXT.add(text); } @Override public void addContainers() { CONTAINERS.add(container1); CONTAINERS.add(container2); CONTAINERS.add(container3); CONTAINERS.add(container4); CONTAINERS.add(container5); CONTAINERS.add(container8); CONTAINERS.add(container9); CONTAINERS.add(container10); CONTAINERS.add(container11); CONTAINERS.add(container12); } @Override public void addTextFields() { TEXTFIELDS.add(textField1); TEXTFIELDS.add(textField2); TEXTFIELDS.add(textField3); TEXTFIELDS.add(textField4); TEXTFIELDS.add(textField5); TEXTFIELDS.add(textField6); TEXTFIELDS.add(textField7); TEXTFIELDS.add(textField8); TEXTFIELDS.add(textField9); TEXTFIELDS.add(textField10); } private void addValoresMonto() { VALORES_MONTO.add(textField4); VALORES_MONTO.add(textField5); VALORES_MONTO.add(textField7); VALORES_MONTO.add(textField9); } private void addAnotacionesMonto() { ANOTACIONES_MONTO.add(textField1); ANOTACIONES_MONTO.add(textField6); ANOTACIONES_MONTO.add(textField8); ANOTACIONES_MONTO.add(textField10); } @Override public void dark() { paintAll(); } @Override public void light() { paintAll(); } @Override public void initStyles() { cross.setSize(50, 50); paintOneContainer(container6, ChoosedPalette.getMidColor()); paintOneContainer(container7, ChoosedPalette.getMidColor()); paintOnePlainText(cancelText, ChoosedPalette.getMidColor()); addValoresMonto(); addAnotacionesMonto(); Tools.addMouseListenerIngresa(TEXTFIELDS); } private FacturaModel devolverDatosCrear() { FacturaModel facturaLocal = new FacturaModel(); facturaLocal.setSaldo(Float.parseFloat(emptyValue(textField3.getText()))); for (int i = 0; i < 4; i++) { facturaLocal.getMontos().add(new MontosModel(Float.parseFloat(emptyValue(VALORES_MONTO.get(i).getText())), emptyString(ANOTACIONES_MONTO.get(i).getText()))); } facturaLocal.setTotales(Float.parseFloat(emptyValue(textField2.getText()))); return facturaLocal; } private FacturaModel devolverDatosActualizar() { factura.setSaldo(Float.parseFloat(emptyValue(textField3.getText()))); ArrayList<MontosModel> montos = new ArrayList<>(); for (int i = 0; i < 4; i++) { MontosModel monto = new MontosModel(); monto.setIdMontos(factura.getMontos().get(i).getIdMontos()); monto.setMonto(Float.parseFloat(emptyValue(VALORES_MONTO.get(i).getText()))); monto.setAnotaciones(emptyString(ANOTACIONES_MONTO.get(i).getText())); montos.add(monto); } factura.setMontos(montos); factura.setTotales(Float.parseFloat(emptyValue(textField2.getText()))); return factura; } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); container3 = new com.k33ptoo.components.KGradientPanel(); textField2 = new javax.swing.JTextField(); title2 = new javax.swing.JLabel(); container1 = new com.k33ptoo.components.KGradientPanel(); textField1 = new javax.swing.JTextField(); title3 = new javax.swing.JLabel(); cross = new javax.swing.JLabel(); title4 = new javax.swing.JLabel(); container2 = new com.k33ptoo.components.KGradientPanel(); textField3 = new javax.swing.JTextField(); container4 = new com.k33ptoo.components.KGradientPanel(); textField4 = new javax.swing.JTextField(); container5 = new com.k33ptoo.components.KGradientPanel(); textField5 = new javax.swing.JTextField(); container8 = new com.k33ptoo.components.KGradientPanel(); textField6 = new javax.swing.JTextField(); container9 = new com.k33ptoo.components.KGradientPanel(); textField7 = new javax.swing.JTextField(); container10 = new com.k33ptoo.components.KGradientPanel(); textField8 = new javax.swing.JTextField(); container11 = new com.k33ptoo.components.KGradientPanel(); textField9 = new javax.swing.JTextField(); container12 = new com.k33ptoo.components.KGradientPanel(); textField10 = new javax.swing.JTextField(); nombre = new javax.swing.JLabel(); text = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); container6 = new com.k33ptoo.components.KGradientPanel(); jLabel1 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); container7 = new com.k33ptoo.components.KGradientPanel(); cancelText = new javax.swing.JLabel(); setBackground(new java.awt.Color(255, 255, 255)); setMaximumSize(new java.awt.Dimension(500, 625)); setMinimumSize(new java.awt.Dimension(500, 625)); setPreferredSize(new java.awt.Dimension(500, 625)); setLayout(new java.awt.BorderLayout()); jPanel2.setOpaque(false); jPanel2.setLayout(new java.awt.BorderLayout()); jPanel4.setOpaque(false); jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); container3.setkEndColor(new java.awt.Color(204, 204, 204)); container3.setkFillBackground(false); container3.setkStartColor(new java.awt.Color(204, 204, 204)); container3.setOpaque(false); textField2.setBackground(new java.awt.Color(255, 255, 255)); textField2.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N textField2.setText("Ingresar total"); textField2.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(0, 0, 0))); textField2.setOpaque(false); textField2.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { textField2KeyTyped(evt); } }); javax.swing.GroupLayout container3Layout = new javax.swing.GroupLayout(container3); container3.setLayout(container3Layout); container3Layout.setHorizontalGroup( container3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, container3Layout.createSequentialGroup() .addContainerGap(14, Short.MAX_VALUE) .addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); container3Layout.setVerticalGroup( container3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textField2, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) ); jPanel4.add(container3, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 470, 420, 40)); title2.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 14)); // NOI18N title2.setText("Montos"); jPanel4.add(title2, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 200, -1, -1)); container1.setkEndColor(new java.awt.Color(204, 204, 204)); container1.setkFillBackground(false); container1.setkStartColor(new java.awt.Color(204, 204, 204)); container1.setOpaque(false); textField1.setBackground(new java.awt.Color(255, 255, 255)); textField1.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N textField1.setText("Ingresar anotaciones"); textField1.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(0, 0, 0))); textField1.setOpaque(false); textField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField1ActionPerformed(evt); } }); javax.swing.GroupLayout container1Layout = new javax.swing.GroupLayout(container1); container1.setLayout(container1Layout); container1Layout.setHorizontalGroup( container1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(container1Layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(textField1, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE) .addContainerGap()) ); container1Layout.setVerticalGroup( container1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textField1, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) ); jPanel4.add(container1, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 230, 320, 40)); title3.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 14)); // NOI18N title3.setText("Total"); jPanel4.add(title3, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 440, -1, -1)); cross.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 12)); // NOI18N cross.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); cross.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { crossMouseClicked(evt); } }); jPanel4.add(cross, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 10, 30, 30)); title4.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 14)); // NOI18N title4.setText("Saldo"); jPanel4.add(title4, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 110, -1, -1)); container2.setkEndColor(new java.awt.Color(204, 204, 204)); container2.setkFillBackground(false); container2.setkStartColor(new java.awt.Color(204, 204, 204)); container2.setOpaque(false); textField3.setBackground(new java.awt.Color(255, 255, 255)); textField3.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N textField3.setText("Ingresar saldo"); textField3.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(0, 0, 0))); textField3.setOpaque(false); textField3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { textField3MouseClicked(evt); } }); textField3.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { textField3KeyTyped(evt); } }); javax.swing.GroupLayout container2Layout = new javax.swing.GroupLayout(container2); container2.setLayout(container2Layout); container2Layout.setHorizontalGroup( container2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, container2Layout.createSequentialGroup() .addContainerGap(14, Short.MAX_VALUE) .addComponent(textField3, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); container2Layout.setVerticalGroup( container2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textField3, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) ); jPanel4.add(container2, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 140, 420, 40)); container4.setkEndColor(new java.awt.Color(204, 204, 204)); container4.setkFillBackground(false); container4.setkStartColor(new java.awt.Color(204, 204, 204)); container4.setOpaque(false); textField4.setBackground(new java.awt.Color(255, 255, 255)); textField4.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N textField4.setText("$0.00"); textField4.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(0, 0, 0))); textField4.setOpaque(false); textField4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { textField4MouseClicked(evt); } }); textField4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField4ActionPerformed(evt); } }); textField4.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { textField4KeyTyped(evt); } }); javax.swing.GroupLayout container4Layout = new javax.swing.GroupLayout(container4); container4.setLayout(container4Layout); container4Layout.setHorizontalGroup( container4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, container4Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField4, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(318, 318, 318)) ); container4Layout.setVerticalGroup( container4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textField4, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) ); jPanel4.add(container4, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 230, 90, 40)); container5.setkEndColor(new java.awt.Color(204, 204, 204)); container5.setkFillBackground(false); container5.setkStartColor(new java.awt.Color(204, 204, 204)); container5.setOpaque(false); textField5.setBackground(new java.awt.Color(255, 255, 255)); textField5.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N textField5.setText("$0.00"); textField5.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(0, 0, 0))); textField5.setOpaque(false); textField5.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { textField5MouseClicked(evt); } }); textField5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField5ActionPerformed(evt); } }); textField5.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { textField5KeyTyped(evt); } }); javax.swing.GroupLayout container5Layout = new javax.swing.GroupLayout(container5); container5.setLayout(container5Layout); container5Layout.setHorizontalGroup( container5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, container5Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField5, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(330, 330, 330)) ); container5Layout.setVerticalGroup( container5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textField5, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) ); jPanel4.add(container5, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 280, 90, 40)); container8.setkEndColor(new java.awt.Color(204, 204, 204)); container8.setkFillBackground(false); container8.setkStartColor(new java.awt.Color(204, 204, 204)); container8.setOpaque(false); textField6.setBackground(new java.awt.Color(255, 255, 255)); textField6.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N textField6.setText("Ingresar anotaciones"); textField6.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(0, 0, 0))); textField6.setOpaque(false); textField6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField6ActionPerformed(evt); } }); javax.swing.GroupLayout container8Layout = new javax.swing.GroupLayout(container8); container8.setLayout(container8Layout); container8Layout.setHorizontalGroup( container8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(container8Layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(textField6, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE) .addContainerGap()) ); container8Layout.setVerticalGroup( container8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textField6, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) ); jPanel4.add(container8, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 280, 320, 40)); container9.setkEndColor(new java.awt.Color(204, 204, 204)); container9.setkFillBackground(false); container9.setkStartColor(new java.awt.Color(204, 204, 204)); container9.setOpaque(false); textField7.setBackground(new java.awt.Color(255, 255, 255)); textField7.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N textField7.setText("$0.00"); textField7.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(0, 0, 0))); textField7.setOpaque(false); textField7.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { textField7MouseClicked(evt); } }); textField7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField7ActionPerformed(evt); } }); textField7.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { textField7KeyTyped(evt); } }); javax.swing.GroupLayout container9Layout = new javax.swing.GroupLayout(container9); container9.setLayout(container9Layout); container9Layout.setHorizontalGroup( container9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, container9Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField7, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(330, 330, 330)) ); container9Layout.setVerticalGroup( container9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textField7, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) ); jPanel4.add(container9, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 330, 90, 40)); container10.setkEndColor(new java.awt.Color(204, 204, 204)); container10.setkFillBackground(false); container10.setkStartColor(new java.awt.Color(204, 204, 204)); container10.setOpaque(false); textField8.setBackground(new java.awt.Color(255, 255, 255)); textField8.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N textField8.setText("Ingresar anotaciones"); textField8.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(0, 0, 0))); textField8.setOpaque(false); textField8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField8ActionPerformed(evt); } }); javax.swing.GroupLayout container10Layout = new javax.swing.GroupLayout(container10); container10.setLayout(container10Layout); container10Layout.setHorizontalGroup( container10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(container10Layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(textField8, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE) .addContainerGap()) ); container10Layout.setVerticalGroup( container10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textField8, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) ); jPanel4.add(container10, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 330, 320, 40)); container11.setkEndColor(new java.awt.Color(204, 204, 204)); container11.setkFillBackground(false); container11.setkStartColor(new java.awt.Color(204, 204, 204)); container11.setOpaque(false); textField9.setBackground(new java.awt.Color(255, 255, 255)); textField9.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N textField9.setText("$0.00"); textField9.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(0, 0, 0))); textField9.setOpaque(false); textField9.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { textField9MouseClicked(evt); } }); textField9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField9ActionPerformed(evt); } }); textField9.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { textField9KeyTyped(evt); } }); javax.swing.GroupLayout container11Layout = new javax.swing.GroupLayout(container11); container11.setLayout(container11Layout); container11Layout.setHorizontalGroup( container11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, container11Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(textField9, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(330, 330, 330)) ); container11Layout.setVerticalGroup( container11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textField9, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) ); jPanel4.add(container11, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 380, 90, 40)); container12.setkEndColor(new java.awt.Color(204, 204, 204)); container12.setkFillBackground(false); container12.setkStartColor(new java.awt.Color(204, 204, 204)); container12.setOpaque(false); textField10.setBackground(new java.awt.Color(255, 255, 255)); textField10.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N textField10.setText("Ingresar anotaciones"); textField10.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 0, 1, 0, new java.awt.Color(0, 0, 0))); textField10.setOpaque(false); textField10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField10ActionPerformed(evt); } }); javax.swing.GroupLayout container12Layout = new javax.swing.GroupLayout(container12); container12.setLayout(container12Layout); container12Layout.setHorizontalGroup( container12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(container12Layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(textField10, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE) .addContainerGap()) ); container12Layout.setVerticalGroup( container12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textField10, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE) ); jPanel4.add(container12, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 380, 320, 40)); nombre.setFont(new java.awt.Font("Microsoft YaHei UI", 1, 18)); // NOI18N nombre.setText("Nombre del paciente"); jPanel4.add(nombre, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 60, 420, 30)); text.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N text.setText("Consulta"); jPanel4.add(text, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 40, -1, -1)); jPanel2.add(jPanel4, java.awt.BorderLayout.CENTER); add(jPanel2, java.awt.BorderLayout.CENTER); jPanel1.setMinimumSize(new java.awt.Dimension(0, 100)); jPanel1.setOpaque(false); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); container6.setkEndColor(new java.awt.Color(0, 0, 0)); container6.setkStartColor(new java.awt.Color(0, 0, 0)); container6.setOpaque(false); container6.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { container6MouseClicked(evt); } }); jLabel1.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Guardar"); jLabel1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); javax.swing.GroupLayout container6Layout = new javax.swing.GroupLayout(container6); container6.setLayout(container6Layout); container6Layout.setHorizontalGroup( container6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(container6Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE) .addContainerGap()) ); container6Layout.setVerticalGroup( container6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(container6Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE) .addContainerGap()) ); jPanel1.add(container6, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 30, 140, 40)); jPanel3.setOpaque(false); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 140, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 30, Short.MAX_VALUE) ); jPanel1.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 70, 140, 30)); jPanel5.setOpaque(false); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 140, Short.MAX_VALUE) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 30, Short.MAX_VALUE) ); jPanel1.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 70, 140, 30)); container7.setkEndColor(new java.awt.Color(0, 0, 0)); container7.setkFillBackground(false); container7.setkStartColor(new java.awt.Color(0, 0, 0)); container7.setOpaque(false); container7.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { container7MouseClicked(evt); } }); cancelText.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 12)); // NOI18N cancelText.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); cancelText.setText("Cancelar"); cancelText.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); javax.swing.GroupLayout container7Layout = new javax.swing.GroupLayout(container7); container7.setLayout(container7Layout); container7Layout.setHorizontalGroup( container7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(container7Layout.createSequentialGroup() .addContainerGap() .addComponent(cancelText, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE) .addContainerGap()) ); container7Layout.setVerticalGroup( container7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(container7Layout.createSequentialGroup() .addContainerGap() .addComponent(cancelText, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE) .addContainerGap()) ); jPanel1.add(container7, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 30, 140, 40)); add(jPanel1, java.awt.BorderLayout.PAGE_END); }// </editor-fold>//GEN-END:initComponents private void crossMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_crossMouseClicked
ApplicationContext.registroFactura.dispose();
0
2023-10-26 19:35:40+00:00
16k
dawex/sigourney
trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2310/serialization/JacksonModuleFactory.java
[ { "identifier": "FormatProvider", "path": "trust-framework/verifiable-credentials-core/src/main/java/com/dawex/sigourney/trustframework/vc/core/jsonld/serialization/FormatProvider.java", "snippet": "public interface FormatProvider {\n\n\t/**\n\t * Returns the format matching the specified format name\n\...
import com.dawex.sigourney.trustframework.vc.core.Proof; import com.dawex.sigourney.trustframework.vc.core.SignedObject; import com.dawex.sigourney.trustframework.vc.core.jsonld.annotation.JsonLdContexts; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.FormatProvider; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.JsonLdContextsSerializer; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.JsonLdSerializer; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.SignedObjectJsonLdSerializer; import com.dawex.sigourney.trustframework.vc.model.shared.Did; import com.dawex.sigourney.trustframework.vc.model.shared.JsonWebKey2020; import com.dawex.sigourney.trustframework.vc.model.v2310.common.Address; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.AggregationOf; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.DataProductCredentialSubject; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.DataProductVerifiableCredential; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.Distribution; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.Location; import com.dawex.sigourney.trustframework.vc.model.v2310.organisation.OrganisationCredentialSubject; import com.dawex.sigourney.trustframework.vc.model.v2310.organisation.OrganisationVerifiableCredential; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.module.SimpleModule; import java.util.function.Supplier;
13,089
package com.dawex.sigourney.trustframework.vc.model.v2310.serialization; public class JacksonModuleFactory { /** * Create a configured Jackson module for serializing organisation verifiable credentials */ public static Module organisationSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) { final SimpleModule module = new SimpleModule(); module.addSerializer(Address.class, new JsonLdSerializer<>(Address.class, formatProvider)); module.addSerializer(OrganisationCredentialSubject.class, new JsonLdSerializer<>(OrganisationCredentialSubject.class, formatProvider)); module.addSerializer(JsonLdContexts.class, new JsonLdContextsSerializer(baseIriSupplier)); module.addSerializer(OrganisationVerifiableCredential.class, new JsonLdSerializer<>(OrganisationVerifiableCredential.class, formatProvider)); module.addSerializer(Proof.class, new JsonLdSerializer<>(Proof.class, formatProvider)); module.addSerializer(SignedObject.class, new SignedObjectJsonLdSerializer(formatProvider)); return module; } /** * Create a configured Jackson module for serializing data product verifiable credentials */ public static Module dataProductSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) { final SimpleModule module = new SimpleModule(); module.addSerializer(AggregationOf.class, new JsonLdSerializer<>(AggregationOf.class, formatProvider));
package com.dawex.sigourney.trustframework.vc.model.v2310.serialization; public class JacksonModuleFactory { /** * Create a configured Jackson module for serializing organisation verifiable credentials */ public static Module organisationSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) { final SimpleModule module = new SimpleModule(); module.addSerializer(Address.class, new JsonLdSerializer<>(Address.class, formatProvider)); module.addSerializer(OrganisationCredentialSubject.class, new JsonLdSerializer<>(OrganisationCredentialSubject.class, formatProvider)); module.addSerializer(JsonLdContexts.class, new JsonLdContextsSerializer(baseIriSupplier)); module.addSerializer(OrganisationVerifiableCredential.class, new JsonLdSerializer<>(OrganisationVerifiableCredential.class, formatProvider)); module.addSerializer(Proof.class, new JsonLdSerializer<>(Proof.class, formatProvider)); module.addSerializer(SignedObject.class, new SignedObjectJsonLdSerializer(formatProvider)); return module; } /** * Create a configured Jackson module for serializing data product verifiable credentials */ public static Module dataProductSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) { final SimpleModule module = new SimpleModule(); module.addSerializer(AggregationOf.class, new JsonLdSerializer<>(AggregationOf.class, formatProvider));
module.addSerializer(DataProductCredentialSubject.class,
8
2023-10-25 16:10:40+00:00
16k
inceptive-tech/ENTSOEDataRetrieval
src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/ENTSOEDataFetcher.java
[ { "identifier": "DataRetrievalRuntimeException", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/exceptions/DataRetrievalRuntimeException.java", "snippet": "public class DataRetrievalRuntimeException extends RuntimeException{\n private static final Logger LOGGER = LogManager.getLogge...
import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import javax.xml.bind.DataBindingException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalRuntimeException; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.Area; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.ColumnType; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.ContractMarketAgreement; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.DocumentType; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.Params; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.ProcessType; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.GLMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.PublicationMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.UnavailabilityMarketDocument;
12,919
if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return Optional.empty(); } if (gap.toMinutes() < 60) { LOGGER.warn("Error, uncorrect duration. Expected at least 60 minutes but it was " + gap.toMinutes() + " minutes"); return Optional.empty(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.SYSTEM_TOTAL_LOAD.getId()); params.put(Params.PROCESS_TYPE.getValue(), ProcessType.REALISED.getId()); params.put(Params.OUT_BIDDINDZONE_DOMAIN.getValue(), outBiddingZoneDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); String msg = "Unable to correctly fetch actual load at " + outBiddingZoneDomain.getPrettyName() + " from " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " to " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME); return performGetOperation(params, msg, GLMarketDocument.class); } public Optional<GLMarketDocument> fetchDayAheadLoadForecast(Area outBiddingZoneDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("6.1.B", periodStart, outBiddingZoneDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return Optional.empty(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return Optional.empty(); } if (gap.toHours() < 24) { LOGGER.warn("Error, uncorrect duration. Expected at least 24 hours but it was " + gap.toMinutes() + " minutes"); return Optional.empty(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.SYSTEM_TOTAL_LOAD.getId()); params.put(Params.PROCESS_TYPE.getValue(), ProcessType.DAY_AHEAD.getId()); params.put(Params.OUT_BIDDINDZONE_DOMAIN.getValue(), outBiddingZoneDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); GLMarketDocument doc = null; String msg = "Unable to correctly fetch day ahead load at " + outBiddingZoneDomain.getPrettyName() + " from " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " to " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME); return performGetOperation(params, msg, GLMarketDocument.class); } public Optional<GLMarketDocument> fetchWeekAheadLoadForecast(Area outBiddingZoneDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("6.1.C", periodStart, outBiddingZoneDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return Optional.empty(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return Optional.empty(); } if (gap.toDays() < 7) { LOGGER.warn("Error, uncorrect duration. Expected at least 7 days but it was " + gap.toMinutes() + " minutes"); return Optional.empty(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.SYSTEM_TOTAL_LOAD.getId()); params.put(Params.PROCESS_TYPE.getValue(), ProcessType.WEEK_AHEAD.getId()); params.put(Params.OUT_BIDDINDZONE_DOMAIN.getValue(), outBiddingZoneDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); String msg = "Unable to correctly fetch week ahead load at " + outBiddingZoneDomain.getPrettyName() + " from " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " to " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME); return performGetOperation(params, msg, GLMarketDocument.class); } public Optional<GLMarketDocument> fetchAggregatedGenerationType(Area inDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("16.1.B&C", periodStart, inDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return Optional.empty(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return Optional.empty(); } if (gap.toDays() < 7) { LOGGER.warn("Error, uncorrect duration. Expected at least 7 days but it was " + gap.toMinutes() + " minutes"); return Optional.empty(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.ACTUAL_GENERATION_PER_TYPE.getId()); params.put(Params.PROCESS_TYPE.getValue(), ProcessType.REALISED.getId()); params.put(Params.IN_DOMAIN.getValue(), inDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); String msg = "Unable to correctly fetch aggregated generation per type on " + inDomain.getPrettyName() + " from " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " to " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME); return performGetOperation(params, msg, GLMarketDocument.class); }
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval.fetcher; /** * The fetcher using https://transparency.entsoe.eu/content/static_content/Static%20content/web%20api/Guide.html * allowing to retrieve data from all the suported API. This class only presents the API of what you can get, and return * the objects or nothing if there was a fetch problem. * * @author Andres Bel Alonso */ public class ENTSOEDataFetcher { private static final Logger LOGGER = LogManager.getLogger(ENTSOEDataFetcher.class); public static String BASE_URL = "https://web-api.tp.entsoe.eu/api"; private String authToken; private HttpBridge bridge; private DisponibilityChecker checker; public ENTSOEDataFetcher(String authToken, boolean useRequestCache) { this.authToken = authToken; this.bridge = new HttpBridge(useRequestCache); // TODO : fix server URL this.checker = new DisponibilityChecker(); } /** * One year limitation applies. Fetchs actual load (documentType : A65, ProcessType : A16) * * @return */ public Optional<GLMarketDocument> fetchActualLoad(Area outBiddingZoneDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("6.1.A", periodStart, outBiddingZoneDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return Optional.empty(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return Optional.empty(); } if (gap.toMinutes() < 60) { LOGGER.warn("Error, uncorrect duration. Expected at least 60 minutes but it was " + gap.toMinutes() + " minutes"); return Optional.empty(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.SYSTEM_TOTAL_LOAD.getId()); params.put(Params.PROCESS_TYPE.getValue(), ProcessType.REALISED.getId()); params.put(Params.OUT_BIDDINDZONE_DOMAIN.getValue(), outBiddingZoneDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); String msg = "Unable to correctly fetch actual load at " + outBiddingZoneDomain.getPrettyName() + " from " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " to " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME); return performGetOperation(params, msg, GLMarketDocument.class); } public Optional<GLMarketDocument> fetchDayAheadLoadForecast(Area outBiddingZoneDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("6.1.B", periodStart, outBiddingZoneDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return Optional.empty(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return Optional.empty(); } if (gap.toHours() < 24) { LOGGER.warn("Error, uncorrect duration. Expected at least 24 hours but it was " + gap.toMinutes() + " minutes"); return Optional.empty(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.SYSTEM_TOTAL_LOAD.getId()); params.put(Params.PROCESS_TYPE.getValue(), ProcessType.DAY_AHEAD.getId()); params.put(Params.OUT_BIDDINDZONE_DOMAIN.getValue(), outBiddingZoneDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); GLMarketDocument doc = null; String msg = "Unable to correctly fetch day ahead load at " + outBiddingZoneDomain.getPrettyName() + " from " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " to " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME); return performGetOperation(params, msg, GLMarketDocument.class); } public Optional<GLMarketDocument> fetchWeekAheadLoadForecast(Area outBiddingZoneDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("6.1.C", periodStart, outBiddingZoneDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return Optional.empty(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return Optional.empty(); } if (gap.toDays() < 7) { LOGGER.warn("Error, uncorrect duration. Expected at least 7 days but it was " + gap.toMinutes() + " minutes"); return Optional.empty(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.SYSTEM_TOTAL_LOAD.getId()); params.put(Params.PROCESS_TYPE.getValue(), ProcessType.WEEK_AHEAD.getId()); params.put(Params.OUT_BIDDINDZONE_DOMAIN.getValue(), outBiddingZoneDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); String msg = "Unable to correctly fetch week ahead load at " + outBiddingZoneDomain.getPrettyName() + " from " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " to " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME); return performGetOperation(params, msg, GLMarketDocument.class); } public Optional<GLMarketDocument> fetchAggregatedGenerationType(Area inDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("16.1.B&C", periodStart, inDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return Optional.empty(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return Optional.empty(); } if (gap.toDays() < 7) { LOGGER.warn("Error, uncorrect duration. Expected at least 7 days but it was " + gap.toMinutes() + " minutes"); return Optional.empty(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.ACTUAL_GENERATION_PER_TYPE.getId()); params.put(Params.PROCESS_TYPE.getValue(), ProcessType.REALISED.getId()); params.put(Params.IN_DOMAIN.getValue(), inDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); String msg = "Unable to correctly fetch aggregated generation per type on " + inDomain.getPrettyName() + " from " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " to " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME); return performGetOperation(params, msg, GLMarketDocument.class); }
public Optional<PublicationMarketDocument> fetchPhysicalFlows(Area inDomain, Area outDomain, LocalDateTime periodStart,
8
2023-10-30 09:09:53+00:00
16k
EricFan2002/SC2002
src/app/entity/RepositoryCollection.java
[ { "identifier": "CampDeserializer", "path": "src/app/controller/deserializer/CampDeserializer.java", "snippet": "public class CampDeserializer {\n\n /**\n * Private constructor to prevent instantiation.\n */\n private CampDeserializer() {\n }\n\n /**\n * Deserializes the provided...
import java.util.ArrayList; import app.controller.deserializer.CampDeserializer; import app.controller.deserializer.EnquiryDeserializer; import app.controller.deserializer.SuggestionDeserializer; import app.controller.deserializer.UserDeserializer; import app.entity.camp.CampList; import app.entity.enquiry.EnquiryList; import app.entity.suggestion.SuggestionList; import app.entity.user.UserList; import app.utils.CSV; import app.consts.Config;
12,590
package app.entity; /** * The {@code RepositoryCollection} class provides a central collection of * repositories for users, camps, enquiries, and suggestions. * It handles loading and saving data to CSV files using deserializers and CSV * utilities. */ public class RepositoryCollection { /** * The repository for user objects. */ private static UserList userRepository; /** * The repository for camp objects. */ private static CampList campRepository; /** * The repository for enquiry objects. */ private static EnquiryList enquiryRepository; /** * The repository for suggestion objects. */ private static SuggestionList suggestionRepository; /** * Private constructor to prevent instantiation. */ private RepositoryCollection() { } /** * Loads data from CSV files into the repositories using deserializers. */ public static void load() { ArrayList<ArrayList<String>> userData = CSV.importFromCSV(Config.USER_REPOSITORY_PATH); ArrayList<ArrayList<String>> campData = CSV.importFromCSV(Config.CAMP_REPOSITORY_PATH); ArrayList<ArrayList<String>> enquiryData = CSV.importFromCSV(Config.ENQUIRY_REPOSITORY_PATH); ArrayList<ArrayList<String>> suggestionData = CSV.importFromCSV(Config.SUGGESTION_REPOSITORY_PATH); userRepository = UserDeserializer.deserialize(userData);
package app.entity; /** * The {@code RepositoryCollection} class provides a central collection of * repositories for users, camps, enquiries, and suggestions. * It handles loading and saving data to CSV files using deserializers and CSV * utilities. */ public class RepositoryCollection { /** * The repository for user objects. */ private static UserList userRepository; /** * The repository for camp objects. */ private static CampList campRepository; /** * The repository for enquiry objects. */ private static EnquiryList enquiryRepository; /** * The repository for suggestion objects. */ private static SuggestionList suggestionRepository; /** * Private constructor to prevent instantiation. */ private RepositoryCollection() { } /** * Loads data from CSV files into the repositories using deserializers. */ public static void load() { ArrayList<ArrayList<String>> userData = CSV.importFromCSV(Config.USER_REPOSITORY_PATH); ArrayList<ArrayList<String>> campData = CSV.importFromCSV(Config.CAMP_REPOSITORY_PATH); ArrayList<ArrayList<String>> enquiryData = CSV.importFromCSV(Config.ENQUIRY_REPOSITORY_PATH); ArrayList<ArrayList<String>> suggestionData = CSV.importFromCSV(Config.SUGGESTION_REPOSITORY_PATH); userRepository = UserDeserializer.deserialize(userData);
campRepository = CampDeserializer.deserialize(campData, userRepository);
0
2023-11-01 05:18:29+00:00
16k
TNO/PPS
plugins/nl.esi.pps.tmsc.edit/src-gen/nl/esi/pps/tmsc/provider/TmscEditPlugin.java
[ { "identifier": "PropertiesEditPlugin", "path": "plugins/nl.esi.emf.properties.edit/src-gen/nl/esi/emf/properties/provider/PropertiesEditPlugin.java", "snippet": "public final class PropertiesEditPlugin extends EMFPlugin {\n\t/**\n\t * Keep track of the singleton.\n\t * <!-- begin-user-doc -->\n\t * <!-...
import java.util.Collection; import java.util.Map; import org.eclipse.emf.common.EMFPlugin; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.util.ResourceLocator; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.edit.provider.ComposedAdapterFactory; import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory; import org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory; import org.osgi.framework.BundleContext; import nl.esi.emf.properties.provider.PropertiesEditPlugin; import nl.esi.emf.properties.provider.PropertiesItemProviderAdapterFactory; import nl.esi.pps.architecture.deployed.provider.DeployedItemProviderAdapterFactory; import nl.esi.pps.architecture.implemented.provider.ImplementedItemProviderAdapterFactory; import nl.esi.pps.architecture.instantiated.provider.InstantiatedItemProviderAdapterFactory; import nl.esi.pps.architecture.provider.ArchitectureEditPlugin; import nl.esi.pps.architecture.provider.ArchitectureItemProviderAdapterFactory; import nl.esi.pps.architecture.specified.provider.SpecifiedItemProviderAdapterFactory; import nl.esi.pps.common.emf.common.PngEclipsePlugin; import nl.esi.pps.tmsc.provider.dataanalysis.IDataAnalysisItemContentProvider; import nl.esi.pps.tmsc.provider.dataanalysis.internal.DataAnalysisItemContentProviderRegistryReader;
13,169
/** */ package nl.esi.pps.tmsc.provider; /** * This is the central singleton for the Tmsc edit plugin. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public final class TmscEditPlugin extends EMFPlugin { /** * Keep track of the singleton. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final TmscEditPlugin INSTANCE = new TmscEditPlugin(); /** * Keep track of the singleton. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static Implementation plugin; /** * Create the instance. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TmscEditPlugin() { super(new ResourceLocator[] { ArchitectureEditPlugin.INSTANCE, PropertiesEditPlugin.INSTANCE, }); } /** * Returns the singleton instance of the Eclipse plugin. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the singleton instance. * @generated */ @Override public ResourceLocator getPluginResourceLocator() { return plugin; } /** * Returns the singleton instance of the Eclipse plugin. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the singleton instance. * @generated */ public static Implementation getPlugin() { return plugin; } /** * Creates a {@link ResourceSet} with edit support. * * @see #createItemProviderAdapterFactory() * @see ResourceSet#getAdapterFactories() */ public static ResourceSet createResourceSet() { ResourceSetImpl resourceSet = new ResourceSetImpl(); resourceSet.getAdapterFactories().add(createItemProviderAdapterFactory()); return resourceSet; } /** * Creates a {@link ComposedAdapterFactory} for all dependent languages, incl. reflective support. */ public static ComposedAdapterFactory createItemProviderAdapterFactory() { ComposedAdapterFactory adapterFactory = new ComposedAdapterFactory( ComposedAdapterFactory.Descriptor.Registry.INSTANCE) { // Avoiding multi-threading issues by making this method synchronized @Override public synchronized AdapterFactory getFactoryForTypes(Collection<?> types) { return super.getFactoryForTypes(types); } }; adapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new TmscItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new ArchitectureItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new SpecifiedItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new ImplementedItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new DeployedItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new InstantiatedItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new PropertiesItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory()); return adapterFactory; } /** * The actual implementation of the Eclipse <b>Plugin</b>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public static class Implementation extends PngEclipsePlugin { private DataAnalysisItemContentProviderRegistryReader dataAnalysisRegistryReader = null; /** * Creates an instance. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Implementation() { super(); // Remember the static instance. // plugin = this; } @Override public void start(BundleContext context) throws Exception { super.start(context); } @Override public void stop(BundleContext context) throws Exception { super.stop(context); if (dataAnalysisRegistryReader != null) { dataAnalysisRegistryReader.dispose(); } } /** * Returns an unmodifiable {@link Map} containing all registered * {@link IDataAnalysisItemContentProvider data-analysis content providers}, * mapped by their * {@link IDataAnalysisItemContentProvider#getConfigurations(Object) * configuration}. * * @return a {@link Map} containing all registered data-analysis content * providers, mapped by their configuration. */
/** */ package nl.esi.pps.tmsc.provider; /** * This is the central singleton for the Tmsc edit plugin. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public final class TmscEditPlugin extends EMFPlugin { /** * Keep track of the singleton. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final TmscEditPlugin INSTANCE = new TmscEditPlugin(); /** * Keep track of the singleton. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static Implementation plugin; /** * Create the instance. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TmscEditPlugin() { super(new ResourceLocator[] { ArchitectureEditPlugin.INSTANCE, PropertiesEditPlugin.INSTANCE, }); } /** * Returns the singleton instance of the Eclipse plugin. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the singleton instance. * @generated */ @Override public ResourceLocator getPluginResourceLocator() { return plugin; } /** * Returns the singleton instance of the Eclipse plugin. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the singleton instance. * @generated */ public static Implementation getPlugin() { return plugin; } /** * Creates a {@link ResourceSet} with edit support. * * @see #createItemProviderAdapterFactory() * @see ResourceSet#getAdapterFactories() */ public static ResourceSet createResourceSet() { ResourceSetImpl resourceSet = new ResourceSetImpl(); resourceSet.getAdapterFactories().add(createItemProviderAdapterFactory()); return resourceSet; } /** * Creates a {@link ComposedAdapterFactory} for all dependent languages, incl. reflective support. */ public static ComposedAdapterFactory createItemProviderAdapterFactory() { ComposedAdapterFactory adapterFactory = new ComposedAdapterFactory( ComposedAdapterFactory.Descriptor.Registry.INSTANCE) { // Avoiding multi-threading issues by making this method synchronized @Override public synchronized AdapterFactory getFactoryForTypes(Collection<?> types) { return super.getFactoryForTypes(types); } }; adapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new TmscItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new ArchitectureItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new SpecifiedItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new ImplementedItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new DeployedItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new InstantiatedItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new PropertiesItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory()); return adapterFactory; } /** * The actual implementation of the Eclipse <b>Plugin</b>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public static class Implementation extends PngEclipsePlugin { private DataAnalysisItemContentProviderRegistryReader dataAnalysisRegistryReader = null; /** * Creates an instance. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Implementation() { super(); // Remember the static instance. // plugin = this; } @Override public void start(BundleContext context) throws Exception { super.start(context); } @Override public void stop(BundleContext context) throws Exception { super.stop(context); if (dataAnalysisRegistryReader != null) { dataAnalysisRegistryReader.dispose(); } } /** * Returns an unmodifiable {@link Map} containing all registered * {@link IDataAnalysisItemContentProvider data-analysis content providers}, * mapped by their * {@link IDataAnalysisItemContentProvider#getConfigurations(Object) * configuration}. * * @return a {@link Map} containing all registered data-analysis content * providers, mapped by their configuration. */
public Iterable<IDataAnalysisItemContentProvider> getRegisteredDataAnalysisItemContentProviders(EClass eClass) {
9
2023-10-30 16:00:25+00:00
16k
CERBON-MODS/Bosses-of-Mass-Destruction-FORGE
src/main/java/com/cerbon/bosses_of_mass_destruction/block/custom/ObsidilithSummonBlock.java
[ { "identifier": "BMDBlocks", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/block/BMDBlocks.java", "snippet": "public class BMDBlocks {\n public static final DeferredRegister<Block> BLOCKS =\n DeferredRegister.create(ForgeRegistries.BLOCKS, BMDConstants.MOD_ID);\n\n public...
import com.cerbon.bosses_of_mass_destruction.block.BMDBlocks; import com.cerbon.bosses_of_mass_destruction.entity.BMDEntities; import com.cerbon.bosses_of_mass_destruction.entity.custom.obsidilith.ObsidilithEntity; import com.cerbon.bosses_of_mass_destruction.particle.BMDParticles; import com.cerbon.cerbons_api.api.general.event.EventScheduler; import com.cerbon.cerbons_api.api.general.event.TimedEvent; import com.cerbon.cerbons_api.api.general.particle.ClientParticleBuilder; import com.cerbon.cerbons_api.api.static_utilities.RandomUtils; import com.cerbon.cerbons_api.api.static_utilities.VecUtils; import com.cerbon.cerbons_api.capability.CerbonsApiCapabilities; import net.minecraft.core.BlockPos; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.EndPortalFrameBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
12,225
package com.cerbon.bosses_of_mass_destruction.block.custom; public class ObsidilithSummonBlock extends Block { public static final BooleanProperty eye = BlockStateProperties.EYE; protected final VoxelShape frameShape = box(0.0, 0.0, 0.0, 16.0, 13.0, 16.0); protected final VoxelShape eyeShape = box(4.0, 13.0, 4.0, 12.0, 16.0, 12.0); protected final VoxelShape frameWithEyeShape = Shapes.or(frameShape, eyeShape); public ObsidilithSummonBlock(Properties properties) { super(properties); registerDefaultState(getStateDefinition().any().setValue(eye, false)); } @Override public boolean useShapeForLightOcclusion(@NotNull BlockState state) { return true; } @Override public @NotNull VoxelShape getShape(BlockState state, @NotNull BlockGetter level, @NotNull BlockPos pos, @NotNull CollisionContext context) { return state.getValue(eye) ? frameWithEyeShape : frameShape; } @Nullable @Override public BlockState getStateForPlacement(@NotNull BlockPlaceContext context) { return defaultBlockState().setValue(eye, false); } @Override public boolean hasAnalogOutputSignal(@NotNull BlockState state) { return true; } @Override public int getAnalogOutputSignal(BlockState state, @NotNull Level level, @NotNull BlockPos pos) { return state.getValue(eye) ? 15 : 0; } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(eye); } public static void onEnderEyeUsed(UseOnContext context, CallbackInfoReturnable<InteractionResult> cir){ Level level = context.getLevel(); BlockPos blockPos = context.getClickedPos(); BlockState blockState = level.getBlockState(blockPos); if (blockState.is(BMDBlocks.OBSIDILITH_SUMMON_BLOCK.get()) && !blockState.getValue(EndPortalFrameBlock.HAS_EYE)){ EventScheduler eventScheduler = CerbonsApiCapabilities.getLevelEventScheduler(level); if (level.isClientSide){ cir.setReturnValue(InteractionResult.SUCCESS); addSummonEntityEffects(eventScheduler, blockPos); } else { BlockState blockState2 = blockState.setValue(EndPortalFrameBlock.HAS_EYE, true); pushEntitiesUp(blockState, blockState2, level, blockPos); level.setBlock(blockPos, blockState2, 2); context.getItemInHand().shrink(1); level.levelEvent(1503, blockPos, 0); addSummonEntityEvent(eventScheduler, level, blockPos); cir.setReturnValue(InteractionResult.PASS); } } } @OnlyIn(Dist.CLIENT) private static void addSummonEntityEffects(EventScheduler eventScheduler, BlockPos blockPos){ Vec3 centralPos = VecUtils.asVec3(blockPos.above()).add(VecUtils.unit.scale(0.5)); Vec3 particleVel = VecUtils.yAxis.scale(-0.03); eventScheduler.addEvent( new TimedEvent( () -> Particles.activateParticleFactory.build( centralPos.add(RandomUtils.randVec().scale(2.0)), particleVel ), 0, 80, () -> false ) ); } private static void addSummonEntityEvent(EventScheduler eventScheduler, Level level, BlockPos blockPos){ Vec3 pos = VecUtils.asVec3(blockPos).add(new Vec3(0.5, 0.0, 0.5)); eventScheduler.addEvent( new TimedEvent( () -> { level.setBlockAndUpdate(blockPos, Blocks.AIR.defaultBlockState());
package com.cerbon.bosses_of_mass_destruction.block.custom; public class ObsidilithSummonBlock extends Block { public static final BooleanProperty eye = BlockStateProperties.EYE; protected final VoxelShape frameShape = box(0.0, 0.0, 0.0, 16.0, 13.0, 16.0); protected final VoxelShape eyeShape = box(4.0, 13.0, 4.0, 12.0, 16.0, 12.0); protected final VoxelShape frameWithEyeShape = Shapes.or(frameShape, eyeShape); public ObsidilithSummonBlock(Properties properties) { super(properties); registerDefaultState(getStateDefinition().any().setValue(eye, false)); } @Override public boolean useShapeForLightOcclusion(@NotNull BlockState state) { return true; } @Override public @NotNull VoxelShape getShape(BlockState state, @NotNull BlockGetter level, @NotNull BlockPos pos, @NotNull CollisionContext context) { return state.getValue(eye) ? frameWithEyeShape : frameShape; } @Nullable @Override public BlockState getStateForPlacement(@NotNull BlockPlaceContext context) { return defaultBlockState().setValue(eye, false); } @Override public boolean hasAnalogOutputSignal(@NotNull BlockState state) { return true; } @Override public int getAnalogOutputSignal(BlockState state, @NotNull Level level, @NotNull BlockPos pos) { return state.getValue(eye) ? 15 : 0; } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(eye); } public static void onEnderEyeUsed(UseOnContext context, CallbackInfoReturnable<InteractionResult> cir){ Level level = context.getLevel(); BlockPos blockPos = context.getClickedPos(); BlockState blockState = level.getBlockState(blockPos); if (blockState.is(BMDBlocks.OBSIDILITH_SUMMON_BLOCK.get()) && !blockState.getValue(EndPortalFrameBlock.HAS_EYE)){ EventScheduler eventScheduler = CerbonsApiCapabilities.getLevelEventScheduler(level); if (level.isClientSide){ cir.setReturnValue(InteractionResult.SUCCESS); addSummonEntityEffects(eventScheduler, blockPos); } else { BlockState blockState2 = blockState.setValue(EndPortalFrameBlock.HAS_EYE, true); pushEntitiesUp(blockState, blockState2, level, blockPos); level.setBlock(blockPos, blockState2, 2); context.getItemInHand().shrink(1); level.levelEvent(1503, blockPos, 0); addSummonEntityEvent(eventScheduler, level, blockPos); cir.setReturnValue(InteractionResult.PASS); } } } @OnlyIn(Dist.CLIENT) private static void addSummonEntityEffects(EventScheduler eventScheduler, BlockPos blockPos){ Vec3 centralPos = VecUtils.asVec3(blockPos.above()).add(VecUtils.unit.scale(0.5)); Vec3 particleVel = VecUtils.yAxis.scale(-0.03); eventScheduler.addEvent( new TimedEvent( () -> Particles.activateParticleFactory.build( centralPos.add(RandomUtils.randVec().scale(2.0)), particleVel ), 0, 80, () -> false ) ); } private static void addSummonEntityEvent(EventScheduler eventScheduler, Level level, BlockPos blockPos){ Vec3 pos = VecUtils.asVec3(blockPos).add(new Vec3(0.5, 0.0, 0.5)); eventScheduler.addEvent( new TimedEvent( () -> { level.setBlockAndUpdate(blockPos, Blocks.AIR.defaultBlockState());
ObsidilithEntity obsidilithEntity = BMDEntities.OBSIDILITH.get().create(level);
2
2023-10-25 16:28:17+00:00
16k
SmartGecko44/Spigot-Admin-Toys
src/main/java/org/gecko/wauh/logic/Scale.java
[ { "identifier": "Main", "path": "src/main/java/org/gecko/wauh/Main.java", "snippet": "public final class Main extends JavaPlugin {\n\n ConfigurationManager configManager;\n FileConfiguration config;\n private int playerRadiusLimit;\n private int tntRadiusLimit;\n private int creeperRadius...
import org.bukkit.block.Block; import org.gecko.wauh.Main; import org.gecko.wauh.listeners.BarrierListener; import org.gecko.wauh.listeners.BedrockListener; import org.gecko.wauh.listeners.BucketListener; import org.gecko.wauh.listeners.WaterBucketListener; import java.util.*;
13,906
package org.gecko.wauh.logic; public class Scale { public void ScaleReverseLogic(int totalRemovedCount, int radiusLimit, Set<Block> markedBlocks, String source) { Main mainPlugin = Main.getPlugin(Main.class); BucketListener bucketListener = mainPlugin.getBucketListener(); BarrierListener barrierListener = mainPlugin.getBarrierListener(); BedrockListener bedrockListener = mainPlugin.getBedrockListener();
package org.gecko.wauh.logic; public class Scale { public void ScaleReverseLogic(int totalRemovedCount, int radiusLimit, Set<Block> markedBlocks, String source) { Main mainPlugin = Main.getPlugin(Main.class); BucketListener bucketListener = mainPlugin.getBucketListener(); BarrierListener barrierListener = mainPlugin.getBarrierListener(); BedrockListener bedrockListener = mainPlugin.getBedrockListener();
WaterBucketListener waterBucketListener = mainPlugin.getWaterBucketListener();
4
2023-10-28 11:26:45+00:00
16k
sinch/sinch-sdk-java
openapi-contracts/src/main/com/sinch/sdk/domains/sms/adapters/api/v1/DeliveryReportsApi.java
[ { "identifier": "ApiException", "path": "core/src/main/com/sinch/sdk/core/exceptions/ApiException.java", "snippet": "public class ApiException extends RuntimeException {\n\n private static final long serialVersionUID = -1L;\n private int code = 0;\n\n public ApiException() {}\n\n public ApiException...
import com.fasterxml.jackson.core.type.TypeReference; import com.sinch.sdk.core.exceptions.ApiException; import com.sinch.sdk.core.exceptions.ApiExceptionBuilder; import com.sinch.sdk.core.http.AuthManager; import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.core.http.HttpMapper; import com.sinch.sdk.core.http.HttpMethod; import com.sinch.sdk.core.http.HttpRequest; import com.sinch.sdk.core.http.HttpResponse; import com.sinch.sdk.core.http.HttpStatus; import com.sinch.sdk.core.http.URLParameter; import com.sinch.sdk.core.http.URLPathUtils; import com.sinch.sdk.core.models.ServerConfiguration; import com.sinch.sdk.domains.sms.models.dto.v1.DeliveryReportDto; import com.sinch.sdk.domains.sms.models.dto.v1.DeliveryReportListDto; import com.sinch.sdk.domains.sms.models.dto.v1.RecipientDeliveryReportDto; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger;
12,780
/* * API Overview | Sinch * Sinch SMS API is one of the easiest APIs we offer and enables you to add fast and reliable global SMS to your applications. Send single messages, scheduled batch messages, use available message templates and more. * * The version of the OpenAPI document: v1 * Contact: Support@sinch.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.sinch.sdk.domains.sms.adapters.api.v1; public class DeliveryReportsApi { private static final Logger LOGGER = Logger.getLogger(DeliveryReportsApi.class.getName()); private HttpClient httpClient; private ServerConfiguration serverConfiguration; private Map<String, AuthManager> authManagersByOasSecuritySchemes; private HttpMapper mapper; public DeliveryReportsApi( HttpClient httpClient, ServerConfiguration serverConfiguration, Map<String, AuthManager> authManagersByOasSecuritySchemes, HttpMapper mapper) { this.httpClient = httpClient; this.serverConfiguration = serverConfiguration; this.authManagersByOasSecuritySchemes = authManagersByOasSecuritySchemes; this.mapper = mapper; } /** * Retrieve a delivery report Delivery reports can be retrieved even if no callback was requested. * The difference between a summary and a full report is only that the full report contains the * phone numbers in &lt;a * href&#x3D;\&quot;https://community.sinch.com/t5/Glossary/E-164/ta-p/7537\&quot; * target&#x3D;\&quot;_blank\&quot;&gt;E.164&lt;/a&gt; format for each status code. * * @param servicePlanId Your service plan ID. You can find this on your * [Dashboard](https://dashboard.sinch.com/sms/api/rest). (required) * @param batchId The batch ID you received from sending a message. (required) * @param type The type of delivery report. - A &#x60;summary&#x60; will count the number of * messages sent per status. - A &#x60;full&#x60; report give that of a &#x60;summary&#x60; * report but in addition, lists phone numbers. (optional, default to summary) * @param status Comma separated list of delivery_report_statuses to include (optional) * @param code Comma separated list of delivery_receipt_error_codes to include\&quot; (optional) * @return DeliveryReportDto * @throws ApiException if fails to make API call */ public DeliveryReportDto getDeliveryReportByBatchId( String servicePlanId, String batchId, String type, String status, String code) throws ApiException { LOGGER.finest( "[getDeliveryReportByBatchId]" + " " + "servicePlanId: " + servicePlanId + ", " + "batchId: " + batchId + ", " + "type: " + type + ", " + "status: " + status + ", " + "code: " + code); HttpRequest httpRequest = getDeliveryReportByBatchIdRequestBuilder(servicePlanId, batchId, type, status, code); HttpResponse response = httpClient.invokeAPI( this.serverConfiguration, this.authManagersByOasSecuritySchemes, httpRequest); if (HttpStatus.isSuccessfulStatus(response.getCode())) { TypeReference<DeliveryReportDto> localVarReturnType = new TypeReference<DeliveryReportDto>() {}; return mapper.deserialize(response, localVarReturnType); } // fallback to default errors handling: // all error cases definition are not required from specs: will try some "hardcoded" content // parsing throw ApiExceptionBuilder.build( response.getMessage(), response.getCode(), mapper.deserialize(response, new TypeReference<HashMap<String, ?>>() {})); } private HttpRequest getDeliveryReportByBatchIdRequestBuilder( String servicePlanId, String batchId, String type, String status, String code) throws ApiException { // verify the required parameter 'servicePlanId' is set if (servicePlanId == null) { throw new ApiException( 400, "Missing the required parameter 'servicePlanId' when calling getDeliveryReportByBatchId"); } // verify the required parameter 'batchId' is set if (batchId == null) { throw new ApiException( 400, "Missing the required parameter 'batchId' when calling getDeliveryReportByBatchId"); } String localVarPath = "/xms/v1/{service_plan_id}/batches/{batch_id}/delivery_report" .replaceAll( "\\{" + "service_plan_id" + "\\}", URLPathUtils.encodePathSegment(servicePlanId.toString())) .replaceAll( "\\{" + "batch_id" + "\\}", URLPathUtils.encodePathSegment(batchId.toString())); List<URLParameter> localVarQueryParams = new ArrayList<>(); if (null != type) { localVarQueryParams.add( new URLParameter("type", type, URLParameter.STYLE.valueOf("form".toUpperCase()), true)); } if (null != status) { localVarQueryParams.add( new URLParameter( "status", status, URLParameter.STYLE.valueOf("form".toUpperCase()), true)); } if (null != code) { localVarQueryParams.add( new URLParameter("code", code, URLParameter.STYLE.valueOf("form".toUpperCase()), true)); } Map<String, String> localVarHeaderParams = new HashMap<>(); final Collection<String> localVarAccepts = Arrays.asList("application/json"); final Collection<String> localVarContentTypes = Arrays.asList(); final Collection<String> localVarAuthNames = Arrays.asList("BearerAuth"); final String serializedBody = null; return new HttpRequest( localVarPath, HttpMethod.GET, localVarQueryParams, serializedBody, localVarHeaderParams, localVarAccepts, localVarContentTypes, localVarAuthNames); } /** * Retrieve a recipient delivery report A recipient delivery report contains the message status * for a single recipient phone number. * * @param servicePlanId Your service plan ID. You can find this on your * [Dashboard](https://dashboard.sinch.com/sms/api/rest). (required) * @param batchId The batch ID you received from sending a message. (required) * @param recipientMsisdn Phone number for which you to want to search. (required) * @return RecipientDeliveryReportDto * @throws ApiException if fails to make API call */
/* * API Overview | Sinch * Sinch SMS API is one of the easiest APIs we offer and enables you to add fast and reliable global SMS to your applications. Send single messages, scheduled batch messages, use available message templates and more. * * The version of the OpenAPI document: v1 * Contact: Support@sinch.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.sinch.sdk.domains.sms.adapters.api.v1; public class DeliveryReportsApi { private static final Logger LOGGER = Logger.getLogger(DeliveryReportsApi.class.getName()); private HttpClient httpClient; private ServerConfiguration serverConfiguration; private Map<String, AuthManager> authManagersByOasSecuritySchemes; private HttpMapper mapper; public DeliveryReportsApi( HttpClient httpClient, ServerConfiguration serverConfiguration, Map<String, AuthManager> authManagersByOasSecuritySchemes, HttpMapper mapper) { this.httpClient = httpClient; this.serverConfiguration = serverConfiguration; this.authManagersByOasSecuritySchemes = authManagersByOasSecuritySchemes; this.mapper = mapper; } /** * Retrieve a delivery report Delivery reports can be retrieved even if no callback was requested. * The difference between a summary and a full report is only that the full report contains the * phone numbers in &lt;a * href&#x3D;\&quot;https://community.sinch.com/t5/Glossary/E-164/ta-p/7537\&quot; * target&#x3D;\&quot;_blank\&quot;&gt;E.164&lt;/a&gt; format for each status code. * * @param servicePlanId Your service plan ID. You can find this on your * [Dashboard](https://dashboard.sinch.com/sms/api/rest). (required) * @param batchId The batch ID you received from sending a message. (required) * @param type The type of delivery report. - A &#x60;summary&#x60; will count the number of * messages sent per status. - A &#x60;full&#x60; report give that of a &#x60;summary&#x60; * report but in addition, lists phone numbers. (optional, default to summary) * @param status Comma separated list of delivery_report_statuses to include (optional) * @param code Comma separated list of delivery_receipt_error_codes to include\&quot; (optional) * @return DeliveryReportDto * @throws ApiException if fails to make API call */ public DeliveryReportDto getDeliveryReportByBatchId( String servicePlanId, String batchId, String type, String status, String code) throws ApiException { LOGGER.finest( "[getDeliveryReportByBatchId]" + " " + "servicePlanId: " + servicePlanId + ", " + "batchId: " + batchId + ", " + "type: " + type + ", " + "status: " + status + ", " + "code: " + code); HttpRequest httpRequest = getDeliveryReportByBatchIdRequestBuilder(servicePlanId, batchId, type, status, code); HttpResponse response = httpClient.invokeAPI( this.serverConfiguration, this.authManagersByOasSecuritySchemes, httpRequest); if (HttpStatus.isSuccessfulStatus(response.getCode())) { TypeReference<DeliveryReportDto> localVarReturnType = new TypeReference<DeliveryReportDto>() {}; return mapper.deserialize(response, localVarReturnType); } // fallback to default errors handling: // all error cases definition are not required from specs: will try some "hardcoded" content // parsing throw ApiExceptionBuilder.build( response.getMessage(), response.getCode(), mapper.deserialize(response, new TypeReference<HashMap<String, ?>>() {})); } private HttpRequest getDeliveryReportByBatchIdRequestBuilder( String servicePlanId, String batchId, String type, String status, String code) throws ApiException { // verify the required parameter 'servicePlanId' is set if (servicePlanId == null) { throw new ApiException( 400, "Missing the required parameter 'servicePlanId' when calling getDeliveryReportByBatchId"); } // verify the required parameter 'batchId' is set if (batchId == null) { throw new ApiException( 400, "Missing the required parameter 'batchId' when calling getDeliveryReportByBatchId"); } String localVarPath = "/xms/v1/{service_plan_id}/batches/{batch_id}/delivery_report" .replaceAll( "\\{" + "service_plan_id" + "\\}", URLPathUtils.encodePathSegment(servicePlanId.toString())) .replaceAll( "\\{" + "batch_id" + "\\}", URLPathUtils.encodePathSegment(batchId.toString())); List<URLParameter> localVarQueryParams = new ArrayList<>(); if (null != type) { localVarQueryParams.add( new URLParameter("type", type, URLParameter.STYLE.valueOf("form".toUpperCase()), true)); } if (null != status) { localVarQueryParams.add( new URLParameter( "status", status, URLParameter.STYLE.valueOf("form".toUpperCase()), true)); } if (null != code) { localVarQueryParams.add( new URLParameter("code", code, URLParameter.STYLE.valueOf("form".toUpperCase()), true)); } Map<String, String> localVarHeaderParams = new HashMap<>(); final Collection<String> localVarAccepts = Arrays.asList("application/json"); final Collection<String> localVarContentTypes = Arrays.asList(); final Collection<String> localVarAuthNames = Arrays.asList("BearerAuth"); final String serializedBody = null; return new HttpRequest( localVarPath, HttpMethod.GET, localVarQueryParams, serializedBody, localVarHeaderParams, localVarAccepts, localVarContentTypes, localVarAuthNames); } /** * Retrieve a recipient delivery report A recipient delivery report contains the message status * for a single recipient phone number. * * @param servicePlanId Your service plan ID. You can find this on your * [Dashboard](https://dashboard.sinch.com/sms/api/rest). (required) * @param batchId The batch ID you received from sending a message. (required) * @param recipientMsisdn Phone number for which you to want to search. (required) * @return RecipientDeliveryReportDto * @throws ApiException if fails to make API call */
public RecipientDeliveryReportDto getDeliveryReportByPhoneNumber(
14
2023-10-31 08:32:59+00:00
16k
zxzf1234/jimmer-ruoyivuepro
backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/service/system/user/UserServiceImpl.java
[ { "identifier": "CommonStatusEnum", "path": "backend/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/enums/CommonStatusEnum.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum CommonStatusEnum implements IntArrayValuable {\n\n ENABLE(0, \"开启\"),\n DISABLE(1, \...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.StrUtil; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.exception.ServiceException; import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils; import cn.iocoder.yudao.framework.datapermission.core.util.DataPermissionUtils; import cn.iocoder.yudao.service.api.infra.file.FileApi; import cn.iocoder.yudao.service.model.system.user.SystemUser; import cn.iocoder.yudao.service.vo.system.user.profile.UserProfileUpdatePasswordReqVO; import cn.iocoder.yudao.service.vo.system.user.profile.UserProfileUpdateReqVO; import cn.iocoder.yudao.service.vo.system.user.user.*; import cn.iocoder.yudao.service.convert.system.user.UserConvert; import cn.iocoder.yudao.service.model.system.dept.SystemUserPost; import cn.iocoder.yudao.service.model.system.dept.SystemUserPostDraft; import cn.iocoder.yudao.service.model.system.user.SystemUserDraft; import cn.iocoder.yudao.service.repository.system.dept.SystemUserPostRepository; import cn.iocoder.yudao.service.repository.system.user.SystemUserRepository; import cn.iocoder.yudao.service.service.system.dept.DeptService; import cn.iocoder.yudao.service.service.system.dept.PostService; import cn.iocoder.yudao.service.service.system.permission.PermissionService; import com.google.common.annotations.VisibleForTesting; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.io.InputStream; import java.util.*; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList; import static cn.iocoder.yudao.service.enums.system.ErrorCodeConstants.*;
11,157
package cn.iocoder.yudao.service.service.system.user; /** * 后台用户 Service 实现类 * * @author 芋道源码 */ @Service("adminUserService") @Slf4j public class UserServiceImpl implements UserService { @Resource private SystemUserRepository systemUserRepository; @Resource private SystemUserPostRepository systemUserPostRepository; @Value("${sys.user.init-password:yudaoyuanma}") private String userInitPassword; @Resource private DeptService deptService; @Resource private PostService postService; @Resource private PermissionService permissionService; @Resource private PasswordEncoder passwordEncoder; @Resource private FileApi fileApi; @Override @Transactional(rollbackFor = Exception.class) public Long createUser(UserCreateReq reqVO) { // 校验正确性 validateUserForCreateOrUpdate(null, reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(), reqVO.getDeptId(), reqVO.getPostIds());
package cn.iocoder.yudao.service.service.system.user; /** * 后台用户 Service 实现类 * * @author 芋道源码 */ @Service("adminUserService") @Slf4j public class UserServiceImpl implements UserService { @Resource private SystemUserRepository systemUserRepository; @Resource private SystemUserPostRepository systemUserPostRepository; @Value("${sys.user.init-password:yudaoyuanma}") private String userInitPassword; @Resource private DeptService deptService; @Resource private PostService postService; @Resource private PermissionService permissionService; @Resource private PasswordEncoder passwordEncoder; @Resource private FileApi fileApi; @Override @Transactional(rollbackFor = Exception.class) public Long createUser(UserCreateReq reqVO) { // 校验正确性 validateUserForCreateOrUpdate(null, reqVO.getUsername(), reqVO.getMobile(), reqVO.getEmail(), reqVO.getDeptId(), reqVO.getPostIds());
SystemUser newUserConvert = UserConvert.INSTANCE.convertUser(reqVO);
8
2023-10-27 06:35:24+00:00
16k
slatepowered/slate
slate-cluster/src/main/java/slatepowered/slate/cluster/ClusterInstance.java
[ { "identifier": "CommunicationKey", "path": "slate-common/src/main/java/slatepowered/slate/communication/CommunicationKey.java", "snippet": "public class CommunicationKey {\r\n\r\n public static class ClusterDeclareCommunicationKey extends CommunicationKey {\r\n @Override\r\n public int...
import slatepowered.slate.allocation.*; import slatepowered.slate.communication.CommunicationKey; import slatepowered.slate.communication.CommunicationStrategy; import slatepowered.slate.logging.Logger; import slatepowered.slate.logging.Logging; import slatepowered.slate.model.ClusterManagedNode; import slatepowered.slate.model.ClusterNetwork; import slatepowered.slate.model.Node; import slatepowered.slate.model.NodeComponent; import slatepowered.slate.action.NodeAllocationAdapter; import slatepowered.slate.network.NetworkInfoService; import slatepowered.slate.packages.PackageAttachment; import slatepowered.slate.packages.PackageManager; import slatepowered.slate.packages.Packages; import slatepowered.slate.packages.service.LateAttachmentService; import slatepowered.slate.plugin.SlatePluginManager; import slatepowered.veru.collection.Sequence; import slatepowered.veru.misc.Throwables; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture;
12,125
package slatepowered.slate.cluster; /** * An instance of this cluster for a specific network. */ public abstract class ClusterInstance extends ClusterNetwork { protected static final Logger LOGGER = Logging.getLogger("ClusterInstance"); /** * The cluster. */ protected final Cluster<?> cluster; /** * The directory for this cluster instance. */ protected final Path directory; /** * Whether this instance is enabled. */ private boolean enabled = true; public ClusterInstance(Cluster<?> cluster, CommunicationKey communicationKey, CommunicationStrategy communicationStrategy) { super(communicationKey, communicationStrategy); this.cluster = cluster; this.directory = cluster.getInstanceDirectory(this); cluster.getPluginManager().initialize(this); try { Files.createDirectories(directory); } catch (Throwable t) { Throwables.sneakyThrow(t); } } /** * Set if this cluster instance is enabled. * * When disabled a cluster instance will not accept allocation * or destruction of nodes, essentially sitting idle. * * @param enabled Enable flag. * @return This. */ public ClusterInstance setEnabled(boolean enabled) { this.enabled = enabled; return this; } public boolean isEnabled() { return enabled; } public Cluster getCluster() { return cluster; } // first check registered nodes, otherwise // fetch the info about a node remotely // and create it as a non-managed node private Node fetchAndCreateNode(String name) { Node node = getNode(name); if (node == null) { NetworkInfoService.NodeInfo nodeInfo = getService(NetworkInfoService.KEY) .fetchNodeInfo(name); node = new Node(nodeInfo.getName(), this) { @Override public String[] getTags() { return nodeInfo.getTags(); } }; } return node; } /** * Closes this cluster instance. */ public void close() { cluster.getPluginManager().disable(this); cluster.closeInstance(this); } /** * Get the allocation checker to check availability. * * @return The allocation checker. */ protected ClusterAllocationChecker getAllocationChecker() { return null; } /** * Attempts to allocate and initialize a node following the given request. * * @param request The allocation request. * @return The allocation result. */ @SuppressWarnings("unchecked") public ClusterManagedNode allocateAndInitializeNode(NodeAllocationRequest request) { try { NetworkInfoService networkInfoService = getService(NetworkInfoService.KEY); // create node locally LOGGER.debug("Allocating node with name(" + request.getNodeName() + ") with componentCount(" + request.getComponents().size() + ")"); ClusterManagedNode node = new ClusterManagedNode( fetchAndCreateNode(request.getParentNodeName()), request.getNodeName(), ClusterInstance.this,
package slatepowered.slate.cluster; /** * An instance of this cluster for a specific network. */ public abstract class ClusterInstance extends ClusterNetwork { protected static final Logger LOGGER = Logging.getLogger("ClusterInstance"); /** * The cluster. */ protected final Cluster<?> cluster; /** * The directory for this cluster instance. */ protected final Path directory; /** * Whether this instance is enabled. */ private boolean enabled = true; public ClusterInstance(Cluster<?> cluster, CommunicationKey communicationKey, CommunicationStrategy communicationStrategy) { super(communicationKey, communicationStrategy); this.cluster = cluster; this.directory = cluster.getInstanceDirectory(this); cluster.getPluginManager().initialize(this); try { Files.createDirectories(directory); } catch (Throwable t) { Throwables.sneakyThrow(t); } } /** * Set if this cluster instance is enabled. * * When disabled a cluster instance will not accept allocation * or destruction of nodes, essentially sitting idle. * * @param enabled Enable flag. * @return This. */ public ClusterInstance setEnabled(boolean enabled) { this.enabled = enabled; return this; } public boolean isEnabled() { return enabled; } public Cluster getCluster() { return cluster; } // first check registered nodes, otherwise // fetch the info about a node remotely // and create it as a non-managed node private Node fetchAndCreateNode(String name) { Node node = getNode(name); if (node == null) { NetworkInfoService.NodeInfo nodeInfo = getService(NetworkInfoService.KEY) .fetchNodeInfo(name); node = new Node(nodeInfo.getName(), this) { @Override public String[] getTags() { return nodeInfo.getTags(); } }; } return node; } /** * Closes this cluster instance. */ public void close() { cluster.getPluginManager().disable(this); cluster.closeInstance(this); } /** * Get the allocation checker to check availability. * * @return The allocation checker. */ protected ClusterAllocationChecker getAllocationChecker() { return null; } /** * Attempts to allocate and initialize a node following the given request. * * @param request The allocation request. * @return The allocation result. */ @SuppressWarnings("unchecked") public ClusterManagedNode allocateAndInitializeNode(NodeAllocationRequest request) { try { NetworkInfoService networkInfoService = getService(NetworkInfoService.KEY); // create node locally LOGGER.debug("Allocating node with name(" + request.getNodeName() + ") with componentCount(" + request.getComponents().size() + ")"); ClusterManagedNode node = new ClusterManagedNode( fetchAndCreateNode(request.getParentNodeName()), request.getNodeName(), ClusterInstance.this,
(List<NodeComponent>)(Object)request.getComponents(),
7
2023-10-30 08:58:02+00:00
16k
Melledy/LunarCore
src/main/java/emu/lunarcore/game/battle/MazeBuff.java
[ { "identifier": "MazeBuffExcel", "path": "src/main/java/emu/lunarcore/data/excel/MazeBuffExcel.java", "snippet": "@Getter\n@ResourceType(name = {\"MazeBuff.json\"})\npublic class MazeBuffExcel extends GameResource {\n private int ID;\n private int Lv;\n\n @Override\n public int getId() {\n ...
import emu.lunarcore.data.excel.MazeBuffExcel; import emu.lunarcore.game.scene.entity.GameEntity; import emu.lunarcore.proto.BattleBuffOuterClass.BattleBuff; import emu.lunarcore.proto.BattleBuffOuterClass.BattleBuff.DynamicValuesEntry; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import it.unimi.dsi.fastutil.objects.Object2DoubleMap; import it.unimi.dsi.fastutil.objects.Object2DoubleOpenHashMap; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter;
11,535
package emu.lunarcore.game.battle; @Getter public class MazeBuff { private int id; private int level; private int ownerIndex; private int waveFlag; private IntList targetIndex; @Getter(AccessLevel.NONE) private Object2DoubleMap<String> dynamicValues; @Setter private transient GameEntity owner; public MazeBuff(MazeBuffExcel excel, int ownerIndex, int waveFlag) { this(excel.getBuffId(), excel.getLv(), ownerIndex, waveFlag); } public MazeBuff(int id, int level, int ownerIndex, int waveFlag) { this.id = id; this.level = level; this.ownerIndex = ownerIndex; this.waveFlag = waveFlag; } public void addTargetIndex(int index) { if (this.targetIndex == null) { this.targetIndex = new IntArrayList(); } this.targetIndex.add(index); } public void addDynamicValue(String key, double value) { if (this.dynamicValues == null) { this.dynamicValues = new Object2DoubleOpenHashMap<>(); } this.dynamicValues.put(key, value); }
package emu.lunarcore.game.battle; @Getter public class MazeBuff { private int id; private int level; private int ownerIndex; private int waveFlag; private IntList targetIndex; @Getter(AccessLevel.NONE) private Object2DoubleMap<String> dynamicValues; @Setter private transient GameEntity owner; public MazeBuff(MazeBuffExcel excel, int ownerIndex, int waveFlag) { this(excel.getBuffId(), excel.getLv(), ownerIndex, waveFlag); } public MazeBuff(int id, int level, int ownerIndex, int waveFlag) { this.id = id; this.level = level; this.ownerIndex = ownerIndex; this.waveFlag = waveFlag; } public void addTargetIndex(int index) { if (this.targetIndex == null) { this.targetIndex = new IntArrayList(); } this.targetIndex.add(index); } public void addDynamicValue(String key, double value) { if (this.dynamicValues == null) { this.dynamicValues = new Object2DoubleOpenHashMap<>(); } this.dynamicValues.put(key, value); }
public BattleBuff toProto() {
2
2023-10-10 12:57:35+00:00
16k
Swofty-Developments/Continued-Slime-World-Manager
swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/commands/subtypes/subCommand_migrate.java
[ { "identifier": "UnknownWorldException", "path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/exceptions/UnknownWorldException.java", "snippet": "public class UnknownWorldException extends SlimeException {\n\n public UnknownWorldException(String world) {\n super(\"Unknown world \" ...
import net.swofty.swm.api.exceptions.UnknownWorldException; import net.swofty.swm.api.exceptions.WorldAlreadyExistsException; import net.swofty.swm.api.exceptions.WorldInUseException; import net.swofty.swm.api.loaders.SlimeLoader; import net.swofty.swm.api.world.data.WorldData; import net.swofty.swm.api.world.data.WorldsConfig; import net.swofty.swm.plugin.SWMPlugin; import net.swofty.swm.plugin.commands.CommandCooldown; import net.swofty.swm.plugin.commands.CommandParameters; import net.swofty.swm.plugin.commands.CommandSource; import net.swofty.swm.plugin.commands.SWMCommand; import net.swofty.swm.plugin.config.ConfigManager; import net.swofty.swm.plugin.loader.LoaderUtils; import net.swofty.swm.plugin.log.Logging; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import java.io.IOException; import java.util.Collections; import java.util.LinkedList; import java.util.List;
10,970
package net.swofty.swm.plugin.commands.subtypes; @CommandParameters(description = "Migrates a world from one data source to another", inGameOnly = false, permission = "swm.migrate") public class subCommand_migrate extends SWMCommand implements CommandCooldown { @Override public long cooldownSeconds() { return 0; } @Override public void run(CommandSource sender, String[] args) { if (args.length == 0) { sender.send("§cUsage: /swm migrate <world> <new-data-source>"); return; } String worldName = args[0]; WorldsConfig config = SWMPlugin.getInstance().getConfigManager().getWorldConfig(); WorldData worldData = config.getWorlds().get(worldName); if (worldData == null) {
package net.swofty.swm.plugin.commands.subtypes; @CommandParameters(description = "Migrates a world from one data source to another", inGameOnly = false, permission = "swm.migrate") public class subCommand_migrate extends SWMCommand implements CommandCooldown { @Override public long cooldownSeconds() { return 0; } @Override public void run(CommandSource sender, String[] args) { if (args.length == 0) { sender.send("§cUsage: /swm migrate <world> <new-data-source>"); return; } String worldName = args[0]; WorldsConfig config = SWMPlugin.getInstance().getConfigManager().getWorldConfig(); WorldData worldData = config.getWorlds().get(worldName); if (worldData == null) {
sender.send(Logging.COMMAND_PREFIX + ChatColor.RED + "Unknown world " + worldName + "! Are you sure you configured it correctly?");
12
2023-10-08 10:54:28+00:00
16k
ZJU-ACES-ISE/chatunitest-core
src/main/java/zju/cst/aces/api/impl/obfuscator/Obfuscator.java
[ { "identifier": "Config", "path": "src/main/java/zju/cst/aces/api/config/Config.java", "snippet": "@Getter\n@Setter\npublic class Config {\n public String date;\n public Gson GSON;\n public Project project;\n public JavaParser parser;\n public JavaParserFacade parserFacade;\n public Li...
import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.ImportDeclaration; import com.github.javaparser.ast.PackageDeclaration; import com.github.javaparser.ast.body.BodyDeclaration; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.comments.LineComment; import com.github.javaparser.ast.expr.MethodReferenceExpr; import com.github.javaparser.ast.expr.SimpleName; import com.github.javaparser.ast.expr.StringLiteralExpr; import com.github.javaparser.ast.visitor.VoidVisitorAdapter; import com.google.gson.reflect.TypeToken; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.Data; import org.objectweb.asm.tree.ClassNode; import zju.cst.aces.api.config.Config; import zju.cst.aces.api.impl.obfuscator.frame.SymbolFrame; import zju.cst.aces.api.impl.obfuscator.util.ASMParser; import zju.cst.aces.dto.PromptInfo; import zju.cst.aces.dto.TestMessage; import zju.cst.aces.api.impl.obfuscator.util.SymbolAnalyzer; import zju.cst.aces.parser.ProjectParser; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.jar.JarFile; import java.util.stream.Collectors;
12,782
SymbolFrame sf = findSymbolFrameByClass(key); if (sf == null) { continue; } sf.toObNames(targetGroupIds).forEach(name -> { encryptName(name); }); obfuscatedDep.put(obfuscateName(key), obfuscateJava(dep.get(key))); } return obfuscatedDep; } public Map<String, String> deobfuscateDep(Map<String, String> dep) { Map<String, String> deobfuscatedDep = new HashMap<>(); for (String key : dep.keySet()) { deobfuscatedDep.put(deobfuscateName(key), deobfuscateJava(dep.get(key))); } return deobfuscatedDep; } public TestMessage obfuscateTestMessage(TestMessage msg) { if (msg == null) { return null; } msg.setErrorMessage(msg.getErrorMessage().stream().map(this::obfuscateText).collect(Collectors.toList())); return msg; } public TestMessage deobfuscateTestMessage(TestMessage msg) { if (msg == null) { return null; } msg.setErrorMessage(msg.getErrorMessage().stream().map(this::deobfuscateText).collect(Collectors.toList())); return msg; } private String encryptName(String oldName) { if (symbolFrame == null) { throw new RuntimeException("Symbol frames are not initialized!"); } if (cryptoMap.containsKey(oldName)) { return cryptoMap.get(oldName); } if (oldName.length() < 4) { return oldName; } if (oldName.startsWith("set") || oldName.startsWith("get") || oldName.startsWith("is") || oldName.startsWith("has")) { String prefix = ""; if (oldName.startsWith("is")) { prefix = oldName.substring(0, 2); } else { prefix = oldName.substring(0, 3); } String suffix = oldName.substring(prefix.length()); String newName = prefix + caesarCipher(suffix); putCryptoMap(oldName, newName); return newName; } else { String newName = caesarCipher(oldName); putCryptoMap(oldName, newName); return newName; } } private String encryptIfExist(String oldName) { if (symbolFrame == null) { throw new RuntimeException("Symbol frames are not initialized!"); } if (cryptoMap.containsKey(oldName)) { return cryptoMap.get(oldName); } return oldName; } // Caesar Cipher private String caesarCipher(String old) { StringBuilder sb = new StringBuilder(); for (char c : old.toCharArray()) { if (c >= 'a' && c < 'z' || c >= 'A' && c < 'Z') { sb.append((char) (c + this.shift)); } else if (c == 'z') { sb.append('a'); } else if (c == 'Z') { sb.append('A'); } else { sb.append(c); } } return sb.toString(); } private String decryptName(String oldName) { if (this.reversedMap == null) { this.reversedMap = createReversedMap(this.cryptoMap); } if (this.allCaseMap == null) { this.allCaseMap = createAllCaseMap(this.reversedMap); } if (allCaseMap.containsKey(oldName)) { return allCaseMap.get(oldName); } return oldName; } // TODO: export to json public Map<String, SymbolFrame> generateSymbolFrames() { Set<ClassNode> candidateClasses = new HashSet<>(); ASMParser asmParser = new ASMParser(config); Map<String, SymbolFrame> symbolFrames = new HashMap<>(); try { Path artifactPath = config.getProject().getArtifactPath(); JarFile projectJar = new JarFile(artifactPath.toString()); candidateClasses.addAll(asmParser.loadClasses(projectJar)); for (ClassNode classNode : candidateClasses) { String className = classNode.name; if (!SymbolFrame.isClassInGroup(className, targetGroupIds)) { continue; }
package zju.cst.aces.api.impl.obfuscator; @Data public class Obfuscator { public final Config config; private Map<String, String> cryptoMap; private Map<String, String> reversedMap; private Map<String, String> allCaseMap; private SymbolFrame symbolFrame; private int shift = 1; private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); public List<String> targetGroupIds; public Obfuscator(Config config) { this.config = config; this.cryptoMap = new TreeMap<>((s1, s2) -> { int diff = s2.length() - s1.length(); if (diff != 0) { return diff; } else { return s2.compareTo(s1); // If the length is the same, sort in dictionary reverse order } }); setTargetGroupIds(config); } //TODO public void setTargetGroupIds(Config config) { String projectGroupId = config.getProject().getGroupId(); List<String> groupIds = Arrays.stream(config.getObfuscateGroupIds()) .map(String::trim) .collect(Collectors.toList()); if (!groupIds.contains(projectGroupId)) { groupIds.add(projectGroupId); } this.targetGroupIds = groupIds; } public PromptInfo obfuscatePromptInfo(PromptInfo promptInfo) { this.symbolFrame = findSymbolFrameByClass(promptInfo.getFullClassName()); if (this.symbolFrame == null) { throw new RuntimeException("Cannot find symbol frame for class: " + promptInfo.getFullClassName()); } this.symbolFrame.toObNames(targetGroupIds).forEach(name -> { encryptName(name); }); promptInfo.setContext(obfuscateJava(promptInfo.getContext())); promptInfo.setUnitTest(obfuscateJava(promptInfo.getUnitTest())); promptInfo.setConstructorDeps(obfuscateDep(promptInfo.getConstructorDeps())); promptInfo.setMethodDeps(obfuscateDep(promptInfo.getMethodDeps())); promptInfo.setErrorMsg(obfuscateTestMessage(promptInfo.getErrorMsg())); promptInfo.setClassName(obfuscateName(promptInfo.getClassName())); promptInfo.setMethodName(obfuscateName(promptInfo.getMethodName())); promptInfo.setMethodSignature(obfuscateMethodSig(promptInfo.getMethodSignature())); // TODO: obfuscate other method brief // promptInfo.setOtherMethodBrief(promptInfo.getOtherMethodBrief().stream().map(this::obfuscateMethodBrief).collect(Collectors.toList())); this.reversedMap = createReversedMap(this.cryptoMap); this.allCaseMap = createAllCaseMap(this.reversedMap); return promptInfo; } public String obfuscateMethodBrief(String brief) { try { BodyDeclaration md = StaticJavaParser.parseBodyDeclaration(brief); md.accept(new ObfuscatorVisitor(), null); return md.toString().substring(0, md.toString().lastIndexOf("{")); } catch (Exception e) { config.getLog().error("Failed to obfuscate method brief: " + e); } return brief; } public String obfuscateMethodSig(String methodSig) { return obfuscateString(methodSig); } public String obfuscateMethod(String code) { if (code == "") { return ""; } String obfuscatedCode = ""; try { BodyDeclaration md = StaticJavaParser.parseBodyDeclaration(code); md.accept(new ObfuscatorVisitor(), null); obfuscatedCode = md.toString(); } catch (Exception e) { config.getLog().error("Failed to obfuscate method source code: " + e); } return obfuscatedCode; } public String obfuscateJava(String code) { if (code == "") { return ""; } String obfuscatedCode = ""; try { CompilationUnit cu = StaticJavaParser.parse(code); PackageDeclaration pd = cu.getPackageDeclaration().orElse(null); if (pd != null) { String packageName = pd.getNameAsString(); String obfuscatedPackage = Arrays.stream(packageName.split("\\.")).map(this::caesarCipher).collect(Collectors.joining(".")); putCryptoMap(packageName, obfuscatedPackage); pd.setName(obfuscatedPackage); } List<ImportDeclaration> imports = cu.getImports(); if (imports != null) { imports.forEach(id -> { if (SymbolFrame.isInGroup(id.toString(), targetGroupIds)) { String importName = id.getNameAsString(); String obfuscatedId = Arrays.stream(importName.split("\\.")).map(this::caesarCipher).collect(Collectors.joining(".")); id.setName(obfuscatedId); putCryptoMap(importName, obfuscatedId); } }); } cu.accept(new ObfuscatorVisitor(), null); obfuscatedCode = cu.toString(); } catch (Exception e) { //TODO: solve dep constructors and methods code config.getLog().error("Failed to obfuscate code: " + e); } return obfuscatedCode; } public String deobfuscateJava(String code) { if (code == "") { return ""; } String obfuscatedCode = ""; try { CompilationUnit cu = StaticJavaParser.parse(code); PackageDeclaration pd = cu.getPackageDeclaration().orElseThrow(); String packageName = pd.getNameAsString(); String deobfuscatedPackage = decryptName(packageName); pd.setName(deobfuscatedPackage); List<ImportDeclaration> imports = cu.getImports(); List<ImportDeclaration> toRemove = new ArrayList<>(); if (imports != null) { imports.forEach(id -> { String importName = id.getNameAsString(); String deobfuscatedId = decryptName(importName); if (deobfuscatedId.split("\\.")[0].equals(encryptName(packageName.split("\\.")[0]))) { toRemove.add(id); } else { id.setName(deobfuscatedId); } }); } toRemove.forEach(id -> id.remove()); cu.accept(new DeobfuscatorVisitor(), null); obfuscatedCode = cu.toString(); } catch (Exception e) { config.getLog().error("Failed to deobfuscate code: " + e); e.printStackTrace(); } return obfuscatedCode; } public String obfuscateName(String name) { if (name.contains("\\.")) { String[] names = name.split("\\."); String obfuscatedName = Arrays.stream(names).map(this::caesarCipher).collect(Collectors.joining(".")); putCryptoMap(name, obfuscatedName); return obfuscatedName; } else { return encryptName(name); } } public String deobfuscateName(String name) { return decryptName(name); } public String obfuscateSig(String sig) { return obfuscateString(sig); } public String deobfuscateSig(String sig) { return deobfuscateString(sig); } public String obfuscateText(String text) { return obfuscateString(text); } public String deobfuscateText(String text) { return deobfuscateString(text); } public String obfuscateString(String str) { if (cryptoMap.size() == 0) { throw new RuntimeException("Crypto map is empty! Must run obfuscateJava first!"); } try { for (String key : cryptoMap.keySet()) { str = str.replaceAll(capitalize(key), capitalize(cryptoMap.get(key))); str = str.replaceAll(decapitalize(key), decapitalize(cryptoMap.get(key))); } } catch (Exception e) { config.getLog().error("Failed to obfuscate String: " + e); } return str; } public String deobfuscateString(String str) { if (cryptoMap.size() == 0) { throw new RuntimeException("Crypto map is empty! Must run obfuscateJava first!"); } try { for (String key : cryptoMap.keySet()) { if (key.length() < 4) { continue; } // process the upper case and lower case of the crypto string. str = str.replaceAll(capitalize(cryptoMap.get(key)), capitalize(key)); str = str.replaceAll(decapitalize(cryptoMap.get(key)), decapitalize(key)); } } catch (Exception e) { config.getLog().error("Failed to deobfuscate String: " + e); } return str; } public Map<String, String> obfuscateDep(Map<String, String> dep) { Map<String, String> obfuscatedDep = new HashMap<>(); for (String key : dep.keySet()) { SymbolFrame sf = findSymbolFrameByClass(key); if (sf == null) { continue; } sf.toObNames(targetGroupIds).forEach(name -> { encryptName(name); }); obfuscatedDep.put(obfuscateName(key), obfuscateJava(dep.get(key))); } return obfuscatedDep; } public Map<String, String> deobfuscateDep(Map<String, String> dep) { Map<String, String> deobfuscatedDep = new HashMap<>(); for (String key : dep.keySet()) { deobfuscatedDep.put(deobfuscateName(key), deobfuscateJava(dep.get(key))); } return deobfuscatedDep; } public TestMessage obfuscateTestMessage(TestMessage msg) { if (msg == null) { return null; } msg.setErrorMessage(msg.getErrorMessage().stream().map(this::obfuscateText).collect(Collectors.toList())); return msg; } public TestMessage deobfuscateTestMessage(TestMessage msg) { if (msg == null) { return null; } msg.setErrorMessage(msg.getErrorMessage().stream().map(this::deobfuscateText).collect(Collectors.toList())); return msg; } private String encryptName(String oldName) { if (symbolFrame == null) { throw new RuntimeException("Symbol frames are not initialized!"); } if (cryptoMap.containsKey(oldName)) { return cryptoMap.get(oldName); } if (oldName.length() < 4) { return oldName; } if (oldName.startsWith("set") || oldName.startsWith("get") || oldName.startsWith("is") || oldName.startsWith("has")) { String prefix = ""; if (oldName.startsWith("is")) { prefix = oldName.substring(0, 2); } else { prefix = oldName.substring(0, 3); } String suffix = oldName.substring(prefix.length()); String newName = prefix + caesarCipher(suffix); putCryptoMap(oldName, newName); return newName; } else { String newName = caesarCipher(oldName); putCryptoMap(oldName, newName); return newName; } } private String encryptIfExist(String oldName) { if (symbolFrame == null) { throw new RuntimeException("Symbol frames are not initialized!"); } if (cryptoMap.containsKey(oldName)) { return cryptoMap.get(oldName); } return oldName; } // Caesar Cipher private String caesarCipher(String old) { StringBuilder sb = new StringBuilder(); for (char c : old.toCharArray()) { if (c >= 'a' && c < 'z' || c >= 'A' && c < 'Z') { sb.append((char) (c + this.shift)); } else if (c == 'z') { sb.append('a'); } else if (c == 'Z') { sb.append('A'); } else { sb.append(c); } } return sb.toString(); } private String decryptName(String oldName) { if (this.reversedMap == null) { this.reversedMap = createReversedMap(this.cryptoMap); } if (this.allCaseMap == null) { this.allCaseMap = createAllCaseMap(this.reversedMap); } if (allCaseMap.containsKey(oldName)) { return allCaseMap.get(oldName); } return oldName; } // TODO: export to json public Map<String, SymbolFrame> generateSymbolFrames() { Set<ClassNode> candidateClasses = new HashSet<>(); ASMParser asmParser = new ASMParser(config); Map<String, SymbolFrame> symbolFrames = new HashMap<>(); try { Path artifactPath = config.getProject().getArtifactPath(); JarFile projectJar = new JarFile(artifactPath.toString()); candidateClasses.addAll(asmParser.loadClasses(projectJar)); for (ClassNode classNode : candidateClasses) { String className = classNode.name; if (!SymbolFrame.isClassInGroup(className, targetGroupIds)) { continue; }
SymbolAnalyzer analyzer = new SymbolAnalyzer();
5
2023-10-14 07:15:10+00:00
16k
ProjectgamesOOP/Adventure_to_the_Fallen_Kingdom
src/gamestates/Playing.java
[ { "identifier": "LevelManager", "path": "src/Level/LevelManager.java", "snippet": "public class LevelManager {\n\n\tprivate Game game;\n\tprivate BufferedImage[] levelSprite;\n\tprivate ArrayList<levels> Levels;\n\tprivate int lvlIndex = 0;\n\n\tpublic LevelManager(Game game) {\n\t\tthis.game = game;\n\...
import Level.LevelManager; import UI.GameOverOverlay; import UI.LevelCompleted; import UI.PauseOverlay; import entities.EnemyManager; import entities.Player; import main.Game; import utilz.LoadSave; import objects.ObjectManager; import java.awt.Color; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.Random; import static utilz.Constants.Environment.*;
11,833
package gamestates; public class Playing extends State implements Statemethods { private Player player; private LevelManager levelManager; private EnemyManager enemyManager;
package gamestates; public class Playing extends State implements Statemethods { private Player player; private LevelManager levelManager; private EnemyManager enemyManager;
private PauseOverlay pauseOverlay;
3
2023-10-07 12:07:45+00:00
16k
yc-huang/bsdb
src/main/java/it/unimi/dsi/sux4j/mph/GOVMinimalPerfectHashFunctionModified.java
[ { "identifier": "ConcurrentBucketedHashStore", "path": "src/main/java/it/unimi/dsi/sux4j/io/ConcurrentBucketedHashStore.java", "snippet": "public class ConcurrentBucketedHashStore<T> implements Serializable, SafelyCloseable, Iterable<ConcurrentBucketedHashStore.Bucket> {\n public static final long se...
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.Serializable; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Iterator; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.zip.GZIPInputStream; import org.apache.commons.math3.random.RandomGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.martiansoftware.jsap.FlaggedOption; import com.martiansoftware.jsap.JSAP; import com.martiansoftware.jsap.JSAPException; import com.martiansoftware.jsap.JSAPResult; import com.martiansoftware.jsap.Parameter; import com.martiansoftware.jsap.SimpleJSAP; import com.martiansoftware.jsap.Switch; import com.martiansoftware.jsap.UnflaggedOption; import com.martiansoftware.jsap.stringparsers.FileStringParser; import com.martiansoftware.jsap.stringparsers.ForNameStringParser; import it.unimi.dsi.Util; import it.unimi.dsi.bits.LongArrayBitVector; import it.unimi.dsi.bits.TransformationStrategies; import it.unimi.dsi.bits.TransformationStrategy; import it.unimi.dsi.fastutil.io.BinIO; import it.unimi.dsi.fastutil.longs.LongBigList; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.io.FileLinesByteArrayIterable; import it.unimi.dsi.io.FileLinesMutableStringIterable; import it.unimi.dsi.logging.ProgressLogger; import it.unimi.dsi.sux4j.io.ConcurrentBucketedHashStore; import it.unimi.dsi.sux4j.io.ConcurrentBucketedHashStore.Bucket; import it.unimi.dsi.sux4j.io.ConcurrentBucketedHashStore.DuplicateException; import it.unimi.dsi.sux4j.mph.solve.Linear3SystemSolver; import it.unimi.dsi.sux4j.mph.solve.Orient3Hypergraph; import it.unimi.dsi.util.XoRoShiRo128PlusRandomGenerator; import it.unimi.dsi.util.concurrent.ReorderingBlockingQueue;
11,147
/* * Sux4J: Succinct data structures for Java * * Copyright (C) 2016-2022 Sebastiano Vigna * * This program and the accompanying materials are made available under the * terms of the GNU Lesser General Public License v2.1 or later, * which is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html, * or the Apache Software License 2.0, which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * 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. * * SPDX-License-Identifier: LGPL-2.1-or-later OR Apache-2.0 */ package it.unimi.dsi.sux4j.mph; /** * Modified to use ConcurrentBucketedHashStore instead of BucketedHashStore. * * A minimal perfect hash function stored using the {@linkplain Linear3SystemSolver * Genuzio-Ottaviano-Vigna 3-regular <b>F</b><sub>3</sub>-linear system technique}. It is the * fastest minimal perfect hash function available with space close to 2 bits per key. * * <P> * Given a list of keys without duplicates, the {@linkplain Builder builder} of this class finds a * minimal perfect hash function for the list. Subsequent calls to the {@link #getLong(Object)} * method will return a distinct number for each key in the list. For keys out of the list, the * resulting number is not specified. In some (rare) cases it might be possible to establish that a * key was not in the original list, and in that case -1 will be returned; by <em>signing</em> the * function (see below), you can guarantee with a prescribed probability that -1 will be returned on * keys not in the original list. The class can then be saved by serialisation and reused later. * * <p> * This class uses a {@linkplain ConcurrentBucketedHashStore bucketed hash store} to provide highly scalable * construction. Note that at construction time you can {@linkplain Builder#store(ConcurrentBucketedHashStore) * pass a BucketedHashStore} containing the keys (associated with any value); however, if the store * is rebuilt because of a {@link DuplicateException} it * will be rebuilt associating with each key its ordinal position. * * <P> * For convenience, this class provides a main method that reads from standard input a (possibly * <code>gzip</code>'d) sequence of newline-separated strings, and writes a serialised minimal * perfect hash function for the given list. * * <h2>Signing</h2> * * <p> * Optionally, it is possible to {@linkplain Builder#signed(int) <em>sign</em>} the minimal perfect * hash function. A <var>w</var>-bit signature will be associated with each key, so that * {@link #getLong(Object)} will return -1 on strings that are not in the original key set. As * usual, false positives are possible with probability 2<sup>-<var>w</var></sup>. * * <h2>Multithreading</h2> * * <p> * This implementation is multithreaded: each bucket returned by the {@link ConcurrentBucketedHashStore} is * processed independently. By default, this class uses {@link Runtime#availableProcessors()} * parallel threads, but by default no more than 4. If you wish to set a specific number of threads, * you can do so through the system property {@value #NUMBER_OF_THREADS_PROPERTY}. * * <h2>How it Works</h2> * * <p> * The detail of the data structure can be found in &ldquo;Fast Scalable Construction of (Minimal * Perfect Hash) Functions&rdquo;, by Marco Genuzio, Giuseppe Ottaviano and Sebastiano Vigna, * <i>15th International Symposium on Experimental Algorithms &mdash; SEA 2016</i>, Lecture Notes in * Computer Science, Springer, 2016. We generate a random 3-regular hypergraph and give it an * {@linkplain Orient3Hypergraph orientation}. From the orientation, we generate a random linear * system on <b>F</b><sub>3</sub>, where the variables in the <var>k</var>-th equation are the * vertices of the <var>k</var>-th hyperedge, and the known term of the <var>k</var>-th equation is * the vertex giving orientation to the <var>k</var>-th hyperedge. Then, we * {@linkplain Linear3SystemSolver solve the system} and store the solution, which provides a * perfect hash function. * * <p> * To obtain a minimal perfect hash function, we simply notice that we whenever we have to assign a * value to a vertex, we can take care of using the number 3 instead of 0 if the vertex is actually * the output value for some key. The final value of the minimal perfect hash function is the number * of nonzero pairs of bits that precede the perfect hash value for the key. To compute this number, * we use use in each bucket {@linkplain #countNonzeroPairs(long) broadword programming}. * * Since the system must have &#8776;10% more variables than equations to be solvable, a * {@link GOVMinimalPerfectHashFunctionModified} on <var>n</var> keys requires 2.2<var>n</var> bits. * * @author Sebastiano Vigna * @since 4.0.0 */ public class GOVMinimalPerfectHashFunctionModified<T> extends AbstractHashFunction<T> implements Serializable { public static final long serialVersionUID = 6L; private static final Logger LOGGER = LoggerFactory.getLogger(GOVMinimalPerfectHashFunctionModified.class); private static final LongArrayBitVector END_OF_SOLUTION_QUEUE = LongArrayBitVector.getInstance();
/* * Sux4J: Succinct data structures for Java * * Copyright (C) 2016-2022 Sebastiano Vigna * * This program and the accompanying materials are made available under the * terms of the GNU Lesser General Public License v2.1 or later, * which is available at * http://www.gnu.org/licenses/old-licenses/lgpl-2.1-standalone.html, * or the Apache Software License 2.0, which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * 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. * * SPDX-License-Identifier: LGPL-2.1-or-later OR Apache-2.0 */ package it.unimi.dsi.sux4j.mph; /** * Modified to use ConcurrentBucketedHashStore instead of BucketedHashStore. * * A minimal perfect hash function stored using the {@linkplain Linear3SystemSolver * Genuzio-Ottaviano-Vigna 3-regular <b>F</b><sub>3</sub>-linear system technique}. It is the * fastest minimal perfect hash function available with space close to 2 bits per key. * * <P> * Given a list of keys without duplicates, the {@linkplain Builder builder} of this class finds a * minimal perfect hash function for the list. Subsequent calls to the {@link #getLong(Object)} * method will return a distinct number for each key in the list. For keys out of the list, the * resulting number is not specified. In some (rare) cases it might be possible to establish that a * key was not in the original list, and in that case -1 will be returned; by <em>signing</em> the * function (see below), you can guarantee with a prescribed probability that -1 will be returned on * keys not in the original list. The class can then be saved by serialisation and reused later. * * <p> * This class uses a {@linkplain ConcurrentBucketedHashStore bucketed hash store} to provide highly scalable * construction. Note that at construction time you can {@linkplain Builder#store(ConcurrentBucketedHashStore) * pass a BucketedHashStore} containing the keys (associated with any value); however, if the store * is rebuilt because of a {@link DuplicateException} it * will be rebuilt associating with each key its ordinal position. * * <P> * For convenience, this class provides a main method that reads from standard input a (possibly * <code>gzip</code>'d) sequence of newline-separated strings, and writes a serialised minimal * perfect hash function for the given list. * * <h2>Signing</h2> * * <p> * Optionally, it is possible to {@linkplain Builder#signed(int) <em>sign</em>} the minimal perfect * hash function. A <var>w</var>-bit signature will be associated with each key, so that * {@link #getLong(Object)} will return -1 on strings that are not in the original key set. As * usual, false positives are possible with probability 2<sup>-<var>w</var></sup>. * * <h2>Multithreading</h2> * * <p> * This implementation is multithreaded: each bucket returned by the {@link ConcurrentBucketedHashStore} is * processed independently. By default, this class uses {@link Runtime#availableProcessors()} * parallel threads, but by default no more than 4. If you wish to set a specific number of threads, * you can do so through the system property {@value #NUMBER_OF_THREADS_PROPERTY}. * * <h2>How it Works</h2> * * <p> * The detail of the data structure can be found in &ldquo;Fast Scalable Construction of (Minimal * Perfect Hash) Functions&rdquo;, by Marco Genuzio, Giuseppe Ottaviano and Sebastiano Vigna, * <i>15th International Symposium on Experimental Algorithms &mdash; SEA 2016</i>, Lecture Notes in * Computer Science, Springer, 2016. We generate a random 3-regular hypergraph and give it an * {@linkplain Orient3Hypergraph orientation}. From the orientation, we generate a random linear * system on <b>F</b><sub>3</sub>, where the variables in the <var>k</var>-th equation are the * vertices of the <var>k</var>-th hyperedge, and the known term of the <var>k</var>-th equation is * the vertex giving orientation to the <var>k</var>-th hyperedge. Then, we * {@linkplain Linear3SystemSolver solve the system} and store the solution, which provides a * perfect hash function. * * <p> * To obtain a minimal perfect hash function, we simply notice that we whenever we have to assign a * value to a vertex, we can take care of using the number 3 instead of 0 if the vertex is actually * the output value for some key. The final value of the minimal perfect hash function is the number * of nonzero pairs of bits that precede the perfect hash value for the key. To compute this number, * we use use in each bucket {@linkplain #countNonzeroPairs(long) broadword programming}. * * Since the system must have &#8776;10% more variables than equations to be solvable, a * {@link GOVMinimalPerfectHashFunctionModified} on <var>n</var> keys requires 2.2<var>n</var> bits. * * @author Sebastiano Vigna * @since 4.0.0 */ public class GOVMinimalPerfectHashFunctionModified<T> extends AbstractHashFunction<T> implements Serializable { public static final long serialVersionUID = 6L; private static final Logger LOGGER = LoggerFactory.getLogger(GOVMinimalPerfectHashFunctionModified.class); private static final LongArrayBitVector END_OF_SOLUTION_QUEUE = LongArrayBitVector.getInstance();
private static final Bucket END_OF_BUCKET_QUEUE = new Bucket();
1
2023-10-07 03:32:27+00:00
16k
wise-old-man/wiseoldman-runelite-plugin
src/main/java/net/wiseoldman/panel/TableRow.java
[ { "identifier": "Format", "path": "src/main/java/net/wiseoldman/util/Format.java", "snippet": "public class Format\n{\n public static String formatNumber(long num)\n {\n if ((num < 10000 && num > -10000))\n {\n return QuantityFormatter.formatNumber(num);\n }\n\n ...
import net.wiseoldman.util.Format; import net.wiseoldman.util.Utils; import net.wiseoldman.WomUtilsPlugin; import net.wiseoldman.beans.Boss; import net.wiseoldman.beans.Activity; import net.wiseoldman.beans.Skill; import lombok.extern.slf4j.Slf4j; import net.runelite.api.Experience; import net.runelite.client.ui.ColorScheme; import net.runelite.client.ui.FontManager; import net.runelite.client.util.ImageUtil; import net.runelite.client.util.QuantityFormatter; import net.runelite.client.hiscore.HiscoreSkill; import net.runelite.client.hiscore.HiscoreSkillType; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.util.HashMap; import java.util.Map;
11,440
/* * Copyright (c) 2021, Rorro <https://github.com/rorro> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.wiseoldman.panel; @Slf4j public class TableRow extends JPanel { private static final int ICON_WIDTH = 35; Map<String, JLabel> labels = new HashMap<>(); TableRow(String name, String formattedName, HiscoreSkillType type, String... labels) { setLayout(new BorderLayout()); setBorder(new EmptyBorder(2, 0, 2, 0)); setBackground(ColorScheme.DARKER_GRAY_COLOR); JPanel dataPanel = new JPanel(new GridLayout()); dataPanel.setOpaque(false); final String directory; if (type == HiscoreSkillType.BOSS) { directory = "bosses/"; } else if (type == HiscoreSkillType.ACTIVITY) { directory = "activities/"; } else { directory = "/skill_icons_small/"; } for (String l : labels) { dataPanel.add(createCell(l)); } String iconDirectory = directory + name.toLowerCase() + ".png"; log.debug("Loading icon for {}", iconDirectory); JPanel iconPanel = new JPanel(new BorderLayout()); iconPanel.setOpaque(false); JLabel iconLabel = new JLabel("", SwingConstants.CENTER); iconPanel.add(iconLabel); ImageIcon icon = new ImageIcon(ImageUtil.loadImageResource(WomUtilsPlugin.class, iconDirectory)); iconPanel.setPreferredSize(new Dimension(ICON_WIDTH, icon.getIconHeight())); iconLabel.setIcon(icon); iconLabel.setToolTipText(formattedName); add(iconPanel, BorderLayout.WEST); add(dataPanel); } private JLabel createCell(String l) { JLabel label = new JLabel("--", SwingConstants.CENTER); label.setFont(FontManager.getRunescapeSmallFont()); labels.put(l, label); return label; } void update(Skill skill, boolean virtualLevels) { long experience = skill.getExperience(); int level = skill.getLevel(); int rank = skill.getRank(); boolean ranked = rank != -1; double ehp = skill.getEhp(); JLabel experienceLabel = labels.get("experience"); experienceLabel.setText(experience > 0 ? Format.formatNumber(experience) : "--"); experienceLabel.setToolTipText(experience > 0 ? QuantityFormatter.formatNumber(experience) : ""); JLabel levelLabel = labels.get("level"); int levelToDisplay = !virtualLevels && level > Experience.MAX_REAL_LEVEL ? Experience.MAX_REAL_LEVEL : level; levelLabel.setText(String.valueOf(levelToDisplay)); levelLabel.setToolTipText(String.valueOf(levelToDisplay)); JLabel rankLabel = labels.get("rank"); rankLabel.setText(ranked ? Format.formatNumber(rank) : "--"); rankLabel.setToolTipText(ranked ? QuantityFormatter.formatNumber(rank) : "Unranked"); JLabel ehpLabel = labels.get("ehp"); ehpLabel.setText(Format.formatNumber(ehp)); ehpLabel.setToolTipText(QuantityFormatter.formatNumber(ehp)); }
/* * Copyright (c) 2021, Rorro <https://github.com/rorro> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.wiseoldman.panel; @Slf4j public class TableRow extends JPanel { private static final int ICON_WIDTH = 35; Map<String, JLabel> labels = new HashMap<>(); TableRow(String name, String formattedName, HiscoreSkillType type, String... labels) { setLayout(new BorderLayout()); setBorder(new EmptyBorder(2, 0, 2, 0)); setBackground(ColorScheme.DARKER_GRAY_COLOR); JPanel dataPanel = new JPanel(new GridLayout()); dataPanel.setOpaque(false); final String directory; if (type == HiscoreSkillType.BOSS) { directory = "bosses/"; } else if (type == HiscoreSkillType.ACTIVITY) { directory = "activities/"; } else { directory = "/skill_icons_small/"; } for (String l : labels) { dataPanel.add(createCell(l)); } String iconDirectory = directory + name.toLowerCase() + ".png"; log.debug("Loading icon for {}", iconDirectory); JPanel iconPanel = new JPanel(new BorderLayout()); iconPanel.setOpaque(false); JLabel iconLabel = new JLabel("", SwingConstants.CENTER); iconPanel.add(iconLabel); ImageIcon icon = new ImageIcon(ImageUtil.loadImageResource(WomUtilsPlugin.class, iconDirectory)); iconPanel.setPreferredSize(new Dimension(ICON_WIDTH, icon.getIconHeight())); iconLabel.setIcon(icon); iconLabel.setToolTipText(formattedName); add(iconPanel, BorderLayout.WEST); add(dataPanel); } private JLabel createCell(String l) { JLabel label = new JLabel("--", SwingConstants.CENTER); label.setFont(FontManager.getRunescapeSmallFont()); labels.put(l, label); return label; } void update(Skill skill, boolean virtualLevels) { long experience = skill.getExperience(); int level = skill.getLevel(); int rank = skill.getRank(); boolean ranked = rank != -1; double ehp = skill.getEhp(); JLabel experienceLabel = labels.get("experience"); experienceLabel.setText(experience > 0 ? Format.formatNumber(experience) : "--"); experienceLabel.setToolTipText(experience > 0 ? QuantityFormatter.formatNumber(experience) : ""); JLabel levelLabel = labels.get("level"); int levelToDisplay = !virtualLevels && level > Experience.MAX_REAL_LEVEL ? Experience.MAX_REAL_LEVEL : level; levelLabel.setText(String.valueOf(levelToDisplay)); levelLabel.setToolTipText(String.valueOf(levelToDisplay)); JLabel rankLabel = labels.get("rank"); rankLabel.setText(ranked ? Format.formatNumber(rank) : "--"); rankLabel.setToolTipText(ranked ? QuantityFormatter.formatNumber(rank) : "Unranked"); JLabel ehpLabel = labels.get("ehp"); ehpLabel.setText(Format.formatNumber(ehp)); ehpLabel.setToolTipText(QuantityFormatter.formatNumber(ehp)); }
void update(Boss boss, HiscoreSkill b)
3
2023-10-09 14:23:06+00:00
16k
ProfessorFichte/More-RPG-Classes
src/main/java/net/more_rpg_classes/MRPGCMod.java
[ { "identifier": "MoreParticles", "path": "src/main/java/net/more_rpg_classes/client/particle/MoreParticles.java", "snippet": "public class MoreParticles {\n public static final DefaultParticleType IGNI_SIGN = FabricParticleTypes.simple();\n public static final DefaultParticleType AARD_SIGN = Fabri...
import net.fabricmc.api.ModInitializer; import net.more_rpg_classes.client.particle.MoreParticles; import net.more_rpg_classes.custom.custom_spells.CustomSpells; import net.more_rpg_classes.effect.MRPGCEffects; import net.more_rpg_classes.entity.attribute.MRPGCEntityAttributes; import net.more_rpg_classes.item.MRPGCBooks; import net.more_rpg_classes.item.MRPGCGroup; import net.more_rpg_classes.item.MRPGCItems; import net.more_rpg_classes.sounds.ModSounds; import net.more_rpg_classes.util.MRPGCLootTableChestModifiers; import net.more_rpg_classes.util.MRPGCLootTableEntityModifiers; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
11,436
package net.more_rpg_classes; public class MRPGCMod implements ModInitializer { public static final String MOD_ID = "more_rpg_classes"; public static final Logger LOGGER = LoggerFactory.getLogger("more_rpg_classes"); @Override public void onInitialize() { MRPGCItems.registerModItems(); MRPGCGroup.registerItemGroups(); MRPGCLootTableEntityModifiers.modifyLootEntityTables();
package net.more_rpg_classes; public class MRPGCMod implements ModInitializer { public static final String MOD_ID = "more_rpg_classes"; public static final Logger LOGGER = LoggerFactory.getLogger("more_rpg_classes"); @Override public void onInitialize() { MRPGCItems.registerModItems(); MRPGCGroup.registerItemGroups(); MRPGCLootTableEntityModifiers.modifyLootEntityTables();
MRPGCLootTableChestModifiers.modifyChestLootTables();
8
2023-10-14 12:44:07+00:00
16k
nexus3a/monitor-remote-agent
src/main/java/com/monitor/agent/server/handler/AccessibilityHandler.java
[ { "identifier": "DirectoryWatcher", "path": "src/main/java/com/monitor/agent/server/DirectoryWatcher.java", "snippet": "public class DirectoryWatcher {\r\n \r\n private static final Logger logger = Logger.getLogger(DirectoryWatcher.class);\r\n \r\n private final Map<DirectoryChangeListener, ...
import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.FilenameUtils; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import com.monitor.agent.server.DirectoryWatcher; import com.monitor.agent.server.Server; import com.monitor.agent.server.config.ConfigurationManager; import com.monitor.agent.server.config.FilesConfig; import com.monitor.agent.server.config.OneCServerConfig; import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.router.RouterNanoHTTPD; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet;
13,193
package com.monitor.agent.server.handler; /* * Copyright 2022 Aleksei Andreev * * 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. * */ public class AccessibilityHandler extends DefaultResponder { private static final String TEST_FILE_NAME = ".monitor-remote-agent-test"; private static final String AGENT_WORKDIR_MASK = "\\$\\{agent-path\\}"; private static final String AGENT_CONFIG_MASK = "\\$\\{agent-config\\}"; private static class PathCheckResult { String wildcard; String path; boolean unexpected = false; boolean exists = false; boolean created = false; boolean read = false; boolean write = false; String exception = ""; String testfile = ""; public String getWildcard() { return wildcard; } public String getPath() { return path; } public boolean isUnexpected() { return unexpected; } public boolean isExists() { return exists; } public boolean isCreated() { return created; } public boolean isRead() { return read; } public boolean isWrite() { return write; } public String getException() { return exception; } public String getTestfile() { return testfile; } } private static class SectionTests { String section; List<List<PathCheckResult>> tests = new ArrayList<>(); public String getSection() { return section; } public List<List<PathCheckResult>> getTests() { return tests; } } private static class OneCServerPathsTests { @JsonProperty("address") String server1c; List<SectionTests> sections = new ArrayList<>(); @JsonProperty("logcfg path test") PathCheckResult logCfgPathTest; public String getServer1c() { return server1c; } public List<SectionTests> getSections() { return sections; } public PathCheckResult getLogCfgPathTest() { return logCfgPathTest; } } private static class ConfigTests { List<List<PathCheckResult>> tests = new ArrayList<>(); @JsonProperty("1c servers") List<OneCServerPathsTests> servers = new ArrayList<>(); @JsonProperty("agent path test") PathCheckResult agentPathTest; public List<List<PathCheckResult>> getTests() { return tests; } public List<OneCServerPathsTests> getServers() { return servers; } public PathCheckResult getAgentPathTest() { return agentPathTest; } } private static String getTestFileName(File directory, String testFileWildcard) { if (testFileWildcard == null || testFileWildcard.isEmpty() || "*.*".equals(testFileWildcard)) { String fileName = TEST_FILE_NAME; for (int suffix = 0; suffix < 1000; suffix++) { File file = new File(directory, fileName); if (!file.exists()) { break; } fileName = TEST_FILE_NAME + "-" + String.valueOf(suffix); } return fileName; } if (testFileWildcard.contains("*") || testFileWildcard.contains("?")) { String fileName = null; for (int suffix = 0; suffix < 1000; suffix++) { fileName = testFileWildcard.replaceAll("\\*", String.valueOf(suffix)).replaceAll("\\?", "_"); File file = new File(directory, fileName); if (!file.exists()) { break; } } return fileName; } return testFileWildcard; } private static List<PathCheckResult> checkWildcard(String filesToWatch) { List<PathCheckResult> results = new ArrayList<>(); String directoryWildcard = FilenameUtils.getFullPath(filesToWatch); String testFileName = FilenameUtils.getName(filesToWatch);
package com.monitor.agent.server.handler; /* * Copyright 2022 Aleksei Andreev * * 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. * */ public class AccessibilityHandler extends DefaultResponder { private static final String TEST_FILE_NAME = ".monitor-remote-agent-test"; private static final String AGENT_WORKDIR_MASK = "\\$\\{agent-path\\}"; private static final String AGENT_CONFIG_MASK = "\\$\\{agent-config\\}"; private static class PathCheckResult { String wildcard; String path; boolean unexpected = false; boolean exists = false; boolean created = false; boolean read = false; boolean write = false; String exception = ""; String testfile = ""; public String getWildcard() { return wildcard; } public String getPath() { return path; } public boolean isUnexpected() { return unexpected; } public boolean isExists() { return exists; } public boolean isCreated() { return created; } public boolean isRead() { return read; } public boolean isWrite() { return write; } public String getException() { return exception; } public String getTestfile() { return testfile; } } private static class SectionTests { String section; List<List<PathCheckResult>> tests = new ArrayList<>(); public String getSection() { return section; } public List<List<PathCheckResult>> getTests() { return tests; } } private static class OneCServerPathsTests { @JsonProperty("address") String server1c; List<SectionTests> sections = new ArrayList<>(); @JsonProperty("logcfg path test") PathCheckResult logCfgPathTest; public String getServer1c() { return server1c; } public List<SectionTests> getSections() { return sections; } public PathCheckResult getLogCfgPathTest() { return logCfgPathTest; } } private static class ConfigTests { List<List<PathCheckResult>> tests = new ArrayList<>(); @JsonProperty("1c servers") List<OneCServerPathsTests> servers = new ArrayList<>(); @JsonProperty("agent path test") PathCheckResult agentPathTest; public List<List<PathCheckResult>> getTests() { return tests; } public List<OneCServerPathsTests> getServers() { return servers; } public PathCheckResult getAgentPathTest() { return agentPathTest; } } private static String getTestFileName(File directory, String testFileWildcard) { if (testFileWildcard == null || testFileWildcard.isEmpty() || "*.*".equals(testFileWildcard)) { String fileName = TEST_FILE_NAME; for (int suffix = 0; suffix < 1000; suffix++) { File file = new File(directory, fileName); if (!file.exists()) { break; } fileName = TEST_FILE_NAME + "-" + String.valueOf(suffix); } return fileName; } if (testFileWildcard.contains("*") || testFileWildcard.contains("?")) { String fileName = null; for (int suffix = 0; suffix < 1000; suffix++) { fileName = testFileWildcard.replaceAll("\\*", String.valueOf(suffix)).replaceAll("\\?", "_"); File file = new File(directory, fileName); if (!file.exists()) { break; } } return fileName; } return testFileWildcard; } private static List<PathCheckResult> checkWildcard(String filesToWatch) { List<PathCheckResult> results = new ArrayList<>(); String directoryWildcard = FilenameUtils.getFullPath(filesToWatch); String testFileName = FilenameUtils.getName(filesToWatch);
DirectoryWatcher watcher = new DirectoryWatcher();
0
2023-10-11 20:25:12+00:00
16k
giteecode/bookmanage2-public
nhXJH-framework/src/main/java/com/nhXJH/framework/manager/factory/AsyncFactory.java
[ { "identifier": "Constants", "path": "nhXJH-common/src/main/java/com/nhXJH/common/constant/Constants.java", "snippet": "public class Constants {\n /**\n * UTF-8 字符集\n */\n public static final String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n public static final String GBK =...
import java.util.TimerTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.nhXJH.common.constant.Constants; import com.nhXJH.common.utils.LogUtils; import com.nhXJH.common.utils.ServletUtils; import com.nhXJH.common.utils.StringUtils; import com.nhXJH.common.utils.ip.AddressUtils; import com.nhXJH.common.utils.ip.IpUtils; import com.nhXJH.common.utils.spring.SpringUtils; import com.nhXJH.system.domain.SysLogininfor; import com.nhXJH.system.domain.SysOperLog; import com.nhXJH.system.service.ISysLogininforService; import com.nhXJH.system.service.ISysOperLogService; import eu.bitwalker.useragentutils.UserAgent;
12,078
package com.nhXJH.framework.manager.factory; /** * 异步工厂(产生任务用) * * @author nhXJH */ public class AsyncFactory { private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user"); /** * 记录登录信息 * * @param username 用户名 * @param status 状态 * @param message 消息 * @param args 列表 * @return 任务task */ public static TimerTask recordLogininfor(final String username, final String status, final String message, final Object... args) { final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")); final String ip = IpUtils.getIpAddr(ServletUtils.getRequest()); return new TimerTask() { @Override public void run() { String address = AddressUtils.getRealAddressByIP(ip); StringBuilder s = new StringBuilder(); s.append(LogUtils.getBlock(ip)); s.append(address); s.append(LogUtils.getBlock(username)); s.append(LogUtils.getBlock(status)); s.append(LogUtils.getBlock(message)); // 打印信息到日志 sys_user_logger.info(s.toString(), args); // 获取客户端操作系统 String os = userAgent.getOperatingSystem().getName(); // 获取客户端浏览器 String browser = userAgent.getBrowser().getName(); // 封装对象 SysLogininfor logininfor = new SysLogininfor(); logininfor.setUserName(username); logininfor.setIpaddr(ip); logininfor.setLoginLocation(address); logininfor.setBrowser(browser); logininfor.setOs(os); logininfor.setMsg(message); // 日志状态 if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) { logininfor.setStatus(Constants.SUCCESS); } else if (Constants.LOGIN_FAIL.equals(status)) { logininfor.setStatus(Constants.FAIL); } // 插入数据 SpringUtils.getBean(ISysLogininforService.class).insertLogininfor(logininfor); } }; } /** * 操作日志记录 * * @param operLog 操作日志信息 * @return 任务task */ public static TimerTask recordOper(final SysOperLog operLog) { return new TimerTask() { @Override public void run() { // 远程查询操作地点 operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
package com.nhXJH.framework.manager.factory; /** * 异步工厂(产生任务用) * * @author nhXJH */ public class AsyncFactory { private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user"); /** * 记录登录信息 * * @param username 用户名 * @param status 状态 * @param message 消息 * @param args 列表 * @return 任务task */ public static TimerTask recordLogininfor(final String username, final String status, final String message, final Object... args) { final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")); final String ip = IpUtils.getIpAddr(ServletUtils.getRequest()); return new TimerTask() { @Override public void run() { String address = AddressUtils.getRealAddressByIP(ip); StringBuilder s = new StringBuilder(); s.append(LogUtils.getBlock(ip)); s.append(address); s.append(LogUtils.getBlock(username)); s.append(LogUtils.getBlock(status)); s.append(LogUtils.getBlock(message)); // 打印信息到日志 sys_user_logger.info(s.toString(), args); // 获取客户端操作系统 String os = userAgent.getOperatingSystem().getName(); // 获取客户端浏览器 String browser = userAgent.getBrowser().getName(); // 封装对象 SysLogininfor logininfor = new SysLogininfor(); logininfor.setUserName(username); logininfor.setIpaddr(ip); logininfor.setLoginLocation(address); logininfor.setBrowser(browser); logininfor.setOs(os); logininfor.setMsg(message); // 日志状态 if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) { logininfor.setStatus(Constants.SUCCESS); } else if (Constants.LOGIN_FAIL.equals(status)) { logininfor.setStatus(Constants.FAIL); } // 插入数据 SpringUtils.getBean(ISysLogininforService.class).insertLogininfor(logininfor); } }; } /** * 操作日志记录 * * @param operLog 操作日志信息 * @return 任务task */ public static TimerTask recordOper(final SysOperLog operLog) { return new TimerTask() { @Override public void run() { // 远程查询操作地点 operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);
10
2023-10-13 07:19:20+00:00
16k
M-D-Team/ait-fabric-1.20.1
src/main/java/mdteam/ait/tardis/util/TardisChunkUtil.java
[ { "identifier": "ForcedChunkUtil", "path": "src/main/java/mdteam/ait/core/util/ForcedChunkUtil.java", "snippet": "public class ForcedChunkUtil {\n public static void keepChunkLoaded(ServerWorld world, BlockPos pos) {\n ChunkPos chunk = new ChunkPos(pos);\n world.setChunkForced(chunk.x, ...
import mdteam.ait.core.util.ForcedChunkUtil; import mdteam.ait.tardis.Tardis; import mdteam.ait.tardis.TardisTravel; import mdteam.ait.tardis.handler.properties.PropertiesHandler; import net.minecraft.server.world.ServerWorld;
13,481
package mdteam.ait.tardis.util; public class TardisChunkUtil { public static void forceLoadExteriorChunk(Tardis tardis) { if (!(tardis.getTravel().getPosition().getWorld() instanceof ServerWorld)) return; ForcedChunkUtil.keepChunkLoaded((ServerWorld) tardis.getTravel().getPosition().getWorld(), tardis.getTravel().getPosition()); } public static void stopForceExteriorChunk(Tardis tardis) { if (!(tardis.getTravel().getPosition().getWorld() instanceof ServerWorld)) return; ForcedChunkUtil.stopForceLoading((ServerWorld) tardis.getTravel().getPosition().getWorld(), tardis.getTravel().getPosition()); } public static boolean isExteriorChunkForced(Tardis tardis) { if (!(tardis.getTravel().getPosition().getWorld() instanceof ServerWorld)) return false; return ForcedChunkUtil.isChunkForced((ServerWorld) tardis.getTravel().getPosition().getWorld(), tardis.getTravel().getPosition()); } public static boolean shouldExteriorChunkBeForced(Tardis tardis) { if (!(tardis.getTravel().getPosition().getWorld() instanceof ServerWorld)) return false; return (PropertiesHandler.getBool(tardis.getHandlers().getProperties(), PropertiesHandler.IS_FALLING))
package mdteam.ait.tardis.util; public class TardisChunkUtil { public static void forceLoadExteriorChunk(Tardis tardis) { if (!(tardis.getTravel().getPosition().getWorld() instanceof ServerWorld)) return; ForcedChunkUtil.keepChunkLoaded((ServerWorld) tardis.getTravel().getPosition().getWorld(), tardis.getTravel().getPosition()); } public static void stopForceExteriorChunk(Tardis tardis) { if (!(tardis.getTravel().getPosition().getWorld() instanceof ServerWorld)) return; ForcedChunkUtil.stopForceLoading((ServerWorld) tardis.getTravel().getPosition().getWorld(), tardis.getTravel().getPosition()); } public static boolean isExteriorChunkForced(Tardis tardis) { if (!(tardis.getTravel().getPosition().getWorld() instanceof ServerWorld)) return false; return ForcedChunkUtil.isChunkForced((ServerWorld) tardis.getTravel().getPosition().getWorld(), tardis.getTravel().getPosition()); } public static boolean shouldExteriorChunkBeForced(Tardis tardis) { if (!(tardis.getTravel().getPosition().getWorld() instanceof ServerWorld)) return false; return (PropertiesHandler.getBool(tardis.getHandlers().getProperties(), PropertiesHandler.IS_FALLING))
|| (tardis.getTravel().getState() == TardisTravel.State.DEMAT)
2
2023-10-08 00:38:53+00:00
16k
jianjian3219/044_bookmanage2-public
nhXJH-framework/src/main/java/com/nhXJH/framework/web/service/SysLoginService.java
[ { "identifier": "Constants", "path": "nhXJH-common/src/main/java/com/nhXJH/common/constant/Constants.java", "snippet": "public class Constants {\n /**\n * UTF-8 字符集\n */\n public static final String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n public static final String GBK =...
import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import com.nhXJH.common.constant.Constants; import com.nhXJH.common.core.domain.entity.SysUser; import com.nhXJH.common.core.domain.model.LoginUser; import com.nhXJH.common.core.redis.RedisCache; import com.nhXJH.common.exception.ServiceException; import com.nhXJH.common.exception.user.CaptchaException; import com.nhXJH.common.exception.user.CaptchaExpireException; import com.nhXJH.common.exception.user.UserPasswordNotMatchException; import com.nhXJH.common.utils.DateUtils; import com.nhXJH.common.utils.MessageUtils; import com.nhXJH.common.utils.ServletUtils; import com.nhXJH.common.utils.ip.IpUtils; import com.nhXJH.framework.manager.AsyncManager; import com.nhXJH.framework.manager.factory.AsyncFactory; import com.nhXJH.system.service.ISysConfigService; import com.nhXJH.system.service.ISysUserService;
13,752
package com.nhXJH.framework.web.service; /** * 登录校验方法 * * @author nhXJH */ @Component public class SysLoginService { @Autowired private TokenService tokenService; @Resource private AuthenticationManager authenticationManager; @Autowired private RedisCache redisCache; @Autowired private ISysUserService userService; @Autowired private ISysConfigService configService; /** * 登录验证 * * @param username 用户名 * @param password 密码 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public String login(String username, String password, String code, String uuid) { boolean captchaOnOff = configService.selectCaptchaOnOff(); // 验证码开关 if (captchaOnOff) { validateCaptcha(username, code, uuid); } // 用户验证 Authentication authentication = null; try { // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(username, password)); } catch (Exception e) { if (e instanceof BadCredentialsException) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); throw new UserPasswordNotMatchException(); } else { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage())); throw new ServiceException(e.getMessage()); } } AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"))); LoginUser loginUser = (LoginUser) authentication.getPrincipal(); recordLoginInfo(loginUser.getUserId()); // 生成token return tokenService.createToken(loginUser); } /** * 校验验证码 * * @param username 用户名 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public void validateCaptcha(String username, String code, String uuid) { String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid; String captcha = redisCache.getCacheObject(verifyKey); redisCache.deleteObject(verifyKey); if (captcha == null) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"))); throw new CaptchaExpireException(); } if (!code.equalsIgnoreCase(captcha)) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); throw new CaptchaException(); } } /** * 记录登录信息 * * @param userId 用户ID */ public void recordLoginInfo(Long userId) { SysUser sysUser = new SysUser(); sysUser.setUserId(userId);
package com.nhXJH.framework.web.service; /** * 登录校验方法 * * @author nhXJH */ @Component public class SysLoginService { @Autowired private TokenService tokenService; @Resource private AuthenticationManager authenticationManager; @Autowired private RedisCache redisCache; @Autowired private ISysUserService userService; @Autowired private ISysConfigService configService; /** * 登录验证 * * @param username 用户名 * @param password 密码 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public String login(String username, String password, String code, String uuid) { boolean captchaOnOff = configService.selectCaptchaOnOff(); // 验证码开关 if (captchaOnOff) { validateCaptcha(username, code, uuid); } // 用户验证 Authentication authentication = null; try { // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(username, password)); } catch (Exception e) { if (e instanceof BadCredentialsException) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); throw new UserPasswordNotMatchException(); } else { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage())); throw new ServiceException(e.getMessage()); } } AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"))); LoginUser loginUser = (LoginUser) authentication.getPrincipal(); recordLoginInfo(loginUser.getUserId()); // 生成token return tokenService.createToken(loginUser); } /** * 校验验证码 * * @param username 用户名 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public void validateCaptcha(String username, String code, String uuid) { String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid; String captcha = redisCache.getCacheObject(verifyKey); redisCache.deleteObject(verifyKey); if (captcha == null) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"))); throw new CaptchaExpireException(); } if (!code.equalsIgnoreCase(captcha)) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); throw new CaptchaException(); } } /** * 记录登录信息 * * @param userId 用户ID */ public void recordLoginInfo(Long userId) { SysUser sysUser = new SysUser(); sysUser.setUserId(userId);
sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
11
2023-10-14 04:57:42+00:00
16k
DrMango14/Create-Design-n-Decor
src/main/java/com/mangomilk/design_decor/registry/MmbBlockEntities.java
[ { "identifier": "BlueContainerBlockEntity", "path": "src/main/java/com/mangomilk/design_decor/blocks/containers/blue/BlueContainerBlockEntity.java", "snippet": "public class BlueContainerBlockEntity extends ItemVaultBlockEntity implements IMultiBlockEntityContainer.Inventory {\n\n\tprotected LazyOptiona...
import com.mangomilk.design_decor.blocks.containers.blue.BlueContainerBlockEntity; import com.mangomilk.design_decor.blocks.containers.green.GreenContainerBlockEntity; import com.mangomilk.design_decor.blocks.containers.red.RedContainerBlockEntity; import com.mangomilk.design_decor.blocks.crushing_wheels.MmbCrushingWheelBlockEntity; import com.mangomilk.design_decor.blocks.crushing_wheels.MmbCrushingWheelControllerBlockEntity; import com.mangomilk.design_decor.blocks.gas_tank.GasTankBlockEntity; import com.mangomilk.design_decor.blocks.industrial_gear.IndustrialGearInstance; import com.mangomilk.design_decor.blocks.industrial_gear.IndustrialGearRenderer; import com.mangomilk.design_decor.blocks.millstone.DecoMillStoneBlockEntity; import com.mangomilk.design_decor.blocks.millstone.instance.*; import com.mangomilk.design_decor.blocks.millstone.renderer.*; import com.simibubi.create.AllBlocks; import com.simibubi.create.content.kinetics.base.CutoutRotatingInstance; import com.simibubi.create.content.kinetics.base.KineticBlockEntityRenderer; import com.simibubi.create.content.kinetics.simpleRelays.BracketedKineticBlockEntity; import com.tterrag.registrate.util.entry.BlockEntityEntry; import static com.mangomilk.design_decor.CreateMMBuilding.REGISTRATE;
13,864
package com.mangomilk.design_decor.registry; public class MmbBlockEntities { public static final BlockEntityEntry<BracketedKineticBlockEntity> BRACKETED_KINETIC = REGISTRATE .blockEntity("simple_kinetic", BracketedKineticBlockEntity::new) .instance(() -> IndustrialGearInstance::new, false) .validBlocks(MmbBlocks.COGWHEEL, MmbBlocks.LARGE_COGWHEEL) .renderer(() -> IndustrialGearRenderer::new) .register();
package com.mangomilk.design_decor.registry; public class MmbBlockEntities { public static final BlockEntityEntry<BracketedKineticBlockEntity> BRACKETED_KINETIC = REGISTRATE .blockEntity("simple_kinetic", BracketedKineticBlockEntity::new) .instance(() -> IndustrialGearInstance::new, false) .validBlocks(MmbBlocks.COGWHEEL, MmbBlocks.LARGE_COGWHEEL) .renderer(() -> IndustrialGearRenderer::new) .register();
public static final BlockEntityEntry<GasTankBlockEntity> GAS_TANK = REGISTRATE
5
2023-10-14 21:51:49+00:00
16k
Spider-Admin/Frost
src/main/java/frost/fileTransfer/upload/GenerateShaThread.java
[ { "identifier": "Core", "path": "src/main/java/frost/Core.java", "snippet": "public class Core {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(Core.class);\r\n\r\n // Core instanciates itself, frostSettings must be created before instance=Core() !\r\n public static final Se...
import java.io.File; import java.util.LinkedList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import frost.Core; import frost.fileTransfer.FileTransferManager; import frost.fileTransfer.NewUploadFilesManager; import frost.fileTransfer.sharing.FrostSharedFileItem; import frost.storage.perst.NewUploadFile; import frost.util.Mixed;
11,025
/* GenerateShaThread.java / Frost Copyright (C) 2006 Frost Project <jtcfrost.sourceforge.net> This program 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 2 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.fileTransfer.upload; /** * Generates the sha checksum of a file. */ public class GenerateShaThread extends Thread { private static final Logger logger = LoggerFactory.getLogger(GenerateShaThread.class); private NewUploadFilesManager newUploadFilesManager; private static final int wait1minute = 1 * 60 * 1000; FileQueue fileQueue; /** * @param newUploadFilesManager */ public GenerateShaThread(NewUploadFilesManager newUploadFilesManager) { this.newUploadFilesManager = newUploadFilesManager; fileQueue = new FileQueue(); } /** * @param f */ public void addToFileQueue(final NewUploadFile f) { // awakes thread fileQueue.appendFileToQueue(f); } /** * @return */ public int getQueueSize() { return fileQueue.getQueueSize(); } /* (non-Javadoc) * @see java.lang.Thread#run() */ @Override public void run() { final int maxAllowedExceptions = 5; int occuredExceptions = 0; while(true) { try { // if now work is in queue this call waits for a new queueitem final NewUploadFile newUploadFile = fileQueue.getFileFromQueue(); if( newUploadFile == null ) { // paranoia Mixed.wait(wait1minute); continue; } final File newFile = new File(newUploadFile.getFilePath()); final String sha = Core.getCrypto().computeChecksumSHA256(newFile); if( sha != null ) { // create new item final FrostSharedFileItem sfi = new FrostSharedFileItem( newFile, newUploadFile.getFrom(), sha); // add to shared files
/* GenerateShaThread.java / Frost Copyright (C) 2006 Frost Project <jtcfrost.sourceforge.net> This program 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 2 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost.fileTransfer.upload; /** * Generates the sha checksum of a file. */ public class GenerateShaThread extends Thread { private static final Logger logger = LoggerFactory.getLogger(GenerateShaThread.class); private NewUploadFilesManager newUploadFilesManager; private static final int wait1minute = 1 * 60 * 1000; FileQueue fileQueue; /** * @param newUploadFilesManager */ public GenerateShaThread(NewUploadFilesManager newUploadFilesManager) { this.newUploadFilesManager = newUploadFilesManager; fileQueue = new FileQueue(); } /** * @param f */ public void addToFileQueue(final NewUploadFile f) { // awakes thread fileQueue.appendFileToQueue(f); } /** * @return */ public int getQueueSize() { return fileQueue.getQueueSize(); } /* (non-Javadoc) * @see java.lang.Thread#run() */ @Override public void run() { final int maxAllowedExceptions = 5; int occuredExceptions = 0; while(true) { try { // if now work is in queue this call waits for a new queueitem final NewUploadFile newUploadFile = fileQueue.getFileFromQueue(); if( newUploadFile == null ) { // paranoia Mixed.wait(wait1minute); continue; } final File newFile = new File(newUploadFile.getFilePath()); final String sha = Core.getCrypto().computeChecksumSHA256(newFile); if( sha != null ) { // create new item final FrostSharedFileItem sfi = new FrostSharedFileItem( newFile, newUploadFile.getFrom(), sha); // add to shared files
FileTransferManager.inst().getSharedFilesManager().getModel().addNewSharedFile(sfi, newUploadFile.isReplacePathIfFileExists());
1
2023-10-07 22:25:20+00:00
16k
openpilot-hub/devpilot-intellij
src/main/java/com/zhongan/devpilot/actions/editor/popupmenu/PopupMenuEditorActionGroupUtil.java
[ { "identifier": "DevPilotNotification", "path": "src/main/java/com/zhongan/devpilot/actions/notifications/DevPilotNotification.java", "snippet": "public class DevPilotNotification {\n\n public static void info(String content) {\n var notification = new Notification(\n \"DevPilot Not...
import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowManager; import com.zhongan.devpilot.actions.notifications.DevPilotNotification; import com.zhongan.devpilot.constant.DefaultConst; import com.zhongan.devpilot.constant.PromptConst; import com.zhongan.devpilot.enums.EditorActionEnum; import com.zhongan.devpilot.enums.SessionTypeEnum; import com.zhongan.devpilot.gui.toolwindows.chat.DevPilotChatToolWindowService; import com.zhongan.devpilot.gui.toolwindows.components.EditorInfo; import com.zhongan.devpilot.settings.actionconfiguration.EditorActionConfigurationState; import com.zhongan.devpilot.settings.state.DevPilotLlmSettingsState; import com.zhongan.devpilot.settings.state.LanguageSettingsState; import com.zhongan.devpilot.util.DevPilotMessageBundle; import com.zhongan.devpilot.util.DocumentUtil; import com.zhongan.devpilot.util.LanguageUtil; import com.zhongan.devpilot.util.PerformanceCheckUtils; import com.zhongan.devpilot.util.PromptTemplate; import com.zhongan.devpilot.util.PsiFileUtil; import com.zhongan.devpilot.webview.model.CodeReferenceModel; import com.zhongan.devpilot.webview.model.MessageModel; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.function.Consumer; import javax.swing.Icon; import static com.zhongan.devpilot.constant.PlaceholderConst.ADDITIONAL_MOCK_PROMPT; import static com.zhongan.devpilot.constant.PlaceholderConst.LANGUAGE; import static com.zhongan.devpilot.constant.PlaceholderConst.MOCK_FRAMEWORK; import static com.zhongan.devpilot.constant.PlaceholderConst.SELECTED_CODE; import static com.zhongan.devpilot.constant.PlaceholderConst.TEST_FRAMEWORK;
12,054
package com.zhongan.devpilot.actions.editor.popupmenu; public class PopupMenuEditorActionGroupUtil { private static final Map<String, Icon> ICONS = new LinkedHashMap<>(Map.of( EditorActionEnum.PERFORMANCE_CHECK.getLabel(), AllIcons.Plugins.Updated, EditorActionEnum.GENERATE_COMMENTS.getLabel(), AllIcons.Actions.InlayRenameInCommentsActive, EditorActionEnum.GENERATE_TESTS.getLabel(), AllIcons.Modules.GeneratedTestRoot, EditorActionEnum.FIX_THIS.getLabel(), AllIcons.Actions.QuickfixBulb, EditorActionEnum.REVIEW_CODE.getLabel(), AllIcons.Actions.PreviewDetailsVertically, EditorActionEnum.EXPLAIN_THIS.getLabel(), AllIcons.Actions.Preview)); public static void refreshActions(Project project) { AnAction actionGroup = ActionManager.getInstance().getAction("com.zhongan.devpilot.actions.editor.popupmenu.BasicEditorAction"); if (actionGroup instanceof DefaultActionGroup) { DefaultActionGroup group = (DefaultActionGroup) actionGroup; group.removeAll(); group.add(new NewChatAction()); group.addSeparator(); var defaultActions = EditorActionConfigurationState.getInstance().getDefaultActions(); defaultActions.forEach((label, prompt) -> { var action = new BasicEditorAction(DevPilotMessageBundle.get(label), DevPilotMessageBundle.get(label), ICONS.getOrDefault(label, AllIcons.FileTypes.Unknown)) { @Override protected void actionPerformed(Project project, Editor editor, String selectedText) { ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow("DevPilot"); toolWindow.show(); if (isInputExceedLimit(selectedText, prompt)) { DevPilotNotification.info(DevPilotMessageBundle.get("devpilot.notification.input.tooLong")); return; } var editorActionEnum = EditorActionEnum.getEnumByLabel(label); if (Objects.isNull(editorActionEnum)) { return; } Consumer<String> callback = result -> { if (validateResult(result)) { DevPilotNotification.info(DevPilotMessageBundle.get("devpilot.notification.input.tooLong")); return; } switch (editorActionEnum) { case PERFORMANCE_CHECK: // display result, and open diff window PerformanceCheckUtils.showDiffWindow(selectedText, project, editor); break; case GENERATE_COMMENTS: DocumentUtil.diffCommentAndFormatWindow(project, editor, result); break; default: break; } }; EditorInfo editorInfo = new EditorInfo(editor); PromptTemplate promptTemplate = PromptTemplate.of(prompt); promptTemplate.setVariable(SELECTED_CODE, selectedText); if (editorActionEnum == EditorActionEnum.GENERATE_TESTS) { Optional.ofNullable(FileDocumentManager.getInstance().getFile(editor.getDocument())) .map(vFile -> LanguageUtil.getLanguageByExtension(vFile.getExtension())) .ifPresent(language -> { promptTemplate.setVariable(LANGUAGE, language.getLanguageName()); promptTemplate.setVariable(TEST_FRAMEWORK, language.getDefaultTestFramework()); promptTemplate.setVariable(MOCK_FRAMEWORK, language.getDefaultMockFramework()); if (language.isJvmPlatform() && PsiFileUtil.isCaretInWebClass(project, editor)) { promptTemplate.setVariable(ADDITIONAL_MOCK_PROMPT, PromptConst.MOCK_WEB_MVC); } }); } if (LanguageSettingsState.getInstance().getLanguageIndex() == 1) { promptTemplate.appendLast(PromptConst.ANSWER_IN_CHINESE); }
package com.zhongan.devpilot.actions.editor.popupmenu; public class PopupMenuEditorActionGroupUtil { private static final Map<String, Icon> ICONS = new LinkedHashMap<>(Map.of( EditorActionEnum.PERFORMANCE_CHECK.getLabel(), AllIcons.Plugins.Updated, EditorActionEnum.GENERATE_COMMENTS.getLabel(), AllIcons.Actions.InlayRenameInCommentsActive, EditorActionEnum.GENERATE_TESTS.getLabel(), AllIcons.Modules.GeneratedTestRoot, EditorActionEnum.FIX_THIS.getLabel(), AllIcons.Actions.QuickfixBulb, EditorActionEnum.REVIEW_CODE.getLabel(), AllIcons.Actions.PreviewDetailsVertically, EditorActionEnum.EXPLAIN_THIS.getLabel(), AllIcons.Actions.Preview)); public static void refreshActions(Project project) { AnAction actionGroup = ActionManager.getInstance().getAction("com.zhongan.devpilot.actions.editor.popupmenu.BasicEditorAction"); if (actionGroup instanceof DefaultActionGroup) { DefaultActionGroup group = (DefaultActionGroup) actionGroup; group.removeAll(); group.add(new NewChatAction()); group.addSeparator(); var defaultActions = EditorActionConfigurationState.getInstance().getDefaultActions(); defaultActions.forEach((label, prompt) -> { var action = new BasicEditorAction(DevPilotMessageBundle.get(label), DevPilotMessageBundle.get(label), ICONS.getOrDefault(label, AllIcons.FileTypes.Unknown)) { @Override protected void actionPerformed(Project project, Editor editor, String selectedText) { ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow("DevPilot"); toolWindow.show(); if (isInputExceedLimit(selectedText, prompt)) { DevPilotNotification.info(DevPilotMessageBundle.get("devpilot.notification.input.tooLong")); return; } var editorActionEnum = EditorActionEnum.getEnumByLabel(label); if (Objects.isNull(editorActionEnum)) { return; } Consumer<String> callback = result -> { if (validateResult(result)) { DevPilotNotification.info(DevPilotMessageBundle.get("devpilot.notification.input.tooLong")); return; } switch (editorActionEnum) { case PERFORMANCE_CHECK: // display result, and open diff window PerformanceCheckUtils.showDiffWindow(selectedText, project, editor); break; case GENERATE_COMMENTS: DocumentUtil.diffCommentAndFormatWindow(project, editor, result); break; default: break; } }; EditorInfo editorInfo = new EditorInfo(editor); PromptTemplate promptTemplate = PromptTemplate.of(prompt); promptTemplate.setVariable(SELECTED_CODE, selectedText); if (editorActionEnum == EditorActionEnum.GENERATE_TESTS) { Optional.ofNullable(FileDocumentManager.getInstance().getFile(editor.getDocument())) .map(vFile -> LanguageUtil.getLanguageByExtension(vFile.getExtension())) .ifPresent(language -> { promptTemplate.setVariable(LANGUAGE, language.getLanguageName()); promptTemplate.setVariable(TEST_FRAMEWORK, language.getDefaultTestFramework()); promptTemplate.setVariable(MOCK_FRAMEWORK, language.getDefaultMockFramework()); if (language.isJvmPlatform() && PsiFileUtil.isCaretInWebClass(project, editor)) { promptTemplate.setVariable(ADDITIONAL_MOCK_PROMPT, PromptConst.MOCK_WEB_MVC); } }); } if (LanguageSettingsState.getInstance().getLanguageIndex() == 1) { promptTemplate.appendLast(PromptConst.ANSWER_IN_CHINESE); }
var service = project.getService(DevPilotChatToolWindowService.class);
5
2023-11-29 06:37:51+00:00
16k
okx/OKBund
aa-task/src/main/java/com/okcoin/dapp/bundler/manager/BundlerServiceImpl.java
[ { "identifier": "BundleConfig", "path": "aa-task/src/main/java/com/okcoin/dapp/bundler/config/BundleConfig.java", "snippet": "@Configuration\n@ConfigurationProperties(prefix = \"bundler.bundle\")\n@Data\npublic class BundleConfig {\n\n private BigInteger maxBundleGas;\n\n private BigDecimal baseFe...
import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.okcoin.dapp.bundler.config.BundleConfig; import com.okcoin.dapp.bundler.config.OnChainConfig; import com.okcoin.dapp.bundler.domain.UopBundleDO; import com.okcoin.dapp.bundler.infra.chain.FieldUtil; import com.okcoin.dapp.bundler.infra.chain.IChain; import com.okcoin.dapp.bundler.infra.chain.ReceiptUtil; import com.okcoin.dapp.bundler.infra.chain.web3j.resp.TransactionReceiptCommon; import com.okcoin.dapp.bundler.pool.bundler.IBundleService; import com.okcoin.dapp.bundler.pool.config.ChainConfig; import com.okcoin.dapp.bundler.pool.config.PoolConfig; import com.okcoin.dapp.bundler.pool.domain.TxAndOpHashMappingDO; import com.okcoin.dapp.bundler.pool.domain.UserOperationDO; import com.okcoin.dapp.bundler.pool.domain.debug.SimulateValidationResult; import com.okcoin.dapp.bundler.pool.domain.debug.SlotMap; import com.okcoin.dapp.bundler.pool.domain.pool.MempoolEntry; import com.okcoin.dapp.bundler.pool.domain.reputation.ReputationStatusEnum; import com.okcoin.dapp.bundler.pool.entrypoint.Entrypoint; import com.okcoin.dapp.bundler.pool.gasprice.GasPriceInfo; import com.okcoin.dapp.bundler.pool.gasprice.GasService; import com.okcoin.dapp.bundler.pool.mem.MempoolService; import com.okcoin.dapp.bundler.pool.reputation.ReputationService; import com.okcoin.dapp.bundler.pool.result.OnChainTxFailedService; import com.okcoin.dapp.bundler.pool.simulation.EntryPointSimulationsFactory; import com.okcoin.dapp.bundler.pool.simulation.IEntryPointSimulations; import com.okcoin.dapp.bundler.pool.util.AddressUtil; import com.okcoin.dapp.bundler.pool.util.MathUtil; import com.okcoin.dapp.bundler.task.logevent.LogEventService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.web3j.crypto.Credentials; import javax.annotation.Resource; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors;
11,985
package com.okcoin.dapp.bundler.manager; /** * @ClassName BundlerServiceImpl * @Author qunqin * @Date 2023/10/25 **/ @Component @Slf4j public class BundlerServiceImpl implements IBundleService { @Resource private MempoolService mempoolService; @Resource private BundleConfig bundleConfig; @Resource private GasService gasService; @Resource private EntryPointSimulationsFactory entryPointSimulationsFactory; @Autowired private OnChainConfig onChainConfig; @Autowired private ChainConfig chainConfig; @Autowired private LogEventService logEventService; @Autowired private ReputationService reputationService; @Autowired private PoolConfig poolConfig; @Autowired private OnChainTxFailedService onChainTxFailedService; private static final Long THROTTLED_ENTITY_BUNDLE_COUNT = 4L; private UopBundleDO createBundle() {
package com.okcoin.dapp.bundler.manager; /** * @ClassName BundlerServiceImpl * @Author qunqin * @Date 2023/10/25 **/ @Component @Slf4j public class BundlerServiceImpl implements IBundleService { @Resource private MempoolService mempoolService; @Resource private BundleConfig bundleConfig; @Resource private GasService gasService; @Resource private EntryPointSimulationsFactory entryPointSimulationsFactory; @Autowired private OnChainConfig onChainConfig; @Autowired private ChainConfig chainConfig; @Autowired private LogEventService logEventService; @Autowired private ReputationService reputationService; @Autowired private PoolConfig poolConfig; @Autowired private OnChainTxFailedService onChainTxFailedService; private static final Long THROTTLED_ENTITY_BUNDLE_COUNT = 4L; private UopBundleDO createBundle() {
List<MempoolEntry> entryList = Lists.newArrayList();
14
2023-11-27 10:54:49+00:00
16k
seraxis/lr2oraja-endlessdream
core/src/bms/player/beatoraja/select/bar/ExecutableBar.java
[ { "identifier": "MainState", "path": "core/src/bms/player/beatoraja/MainState.java", "snippet": "public abstract class MainState {\n\n\tpublic final MainController main;\n\n\t/**\n\t * スキン\n\t */\n\tprivate Skin skin;\n\n\tprivate Stage stage;\n\t\n\tpublic final TimerManager timer;\n\t\n\tpublic final ...
import java.util.ArrayDeque; import java.util.Queue; import bms.player.beatoraja.MainState; import bms.player.beatoraja.select.MusicSelector; import bms.player.beatoraja.song.SongData;
12,656
package bms.player.beatoraja.select.bar; /** * Bar to resolve when selecting a song. * TODO: ExecutableBar extends to make things happen */ public class ExecutableBar extends SelectableBar { /** * index table size */ private final static int QueueLength = 1000; /** * bar title */ private String title = "RANDOM SELECT"; /** * source songs */ private SongData[] songs = null; /** * current state pointer */ private MainState state; /** * Queue for get index to SongData array. */ private Queue<Integer> queue; /** * currentSong */ private SongData currentSong = null; /** * Constructor * * @param songs SongData array that is the source of SongData returned according to the conditions. * @param state MainState pointer. */ public ExecutableBar(SongData[] songs, MainState state, String title) { super(); this.title = title; this.songs = songs; this.state = state; createIndexQueue(); } /** * @return SongData */ public SongData getSongData() { return _getSongData(); } /** * Return random SongData * * @return SongData extracted from this.songs */ private synchronized SongData _getSongData() { if (queue.size() == 0) { createIndexQueue(); }
package bms.player.beatoraja.select.bar; /** * Bar to resolve when selecting a song. * TODO: ExecutableBar extends to make things happen */ public class ExecutableBar extends SelectableBar { /** * index table size */ private final static int QueueLength = 1000; /** * bar title */ private String title = "RANDOM SELECT"; /** * source songs */ private SongData[] songs = null; /** * current state pointer */ private MainState state; /** * Queue for get index to SongData array. */ private Queue<Integer> queue; /** * currentSong */ private SongData currentSong = null; /** * Constructor * * @param songs SongData array that is the source of SongData returned according to the conditions. * @param state MainState pointer. */ public ExecutableBar(SongData[] songs, MainState state, String title) { super(); this.title = title; this.songs = songs; this.state = state; createIndexQueue(); } /** * @return SongData */ public SongData getSongData() { return _getSongData(); } /** * Return random SongData * * @return SongData extracted from this.songs */ private synchronized SongData _getSongData() { if (queue.size() == 0) { createIndexQueue(); }
if (state instanceof MusicSelector || currentSong == null) {
1
2023-12-02 23:41:17+00:00
16k
Elb1to/FFA
src/main/java/me/elb1to/ffa/FfaPlugin.java
[ { "identifier": "Assemble", "path": "src/main/java/io/github/thatkawaiisam/assemble/Assemble.java", "snippet": "@Getter\n@Setter\npublic class Assemble {\n\n\tprivate final JavaPlugin plugin;\n\tprivate final ChatColor[] chatColorCache = ChatColor.values();\n\tprivate AssembleAdapter adapter;\n\tprivate...
import io.github.thatkawaiisam.assemble.Assemble; import io.github.thatkawaiisam.assemble.AssembleStyle; import lombok.Getter; import me.elb1to.ffa.command.manager.CommandManager; import me.elb1to.ffa.database.MongoSrv; import me.elb1to.ffa.game.listener.FfaListener; import me.elb1to.ffa.game.manager.FfaManager; import me.elb1to.ffa.game.task.ItemRemovalTask; import me.elb1to.ffa.kit.manager.KitManager; import me.elb1to.ffa.layout.ScoreboardLayout; import me.elb1to.ffa.leaderboard.manager.LeaderboardManager; import me.elb1to.ffa.map.FfaMap; import me.elb1to.ffa.map.manager.MapManager; import me.elb1to.ffa.user.UserProfile; import me.elb1to.ffa.user.listener.UserProfileListener; import me.elb1to.ffa.user.manager.UserProfileManager; import me.elb1to.ffa.util.menu.listener.ButtonListener; import me.elb1to.ffa.util.world.Cuboid; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.WorldCreator; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.plugin.java.JavaPlugin;
11,135
package me.elb1to.ffa; /** * @author Elb1to * @since 11/22/2023 */ @Getter public class FfaPlugin extends JavaPlugin { private MongoSrv mongoSrv;
package me.elb1to.ffa; /** * @author Elb1to * @since 11/22/2023 */ @Getter public class FfaPlugin extends JavaPlugin { private MongoSrv mongoSrv;
private MapManager mapManager;
11
2023-11-28 16:53:29+00:00
16k
WiIIiam278/HuskClaims
common/src/main/java/net/william278/huskclaims/command/UnTrustCommand.java
[ { "identifier": "HuskClaims", "path": "common/src/main/java/net/william278/huskclaims/HuskClaims.java", "snippet": "public interface HuskClaims extends Task.Supplier, ConfigProvider, DatabaseProvider, GsonProvider, UserManager,\n ClaimManager, GroupManager, TrustTagManager, ListenerProvider, User...
import net.william278.huskclaims.user.User; import org.jetbrains.annotations.Blocking; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Optional; import com.google.common.collect.Lists; import net.william278.huskclaims.HuskClaims; import net.william278.huskclaims.claim.Claim; import net.william278.huskclaims.claim.ClaimWorld; import net.william278.huskclaims.config.Settings; import net.william278.huskclaims.trust.TrustLevel; import net.william278.huskclaims.trust.TrustTag; import net.william278.huskclaims.trust.Trustable; import net.william278.huskclaims.trust.UserGroup; import net.william278.huskclaims.user.CommandUser; import net.william278.huskclaims.user.OnlineUser;
13,104
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <will27528@gmail.com> * Copyright (c) contributors * * 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 net.william278.huskclaims.command; public class UnTrustCommand extends InClaimCommand implements TabCompletable { protected UnTrustCommand(@NotNull HuskClaims plugin) { super( List.of("untrust"), getUsageText(plugin.getSettings()), TrustLevel.Privilege.MANAGE_TRUSTEES, plugin ); } @Override
/* * This file is part of HuskClaims, licensed under the Apache License 2.0. * * Copyright (c) William278 <will27528@gmail.com> * Copyright (c) contributors * * 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 net.william278.huskclaims.command; public class UnTrustCommand extends InClaimCommand implements TabCompletable { protected UnTrustCommand(@NotNull HuskClaims plugin) { super( List.of("untrust"), getUsageText(plugin.getSettings()), TrustLevel.Privilege.MANAGE_TRUSTEES, plugin ); } @Override
public void execute(@NotNull OnlineUser executor, @NotNull ClaimWorld world,
8
2023-11-28 01:09:43+00:00
16k
Manzzx/multi-channel-message-reach
metax-web/src/main/java/com/metax/web/xxljob/service/impl/XxlJobServiceImpl.java
[ { "identifier": "SecurityContextHolder", "path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/context/SecurityContextHolder.java", "snippet": "public class SecurityContextHolder\n{\n private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new Transmitt...
import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson2.JSON; import com.metax.common.core.context.SecurityContextHolder; import com.metax.common.core.exception.ServiceException; import com.metax.common.core.web.domain.AjaxResult; import com.metax.web.domain.MessageTemplate; import com.metax.web.mapper.MessageTemplateMapper; import com.metax.web.util.DataUtil; import com.metax.web.xxljob.domain.CronTaskCords; import com.metax.web.xxljob.domain.XxlJobInfo; import com.metax.web.xxljob.enums.ExecutorRouteStrategyEnum; import com.metax.web.xxljob.enums.MisfireStrategyEnum; import com.metax.web.xxljob.enums.ScheduleTypeEnum; import com.metax.web.xxljob.service.XxlJobService; import com.metax.web.xxljob.util.XxlJobUtil; import com.xxl.job.core.biz.model.ReturnT; import com.xxl.job.core.enums.ExecutorBlockStrategyEnum; import com.xxl.job.core.glue.GlueTypeEnum; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.scheduling.support.CronExpression; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.Date; import java.util.Objects; import static com.metax.common.core.constant.MetaxDataConstants.*; import static com.metax.common.core.web.domain.AjaxResult.DATA_TAG;
12,592
package com.metax.web.xxljob.service.impl; @Service @Slf4j public class XxlJobServiceImpl implements XxlJobService { @Autowired private XxlJobUtil xxlJobUtil; @Autowired private MessageTemplateMapper messageTemplateMapper; @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private DataUtil dataUtil; @Value("${xxl.job.executor.jobHandlerName}") private String jobName; /** * 保存xxlJob任务 * * @param messageTemplate * @return */ @Override public AjaxResult save(MessageTemplate messageTemplate) { XxlJobInfo xxlJobInfo = buildXxlJobInfo(messageTemplate); String result = xxlJobUtil.add(xxlJobInfo); ReturnT returnT = JSON.parseObject(result, ReturnT.class); if (ReturnT.SUCCESS_CODE != returnT.getCode()) { throw new ServiceException("定时消息任务:" + messageTemplate.getName() + "启动失败!"); } //保存任务到调度中心成功 返回id Integer cronTaskId = Integer.valueOf((String) returnT.getContent()); return AjaxResult.success(cronTaskId); } /** * 构建xxlJobInfo * * @param messageTemplate * @return */ @Override public XxlJobInfo buildXxlJobInfo(MessageTemplate messageTemplate) { String pushTime = messageTemplate.getExpectPushTime(); String pushTimeTemp = pushTime; //0 或者 不指定时间都是立即执行 if (pushTime == null || PUSH_NOW.equals(pushTime)) { pushTime = DateUtil.format(DateUtil.offsetSecond(new Date(), DELAY_TIME), CRON_FORMAT); } boolean validExpression = CronExpression.isValidExpression(pushTime); if (!validExpression && !PUSH_NOW.equals(pushTimeTemp)) { throw new ServiceException("定时消息任务:" + messageTemplate.getName() + " cron表达式存在错误 请修改!"); } XxlJobInfo xxlJobInfo = XxlJobInfo.builder() .jobGroup(xxlJobUtil.getGroupId()).jobDesc(messageTemplate.getName()) .author(messageTemplate.getCreator()) .scheduleConf(pushTime) .scheduleType(ScheduleTypeEnum.CRON.name()) .misfireStrategy(MisfireStrategyEnum.DO_NOTHING.name()) .executorRouteStrategy(ExecutorRouteStrategyEnum.CONSISTENT_HASH.name()) .executorHandler(jobName) //将模板id和发送方id作为任务参数 .executorParam(messageTemplate.getId()+SEPARATOR+SecurityContextHolder.getUserId()) .executorBlockStrategy(ExecutorBlockStrategyEnum.SERIAL_EXECUTION.name()) .executorTimeout(TIME_OUT) .executorFailRetryCount(RETRY_COUNT) .glueType(GlueTypeEnum.BEAN.name()) .triggerStatus(TRIGGER_STATUS_FALSE) .glueRemark(StrUtil.EMPTY) .glueSource(StrUtil.EMPTY) .alarmEmail(NOTING_EMAIL) .childJobId(StrUtil.EMPTY).build(); if (Objects.nonNull(messageTemplate.getCronTaskId())) { xxlJobInfo.setId(messageTemplate.getCronTaskId()); } return xxlJobInfo; } /** * 启动任务 * * @param id * @return */ public AjaxResult start(Long id) { Long sender = SecurityContextHolder.getUserId(); MessageTemplate messageTemplate = messageTemplateMapper.selectById(id); if (!Objects.nonNull(messageTemplate.getCronTaskId())) { //不存在cronTaskId AjaxResult result = save(messageTemplate);
package com.metax.web.xxljob.service.impl; @Service @Slf4j public class XxlJobServiceImpl implements XxlJobService { @Autowired private XxlJobUtil xxlJobUtil; @Autowired private MessageTemplateMapper messageTemplateMapper; @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private DataUtil dataUtil; @Value("${xxl.job.executor.jobHandlerName}") private String jobName; /** * 保存xxlJob任务 * * @param messageTemplate * @return */ @Override public AjaxResult save(MessageTemplate messageTemplate) { XxlJobInfo xxlJobInfo = buildXxlJobInfo(messageTemplate); String result = xxlJobUtil.add(xxlJobInfo); ReturnT returnT = JSON.parseObject(result, ReturnT.class); if (ReturnT.SUCCESS_CODE != returnT.getCode()) { throw new ServiceException("定时消息任务:" + messageTemplate.getName() + "启动失败!"); } //保存任务到调度中心成功 返回id Integer cronTaskId = Integer.valueOf((String) returnT.getContent()); return AjaxResult.success(cronTaskId); } /** * 构建xxlJobInfo * * @param messageTemplate * @return */ @Override public XxlJobInfo buildXxlJobInfo(MessageTemplate messageTemplate) { String pushTime = messageTemplate.getExpectPushTime(); String pushTimeTemp = pushTime; //0 或者 不指定时间都是立即执行 if (pushTime == null || PUSH_NOW.equals(pushTime)) { pushTime = DateUtil.format(DateUtil.offsetSecond(new Date(), DELAY_TIME), CRON_FORMAT); } boolean validExpression = CronExpression.isValidExpression(pushTime); if (!validExpression && !PUSH_NOW.equals(pushTimeTemp)) { throw new ServiceException("定时消息任务:" + messageTemplate.getName() + " cron表达式存在错误 请修改!"); } XxlJobInfo xxlJobInfo = XxlJobInfo.builder() .jobGroup(xxlJobUtil.getGroupId()).jobDesc(messageTemplate.getName()) .author(messageTemplate.getCreator()) .scheduleConf(pushTime) .scheduleType(ScheduleTypeEnum.CRON.name()) .misfireStrategy(MisfireStrategyEnum.DO_NOTHING.name()) .executorRouteStrategy(ExecutorRouteStrategyEnum.CONSISTENT_HASH.name()) .executorHandler(jobName) //将模板id和发送方id作为任务参数 .executorParam(messageTemplate.getId()+SEPARATOR+SecurityContextHolder.getUserId()) .executorBlockStrategy(ExecutorBlockStrategyEnum.SERIAL_EXECUTION.name()) .executorTimeout(TIME_OUT) .executorFailRetryCount(RETRY_COUNT) .glueType(GlueTypeEnum.BEAN.name()) .triggerStatus(TRIGGER_STATUS_FALSE) .glueRemark(StrUtil.EMPTY) .glueSource(StrUtil.EMPTY) .alarmEmail(NOTING_EMAIL) .childJobId(StrUtil.EMPTY).build(); if (Objects.nonNull(messageTemplate.getCronTaskId())) { xxlJobInfo.setId(messageTemplate.getCronTaskId()); } return xxlJobInfo; } /** * 启动任务 * * @param id * @return */ public AjaxResult start(Long id) { Long sender = SecurityContextHolder.getUserId(); MessageTemplate messageTemplate = messageTemplateMapper.selectById(id); if (!Objects.nonNull(messageTemplate.getCronTaskId())) { //不存在cronTaskId AjaxResult result = save(messageTemplate);
Integer cronTaskId = (Integer) result.get(DATA_TAG);
14
2023-12-04 05:10:13+00:00
16k
ydb-platform/yoj-project
repository/src/main/java/tech/ydb/yoj/repository/db/projection/ProjectionMappings.java
[ { "identifier": "Schema", "path": "databind/src/main/java/tech/ydb/yoj/databind/schema/Schema.java", "snippet": "public abstract class Schema<T> {\n public static final String PATH_DELIMITER = \".\";\n\n @Getter(PROTECTED)\n private final SchemaKey<T> schemaKey;\n\n @Getter\n private fina...
import com.google.common.base.Preconditions; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import lombok.NonNull; import lombok.RequiredArgsConstructor; import tech.ydb.yoj.databind.schema.Schema; import tech.ydb.yoj.repository.db.Entity; import tech.ydb.yoj.repository.db.EntityIdSchema; import tech.ydb.yoj.repository.db.EntitySchema; import tech.ydb.yoj.repository.db.list.ListRequest; import tech.ydb.yoj.repository.db.list.ListResult; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.function.UnaryOperator; import static java.util.stream.Collectors.toList; import static lombok.AccessLevel.PRIVATE;
12,159
package tech.ydb.yoj.repository.db.projection; public final class ProjectionMappings { private ProjectionMappings() { } /** * Creates a <em>lenient</em> one-to-one mapping from entity fields to projection fields, which contains all * {@link #strictFieldMapping(Class, Class) strict mappings}, plus mappings of the form * {@code <entity field> <-> <projection field with the same path>} (if both fields exist). * * @param projectionType projection class * @param entityType entity class * @param <P> projection type * @param <T> entity type * @return Map: Entity field path -> Projection field path * @see #strictFieldMapping(Class, Class) */ @NonNull public static <P extends Entity<P>, T extends Entity<T>> Map<String, String> lenientFieldMapping( @NonNull Class<P> projectionType, @NonNull Class<T> entityType) { EntitySchema<T> entitySchema = EntitySchema.of(entityType); Class<?> entityIdType = entitySchema.getIdSchema().getType(); BiMap<String, String> mapping = HashBiMap.create(strictFieldMapping(projectionType, entityType)); EntitySchema.of(projectionType).flattenFields() .stream() .filter(pf -> !isEntityId(pf, entityIdType) && !mapping.inverse().containsKey(pf.getPath())) .forEach(pf -> findMatchingNonIdField(pf, entitySchema) .ifPresent(ef -> mapping.put(ef.getPath(), pf.getPath())) ); return mapping; } /** * Creates a one-to-one mapping from entity fields to entity projection ID fields, assuming that the projection ID * contains fields with the same name as in the main entity and <em>at most one</em> field for the main entity ID * (with any name). * </ul> * <p> * <em>E.g.</em>, the following entity-projection pair qualifies: <blockquote><pre> * &#64;Value class MyEntity implements Entity&lt;MyEntity> { * Id id; * String field; * * &#64;Value static class Id implements Entity.Id&lt;MyEntity> { String value; } * } * * &#64;Value class MyIndex implements Entity&lt;MyIndex> { * Id id; * * &#64;Value * static class Id implements Entity.Id&lt;MyIndex> { * // MUST have the same Java field name as in the entity class * // (DB name specified in &#64;Column annotation does not matter.) * String field; * * // OPTIONAL. If present, this field MAY have any name * MyEntity.Id entityId; * } * } * </pre></blockquote> * * @param projectionType projection class * @param entityType entity class * @param <P> projection type * @param <T> entity type * @return Bidirectional mapping: Entity field path -> Projection field path */ @NonNull public static <P extends Entity<P>, T extends Entity<T>> Map<String, String> strictFieldMapping( @NonNull Class<P> projectionType, @NonNull Class<T> entityType) { EntitySchema<T> entitySchema = EntitySchema.of(entityType); Class<?> entityIdType = entitySchema.getIdSchema().getType(); List<Schema.JavaField> projectionIdFields = EntityIdSchema.ofEntity(projectionType).getFields(); Map<String, String> mapping = new HashMap<>(); projectionIdFields .stream() .filter(f -> !isEntityId(f, entityIdType)) .flatMap(Schema.JavaField::flatten) .forEach(f -> mapping.put(getMatchingNonIdField(f, entitySchema).getPath(), f.getPath())); List<Schema.JavaField> idTypeFields = projectionIdFields.stream() .filter(f -> isEntityId(f, entityIdType)) .collect(toList()); if (idTypeFields.size() > 1) { throw new IllegalStateException("Projection ID cannot have more than 1 field with type: " + entityIdType); } if (idTypeFields.size() == 0) { return mapping; } idTypeFields.get(0).flatten().forEach(idPart -> mapping.put(getMatchingIdField(idPart, entitySchema).getPath(), idPart.getPath())); return mapping; } private static boolean isEntityId(@NonNull Schema.JavaField field, @NonNull Class<?> entityIdType) { return field.getType().equals(entityIdType); } @NonNull private static Optional<Schema.JavaField> findMatchingNonIdField(@NonNull Schema.JavaField projectionField, @NonNull EntitySchema<?> realEntity) { // Entity.<field> <-> Projection.id.<field> return realEntity.findField(projectionField.getRawPath()); } @NonNull private static Schema.JavaField getMatchingNonIdField(@NonNull Schema.JavaField projectionField, @NonNull EntitySchema<?> realEntity) { // Entity.<field> <-> Projection.id.<field> return realEntity.getField(projectionField.getRawPath()); } @NonNull private static Schema.JavaField getMatchingIdField(@NonNull Schema.JavaField projectionIdField, @NonNull EntitySchema<?> realEntity) { // Entity.id[.<subfield>] <-> Projection.id.<entity ID-typed field name>[.<subfield>] return realEntity.getIdSchema().getField(projectionIdField.getRawSubPath(1)); } @NonNull public static <P extends Entity<P>> ListViaProjection<P> listViaProjection(@NonNull Class<P> projectionType) { return new ListViaProjection<>(projectionType); } @RequiredArgsConstructor(access = PRIVATE) public static final class ListViaProjection<P extends Entity<P>> { private final Class<P> projectionType; @NonNull public <T extends Entity<T>> Listing<T, P> entities(@NonNull ListRequest<T> request) { return entities(request, lenientFieldMapping(projectionType, request.getSchema().getType())); } @NonNull public <T extends Entity<T>> Listing<T, P> entities(@NonNull ListRequest<T> request, @NonNull Map<String, String> fieldMapping) { return entities(request, f -> getFieldMapping(fieldMapping, f)); } @NonNull private String getFieldMapping(@NonNull Map<String, String> fieldMapping, String f) { String mapping = fieldMapping.get(f); Preconditions.checkState(mapping != null, "No mapping for entity field \"%s\" in projection %s", f, projectionType); return mapping; } @NonNull public <T extends Entity<T>> Listing<T, P> entities(@NonNull ListRequest<T> request, @NonNull UnaryOperator<String> fieldMapping) { return new Listing<>(request, request.forEntity(projectionType, fieldMapping)); } @RequiredArgsConstructor(access = PRIVATE) public static final class Listing<T extends Entity<T>, P extends Entity<P>> { private final ListRequest<T> request; private final ListRequest<P> projRequest; @NonNull public TransformedListing<T, P> transforming(@NonNull Function<P, T> unproject) { return new TransformedListing<>(this, unproject); } @NonNull
package tech.ydb.yoj.repository.db.projection; public final class ProjectionMappings { private ProjectionMappings() { } /** * Creates a <em>lenient</em> one-to-one mapping from entity fields to projection fields, which contains all * {@link #strictFieldMapping(Class, Class) strict mappings}, plus mappings of the form * {@code <entity field> <-> <projection field with the same path>} (if both fields exist). * * @param projectionType projection class * @param entityType entity class * @param <P> projection type * @param <T> entity type * @return Map: Entity field path -> Projection field path * @see #strictFieldMapping(Class, Class) */ @NonNull public static <P extends Entity<P>, T extends Entity<T>> Map<String, String> lenientFieldMapping( @NonNull Class<P> projectionType, @NonNull Class<T> entityType) { EntitySchema<T> entitySchema = EntitySchema.of(entityType); Class<?> entityIdType = entitySchema.getIdSchema().getType(); BiMap<String, String> mapping = HashBiMap.create(strictFieldMapping(projectionType, entityType)); EntitySchema.of(projectionType).flattenFields() .stream() .filter(pf -> !isEntityId(pf, entityIdType) && !mapping.inverse().containsKey(pf.getPath())) .forEach(pf -> findMatchingNonIdField(pf, entitySchema) .ifPresent(ef -> mapping.put(ef.getPath(), pf.getPath())) ); return mapping; } /** * Creates a one-to-one mapping from entity fields to entity projection ID fields, assuming that the projection ID * contains fields with the same name as in the main entity and <em>at most one</em> field for the main entity ID * (with any name). * </ul> * <p> * <em>E.g.</em>, the following entity-projection pair qualifies: <blockquote><pre> * &#64;Value class MyEntity implements Entity&lt;MyEntity> { * Id id; * String field; * * &#64;Value static class Id implements Entity.Id&lt;MyEntity> { String value; } * } * * &#64;Value class MyIndex implements Entity&lt;MyIndex> { * Id id; * * &#64;Value * static class Id implements Entity.Id&lt;MyIndex> { * // MUST have the same Java field name as in the entity class * // (DB name specified in &#64;Column annotation does not matter.) * String field; * * // OPTIONAL. If present, this field MAY have any name * MyEntity.Id entityId; * } * } * </pre></blockquote> * * @param projectionType projection class * @param entityType entity class * @param <P> projection type * @param <T> entity type * @return Bidirectional mapping: Entity field path -> Projection field path */ @NonNull public static <P extends Entity<P>, T extends Entity<T>> Map<String, String> strictFieldMapping( @NonNull Class<P> projectionType, @NonNull Class<T> entityType) { EntitySchema<T> entitySchema = EntitySchema.of(entityType); Class<?> entityIdType = entitySchema.getIdSchema().getType(); List<Schema.JavaField> projectionIdFields = EntityIdSchema.ofEntity(projectionType).getFields(); Map<String, String> mapping = new HashMap<>(); projectionIdFields .stream() .filter(f -> !isEntityId(f, entityIdType)) .flatMap(Schema.JavaField::flatten) .forEach(f -> mapping.put(getMatchingNonIdField(f, entitySchema).getPath(), f.getPath())); List<Schema.JavaField> idTypeFields = projectionIdFields.stream() .filter(f -> isEntityId(f, entityIdType)) .collect(toList()); if (idTypeFields.size() > 1) { throw new IllegalStateException("Projection ID cannot have more than 1 field with type: " + entityIdType); } if (idTypeFields.size() == 0) { return mapping; } idTypeFields.get(0).flatten().forEach(idPart -> mapping.put(getMatchingIdField(idPart, entitySchema).getPath(), idPart.getPath())); return mapping; } private static boolean isEntityId(@NonNull Schema.JavaField field, @NonNull Class<?> entityIdType) { return field.getType().equals(entityIdType); } @NonNull private static Optional<Schema.JavaField> findMatchingNonIdField(@NonNull Schema.JavaField projectionField, @NonNull EntitySchema<?> realEntity) { // Entity.<field> <-> Projection.id.<field> return realEntity.findField(projectionField.getRawPath()); } @NonNull private static Schema.JavaField getMatchingNonIdField(@NonNull Schema.JavaField projectionField, @NonNull EntitySchema<?> realEntity) { // Entity.<field> <-> Projection.id.<field> return realEntity.getField(projectionField.getRawPath()); } @NonNull private static Schema.JavaField getMatchingIdField(@NonNull Schema.JavaField projectionIdField, @NonNull EntitySchema<?> realEntity) { // Entity.id[.<subfield>] <-> Projection.id.<entity ID-typed field name>[.<subfield>] return realEntity.getIdSchema().getField(projectionIdField.getRawSubPath(1)); } @NonNull public static <P extends Entity<P>> ListViaProjection<P> listViaProjection(@NonNull Class<P> projectionType) { return new ListViaProjection<>(projectionType); } @RequiredArgsConstructor(access = PRIVATE) public static final class ListViaProjection<P extends Entity<P>> { private final Class<P> projectionType; @NonNull public <T extends Entity<T>> Listing<T, P> entities(@NonNull ListRequest<T> request) { return entities(request, lenientFieldMapping(projectionType, request.getSchema().getType())); } @NonNull public <T extends Entity<T>> Listing<T, P> entities(@NonNull ListRequest<T> request, @NonNull Map<String, String> fieldMapping) { return entities(request, f -> getFieldMapping(fieldMapping, f)); } @NonNull private String getFieldMapping(@NonNull Map<String, String> fieldMapping, String f) { String mapping = fieldMapping.get(f); Preconditions.checkState(mapping != null, "No mapping for entity field \"%s\" in projection %s", f, projectionType); return mapping; } @NonNull public <T extends Entity<T>> Listing<T, P> entities(@NonNull ListRequest<T> request, @NonNull UnaryOperator<String> fieldMapping) { return new Listing<>(request, request.forEntity(projectionType, fieldMapping)); } @RequiredArgsConstructor(access = PRIVATE) public static final class Listing<T extends Entity<T>, P extends Entity<P>> { private final ListRequest<T> request; private final ListRequest<P> projRequest; @NonNull public TransformedListing<T, P> transforming(@NonNull Function<P, T> unproject) { return new TransformedListing<>(this, unproject); } @NonNull
public ListResult<P> run(@NonNull Function<ListRequest<P>, ListResult<P>> listFunc) {
5
2023-12-05 15:57:58+00:00
16k
Vera-Firefly/PojavLauncher-Experimental-Edition
app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/prefs/LauncherPreferences.java
[ { "identifier": "is32BitsDevice", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/Architecture.java", "snippet": "public static boolean is32BitsDevice(){\n\treturn !is64BitsDevice();\n}" }, { "identifier": "MultiRTUtils", "path": "app_pojavlauncher/src/main/java/net/kdt/pojavlau...
import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.P; import static net.kdt.pojavlaunch.Architecture.is32BitsDevice; import android.app.Activity; import android.content.*; import android.graphics.Rect; import android.os.Build; import android.util.Log; import net.kdt.pojavlaunch.*; import net.kdt.pojavlaunch.multirt.MultiRTUtils; import net.kdt.pojavlaunch.utils.JREUtils;
10,839
package net.kdt.pojavlaunch.prefs; public class LauncherPreferences { public static final String PREF_KEY_CURRENT_PROFILE = "currentProfile"; public static final String PREF_KEY_SKIP_NOTIFICATION_CHECK = "skipNotificationPermissionCheck"; public static SharedPreferences DEFAULT_PREF; public static String PREF_RENDERER = "opengles2"; public static boolean PREF_VERTYPE_RELEASE = true; public static boolean PREF_VERTYPE_SNAPSHOT = false; public static boolean PREF_VERTYPE_OLDALPHA = false; public static boolean PREF_VERTYPE_OLDBETA = false; public static boolean PREF_HIDE_SIDEBAR = false; public static boolean PREF_IGNORE_NOTCH = false; public static int PREF_NOTCH_SIZE = 0; public static float PREF_BUTTONSIZE = 100f; public static float PREF_MOUSESCALE = 100f; public static int PREF_LONGPRESS_TRIGGER = 300; public static String PREF_DEFAULTCTRL_PATH = Tools.CTRLDEF_FILE; public static String PREF_CUSTOM_JAVA_ARGS; public static boolean PREF_FORCE_ENGLISH = false; public static final String PREF_VERSION_REPOS = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json"; public static boolean PREF_CHECK_LIBRARY_SHA = true; public static boolean PREF_DISABLE_GESTURES = false; public static boolean PREF_DISABLE_SWAP_HAND = false; public static float PREF_MOUSESPEED = 1f; public static int PREF_RAM_ALLOCATION; public static String PREF_DEFAULT_RUNTIME; public static boolean PREF_SUSTAINED_PERFORMANCE = false; public static boolean PREF_VIRTUAL_MOUSE_START = false; public static boolean PREF_ARC_CAPES = false; public static boolean PREF_USE_ALTERNATE_SURFACE = true; public static boolean PREF_JAVA_SANDBOX = true; public static int PREF_SCALE_FACTOR = 100; public static boolean PREF_ENABLE_GYRO = false; public static float PREF_GYRO_SENSITIVITY = 1f; public static int PREF_GYRO_SAMPLE_RATE = 16; public static boolean PREF_GYRO_SMOOTHING = true; public static boolean PREF_GYRO_INVERT_X = false; public static boolean PREF_GYRO_INVERT_Y = false; public static boolean PREF_FORCE_VSYNC = false; public static boolean PREF_BUTTON_ALL_CAPS = true; public static boolean PREF_DUMP_SHADERS = false; public static float PREF_DEADZONE_SCALE = 1f; public static boolean PREF_BIG_CORE_AFFINITY = false; public static boolean PREF_ZINK_PREFER_SYSTEM_DRIVER = false; public static boolean PREF_ZINK_CRASH_HANDLE = false; public static boolean PREF_EXP_SETUP = false; public static boolean PREF_EXP_SETUP_DEFAULT = false; public static boolean PREF_EXP_SETUP_S = false; public static boolean PREF_EXP_SETUP_LW = false; public static boolean PREF_EXP_SETUP_VIRGL = false; public static boolean PREF_EXP_SETUP_PAN = false; public static boolean PREF_EXP_SETUP_FD = false; public static boolean PREF_VERIFY_MANIFEST = true; public static String PREF_DOWNLOAD_SOURCE = "default"; public static boolean PREF_SKIP_NOTIFICATION_PERMISSION_CHECK = false; public static boolean PREF_VSYNC_IN_ZINK = true; public static boolean PREF_SHOW_FIREFLY_AD = true; public static void loadPreferences(Context ctx) { //Required for the data folder. Tools.initContextConstants(ctx); PREF_RENDERER = DEFAULT_PREF.getString("renderer", "opengles2"); PREF_BUTTONSIZE = DEFAULT_PREF.getInt("buttonscale", 100); PREF_MOUSESCALE = DEFAULT_PREF.getInt("mousescale", 100); PREF_MOUSESPEED = ((float)DEFAULT_PREF.getInt("mousespeed",100))/100f; PREF_HIDE_SIDEBAR = DEFAULT_PREF.getBoolean("hideSidebar", false); PREF_IGNORE_NOTCH = DEFAULT_PREF.getBoolean("ignoreNotch", false); PREF_VERTYPE_RELEASE = DEFAULT_PREF.getBoolean("vertype_release", true); PREF_VERTYPE_SNAPSHOT = DEFAULT_PREF.getBoolean("vertype_snapshot", false); PREF_VERTYPE_OLDALPHA = DEFAULT_PREF.getBoolean("vertype_oldalpha", false); PREF_VERTYPE_OLDBETA = DEFAULT_PREF.getBoolean("vertype_oldbeta", false); PREF_LONGPRESS_TRIGGER = DEFAULT_PREF.getInt("timeLongPressTrigger", 300); PREF_DEFAULTCTRL_PATH = DEFAULT_PREF.getString("defaultCtrl", Tools.CTRLDEF_FILE); PREF_FORCE_ENGLISH = DEFAULT_PREF.getBoolean("force_english", false); PREF_CHECK_LIBRARY_SHA = DEFAULT_PREF.getBoolean("checkLibraries",true); PREF_DISABLE_GESTURES = DEFAULT_PREF.getBoolean("disableGestures",false); PREF_DISABLE_SWAP_HAND = DEFAULT_PREF.getBoolean("disableDoubleTap", false); PREF_RAM_ALLOCATION = DEFAULT_PREF.getInt("allocation", findBestRAMAllocation(ctx)); PREF_CUSTOM_JAVA_ARGS = DEFAULT_PREF.getString("javaArgs", ""); PREF_SUSTAINED_PERFORMANCE = DEFAULT_PREF.getBoolean("sustainedPerformance", false); PREF_VIRTUAL_MOUSE_START = DEFAULT_PREF.getBoolean("mouse_start", false); PREF_ARC_CAPES = DEFAULT_PREF.getBoolean("arc_capes",false); PREF_USE_ALTERNATE_SURFACE = DEFAULT_PREF.getBoolean("alternate_surface", false); PREF_JAVA_SANDBOX = DEFAULT_PREF.getBoolean("java_sandbox", true); PREF_SCALE_FACTOR = DEFAULT_PREF.getInt("resolutionRatio", 100); PREF_ENABLE_GYRO = DEFAULT_PREF.getBoolean("enableGyro", false); PREF_GYRO_SENSITIVITY = ((float)DEFAULT_PREF.getInt("gyroSensitivity", 100))/100f; PREF_GYRO_SAMPLE_RATE = DEFAULT_PREF.getInt("gyroSampleRate", 16); PREF_GYRO_SMOOTHING = DEFAULT_PREF.getBoolean("gyroSmoothing", true); PREF_GYRO_INVERT_X = DEFAULT_PREF.getBoolean("gyroInvertX", false); PREF_GYRO_INVERT_Y = DEFAULT_PREF.getBoolean("gyroInvertY", false); PREF_FORCE_VSYNC = DEFAULT_PREF.getBoolean("force_vsync", false); PREF_BUTTON_ALL_CAPS = DEFAULT_PREF.getBoolean("buttonAllCaps", true); PREF_DUMP_SHADERS = DEFAULT_PREF.getBoolean("dump_shaders", false); PREF_DEADZONE_SCALE = ((float) DEFAULT_PREF.getInt("gamepad_deadzone_scale", 100))/100f; PREF_BIG_CORE_AFFINITY = DEFAULT_PREF.getBoolean("bigCoreAffinity", false); PREF_ZINK_PREFER_SYSTEM_DRIVER = DEFAULT_PREF.getBoolean("zinkPreferSystemDriver", false); PREF_ZINK_CRASH_HANDLE = DEFAULT_PREF.getBoolean("zinkCrashhandle", false); PREF_DOWNLOAD_SOURCE = DEFAULT_PREF.getString("downloadSource", "default"); PREF_VERIFY_MANIFEST = DEFAULT_PREF.getBoolean("verifyManifest", true); PREF_SKIP_NOTIFICATION_PERMISSION_CHECK = DEFAULT_PREF.getBoolean(PREF_KEY_SKIP_NOTIFICATION_CHECK, false); PREF_VSYNC_IN_ZINK = DEFAULT_PREF.getBoolean("vsync_in_zink", true); PREF_EXP_SETUP = DEFAULT_PREF.getBoolean("ExperimentalSetup", false); PREF_EXP_SETUP_DEFAULT = DEFAULT_PREF.getBoolean("ZinkF", false); PREF_EXP_SETUP_S = DEFAULT_PREF.getBoolean("ZinkS", false); PREF_EXP_SETUP_LW = DEFAULT_PREF.getBoolean("VulkanLwarlip", false); PREF_EXP_SETUP_VIRGL = DEFAULT_PREF.getBoolean("Rvirpipe", false); PREF_EXP_SETUP_PAN = DEFAULT_PREF.getBoolean("Rpanfrost", false); PREF_EXP_SETUP_FD = DEFAULT_PREF.getBoolean("Rfreedreno", false); PREF_SHOW_FIREFLY_AD = DEFAULT_PREF.getBoolean("FireflyAlertDialog", true); String argLwjglLibname = "-Dorg.lwjgl.opengl.libname=";
package net.kdt.pojavlaunch.prefs; public class LauncherPreferences { public static final String PREF_KEY_CURRENT_PROFILE = "currentProfile"; public static final String PREF_KEY_SKIP_NOTIFICATION_CHECK = "skipNotificationPermissionCheck"; public static SharedPreferences DEFAULT_PREF; public static String PREF_RENDERER = "opengles2"; public static boolean PREF_VERTYPE_RELEASE = true; public static boolean PREF_VERTYPE_SNAPSHOT = false; public static boolean PREF_VERTYPE_OLDALPHA = false; public static boolean PREF_VERTYPE_OLDBETA = false; public static boolean PREF_HIDE_SIDEBAR = false; public static boolean PREF_IGNORE_NOTCH = false; public static int PREF_NOTCH_SIZE = 0; public static float PREF_BUTTONSIZE = 100f; public static float PREF_MOUSESCALE = 100f; public static int PREF_LONGPRESS_TRIGGER = 300; public static String PREF_DEFAULTCTRL_PATH = Tools.CTRLDEF_FILE; public static String PREF_CUSTOM_JAVA_ARGS; public static boolean PREF_FORCE_ENGLISH = false; public static final String PREF_VERSION_REPOS = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json"; public static boolean PREF_CHECK_LIBRARY_SHA = true; public static boolean PREF_DISABLE_GESTURES = false; public static boolean PREF_DISABLE_SWAP_HAND = false; public static float PREF_MOUSESPEED = 1f; public static int PREF_RAM_ALLOCATION; public static String PREF_DEFAULT_RUNTIME; public static boolean PREF_SUSTAINED_PERFORMANCE = false; public static boolean PREF_VIRTUAL_MOUSE_START = false; public static boolean PREF_ARC_CAPES = false; public static boolean PREF_USE_ALTERNATE_SURFACE = true; public static boolean PREF_JAVA_SANDBOX = true; public static int PREF_SCALE_FACTOR = 100; public static boolean PREF_ENABLE_GYRO = false; public static float PREF_GYRO_SENSITIVITY = 1f; public static int PREF_GYRO_SAMPLE_RATE = 16; public static boolean PREF_GYRO_SMOOTHING = true; public static boolean PREF_GYRO_INVERT_X = false; public static boolean PREF_GYRO_INVERT_Y = false; public static boolean PREF_FORCE_VSYNC = false; public static boolean PREF_BUTTON_ALL_CAPS = true; public static boolean PREF_DUMP_SHADERS = false; public static float PREF_DEADZONE_SCALE = 1f; public static boolean PREF_BIG_CORE_AFFINITY = false; public static boolean PREF_ZINK_PREFER_SYSTEM_DRIVER = false; public static boolean PREF_ZINK_CRASH_HANDLE = false; public static boolean PREF_EXP_SETUP = false; public static boolean PREF_EXP_SETUP_DEFAULT = false; public static boolean PREF_EXP_SETUP_S = false; public static boolean PREF_EXP_SETUP_LW = false; public static boolean PREF_EXP_SETUP_VIRGL = false; public static boolean PREF_EXP_SETUP_PAN = false; public static boolean PREF_EXP_SETUP_FD = false; public static boolean PREF_VERIFY_MANIFEST = true; public static String PREF_DOWNLOAD_SOURCE = "default"; public static boolean PREF_SKIP_NOTIFICATION_PERMISSION_CHECK = false; public static boolean PREF_VSYNC_IN_ZINK = true; public static boolean PREF_SHOW_FIREFLY_AD = true; public static void loadPreferences(Context ctx) { //Required for the data folder. Tools.initContextConstants(ctx); PREF_RENDERER = DEFAULT_PREF.getString("renderer", "opengles2"); PREF_BUTTONSIZE = DEFAULT_PREF.getInt("buttonscale", 100); PREF_MOUSESCALE = DEFAULT_PREF.getInt("mousescale", 100); PREF_MOUSESPEED = ((float)DEFAULT_PREF.getInt("mousespeed",100))/100f; PREF_HIDE_SIDEBAR = DEFAULT_PREF.getBoolean("hideSidebar", false); PREF_IGNORE_NOTCH = DEFAULT_PREF.getBoolean("ignoreNotch", false); PREF_VERTYPE_RELEASE = DEFAULT_PREF.getBoolean("vertype_release", true); PREF_VERTYPE_SNAPSHOT = DEFAULT_PREF.getBoolean("vertype_snapshot", false); PREF_VERTYPE_OLDALPHA = DEFAULT_PREF.getBoolean("vertype_oldalpha", false); PREF_VERTYPE_OLDBETA = DEFAULT_PREF.getBoolean("vertype_oldbeta", false); PREF_LONGPRESS_TRIGGER = DEFAULT_PREF.getInt("timeLongPressTrigger", 300); PREF_DEFAULTCTRL_PATH = DEFAULT_PREF.getString("defaultCtrl", Tools.CTRLDEF_FILE); PREF_FORCE_ENGLISH = DEFAULT_PREF.getBoolean("force_english", false); PREF_CHECK_LIBRARY_SHA = DEFAULT_PREF.getBoolean("checkLibraries",true); PREF_DISABLE_GESTURES = DEFAULT_PREF.getBoolean("disableGestures",false); PREF_DISABLE_SWAP_HAND = DEFAULT_PREF.getBoolean("disableDoubleTap", false); PREF_RAM_ALLOCATION = DEFAULT_PREF.getInt("allocation", findBestRAMAllocation(ctx)); PREF_CUSTOM_JAVA_ARGS = DEFAULT_PREF.getString("javaArgs", ""); PREF_SUSTAINED_PERFORMANCE = DEFAULT_PREF.getBoolean("sustainedPerformance", false); PREF_VIRTUAL_MOUSE_START = DEFAULT_PREF.getBoolean("mouse_start", false); PREF_ARC_CAPES = DEFAULT_PREF.getBoolean("arc_capes",false); PREF_USE_ALTERNATE_SURFACE = DEFAULT_PREF.getBoolean("alternate_surface", false); PREF_JAVA_SANDBOX = DEFAULT_PREF.getBoolean("java_sandbox", true); PREF_SCALE_FACTOR = DEFAULT_PREF.getInt("resolutionRatio", 100); PREF_ENABLE_GYRO = DEFAULT_PREF.getBoolean("enableGyro", false); PREF_GYRO_SENSITIVITY = ((float)DEFAULT_PREF.getInt("gyroSensitivity", 100))/100f; PREF_GYRO_SAMPLE_RATE = DEFAULT_PREF.getInt("gyroSampleRate", 16); PREF_GYRO_SMOOTHING = DEFAULT_PREF.getBoolean("gyroSmoothing", true); PREF_GYRO_INVERT_X = DEFAULT_PREF.getBoolean("gyroInvertX", false); PREF_GYRO_INVERT_Y = DEFAULT_PREF.getBoolean("gyroInvertY", false); PREF_FORCE_VSYNC = DEFAULT_PREF.getBoolean("force_vsync", false); PREF_BUTTON_ALL_CAPS = DEFAULT_PREF.getBoolean("buttonAllCaps", true); PREF_DUMP_SHADERS = DEFAULT_PREF.getBoolean("dump_shaders", false); PREF_DEADZONE_SCALE = ((float) DEFAULT_PREF.getInt("gamepad_deadzone_scale", 100))/100f; PREF_BIG_CORE_AFFINITY = DEFAULT_PREF.getBoolean("bigCoreAffinity", false); PREF_ZINK_PREFER_SYSTEM_DRIVER = DEFAULT_PREF.getBoolean("zinkPreferSystemDriver", false); PREF_ZINK_CRASH_HANDLE = DEFAULT_PREF.getBoolean("zinkCrashhandle", false); PREF_DOWNLOAD_SOURCE = DEFAULT_PREF.getString("downloadSource", "default"); PREF_VERIFY_MANIFEST = DEFAULT_PREF.getBoolean("verifyManifest", true); PREF_SKIP_NOTIFICATION_PERMISSION_CHECK = DEFAULT_PREF.getBoolean(PREF_KEY_SKIP_NOTIFICATION_CHECK, false); PREF_VSYNC_IN_ZINK = DEFAULT_PREF.getBoolean("vsync_in_zink", true); PREF_EXP_SETUP = DEFAULT_PREF.getBoolean("ExperimentalSetup", false); PREF_EXP_SETUP_DEFAULT = DEFAULT_PREF.getBoolean("ZinkF", false); PREF_EXP_SETUP_S = DEFAULT_PREF.getBoolean("ZinkS", false); PREF_EXP_SETUP_LW = DEFAULT_PREF.getBoolean("VulkanLwarlip", false); PREF_EXP_SETUP_VIRGL = DEFAULT_PREF.getBoolean("Rvirpipe", false); PREF_EXP_SETUP_PAN = DEFAULT_PREF.getBoolean("Rpanfrost", false); PREF_EXP_SETUP_FD = DEFAULT_PREF.getBoolean("Rfreedreno", false); PREF_SHOW_FIREFLY_AD = DEFAULT_PREF.getBoolean("FireflyAlertDialog", true); String argLwjglLibname = "-Dorg.lwjgl.opengl.libname=";
for (String arg : JREUtils.parseJavaArguments(PREF_CUSTOM_JAVA_ARGS)) {
2
2023-12-01 16:16:12+00:00
16k
kawashirov/distant-horizons
common/src/main/java/com/seibel/distanthorizons/common/wrappers/world/ServerLevelWrapper.java
[ { "identifier": "McObjectConverter", "path": "common/src/main/java/com/seibel/distanthorizons/common/wrappers/McObjectConverter.java", "snippet": "public class McObjectConverter\n{\n\tprivate static int bufferIndex(int x, int y)\n\t{\n\t\treturn y * 4 + x;\n\t}\n\t/** Taken from Minecraft's com.mojang.m...
import java.io.File; import java.util.concurrent.ConcurrentHashMap; import com.seibel.distanthorizons.api.enums.worldGeneration.EDhApiLevelType; import com.seibel.distanthorizons.common.wrappers.McObjectConverter; import com.seibel.distanthorizons.common.wrappers.block.BiomeWrapper; import com.seibel.distanthorizons.common.wrappers.block.BlockStateWrapper; import com.seibel.distanthorizons.common.wrappers.block.cache.ServerBlockDetailMap; import com.seibel.distanthorizons.common.wrappers.chunk.ChunkWrapper; import com.seibel.distanthorizons.common.wrappers.minecraft.MinecraftClientWrapper; import com.seibel.distanthorizons.core.logging.DhLoggerBuilder; import com.seibel.distanthorizons.core.pos.DhBlockPos; import com.seibel.distanthorizons.core.pos.DhChunkPos; import com.seibel.distanthorizons.core.wrapperInterfaces.block.IBlockStateWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.chunk.IChunkWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IBiomeWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IClientLevelWrapper; import com.seibel.distanthorizons.core.wrapperInterfaces.world.IServerLevelWrapper; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkSource; import net.minecraft.world.level.chunk.ChunkStatus; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.Nullable;
13,117
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program 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, version 3. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.common.wrappers.world; /** * @version 2022-9-16 */ public class ServerLevelWrapper implements IServerLevelWrapper { private static final Logger LOGGER = DhLoggerBuilder.getLogger(); private static final ConcurrentHashMap<ServerLevel, ServerLevelWrapper> LEVEL_WRAPPER_BY_SERVER_LEVEL = new ConcurrentHashMap<>(); final ServerLevel level; ServerBlockDetailMap blockMap = new ServerBlockDetailMap(this); //==============// // constructors // //==============// public static ServerLevelWrapper getWrapper(ServerLevel level) { return LEVEL_WRAPPER_BY_SERVER_LEVEL.computeIfAbsent(level, ServerLevelWrapper::new); } public ServerLevelWrapper(ServerLevel level) { this.level = level; } //=========// // methods // //=========// @Nullable @Override public IClientLevelWrapper tryGetClientLevelWrapper() { MinecraftClientWrapper client = MinecraftClientWrapper.INSTANCE; if (client.mc.level == null) { return null; } return ClientLevelWrapper.getWrapper(client.mc.level); } @Override public File getSaveFolder() { return level.getChunkSource().getDataStorage().dataFolder; } @Override public DimensionTypeWrapper getDimensionType() { return DimensionTypeWrapper.getDimensionTypeWrapper(level.dimensionType()); } @Override public EDhApiLevelType getLevelType() { return EDhApiLevelType.SERVER_LEVEL; } public ServerLevel getLevel() { return level; } @Override public boolean hasCeiling() { return level.dimensionType().hasCeiling(); } @Override public boolean hasSkyLight() { return level.dimensionType().hasSkyLight(); } @Override public int getHeight() { return level.getHeight(); } @Override public int getMinHeight() { #if PRE_MC_1_17_1 return 0; #else return level.getMinBuildHeight(); #endif } @Override public IChunkWrapper tryGetChunk(DhChunkPos pos) { if (!level.hasChunk(pos.x, pos.z)) return null; ChunkAccess chunk = level.getChunk(pos.x, pos.z, ChunkStatus.FULL, false); if (chunk == null) return null;
/* * This file is part of the Distant Horizons mod * licensed under the GNU LGPL v3 License. * * Copyright (C) 2020-2023 James Seibel * * This program 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, version 3. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.seibel.distanthorizons.common.wrappers.world; /** * @version 2022-9-16 */ public class ServerLevelWrapper implements IServerLevelWrapper { private static final Logger LOGGER = DhLoggerBuilder.getLogger(); private static final ConcurrentHashMap<ServerLevel, ServerLevelWrapper> LEVEL_WRAPPER_BY_SERVER_LEVEL = new ConcurrentHashMap<>(); final ServerLevel level; ServerBlockDetailMap blockMap = new ServerBlockDetailMap(this); //==============// // constructors // //==============// public static ServerLevelWrapper getWrapper(ServerLevel level) { return LEVEL_WRAPPER_BY_SERVER_LEVEL.computeIfAbsent(level, ServerLevelWrapper::new); } public ServerLevelWrapper(ServerLevel level) { this.level = level; } //=========// // methods // //=========// @Nullable @Override public IClientLevelWrapper tryGetClientLevelWrapper() { MinecraftClientWrapper client = MinecraftClientWrapper.INSTANCE; if (client.mc.level == null) { return null; } return ClientLevelWrapper.getWrapper(client.mc.level); } @Override public File getSaveFolder() { return level.getChunkSource().getDataStorage().dataFolder; } @Override public DimensionTypeWrapper getDimensionType() { return DimensionTypeWrapper.getDimensionTypeWrapper(level.dimensionType()); } @Override public EDhApiLevelType getLevelType() { return EDhApiLevelType.SERVER_LEVEL; } public ServerLevel getLevel() { return level; } @Override public boolean hasCeiling() { return level.dimensionType().hasCeiling(); } @Override public boolean hasSkyLight() { return level.dimensionType().hasSkyLight(); } @Override public int getHeight() { return level.getHeight(); } @Override public int getMinHeight() { #if PRE_MC_1_17_1 return 0; #else return level.getMinBuildHeight(); #endif } @Override public IChunkWrapper tryGetChunk(DhChunkPos pos) { if (!level.hasChunk(pos.x, pos.z)) return null; ChunkAccess chunk = level.getChunk(pos.x, pos.z, ChunkStatus.FULL, false); if (chunk == null) return null;
return new ChunkWrapper(chunk, level, this);
4
2023-12-04 11:41:46+00:00
16k
hmcts/juror-sql-support-library
src/main/java/uk/gov/hmcts/juror/support/sql/service/SqlSupportService.java
[ { "identifier": "Constants", "path": "src/main/java/uk/gov/hmcts/juror/support/sql/Constants.java", "snippet": "public class Constants {\n\n public static final String PHONE_REGEX = \"^(\\\\+44|0)7\\\\d{9}$\";\n public static final String NOTES_REGEX = \"[A-Za-z0-9]{10,501}\";\n public static f...
import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StopWatch; import uk.gov.hmcts.juror.support.generation.generators.value.RandomFromCollectionGeneratorImpl; import uk.gov.hmcts.juror.support.generation.util.RandomGenerator; import uk.gov.hmcts.juror.support.sql.Constants; import uk.gov.hmcts.juror.support.sql.Util; import uk.gov.hmcts.juror.support.sql.dto.JurorAccountDetailsDto; import uk.gov.hmcts.juror.support.sql.entity.CourtLocation; import uk.gov.hmcts.juror.support.sql.entity.Juror; import uk.gov.hmcts.juror.support.sql.entity.JurorGenerator; import uk.gov.hmcts.juror.support.sql.entity.JurorPool; import uk.gov.hmcts.juror.support.sql.entity.JurorPoolGenerator; import uk.gov.hmcts.juror.support.sql.entity.JurorStatus; import uk.gov.hmcts.juror.support.sql.entity.PoolRequest; import uk.gov.hmcts.juror.support.sql.entity.PoolRequestGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.AbstractJurorResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.AbstractJurorResponseGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.DigitalResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.DigitalResponseGenerator; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.PaperResponse; import uk.gov.hmcts.juror.support.sql.entity.jurorresponse.PaperResponseGenerator; import uk.gov.hmcts.juror.support.sql.generators.DigitalResponseGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.JurorGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.JurorPoolGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.PaperResponseGeneratorUtil; import uk.gov.hmcts.juror.support.sql.generators.PoolRequestGeneratorUtil; import uk.gov.hmcts.juror.support.sql.repository.CourtLocationRepository; import uk.gov.hmcts.juror.support.sql.repository.DigitalResponseRepository; import uk.gov.hmcts.juror.support.sql.repository.JurorPoolRepository; import uk.gov.hmcts.juror.support.sql.repository.JurorRepository; import uk.gov.hmcts.juror.support.sql.repository.PaperResponseRepository; import uk.gov.hmcts.juror.support.sql.repository.PoolRequestRepository; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiFunction; import java.util.stream.Collectors;
12,653
package uk.gov.hmcts.juror.support.sql.service; @Component @RequiredArgsConstructor(onConstructor = @__(@Autowired)) @Slf4j public class SqlSupportService { private final JurorRepository jurorRepository; private final PoolRequestRepository poolRequestRepository; private final JurorPoolRepository jurorPoolRepository; private final DigitalResponseRepository digitalResponseRepository; private final PaperResponseRepository paperResponseRepository; private StopWatch stopWatch;
package uk.gov.hmcts.juror.support.sql.service; @Component @RequiredArgsConstructor(onConstructor = @__(@Autowired)) @Slf4j public class SqlSupportService { private final JurorRepository jurorRepository; private final PoolRequestRepository poolRequestRepository; private final JurorPoolRepository jurorPoolRepository; private final DigitalResponseRepository digitalResponseRepository; private final PaperResponseRepository paperResponseRepository; private StopWatch stopWatch;
private final CourtLocationRepository courtLocationRepository;
16
2023-12-01 11:38:42+00:00
16k
SuperRicky14/TpaPlusPlus
src/main/java/net/superricky/tpaplusplus/util/manager/EventHandler.java
[ { "identifier": "Main", "path": "src/main/java/net/superricky/tpaplusplus/Main.java", "snippet": "@Mod(Main.MOD_ID)\npublic class Main {\n // Our mod id\n public static final String MOD_ID = \"tpaplusplus\";\n public static final String MOD_VERSION = \"1.3-1.20.x-BETA-3\";\n\n public Main() ...
import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.LivingEntity; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.level.LevelEvent; import net.minecraftforge.event.server.ServerStartedEvent; import net.minecraftforge.event.server.ServerStoppedEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.superricky.tpaplusplus.Main; import net.superricky.tpaplusplus.event.RequestMovedEvent; import net.superricky.tpaplusplus.util.LevelBoundVec3; import net.superricky.tpaplusplus.util.Request; import net.superricky.tpaplusplus.util.configuration.Config; import net.superricky.tpaplusplus.util.configuration.Messages; import net.superricky.tpaplusplus.event.RequestAcceptSuccessEvent; import net.superricky.tpaplusplus.event.RequestTimeoutEvent; import net.superricky.tpaplusplus.util.configuration.formatters.MessageParser; import net.superricky.tpaplusplus.util.manager.saved.SaveDataManager; import java.util.Map;
13,173
package net.superricky.tpaplusplus.util.manager; @Mod.EventBusSubscriber public class EventHandler { private EventHandler() {} /** * Our custom event. * This event is triggered once the timer of a teleport request reaches 0, notifying all members that were affected. * * @param event Takes a RequestTimeoutEvent parameter */ @SubscribeEvent public static void onTimeoutEvent(RequestTimeoutEvent event) { Request request = event.getRequest(); /* Check if the request has not been accepted or denied, so you don't print timeout messages multiple times. * UPDATE: This now ACTUALLY prevents printing timeout messages multiple times, because now the check is inverted (see RequestManager#alreadySentTeleportRequest), * since before we were only displaying your timeout message IF the timeout message did NOT expire, which you can imagine that caused problems. */ if (Boolean.FALSE.equals(RequestManager.alreadySentTeleportRequest(request))) return; ServerPlayer receiver = request.getReceiver(); ServerPlayer sender = request.getSender(); if (request.isHereRequest()) { sender.sendSystemMessage(Component.literal(String.format(Messages.SENDER_TPAHERE_TIMEOUT.get(), receiver.getDisplayName().getString()))); receiver.sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_TPAHERE_TIMEOUT.get(), sender.getDisplayName().getString()))); RequestManager.requestSet.remove(request); return; } sender.sendSystemMessage(Component.literal(String.format(Messages.SENDER_TPA_TIMEOUT.get(), receiver.getDisplayName().getString()))); receiver.sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_TPA_TIMEOUT.get(), sender.getDisplayName().getString()))); RequestManager.requestSet.remove(request); } /** * Triggered when a TPAAcceptTimer is successful. * Here we just run our acceptTeleportRequest method from TeleportManager.java with ABSOLUTE mode enabled, so the player will be teleported to the other player. * This is what will happen after the 5 4 3 2 1 (or whatever countdown in the config) is finished! * @param event Takes a RequestAcceptSuccessEvent parameter */ @SubscribeEvent
package net.superricky.tpaplusplus.util.manager; @Mod.EventBusSubscriber public class EventHandler { private EventHandler() {} /** * Our custom event. * This event is triggered once the timer of a teleport request reaches 0, notifying all members that were affected. * * @param event Takes a RequestTimeoutEvent parameter */ @SubscribeEvent public static void onTimeoutEvent(RequestTimeoutEvent event) { Request request = event.getRequest(); /* Check if the request has not been accepted or denied, so you don't print timeout messages multiple times. * UPDATE: This now ACTUALLY prevents printing timeout messages multiple times, because now the check is inverted (see RequestManager#alreadySentTeleportRequest), * since before we were only displaying your timeout message IF the timeout message did NOT expire, which you can imagine that caused problems. */ if (Boolean.FALSE.equals(RequestManager.alreadySentTeleportRequest(request))) return; ServerPlayer receiver = request.getReceiver(); ServerPlayer sender = request.getSender(); if (request.isHereRequest()) { sender.sendSystemMessage(Component.literal(String.format(Messages.SENDER_TPAHERE_TIMEOUT.get(), receiver.getDisplayName().getString()))); receiver.sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_TPAHERE_TIMEOUT.get(), sender.getDisplayName().getString()))); RequestManager.requestSet.remove(request); return; } sender.sendSystemMessage(Component.literal(String.format(Messages.SENDER_TPA_TIMEOUT.get(), receiver.getDisplayName().getString()))); receiver.sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_TPA_TIMEOUT.get(), sender.getDisplayName().getString()))); RequestManager.requestSet.remove(request); } /** * Triggered when a TPAAcceptTimer is successful. * Here we just run our acceptTeleportRequest method from TeleportManager.java with ABSOLUTE mode enabled, so the player will be teleported to the other player. * This is what will happen after the 5 4 3 2 1 (or whatever countdown in the config) is finished! * @param event Takes a RequestAcceptSuccessEvent parameter */ @SubscribeEvent
public static void onTPAAcceptTimerSuccess(RequestAcceptSuccessEvent event) {
6
2023-12-02 05:41:24+00:00
16k
shawn-sheep/Activity_Diary
app/src/main/java/de/rampro/activitydiary/ui/generic/EditActivity.java
[ { "identifier": "ActivityDiaryApplication", "path": "app/src/main/java/de/rampro/activitydiary/ActivityDiaryApplication.java", "snippet": "public class ActivityDiaryApplication extends Application {\n\n private static Context context;\n\n public void onCreate() {\n SpeechUtility.createUtili...
import android.content.AsyncQueryHandler; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import androidx.annotation.ColorInt; import androidx.annotation.Nullable; import com.google.android.material.textfield.TextInputLayout; import androidx.appcompat.widget.TooltipCompat; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Toast; import com.pes.androidmaterialcolorpickerdialog.ColorPicker; import com.pes.androidmaterialcolorpickerdialog.ColorPickerCallback; import java.util.LinkedList; import de.rampro.activitydiary.ActivityDiaryApplication; import de.rampro.activitydiary.R; import de.rampro.activitydiary.db.ActivityDiaryContract; import de.rampro.activitydiary.helpers.ActivityHelper; import de.rampro.activitydiary.helpers.JaroWinkler; import de.rampro.activitydiary.helpers.GraphicsHelper; import de.rampro.activitydiary.model.DiaryActivity;
14,319
/* * ActivityDiary * * Copyright (C) 2017-2018 Raphael Mack http://www.raphael-mack.de * Copyright (C) 2018 Sam Partee * * This program 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. * * 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.rampro.activitydiary.ui.generic; /* * EditActivity to add and modify activities * * */ public class EditActivity extends BaseActivity implements ActivityHelper.DataChangedListener { @Nullable private DiaryActivity currentActivity; /* null is for creating a new object */ private final int QUERY_NAMES = 1; private final int RENAME_DELETED_ACTIVITY = 2; private final int TEST_DELETED_NAME = 3; private final int SIMILAR_ACTIVITY = 4;
/* * ActivityDiary * * Copyright (C) 2017-2018 Raphael Mack http://www.raphael-mack.de * Copyright (C) 2018 Sam Partee * * This program 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. * * 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.rampro.activitydiary.ui.generic; /* * EditActivity to add and modify activities * * */ public class EditActivity extends BaseActivity implements ActivityHelper.DataChangedListener { @Nullable private DiaryActivity currentActivity; /* null is for creating a new object */ private final int QUERY_NAMES = 1; private final int RENAME_DELETED_ACTIVITY = 2; private final int TEST_DELETED_NAME = 3; private final int SIMILAR_ACTIVITY = 4;
private final String[] NAME_TEST_PROJ = new String[]{ActivityDiaryContract.DiaryActivity.NAME};
1
2023-12-02 12:36:40+00:00
16k
Ethylene9160/Chess
src/chess/panels/WebPanel.java
[ { "identifier": "Chess", "path": "src/chess/pieces/Chess.java", "snippet": "public abstract class Chess {\n public final static String KING = \"king\", ROOK = \"rook\", QUEEN = \"queen\",\n KNIGHT = \"knight\", BISHOP = \"bishop\", PAWN = \"pawn\";\n public static Style style = Style.DE...
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.Socket; import chess.pieces.Chess; import chess.recorder.Record; import chess.shop.MoneyShop; import chess.shop.ShengwangShop; import chess.shop.Shop; import chess.style.Style; import chess.threads.OpponentEmoThread; import chess.threads.YourEmoThread; import chess.util.Constants; import chess.util.ImagePath; import chess.web.ChessChannel; import chess.web.Receiver; import chess.web.Sender;
11,117
package chess.panels; public class WebPanel extends PanelBase implements MouseListener, ActionListener, KeyListener { public final static String SIGN_SPLIT = "&", LINE_SPLIT = "#"; public final static char SIGN_SPLIT_CHAR = '&', LINE_SPLIT_CHAR = '#'; public static final char INVITE_CONNECT = 'a', NO_PERSON_FOUND = 'b', REGIST = 'c', PREPARE = 'd', APPLY_ACCOUNT = 'e', POSITION = 'f', ACCEPT_CONNECT = 'g', ERROR = 'h', APPLY_REGRET = 'i', ACCEPT_REGRET = 'j', REJECT_REGRET = 'k', SET_NAME = 'l', RESET_PASSWARD = 'm', SUCCESS_SET_PASSWARD = 'n', SYSTEM_WINDOWS = 'o', REJECT_CONNECT = 'p', FIND_ONLINE = 'q', SURREND = 'r', GET_ID = 's', SEND_MESSAGE = 't', APPLY_PEACE = 'u', AGREE_PEACE = 'v', REJECT_PEACE = 'w', DISCONNECT = 'x', PLAYER_INFO = 'y', WRONG_PASSWARD = 'z', APPLY_SWAP = 'A', AGREE_SWAP = 'B', REJECT_SWAP ='C', SERVER_CLOSE = 'D', CHANGE_HEAD = 'E', CHANGE_NAME ='F', EMO_MES ='G', SHENGBIAN = 'H', LONG_CHANGE = 'I', TO_SHENGWANG ='J', GET_MONEY = 'K'; public static final String DEFAULT_NAME = "default", COLOR_BUTTON = "Cl", DISCONNECT_BUTTON = "Db", DEFAULT_HEAD = "default.png"; private String opponentName = DEFAULT_NAME, opponentID, yourName = DEFAULT_NAME, yourID, yourHead = DEFAULT_HEAD, opponentHead = DEFAULT_HEAD, yourEmo, opponentEmo; private StringBuilder messageBuilder = new StringBuilder(); private boolean isConnect, isYouPrepare, isOpponentPrepare, isYou; private int yourColor, oOX,oOY,oNX, oNY; private JButton confirmButton, applyButton, forgetButton, emoButton, setSignButton, prepareButton, clorButton, disconnectBut; public JDialog registerDialog = new JDialog(); private JTextField account = new JTextField("10001"), passward = new JTextField("123456"); private Sender sender;
package chess.panels; public class WebPanel extends PanelBase implements MouseListener, ActionListener, KeyListener { public final static String SIGN_SPLIT = "&", LINE_SPLIT = "#"; public final static char SIGN_SPLIT_CHAR = '&', LINE_SPLIT_CHAR = '#'; public static final char INVITE_CONNECT = 'a', NO_PERSON_FOUND = 'b', REGIST = 'c', PREPARE = 'd', APPLY_ACCOUNT = 'e', POSITION = 'f', ACCEPT_CONNECT = 'g', ERROR = 'h', APPLY_REGRET = 'i', ACCEPT_REGRET = 'j', REJECT_REGRET = 'k', SET_NAME = 'l', RESET_PASSWARD = 'm', SUCCESS_SET_PASSWARD = 'n', SYSTEM_WINDOWS = 'o', REJECT_CONNECT = 'p', FIND_ONLINE = 'q', SURREND = 'r', GET_ID = 's', SEND_MESSAGE = 't', APPLY_PEACE = 'u', AGREE_PEACE = 'v', REJECT_PEACE = 'w', DISCONNECT = 'x', PLAYER_INFO = 'y', WRONG_PASSWARD = 'z', APPLY_SWAP = 'A', AGREE_SWAP = 'B', REJECT_SWAP ='C', SERVER_CLOSE = 'D', CHANGE_HEAD = 'E', CHANGE_NAME ='F', EMO_MES ='G', SHENGBIAN = 'H', LONG_CHANGE = 'I', TO_SHENGWANG ='J', GET_MONEY = 'K'; public static final String DEFAULT_NAME = "default", COLOR_BUTTON = "Cl", DISCONNECT_BUTTON = "Db", DEFAULT_HEAD = "default.png"; private String opponentName = DEFAULT_NAME, opponentID, yourName = DEFAULT_NAME, yourID, yourHead = DEFAULT_HEAD, opponentHead = DEFAULT_HEAD, yourEmo, opponentEmo; private StringBuilder messageBuilder = new StringBuilder(); private boolean isConnect, isYouPrepare, isOpponentPrepare, isYou; private int yourColor, oOX,oOY,oNX, oNY; private JButton confirmButton, applyButton, forgetButton, emoButton, setSignButton, prepareButton, clorButton, disconnectBut; public JDialog registerDialog = new JDialog(); private JTextField account = new JTextField("10001"), passward = new JTextField("123456"); private Sender sender;
private Receiver receiver;
11
2023-12-01 02:33:32+00:00
16k
tuxiaobei-scu/Draw-and-guess
entry/src/main/java/com/tuxiaobei/drawandguess/slice/MainAbilitySlice.java
[ { "identifier": "MainAbility", "path": "entry/src/main/java/com/tuxiaobei/drawandguess/MainAbility.java", "snippet": "public class MainAbility extends Ability {\n @Override\n public void onStart(Intent intent) {\n super.onStart(intent);\n super.setMainRoute(MainAbilitySlice.class.get...
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT; import static ohos.security.SystemPermission.DISTRIBUTED_DATASYNC; import com.tuxiaobei.drawandguess.MainAbility; import com.tuxiaobei.drawandguess.ResourceTable; import com.tuxiaobei.drawandguess.bean.AnswerItem; import com.tuxiaobei.drawandguess.bean.MyPoint; import com.tuxiaobei.drawandguess.component.ChangeName; import com.tuxiaobei.drawandguess.component.DeviceSelectDialog; import com.tuxiaobei.drawandguess.component.DrawPoint; import com.tuxiaobei.drawandguess.component.WordSelectDialog; import com.tuxiaobei.drawandguess.game.Guesser; import com.tuxiaobei.drawandguess.game.MainGame; import com.tuxiaobei.drawandguess.provider.AnswerItemProvider; import com.tuxiaobei.drawandguess.util.GsonUtil; import com.tuxiaobei.drawandguess.util.LogUtils; import com.tuxiaobei.drawandguess.util.Tools; import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; import ohos.aafwk.content.Operation; import ohos.agp.components.*; import ohos.bundle.IBundleManager; import ohos.data.distributed.common.*; import ohos.data.distributed.user.SingleKvStore; import ohos.global.resource.NotExistException; import ohos.global.resource.WrongTypeException; import java.io.IOException; import java.util.ArrayList; import java.util.List;
11,581
/** * 获取数据库中的点数据,并在画布上画出来 */ private void drawPoints() { List<Entry> points = pointsSingleKvStore.getEntries(POINTS_KEY); for (Entry entry : points) { if (entry.getKey().equals(POINTS_KEY)) { List<MyPoint> remotePoints = GsonUtil.jsonToList(pointsSingleKvStore.getString(POINTS_KEY), MyPoint.class); getUITaskDispatcher().delayDispatch(() -> drawl.setDrawParams(remotePoints), DELAY_TIME); } } } /** * 更新答案消息列表 */ private void updateAnsShow() { List<Entry> ans = ansSingleKvStore.getEntries(ANS_KEY); for (Entry entry : ans) { if (entry.getKey().equals(ANS_KEY)) { List<AnswerItem> remoteAns= GsonUtil.jsonToList(ansSingleKvStore.getString(ANS_KEY), AnswerItem.class); getUITaskDispatcher().delayDispatch(() -> {showAns(remoteAns);}, DELAY_TIME); } } } /** * 获取昵称 * @param deviceId 设备id * @return 昵称 */ public String getName(String deviceId) { if (Tools.getDeviceId(this).equals(deviceId)) { if (isLocal) { return "系统"; } return local_name; } String ret; try { ret = nameSingleKvStore.getString(deviceId); }catch (KvStoreException e) { ret = deviceId.substring(0, 6); } if (ret == null || ret.isEmpty()) { ret = deviceId.substring(0, 6); } return ret; } /** * Receive database messages */ private class pointsKvStoreObserverClient implements KvStoreObserver { @Override public void onChange(ChangeNotification notification) { LogUtils.info(TAG, "data changed......"); drawPoints(); } } private class ansKvStoreObserverClient implements KvStoreObserver { @Override public void onChange(ChangeNotification notification) { LogUtils.info(TAG, "ans changed......"); updateAnsShow(); } } private class nameKvStoreObserverClient implements KvStoreObserver { @Override public void onChange(ChangeNotification notification) { LogUtils.info(TAG, "name changed......"); getUITaskDispatcher().delayDispatch(() -> {answerItemProvider.notifyDataChanged();}, DELAY_TIME); } } /** * 创建分布式数据库 */ private void initDatabase() { // 创建分布式数据库管理对象 KvManagerConfig config = new KvManagerConfig(this); kvManager = KvManagerFactory.getInstance().createKvManager(config); // 创建分布式数据库 Options options = new Options(); options.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.SINGLE_VERSION); pointsSingleKvStore = kvManager.getKvStore(options, storeId); // 订阅分布式数据变化 KvStoreObserver kvStoreObserverClient = new pointsKvStoreObserverClient(); pointsSingleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, kvStoreObserverClient); // 创建分布式数据库 ansSingleKvStore = kvManager.getKvStore(options, storeId); // 订阅分布式数据变化 KvStoreObserver kvStoreObserverClient1 = new ansKvStoreObserverClient(); ansSingleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, kvStoreObserverClient1); // 创建分布式数据库 nameSingleKvStore = kvManager.getKvStore(options, storeId); // 订阅分布式数据变化 KvStoreObserver kvStoreObserverClient2 = new nameKvStoreObserverClient(); nameSingleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, kvStoreObserverClient2); } /** * Starting Multiple Remote Fas * * @param deviceIds deviceIds */ private void startRemoteFas(List<String> deviceIds) { Intent[] intents = new Intent[deviceIds.size()]; for (int i = 0; i < deviceIds.size(); i++) { Intent intent = new Intent(); intent.setParam(IS_FORM_LOCAL_KEY, true); intent.setParam(COLOR_INDEX_KEY, i + 1); intent.setParam(STORE_ID_KEY, storeId); Operation operation = new Intent.OperationBuilder() .withDeviceId(deviceIds.get(i)) .withBundleName(getBundleName())
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuxiaobei.drawandguess.slice; /** * MainAbilitySlice * * @since 2021-04-06 */ public class MainAbilitySlice extends AbilitySlice { private static final String TAG = MainAbilitySlice.class.getName(); private static final int PERMISSION_CODE = 20201203; private static final int DELAY_TIME = 10; private static final String STORE_ID_KEY = "storeId"; private static final String POINTS_KEY = "points"; private static final String ANS_KEY = "ans"; private static final String COLOR_INDEX_KEY = "colorIndex"; private static final String IS_FORM_LOCAL_KEY = "isFormLocal"; private static String storeId; private DependentLayout canvas; private Image transform; private Image change_name; private KvManager kvManager; private SingleKvStore pointsSingleKvStore; private SingleKvStore ansSingleKvStore; private SingleKvStore nameSingleKvStore; private Text title; private DrawPoint drawl; private Image play; private Button back; private Text show_score; private Guesser guesser; private Text tip; private Button submit; private TextField ans; private MainGame main_game; private ListContainer ans_list; private final List<AnswerItem> ansData = new ArrayList<>(); private AnswerItemProvider answerItemProvider; private String deviceId; private String local_name; private boolean isLocal; @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_main); storeId = STORE_ID_KEY + Tools.getRandom(); isLocal = !intent.getBooleanParam(IS_FORM_LOCAL_KEY, false); drawl = new DrawPoint(this, isLocal); findComponentById(isLocal); requestPermission(); initView(intent); initDatabase(); if (isLocal) { nameSingleKvStore.putString(Tools.getDeviceId(this), "系统"); } initDraw(intent); ohos.global.resource.ResourceManager resManager = getResourceManager(); String[] words = null; try { words = resManager.getElement(ResourceTable.Strarray_words).getStringArray(); } catch (IOException e) { e.printStackTrace(); } catch (NotExistException e) { e.printStackTrace(); } catch (WrongTypeException e) { e.printStackTrace(); } main_game = new MainGame(this, words); initListContainer(); } private void initListContainer() { answerItemProvider = new AnswerItemProvider(ansData, this, isLocal); ans_list.setItemProvider(answerItemProvider); } private void initView(Intent intent) { if (!isLocal) { local_name = Tools.getDeviceId(this).substring(0, 6); storeId = intent.getStringParam(STORE_ID_KEY); } title.setText(isLocal ? "本地端" : local_name); transform.setVisibility(isLocal ? Component.VISIBLE : Component.INVISIBLE); } private void requestPermission() { if (verifySelfPermission(DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED) { if (canRequestPermission(DISTRIBUTED_DATASYNC)) { requestPermissionsFromUser(new String[]{DISTRIBUTED_DATASYNC}, PERMISSION_CODE); } } } private void findComponentById(Boolean isLocal) { if (findComponentById(ResourceTable.Id_canvas) instanceof DependentLayout) { canvas = (DependentLayout) findComponentById(ResourceTable.Id_canvas); } if (findComponentById(ResourceTable.Id_transform) instanceof Image) { transform = (Image) findComponentById(ResourceTable.Id_transform); } if (findComponentById(ResourceTable.Id_change_name) instanceof Image) { change_name = (Image) findComponentById(ResourceTable.Id_change_name); } if (findComponentById(ResourceTable.Id_play) instanceof Image) { play = (Image) findComponentById(ResourceTable.Id_play); } if (findComponentById(ResourceTable.Id_title) instanceof Text) { title = (Text) findComponentById(ResourceTable.Id_title); } if (findComponentById(ResourceTable.Id_back) instanceof Button) { back = (Button) findComponentById(ResourceTable.Id_back); } if (findComponentById(ResourceTable.Id_ans) instanceof TextField) { ans = (TextField) findComponentById(ResourceTable.Id_ans); } if (findComponentById(ResourceTable.Id_submit) instanceof Button) { submit = (Button) findComponentById(ResourceTable.Id_submit); } if (findComponentById(ResourceTable.Id_tip) instanceof Text) { tip = (Text) findComponentById(ResourceTable.Id_tip); } if (findComponentById(ResourceTable.Id_list_answers) instanceof ListContainer) { ans_list = (ListContainer) findComponentById(ResourceTable.Id_list_answers); } if (findComponentById(ResourceTable.Id_show_score) instanceof Text) { show_score = (Text) findComponentById(ResourceTable.Id_show_score); } if (isLocal) { if (findComponentById(ResourceTable.Id_red) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_red)); } if (findComponentById(ResourceTable.Id_green) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_green)); } if (findComponentById(ResourceTable.Id_blue) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_blue)); } if (findComponentById(ResourceTable.Id_yellow) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_yellow)); } if (findComponentById(ResourceTable.Id_pink) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_pink)); } if (findComponentById(ResourceTable.Id_cyan) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_cyan)); } if (findComponentById(ResourceTable.Id_black) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_black)); } ans.setVisibility(Component.HIDE); submit.setVisibility(Component.HIDE); } else { back.setVisibility(Component.HIDE); play.setVisibility(Component.HIDE); show_score.setVisibility(Component.VISIBLE); change_name.setVisibility(Component.VISIBLE); guesser = new Guesser(submit, ans, tip, show_score, this); } transform.setClickedListener(component -> { DeviceSelectDialog dialog = new DeviceSelectDialog(MainAbilitySlice.this); dialog.setListener(deviceIds -> { if (deviceIds != null && !deviceIds.isEmpty()) { // 启动远程页面 startRemoteFas(deviceIds); // 同步远程数据库 pointsSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); ansSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); nameSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); } dialog.hide(); }); dialog.show(); }); play.setClickedListener(component -> { WordSelectDialog dialog = new WordSelectDialog(MainAbilitySlice.this, main_game.getWords()); dialog.setListener(word -> { if (!word.isEmpty()) { newGame(word); } dialog.hide(); }); dialog.show(); }); change_name.setClickedListener(component -> { ChangeName dialog = new ChangeName(MainAbilitySlice.this, local_name); dialog.setListener(name -> { if (!name.isEmpty()) { setName(name); } dialog.hide(); }); dialog.show(); }); } /** * Initialize art boards * * @param intent Intent */ private void initDraw(Intent intent) { boolean isLocal = !intent.getBooleanParam(IS_FORM_LOCAL_KEY, false); //int colorIndex = switchcolor.getColorIndex(); drawl.setWidth(MATCH_PARENT); drawl.setWidth(MATCH_PARENT); canvas.addComponent(drawl); drawPoints(); drawl.setOnDrawBack(points -> { if (points != null && points.size() > 1) { String pointsString = GsonUtil.objectToString(points); LogUtils.info(TAG, "pointsString::" + pointsString); if (pointsSingleKvStore != null) { pointsSingleKvStore.putString(POINTS_KEY, pointsString); } } }); back.setClickedListener(component -> { List<MyPoint> points = drawl.getPoints(); if (points == null || points.size() <= 1) { return; } points.remove(points.size() - 1); for (int i = points.size() - 1; i >= 0; i--) { if (points.get(i).isLastPoint()) { break; } points.remove(i); } drawl.setDrawParams(points); String pointsString = GsonUtil.objectToString(points); if (pointsSingleKvStore != null) { pointsSingleKvStore.putString(POINTS_KEY, pointsString); } }); } public boolean getIslocal() { return isLocal; } /** * 设置昵称 * @param name 昵称 */ private void setName(String name) { title.setText(name); local_name = name; nameSingleKvStore.putString(Tools.getDeviceId(this), name); } /** * 添加答案元素 * @param ans */ public void addAnswer(AnswerItem ans) { ans.setDeviceId(Tools.getDeviceId(this)); ansData.add(0, ans); String ansString = GsonUtil.objectToString(ansData); if (ansSingleKvStore != null) { ansSingleKvStore.putString(ANS_KEY, ansString); } } /** * 开始新游戏 * @param word 新词语 */ private void newGame(String word) { ansData.clear(); AnswerItem a = new AnswerItem("开始第 " + main_game.getRoundnum() +" 轮游戏了!", 4); a.setWord(word); addAnswer(a); //answerItemProvider.notifyDataChanged(); main_game.setWord(word); main_game.generateWords(); title.setText(word); clearBoard(); } /** * 展示答案消息列表 * @param answers 答案消息数据 */ private void showAns(List<AnswerItem> answers) { if (!isLocal) { guesser.checkEnable(answers); } ansData.clear(); ansData.addAll(answers); answerItemProvider.notifyDataChanged(); } /** * 清空画板 */ private void clearBoard() { List<MyPoint> points = new ArrayList<>(0); drawl.setDrawParams(points); String pointsString = GsonUtil.objectToString(points); if (pointsSingleKvStore != null) { pointsSingleKvStore.putString(POINTS_KEY, pointsString); } } /** * 获取数据库中的点数据,并在画布上画出来 */ private void drawPoints() { List<Entry> points = pointsSingleKvStore.getEntries(POINTS_KEY); for (Entry entry : points) { if (entry.getKey().equals(POINTS_KEY)) { List<MyPoint> remotePoints = GsonUtil.jsonToList(pointsSingleKvStore.getString(POINTS_KEY), MyPoint.class); getUITaskDispatcher().delayDispatch(() -> drawl.setDrawParams(remotePoints), DELAY_TIME); } } } /** * 更新答案消息列表 */ private void updateAnsShow() { List<Entry> ans = ansSingleKvStore.getEntries(ANS_KEY); for (Entry entry : ans) { if (entry.getKey().equals(ANS_KEY)) { List<AnswerItem> remoteAns= GsonUtil.jsonToList(ansSingleKvStore.getString(ANS_KEY), AnswerItem.class); getUITaskDispatcher().delayDispatch(() -> {showAns(remoteAns);}, DELAY_TIME); } } } /** * 获取昵称 * @param deviceId 设备id * @return 昵称 */ public String getName(String deviceId) { if (Tools.getDeviceId(this).equals(deviceId)) { if (isLocal) { return "系统"; } return local_name; } String ret; try { ret = nameSingleKvStore.getString(deviceId); }catch (KvStoreException e) { ret = deviceId.substring(0, 6); } if (ret == null || ret.isEmpty()) { ret = deviceId.substring(0, 6); } return ret; } /** * Receive database messages */ private class pointsKvStoreObserverClient implements KvStoreObserver { @Override public void onChange(ChangeNotification notification) { LogUtils.info(TAG, "data changed......"); drawPoints(); } } private class ansKvStoreObserverClient implements KvStoreObserver { @Override public void onChange(ChangeNotification notification) { LogUtils.info(TAG, "ans changed......"); updateAnsShow(); } } private class nameKvStoreObserverClient implements KvStoreObserver { @Override public void onChange(ChangeNotification notification) { LogUtils.info(TAG, "name changed......"); getUITaskDispatcher().delayDispatch(() -> {answerItemProvider.notifyDataChanged();}, DELAY_TIME); } } /** * 创建分布式数据库 */ private void initDatabase() { // 创建分布式数据库管理对象 KvManagerConfig config = new KvManagerConfig(this); kvManager = KvManagerFactory.getInstance().createKvManager(config); // 创建分布式数据库 Options options = new Options(); options.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.SINGLE_VERSION); pointsSingleKvStore = kvManager.getKvStore(options, storeId); // 订阅分布式数据变化 KvStoreObserver kvStoreObserverClient = new pointsKvStoreObserverClient(); pointsSingleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, kvStoreObserverClient); // 创建分布式数据库 ansSingleKvStore = kvManager.getKvStore(options, storeId); // 订阅分布式数据变化 KvStoreObserver kvStoreObserverClient1 = new ansKvStoreObserverClient(); ansSingleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, kvStoreObserverClient1); // 创建分布式数据库 nameSingleKvStore = kvManager.getKvStore(options, storeId); // 订阅分布式数据变化 KvStoreObserver kvStoreObserverClient2 = new nameKvStoreObserverClient(); nameSingleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, kvStoreObserverClient2); } /** * Starting Multiple Remote Fas * * @param deviceIds deviceIds */ private void startRemoteFas(List<String> deviceIds) { Intent[] intents = new Intent[deviceIds.size()]; for (int i = 0; i < deviceIds.size(); i++) { Intent intent = new Intent(); intent.setParam(IS_FORM_LOCAL_KEY, true); intent.setParam(COLOR_INDEX_KEY, i + 1); intent.setParam(STORE_ID_KEY, storeId); Operation operation = new Intent.OperationBuilder() .withDeviceId(deviceIds.get(i)) .withBundleName(getBundleName())
.withAbilityName(MainAbility.class.getName())
0
2023-12-03 13:36:00+00:00
16k
andre111/voxedit
src/client/java/me/andre111/voxedit/client/VoxEditClient.java
[ { "identifier": "Presets", "path": "src/main/java/me/andre111/voxedit/Presets.java", "snippet": "public class Presets {\n\tpublic static final ToolItem.Data andre111;\n\tpublic static final ItemStack andre111Stack;\n\tstatic {\n\t\tandre111 = new ToolItem.Data(Util.make(new ArrayList<>(), list -> {\n\t\...
import org.lwjgl.glfw.GLFW; import org.spongepowered.include.com.google.common.base.Objects; import me.andre111.voxedit.Presets; import me.andre111.voxedit.VoxEdit; import me.andre111.voxedit.client.gui.screen.ToolSelectionScreen; import me.andre111.voxedit.client.network.ClientNetworking; import me.andre111.voxedit.client.renderer.EditorRenderer; import me.andre111.voxedit.client.renderer.HudRenderer; import me.andre111.voxedit.client.renderer.SelectionRenderer; import me.andre111.voxedit.client.renderer.ToolRenderer; import me.andre111.voxedit.item.ToolItem; import me.andre111.voxedit.item.VoxEditItem; import me.andre111.voxedit.network.Command; import me.andre111.voxedit.tool.ConfiguredTool; import me.andre111.voxedit.tool.Tool; import me.andre111.voxedit.tool.config.ToolConfig; import me.andre111.voxedit.tool.data.Selection; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; import net.fabricmc.fabric.api.client.rendering.v1.BuiltinItemRendererRegistry; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents; import net.fabricmc.fabric.api.event.client.player.ClientPreAttackCallback; import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.option.KeyBinding; import net.minecraft.client.util.InputUtil; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.text.Text; import net.minecraft.util.hit.BlockHitResult;
11,535
/* * Copyright (c) 2023 André Schweiger * * 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 me.andre111.voxedit.client; @Environment(value=EnvType.CLIENT) public class VoxEditClient implements ClientModInitializer { public static final KeyBinding INCREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_UP, "key.category.voxedit")); public static final KeyBinding DECREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_DOWN, "key.category.voxedit")); public static final KeyBinding INCREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_ADD, "key.category.voxedit")); public static final KeyBinding DECREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_SUBTRACT, "key.category.voxedit")); public static final KeyBinding UNDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.undo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Z, "key.category.voxedit")); public static final KeyBinding REDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.redo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Y, "key.category.voxedit")); public static final KeyBinding OPEN_MENU = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.openMenu", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_V, "key.category.voxedit")); public static int retargetCooldown; @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void onInitializeClient() { ClientNetworking.init(); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_TOOL, ToolRenderer.INSTANCE); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_EDITOR, EditorRenderer.INSTANCE); HudRenderer.init(); ItemGroupEvents.MODIFY_ENTRIES_ALL.register((group, entries) -> { if(group.getType() == ItemGroup.Type.CATEGORY && entries.shouldShowOpRestrictedItems()) { boolean hasCB = entries.getDisplayStacks().stream().filter(stack -> stack.getItem() == Items.COMMAND_BLOCK).findAny().isPresent(); if(hasCB) { for(Tool<?, ?> tool : VoxEdit.TOOL_REGISTRY) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(tool.getDefault())); for(ToolConfig config : tool.getAdditionalCreativeMenuConfigs()) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(new ConfiguredTool(tool, config))); } } entries.add(Presets.andre111Stack); entries.add(VoxEdit.ITEM_EDITOR.getDefaultStack()); } } }); ClientTickEvents.START_CLIENT_TICK.register((mc) -> { if(mc.world != null && mc.player != null) tick(); }); WorldRenderEvents.LAST.register((context) -> { render(context.matrixStack(), context.tickDelta()); }); ClientPreAttackCallback.EVENT.register((client, player, clickCount) -> { ItemStack stack = player.getMainHandStack();
/* * Copyright (c) 2023 André Schweiger * * 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 me.andre111.voxedit.client; @Environment(value=EnvType.CLIENT) public class VoxEditClient implements ClientModInitializer { public static final KeyBinding INCREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_UP, "key.category.voxedit")); public static final KeyBinding DECREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_DOWN, "key.category.voxedit")); public static final KeyBinding INCREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_ADD, "key.category.voxedit")); public static final KeyBinding DECREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_SUBTRACT, "key.category.voxedit")); public static final KeyBinding UNDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.undo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Z, "key.category.voxedit")); public static final KeyBinding REDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.redo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Y, "key.category.voxedit")); public static final KeyBinding OPEN_MENU = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.openMenu", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_V, "key.category.voxedit")); public static int retargetCooldown; @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void onInitializeClient() { ClientNetworking.init(); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_TOOL, ToolRenderer.INSTANCE); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_EDITOR, EditorRenderer.INSTANCE); HudRenderer.init(); ItemGroupEvents.MODIFY_ENTRIES_ALL.register((group, entries) -> { if(group.getType() == ItemGroup.Type.CATEGORY && entries.shouldShowOpRestrictedItems()) { boolean hasCB = entries.getDisplayStacks().stream().filter(stack -> stack.getItem() == Items.COMMAND_BLOCK).findAny().isPresent(); if(hasCB) { for(Tool<?, ?> tool : VoxEdit.TOOL_REGISTRY) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(tool.getDefault())); for(ToolConfig config : tool.getAdditionalCreativeMenuConfigs()) { entries.add(VoxEdit.ITEM_TOOL.getStackWith(new ConfiguredTool(tool, config))); } } entries.add(Presets.andre111Stack); entries.add(VoxEdit.ITEM_EDITOR.getDefaultStack()); } } }); ClientTickEvents.START_CLIENT_TICK.register((mc) -> { if(mc.world != null && mc.player != null) tick(); }); WorldRenderEvents.LAST.register((context) -> { render(context.matrixStack(), context.tickDelta()); }); ClientPreAttackCallback.EVENT.register((client, player, clickCount) -> { ItemStack stack = player.getMainHandStack();
if(stack.getItem() instanceof VoxEditItem) {
9
2023-12-01 15:12:26+00:00
16k
bioastroiner/Minetweaker-Gregtech6-Addon
src/main/java/mods/bio/gttweaker/core/GTTweaker.java
[ { "identifier": "IMaterial", "path": "src/main/java/mods/bio/gttweaker/api/mods/gregtech/oredict/IMaterial.java", "snippet": "@ZenClass(\"mods.gregtech.oredict.IMaterial\")\npublic interface IMaterial {\n\tOreDictMaterial getMaterial();\n\n\t@ZenOperator(OperatorType.MUL)\n\tIMaterialStack multiply(long...
import cpw.mods.fml.common.event.FMLInitializationEvent; import gregapi.recipes.Recipe; import minetweaker.MineTweakerAPI; import minetweaker.MineTweakerImplementationAPI; import minetweaker.api.item.IIngredient; import minetweaker.util.IEventHandler; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterial; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialData; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialStack; import mods.bio.gttweaker.api.mods.gregtech.oredict.IPrefix; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipe; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipeFactory; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipeMap; import mods.bio.gttweaker.core.command.GTCommand; import mods.bio.gttweaker.core.json.OreDictMaterial_Serializable; import mods.bio.gttweaker.mods.gregtech.oredict.*; import mods.bio.gttweaker.mods.gregtech.recipe.CTRecipe; import mods.bio.gttweaker.mods.gregtech.recipe.CTRecipeMaps; import mods.bio.gttweaker.mods.gregtech.oredict.bracket.CTMaterialBracketHandler; import mods.bio.gttweaker.mods.gregtech.oredict.bracket.CTPrefixBracketHandler; import mods.bio.gttweaker.mods.gregtech.recipe.bracket.CTRecipeMapBracketHandler; import mods.bio.gttweaker.mods.minetweaker.CTIItemStackExpansion; import mods.bio.gttweaker.mods.minetweaker.CTILiquidStackExpansion; import mods.bio.gttweaker.mods.minetweaker.CTIOreDictExpansion; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import java.util.Objects;
11,359
package mods.bio.gttweaker.core; @cpw.mods.fml.common.Mod(modid = GTTweaker.MOD_ID, name = GTTweaker.MOD_NAME, version = GTTweaker.VERSION) public final class GTTweaker extends gregapi.api.Abstract_Mod { // https://github.com/GTNewHorizons/Minetweaker-Gregtech-5-Addon/blob/master/src/main/java/gttweaker/GTTweaker.java public static final String MOD_ID = "GRADLETOKEN_MODID"; public static final String MOD_NAME = "GRADLETOKEN_MODNAME"; public static final String VERSION = "GRADLETOKEN_VERSION"; public static final String GROUPNAME = "GRADLETOKEN_GROUPNAME"; public static gregapi.code.ModData MOD_DATA = new gregapi.code.ModData(MOD_ID, MOD_NAME); //@cpw.mods.fml.common.SidedProxy(modId = MOD_ID, clientSide = "gregapi.api.example.Example_Proxy_Client", serverSide = "gregapi.api.example.Example_Proxy_Server") public static gregapi.api.Abstract_Proxy PROXY; public static String FORMAT_RECIPE_MAP(Recipe.RecipeMap map){ String[] tmp = map.toString().split("\\."); return tmp[tmp.length-1]; } public static Recipe.RecipeMap FORMAT_RECIPE_MAP(String name){ Recipe.RecipeMap out = null; if(Recipe.RecipeMap.RECIPE_MAPS.containsKey(name)){ out = Recipe.RecipeMap.RECIPE_MAPS.get(name); } if(out == null) for (Recipe.RecipeMap map: Recipe.RecipeMap.RECIPE_MAP_LIST) { String[] tmp = map.toString().split("\\."); String sName = tmp[tmp.length-1]; if(Objects.equals(sName.toLowerCase(),name.toLowerCase())){ out = map; } } if(out!=null){ return out; } else { MineTweakerAPI.logError(name + " is not a valid recipemap name!"); } return out; } public GTTweaker() { } @Override public String getModID() { return MOD_ID; } @Override public String getModName() { return MOD_NAME; } @Override public String getModNameForLog() { return "GTTWEAKER"; } @Override public gregapi.api.Abstract_Proxy getProxy() { return PROXY; } // Do not change these 7 Functions. Just keep them this way. @cpw.mods.fml.common.Mod.EventHandler public final void onPreLoad(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { onModPreInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onLoad(cpw.mods.fml.common.event.FMLInitializationEvent aEvent) { onModInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onPostLoad(cpw.mods.fml.common.event.FMLPostInitializationEvent aEvent) { onModPostInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarting(cpw.mods.fml.common.event.FMLServerStartingEvent aEvent) { onModServerStarting(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarted(cpw.mods.fml.common.event.FMLServerStartedEvent aEvent) { onModServerStarted(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopping(cpw.mods.fml.common.event.FMLServerStoppingEvent aEvent) { onModServerStopping(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopped(cpw.mods.fml.common.event.FMLServerStoppedEvent aEvent) { onModServerStopped(aEvent); } @Override public void onModPreInit2(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { } @Override public void onModInit2(FMLInitializationEvent aEvent) { OreDictMaterial_Serializable._INITLIZE(); MineTweakerAPI.registerClass(IRecipe.class); MineTweakerAPI.registerClass(IRecipeFactory.class); MineTweakerAPI.registerClass(IRecipeMap.class); MineTweakerAPI.registerClass(IMaterial.class); MineTweakerAPI.registerClass(IMaterialStack.class); MineTweakerAPI.registerClass(IPrefix.class); MineTweakerAPI.registerClass(IMaterialData.class); MineTweakerAPI.registerClass(CTRecipeMaps.class); MineTweakerAPI.registerClass(CTUnifier.class); MineTweakerAPI.registerClass(CTIOreDictExpansion.class);
package mods.bio.gttweaker.core; @cpw.mods.fml.common.Mod(modid = GTTweaker.MOD_ID, name = GTTweaker.MOD_NAME, version = GTTweaker.VERSION) public final class GTTweaker extends gregapi.api.Abstract_Mod { // https://github.com/GTNewHorizons/Minetweaker-Gregtech-5-Addon/blob/master/src/main/java/gttweaker/GTTweaker.java public static final String MOD_ID = "GRADLETOKEN_MODID"; public static final String MOD_NAME = "GRADLETOKEN_MODNAME"; public static final String VERSION = "GRADLETOKEN_VERSION"; public static final String GROUPNAME = "GRADLETOKEN_GROUPNAME"; public static gregapi.code.ModData MOD_DATA = new gregapi.code.ModData(MOD_ID, MOD_NAME); //@cpw.mods.fml.common.SidedProxy(modId = MOD_ID, clientSide = "gregapi.api.example.Example_Proxy_Client", serverSide = "gregapi.api.example.Example_Proxy_Server") public static gregapi.api.Abstract_Proxy PROXY; public static String FORMAT_RECIPE_MAP(Recipe.RecipeMap map){ String[] tmp = map.toString().split("\\."); return tmp[tmp.length-1]; } public static Recipe.RecipeMap FORMAT_RECIPE_MAP(String name){ Recipe.RecipeMap out = null; if(Recipe.RecipeMap.RECIPE_MAPS.containsKey(name)){ out = Recipe.RecipeMap.RECIPE_MAPS.get(name); } if(out == null) for (Recipe.RecipeMap map: Recipe.RecipeMap.RECIPE_MAP_LIST) { String[] tmp = map.toString().split("\\."); String sName = tmp[tmp.length-1]; if(Objects.equals(sName.toLowerCase(),name.toLowerCase())){ out = map; } } if(out!=null){ return out; } else { MineTweakerAPI.logError(name + " is not a valid recipemap name!"); } return out; } public GTTweaker() { } @Override public String getModID() { return MOD_ID; } @Override public String getModName() { return MOD_NAME; } @Override public String getModNameForLog() { return "GTTWEAKER"; } @Override public gregapi.api.Abstract_Proxy getProxy() { return PROXY; } // Do not change these 7 Functions. Just keep them this way. @cpw.mods.fml.common.Mod.EventHandler public final void onPreLoad(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { onModPreInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onLoad(cpw.mods.fml.common.event.FMLInitializationEvent aEvent) { onModInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onPostLoad(cpw.mods.fml.common.event.FMLPostInitializationEvent aEvent) { onModPostInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarting(cpw.mods.fml.common.event.FMLServerStartingEvent aEvent) { onModServerStarting(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarted(cpw.mods.fml.common.event.FMLServerStartedEvent aEvent) { onModServerStarted(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopping(cpw.mods.fml.common.event.FMLServerStoppingEvent aEvent) { onModServerStopping(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopped(cpw.mods.fml.common.event.FMLServerStoppedEvent aEvent) { onModServerStopped(aEvent); } @Override public void onModPreInit2(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { } @Override public void onModInit2(FMLInitializationEvent aEvent) { OreDictMaterial_Serializable._INITLIZE(); MineTweakerAPI.registerClass(IRecipe.class); MineTweakerAPI.registerClass(IRecipeFactory.class); MineTweakerAPI.registerClass(IRecipeMap.class); MineTweakerAPI.registerClass(IMaterial.class); MineTweakerAPI.registerClass(IMaterialStack.class); MineTweakerAPI.registerClass(IPrefix.class); MineTweakerAPI.registerClass(IMaterialData.class); MineTweakerAPI.registerClass(CTRecipeMaps.class); MineTweakerAPI.registerClass(CTUnifier.class); MineTweakerAPI.registerClass(CTIOreDictExpansion.class);
MineTweakerAPI.registerClass(CTIItemStackExpansion.class);
14
2023-12-03 11:55:49+00:00
16k
tuxiaobei-scu/SCU-CCSOJ-Backend
DataBackup/src/main/java/top/hcode/hoj/manager/group/discussion/GroupDiscussionManager.java
[ { "identifier": "StatusFailException", "path": "DataBackup/src/main/java/top/hcode/hoj/common/exception/StatusFailException.java", "snippet": "public class StatusFailException extends Exception{\n public StatusFailException() {\n }\n\n public StatusFailException(String message) {\n super...
import org.springframework.util.StringUtils; import top.hcode.hoj.common.exception.StatusFailException; import top.hcode.hoj.common.exception.StatusForbiddenException; import top.hcode.hoj.common.exception.StatusNotFoundException; import top.hcode.hoj.dao.discussion.DiscussionEntityService; import top.hcode.hoj.dao.group.GroupEntityService; import top.hcode.hoj.dao.problem.ProblemEntityService; import top.hcode.hoj.dao.user.UserAcproblemEntityService; import top.hcode.hoj.pojo.entity.discussion.Discussion; import top.hcode.hoj.pojo.entity.group.Group; import top.hcode.hoj.pojo.entity.problem.Problem; import top.hcode.hoj.pojo.entity.user.UserAcproblem; import top.hcode.hoj.pojo.vo.UserRolesVo; import top.hcode.hoj.utils.Constants; import top.hcode.hoj.utils.RedisUtils; import top.hcode.hoj.validator.GroupValidator; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
11,205
package top.hcode.hoj.manager.group.discussion; /** * @Author: LengYun * @Date: 2022/3/11 13:36 * @Description: */ @Component public class GroupDiscussionManager { @Autowired
package top.hcode.hoj.manager.group.discussion; /** * @Author: LengYun * @Date: 2022/3/11 13:36 * @Description: */ @Component public class GroupDiscussionManager { @Autowired
private GroupEntityService groupEntityService;
4
2023-12-03 14:15:51+00:00
16k
yichenhsiaonz/EscAIpe-room-final
src/main/java/nz/ac/auckland/se206/GameState.java
[ { "identifier": "SharedElements", "path": "src/main/java/nz/ac/auckland/se206/controllers/SharedElements.java", "snippet": "public class SharedElements {\n\n private static SharedElements instance;\n private static HBox[] taskBarHorizontalBoxList = new HBox[3];\n private static VBox[] inventoryVBoxLi...
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Random; import javafx.animation.FadeTransition; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.ParallelTransition; import javafx.animation.ScaleTransition; import javafx.animation.Timeline; import javafx.animation.TranslateTransition; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.event.EventHandler; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.util.Duration; import nz.ac.auckland.se206.controllers.SharedElements; import nz.ac.auckland.se206.gpt.ChatMessage; import nz.ac.auckland.se206.gpt.GptPromptEngineering; import nz.ac.auckland.se206.gpt.openai.ApiProxyException; import nz.ac.auckland.se206.gpt.openai.ChatCompletionRequest; import nz.ac.auckland.se206.gpt.openai.ChatCompletionResult; import nz.ac.auckland.se206.gpt.openai.ChatCompletionResult.Choice;
12,324
package nz.ac.auckland.se206; /** Represents the state of the game. */ public class GameState { /** The items that the player can pick up. */ public enum Items { BREAD_TOASTED, BREAD_UNTOASTED, PAPER, USB } private static GameState instance; private static int windowWidth = 1920; private static int windowHeight = 1080; private static int width = 1920; private static int height = 1080; public static boolean hasBread = false; public static boolean hasToast = false; public static boolean toasterPuzzleHints = true; public static boolean paperPuzzleHints = true; public static boolean computerPuzzleHints = true; public static boolean isExitUnlocked = false; public static boolean isUsbEnding = false; public static String code; public static String endingCongrats = ""; public static String endingReveal = ""; public static String usbEndingReveal = ""; private static HashMap<Items, ImageView[]> inventoryMap = new HashMap<Items, ImageView[]>(); private static MediaPlayer mediaPlayer; private static boolean moving = false; /** Resets fields to start a new game. */ public static void newGame() { // reset flags endingCongrats = ""; endingReveal = ""; usbEndingReveal = ""; hasBread = false; hasToast = false; toasterPuzzleHints = true; paperPuzzleHints = true; computerPuzzleHints = true; isExitUnlocked = false; isUsbEnding = false; moving = false; // create new instance instance = new GameState(); } public static void foundUsb() { isUsbEnding = true; } private static void inventoryMapAdd(Items item, ImageView[] itemImageView) { // add list of instances of identical items to the map inventoryMap.put(item, itemImageView); } /** This method starts the timer of the game. */ public static void startTimer() { // allocate a thread to the timer System.out.println(instance.chosenTime); instance.timerThread = new Thread(instance.timerTask); instance.timerThread.start(); } public static Task<Void> getTimer() { // return the currently running timer return instance.timerTask; } public static void stopTimer() { // stop the timer instance.timerThread.interrupt(); } /** * This method sets the difficulty of the game for the user. * * @param difficulty the difficulty of the game */ public static void setDifficulty(int difficulty) { // set the difficulty and update the hints button accordingly instance.chosenDifficulty = difficulty; instance.hints = difficulty; SharedElements.setHintsText(instance.hints); } public static int getDifficulty() { return instance.chosenDifficulty; } public static void setTime(int time) { instance.chosenTime = time; } public static void setWidth(int newWidth) { width = newWidth; } public static void setHeight(int newHeight) { height = newHeight; } public static void setWindowWidth(int width) { windowWidth = width; } public static void setWindowHeight(int height) { windowHeight = height; } public static int getWindowHeight() { return height; } public static int getWindowWidth() { return width; } public static String getSecondDigits() { return String.valueOf(instance.secondDigits); } public static boolean getMuted() { return instance.muted; } /** This method toggles whether the game is muted or not. */ public static void toggleMuted() { SharedElements.toggleMuteText(); instance.muted = !instance.muted; if (instance.muted) { TextToSpeechManager.cutOff(); stopSound(); } } /** * Gets a response from GPT the AI application. * * @param msg the message to send to GPT * @param hintFlag whether the message is a hint * @return the response from GPT * @throws ApiProxyException if there is an error with the API */ public static ChatMessage runGpt(ChatMessage msg, boolean hintFlag) throws ApiProxyException { // get loading image in each room List<ImageView> loadingImages = getLoadingIcons(); // get talking image in each room List<ImageView> talkingImages = getTalkingIcons(); // show loading image for (ImageView imageView : loadingImages) { imageView.setVisible(true); } // add message to gpt request instance.chatBoxChatCompletionRequest.addMessage(msg); // disable gpt related buttons SharedElements.disableSendButton(); SharedElements.disableHintsButton(); // task for gpt chat generation Task<ChatMessage> gptTask = new Task<ChatMessage>() { @Override protected ChatMessage call() throws Exception { try { // get response from gpt ChatCompletionResult chatCompletionResult = instance.chatBoxChatCompletionRequest.execute();
package nz.ac.auckland.se206; /** Represents the state of the game. */ public class GameState { /** The items that the player can pick up. */ public enum Items { BREAD_TOASTED, BREAD_UNTOASTED, PAPER, USB } private static GameState instance; private static int windowWidth = 1920; private static int windowHeight = 1080; private static int width = 1920; private static int height = 1080; public static boolean hasBread = false; public static boolean hasToast = false; public static boolean toasterPuzzleHints = true; public static boolean paperPuzzleHints = true; public static boolean computerPuzzleHints = true; public static boolean isExitUnlocked = false; public static boolean isUsbEnding = false; public static String code; public static String endingCongrats = ""; public static String endingReveal = ""; public static String usbEndingReveal = ""; private static HashMap<Items, ImageView[]> inventoryMap = new HashMap<Items, ImageView[]>(); private static MediaPlayer mediaPlayer; private static boolean moving = false; /** Resets fields to start a new game. */ public static void newGame() { // reset flags endingCongrats = ""; endingReveal = ""; usbEndingReveal = ""; hasBread = false; hasToast = false; toasterPuzzleHints = true; paperPuzzleHints = true; computerPuzzleHints = true; isExitUnlocked = false; isUsbEnding = false; moving = false; // create new instance instance = new GameState(); } public static void foundUsb() { isUsbEnding = true; } private static void inventoryMapAdd(Items item, ImageView[] itemImageView) { // add list of instances of identical items to the map inventoryMap.put(item, itemImageView); } /** This method starts the timer of the game. */ public static void startTimer() { // allocate a thread to the timer System.out.println(instance.chosenTime); instance.timerThread = new Thread(instance.timerTask); instance.timerThread.start(); } public static Task<Void> getTimer() { // return the currently running timer return instance.timerTask; } public static void stopTimer() { // stop the timer instance.timerThread.interrupt(); } /** * This method sets the difficulty of the game for the user. * * @param difficulty the difficulty of the game */ public static void setDifficulty(int difficulty) { // set the difficulty and update the hints button accordingly instance.chosenDifficulty = difficulty; instance.hints = difficulty; SharedElements.setHintsText(instance.hints); } public static int getDifficulty() { return instance.chosenDifficulty; } public static void setTime(int time) { instance.chosenTime = time; } public static void setWidth(int newWidth) { width = newWidth; } public static void setHeight(int newHeight) { height = newHeight; } public static void setWindowWidth(int width) { windowWidth = width; } public static void setWindowHeight(int height) { windowHeight = height; } public static int getWindowHeight() { return height; } public static int getWindowWidth() { return width; } public static String getSecondDigits() { return String.valueOf(instance.secondDigits); } public static boolean getMuted() { return instance.muted; } /** This method toggles whether the game is muted or not. */ public static void toggleMuted() { SharedElements.toggleMuteText(); instance.muted = !instance.muted; if (instance.muted) { TextToSpeechManager.cutOff(); stopSound(); } } /** * Gets a response from GPT the AI application. * * @param msg the message to send to GPT * @param hintFlag whether the message is a hint * @return the response from GPT * @throws ApiProxyException if there is an error with the API */ public static ChatMessage runGpt(ChatMessage msg, boolean hintFlag) throws ApiProxyException { // get loading image in each room List<ImageView> loadingImages = getLoadingIcons(); // get talking image in each room List<ImageView> talkingImages = getTalkingIcons(); // show loading image for (ImageView imageView : loadingImages) { imageView.setVisible(true); } // add message to gpt request instance.chatBoxChatCompletionRequest.addMessage(msg); // disable gpt related buttons SharedElements.disableSendButton(); SharedElements.disableHintsButton(); // task for gpt chat generation Task<ChatMessage> gptTask = new Task<ChatMessage>() { @Override protected ChatMessage call() throws Exception { try { // get response from gpt ChatCompletionResult chatCompletionResult = instance.chatBoxChatCompletionRequest.execute();
Choice result = chatCompletionResult.getChoices().iterator().next();
6
2023-12-02 04:57:43+00:00
16k
nageoffer/shortlink
project/src/main/java/com/nageoffer/shortlink/project/service/impl/ShortLinkStatsServiceImpl.java
[ { "identifier": "LinkAccessLogsDO", "path": "project/src/main/java/com/nageoffer/shortlink/project/dao/entity/LinkAccessLogsDO.java", "snippet": "@Data\n@TableName(\"t_link_access_logs\")\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class LinkAccessLogsDO extends BaseDO {\n\n /**\n ...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateField; import cn.hutool.core.date.DateUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.nageoffer.shortlink.project.dao.entity.LinkAccessLogsDO; import com.nageoffer.shortlink.project.dao.entity.LinkAccessStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkDeviceStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkLocaleStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkNetworkStatsDO; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessLogsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkBrowserStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkDeviceStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkLocaleStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkNetworkStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkOsStatsMapper; import com.nageoffer.shortlink.project.dto.req.ShortLinkGroupStatsAccessRecordReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkGroupStatsReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsAccessRecordReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsReqDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsAccessDailyRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsAccessRecordRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsBrowserRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsDeviceRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsLocaleCNRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsNetworkRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsOsRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsTopIpRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsUvRespDTO; import com.nageoffer.shortlink.project.service.ShortLinkStatsService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger;
12,233
.locale(each.getProvince()) .ratio(actualRatio) .build(); localeCnStats.add(localeCNRespDTO); }); // 小时访问详情 List<Integer> hourStats = new ArrayList<>(); List<LinkAccessStatsDO> listHourStatsByShortLink = linkAccessStatsMapper.listHourStatsByShortLink(requestParam); for (int i = 0; i < 24; i++) { AtomicInteger hour = new AtomicInteger(i); int hourCnt = listHourStatsByShortLink.stream() .filter(each -> Objects.equals(each.getHour(), hour.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); hourStats.add(hourCnt); } // 高频访问IP详情 List<ShortLinkStatsTopIpRespDTO> topIpStats = new ArrayList<>(); List<HashMap<String, Object>> listTopIpByShortLink = linkAccessLogsMapper.listTopIpByShortLink(requestParam); listTopIpByShortLink.forEach(each -> { ShortLinkStatsTopIpRespDTO statsTopIpRespDTO = ShortLinkStatsTopIpRespDTO.builder() .ip(each.get("ip").toString()) .cnt(Integer.parseInt(each.get("count").toString())) .build(); topIpStats.add(statsTopIpRespDTO); }); // 一周访问详情 List<Integer> weekdayStats = new ArrayList<>(); List<LinkAccessStatsDO> listWeekdayStatsByShortLink = linkAccessStatsMapper.listWeekdayStatsByShortLink(requestParam); for (int i = 1; i < 8; i++) { AtomicInteger weekday = new AtomicInteger(i); int weekdayCnt = listWeekdayStatsByShortLink.stream() .filter(each -> Objects.equals(each.getWeekday(), weekday.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); weekdayStats.add(weekdayCnt); } // 浏览器访问详情 List<ShortLinkStatsBrowserRespDTO> browserStats = new ArrayList<>(); List<HashMap<String, Object>> listBrowserStatsByShortLink = linkBrowserStatsMapper.listBrowserStatsByShortLink(requestParam); int browserSum = listBrowserStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listBrowserStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / browserSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsBrowserRespDTO browserRespDTO = ShortLinkStatsBrowserRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .browser(each.get("browser").toString()) .ratio(actualRatio) .build(); browserStats.add(browserRespDTO); }); // 操作系统访问详情 List<ShortLinkStatsOsRespDTO> osStats = new ArrayList<>(); List<HashMap<String, Object>> listOsStatsByShortLink = linkOsStatsMapper.listOsStatsByShortLink(requestParam); int osSum = listOsStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listOsStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / osSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsOsRespDTO osRespDTO = ShortLinkStatsOsRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .os(each.get("os").toString()) .ratio(actualRatio) .build(); osStats.add(osRespDTO); }); // 访客访问类型详情 List<ShortLinkStatsUvRespDTO> uvTypeStats = new ArrayList<>(); HashMap<String, Object> findUvTypeByShortLink = linkAccessLogsMapper.findUvTypeCntByShortLink(requestParam); int oldUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("oldUserCnt")) .map(Object::toString) .orElse("0") ); int newUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("newUserCnt")) .map(Object::toString) .orElse("0") ); int uvSum = oldUserCnt + newUserCnt; double oldRatio = (double) oldUserCnt / uvSum; double actualOldRatio = Math.round(oldRatio * 100.0) / 100.0; double newRatio = (double) newUserCnt / uvSum; double actualNewRatio = Math.round(newRatio * 100.0) / 100.0; ShortLinkStatsUvRespDTO newUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("newUser") .cnt(newUserCnt) .ratio(actualNewRatio) .build(); uvTypeStats.add(newUvRespDTO); ShortLinkStatsUvRespDTO oldUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("oldUser") .cnt(oldUserCnt) .ratio(actualOldRatio) .build(); uvTypeStats.add(oldUvRespDTO); // 访问设备类型详情 List<ShortLinkStatsDeviceRespDTO> deviceStats = new ArrayList<>(); List<LinkDeviceStatsDO> listDeviceStatsByShortLink = linkDeviceStatsMapper.listDeviceStatsByShortLink(requestParam); int deviceSum = listDeviceStatsByShortLink.stream() .mapToInt(LinkDeviceStatsDO::getCnt) .sum(); listDeviceStatsByShortLink.forEach(each -> { double ratio = (double) each.getCnt() / deviceSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsDeviceRespDTO deviceRespDTO = ShortLinkStatsDeviceRespDTO.builder() .cnt(each.getCnt()) .device(each.getDevice()) .ratio(actualRatio) .build(); deviceStats.add(deviceRespDTO); }); // 访问网络类型详情
/* * 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.nageoffer.shortlink.project.service.impl; /** * 短链接监控接口实现层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Service @RequiredArgsConstructor public class ShortLinkStatsServiceImpl implements ShortLinkStatsService { private final LinkAccessStatsMapper linkAccessStatsMapper; private final LinkLocaleStatsMapper linkLocaleStatsMapper; private final LinkAccessLogsMapper linkAccessLogsMapper; private final LinkBrowserStatsMapper linkBrowserStatsMapper; private final LinkOsStatsMapper linkOsStatsMapper; private final LinkDeviceStatsMapper linkDeviceStatsMapper; private final LinkNetworkStatsMapper linkNetworkStatsMapper; @Override public ShortLinkStatsRespDTO oneShortLinkStats(ShortLinkStatsReqDTO requestParam) { List<LinkAccessStatsDO> listStatsByShortLink = linkAccessStatsMapper.listStatsByShortLink(requestParam); if (CollUtil.isEmpty(listStatsByShortLink)) { return null; } // 基础访问数据 LinkAccessStatsDO pvUvUidStatsByShortLink = linkAccessLogsMapper.findPvUvUidStatsByShortLink(requestParam); // 基础访问详情 List<ShortLinkStatsAccessDailyRespDTO> daily = new ArrayList<>(); List<String> rangeDates = DateUtil.rangeToList(DateUtil.parse(requestParam.getStartDate()), DateUtil.parse(requestParam.getEndDate()), DateField.DAY_OF_MONTH).stream() .map(DateUtil::formatDate) .toList(); rangeDates.forEach(each -> listStatsByShortLink.stream() .filter(item -> Objects.equals(each, DateUtil.formatDate(item.getDate()))) .findFirst() .ifPresentOrElse(item -> { ShortLinkStatsAccessDailyRespDTO accessDailyRespDTO = ShortLinkStatsAccessDailyRespDTO.builder() .date(each) .pv(item.getPv()) .uv(item.getUv()) .uip(item.getUip()) .build(); daily.add(accessDailyRespDTO); }, () -> { ShortLinkStatsAccessDailyRespDTO accessDailyRespDTO = ShortLinkStatsAccessDailyRespDTO.builder() .date(each) .pv(0) .uv(0) .uip(0) .build(); daily.add(accessDailyRespDTO); })); // 地区访问详情(仅国内) List<ShortLinkStatsLocaleCNRespDTO> localeCnStats = new ArrayList<>(); List<LinkLocaleStatsDO> listedLocaleByShortLink = linkLocaleStatsMapper.listLocaleByShortLink(requestParam); int localeCnSum = listedLocaleByShortLink.stream() .mapToInt(LinkLocaleStatsDO::getCnt) .sum(); listedLocaleByShortLink.forEach(each -> { double ratio = (double) each.getCnt() / localeCnSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsLocaleCNRespDTO localeCNRespDTO = ShortLinkStatsLocaleCNRespDTO.builder() .cnt(each.getCnt()) .locale(each.getProvince()) .ratio(actualRatio) .build(); localeCnStats.add(localeCNRespDTO); }); // 小时访问详情 List<Integer> hourStats = new ArrayList<>(); List<LinkAccessStatsDO> listHourStatsByShortLink = linkAccessStatsMapper.listHourStatsByShortLink(requestParam); for (int i = 0; i < 24; i++) { AtomicInteger hour = new AtomicInteger(i); int hourCnt = listHourStatsByShortLink.stream() .filter(each -> Objects.equals(each.getHour(), hour.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); hourStats.add(hourCnt); } // 高频访问IP详情 List<ShortLinkStatsTopIpRespDTO> topIpStats = new ArrayList<>(); List<HashMap<String, Object>> listTopIpByShortLink = linkAccessLogsMapper.listTopIpByShortLink(requestParam); listTopIpByShortLink.forEach(each -> { ShortLinkStatsTopIpRespDTO statsTopIpRespDTO = ShortLinkStatsTopIpRespDTO.builder() .ip(each.get("ip").toString()) .cnt(Integer.parseInt(each.get("count").toString())) .build(); topIpStats.add(statsTopIpRespDTO); }); // 一周访问详情 List<Integer> weekdayStats = new ArrayList<>(); List<LinkAccessStatsDO> listWeekdayStatsByShortLink = linkAccessStatsMapper.listWeekdayStatsByShortLink(requestParam); for (int i = 1; i < 8; i++) { AtomicInteger weekday = new AtomicInteger(i); int weekdayCnt = listWeekdayStatsByShortLink.stream() .filter(each -> Objects.equals(each.getWeekday(), weekday.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); weekdayStats.add(weekdayCnt); } // 浏览器访问详情 List<ShortLinkStatsBrowserRespDTO> browserStats = new ArrayList<>(); List<HashMap<String, Object>> listBrowserStatsByShortLink = linkBrowserStatsMapper.listBrowserStatsByShortLink(requestParam); int browserSum = listBrowserStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listBrowserStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / browserSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsBrowserRespDTO browserRespDTO = ShortLinkStatsBrowserRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .browser(each.get("browser").toString()) .ratio(actualRatio) .build(); browserStats.add(browserRespDTO); }); // 操作系统访问详情 List<ShortLinkStatsOsRespDTO> osStats = new ArrayList<>(); List<HashMap<String, Object>> listOsStatsByShortLink = linkOsStatsMapper.listOsStatsByShortLink(requestParam); int osSum = listOsStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listOsStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / osSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsOsRespDTO osRespDTO = ShortLinkStatsOsRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .os(each.get("os").toString()) .ratio(actualRatio) .build(); osStats.add(osRespDTO); }); // 访客访问类型详情 List<ShortLinkStatsUvRespDTO> uvTypeStats = new ArrayList<>(); HashMap<String, Object> findUvTypeByShortLink = linkAccessLogsMapper.findUvTypeCntByShortLink(requestParam); int oldUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("oldUserCnt")) .map(Object::toString) .orElse("0") ); int newUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("newUserCnt")) .map(Object::toString) .orElse("0") ); int uvSum = oldUserCnt + newUserCnt; double oldRatio = (double) oldUserCnt / uvSum; double actualOldRatio = Math.round(oldRatio * 100.0) / 100.0; double newRatio = (double) newUserCnt / uvSum; double actualNewRatio = Math.round(newRatio * 100.0) / 100.0; ShortLinkStatsUvRespDTO newUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("newUser") .cnt(newUserCnt) .ratio(actualNewRatio) .build(); uvTypeStats.add(newUvRespDTO); ShortLinkStatsUvRespDTO oldUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("oldUser") .cnt(oldUserCnt) .ratio(actualOldRatio) .build(); uvTypeStats.add(oldUvRespDTO); // 访问设备类型详情 List<ShortLinkStatsDeviceRespDTO> deviceStats = new ArrayList<>(); List<LinkDeviceStatsDO> listDeviceStatsByShortLink = linkDeviceStatsMapper.listDeviceStatsByShortLink(requestParam); int deviceSum = listDeviceStatsByShortLink.stream() .mapToInt(LinkDeviceStatsDO::getCnt) .sum(); listDeviceStatsByShortLink.forEach(each -> { double ratio = (double) each.getCnt() / deviceSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsDeviceRespDTO deviceRespDTO = ShortLinkStatsDeviceRespDTO.builder() .cnt(each.getCnt()) .device(each.getDevice()) .ratio(actualRatio) .build(); deviceStats.add(deviceRespDTO); }); // 访问网络类型详情
List<ShortLinkStatsNetworkRespDTO> networkStats = new ArrayList<>();
21
2023-11-19 16:04:32+00:00
16k
TongchengOpenSource/ckibana
src/main/java/com/ly/ckibana/strategy/clause/MatchPhraseClauseStrategy.java
[ { "identifier": "Constants", "path": "src/main/java/com/ly/ckibana/constants/Constants.java", "snippet": "public class Constants {\n\n public static final String HEADER_ELASTICSEARCH = \"Elasticsearch\";\n\n public static final String HEADER_X_ELASTIC_PRODUCT = \"X-elastic-product\";\n\n public...
import com.alibaba.fastjson2.JSONObject; import com.ly.ckibana.constants.Constants; import com.ly.ckibana.model.compute.QueryClause; import com.ly.ckibana.model.enums.IPType; import com.ly.ckibana.model.enums.QueryClauseType; import com.ly.ckibana.model.request.CkRequestContext; import com.ly.ckibana.util.ParamConvertUtils; import com.ly.ckibana.util.ProxyUtils; import com.ly.ckibana.util.QueryConvertUtils; import com.ly.ckibana.util.SqlUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map;
11,349
/* * Copyright (c) 2023 LY.com All Rights Reserved. * * 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.ly.ckibana.strategy.clause; @Component public class MatchPhraseClauseStrategy implements ClauseStrategy { @Override public QueryClauseType getType() { return QueryClauseType.MATCH_PHRASE; } @Override public String toSql(QueryClause queryClause) { CkRequestContext ckRequestContext = queryClause.getCkRequestContext(); String result = ""; Map<String, Object> mapParam = new HashMap<>(queryClause.getParam()); String field = mapParam.keySet().iterator().next(); String ckFieldName = ParamConvertUtils.convertUiFieldToCkField(ckRequestContext.getColumns(), field); String ckFieldNameSqlPart = ProxyUtils.getFieldSqlPart(ckFieldName); String type = ProxyUtils.getCkFieldTypeByName(ckFieldName, ckRequestContext.getColumns()); Object body = parseBody(mapParam.get(field), ckFieldName, type, ckRequestContext.getIndexPattern().getTimeField());
/* * Copyright (c) 2023 LY.com All Rights Reserved. * * 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.ly.ckibana.strategy.clause; @Component public class MatchPhraseClauseStrategy implements ClauseStrategy { @Override public QueryClauseType getType() { return QueryClauseType.MATCH_PHRASE; } @Override public String toSql(QueryClause queryClause) { CkRequestContext ckRequestContext = queryClause.getCkRequestContext(); String result = ""; Map<String, Object> mapParam = new HashMap<>(queryClause.getParam()); String field = mapParam.keySet().iterator().next(); String ckFieldName = ParamConvertUtils.convertUiFieldToCkField(ckRequestContext.getColumns(), field); String ckFieldNameSqlPart = ProxyUtils.getFieldSqlPart(ckFieldName); String type = ProxyUtils.getCkFieldTypeByName(ckFieldName, ckRequestContext.getColumns()); Object body = parseBody(mapParam.get(field), ckFieldName, type, ckRequestContext.getIndexPattern().getTimeField());
IPType ipType = ProxyUtils.getIpType(type, body.toString());
2
2023-11-21 09:12:07+00:00
16k
libgdx/gdx-particle-editor
core/src/main/java/com/ray3k/gdxparticleeditor/widgets/subpanels/RangeSubPanel.java
[ { "identifier": "UndoManager", "path": "core/src/main/java/com/ray3k/gdxparticleeditor/undo/UndoManager.java", "snippet": "public class UndoManager {\n public final static Array<Undoable> undoables = new Array<>();\n public static int undoIndex = -1;\n\n public static void add(Undoable undoable...
import com.badlogic.gdx.graphics.g2d.ParticleEmitter.RangedNumericValue; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.utils.Align; import com.ray3k.gdxparticleeditor.undo.UndoManager; import com.ray3k.gdxparticleeditor.undo.undoables.RangedNumericValueUndoable; import com.ray3k.gdxparticleeditor.undo.undoables.SetPropertyUndoable; import com.ray3k.gdxparticleeditor.widgets.Panel; import com.ray3k.gdxparticleeditor.widgets.ToggleGroup; import com.ray3k.gdxparticleeditor.widgets.panels.EmitterPropertiesPanel.ShownProperty; import com.ray3k.stripe.Spinner; import com.ray3k.stripe.Spinner.Orientation; import static com.ray3k.gdxparticleeditor.Core.*; import static com.ray3k.gdxparticleeditor.Listeners.*; import static com.ray3k.gdxparticleeditor.widgets.styles.Styles.spinnerStyle; import static com.ray3k.gdxparticleeditor.widgets.styles.Styles.tooltipBottomArrowStyle;
12,155
package com.ray3k.gdxparticleeditor.widgets.subpanels; /** * A widget that allows modification of an emitter value that only has a min/max. Numeric spinners. */ public class RangeSubPanel extends Panel { public RangeSubPanel(String title, RangedNumericValue value, String tooltip, String undoDescription, ShownProperty closeProperty, float sliderIncrement, float sliderRange, int decimalPlaces, boolean adjustByPPM, boolean resetParticleEffect) { final int spinnerWidth = 70; final int itemSpacing = 5; setTouchable(Touchable.enabled); tabTable.padRight(7); tabTable.left(); var label = new Label(title, skin, "header"); tabTable.add(label).space(3); if (closeProperty != null) { var button = new Button(skin, "close"); tabTable.add(button); addHandListener(button); onChange(button, () -> UndoManager.add(new SetPropertyUndoable(selectedEmitter, closeProperty, false, "set " + closeProperty.name + " property"))); } //Value var table = new Table(); bodyTable.add(table).expandX().left(); table.defaults().space(itemSpacing).left(); label = new Label("Value:", skin); table.add(label); var highToggleWidget = new ToggleGroup(); table.add(highToggleWidget); //Value single highToggleWidget.table1.defaults().space(itemSpacing);
package com.ray3k.gdxparticleeditor.widgets.subpanels; /** * A widget that allows modification of an emitter value that only has a min/max. Numeric spinners. */ public class RangeSubPanel extends Panel { public RangeSubPanel(String title, RangedNumericValue value, String tooltip, String undoDescription, ShownProperty closeProperty, float sliderIncrement, float sliderRange, int decimalPlaces, boolean adjustByPPM, boolean resetParticleEffect) { final int spinnerWidth = 70; final int itemSpacing = 5; setTouchable(Touchable.enabled); tabTable.padRight(7); tabTable.left(); var label = new Label(title, skin, "header"); tabTable.add(label).space(3); if (closeProperty != null) { var button = new Button(skin, "close"); tabTable.add(button); addHandListener(button); onChange(button, () -> UndoManager.add(new SetPropertyUndoable(selectedEmitter, closeProperty, false, "set " + closeProperty.name + " property"))); } //Value var table = new Table(); bodyTable.add(table).expandX().left(); table.defaults().space(itemSpacing).left(); label = new Label("Value:", skin); table.add(label); var highToggleWidget = new ToggleGroup(); table.add(highToggleWidget); //Value single highToggleWidget.table1.defaults().space(itemSpacing);
var valueSpinner = new Spinner(value.getLowMin(), 1, decimalPlaces, Orientation.RIGHT_STACK, spinnerStyle);
7
2023-11-24 15:58:20+00:00
16k
siam1026/siam-server
siam-system/system-provider/src/main/java/com/siam/system/modular/package_user/service_impl/MemberInviteRelationServiceImpl.java
[ { "identifier": "MemberSessionManager", "path": "siam-system/system-api/src/main/java/com/siam/system/modular/package_user/auth/cache/MemberSessionManager.java", "snippet": "public interface MemberSessionManager {\n\n //缓存前缀\n String SESSION_PREFIX = \"LOGIN_USER:\";\n\n /**\n * 创建会话\n ...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.system.modular.package_user.auth.cache.MemberSessionManager; import com.siam.system.modular.package_user.entity.Member; import com.siam.system.modular.package_user.entity.MemberInviteRelation; import com.siam.system.modular.package_user.mapper.MemberInviteRelationMapper; import com.siam.system.modular.package_user.mapper.MemberMapper; import com.siam.system.modular.package_user.model.example.MemberInviteRelationExample; import com.siam.system.modular.package_user.model.param.MemberInviteRelationParam; import com.siam.system.modular.package_user.service.MemberBillingRecordService; import com.siam.system.modular.package_user.service.MemberInviteRelationService; import com.siam.system.modular.package_user.service.MemberService; import com.siam.system.util.TokenUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map;
11,628
package com.siam.system.modular.package_user.service_impl; @Service public class MemberInviteRelationServiceImpl implements MemberInviteRelationService { @Autowired private MemberInviteRelationMapper memberInviteRelationMapper; @Autowired
package com.siam.system.modular.package_user.service_impl; @Service public class MemberInviteRelationServiceImpl implements MemberInviteRelationService { @Autowired private MemberInviteRelationMapper memberInviteRelationMapper; @Autowired
private MemberMapper memberMapper;
4
2023-11-26 12:41:06+00:00
16k
3dcitydb/citydb-tool
citydb-io-citygml/src/main/java/org/citydb/io/citygml/adapter/gml/AbstractMeasureAdapter.java
[ { "identifier": "ModelBuildException", "path": "citydb-io-citygml/src/main/java/org/citydb/io/citygml/builder/ModelBuildException.java", "snippet": "public class ModelBuildException extends Exception {\n\n public ModelBuildException() {\n super();\n }\n\n public ModelBuildException(Strin...
import org.citydb.io.citygml.builder.ModelBuildException; import org.citydb.io.citygml.builder.ModelBuilder; import org.citydb.io.citygml.reader.ModelBuilderHelper; import org.citydb.io.citygml.serializer.ModelSerializeException; import org.citydb.io.citygml.serializer.ModelSerializer; import org.citydb.io.citygml.writer.ModelSerializerHelper; import org.citydb.model.property.Attribute; import org.citydb.model.property.DataType; import org.xmlobjects.gml.model.basictypes.Measure;
14,388
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.io.citygml.adapter.gml; public abstract class AbstractMeasureAdapter<T extends Measure> implements ModelBuilder<T, Attribute>, ModelSerializer<Attribute, T> { @Override
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.io.citygml.adapter.gml; public abstract class AbstractMeasureAdapter<T extends Measure> implements ModelBuilder<T, Attribute>, ModelSerializer<Attribute, T> { @Override
public void build(T source, Attribute target, ModelBuilderHelper helper) throws ModelBuildException {
2
2023-11-19 12:29:54+00:00
16k
magmamaintained/Magma-1.12.2
src/main/java/org/bukkit/event/player/AsyncPlayerPreLoginEvent.java
[ { "identifier": "PlayerProfile", "path": "src/main/java/com/destroystokyo/paper/profile/PlayerProfile.java", "snippet": "public interface PlayerProfile {\n\n /**\n * @return The players name, if set\n */\n @Nullable String getName();\n\n /**\n * Sets this profiles Name\n *\n ...
import com.destroystokyo.paper.profile.PlayerProfile; import java.net.InetAddress; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.event.Event; import org.bukkit.event.HandlerList;
12,775
package org.bukkit.event.player; /** * Stores details for players attempting to log in. * <p> * This event is asynchronous, and not run using main thread. */ public class AsyncPlayerPreLoginEvent extends Event { private static final HandlerList handlers = new HandlerList(); private final String name; private final InetAddress ipAddress; private final UUID uniqueId; private Result result; private String message;
package org.bukkit.event.player; /** * Stores details for players attempting to log in. * <p> * This event is asynchronous, and not run using main thread. */ public class AsyncPlayerPreLoginEvent extends Event { private static final HandlerList handlers = new HandlerList(); private final String name; private final InetAddress ipAddress; private final UUID uniqueId; private Result result; private String message;
private PlayerProfile profile;
0
2023-11-22 11:25:51+00:00
16k
logaritex/assistant-api
src/test/java/com/logaritex/ai/api/samples/AssistantOverview.java
[ { "identifier": "AssistantApi", "path": "src/main/java/com/logaritex/ai/api/AssistantApi.java", "snippet": "public class AssistantApi {\n\n\t/**\n\t * OpenAI assistant api beta marker.\n\t */\n\tpublic static final String OPEN_AI_BETA = \"OpenAI-Beta\";\n\n\t/**\n\t * OpenAI assistant api version.\n\t *...
import com.logaritex.ai.api.Data.Run; import com.logaritex.ai.api.Data.RunRequest; import com.logaritex.ai.api.Data.ThreadRequest; import com.logaritex.ai.api.Data.Tool; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.logaritex.ai.api.AssistantApi; import com.logaritex.ai.api.Data; import com.logaritex.ai.api.Data.AssistantRequestBody; import com.logaritex.ai.api.Data.DataList; import com.logaritex.ai.api.Data.ListRequest; import com.logaritex.ai.api.Data.Message; import com.logaritex.ai.api.Data.MessageRequest; import com.logaritex.ai.api.Data.Role;
12,684
/* * Copyright 2023-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 com.logaritex.ai.api.samples; /** * Java implementation of the Assistant Overview example: https://platform.openai.com/docs/assistants/overview * * @author Christian Tzolov */ public class AssistantOverview { public static void main(String[] args) throws InterruptedException { // 1. Connect to the Assistant API. AssistantApi assistantApi = new AssistantApi(System.getenv("OPENAI_API_KEY")); // 2. Create a Math Tutor assistant. Data.Assistant assistant = assistantApi.createAssistant(new AssistantRequestBody( "gpt-4-1106-preview", // model "Math Tutor", // name "", // description "You are a personal math tutor. Write and run code to answer math questions.", // instructions
/* * Copyright 2023-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 com.logaritex.ai.api.samples; /** * Java implementation of the Assistant Overview example: https://platform.openai.com/docs/assistants/overview * * @author Christian Tzolov */ public class AssistantOverview { public static void main(String[] args) throws InterruptedException { // 1. Connect to the Assistant API. AssistantApi assistantApi = new AssistantApi(System.getenv("OPENAI_API_KEY")); // 2. Create a Math Tutor assistant. Data.Assistant assistant = assistantApi.createAssistant(new AssistantRequestBody( "gpt-4-1106-preview", // model "Math Tutor", // name "", // description "You are a personal math tutor. Write and run code to answer math questions.", // instructions
List.of(new Tool(Tool.Type.code_interpreter)), // tools
3
2023-11-25 18:52:37+00:00
16k
GregTech-Chinese-Community/EPCore
src/main/java/cn/gtcommunity/epimorphism/common/metatileentities/multiblock/EPMetaTileEntityDragonFusionUnit.java
[ { "identifier": "EPRecipeMaps", "path": "src/main/java/cn/gtcommunity/epimorphism/api/recipe/EPRecipeMaps.java", "snippet": "@ZenClass(\"mods.epimorphism.recipe.RecipeMaps\")\n@ZenRegister\npublic class EPRecipeMaps {\n\n // Singleblock Machine Recipemap\n @ZenProperty\n public static final Re...
import cn.gtcommunity.epimorphism.api.recipe.EPRecipeMaps; import cn.gtcommunity.epimorphism.client.renderer.texture.EPTextures; import cn.gtcommunity.epimorphism.common.blocks.EPBlockMultiblockCasingC; import cn.gtcommunity.epimorphism.common.blocks.EPMetablocks; import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.interfaces.IGregTechTileEntity; import gregtech.api.metatileentity.multiblock.IMultiblockPart; import gregtech.api.metatileentity.multiblock.RecipeMapMultiblockController; import gregtech.api.pattern.BlockPattern; import gregtech.api.pattern.FactoryBlockPattern; import gregtech.client.renderer.ICubeRenderer; import gregtech.common.blocks.BlockFusionCasing; import gregtech.common.blocks.MetaBlocks; import net.minecraft.block.state.IBlockState; import net.minecraft.client.resources.I18n; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List;
12,274
package cn.gtcommunity.epimorphism.common.metatileentities.multiblock; public class EPMetaTileEntityDragonFusionUnit extends RecipeMapMultiblockController { public EPMetaTileEntityDragonFusionUnit(ResourceLocation metaTileEntityId) { super(metaTileEntityId, EPRecipeMaps.DRAGON_FUSION_UNIT_RECIPES); } public MetaTileEntity createMetaTileEntity(IGregTechTileEntity tileEntity) { return new EPMetaTileEntityDragonFusionUnit(this.metaTileEntityId); } @Nonnull protected BlockPattern createStructurePattern() { return FactoryBlockPattern.start() .aisle("CCCCC", " ", " ", " ", " ", " ", " ", " ", " ", "CCCCC") .aisle("CCCCC", " W ", " ", " DDD ", " ", " ", " DDD ", " ", " W ", "CCCCC") .aisle("CCCCC", " WOW ", " O ", " DOD ", " O ", " O ", " DOD ", " O ", " WOW ", "CCCCC") .aisle("CCCCC", " W ", " ", " DDD ", " ", " ", " DDD ", " ", " W ", "CCCCC") .aisle("CCSCC", " ", " ", " ", " ", " ", " ", " ", " ", "CCCCC") .where('S', this.selfPredicate()) .where('C', states(getCasingState()) .setMinGlobalLimited(40) .or(autoAbilities())) .where('O', states(getSecondCoilState())) .where('W', states(getThirdCoilState())) .where('D', states(getCoilState())) .where(' ', any()) .build(); } private static IBlockState getCasingState() {
package cn.gtcommunity.epimorphism.common.metatileentities.multiblock; public class EPMetaTileEntityDragonFusionUnit extends RecipeMapMultiblockController { public EPMetaTileEntityDragonFusionUnit(ResourceLocation metaTileEntityId) { super(metaTileEntityId, EPRecipeMaps.DRAGON_FUSION_UNIT_RECIPES); } public MetaTileEntity createMetaTileEntity(IGregTechTileEntity tileEntity) { return new EPMetaTileEntityDragonFusionUnit(this.metaTileEntityId); } @Nonnull protected BlockPattern createStructurePattern() { return FactoryBlockPattern.start() .aisle("CCCCC", " ", " ", " ", " ", " ", " ", " ", " ", "CCCCC") .aisle("CCCCC", " W ", " ", " DDD ", " ", " ", " DDD ", " ", " W ", "CCCCC") .aisle("CCCCC", " WOW ", " O ", " DOD ", " O ", " O ", " DOD ", " O ", " WOW ", "CCCCC") .aisle("CCCCC", " W ", " ", " DDD ", " ", " ", " DDD ", " ", " W ", "CCCCC") .aisle("CCSCC", " ", " ", " ", " ", " ", " ", " ", " ", "CCCCC") .where('S', this.selfPredicate()) .where('C', states(getCasingState()) .setMinGlobalLimited(40) .or(autoAbilities())) .where('O', states(getSecondCoilState())) .where('W', states(getThirdCoilState())) .where('D', states(getCoilState())) .where(' ', any()) .build(); } private static IBlockState getCasingState() {
return EPMetablocks.EP_MULTIBLOCK_CASING_C.getState(EPBlockMultiblockCasingC.CasingType.DRACONIUM_CASING);
2
2023-11-26 01:56:35+00:00
16k
ZayrexDev/ZPixiv
src/main/java/xyz/zcraft/zpixiv/ui/Main.java
[ { "identifier": "PixivClient", "path": "src/main/java/xyz/zcraft/zpixiv/api/PixivClient.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class PixivClient {\n private static final Logger LOG = LogManager.getLogger(PixivClient.class);\n private static final String userAgent = \"Mozilla/5.0 ...
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONWriter; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Stage; import javafx.stage.StageStyle; import lombok.Getter; import lombok.Setter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import xyz.zcraft.zpixiv.api.PixivClient; import xyz.zcraft.zpixiv.ui.controller.InspectController; import xyz.zcraft.zpixiv.ui.controller.MainController; import xyz.zcraft.zpixiv.util.CachedImage; import xyz.zcraft.zpixiv.util.Config; import xyz.zcraft.zpixiv.util.ResourceLoader; import xyz.zcraft.zpixiv.util.SSLUtil; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Base64; import java.util.LinkedList; import java.util.Timer; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor;
11,880
package xyz.zcraft.zpixiv.ui; public class Main extends Application { @Getter public static final LinkedList<CachedImage> loginBackground = new LinkedList<>(); private static final Logger LOG = LogManager.getLogger(Main.class); @Getter private static final ThreadPoolExecutor tpe = (ThreadPoolExecutor) Executors.newCachedThreadPool(); @Getter private static final Timer timer = new Timer(); @Getter private static final Path dataPath = Path.of("data"); @Getter private static final Path configPath = dataPath.resolve("config.json"); @Getter private static final Path userPath = dataPath.resolve("user"); @Getter private static Config config; @Getter private static Stage stage = null; @Getter private static MainController mainController = null; @Getter @Setter private static PixivClient client = null; public static void saveCookie(String cookie) throws IOException { Files.writeString(userPath, Base64.getEncoder().encodeToString(cookie.getBytes())); } public static String loadCookie() throws IOException { if (!Files.exists(userPath)) return null; else return new String(Base64.getDecoder().decode(Files.readString(userPath))); } public static void deleteCookie() throws IOException { Files.delete(userPath); } public static void main(String[] args) { try { config = loadConfig(); } catch (Exception e) { config = new Config(); LOG.error("Error loading config.", e); } launch(args); } public static void showAlert(String title, String content) { mainController.showAlert(title, content); } public static void saveConfig() throws Exception { String string = JSONObject.from(config).toString(JSONWriter.Feature.PrettyFormat); Files.writeString(configPath, string); } public static Config loadConfig() throws Exception { if (Files.exists(configPath)) { return JSONObject.parseObject(Files.readString(configPath)).to(Config.class); } else { return new Config(); } } public static void openInspectStage(CachedImage[] images) { try { final FXMLLoader fxmlLoader = new FXMLLoader(ResourceLoader.load("fxml/Inspect.fxml")); Stage inspectStage = new Stage(); inspectStage.setScene(new Scene(fxmlLoader.load())); InspectController controller = fxmlLoader.getController(); controller.init(inspectStage, images); inspectStage.show(); } catch (IOException e) { LOG.error("Failed to open inspection stage.", e); showAlert("错误", "打开失败"); } } @Override public void start(Stage stage) { Main.stage = stage; try {
package xyz.zcraft.zpixiv.ui; public class Main extends Application { @Getter public static final LinkedList<CachedImage> loginBackground = new LinkedList<>(); private static final Logger LOG = LogManager.getLogger(Main.class); @Getter private static final ThreadPoolExecutor tpe = (ThreadPoolExecutor) Executors.newCachedThreadPool(); @Getter private static final Timer timer = new Timer(); @Getter private static final Path dataPath = Path.of("data"); @Getter private static final Path configPath = dataPath.resolve("config.json"); @Getter private static final Path userPath = dataPath.resolve("user"); @Getter private static Config config; @Getter private static Stage stage = null; @Getter private static MainController mainController = null; @Getter @Setter private static PixivClient client = null; public static void saveCookie(String cookie) throws IOException { Files.writeString(userPath, Base64.getEncoder().encodeToString(cookie.getBytes())); } public static String loadCookie() throws IOException { if (!Files.exists(userPath)) return null; else return new String(Base64.getDecoder().decode(Files.readString(userPath))); } public static void deleteCookie() throws IOException { Files.delete(userPath); } public static void main(String[] args) { try { config = loadConfig(); } catch (Exception e) { config = new Config(); LOG.error("Error loading config.", e); } launch(args); } public static void showAlert(String title, String content) { mainController.showAlert(title, content); } public static void saveConfig() throws Exception { String string = JSONObject.from(config).toString(JSONWriter.Feature.PrettyFormat); Files.writeString(configPath, string); } public static Config loadConfig() throws Exception { if (Files.exists(configPath)) { return JSONObject.parseObject(Files.readString(configPath)).to(Config.class); } else { return new Config(); } } public static void openInspectStage(CachedImage[] images) { try { final FXMLLoader fxmlLoader = new FXMLLoader(ResourceLoader.load("fxml/Inspect.fxml")); Stage inspectStage = new Stage(); inspectStage.setScene(new Scene(fxmlLoader.load())); InspectController controller = fxmlLoader.getController(); controller.init(inspectStage, images); inspectStage.show(); } catch (IOException e) { LOG.error("Failed to open inspection stage.", e); showAlert("错误", "打开失败"); } } @Override public void start(Stage stage) { Main.stage = stage; try {
SSLUtil.ignoreSsl();
6
2023-11-23 15:08:16+00:00
16k
myzticbean/QSFindItemAddOn
src/main/java/io/myzticbean/finditemaddon/Handlers/CommandHandler/CmdExecutorHandler.java
[ { "identifier": "ConfigSetup", "path": "src/main/java/io/myzticbean/finditemaddon/ConfigUtil/ConfigSetup.java", "snippet": "public class ConfigSetup {\n\n private static File configFile;\n private static File sampleConfigFile;\n private static FileConfiguration configFileConfiguration;\n pri...
import io.myzticbean.finditemaddon.ConfigUtil.ConfigSetup; import io.myzticbean.finditemaddon.FindItemAddOn; import io.myzticbean.finditemaddon.Handlers.GUIHandler.Menus.FoundShopsMenu; import io.myzticbean.finditemaddon.Models.FoundShopItemModel; import io.myzticbean.finditemaddon.Utils.Defaults.PlayerPerms; import io.myzticbean.finditemaddon.Utils.JsonStorageUtils.HiddenShopStorageUtil; import io.myzticbean.finditemaddon.Utils.LoggerUtils; import io.myzticbean.finditemaddon.Utils.WarpUtils.WarpUtils; import me.kodysimpson.simpapi.colors.ColorTranslator; import org.apache.commons.lang3.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.maxgamer.quickshop.api.shop.Shop; import java.util.List;
14,219
* Handles the shop hiding feature * @param commandSender Who is the command sender: console or player */ public void handleHideShop(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_HIDESHOP.value())) { Block playerLookAtBlock = player.getTargetBlock(null, 100); if(FindItemAddOn.isQSReremakeInstalled()) { hideShop((Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } else { hideShop((com.ghostchu.quickshop.api.shop.Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } } else { player.sendMessage(ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } /** * Handles the shop reveal feature * @param commandSender Who is the command sender: console or player */ public void handleRevealShop(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_HIDESHOP.value())) { Block playerLookAtBlock = player.getTargetBlock(null, 100); if(FindItemAddOn.isQSReremakeInstalled()) { revealShop((Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } else { revealShop((com.ghostchu.quickshop.api.shop.Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } } else { player.sendMessage(ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } /** * Handles the saving hidden shops to file feature * @param commandSender Who is the command sender: console or player */ /* public void handleHiddenShopSavingToFile(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_ADMIN.toString())) { HiddenShopStorageUtil.saveHiddenShopsToFile(); player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&aSaved hidden shops!")); } else { player.sendMessage( ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } */ /** * Handles the loading of hidden shops from file feature * @param commandSender Who is the command sender: console or player */ /* public void handleHiddenShopLoadingFromFile(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_ADMIN.toString())) { HiddenShopStorageUtil.loadHiddenShopsFromFile(); player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&aSaved hidden shops!")); } else { player.sendMessage( ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } */ /** * Handles plugin reload * @param commandSender Who is the command sender: console or player */ public void handlePluginReload(CommandSender commandSender) { if (!(commandSender instanceof Player)) { ConfigSetup.reloadConfig(); ConfigSetup.checkForMissingProperties(); ConfigSetup.saveConfig(); FindItemAddOn.initConfigProvider(); List allServerShops = FindItemAddOn.getQsApiInstance().getAllShops(); if(allServerShops.size() == 0) { LoggerUtils.logWarning("&6Found &e0 &6shops on the server. If you ran &e/qs reload &6recently, please restart your server!"); } else { LoggerUtils.logInfo("&aFound &e" + allServerShops.size() + " &ashops on the server."); }
package io.myzticbean.finditemaddon.Handlers.CommandHandler; /** * Handler for different parameters of /finditem command * @author ronsane */ public class CmdExecutorHandler { /** * Handles the main shop search process * @param buySellSubCommand Whether player is buying or selling * @param commandSender Who is the command sender: console or player * @param itemArg Specifies Item ID or Item name */ public void handleShopSearch(String buySellSubCommand, CommandSender commandSender, String itemArg) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_USE.value())) { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_SEARCH_LOADING_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().SHOP_SEARCH_LOADING_MSG)); } boolean isBuying; if(StringUtils.isEmpty(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE) || StringUtils.containsIgnoreCase(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE, " ")) { isBuying = buySellSubCommand.equalsIgnoreCase("to_buy"); } else { isBuying = buySellSubCommand.equalsIgnoreCase(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE); } if(itemArg.equalsIgnoreCase("*")) { List<FoundShopItemModel> searchResultList = FindItemAddOn.getQsApiInstance().fetchAllItemsFromAllShops(isBuying, player); if(searchResultList.size() > 0) { Bukkit.getScheduler().runTaskAsynchronously(FindItemAddOn.getInstance(), () -> { FoundShopsMenu menu = new FoundShopsMenu(FindItemAddOn.getPlayerMenuUtility(player), searchResultList); Bukkit.getScheduler().runTask(FindItemAddOn.getInstance(), () -> menu.open(searchResultList)); }); } else { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().NO_SHOP_FOUND_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().NO_SHOP_FOUND_MSG)); } } } else { Material mat = Material.getMaterial(itemArg.toUpperCase()); if(mat != null) { LoggerUtils.logDebugInfo("Material found: " + mat.toString()); List<FoundShopItemModel> searchResultList = FindItemAddOn.getQsApiInstance().findItemBasedOnTypeFromAllShops(new ItemStack(mat), isBuying, player); if(searchResultList.size() > 0) { Bukkit.getScheduler().runTaskAsynchronously(FindItemAddOn.getInstance(), () -> { FoundShopsMenu menu = new FoundShopsMenu(FindItemAddOn.getPlayerMenuUtility(player), searchResultList); Bukkit.getScheduler().runTask(FindItemAddOn.getInstance(), () -> menu.open(searchResultList)); }); } else { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().NO_SHOP_FOUND_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().NO_SHOP_FOUND_MSG)); } } } else { LoggerUtils.logDebugInfo("Material not found! Performing query based search.."); List<FoundShopItemModel> searchResultList = FindItemAddOn.getQsApiInstance().findItemBasedOnDisplayNameFromAllShops(itemArg, isBuying, player); if(searchResultList.size() > 0) { Bukkit.getScheduler().runTaskAsynchronously(FindItemAddOn.getInstance(), () -> { FoundShopsMenu menu = new FoundShopsMenu(FindItemAddOn.getPlayerMenuUtility(player), searchResultList); Bukkit.getScheduler().runTask(FindItemAddOn.getInstance(), () -> menu.open(searchResultList)); }); } else { // Invalid Material if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().FIND_ITEM_CMD_INVALID_MATERIAL_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().FIND_ITEM_CMD_INVALID_MATERIAL_MSG)); } } } } } else { player.sendMessage(ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } /** * Handles the shop hiding feature * @param commandSender Who is the command sender: console or player */ public void handleHideShop(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_HIDESHOP.value())) { Block playerLookAtBlock = player.getTargetBlock(null, 100); if(FindItemAddOn.isQSReremakeInstalled()) { hideShop((Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } else { hideShop((com.ghostchu.quickshop.api.shop.Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } } else { player.sendMessage(ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } /** * Handles the shop reveal feature * @param commandSender Who is the command sender: console or player */ public void handleRevealShop(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_HIDESHOP.value())) { Block playerLookAtBlock = player.getTargetBlock(null, 100); if(FindItemAddOn.isQSReremakeInstalled()) { revealShop((Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } else { revealShop((com.ghostchu.quickshop.api.shop.Shop) FindItemAddOn.getQsApiInstance().findShopAtLocation(playerLookAtBlock), player); } } else { player.sendMessage(ColorTranslator.translateColorCodes(FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } /** * Handles the saving hidden shops to file feature * @param commandSender Who is the command sender: console or player */ /* public void handleHiddenShopSavingToFile(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_ADMIN.toString())) { HiddenShopStorageUtil.saveHiddenShopsToFile(); player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&aSaved hidden shops!")); } else { player.sendMessage( ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } */ /** * Handles the loading of hidden shops from file feature * @param commandSender Who is the command sender: console or player */ /* public void handleHiddenShopLoadingFromFile(CommandSender commandSender) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_ADMIN.toString())) { HiddenShopStorageUtil.loadHiddenShopsFromFile(); player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&aSaved hidden shops!")); } else { player.sendMessage( ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + "&cNo permission!")); } } } */ /** * Handles plugin reload * @param commandSender Who is the command sender: console or player */ public void handlePluginReload(CommandSender commandSender) { if (!(commandSender instanceof Player)) { ConfigSetup.reloadConfig(); ConfigSetup.checkForMissingProperties(); ConfigSetup.saveConfig(); FindItemAddOn.initConfigProvider(); List allServerShops = FindItemAddOn.getQsApiInstance().getAllShops(); if(allServerShops.size() == 0) { LoggerUtils.logWarning("&6Found &e0 &6shops on the server. If you ran &e/qs reload &6recently, please restart your server!"); } else { LoggerUtils.logInfo("&aFound &e" + allServerShops.size() + " &ashops on the server."); }
WarpUtils.updateWarps();
7
2023-11-22 11:36:01+00:00
16k
estkme-group/infineon-lpa-mirror
core/src/main/java/com/infineon/esim/lpa/core/es9plus/messages/request/InitiateAuthenticationReq.java
[ { "identifier": "EUICCInfo1", "path": "messages/src/main/java/com/gsma/sgp/messages/rspdefinitions/EUICCInfo1.java", "snippet": "public class EUICCInfo1 implements BerType, Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic static class EuiccCiPKIdListForVerification implem...
import com.infineon.esim.messages.Ber; import com.infineon.esim.util.Bytes; import androidx.annotation.NonNull; import com.beanit.jasn1.ber.types.string.BerUTF8String; import com.gsma.sgp.messages.rspdefinitions.EUICCInfo1; import com.gsma.sgp.messages.rspdefinitions.InitiateAuthenticationRequest; import com.gsma.sgp.messages.rspdefinitions.Octet16; import com.infineon.esim.lpa.core.es9plus.messages.request.base.RequestMsgBody;
13,143
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.es9plus.messages.request; public class InitiateAuthenticationReq extends RequestMsgBody { private String euiccChallenge; private String euiccInfo1; private String smdpAddress; public String getEuiccChallenge() { return euiccChallenge; } public void setEuiccChallenge(String euiccChallenge) { this.euiccChallenge = euiccChallenge; } public String getEuiccInfo1() { return euiccInfo1; } public void setEuiccInfo1(String euiccInfo1) { this.euiccInfo1 = euiccInfo1; } public String getSmdpAddress() { return smdpAddress; } public void setSmdpAddress(String smdpAddress) { this.smdpAddress = smdpAddress; } public InitiateAuthenticationRequest getRequest() { InitiateAuthenticationRequest initiateAuthenticationRequest = new InitiateAuthenticationRequest(); initiateAuthenticationRequest.setSmdpAddress(this.getSmdpAddressParsed()); initiateAuthenticationRequest.setEuiccInfo1(this.getEuiccInfo1Parsed()); initiateAuthenticationRequest.setEuiccChallenge(this.getEuiccChallengeParsed()); return initiateAuthenticationRequest; } public void setRequest(InitiateAuthenticationRequest initiateAuthenticationRequest) { setEuiccChallengeParsed(initiateAuthenticationRequest.getEuiccChallenge()); setEuiccInfo1Parsed(initiateAuthenticationRequest.getEuiccInfo1()); setSmdpAddressParsed(initiateAuthenticationRequest.getSmdpAddress()); } private Octet16 getEuiccChallengeParsed() {
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.es9plus.messages.request; public class InitiateAuthenticationReq extends RequestMsgBody { private String euiccChallenge; private String euiccInfo1; private String smdpAddress; public String getEuiccChallenge() { return euiccChallenge; } public void setEuiccChallenge(String euiccChallenge) { this.euiccChallenge = euiccChallenge; } public String getEuiccInfo1() { return euiccInfo1; } public void setEuiccInfo1(String euiccInfo1) { this.euiccInfo1 = euiccInfo1; } public String getSmdpAddress() { return smdpAddress; } public void setSmdpAddress(String smdpAddress) { this.smdpAddress = smdpAddress; } public InitiateAuthenticationRequest getRequest() { InitiateAuthenticationRequest initiateAuthenticationRequest = new InitiateAuthenticationRequest(); initiateAuthenticationRequest.setSmdpAddress(this.getSmdpAddressParsed()); initiateAuthenticationRequest.setEuiccInfo1(this.getEuiccInfo1Parsed()); initiateAuthenticationRequest.setEuiccChallenge(this.getEuiccChallengeParsed()); return initiateAuthenticationRequest; } public void setRequest(InitiateAuthenticationRequest initiateAuthenticationRequest) { setEuiccChallengeParsed(initiateAuthenticationRequest.getEuiccChallenge()); setEuiccInfo1Parsed(initiateAuthenticationRequest.getEuiccInfo1()); setSmdpAddressParsed(initiateAuthenticationRequest.getSmdpAddress()); } private Octet16 getEuiccChallengeParsed() {
return new Octet16(Bytes.decodeBase64String(this.euiccChallenge));
5
2023-11-22 07:46:30+00:00
16k
phamdung2209/FAP
src/main/java/com/func/LectureHandler/Add.java
[ { "identifier": "DateOfBirth", "path": "src/main/java/com/Date/DateOfBirth.java", "snippet": "public class DateOfBirth {\n private int day;\n private int month;\n private int year;\n\n public DateOfBirth() {\n }\n\n public DateOfBirth(int day, int month, int year) {\n this.day =...
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import com.date.DateOfBirth; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.persons.Administrator; import com.persons.Lecturer;
11,459
package com.func.LectureHandler; public class Add { public Scanner scanner = new Scanner(System.in); public void addLecture(Administrator admin) { System.out.println("Enter lecture's information:"); System.out.print("ID: "); String lid = scanner.next(); scanner.nextLine(); System.out.print("Full name: "); String lname = scanner.nextLine(); System.out.print("Gender: "); String lgender = scanner.nextLine(); System.out.print("Date of birth: "); int lday = scanner.nextInt(); System.out.print("Month of birth: "); int lmonth = scanner.nextInt(); System.out.print("Year of birth: "); int lyear = scanner.nextInt(); DateOfBirth ldateOfBirth = new DateOfBirth(); ldateOfBirth.setDay(lday); ldateOfBirth.setMonth(lmonth); ldateOfBirth.setYear(lyear); scanner.nextLine(); System.out.print("Address: "); String laddress = scanner.nextLine(); System.out.print("Phone number: "); String lphoneNumber = scanner.nextLine(); System.out.print("Email: "); String lemail = scanner.nextLine(); System.out.print("Department: "); String ldepartment = scanner.nextLine();
package com.func.LectureHandler; public class Add { public Scanner scanner = new Scanner(System.in); public void addLecture(Administrator admin) { System.out.println("Enter lecture's information:"); System.out.print("ID: "); String lid = scanner.next(); scanner.nextLine(); System.out.print("Full name: "); String lname = scanner.nextLine(); System.out.print("Gender: "); String lgender = scanner.nextLine(); System.out.print("Date of birth: "); int lday = scanner.nextInt(); System.out.print("Month of birth: "); int lmonth = scanner.nextInt(); System.out.print("Year of birth: "); int lyear = scanner.nextInt(); DateOfBirth ldateOfBirth = new DateOfBirth(); ldateOfBirth.setDay(lday); ldateOfBirth.setMonth(lmonth); ldateOfBirth.setYear(lyear); scanner.nextLine(); System.out.print("Address: "); String laddress = scanner.nextLine(); System.out.print("Phone number: "); String lphoneNumber = scanner.nextLine(); System.out.print("Email: "); String lemail = scanner.nextLine(); System.out.print("Department: "); String ldepartment = scanner.nextLine();
Lecturer lecturer = Lecturer.getLecturer();
2
2023-11-23 18:42:19+00:00
16k
morihofi/acmeserver
src/main/java/de/morihofi/acmeserver/certificate/acme/api/endpoints/account/NewAccountEndpoint.java
[ { "identifier": "Provisioner", "path": "src/main/java/de/morihofi/acmeserver/certificate/acme/api/Provisioner.java", "snippet": "public class Provisioner {\n\n\n /**\n * Get the ACME Server URL, reachable from other Hosts\n *\n * @return Full url (including HTTPS prefix) and port to this ...
import com.google.gson.Gson; import de.morihofi.acmeserver.certificate.acme.api.Provisioner; import de.morihofi.acmeserver.certificate.acme.api.abstractclass.AbstractAcmeEndpoint; import de.morihofi.acmeserver.certificate.acme.api.endpoints.account.objects.ACMEAccountRequestPayload; import de.morihofi.acmeserver.certificate.acme.api.endpoints.account.objects.AccountResponse; import de.morihofi.acmeserver.certificate.objects.ACMERequestBody; import de.morihofi.acmeserver.database.Database; import de.morihofi.acmeserver.certificate.acme.security.NonceManager; import de.morihofi.acmeserver.exception.exceptions.ACMEInvalidContactException; import de.morihofi.acmeserver.exception.exceptions.ACMEMalformedException; import de.morihofi.acmeserver.tools.crypto.Crypto; import de.morihofi.acmeserver.tools.regex.EmailValidation; import io.javalin.http.Context; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import java.util.List; import java.util.UUID;
11,048
package de.morihofi.acmeserver.certificate.acme.api.endpoints.account; public class NewAccountEndpoint extends AbstractAcmeEndpoint { /** * Logger */ public final Logger log = LogManager.getLogger(getClass());
package de.morihofi.acmeserver.certificate.acme.api.endpoints.account; public class NewAccountEndpoint extends AbstractAcmeEndpoint { /** * Logger */ public final Logger log = LogManager.getLogger(getClass());
public NewAccountEndpoint(Provisioner provisioner) {
0
2023-11-22 15:54:36+00:00
16k
Invadermonky/JustEnoughMagiculture
src/main/java/com/invadermonky/justenoughmagiculture/integrations/jer/mods/JERIceAndFire.java
[ { "identifier": "JERRenderHippocampus", "path": "src/main/java/com/invadermonky/justenoughmagiculture/client/model/entity/mods/iceandfire/JERRenderHippocampus.java", "snippet": "public class JERRenderHippocampus extends RenderHippocampus {\n public JERRenderHippocampus(RenderManager renderManager) {\...
import com.github.alexthe666.iceandfire.entity.*; import com.github.alexthe666.iceandfire.enums.EnumTroll; import com.github.alexthe666.iceandfire.item.IafItemRegistry; import com.github.alexthe666.iceandfire.world.gen.*; import com.github.alexthe666.rats.server.entity.EntityPirat; import com.github.alexthe666.rats.server.entity.EntityRat; import com.google.common.collect.Sets; import com.invadermonky.justenoughmagiculture.client.model.entity.mods.iceandfire.JERRenderHippocampus; import com.invadermonky.justenoughmagiculture.client.render.entity.mods.rats.JERRenderPirat; import com.invadermonky.justenoughmagiculture.client.render.entity.mods.rats.JERRenderRat; import com.invadermonky.justenoughmagiculture.configs.JEMConfig; import com.invadermonky.justenoughmagiculture.configs.mods.JEMConfigIceAndFire; import com.invadermonky.justenoughmagiculture.integrations.jei.categories.jer.villager.CustomVanillaVillagerEntry; import com.invadermonky.justenoughmagiculture.integrations.jer.IJERIntegration; import com.invadermonky.justenoughmagiculture.integrations.jer.JERBase; import com.invadermonky.justenoughmagiculture.registry.CustomVillagerRegistry; import com.invadermonky.justenoughmagiculture.util.BiomeHelper; import com.invadermonky.justenoughmagiculture.util.LogHelper; import com.invadermonky.justenoughmagiculture.util.ReflectionHelper; import com.invadermonky.justenoughmagiculture.util.StringHelper; import com.invadermonky.justenoughmagiculture.util.modhelpers.IaFLootHelper; import gnu.trove.map.hash.THashMap; import gnu.trove.set.hash.THashSet; import jeresources.api.conditionals.LightLevel; import jeresources.api.drop.LootDrop; import jeresources.entry.MobEntry; import jeresources.registry.MobRegistry; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityWitherSkeleton; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.init.Items; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import net.minecraft.world.biome.Biome; import net.minecraftforge.common.BiomeDictionary; import net.minecraftforge.common.BiomeDictionary.Type; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerCareer; import net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession; import org.apache.commons.lang3.reflect.FieldUtils; import javax.annotation.Nonnull; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; import java.util.Set;
14,196
} @Override public void registerModVillagers() { CustomVillagerRegistry registry = CustomVillagerRegistry.getInstance(); THashMap<VillagerProfession,EntityMyrmexBase> desertMyrmexVillagers = new THashMap<>(5); THashMap<VillagerProfession,EntityMyrmexBase> jungleMyrmexVillagers = new THashMap<>(5); if(jerConfig.JER_VILLAGERS.enableMyrmexQueen) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexQueen, setMyrmexTexture(new EntityMyrmexQueen(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexQueen, setMyrmexTexture(new EntityMyrmexQueen(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexRoyal) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexRoyal, setMyrmexTexture(new EntityMyrmexRoyal(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexRoyal, setMyrmexTexture(new EntityMyrmexRoyal(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexSentinel) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexSentinel, setMyrmexTexture(new EntityMyrmexSentinel(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexSentinel, setMyrmexTexture(new EntityMyrmexSentinel(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexSoldier) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexSoldier, setMyrmexTexture(new EntityMyrmexSoldier(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexSoldier, setMyrmexTexture(new EntityMyrmexSoldier(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexWorker) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexWorker, setMyrmexTexture(new EntityMyrmexWorker(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexWorker, setMyrmexTexture(new EntityMyrmexWorker(world), true)); } registerMyrmexVillagers(registry, desertMyrmexVillagers); registerMyrmexVillagers(registry, jungleMyrmexVillagers); if(jerConfig.JER_VILLAGERS.enableSnowVillager) { registerSnowVillagers(registry); } } private EntityMyrmexBase setMyrmexTexture(EntityMyrmexBase entity, boolean isJungle) { entity.setJungleVariant(isJungle); return entity; } private void registerMyrmexVillagers(CustomVillagerRegistry registry, THashMap<VillagerProfession,EntityMyrmexBase> myrmexVillagers) { myrmexVillagers.forEach((profession, villager) -> { try { VillagerCareer career = profession.getCareer(0); List<List<EntityVillager.ITradeList>> trades = (List<List<EntityVillager.ITradeList>>) ReflectionHelper.getFieldObject(career, "trades"); registry.addVillagerEntry(new CustomVanillaVillagerEntry(career.getName(), 0, trades) { @Override public EntityLivingBase getEntity(@Nonnull Minecraft minecraft) throws IllegalAccessException, InvocationTargetException, InstantiationException { return villager; } @Override public String getDisplayName() { return villager.getDisplayName().getFormattedText(); } @Override public float getRenderScale() { if(villager instanceof EntityMyrmexQueen) return 20.0f; else if(villager instanceof EntityMyrmexRoyal) return 20.0f; else if(villager instanceof EntityMyrmexSentinel) return 30.0f; else if(villager instanceof EntityMyrmexSoldier) return 36.0f; else return 36.0f; } }); } catch(Exception e) { LogHelper.warn(String.format("Failed to register %s villager.", villager.getName())); } }); } @SuppressWarnings("unchecked") private void registerSnowVillagers(CustomVillagerRegistry registry) { Map<Integer,VillagerProfession> iafProfessions = IafVillagerRegistry.INSTANCE.professions; iafProfessions.forEach((id, profession) -> { try { EntitySnowVillager snowVillager = new EntitySnowVillager(world); //Ice and fire is a butt, so I have to set this manually. FieldUtils.writeDeclaredField(snowVillager, "prof", profession, true); VillagerCareer career = profession.getCareer(0); List<List<EntityVillager.ITradeList>> trades = (List<List<EntityVillager.ITradeList>>) ReflectionHelper.getFieldObject(career, "trades"); registry.addVillagerEntry(new CustomVanillaVillagerEntry(career.getName(), id, trades) { @Override public EntityLivingBase getEntity(@Nonnull Minecraft minecraft) throws IllegalAccessException, InvocationTargetException, InstantiationException { return snowVillager; } @Override public String getDisplayName() { return snowVillager.getDisplayName().getFormattedText(); } }); } catch (Exception e) { LogHelper.warn(String.format("Failed to register Snow Villager %s", profession.getRegistryName().toString())); } }); } private void registerIAFDungeon(ResourceLocation lootTable) { JERDungeonStrings dungeon = new JERDungeonStrings(lootTable); registerDungeonLoot(dungeon.category, dungeon.unlocName, lootTable); } public static class JERDungeonStrings { public final String category; public final String unlocName; public JERDungeonStrings(ResourceLocation lootTable) { this.category = lootTable.toString();
package com.invadermonky.justenoughmagiculture.integrations.jer.mods; public class JERIceAndFire extends JERBase implements IJERIntegration { private static JERIceAndFire instance; JEMConfigIceAndFire.JER jerConfig = JEMConfig.ICE_AND_FIRE.JUST_ENOUGH_RESOURCES; private JERIceAndFire() {} public JERIceAndFire(boolean enableJERDungeons, boolean enableJERMobs, boolean enableJERVillagers) { if(enableJERDungeons) registerModDungeons(); if(enableJERMobs) registerModEntities(); if(enableJERVillagers) registerModVillagers(); getInstance(); } public static JERIceAndFire getInstance() { return instance != null ? instance : (instance = new JERIceAndFire()); } /** * Ice and fire needs to register render overrides here because they don't work if registered normally. */ public void lateInit() { registerRenderOverrides(); injectLoot(); } @Override public void registerModDungeons() { registerIAFDungeon(WorldGenCyclopsCave.CYCLOPS_CHEST); registerIAFDungeon(WorldGenFireDragonCave.FIREDRAGON_CHEST); registerIAFDungeon(WorldGenFireDragonCave.FIREDRAGON_MALE_CHEST); registerIAFDungeon(WorldGenHydraCave.HYDRA_CHEST); registerIAFDungeon(WorldGenIceDragonCave.ICEDRAGON_CHEST); registerIAFDungeon(WorldGenIceDragonCave.ICEDRAGON_MALE_CHEST); registerIAFDungeon(WorldGenMyrmexDecoration.DESERT_MYRMEX_FOOD_CHEST); registerIAFDungeon(WorldGenMyrmexDecoration.JUNGLE_MYRMEX_FOOD_CHEST); registerIAFDungeon(WorldGenMyrmexDecoration.MYRMEX_GOLD_CHEST); registerIAFDungeon(WorldGenMyrmexDecoration.MYRMEX_TRASH_CHEST); } @Override public void registerModEntities() { registerDragons(); registerDeathworms(); registerDread(); registerMyrmex(); registerSeaSerpents(); registerMiscMobs(); } @Override @SuppressWarnings("unchecked") public void injectLoot() { if(JEMConfig.ICE_AND_FIRE.enableJERInjectedLoot) { for (MobEntry mobEntry : MobRegistry.getInstance().getMobs()) { if (mobEntry.getEntity() instanceof EntityWitherSkeleton) { try { Field entryField = MobRegistry.getInstance().getClass().getDeclaredField("registry"); entryField.setAccessible(true); Set<MobEntry> mobEntries = (Set<MobEntry>) entryField.get(MobRegistry.getInstance()); mobEntries.remove(mobEntry); Field dropsField = mobEntry.getClass().getDeclaredField("drops"); dropsField.setAccessible(true); mobEntry.addDrop(new LootDrop(IafItemRegistry.witherbone, 0, 1)); mobEntries.add(mobEntry); } catch(Exception ignored) {} } } } } private void registerDragons() { THashSet<Type> validFireTypes = new THashSet<>(Sets.newHashSet(Type.HILLS, Type.MOUNTAIN)); THashSet<Type> invalidForeTypes = new THashSet<>(Sets.newHashSet(Type.COLD, Type.SNOWY)); THashSet<Biome> validIceBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); THashSet<Type> invalidIceTypes = new THashSet<>(Sets.newHashSet(Type.BEACH)); if(jerConfig.JER_MOBS.enableFireDragonMale) { for (int i = 0; i < 3; i++) { EntityFireDragon fireDragon = new EntityFireDragon(world); fireDragon.setVariant(i); fireDragon.setCustomNameTag("entity.jem:iaf_fire_dragon_male.name"); List<LootDrop> drops = IaFLootHelper.toDrops(fireDragon, manager.getLootTableFromLocation(EntityFireDragon.MALE_LOOT)); if (jerConfig.JER_MOBS.enableFireDragonMale) { registerMob(fireDragon, LightLevel.any, getIaFSpawnBiomesFromTypes(validFireTypes, invalidForeTypes), drops); } } } if(jerConfig.JER_MOBS.enableIceDragonMale) { for (int i = 0; i < 3; i++) { EntityIceDragon iceDragon = new EntityIceDragon(world); iceDragon.setVariant(i); iceDragon.setCustomNameTag("entity.jem:iaf_ice_dragon_male.name"); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); List<LootDrop> drops = IaFLootHelper.toDrops(iceDragon, manager.getLootTableFromLocation(EntityIceDragon.MALE_LOOT)); if (jerConfig.JER_MOBS.enableFireDragonMale) { registerMob(iceDragon, LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), drops); } } } if(jerConfig.JER_MOBS.enableFireDragonFemale) { for (int i = 0; i < 3; i++) { EntityFireDragon fireDragon = new EntityFireDragon(world); fireDragon.setVariant(i); fireDragon.setCustomNameTag("entity.jem:iaf_fire_dragon_female.name"); List<LootDrop> femaleDrops = IaFLootHelper.toDrops(fireDragon, manager.getLootTableFromLocation(EntityFireDragon.FEMALE_LOOT)); registerMob(fireDragon, LightLevel.any, getIaFSpawnBiomesFromTypes(validFireTypes, invalidForeTypes), femaleDrops); } } if(jerConfig.JER_MOBS.enableIceDragonFemale) { for(int i = 0; i < 3; i++) { EntityIceDragon iceDragon = new EntityIceDragon(world); iceDragon.setVariant(i); iceDragon.setCustomNameTag("entity.jem:iaf_ice_dragon_female.name"); List<LootDrop> femaleDrops = IaFLootHelper.toDrops(iceDragon, manager.getLootTableFromLocation(EntityIceDragon.FEMALE_LOOT)); registerMob(iceDragon, LightLevel.any, getIaFSpawnBiomes(validIceBiomes, invalidIceTypes), femaleDrops); } } registerRenderHook(EntityDragonBase.class, ((renderInfo, e) -> { GlStateManager.scale(3.0,3.0,3.0); GlStateManager.translate(-0.005,-0.05,0); return renderInfo; })); } private void registerDeathworms() { if(jerConfig.JER_MOBS.enableDeathWormRed) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(2); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(5); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.RED_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormRedGiant) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(2); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(10); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.RED_GIANT_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormTan) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(0); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(5); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.TAN_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormTanGiant) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(0); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(10); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.TAN_GIANT_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormWhite) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(1); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(5); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.WHITE_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } if(jerConfig.JER_MOBS.enableDeathWormWhiteGiant) { EntityDeathWorm deathWorm = new EntityDeathWorm(world); deathWorm.setVariant(1); //0 = Tan, 1 = White, 2 = Red deathWorm.setWormAge(10); //Worm Age of 20 creates giant worms. THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.SANDY, Type.DRY)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.BEACH, Type.MESA)); List<LootDrop> drops = IaFLootHelper.toDrops(deathWorm, manager.getLootTableFromLocation(EntityDeathWorm.WHITE_GIANT_LOOT)); registerMob(deathWorm, LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), drops); } } private void registerDread() { if(jerConfig.JER_MOBS.enableDreadBeast) { EntityDreadBeast dreadBeast = new EntityDreadBeast(world); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadBeast, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadBeast.LOOT); adjustHumanoidRenderHook(EntityDreadBeast.class); } if(jerConfig.JER_MOBS.enableDreadGhoul) { EntityDreadGhoul dreadGhoul = new EntityDreadGhoul(world); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadGhoul, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadGhoul.LOOT); adjustHumanoidRenderHook(EntityDreadGhoul.class); } if(jerConfig.JER_MOBS.enableDreadKnight) { EntityDreadKnight dreadKnight = new EntityDreadKnight(world); dreadKnight.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(IafItemRegistry.dread_knight_sword)); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadKnight, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadKnight.LOOT); registerRenderHook(EntityDreadKnight.class, ((renderInfo, e) -> { GlStateManager.translate(-0.05,0.2,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableDreadLich) { EntityDreadLich lich = new EntityDreadLich(world); lich.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(IafItemRegistry.lich_staff)); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(lich, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadLich.LOOT); adjustHumanoidRenderHook(EntityDreadLich.class); } if(jerConfig.JER_MOBS.enableDreadScuttler) { EntityDreadScuttler dreadScuttler = new EntityDreadScuttler(world); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadScuttler, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadScuttler.LOOT); registerRenderHook(EntityDreadScuttler.class, ((renderInfo, e) -> { GlStateManager.scale(0.9,0.9,0.9); GlStateManager.translate(0,-0.2,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableDreadThrall) { EntityDreadThrall dreadThrall = new EntityDreadThrall(world); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, new ItemStack(IafItemRegistry.dread_sword)); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.HEAD, new ItemStack(Items.CHAINMAIL_HELMET)); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.CHEST, new ItemStack(Items.CHAINMAIL_CHESTPLATE)); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.LEGS, new ItemStack(Items.CHAINMAIL_LEGGINGS)); dreadThrall.setItemStackToSlot(EntityEquipmentSlot.FEET, new ItemStack(Items.CHAINMAIL_BOOTS)); THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.COLD, Type.SNOWY); registerMob(dreadThrall, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityDreadThrall.LOOT); adjustHumanoidRenderHook(dreadThrall.getClass()); } } private void registerMyrmex() { if(jerConfig.JER_MOBS.enableMyrmexDesertQueen) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexQueen(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexQueen.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexDesertRoyal) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexRoyal(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexRoyal.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexDesertSentinel) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexSentinel(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexSentinel.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexDesertSoldier) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexSoldier(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexSoldier.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexDesertWorker) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.HOT, Type.DRY, Type.SANDY); registerMob(setMyrmexTexture(new EntityMyrmexWorker(world), false), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityMyrmexWorker.DESERT_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleQueen) { registerMob(setMyrmexTexture(new EntityMyrmexQueen(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexQueen.JUNGLE_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleRoyal) { registerMob(setMyrmexTexture(new EntityMyrmexRoyal(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexRoyal.JUNGLE_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleSentinel) { registerMob(setMyrmexTexture(new EntityMyrmexSentinel(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexSentinel.JUNGLE_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleSoldier) { registerMob(setMyrmexTexture(new EntityMyrmexSoldier(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexSoldier.JUNGLE_LOOT); } if(jerConfig.JER_MOBS.enableMyrmexJungleWorker) { registerMob(setMyrmexTexture(new EntityMyrmexWorker(world), true), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.JUNGLE), EntityMyrmexWorker.JUNGLE_LOOT); } registerRenderHook(EntityMyrmexQueen.class, ((renderInfo, entityLivingBase) -> { GlStateManager.scale(1.7,1.7,1.7); return renderInfo; })); } private void registerSeaSerpents() { if(jerConfig.JER_MOBS.enableSeaSerpent) { for(int i = 0; i < 6; i++) { EntitySeaSerpent seaSerpent = new EntitySeaSerpent(world); NBTTagCompound tag = new NBTTagCompound(); tag.setFloat("Scale", 1f); seaSerpent.readEntityFromNBT(tag); seaSerpent.setVariant(i); List<LootDrop> drops = IaFLootHelper.toDrops(seaSerpent, manager.getLootTableFromLocation(EntitySeaSerpent.LOOT)); registerMob(seaSerpent, LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.OCEAN), drops); } } } private void registerMiscMobs() { if(jerConfig.JER_MOBS.enableAmphithere) { registerMob(new EntityAmphithere(world), LightLevel.any, BiomeHelper.getTypeNamesForTypes(Type.JUNGLE), EntityAmphithere.LOOT); registerRenderHook(EntityAmphithere.class, ((renderInfo, entityLivingBase) -> { GlStateManager.translate(-0.05,1.4,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableCockatrice) { registerMob(new EntityCockatrice(world), LightLevel.any, BiomeHelper.getTypeNamesForTypes(Type.SAVANNA, Type.SPARSE), EntityCockatrice.LOOT); } if(jerConfig.JER_MOBS.enableCyclops) { registerMob(new EntityCyclops(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.BEACH, Type.PLAINS), EntityCyclops.LOOT); registerRenderHook(EntityCyclops.class, ((renderInfo, entityLivingBase) -> { GlStateManager.scale(0.9,0.9,0.9); GlStateManager.translate(-0.05,-1.75,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableGorgon) { registerMob(new EntityGorgon(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.BEACH), EntityGorgon.LOOT); adjustHumanoidRenderHook(EntityGorgon.class); } if(jerConfig.JER_MOBS.enableHippocampus) { registerMob(new EntityHippocampus(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.OCEAN), EntityHippocampus.LOOT); } if(jerConfig.JER_MOBS.enableHippogryph) { registerMob(new EntityHippogryph(world), LightLevel.any, BiomeHelper.getTypeNamesForTypes(Type.HILLS), EntityHippogryph.LOOT); } if(jerConfig.JER_MOBS.enableHydra) { registerMob(new EntityHydra(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.SWAMP), EntityHydra.LOOT); registerRenderHook(EntityHydra.class, ((renderInfo, e) -> { GlStateManager.scale(1.75,1.75,1.75); GlStateManager.translate(-0.05,-0.4,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enablePixie) { THashSet<Biome> validBiomes = getIaFLinkedBiomes(Type.FOREST, Type.SPOOKY); validBiomes.addAll(BiomeDictionary.getBiomes(Type.MAGICAL)); registerMob(new EntityPixie(world), LightLevel.any, BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])), EntityPixie.LOOT); } if(jerConfig.JER_MOBS.enableSiren) { THashSet<Type> validTypes = new THashSet<>(Sets.newHashSet(Type.OCEAN)); THashSet<Type> invalidTypes = new THashSet<>(Sets.newHashSet(Type.COLD)); registerMob(new EntitySiren(world), LightLevel.any, getIaFSpawnBiomesFromTypes(validTypes, invalidTypes), EntitySiren.LOOT); } if(jerConfig.JER_MOBS.enableStymphalianBird) { registerMob(new EntityStymphalianBird(world), LightLevel.any, BiomeHelper.getBiomeNamesForTypes(Type.SWAMP), EntityStymphalianBird.LOOT); registerRenderHook(EntityStymphalianBird.class, ((renderInfo, e) -> { GlStateManager.scale(1.75,1.75,1.75); GlStateManager.translate(-0.05,-0.3,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableTrollForest) { EntityTroll troll = new EntityTroll(world); troll.setType(EnumTroll.FOREST); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.FOREST_LOOT); } if(jerConfig.JER_MOBS.enableTrollFrost) { EntityTroll troll = new EntityTroll(world); troll.setType(EnumTroll.FROST); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.FROST_LOOT); } if(jerConfig.JER_MOBS.enableTrollMountain) { EntityTroll troll = new EntityTroll(world); troll.setType(EnumTroll.MOUNTAIN); registerMob(troll, LightLevel.hostile, BiomeHelper.getTypeNamesForTypes(troll.getType().spawnBiome), EntityTroll.MOUNTAIN_LOOT); } //Generic Render Hooks registerRenderHook(EntityTroll.class, ((renderInfo, e) -> { GlStateManager.translate(-0.05,-0.8,0); return renderInfo; })); } public void registerRenderOverrides() { if(JEMConfig.ICE_AND_FIRE.enableRenderFixes) { //Ice and Fire uses the depreciated method to register entity renders. RenderingRegistry.registerEntityRenderingHandler(EntityHippocampus.class, new JERRenderHippocampus(Minecraft.getMinecraft().getRenderManager())); } } private THashSet<Biome> getIaFLinkedBiomes(Type... types) { THashSet<Biome> biomes = new THashSet<>(); for(Type type : types) { if(biomes.isEmpty()) { biomes.addAll(BiomeDictionary.getBiomes(type)); } else { biomes.removeIf(biome -> (!BiomeDictionary.getBiomes(type).contains(biome))); } } return biomes; } private String[] getIaFSpawnBiomesFromTypes(THashSet<Type> validTypes, THashSet<Type> invalidTypes) { THashSet<Biome> validBiomes = new THashSet<>(); for(Type validType : validTypes) { validBiomes.addAll(BiomeDictionary.getBiomes(validType)); } for(Type invalidType : invalidTypes) { validBiomes.removeAll(BiomeDictionary.getBiomes(invalidType)); } return validBiomes.isEmpty() ? new String[] {"jer.any"} : BiomeHelper.getBiomeNamesForBiomes(validBiomes.toArray(new Biome[0])); } private String[] getIaFSpawnBiomes(THashSet<Biome> biomes, THashSet<Type> invalidTypes) { for(Type type : invalidTypes) { biomes.removeAll(BiomeDictionary.getBiomes(type)); } return biomes.isEmpty() ? new String[] {"jer.any"} : BiomeHelper.getBiomeNamesForBiomes(biomes.toArray(new Biome[0])); } private void adjustHumanoidRenderHook(Class<? extends EntityLivingBase> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(-0.05,-0.4,0); return renderInfo; })); } @Override public void registerModVillagers() { CustomVillagerRegistry registry = CustomVillagerRegistry.getInstance(); THashMap<VillagerProfession,EntityMyrmexBase> desertMyrmexVillagers = new THashMap<>(5); THashMap<VillagerProfession,EntityMyrmexBase> jungleMyrmexVillagers = new THashMap<>(5); if(jerConfig.JER_VILLAGERS.enableMyrmexQueen) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexQueen, setMyrmexTexture(new EntityMyrmexQueen(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexQueen, setMyrmexTexture(new EntityMyrmexQueen(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexRoyal) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexRoyal, setMyrmexTexture(new EntityMyrmexRoyal(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexRoyal, setMyrmexTexture(new EntityMyrmexRoyal(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexSentinel) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexSentinel, setMyrmexTexture(new EntityMyrmexSentinel(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexSentinel, setMyrmexTexture(new EntityMyrmexSentinel(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexSoldier) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexSoldier, setMyrmexTexture(new EntityMyrmexSoldier(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexSoldier, setMyrmexTexture(new EntityMyrmexSoldier(world), true)); } if(jerConfig.JER_VILLAGERS.enableMyrmexWorker) { desertMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.desertMyrmexWorker, setMyrmexTexture(new EntityMyrmexWorker(world), false)); jungleMyrmexVillagers.put(IafVillagerRegistry.INSTANCE.jungleMyrmexWorker, setMyrmexTexture(new EntityMyrmexWorker(world), true)); } registerMyrmexVillagers(registry, desertMyrmexVillagers); registerMyrmexVillagers(registry, jungleMyrmexVillagers); if(jerConfig.JER_VILLAGERS.enableSnowVillager) { registerSnowVillagers(registry); } } private EntityMyrmexBase setMyrmexTexture(EntityMyrmexBase entity, boolean isJungle) { entity.setJungleVariant(isJungle); return entity; } private void registerMyrmexVillagers(CustomVillagerRegistry registry, THashMap<VillagerProfession,EntityMyrmexBase> myrmexVillagers) { myrmexVillagers.forEach((profession, villager) -> { try { VillagerCareer career = profession.getCareer(0); List<List<EntityVillager.ITradeList>> trades = (List<List<EntityVillager.ITradeList>>) ReflectionHelper.getFieldObject(career, "trades"); registry.addVillagerEntry(new CustomVanillaVillagerEntry(career.getName(), 0, trades) { @Override public EntityLivingBase getEntity(@Nonnull Minecraft minecraft) throws IllegalAccessException, InvocationTargetException, InstantiationException { return villager; } @Override public String getDisplayName() { return villager.getDisplayName().getFormattedText(); } @Override public float getRenderScale() { if(villager instanceof EntityMyrmexQueen) return 20.0f; else if(villager instanceof EntityMyrmexRoyal) return 20.0f; else if(villager instanceof EntityMyrmexSentinel) return 30.0f; else if(villager instanceof EntityMyrmexSoldier) return 36.0f; else return 36.0f; } }); } catch(Exception e) { LogHelper.warn(String.format("Failed to register %s villager.", villager.getName())); } }); } @SuppressWarnings("unchecked") private void registerSnowVillagers(CustomVillagerRegistry registry) { Map<Integer,VillagerProfession> iafProfessions = IafVillagerRegistry.INSTANCE.professions; iafProfessions.forEach((id, profession) -> { try { EntitySnowVillager snowVillager = new EntitySnowVillager(world); //Ice and fire is a butt, so I have to set this manually. FieldUtils.writeDeclaredField(snowVillager, "prof", profession, true); VillagerCareer career = profession.getCareer(0); List<List<EntityVillager.ITradeList>> trades = (List<List<EntityVillager.ITradeList>>) ReflectionHelper.getFieldObject(career, "trades"); registry.addVillagerEntry(new CustomVanillaVillagerEntry(career.getName(), id, trades) { @Override public EntityLivingBase getEntity(@Nonnull Minecraft minecraft) throws IllegalAccessException, InvocationTargetException, InstantiationException { return snowVillager; } @Override public String getDisplayName() { return snowVillager.getDisplayName().getFormattedText(); } }); } catch (Exception e) { LogHelper.warn(String.format("Failed to register Snow Villager %s", profession.getRegistryName().toString())); } }); } private void registerIAFDungeon(ResourceLocation lootTable) { JERDungeonStrings dungeon = new JERDungeonStrings(lootTable); registerDungeonLoot(dungeon.category, dungeon.unlocName, lootTable); } public static class JERDungeonStrings { public final String category; public final String unlocName; public JERDungeonStrings(ResourceLocation lootTable) { this.category = lootTable.toString();
this.unlocName = StringHelper.getDungeonTranslationKey(lootTable);
12
2023-11-19 23:09:14+00:00
16k
Provismet/ProviHealth
src/main/java/com/provismet/provihealth/ProviHealthClient.java
[ { "identifier": "ProviHealthApi", "path": "src/main/java/com/provismet/provihealth/api/ProviHealthApi.java", "snippet": "public interface ProviHealthApi {\n public void onInitialize ();\n\n /**\n * Registers an icon that will display on top of the health bar in the HUD for a specific entity gr...
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.provismet.provihealth.api.ProviHealthApi; import com.provismet.provihealth.config.Options; import com.provismet.provihealth.hud.TargetHealthBar; import com.provismet.provihealth.particle.Particles; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier;
11,694
package com.provismet.provihealth; public class ProviHealthClient implements ClientModInitializer { public static final String MODID = "provihealth"; public static final Logger LOGGER = LoggerFactory.getLogger("Provi's Health Bars"); public static Identifier identifier (String path) { return Identifier.of(MODID, path); } @Override public void onInitializeClient () {
package com.provismet.provihealth; public class ProviHealthClient implements ClientModInitializer { public static final String MODID = "provihealth"; public static final Logger LOGGER = LoggerFactory.getLogger("Provi's Health Bars"); public static Identifier identifier (String path) { return Identifier.of(MODID, path); } @Override public void onInitializeClient () {
HudRenderCallback.EVENT.register(new TargetHealthBar());
2
2023-11-26 02:46:37+00:00
16k
ArmanKhanDev/FakepixelDungeonHelper
src/main/java/io/github/quantizr/core/Waypoints.java
[ { "identifier": "DungeonRooms", "path": "build/sources/main/java/io/github/quantizr/DungeonRooms.java", "snippet": "@Mod(modid = DungeonRooms.MODID, version = DungeonRooms.VERSION)\npublic class DungeonRooms\n{\n public static final String MODID = \"FDH\";\n public static final String VERSION = \"...
import com.google.gson.JsonArray; import com.google.gson.JsonObject; import io.github.quantizr.DungeonRooms; import io.github.quantizr.events.PacketEvent; import io.github.quantizr.utils.Utils; import io.github.quantizr.utils.WaypointUtils; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; import net.minecraft.network.play.server.S0DPacketCollectItem; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.StringUtils; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import java.awt.*; import java.util.*; import java.util.List;
13,348
/* 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.core; public class Waypoints { public static boolean enabled = true; public static boolean showEntrance = true; public static boolean showSuperboom = true; public static boolean showSecrets = true; public static boolean showFairySouls = true; public static boolean sneakToDisable = true; public static boolean disableWhenAllFound = true; public static boolean allFound = false; public static boolean showWaypointText = true; public static boolean showBoundingBox = true; public static boolean showBeacon = true; public static int secretNum = 0; public static int completedSecrets = 0; public static Map<String, List<Boolean>> allSecretsMap = new HashMap<>(); public static List<Boolean> secretsList = new ArrayList<>(Arrays.asList(new Boolean[9])); static long lastSneakTime = 0; @SubscribeEvent public void onWorldRender(RenderWorldLastEvent event) { if (!enabled) return; String roomName = AutoRoom.lastRoomName; if (AutoRoom.lastRoomJson != null && roomName != null && secretsList != null) { secretNum = AutoRoom.lastRoomJson.get("secrets").getAsInt(); if (DungeonRooms.waypointsJson.get(roomName) != null) { JsonArray secretsArray = DungeonRooms.waypointsJson.get(roomName).getAsJsonArray(); int arraySize = secretsArray.size(); for(int i = 0; i < arraySize; i++) { JsonObject secretsObject = secretsArray.get(i).getAsJsonObject(); boolean display = true; for(int j = 1; j <= secretNum; j++) { if (!secretsList.get(j-1)) { if (secretsObject.get("secretName").getAsString().contains(String.valueOf(j))) { display = false; break; } } } if (!display) continue; if (disableWhenAllFound && allFound && !secretsObject.get("category").getAsString().equals("fairysoul")) continue; Color color; switch (secretsObject.get("category").getAsString()) { case "entrance": if (!showEntrance) continue; color = new Color(0, 255, 0); break; case "superboom": if (!showSuperboom) continue; color = new Color(255, 0, 0); break; case "chest": if (!showSecrets) continue; color = new Color(2, 213, 250); break; case "item": if (!showSecrets) continue; color = new Color(2, 64, 250); break; case "bat": if (!showSecrets) continue; color = new Color(142, 66, 0); break; case "wither": if (!showSecrets) continue; color = new Color(30, 30, 30); break; case "lever": if (!showSecrets) continue; color = new Color(250, 217, 2); break; case "fairysoul": if (!showFairySouls) continue; color = new Color(255, 85, 255); break; default: color = new Color(190, 255, 252); } Entity viewer = Minecraft.getMinecraft().getRenderViewEntity(); double viewerX = viewer.lastTickPosX + (viewer.posX - viewer.lastTickPosX) * event.partialTicks; double viewerY = viewer.lastTickPosY + (viewer.posY - viewer.lastTickPosY) * event.partialTicks; double viewerZ = viewer.lastTickPosZ + (viewer.posZ - viewer.lastTickPosZ) * event.partialTicks;
/* 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.core; public class Waypoints { public static boolean enabled = true; public static boolean showEntrance = true; public static boolean showSuperboom = true; public static boolean showSecrets = true; public static boolean showFairySouls = true; public static boolean sneakToDisable = true; public static boolean disableWhenAllFound = true; public static boolean allFound = false; public static boolean showWaypointText = true; public static boolean showBoundingBox = true; public static boolean showBeacon = true; public static int secretNum = 0; public static int completedSecrets = 0; public static Map<String, List<Boolean>> allSecretsMap = new HashMap<>(); public static List<Boolean> secretsList = new ArrayList<>(Arrays.asList(new Boolean[9])); static long lastSneakTime = 0; @SubscribeEvent public void onWorldRender(RenderWorldLastEvent event) { if (!enabled) return; String roomName = AutoRoom.lastRoomName; if (AutoRoom.lastRoomJson != null && roomName != null && secretsList != null) { secretNum = AutoRoom.lastRoomJson.get("secrets").getAsInt(); if (DungeonRooms.waypointsJson.get(roomName) != null) { JsonArray secretsArray = DungeonRooms.waypointsJson.get(roomName).getAsJsonArray(); int arraySize = secretsArray.size(); for(int i = 0; i < arraySize; i++) { JsonObject secretsObject = secretsArray.get(i).getAsJsonObject(); boolean display = true; for(int j = 1; j <= secretNum; j++) { if (!secretsList.get(j-1)) { if (secretsObject.get("secretName").getAsString().contains(String.valueOf(j))) { display = false; break; } } } if (!display) continue; if (disableWhenAllFound && allFound && !secretsObject.get("category").getAsString().equals("fairysoul")) continue; Color color; switch (secretsObject.get("category").getAsString()) { case "entrance": if (!showEntrance) continue; color = new Color(0, 255, 0); break; case "superboom": if (!showSuperboom) continue; color = new Color(255, 0, 0); break; case "chest": if (!showSecrets) continue; color = new Color(2, 213, 250); break; case "item": if (!showSecrets) continue; color = new Color(2, 64, 250); break; case "bat": if (!showSecrets) continue; color = new Color(142, 66, 0); break; case "wither": if (!showSecrets) continue; color = new Color(30, 30, 30); break; case "lever": if (!showSecrets) continue; color = new Color(250, 217, 2); break; case "fairysoul": if (!showFairySouls) continue; color = new Color(255, 85, 255); break; default: color = new Color(190, 255, 252); } Entity viewer = Minecraft.getMinecraft().getRenderViewEntity(); double viewerX = viewer.lastTickPosX + (viewer.posX - viewer.lastTickPosX) * event.partialTicks; double viewerY = viewer.lastTickPosY + (viewer.posY - viewer.lastTickPosY) * event.partialTicks; double viewerZ = viewer.lastTickPosZ + (viewer.posZ - viewer.lastTickPosZ) * event.partialTicks;
BlockPos pos = Utils.relativeToActual(new BlockPos(secretsObject.get("x").getAsInt(), secretsObject.get("y").getAsInt(), secretsObject.get("z").getAsInt()));
2
2023-12-22 04:44:39+00:00
16k
lonelytransistor/LauncherAndroidTV
app/src/main/java/net/lonelytransistor/launcher/entrypoints/LauncherActivity.java
[ { "identifier": "BadgeCard", "path": "app/src/main/java/net/lonelytransistor/launcher/BadgeCard.java", "snippet": "public class BadgeCard extends Card {\n public String title;\n public Object badgeImage;\n public String badgeText;\n public Object mainImage;\n public Object statusIcon;\n ...
import android.app.AppOpsManager; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.os.PowerManager; import android.provider.Settings; import android.util.Log; import android.view.View; import android.view.ViewTreeObserver; import androidx.annotation.NonNull; import net.lonelytransistor.launcher.BadgeCard; import net.lonelytransistor.launcher.Card; import net.lonelytransistor.launcher.LauncherBar; import net.lonelytransistor.launcher.MovieCard; import net.lonelytransistor.launcher.R; import net.lonelytransistor.launcher.WidgetBar; import net.lonelytransistor.launcher.generics.GenericActivity;
12,012
package net.lonelytransistor.launcher.entrypoints; public class LauncherActivity extends GenericActivity implements ViewTreeObserver.OnGlobalFocusChangeListener { private static final String TAG = "LauncherActivity"; private static final String PERMISSION_READ_TV_LISTINGS = "android.permission.READ_TV_LISTINGS"; @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); for (int res : grantResults) { if (res != PackageManager.PERMISSION_GRANTED) { finish(); return; } } start(); } private boolean isUsageAccessGranted() { try { PackageManager packageManager = getPackageManager(); ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0); AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE); int mode = appOpsManager.unsafeCheckOpRaw(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName); return (mode == AppOpsManager.MODE_ALLOWED); } catch (PackageManager.NameNotFoundException e) { return false; } } private boolean isIgnoringBatteryOptimizations() { PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); return powerManager.isIgnoringBatteryOptimizations(getPackageName()); } private void start() { if (checkCallingOrSelfPermission(PERMISSION_READ_TV_LISTINGS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{PERMISSION_READ_TV_LISTINGS}, 0); } else { if (!isUsageAccessGranted()) { Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); intent.putExtra(Intent.EXTRA_PACKAGE_NAME, getPackageName()); startActivity(intent); } else if (!Settings.canDrawOverlays(this)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } else /*if (!isIgnoringBatteryOptimizations()) { Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS, Uri.parse("package:" + getPackageName())); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } else*/ { BackgroundService.showLauncher(this); finish(); } } } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); widgetBar.onStop(); } WidgetBar widgetBar; @Override public void onGlobalFocusChanged(View oldFocus, View newFocus) { Log.i(TAG, "Focus: " + newFocus); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the global focus change listener //getWindow().getDecorView().getRootView().getViewTreeObserver().addOnGlobalFocusChangeListener(this); if (true) { start(); } else if (true) { setContentView(R.layout.activity_main); LauncherBar bar = findViewById(R.id.launcherBar); widgetBar = findViewById(R.id.widgetBar); //widgetBar.constructor(this); int row = bar.addRow(new BadgeCard("Title", "Test0", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, null)); bar.addItems(row, widgetBar.getAllWidgetCards()); row = bar.addRow(new BadgeCard("Title", "Test2", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, new Card.Callback() { @Override public boolean onClicked(Card card) { return false; /*int id = mAppWidgetHost.allocateAppWidgetId(); Log.i(TAG, "Bound: " + mAppWidgetManager.bindAppWidgetIdIfAllowed(id, info.provider)); AppWidgetHostView view = mAppWidgetHost.createView(LauncherActivity.this, id, info); view.setAppWidget(id, info); widgetBar.addView(view);/**/ } @Override public void onHovered(Card card, boolean hovered) { } })); bar.addItem(row, new BadgeCard("Title", "Test0", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, null)); bar.addItem(row, new BadgeCard("Title", "Test1", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, null)); bar.addItem(row, new BadgeCard("Title", "Test2", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, null)); row = bar.addRow(new BadgeCard("Title", "Test3", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, null));
package net.lonelytransistor.launcher.entrypoints; public class LauncherActivity extends GenericActivity implements ViewTreeObserver.OnGlobalFocusChangeListener { private static final String TAG = "LauncherActivity"; private static final String PERMISSION_READ_TV_LISTINGS = "android.permission.READ_TV_LISTINGS"; @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); for (int res : grantResults) { if (res != PackageManager.PERMISSION_GRANTED) { finish(); return; } } start(); } private boolean isUsageAccessGranted() { try { PackageManager packageManager = getPackageManager(); ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0); AppOpsManager appOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE); int mode = appOpsManager.unsafeCheckOpRaw(AppOpsManager.OPSTR_GET_USAGE_STATS, applicationInfo.uid, applicationInfo.packageName); return (mode == AppOpsManager.MODE_ALLOWED); } catch (PackageManager.NameNotFoundException e) { return false; } } private boolean isIgnoringBatteryOptimizations() { PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); return powerManager.isIgnoringBatteryOptimizations(getPackageName()); } private void start() { if (checkCallingOrSelfPermission(PERMISSION_READ_TV_LISTINGS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{PERMISSION_READ_TV_LISTINGS}, 0); } else { if (!isUsageAccessGranted()) { Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS); intent.putExtra(Intent.EXTRA_PACKAGE_NAME, getPackageName()); startActivity(intent); } else if (!Settings.canDrawOverlays(this)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } else /*if (!isIgnoringBatteryOptimizations()) { Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS, Uri.parse("package:" + getPackageName())); intent.setData(Uri.parse("package:" + getPackageName())); startActivity(intent); } else*/ { BackgroundService.showLauncher(this); finish(); } } } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); widgetBar.onStop(); } WidgetBar widgetBar; @Override public void onGlobalFocusChanged(View oldFocus, View newFocus) { Log.i(TAG, "Focus: " + newFocus); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the global focus change listener //getWindow().getDecorView().getRootView().getViewTreeObserver().addOnGlobalFocusChangeListener(this); if (true) { start(); } else if (true) { setContentView(R.layout.activity_main); LauncherBar bar = findViewById(R.id.launcherBar); widgetBar = findViewById(R.id.widgetBar); //widgetBar.constructor(this); int row = bar.addRow(new BadgeCard("Title", "Test0", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, null)); bar.addItems(row, widgetBar.getAllWidgetCards()); row = bar.addRow(new BadgeCard("Title", "Test2", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, new Card.Callback() { @Override public boolean onClicked(Card card) { return false; /*int id = mAppWidgetHost.allocateAppWidgetId(); Log.i(TAG, "Bound: " + mAppWidgetManager.bindAppWidgetIdIfAllowed(id, info.provider)); AppWidgetHostView view = mAppWidgetHost.createView(LauncherActivity.this, id, info); view.setAppWidget(id, info); widgetBar.addView(view);/**/ } @Override public void onHovered(Card card, boolean hovered) { } })); bar.addItem(row, new BadgeCard("Title", "Test0", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, null)); bar.addItem(row, new BadgeCard("Title", "Test1", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, null)); bar.addItem(row, new BadgeCard("Title", "Test2", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, null)); row = bar.addRow(new BadgeCard("Title", "Test3", R.drawable.icon_apps, 0xffff5050, 0xff5050ff, null));
bar.addItem(row, new MovieCard(9));
3
2023-12-28 18:24:12+00:00
16k
RoderickQiu/SUSTech_CSE_Projects
CS109_2022_Fall/Chess/controller/GameController.java
[ { "identifier": "ChessBackup", "path": "CS109_2022_Fall/Chess/model/ChessBackup.java", "snippet": "public class ChessBackup {\n String nowColor;\n String[][] type, color;\n boolean[][] reversal;\n String records = \"--\", redEatenList, blackEatenList;\n int redScore, blackScore;\n\n pu...
import Chess.chessComponent.*; import Chess.model.ChessBackup; import Chess.model.ChessboardPoint; import Chess.utils.FileUtils; import Chess.view.Chessboard; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import javax.swing.*; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import static Chess.utils.FileUtils.getCorrectSlash; import static Chess.view.Chessboard.COL_SIZE; import static Chess.view.Chessboard.ROW_SIZE; import static Chess.view.StartFrame.checkRecords;
13,799
return chessData; } catch (IOException e) { e.printStackTrace(); } return null; } public void toGSon() { ChessBackup backup = chessboard.backupGame(); String[][] reversalString = new String[ROW_SIZE][COL_SIZE]; for (int i = 0; i < ROW_SIZE; i++) { for (int j = 0; j < COL_SIZE; j++) { reversalString[i][j] = String.valueOf(backup.getReversal()[i][j]); } } Map<String, JsonElement> data = new HashMap<>(); data.put("nowColor", gson.toJsonTree(backup.getNowColor())); data.put("type", gson.toJsonTree(backup.getType())); data.put("color", gson.toJsonTree(backup.getColor())); data.put("reversal", gson.toJsonTree(reversalString)); data.put("records", gson.toJsonTree(backup.getRecords())); data.put("redEatenList", gson.toJsonTree(backup.getRedEatenList())); data.put("blackEatenList", gson.toJsonTree(backup.getBlackEatenList())); data.put("redScore", gson.toJsonTree(backup.getRedScore())); data.put("blackScore", gson.toJsonTree(backup.getBlackScore())); try { FileUtils.saveDataToFile("save", Base64.getEncoder().encodeToString(gson.toJson(data).getBytes(StandardCharsets.UTF_8)), "txt"); JOptionPane.showMessageDialog(null, "保存在 " + System.getProperty("user.dir") + getCorrectSlash() + "save.txt"); } catch (Exception e) { System.out.println("ERR: " + e.getMessage()); } } private boolean checkChess(String[][] type, String[][] color) { String typeStr = "class Chess.chessComponent.ShuaiComponent class Chess.chessComponent.ShiComponent class Chess.chessComponent.XiangComponent class Chess.chessComponent.JuComponent class Chess.chessComponent.MaComponent class Chess.chessComponent.MaComponent class Chess.chessComponent.ZuComponent class Chess.chessComponent.PaoComponent class Chess.chessComponent.EmptySlotComponent"; final int[] maxList = {1, 2, 2, 2, 2, 5, 2}; int[] blackList = {0, 0, 0, 0, 0, 0, 0}, redList = {0, 0, 0, 0, 0, 0, 0}; for (int i = 0; i < ROW_SIZE; i++) { for (int j = 0; j < COL_SIZE; j++) { if (!typeStr.contains(type[i][j])) return false; if (!type[i][j].equals("class Chess.chessComponent.EmptySlotComponent")) { if (!color[i][j].equals("b") && !color[i][j].equals("r")) return false; if (color[i][j].equals("b")) { switch (type[i][j]) { case "class Chess.chessComponent.ShuaiComponent" -> blackList[0]++; case "class Chess.chessComponent.ShiComponent" -> blackList[1]++; case "class Chess.chessComponent.XiangComponent" -> blackList[2]++; case "class Chess.chessComponent.JuComponent" -> blackList[3]++; case "class Chess.chessComponent.MaComponent" -> blackList[4]++; case "class Chess.chessComponent.ZuComponent" -> blackList[5]++; case "class Chess.chessComponent.PaoComponent" -> blackList[6]++; } } else { switch (type[i][j]) { case "class Chess.chessComponent.ShuaiComponent" -> redList[0]++; case "class Chess.chessComponent.ShiComponent" -> redList[1]++; case "class Chess.chessComponent.XiangComponent" -> redList[2]++; case "class Chess.chessComponent.JuComponent" -> redList[3]++; case "class Chess.chessComponent.MaComponent" -> redList[4]++; case "class Chess.chessComponent.ZuComponent" -> redList[5]++; case "class Chess.chessComponent.PaoComponent" -> redList[6]++; } } } } } for (int i = 0; i < 7; i++) { if (blackList[i] > maxList[i]) return false; if (redList[i] > maxList[i]) return false; } return true; } public void loadGSon(String path) { if (!path.split("\\.")[path.split("\\.").length - 1].equals("txt")) { JOptionPane.showMessageDialog(null, "101 文件格式错误,没有以 .txt 结尾!"); return; } try { String input = FileUtils.getDataFromFileInAbsolutePath(path); String decoded = new String(Base64.getDecoder().decode(input), StandardCharsets.UTF_8); Map<String, JsonElement> data = JsonParser.parseString(decoded).getAsJsonObject().asMap(); String nowColor = gson.fromJson(data.get("nowColor"), new TypeToken<String>() { }.getType()); String[][] type = gson.fromJson(data.get("type"), new TypeToken<String[][]>() { }.getType()); String[][] color = gson.fromJson(data.get("color"), new TypeToken<String[][]>() { }.getType()); String[][] reversal = gson.fromJson(data.get("reversal"), new TypeToken<String[][]>() { }.getType()); String records = gson.fromJson(data.get("records"), new TypeToken<String>() { }.getType()); String redEatenList = gson.fromJson(data.get("redEatenList"), new TypeToken<String>() { }.getType()); String blackEatenList = gson.fromJson(data.get("blackEatenList"), new TypeToken<String>() { }.getType()); int redScore = (gson.fromJson(data.get("redScore"), new TypeToken<Integer>() { }.getType()) == null) ? 0 : gson.fromJson(data.get("redScore"), new TypeToken<Integer>() { }.getType()); int blackScore = (gson.fromJson(data.get("blackScore"), new TypeToken<Integer>() { }.getType()) == null) ? 0 : gson.fromJson(data.get("blackScore"), new TypeToken<Integer>() { }.getType()); boolean[][] reversalBoolean = new boolean[ROW_SIZE][COL_SIZE]; for (int i = 0; i < ROW_SIZE; i++) { for (int j = 0; j < COL_SIZE; j++) { reversalBoolean[i][j] = reversal[i][j].equals("true"); } } if (type.length != ROW_SIZE || type[0].length != COL_SIZE) { JOptionPane.showMessageDialog(null, "102 棋盘尺寸错误!"); } else if (!checkChess(type, color)) { JOptionPane.showMessageDialog(null, "103 棋子并非红黑棋子/空格或某种棋子数不对!"); } else if (nowColor == null) { JOptionPane.showMessageDialog(null, "104 缺少行棋方!");
package Chess.controller; /** * 这个类主要完成由窗体上组件触发的动作。 * 例如点击button等 * ChessGameFrame中组件调用本类的对象,在本类中的方法里完成逻辑运算,将运算的结果传递至chessboard中绘制 */ public class GameController { private Chessboard chessboard; public Gson gson = new Gson(); public GameController(Chessboard chessboard) { this.chessboard = chessboard; } public List<String> loadGameFromFile(String path) { try { List<String> chessData = Files.readAllLines(Path.of(path)); //chessboard.loadGame(chessData); return chessData; } catch (IOException e) { e.printStackTrace(); } return null; } public void toGSon() { ChessBackup backup = chessboard.backupGame(); String[][] reversalString = new String[ROW_SIZE][COL_SIZE]; for (int i = 0; i < ROW_SIZE; i++) { for (int j = 0; j < COL_SIZE; j++) { reversalString[i][j] = String.valueOf(backup.getReversal()[i][j]); } } Map<String, JsonElement> data = new HashMap<>(); data.put("nowColor", gson.toJsonTree(backup.getNowColor())); data.put("type", gson.toJsonTree(backup.getType())); data.put("color", gson.toJsonTree(backup.getColor())); data.put("reversal", gson.toJsonTree(reversalString)); data.put("records", gson.toJsonTree(backup.getRecords())); data.put("redEatenList", gson.toJsonTree(backup.getRedEatenList())); data.put("blackEatenList", gson.toJsonTree(backup.getBlackEatenList())); data.put("redScore", gson.toJsonTree(backup.getRedScore())); data.put("blackScore", gson.toJsonTree(backup.getBlackScore())); try { FileUtils.saveDataToFile("save", Base64.getEncoder().encodeToString(gson.toJson(data).getBytes(StandardCharsets.UTF_8)), "txt"); JOptionPane.showMessageDialog(null, "保存在 " + System.getProperty("user.dir") + getCorrectSlash() + "save.txt"); } catch (Exception e) { System.out.println("ERR: " + e.getMessage()); } } private boolean checkChess(String[][] type, String[][] color) { String typeStr = "class Chess.chessComponent.ShuaiComponent class Chess.chessComponent.ShiComponent class Chess.chessComponent.XiangComponent class Chess.chessComponent.JuComponent class Chess.chessComponent.MaComponent class Chess.chessComponent.MaComponent class Chess.chessComponent.ZuComponent class Chess.chessComponent.PaoComponent class Chess.chessComponent.EmptySlotComponent"; final int[] maxList = {1, 2, 2, 2, 2, 5, 2}; int[] blackList = {0, 0, 0, 0, 0, 0, 0}, redList = {0, 0, 0, 0, 0, 0, 0}; for (int i = 0; i < ROW_SIZE; i++) { for (int j = 0; j < COL_SIZE; j++) { if (!typeStr.contains(type[i][j])) return false; if (!type[i][j].equals("class Chess.chessComponent.EmptySlotComponent")) { if (!color[i][j].equals("b") && !color[i][j].equals("r")) return false; if (color[i][j].equals("b")) { switch (type[i][j]) { case "class Chess.chessComponent.ShuaiComponent" -> blackList[0]++; case "class Chess.chessComponent.ShiComponent" -> blackList[1]++; case "class Chess.chessComponent.XiangComponent" -> blackList[2]++; case "class Chess.chessComponent.JuComponent" -> blackList[3]++; case "class Chess.chessComponent.MaComponent" -> blackList[4]++; case "class Chess.chessComponent.ZuComponent" -> blackList[5]++; case "class Chess.chessComponent.PaoComponent" -> blackList[6]++; } } else { switch (type[i][j]) { case "class Chess.chessComponent.ShuaiComponent" -> redList[0]++; case "class Chess.chessComponent.ShiComponent" -> redList[1]++; case "class Chess.chessComponent.XiangComponent" -> redList[2]++; case "class Chess.chessComponent.JuComponent" -> redList[3]++; case "class Chess.chessComponent.MaComponent" -> redList[4]++; case "class Chess.chessComponent.ZuComponent" -> redList[5]++; case "class Chess.chessComponent.PaoComponent" -> redList[6]++; } } } } } for (int i = 0; i < 7; i++) { if (blackList[i] > maxList[i]) return false; if (redList[i] > maxList[i]) return false; } return true; } public void loadGSon(String path) { if (!path.split("\\.")[path.split("\\.").length - 1].equals("txt")) { JOptionPane.showMessageDialog(null, "101 文件格式错误,没有以 .txt 结尾!"); return; } try { String input = FileUtils.getDataFromFileInAbsolutePath(path); String decoded = new String(Base64.getDecoder().decode(input), StandardCharsets.UTF_8); Map<String, JsonElement> data = JsonParser.parseString(decoded).getAsJsonObject().asMap(); String nowColor = gson.fromJson(data.get("nowColor"), new TypeToken<String>() { }.getType()); String[][] type = gson.fromJson(data.get("type"), new TypeToken<String[][]>() { }.getType()); String[][] color = gson.fromJson(data.get("color"), new TypeToken<String[][]>() { }.getType()); String[][] reversal = gson.fromJson(data.get("reversal"), new TypeToken<String[][]>() { }.getType()); String records = gson.fromJson(data.get("records"), new TypeToken<String>() { }.getType()); String redEatenList = gson.fromJson(data.get("redEatenList"), new TypeToken<String>() { }.getType()); String blackEatenList = gson.fromJson(data.get("blackEatenList"), new TypeToken<String>() { }.getType()); int redScore = (gson.fromJson(data.get("redScore"), new TypeToken<Integer>() { }.getType()) == null) ? 0 : gson.fromJson(data.get("redScore"), new TypeToken<Integer>() { }.getType()); int blackScore = (gson.fromJson(data.get("blackScore"), new TypeToken<Integer>() { }.getType()) == null) ? 0 : gson.fromJson(data.get("blackScore"), new TypeToken<Integer>() { }.getType()); boolean[][] reversalBoolean = new boolean[ROW_SIZE][COL_SIZE]; for (int i = 0; i < ROW_SIZE; i++) { for (int j = 0; j < COL_SIZE; j++) { reversalBoolean[i][j] = reversal[i][j].equals("true"); } } if (type.length != ROW_SIZE || type[0].length != COL_SIZE) { JOptionPane.showMessageDialog(null, "102 棋盘尺寸错误!"); } else if (!checkChess(type, color)) { JOptionPane.showMessageDialog(null, "103 棋子并非红黑棋子/空格或某种棋子数不对!"); } else if (nowColor == null) { JOptionPane.showMessageDialog(null, "104 缺少行棋方!");
} else if (!checkRecords(records)) {
7
2023-12-31 05:50:13+00:00
16k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/config/MayOBeesConfig.java
[ { "identifier": "ModuleManager", "path": "src/main/java/com/github/may2beez/mayobees/module/ModuleManager.java", "snippet": "@Getter\npublic class ModuleManager {\n private static ModuleManager instance;\n\n public static ModuleManager getInstance() {\n if (instance == null) {\n ...
import cc.polyfrost.oneconfig.config.Config; import cc.polyfrost.oneconfig.config.annotations.*; import cc.polyfrost.oneconfig.config.annotations.Number; import cc.polyfrost.oneconfig.config.core.OneColor; import cc.polyfrost.oneconfig.config.core.OneKeyBind; import cc.polyfrost.oneconfig.config.data.InfoType; import cc.polyfrost.oneconfig.config.data.Mod; import cc.polyfrost.oneconfig.config.data.ModType; import com.github.may2beez.mayobees.module.ModuleManager; import com.github.may2beez.mayobees.module.impl.combat.ShortbowAura; import com.github.may2beez.mayobees.module.impl.other.Dev; import com.github.may2beez.mayobees.module.impl.player.GiftAura; import com.github.may2beez.mayobees.module.impl.render.ESP; import com.github.may2beez.mayobees.module.impl.skills.AlchemyHelper; import com.github.may2beez.mayobees.util.LogUtils; import org.lwjgl.input.Keyboard;
14,351
@Info( text = "The speed of the shortbow aura's attack", category = "Combat", subcategory = "Shortbow Aura", size = 2, type = InfoType.INFO ) public static String shortBowAuraAttackSpeedInfo = "The speed of the shortbow aura's attack"; @Slider( name = "Shortbow Aura Cooldown (ms)", description = "The cooldown of the shortbow aura", category = "Combat", subcategory = "Shortbow Aura", min = 0, max = 1000 ) public static int shortBowAuraCooldown = 500; @Slider( name = "Shortbow Aura Cooldown Randomizer (ms)", description = "The randomizer of the shortbow aura cooldown", category = "Combat", subcategory = "Shortbow Aura", min = 0, max = 1000 ) public static int shortBowAuraCooldownRandomizer = 100; public static long getRandomizedCooldown() { return (long) (shortBowAuraCooldown + Math.random() * shortBowAuraCooldownRandomizer); } @Color( name = "Shortbow Aura Target Color", description = "The color of the shortbow aura", category = "Combat", subcategory = "Shortbow Aura" ) public static OneColor shortBowAuraTargetColor = new OneColor(255, 0, 0, 100); //</editor-fold> //<editor-fold desc="RENDER"> //<editor-fold desc="Chest ESP"> @Switch( name = "Chest ESP", description = "Highlights chests", category = "Render", subcategory = "Chest ESP" ) public static boolean chestESP = false; @Color( name = "Chest ESP Color", description = "The color of the chest ESP", category = "Render", subcategory = "Chest ESP" ) public static OneColor chestESPColor = new OneColor(194, 91, 12, 100); @Switch( name = "Chest ESP Tracers", description = "Draws lines to chests", category = "Render", subcategory = "Chest ESP" ) public static boolean chestESPTracers = false; //</editor-fold> //<editor-fold desc="Fairy Soul ESP"> @Switch( name = "Fairy Soul ESP", description = "Highlights fairy souls", category = "Render", subcategory = "Fairy Soul ESP" ) public static boolean fairySoulESP = false; @Color( name = "Fairy Soul ESP Color", description = "The color of the fairy soul ESP", category = "Render", subcategory = "Fairy Soul ESP" ) public static OneColor fairySoulESPColor = new OneColor(147, 8, 207, 100); @Switch( name = "Fairy Soul ESP Tracers", description = "Draws lines to fairy souls", category = "Render", subcategory = "Fairy Soul ESP" ) public static boolean fairySoulESPTracers = false; @Switch( name = "Fairy Soul ESP Show Only Closest", description = "Only shows the closest fairy soul", category = "Render", subcategory = "Fairy Soul ESP" ) public static boolean fairySoulESPShowOnlyClosest = false; @Switch( name = "Fairy Soul ESP Show Distance", description = "Shows the distance to the fairy soul", category = "Render", subcategory = "Fairy Soul ESP" ) public static boolean fairySoulESPShowDistance = false; @Button( name = "Fairy Soul ESP Reset", text = "Reset", description = "Resets the fairy soul ESP", category = "Render", subcategory = "Fairy Soul ESP", size = 2 ) public static void fairySoulESPReset() {
package com.github.may2beez.mayobees.config; public class MayOBeesConfig extends Config { //<editor-fold desc="COMBAT"> @KeyBind( name = "Shortbow Aura", description = "Automatically shoots arrows at nearby enemies", category = "Combat", subcategory = "Shortbow Aura" ) public static OneKeyBind shortBowAuraKeybind = new OneKeyBind(Keyboard.KEY_O); @Text( name = "Shortbow Aura Item's Name", description = "The name of the item to use for the shortbow aura", category = "Combat", subcategory = "Shortbow Aura", size = 2 ) public static String shortBowAuraItemName = "Shortbow"; @Switch( name = "Shortbow Aura Attack Animals", description = "Whether or not to attack mobs", category = "Combat", subcategory = "Shortbow Aura" ) public static boolean shortBowAuraAttackMobs = true; @Switch( name = "Shortbow Aura Attack Until Dead", description = "Whether or not to attack mobs until they are dead", category = "Combat", subcategory = "Shortbow Aura" ) public static boolean shortBowAuraAttackUntilDead = false; @DualOption( name = "Shortbow Aura Rotation Type", description = "The type of rotation to use for the shortbow aura", category = "Combat", subcategory = "Shortbow Aura", left = "Silent", right = "Client", size = 2 ) public static boolean shortBowAuraRotationType = false; @DualOption( name = "Shortbow Aura Mouse Button", description = "The mouse button to use for the shortbow aura", category = "Combat", subcategory = "Shortbow Aura", left = "Left", right = "Right", size = 2 ) public static boolean shortBowAuraMouseButton = false; @DualOption( name = "Shortbow Aura Rotation Mode", description = "The mode of rotation to use for the shortbow aura", category = "Combat", subcategory = "Shortbow Aura", left = "Bow Rotation", right = "Straight Rotation" ) public static boolean shortBowAuraRotationMode = false; @Info( text = "The range of the shortbow aura", category = "Combat", subcategory = "Shortbow Aura", size = 2, type = InfoType.INFO ) public static String shortBowAuraRangeInfo = "The range of the shortbow aura"; @Slider( name = "Shortbow Aura Range", description = "The range of the shortbow aura", category = "Combat", subcategory = "Shortbow Aura", min = 4, max = 30 ) public static int shortBowAuraRange = 15; @Slider( name = "Shortbow Aura FOV", description = "The FOV of the shortbow aura", category = "Combat", subcategory = "Shortbow Aura", min = 0, max = 360 ) public static int shortBowAuraFOV = 120; @Info( text = "The speed of the shortbow aura's rotation", category = "Combat", subcategory = "Shortbow Aura", size = 2, type = InfoType.INFO ) public static String shortBowAuraRotationSpeedInfo = "The speed of the shortbow aura's rotation"; @Slider( name = "Shortbow Aura Rotation Speed", description = "The speed of the shortbow aura's rotation", category = "Combat", subcategory = "Shortbow Aura", min = 50, max = 800 ) public static int shortBowAuraRotationSpeed = 300; @Slider( name = "Shortbow Aura Rotation Speed Randomizer", description = "The speed of the shortbow aura's rotation", category = "Combat", subcategory = "Shortbow Aura", min = 0, max = 500 ) public static int shortBowAuraRotationSpeedRandomizer = 100; public static long getRandomizedRotationSpeed() { return (long) (shortBowAuraRotationSpeed + Math.random() * shortBowAuraRotationSpeedRandomizer); } @Info( text = "The speed of the shortbow aura's attack", category = "Combat", subcategory = "Shortbow Aura", size = 2, type = InfoType.INFO ) public static String shortBowAuraAttackSpeedInfo = "The speed of the shortbow aura's attack"; @Slider( name = "Shortbow Aura Cooldown (ms)", description = "The cooldown of the shortbow aura", category = "Combat", subcategory = "Shortbow Aura", min = 0, max = 1000 ) public static int shortBowAuraCooldown = 500; @Slider( name = "Shortbow Aura Cooldown Randomizer (ms)", description = "The randomizer of the shortbow aura cooldown", category = "Combat", subcategory = "Shortbow Aura", min = 0, max = 1000 ) public static int shortBowAuraCooldownRandomizer = 100; public static long getRandomizedCooldown() { return (long) (shortBowAuraCooldown + Math.random() * shortBowAuraCooldownRandomizer); } @Color( name = "Shortbow Aura Target Color", description = "The color of the shortbow aura", category = "Combat", subcategory = "Shortbow Aura" ) public static OneColor shortBowAuraTargetColor = new OneColor(255, 0, 0, 100); //</editor-fold> //<editor-fold desc="RENDER"> //<editor-fold desc="Chest ESP"> @Switch( name = "Chest ESP", description = "Highlights chests", category = "Render", subcategory = "Chest ESP" ) public static boolean chestESP = false; @Color( name = "Chest ESP Color", description = "The color of the chest ESP", category = "Render", subcategory = "Chest ESP" ) public static OneColor chestESPColor = new OneColor(194, 91, 12, 100); @Switch( name = "Chest ESP Tracers", description = "Draws lines to chests", category = "Render", subcategory = "Chest ESP" ) public static boolean chestESPTracers = false; //</editor-fold> //<editor-fold desc="Fairy Soul ESP"> @Switch( name = "Fairy Soul ESP", description = "Highlights fairy souls", category = "Render", subcategory = "Fairy Soul ESP" ) public static boolean fairySoulESP = false; @Color( name = "Fairy Soul ESP Color", description = "The color of the fairy soul ESP", category = "Render", subcategory = "Fairy Soul ESP" ) public static OneColor fairySoulESPColor = new OneColor(147, 8, 207, 100); @Switch( name = "Fairy Soul ESP Tracers", description = "Draws lines to fairy souls", category = "Render", subcategory = "Fairy Soul ESP" ) public static boolean fairySoulESPTracers = false; @Switch( name = "Fairy Soul ESP Show Only Closest", description = "Only shows the closest fairy soul", category = "Render", subcategory = "Fairy Soul ESP" ) public static boolean fairySoulESPShowOnlyClosest = false; @Switch( name = "Fairy Soul ESP Show Distance", description = "Shows the distance to the fairy soul", category = "Render", subcategory = "Fairy Soul ESP" ) public static boolean fairySoulESPShowDistance = false; @Button( name = "Fairy Soul ESP Reset", text = "Reset", description = "Resets the fairy soul ESP", category = "Render", subcategory = "Fairy Soul ESP", size = 2 ) public static void fairySoulESPReset() {
ESP.getInstance().resetClickedFairySouls();
4
2023-12-24 15:39:11+00:00
16k
Trodev-IT/ScanHub
app/src/main/java/com/trodev/scanhub/HomeFragment.java
[ { "identifier": "EmailActivity", "path": "app/src/main/java/com/trodev/scanhub/activities/EmailActivity.java", "snippet": "public class EmailActivity extends AppCompatActivity {\n\n public final static int QRCodeWidth = 500;\n Bitmap bitmap;\n private Button make_btn, save_btn, downloadBtn;\n ...
import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.google.android.material.card.MaterialCardView; import com.trodev.scanhub.activities.EmailActivity; import com.trodev.scanhub.activities.LocationActivity; import com.trodev.scanhub.activities.ProductQrActivity; import com.trodev.scanhub.activities.ScanGalleryActivity; import com.trodev.scanhub.activities.ScannerActivity; import com.trodev.scanhub.activities.SmsActivity; import com.trodev.scanhub.activities.URLActivity; import com.trodev.scanhub.activities.WifiQrActivity;
12,395
package com.trodev.scanhub; public class HomeFragment extends Fragment { MaterialCardView product_qr, message, wifi; MaterialCardView email_qr, location_qr, url_qr; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); /*init views*/ product_qr = view.findViewById(R.id.product_qr); message = view.findViewById(R.id.message); wifi = view.findViewById(R.id.wifi); email_qr = view.findViewById(R.id.email_qr); location_qr = view.findViewById(R.id.location_qr); url_qr = view.findViewById(R.id.url_qr); /*set on click listener*/ product_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_product(); } }); message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_message(); } }); wifi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_wifi(); } }); email_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_email(); } }); location_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_location(); } }); url_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_url(); } }); return view; } private void goto_url() {
package com.trodev.scanhub; public class HomeFragment extends Fragment { MaterialCardView product_qr, message, wifi; MaterialCardView email_qr, location_qr, url_qr; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); /*init views*/ product_qr = view.findViewById(R.id.product_qr); message = view.findViewById(R.id.message); wifi = view.findViewById(R.id.wifi); email_qr = view.findViewById(R.id.email_qr); location_qr = view.findViewById(R.id.location_qr); url_qr = view.findViewById(R.id.url_qr); /*set on click listener*/ product_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_product(); } }); message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_message(); } }); wifi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_wifi(); } }); email_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_email(); } }); location_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_location(); } }); url_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_url(); } }); return view; } private void goto_url() {
startActivity(new Intent(getContext(), URLActivity.class));
6
2023-12-26 05:10:38+00:00
16k
HuXin0817/shop_api
seller-api/src/main/java/cn/lili/controller/other/broadcast/CommodityStoreController.java
[ { "identifier": "ResultCode", "path": "framework/src/main/java/cn/lili/common/enums/ResultCode.java", "snippet": "public enum ResultCode {\n\n /**\n * 成功状态码\n */\n SUCCESS(200, \"成功\"),\n\n /**\n * 失败返回码\n */\n ERROR(400, \"服务器繁忙,请稍后重试\"),\n\n /**\n * 失败返回码\n */\n ...
import cn.lili.common.enums.ResultCode; import cn.lili.common.enums.ResultUtil; import cn.lili.common.exception.ServiceException; import cn.lili.common.vo.PageVO; import cn.lili.common.vo.ResultMessage; import cn.lili.modules.goods.entity.dos.Commodity; import cn.lili.modules.goods.entity.vos.CommodityVO; import cn.lili.modules.goods.service.CommodityService; import com.baomidou.mybatisplus.core.metadata.IPage; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List;
10,879
package cn.lili.controller.other.broadcast; /** * 店铺端,直播商品接口 * * @author Bulbasaur * @since 2021/5/17 2:05 下午 */ @RestController @Api(tags = "店铺端,直播商品接口") @RequestMapping("/store/broadcast/commodity") public class CommodityStoreController { @Autowired private CommodityService commodityService; @ApiOperation(value = "获取店铺直播商品列表") @ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "商品名称", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "auditStatus", value = "直播商品状态", dataType = "String", paramType = "query") }) @GetMapping
package cn.lili.controller.other.broadcast; /** * 店铺端,直播商品接口 * * @author Bulbasaur * @since 2021/5/17 2:05 下午 */ @RestController @Api(tags = "店铺端,直播商品接口") @RequestMapping("/store/broadcast/commodity") public class CommodityStoreController { @Autowired private CommodityService commodityService; @ApiOperation(value = "获取店铺直播商品列表") @ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "商品名称", dataType = "String", paramType = "query"), @ApiImplicitParam(name = "auditStatus", value = "直播商品状态", dataType = "String", paramType = "query") }) @GetMapping
public ResultMessage<IPage<CommodityVO>> page(String auditStatus, String name, PageVO pageVO) {
4
2023-12-24 19:45:18+00:00
16k
Yanyutin753/PandoraNext-TokensTool
rearServer/src/main/java/com/tokensTool/pandoraNext/util/MyTaskUtils.java
[ { "identifier": "systemSetting", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/systemSetting.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class systemSetting {\n /**\n * 绑定IP和端口\n */\n private String bing;\n /**\n * 请求的超时时间\n */\n...
import com.tokensTool.pandoraNext.pojo.systemSetting; import com.tokensTool.pandoraNext.service.impl.apiServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.support.CronTrigger; import org.springframework.stereotype.Service; import java.util.concurrent.ScheduledFuture;
11,856
package com.tokensTool.pandoraNext.util; @Slf4j @Service public class MyTaskUtils { private final TaskScheduler taskScheduler; @Autowired private apiServiceImpl apiService; private ScheduledFuture<?> future; public MyTaskUtils(TaskScheduler taskScheduler) { this.taskScheduler = taskScheduler; } public void stopTask() { if (future != null) { future.cancel(true); log.info("取消定时任务成功!"); } }
package com.tokensTool.pandoraNext.util; @Slf4j @Service public class MyTaskUtils { private final TaskScheduler taskScheduler; @Autowired private apiServiceImpl apiService; private ScheduledFuture<?> future; public MyTaskUtils(TaskScheduler taskScheduler) { this.taskScheduler = taskScheduler; } public void stopTask() { if (future != null) { future.cancel(true); log.info("取消定时任务成功!"); } }
public void changeTask(systemSetting setting) {
0
2023-11-17 11:37:37+00:00
16k
quarkiverse/quarkus-langchain4j
core/deployment/src/main/java/io/quarkiverse/langchain4j/deployment/AiServicesProcessor.java
[ { "identifier": "illegalConfigurationForMethod", "path": "core/deployment/src/main/java/io/quarkiverse/langchain4j/deployment/ExceptionUtil.java", "snippet": "static IllegalConfigurationException illegalConfigurationForMethod(String message, MethodInfo offendingMethod) {\n String effectiveMessage = m...
import static dev.langchain4j.exception.IllegalConfigurationException.illegalConfiguration; import static dev.langchain4j.service.ServiceOutputParser.outputFormatInstructions; import static io.quarkiverse.langchain4j.deployment.ExceptionUtil.illegalConfigurationForMethod; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.lang.annotation.Annotation; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.AnnotationValue; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.ClassType; import org.jboss.jandex.DotName; import org.jboss.jandex.IndexView; import org.jboss.jandex.MethodInfo; import org.jboss.jandex.MethodParameterInfo; import org.jboss.jandex.ParameterizedType; import org.jboss.jandex.Type; import org.jboss.logging.Logger; import org.objectweb.asm.ClassReader; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.analysis.AnalyzerException; import dev.langchain4j.exception.IllegalConfigurationException; import dev.langchain4j.service.V; import io.quarkiverse.langchain4j.deployment.items.SelectedChatModelProviderBuildItem; import io.quarkiverse.langchain4j.runtime.AiServicesRecorder; import io.quarkiverse.langchain4j.runtime.aiservice.AiServiceClassCreateInfo; import io.quarkiverse.langchain4j.runtime.aiservice.AiServiceMethodCreateInfo; import io.quarkiverse.langchain4j.runtime.aiservice.AiServiceMethodImplementationSupport; import io.quarkiverse.langchain4j.runtime.aiservice.ChatMemoryRemovable; import io.quarkiverse.langchain4j.runtime.aiservice.DeclarativeAiServiceCreateInfo; import io.quarkiverse.langchain4j.runtime.aiservice.MetricsCountedWrapper; import io.quarkiverse.langchain4j.runtime.aiservice.MetricsTimedWrapper; import io.quarkiverse.langchain4j.runtime.aiservice.QuarkusAiServiceContext; import io.quarkiverse.langchain4j.runtime.aiservice.SpanWrapper; import io.quarkus.arc.Arc; import io.quarkus.arc.ArcContainer; import io.quarkus.arc.InstanceHandle; import io.quarkus.arc.deployment.AdditionalBeanBuildItem; import io.quarkus.arc.deployment.GeneratedBeanBuildItem; import io.quarkus.arc.deployment.GeneratedBeanGizmoAdaptor; import io.quarkus.arc.deployment.SyntheticBeanBuildItem; import io.quarkus.arc.deployment.UnremovableBeanBuildItem; import io.quarkus.arc.processor.BuiltinScope; import io.quarkus.arc.processor.ScopeInfo; import io.quarkus.builder.item.MultiBuildItem; import io.quarkus.deployment.Capabilities; import io.quarkus.deployment.Capability; import io.quarkus.deployment.GeneratedClassGizmoAdaptor; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.annotations.ExecutionTime; import io.quarkus.deployment.annotations.Record; import io.quarkus.deployment.builditem.CombinedIndexBuildItem; import io.quarkus.deployment.builditem.GeneratedClassBuildItem; import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem; import io.quarkus.deployment.metrics.MetricsCapabilityBuildItem; import io.quarkus.gizmo.ClassCreator; import io.quarkus.gizmo.ClassOutput; import io.quarkus.gizmo.FieldDescriptor; import io.quarkus.gizmo.Gizmo; import io.quarkus.gizmo.MethodCreator; import io.quarkus.gizmo.MethodDescriptor; import io.quarkus.gizmo.ResultHandle; import io.quarkus.runtime.metrics.MetricsFactory;
13,147
configurator.addInjectionPoint(ParameterizedType.create(CDI_INSTANCE, new Type[] { ClassType.create(Langchain4jDotNames.AUDIT_SERVICE) }, null)); needsAuditServiceBean = true; } if (Langchain4jDotNames.BEAN_MODERATION_MODEL_SUPPLIER.toString().equals(moderationModelSupplierClassName)) { configurator.addInjectionPoint(ClassType.create(Langchain4jDotNames.MODERATION_MODEL)); needsModerationModelBean = true; } syntheticBeanProducer.produce(configurator.done()); } if (needsChatModelBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.CHAT_MODEL)); } if (needsChatMemoryProviderBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.CHAT_MEMORY_PROVIDER)); } if (needsRetrieverBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.RETRIEVER)); } if (needsAuditServiceBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.AUDIT_SERVICE)); } if (needsModerationModelBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.MODERATION_MODEL)); } if (!allToolNames.isEmpty()) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(allToolNames)); } } @BuildStep @Record(ExecutionTime.STATIC_INIT) public void handleAiServices(AiServicesRecorder recorder, CombinedIndexBuildItem indexBuildItem, List<DeclarativeAiServiceBuildItem> declarativeAiServiceItems, BuildProducer<GeneratedClassBuildItem> generatedClassProducer, BuildProducer<GeneratedBeanBuildItem> generatedBeanProducer, BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer, BuildProducer<AiServicesMethodBuildItem> aiServicesMethodProducer, BuildProducer<AdditionalBeanBuildItem> additionalBeanProducer, Optional<MetricsCapabilityBuildItem> metricsCapability, Capabilities capabilities) { IndexView index = indexBuildItem.getIndex(); List<AiServicesUseAnalyzer.Result.Entry> aiServicesAnalysisResults = new ArrayList<>(); for (ClassInfo classInfo : index.getKnownUsers(Langchain4jDotNames.AI_SERVICES)) { String className = classInfo.name().toString(); if (className.startsWith("io.quarkiverse.langchain4j") || className.startsWith("dev.langchain4j")) { // TODO: this can be made smarter if needed continue; } try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( className.replace('.', '/') + ".class")) { if (is == null) { return; } var cn = new ClassNode(Gizmo.ASM_API_VERSION); var cr = new ClassReader(is); cr.accept(cn, 0); for (MethodNode method : cn.methods) { aiServicesAnalysisResults.addAll(AiServicesUseAnalyzer.analyze(cn, method).entries); } } catch (IOException e) { throw new UncheckedIOException("Reading bytecode of class '" + className + "' failed", e); } catch (AnalyzerException e) { log.debug("Unable to analyze bytecode of class '" + className + "'", e); } } Map<String, Boolean> nameToUsed = aiServicesAnalysisResults.stream() .collect(Collectors.toMap(e -> e.createdClassName, e -> e.chatMemoryProviderUsed, (u1, u2) -> u1 || u2)); for (var entry : nameToUsed.entrySet()) { String className = entry.getKey(); ClassInfo classInfo = index.getClassByName(className); if (classInfo == null) { continue; } if (!classInfo.annotations(Langchain4jDotNames.MEMORY_ID).isEmpty() && !entry.getValue()) { log.warn("Class '" + className + "' is used in AiServices and while it leverages @MemoryId, a ChatMemoryProvider has not been configured. This will likely result in an exception being thrown when the service is used."); } } Set<String> detectedForCreate = new HashSet<>(nameToUsed.keySet()); addCreatedAware(index, detectedForCreate); addIfacesWithMessageAnns(index, detectedForCreate); Set<String> registeredAiServiceClassNames = declarativeAiServiceItems.stream() .map(bi -> bi.getServiceClassInfo().name().toString()).collect( Collectors.toUnmodifiableSet()); detectedForCreate.addAll(registeredAiServiceClassNames); Set<ClassInfo> ifacesForCreate = new HashSet<>(); for (String className : detectedForCreate) { ClassInfo classInfo = index.getClassByName(className); if (classInfo == null) { log.warn("'" + className + "' used for creating an AiService was not found in the Quarkus index. Attempting to create " + "an AiService using this class will fail"); continue; } if (!classInfo.isInterface()) { log.warn("'" + className + "' used for creating an AiService is not an interface. Attempting to create an AiService " + "using this class will fail"); } ifacesForCreate.add(classInfo); } var addMicrometerMetrics = metricsCapability.isPresent() && metricsCapability.get().metricsSupported(MetricsFactory.MICROMETER); if (addMicrometerMetrics) { additionalBeanProducer.produce(AdditionalBeanBuildItem.builder().addBeanClass(MetricsTimedWrapper.class).build()); additionalBeanProducer.produce(AdditionalBeanBuildItem.builder().addBeanClass(MetricsCountedWrapper.class).build()); } var addOpenTelemetrySpan = capabilities.isPresent(Capability.OPENTELEMETRY_TRACER); if (addOpenTelemetrySpan) {
package io.quarkiverse.langchain4j.deployment; @SuppressWarnings("OptionalUsedAsFieldOrParameterType") public class AiServicesProcessor { private static final Logger log = Logger.getLogger(AiServicesProcessor.class); private static final DotName V = DotName.createSimple(V.class); public static final DotName MICROMETER_TIMED = DotName.createSimple("io.micrometer.core.annotation.Timed"); public static final DotName MICROMETER_COUNTED = DotName.createSimple("io.micrometer.core.annotation.Counted"); private static final String DEFAULT_DELIMITER = "\n"; private static final Predicate<AnnotationInstance> IS_METHOD_PARAMETER_ANNOTATION = ai -> ai.target() .kind() == AnnotationTarget.Kind.METHOD_PARAMETER; private static final Function<AnnotationInstance, Integer> METHOD_PARAMETER_POSITION_FUNCTION = ai -> Integer .valueOf(ai.target() .asMethodParameter().position()); public static final MethodDescriptor OBJECT_CONSTRUCTOR = MethodDescriptor.ofConstructor(Object.class); private static final MethodDescriptor RECORDER_METHOD_CREATE_INFO = MethodDescriptor.ofMethod(AiServicesRecorder.class, "getAiServiceMethodCreateInfo", AiServiceMethodCreateInfo.class, String.class, String.class); private static final MethodDescriptor SUPPORT_IMPLEMENT = MethodDescriptor.ofMethod( AiServiceMethodImplementationSupport.class, "implement", Object.class, AiServiceMethodImplementationSupport.Input.class); private static final MethodDescriptor QUARKUS_AI_SERVICES_CONTEXT_CLOSE = MethodDescriptor.ofMethod( QuarkusAiServiceContext.class, "close", void.class); private static final MethodDescriptor QUARKUS_AI_SERVICES_CONTEXT_REMOVE_CHAT_MEMORY_IDS = MethodDescriptor.ofMethod( QuarkusAiServiceContext.class, "removeChatMemoryIds", void.class, Object[].class); public static final DotName CDI_INSTANCE = DotName.createSimple(Instance.class); private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final String METRICS_DEFAULT_NAME = "langchain4j.aiservices"; @BuildStep public void nativeSupport(CombinedIndexBuildItem indexBuildItem, List<AiServicesMethodBuildItem> aiServicesMethodBuildItems, BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer) { IndexView index = indexBuildItem.getIndex(); Collection<AnnotationInstance> instances = index.getAnnotations(Langchain4jDotNames.DESCRIPTION); Set<ClassInfo> classesUsingDescription = new HashSet<>(); for (AnnotationInstance instance : instances) { if (instance.target().kind() != AnnotationTarget.Kind.FIELD) { continue; } classesUsingDescription.add(instance.target().asField().declaringClass()); } if (!classesUsingDescription.isEmpty()) { reflectiveClassProducer.produce(ReflectiveClassBuildItem .builder(classesUsingDescription.stream().map(i -> i.name().toString()).toArray(String[]::new)).fields(true) .build()); } Set<DotName> returnTypesToRegister = new HashSet<>(); for (AiServicesMethodBuildItem aiServicesMethodBuildItem : aiServicesMethodBuildItems) { Type type = aiServicesMethodBuildItem.methodInfo.returnType(); if (type.kind() == Type.Kind.PRIMITIVE) { continue; } DotName returnTypeName = type.name(); if (returnTypeName.toString().startsWith("java.")) { continue; } returnTypesToRegister.add(returnTypeName); } if (!returnTypesToRegister.isEmpty()) { reflectiveClassProducer.produce(ReflectiveClassBuildItem .builder(returnTypesToRegister.stream().map(DotName::toString).toArray(String[]::new)) .constructors(false) .build()); } } @BuildStep public void findDeclarativeServices(CombinedIndexBuildItem indexBuildItem, BuildProducer<RequestChatModelBeanBuildItem> requestChatModelBeanProducer, BuildProducer<RequestModerationModelBeanBuildItem> requestModerationModelBeanProducer, BuildProducer<DeclarativeAiServiceBuildItem> declarativeAiServiceProducer, BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer) { IndexView index = indexBuildItem.getIndex(); boolean needChatModelBean = false; boolean needModerationModelBean = false; for (AnnotationInstance instance : index.getAnnotations(Langchain4jDotNames.REGISTER_AI_SERVICES)) { if (instance.target().kind() != AnnotationTarget.Kind.CLASS) { continue; // should never happen } ClassInfo declarativeAiServiceClassInfo = instance.target().asClass(); DotName chatLanguageModelSupplierClassDotName = null; AnnotationValue chatLanguageModelSupplierValue = instance.value("chatLanguageModelSupplier"); if (chatLanguageModelSupplierValue != null) { chatLanguageModelSupplierClassDotName = chatLanguageModelSupplierValue.asClass().name(); if (chatLanguageModelSupplierClassDotName.equals(Langchain4jDotNames.BEAN_CHAT_MODEL_SUPPLIER)) { // this is the case where the default was set, so we just ignore it chatLanguageModelSupplierClassDotName = null; } else { validateSupplierAndRegisterForReflection(chatLanguageModelSupplierClassDotName, index, reflectiveClassProducer); } } if (chatLanguageModelSupplierClassDotName == null) { needChatModelBean = true; } List<DotName> toolDotNames = Collections.emptyList(); AnnotationValue toolsInstance = instance.value("tools"); if (toolsInstance != null) { toolDotNames = Arrays.stream(toolsInstance.asClassArray()).map(Type::name) .collect(Collectors.toList()); } // the default value depends on whether tools exists or not - if they do, then we require a ChatMemoryProvider bean DotName chatMemoryProviderSupplierClassDotName = Langchain4jDotNames.BEAN_CHAT_MEMORY_PROVIDER_SUPPLIER; AnnotationValue chatMemoryProviderSupplierValue = instance.value("chatMemoryProviderSupplier"); if (chatMemoryProviderSupplierValue != null) { chatMemoryProviderSupplierClassDotName = chatMemoryProviderSupplierValue.asClass().name(); if (!chatMemoryProviderSupplierClassDotName .equals(Langchain4jDotNames.BEAN_CHAT_MEMORY_PROVIDER_SUPPLIER)) { validateSupplierAndRegisterForReflection(chatMemoryProviderSupplierClassDotName, index, reflectiveClassProducer); } } DotName retrieverSupplierClassDotName = Langchain4jDotNames.BEAN_IF_EXISTS_RETRIEVER_SUPPLIER; AnnotationValue retrieverSupplierValue = instance.value("retrieverSupplier"); if (retrieverSupplierValue != null) { retrieverSupplierClassDotName = retrieverSupplierValue.asClass().name(); if (!retrieverSupplierClassDotName.equals(Langchain4jDotNames.BEAN_RETRIEVER_SUPPLIER)) { validateSupplierAndRegisterForReflection(retrieverSupplierClassDotName, index, reflectiveClassProducer); } } DotName auditServiceSupplierClassName = Langchain4jDotNames.BEAN_IF_EXISTS_AUDIT_SERVICE_SUPPLIER; AnnotationValue auditServiceSupplierValue = instance.value("auditServiceSupplier"); if (auditServiceSupplierValue != null) { auditServiceSupplierClassName = auditServiceSupplierValue.asClass().name(); validateSupplierAndRegisterForReflection(auditServiceSupplierClassName, index, reflectiveClassProducer); } DotName moderationModelSupplierClassName = null; AnnotationValue moderationModelSupplierValue = instance.value("moderationModelSupplier"); if (moderationModelSupplierValue != null) { moderationModelSupplierClassName = moderationModelSupplierValue.asClass().name(); if (Langchain4jDotNames.NO_MODERATION_MODEL_SUPPLIER.equals(moderationModelSupplierClassName)) { moderationModelSupplierClassName = null; } else if (Langchain4jDotNames.BEAN_MODERATION_MODEL_SUPPLIER.equals(moderationModelSupplierClassName)) { needModerationModelBean = true; } else { validateSupplierAndRegisterForReflection(moderationModelSupplierClassName, index, reflectiveClassProducer); } } BuiltinScope declaredScope = BuiltinScope.from(declarativeAiServiceClassInfo); ScopeInfo cdiScope = declaredScope != null ? declaredScope.getInfo() : BuiltinScope.REQUEST.getInfo(); declarativeAiServiceProducer.produce( new DeclarativeAiServiceBuildItem( declarativeAiServiceClassInfo, chatLanguageModelSupplierClassDotName, toolDotNames, chatMemoryProviderSupplierClassDotName, retrieverSupplierClassDotName, auditServiceSupplierClassName, moderationModelSupplierClassName, cdiScope)); } if (needChatModelBean) { requestChatModelBeanProducer.produce(new RequestChatModelBeanBuildItem()); } if (needModerationModelBean) { requestModerationModelBeanProducer.produce(new RequestModerationModelBeanBuildItem()); } } private void validateSupplierAndRegisterForReflection(DotName supplierDotName, IndexView index, BuildProducer<ReflectiveClassBuildItem> producer) { ClassInfo classInfo = index.getClassByName(supplierDotName); if (classInfo == null) { log.warn("'" + supplierDotName.toString() + "' cannot be indexed"); // TODO: maybe this should be an error return; } if (!classInfo.hasNoArgsConstructor()) { throw new IllegalConfigurationException( "Class '" + supplierDotName.toString() + "' which must contain a no-args constructor."); } producer.produce(ReflectiveClassBuildItem.builder(supplierDotName.toString()).constructors(true).build()); } @BuildStep @Record(ExecutionTime.STATIC_INIT) public void handleDeclarativeServices(AiServicesRecorder recorder, List<DeclarativeAiServiceBuildItem> declarativeAiServiceItems, Optional<SelectedChatModelProviderBuildItem> selectedChatModelProvider, BuildProducer<SyntheticBeanBuildItem> syntheticBeanProducer, BuildProducer<UnremovableBeanBuildItem> unremoveableProducer) { boolean needsChatModelBean = false; boolean needsChatMemoryProviderBean = false; boolean needsRetrieverBean = false; boolean needsAuditServiceBean = false; boolean needsModerationModelBean = false; Set<DotName> allToolNames = new HashSet<>(); for (DeclarativeAiServiceBuildItem bi : declarativeAiServiceItems) { ClassInfo declarativeAiServiceClassInfo = bi.getServiceClassInfo(); String serviceClassName = declarativeAiServiceClassInfo.name().toString(); String chatLanguageModelSupplierClassName = (bi.getLanguageModelSupplierClassDotName() != null ? bi.getLanguageModelSupplierClassDotName().toString() : null); List<String> toolClassNames = bi.getToolDotNames().stream().map(DotName::toString).collect(Collectors.toList()); String chatMemoryProviderSupplierClassName = bi.getChatMemoryProviderSupplierClassDotName() != null ? bi.getChatMemoryProviderSupplierClassDotName().toString() : null; String retrieverSupplierClassName = bi.getRetrieverSupplierClassDotName() != null ? bi.getRetrieverSupplierClassDotName().toString() : null; String auditServiceClassSupplierName = bi.getAuditServiceClassSupplierDotName() != null ? bi.getAuditServiceClassSupplierDotName().toString() : null; String moderationModelSupplierClassName = (bi.getModerationModelSupplierDotName() != null ? bi.getModerationModelSupplierDotName().toString() : null); SyntheticBeanBuildItem.ExtendedBeanConfigurator configurator = SyntheticBeanBuildItem .configure(QuarkusAiServiceContext.class) .createWith(recorder.createDeclarativeAiService( new DeclarativeAiServiceCreateInfo(serviceClassName, chatLanguageModelSupplierClassName, toolClassNames, chatMemoryProviderSupplierClassName, retrieverSupplierClassName, auditServiceClassSupplierName, moderationModelSupplierClassName))) .setRuntimeInit() .addQualifier() .annotation(Langchain4jDotNames.QUARKUS_AI_SERVICE_CONTEXT_QUALIFIER).addValue("value", serviceClassName) .done() .scope(Dependent.class); if ((chatLanguageModelSupplierClassName == null) && selectedChatModelProvider.isPresent()) { // TODO: is second condition needed? configurator.addInjectionPoint(ClassType.create(Langchain4jDotNames.CHAT_MODEL)); needsChatModelBean = true; } if (!toolClassNames.isEmpty()) { for (String toolClassName : toolClassNames) { DotName dotName = DotName.createSimple(toolClassName); configurator.addInjectionPoint(ClassType.create(dotName)); allToolNames.add(dotName); } } if (Langchain4jDotNames.BEAN_CHAT_MEMORY_PROVIDER_SUPPLIER.toString().equals(chatMemoryProviderSupplierClassName)) { configurator.addInjectionPoint(ClassType.create(Langchain4jDotNames.CHAT_MEMORY_PROVIDER)); needsChatMemoryProviderBean = true; } if (Langchain4jDotNames.BEAN_RETRIEVER_SUPPLIER.toString().equals(retrieverSupplierClassName)) { configurator.addInjectionPoint(ParameterizedType.create(Langchain4jDotNames.RETRIEVER, new Type[] { ClassType.create(Langchain4jDotNames.TEXT_SEGMENT) }, null)); needsRetrieverBean = true; } else if (Langchain4jDotNames.BEAN_IF_EXISTS_RETRIEVER_SUPPLIER.toString() .equals(retrieverSupplierClassName)) { configurator.addInjectionPoint(ParameterizedType.create(CDI_INSTANCE, new Type[] { ParameterizedType.create(Langchain4jDotNames.RETRIEVER, new Type[] { ClassType.create(Langchain4jDotNames.TEXT_SEGMENT) }, null) }, null)); needsRetrieverBean = true; } if (Langchain4jDotNames.BEAN_IF_EXISTS_AUDIT_SERVICE_SUPPLIER.toString().equals(auditServiceClassSupplierName)) { configurator.addInjectionPoint(ParameterizedType.create(CDI_INSTANCE, new Type[] { ClassType.create(Langchain4jDotNames.AUDIT_SERVICE) }, null)); needsAuditServiceBean = true; } if (Langchain4jDotNames.BEAN_MODERATION_MODEL_SUPPLIER.toString().equals(moderationModelSupplierClassName)) { configurator.addInjectionPoint(ClassType.create(Langchain4jDotNames.MODERATION_MODEL)); needsModerationModelBean = true; } syntheticBeanProducer.produce(configurator.done()); } if (needsChatModelBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.CHAT_MODEL)); } if (needsChatMemoryProviderBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.CHAT_MEMORY_PROVIDER)); } if (needsRetrieverBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.RETRIEVER)); } if (needsAuditServiceBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.AUDIT_SERVICE)); } if (needsModerationModelBean) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(Langchain4jDotNames.MODERATION_MODEL)); } if (!allToolNames.isEmpty()) { unremoveableProducer.produce(UnremovableBeanBuildItem.beanTypes(allToolNames)); } } @BuildStep @Record(ExecutionTime.STATIC_INIT) public void handleAiServices(AiServicesRecorder recorder, CombinedIndexBuildItem indexBuildItem, List<DeclarativeAiServiceBuildItem> declarativeAiServiceItems, BuildProducer<GeneratedClassBuildItem> generatedClassProducer, BuildProducer<GeneratedBeanBuildItem> generatedBeanProducer, BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer, BuildProducer<AiServicesMethodBuildItem> aiServicesMethodProducer, BuildProducer<AdditionalBeanBuildItem> additionalBeanProducer, Optional<MetricsCapabilityBuildItem> metricsCapability, Capabilities capabilities) { IndexView index = indexBuildItem.getIndex(); List<AiServicesUseAnalyzer.Result.Entry> aiServicesAnalysisResults = new ArrayList<>(); for (ClassInfo classInfo : index.getKnownUsers(Langchain4jDotNames.AI_SERVICES)) { String className = classInfo.name().toString(); if (className.startsWith("io.quarkiverse.langchain4j") || className.startsWith("dev.langchain4j")) { // TODO: this can be made smarter if needed continue; } try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( className.replace('.', '/') + ".class")) { if (is == null) { return; } var cn = new ClassNode(Gizmo.ASM_API_VERSION); var cr = new ClassReader(is); cr.accept(cn, 0); for (MethodNode method : cn.methods) { aiServicesAnalysisResults.addAll(AiServicesUseAnalyzer.analyze(cn, method).entries); } } catch (IOException e) { throw new UncheckedIOException("Reading bytecode of class '" + className + "' failed", e); } catch (AnalyzerException e) { log.debug("Unable to analyze bytecode of class '" + className + "'", e); } } Map<String, Boolean> nameToUsed = aiServicesAnalysisResults.stream() .collect(Collectors.toMap(e -> e.createdClassName, e -> e.chatMemoryProviderUsed, (u1, u2) -> u1 || u2)); for (var entry : nameToUsed.entrySet()) { String className = entry.getKey(); ClassInfo classInfo = index.getClassByName(className); if (classInfo == null) { continue; } if (!classInfo.annotations(Langchain4jDotNames.MEMORY_ID).isEmpty() && !entry.getValue()) { log.warn("Class '" + className + "' is used in AiServices and while it leverages @MemoryId, a ChatMemoryProvider has not been configured. This will likely result in an exception being thrown when the service is used."); } } Set<String> detectedForCreate = new HashSet<>(nameToUsed.keySet()); addCreatedAware(index, detectedForCreate); addIfacesWithMessageAnns(index, detectedForCreate); Set<String> registeredAiServiceClassNames = declarativeAiServiceItems.stream() .map(bi -> bi.getServiceClassInfo().name().toString()).collect( Collectors.toUnmodifiableSet()); detectedForCreate.addAll(registeredAiServiceClassNames); Set<ClassInfo> ifacesForCreate = new HashSet<>(); for (String className : detectedForCreate) { ClassInfo classInfo = index.getClassByName(className); if (classInfo == null) { log.warn("'" + className + "' used for creating an AiService was not found in the Quarkus index. Attempting to create " + "an AiService using this class will fail"); continue; } if (!classInfo.isInterface()) { log.warn("'" + className + "' used for creating an AiService is not an interface. Attempting to create an AiService " + "using this class will fail"); } ifacesForCreate.add(classInfo); } var addMicrometerMetrics = metricsCapability.isPresent() && metricsCapability.get().metricsSupported(MetricsFactory.MICROMETER); if (addMicrometerMetrics) { additionalBeanProducer.produce(AdditionalBeanBuildItem.builder().addBeanClass(MetricsTimedWrapper.class).build()); additionalBeanProducer.produce(AdditionalBeanBuildItem.builder().addBeanClass(MetricsCountedWrapper.class).build()); } var addOpenTelemetrySpan = capabilities.isPresent(Capability.OPENTELEMETRY_TRACER); if (addOpenTelemetrySpan) {
additionalBeanProducer.produce(AdditionalBeanBuildItem.builder().addBeanClass(SpanWrapper.class).build());
11
2023-11-13 09:10:27+00:00
16k
qiusunshine/xiu
clinglibrary/src/main/java/com/qingfeng/clinglibrary/service/manager/ClingManager.java
[ { "identifier": "ClingControlPoint", "path": "clinglibrary/src/main/java/com/qingfeng/clinglibrary/entity/ClingControlPoint.java", "snippet": "public class ClingControlPoint implements IControlPoint<ControlPoint> {\n\n private static ClingControlPoint INSTANCE = null;\n private ControlPoint mContr...
import android.content.Context; import androidx.annotation.Nullable; import com.qingfeng.clinglibrary.entity.ClingControlPoint; import com.qingfeng.clinglibrary.entity.ClingDevice; import com.qingfeng.clinglibrary.entity.IControlPoint; import com.qingfeng.clinglibrary.entity.IDevice; import com.qingfeng.clinglibrary.service.ClingUpnpService; import com.qingfeng.clinglibrary.util.ListUtils; import com.qingfeng.clinglibrary.util.Utils; import org.fourthline.cling.model.meta.Device; import org.fourthline.cling.model.types.DeviceType; import org.fourthline.cling.model.types.ServiceType; import org.fourthline.cling.model.types.UDADeviceType; import org.fourthline.cling.model.types.UDAServiceType; import org.fourthline.cling.registry.Registry; import java.util.ArrayList; import java.util.Collection;
12,410
package com.qingfeng.clinglibrary.service.manager; /** * 说明:所有对服务的操作都通过该类代理执行 * 作者:zhouzhan * 日期:17/6/27 18:12 */ public class ClingManager implements IClingManager { // public static final ServiceType CONTENT_DIRECTORY_SERVICE = new UDAServiceType("ContentDirectory"); public static final ServiceType AV_TRANSPORT_SERVICE = new UDAServiceType("AVTransport"); /** * 控制服务 */ public static final ServiceType RENDERING_CONTROL_SERVICE = new UDAServiceType("RenderingControl"); public static final DeviceType DMR_DEVICE_TYPE = new UDADeviceType("MediaRenderer"); private static ClingManager INSTANCE = null; private ClingUpnpService mUpnpService; public IDeviceManager getDeviceManager() { return mDeviceManager; } private IDeviceManager mDeviceManager; // private SystemService mSystemService; private ClingManager() { } public static ClingManager getInstance() { if (Utils.isNull(INSTANCE)) { INSTANCE = new ClingManager(); } return INSTANCE; } @Override public void searchDevices() { if (!Utils.isNull(mUpnpService)) { mUpnpService.getControlPoint().search(); } } @Override @Nullable public Collection<ClingDevice> getDmrDevices() { if (Utils.isNull(mUpnpService)) { return null; }
package com.qingfeng.clinglibrary.service.manager; /** * 说明:所有对服务的操作都通过该类代理执行 * 作者:zhouzhan * 日期:17/6/27 18:12 */ public class ClingManager implements IClingManager { // public static final ServiceType CONTENT_DIRECTORY_SERVICE = new UDAServiceType("ContentDirectory"); public static final ServiceType AV_TRANSPORT_SERVICE = new UDAServiceType("AVTransport"); /** * 控制服务 */ public static final ServiceType RENDERING_CONTROL_SERVICE = new UDAServiceType("RenderingControl"); public static final DeviceType DMR_DEVICE_TYPE = new UDADeviceType("MediaRenderer"); private static ClingManager INSTANCE = null; private ClingUpnpService mUpnpService; public IDeviceManager getDeviceManager() { return mDeviceManager; } private IDeviceManager mDeviceManager; // private SystemService mSystemService; private ClingManager() { } public static ClingManager getInstance() { if (Utils.isNull(INSTANCE)) { INSTANCE = new ClingManager(); } return INSTANCE; } @Override public void searchDevices() { if (!Utils.isNull(mUpnpService)) { mUpnpService.getControlPoint().search(); } } @Override @Nullable public Collection<ClingDevice> getDmrDevices() { if (Utils.isNull(mUpnpService)) { return null; }
Collection<Device> devices = mUpnpService.getRegistry().getDevices(DMR_DEVICE_TYPE);
7
2023-11-10 14:28:40+00:00
16k
xIdentified/Devotions
src/main/java/me/xidentified/devotions/commandexecutors/DeityCommand.java
[ { "identifier": "Deity", "path": "src/main/java/me/xidentified/devotions/Deity.java", "snippet": "public class Deity {\n private final Devotions plugin;\n // Getter methods below\n @Getter public final String name;\n @Getter private final String lore;\n @Getter private final String alignm...
import de.cubbossa.tinytranslations.GlobalMessages; import me.xidentified.devotions.Deity; import me.xidentified.devotions.Devotions; import me.xidentified.devotions.managers.FavorManager; import me.xidentified.devotions.util.Messages; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.UUID;
12,907
package me.xidentified.devotions.commandexecutors; public class DeityCommand implements CommandExecutor, TabCompleter { private final Devotions plugin; public DeityCommand(Devotions plugin) { this.plugin = plugin; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (!(sender instanceof Player player)) { Devotions.getInstance().sendMessage(sender, GlobalMessages.CMD_PLAYER_ONLY); return true; } if (args.length < 1) { plugin.sendMessage(player, Messages.DEITY_CMD_USAGE); return true; } String subCommand = args[0].toLowerCase(); switch (subCommand) { case "list" -> { return handleList(player); } case "select" -> { return handleSelect(player, args); } case "info" -> { return handleInfo(player, args); } default -> { plugin.sendMessage(player,Messages.DEITY_CMD_USAGE); return true; } } } private boolean handleSelect(Player player, String[] args) { if (args.length < 2) { plugin.sendMessage(player, Messages.DEITY_CMD_SPECIFY_DEITY); return true; } String deityName = args[1];
package me.xidentified.devotions.commandexecutors; public class DeityCommand implements CommandExecutor, TabCompleter { private final Devotions plugin; public DeityCommand(Devotions plugin) { this.plugin = plugin; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { if (!(sender instanceof Player player)) { Devotions.getInstance().sendMessage(sender, GlobalMessages.CMD_PLAYER_ONLY); return true; } if (args.length < 1) { plugin.sendMessage(player, Messages.DEITY_CMD_USAGE); return true; } String subCommand = args[0].toLowerCase(); switch (subCommand) { case "list" -> { return handleList(player); } case "select" -> { return handleSelect(player, args); } case "info" -> { return handleInfo(player, args); } default -> { plugin.sendMessage(player,Messages.DEITY_CMD_USAGE); return true; } } } private boolean handleSelect(Player player, String[] args) { if (args.length < 2) { plugin.sendMessage(player, Messages.DEITY_CMD_SPECIFY_DEITY); return true; } String deityName = args[1];
Deity selectedDeity = plugin.getDevotionManager().getDeityByName(deityName);
0
2023-11-10 07:03:24+00:00
16k
SplitfireUptown/datalinkx
datalinkx-server/src/main/java/com/datalinkx/dataserver/service/impl/JobService.java
[ { "identifier": "JOB_STATUS_STOP", "path": "datalinkx-common/src/main/java/com/datalinkx/common/constants/MetaConstants.java", "snippet": "public static final int JOB_STATUS_STOP = 5;" }, { "identifier": "JOB_STATUS_SYNC", "path": "datalinkx-common/src/main/java/com/datalinkx/common/constant...
import static com.datalinkx.common.constants.MetaConstants.JobStatus.JOB_STATUS_STOP; import static com.datalinkx.common.constants.MetaConstants.JobStatus.JOB_STATUS_SYNC; import static com.datalinkx.common.utils.IdUtils.genKey; import static com.datalinkx.common.utils.JsonUtils.toJson; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.annotation.Resource; import com.datalinkx.common.constants.MessageHubConstants; import com.datalinkx.common.constants.MetaConstants; import com.datalinkx.driver.dsdriver.DsDriverFactory; import com.datalinkx.driver.dsdriver.IDsReader; import com.datalinkx.driver.dsdriver.base.model.TableField; import com.datalinkx.driver.model.DataTransJobDetail; import com.datalinkx.common.result.StatusCode; import com.datalinkx.common.utils.JsonUtils; import com.datalinkx.dataserver.bean.domain.DsBean; import com.datalinkx.dataserver.bean.domain.DsTbBean; import com.datalinkx.dataserver.bean.domain.JobBean; import com.datalinkx.dataserver.bean.domain.JobLogBean; import com.datalinkx.dataserver.bean.dto.JobDto; import com.datalinkx.dataserver.bean.vo.JobVo; import com.datalinkx.dataserver.bean.vo.PageVo; import com.datalinkx.dataserver.client.xxljob.JobClientApi; import com.datalinkx.dataserver.client.xxljob.request.DataTransJobParam; import com.datalinkx.dataserver.controller.form.JobForm; import com.datalinkx.dataserver.controller.form.JobStateForm; import com.datalinkx.common.exception.DatalinkXServerException; import com.datalinkx.dataserver.repository.DsRepository; import com.datalinkx.dataserver.repository.DsTbRepository; import com.datalinkx.dataserver.repository.JobLogRepository; import com.datalinkx.dataserver.repository.JobRepository; import com.datalinkx.dataserver.service.DtsJobService; import com.datalinkx.messagehub.bean.form.ProducerAdapterForm; import com.datalinkx.messagehub.service.MessageHubService; import lombok.SneakyThrows; import lombok.extern.log4j.Log4j2; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.ObjectUtils;
11,631
package com.datalinkx.dataserver.service.impl; @Component @Service @Log4j2 public class JobService implements DtsJobService { private static final int FAILED = 3; private static final int SUCCESS = 2; @Autowired private JobRepository jobRepository; @Autowired DsService dsService; @Autowired DsRepository dsRepository; @Autowired DsTbRepository dsTbRepository; @Autowired JobLogRepository jobLogRepository; @Autowired JobClientApi jobClientApi; @Resource(name = "messageHubServiceImpl") MessageHubService messageHubService; @Transactional(rollbackFor = Exception.class) public String jobCreate(JobForm.JobCreateForm form) { this.validJobForm(form); String jobId = genKey("job"); JobBean jobBean = new JobBean(); jobBean.setJobId(jobId); jobBean.setReaderDsId(form.getFromDsId()); jobBean.setWriterDsId(form.getToDsId()); jobBean.setConfig(toJson(form.getFieldMappings())); jobBean.setFromTbId(getXtbId(form.getFromTbName(), form.getFromDsId())); jobBean.setToTbId(getXtbId(form.getToTbName(), form.getFromDsId()));
package com.datalinkx.dataserver.service.impl; @Component @Service @Log4j2 public class JobService implements DtsJobService { private static final int FAILED = 3; private static final int SUCCESS = 2; @Autowired private JobRepository jobRepository; @Autowired DsService dsService; @Autowired DsRepository dsRepository; @Autowired DsTbRepository dsTbRepository; @Autowired JobLogRepository jobLogRepository; @Autowired JobClientApi jobClientApi; @Resource(name = "messageHubServiceImpl") MessageHubService messageHubService; @Transactional(rollbackFor = Exception.class) public String jobCreate(JobForm.JobCreateForm form) { this.validJobForm(form); String jobId = genKey("job"); JobBean jobBean = new JobBean(); jobBean.setJobId(jobId); jobBean.setReaderDsId(form.getFromDsId()); jobBean.setWriterDsId(form.getToDsId()); jobBean.setConfig(toJson(form.getFieldMappings())); jobBean.setFromTbId(getXtbId(form.getFromTbName(), form.getFromDsId())); jobBean.setToTbId(getXtbId(form.getToTbName(), form.getFromDsId()));
jobBean.setStatus(MetaConstants.JobStatus.JOB_TABLE_CREATE);
5
2023-11-16 02:22:52+00:00
16k
exadel-inc/etoolbox-anydiff
core/src/test/java/com/exadel/etoolbox/anydiff/AllTests.java
[ { "identifier": "DiffBlockXPathTest", "path": "core/src/test/java/com/exadel/etoolbox/anydiff/comparison/DiffBlockXPathTest.java", "snippet": "public class DiffBlockXPathTest {\n\n @Test\n public void shouldReportHtmlPath() throws IOException {\n try (\n InputStream leftInput...
import com.exadel.etoolbox.anydiff.comparison.DiffBlockXPathTest; import com.exadel.etoolbox.anydiff.comparison.DiffCountTest; import com.exadel.etoolbox.anydiff.comparison.DiffTaskTest; import com.exadel.etoolbox.anydiff.comparison.DiffTest; import com.exadel.etoolbox.anydiff.comparison.FragmentTest; import com.exadel.etoolbox.anydiff.comparison.MarkedStringTest; import com.exadel.etoolbox.anydiff.comparison.SpacesHandlingTest; import com.exadel.etoolbox.anydiff.comparison.preprocessor.PreprocessorsTest; import com.exadel.etoolbox.anydiff.runner.DiffRunnerTest; import com.exadel.etoolbox.anydiff.runner.FilterHelperTest; import com.exadel.etoolbox.anydiff.runner.FiltersTest; import org.junit.runner.RunWith; import org.junit.runners.Suite;
14,069
/* * 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; @RunWith(Suite.class) @Suite.SuiteClasses({ DiffTest.class,
/* * 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; @RunWith(Suite.class) @Suite.SuiteClasses({ DiffTest.class,
DiffRunnerTest.class,
8
2023-11-16 14:29:45+00:00
16k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/events/RenderEvents.java
[ { "identifier": "ClientProxy", "path": "src/main/java/sheridan/gunscraft/ClientProxy.java", "snippet": "public class ClientProxy extends CommonProxy{\n\n public static HashMap<Item, TransformData> transformDataMap = new HashMap<>();\n public static HashMap<Item, IGunModel> gunModelMap = new HashMa...
import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.client.MainWindow; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import sheridan.gunscraft.ClientProxy; import sheridan.gunscraft.animation.recoilAnimation.RecoilCameraHandler; import sheridan.gunscraft.items.guns.GenericGun; import sheridan.gunscraft.items.guns.IGenericGun; import sheridan.gunscraft.render.crosshair.BasicCrossHairRenderer;
12,436
package sheridan.gunscraft.events; @Mod.EventBusSubscriber public class RenderEvents { public static float delta = 0; public static float particularTick = 0; private static long lastTickTime = -1; private static final BasicCrossHairRenderer renderer = new BasicCrossHairRenderer(); public static RecoilCameraHandler cameraHandler = new RecoilCameraHandler(); @SubscribeEvent public static void onRenderTick(TickEvent.RenderTickEvent event) { if (event.phase == TickEvent.Phase.END) { if (lastTickTime == -1) { lastTickTime = System.currentTimeMillis(); return; } particularTick = event.renderTickTime; int dis = (int) (System.currentTimeMillis() - lastTickTime); lastTickTime = System.currentTimeMillis(); delta = (float) dis * 0.001f; if (!cameraHandler.inModify.get()) { cameraHandler.handle(delta); } } } @SubscribeEvent public static void renderCrossHair(RenderGameOverlayEvent event) { if (event.isCancelable() && event.getType() == RenderGameOverlayEvent.ElementType.CROSSHAIRS) { if (ClientProxy.mainHandStatus.holdingGun.get() || ClientProxy.offHandStatus.holdingGun.get()) { event.setCanceled(true); if (ClientProxy.mainHandStatus.aiming) { return; } MainWindow window = Minecraft.getInstance().getMainWindow(); renderer.render(event.getMatrixStack(), ClientProxy.bulletSpread, window, BasicCrossHairRenderer.WHITE); } } } @SubscribeEvent public static void renderGunInfo(RenderGameOverlayEvent event) { if (event.isCancelable() && event.getType() == RenderGameOverlayEvent.ElementType.EXPERIENCE) { FontRenderer renderer = Minecraft.getInstance().fontRenderer; MatrixStack matrixStackIn = event.getMatrixStack(); Minecraft minecraft = Minecraft.getInstance(); MainWindow window = Minecraft.getInstance().getMainWindow(); PlayerEntity player = minecraft.player; if (player != null) { ItemStack stackMain = player.getHeldItemMainhand(); ItemStack stackOff = player.getHeldItemOffhand(); int color = 0xFFFAFA0F;
package sheridan.gunscraft.events; @Mod.EventBusSubscriber public class RenderEvents { public static float delta = 0; public static float particularTick = 0; private static long lastTickTime = -1; private static final BasicCrossHairRenderer renderer = new BasicCrossHairRenderer(); public static RecoilCameraHandler cameraHandler = new RecoilCameraHandler(); @SubscribeEvent public static void onRenderTick(TickEvent.RenderTickEvent event) { if (event.phase == TickEvent.Phase.END) { if (lastTickTime == -1) { lastTickTime = System.currentTimeMillis(); return; } particularTick = event.renderTickTime; int dis = (int) (System.currentTimeMillis() - lastTickTime); lastTickTime = System.currentTimeMillis(); delta = (float) dis * 0.001f; if (!cameraHandler.inModify.get()) { cameraHandler.handle(delta); } } } @SubscribeEvent public static void renderCrossHair(RenderGameOverlayEvent event) { if (event.isCancelable() && event.getType() == RenderGameOverlayEvent.ElementType.CROSSHAIRS) { if (ClientProxy.mainHandStatus.holdingGun.get() || ClientProxy.offHandStatus.holdingGun.get()) { event.setCanceled(true); if (ClientProxy.mainHandStatus.aiming) { return; } MainWindow window = Minecraft.getInstance().getMainWindow(); renderer.render(event.getMatrixStack(), ClientProxy.bulletSpread, window, BasicCrossHairRenderer.WHITE); } } } @SubscribeEvent public static void renderGunInfo(RenderGameOverlayEvent event) { if (event.isCancelable() && event.getType() == RenderGameOverlayEvent.ElementType.EXPERIENCE) { FontRenderer renderer = Minecraft.getInstance().fontRenderer; MatrixStack matrixStackIn = event.getMatrixStack(); Minecraft minecraft = Minecraft.getInstance(); MainWindow window = Minecraft.getInstance().getMainWindow(); PlayerEntity player = minecraft.player; if (player != null) { ItemStack stackMain = player.getHeldItemMainhand(); ItemStack stackOff = player.getHeldItemOffhand(); int color = 0xFFFAFA0F;
if (stackMain.getItem() instanceof IGenericGun) {
3
2023-11-14 14:00:55+00:00
16k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/fragments/APKsFragment.java
[ { "identifier": "APKInstallerActivity", "path": "app/src/main/java/com/threethan/questpatcher/activities/APKInstallerActivity.java", "snippet": "public class APKInstallerActivity extends AppCompatActivity {\n\n private AppCompatImageButton mExploreIcon;\n private AppCompatImageView mAppIcon;\n ...
import android.app.Activity; import android.content.ClipData; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatImageButton; import androidx.appcompat.widget.LinearLayoutCompat; import androidx.appcompat.widget.PopupMenu; import androidx.documentfile.provider.DocumentFile; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.threethan.questpatcher.R; import com.threethan.questpatcher.activities.APKInstallerActivity; import com.threethan.questpatcher.activities.InstallerFilePickerActivity; import com.threethan.questpatcher.adapters.APKsAdapter; import com.threethan.questpatcher.utils.APKData; import com.threethan.questpatcher.utils.APKEditorUtils; import com.threethan.questpatcher.utils.APKExplorer; import com.threethan.questpatcher.utils.AppData; import com.threethan.questpatcher.utils.Common; import com.threethan.questpatcher.utils.tasks.ExploreAPK; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.tabs.TabLayout; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Objects; import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils; import in.sunilpaulmathew.sCommon.CommonUtils.sExecutor; import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils;
14,136
package com.threethan.questpatcher.fragments; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 04, 2021 */ public class APKsFragment extends Fragment { private LinearLayoutCompat mProgress; private RecyclerView mRecyclerView;
package com.threethan.questpatcher.fragments; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 04, 2021 */ public class APKsFragment extends Fragment { private LinearLayoutCompat mProgress; private RecyclerView mRecyclerView;
private APKsAdapter mRecycleViewAdapter;
2
2023-11-18 15:13:30+00:00
16k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/system/service/impl/UserServiceImpl.java
[ { "identifier": "FileProperties", "path": "dimple-common/src/main/java/com/dimple/config/FileProperties.java", "snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"file\")\npublic class FileProperties {\n\n /**\n * 文件大小限制\n */\n private Long maxSize;\n\n /**\n * 头像...
import com.dimple.config.FileProperties; import com.dimple.exception.EntityExistException; import com.dimple.exception.EntityNotFoundException; import com.dimple.modules.system.domain.User; import com.dimple.modules.system.repository.UserRepository; import com.dimple.modules.system.service.UserService; import com.dimple.modules.system.service.dto.JobSmallDto; 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.modules.system.service.mapstruct.UserMapper; import com.dimple.utils.FileUtil; import com.dimple.utils.PageUtil; import com.dimple.utils.QueryHelp; import com.dimple.utils.RedisUtils; import com.dimple.utils.SecurityUtils; import com.dimple.utils.StringUtils; import com.dimple.utils.ValidationUtil; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors;
13,713
package com.dimple.modules.system.service.impl; /** * @className: UserServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "user") public class UserServiceImpl implements UserService { private final UserRepository userRepository;
package com.dimple.modules.system.service.impl; /** * @className: UserServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "user") public class UserServiceImpl implements UserService { private final UserRepository userRepository;
private final UserMapper userMapper;
10
2023-11-10 03:30:36+00:00
16k
LazyCoder0101/LazyCoder
ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/component/codeintput/inputmeta/pane/format/code/AdditionalDeafaultFormatCodePane.java
[ { "identifier": "BaseModel", "path": "database/src/main/java/com/lazycoder/database/model/BaseModel.java", "snippet": "public interface BaseModel {\n\n\tpublic static final int TRUE_ = 1;\n\n\tpublic static final int FALSE_ = 0;\n\n}" }, { "identifier": "GeneralFileFormat", "path": "database...
import com.lazycoder.database.model.BaseModel; import com.lazycoder.database.model.GeneralFileFormat; import com.lazycoder.uidatasourceedit.AbstractFormatCodeInputPane; import com.lazycoder.uidatasourceedit.FormatEditPaneHolder; import com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.condition.CodeCondition; import com.lazycoder.uidatasourceedit.component.codeintput.intputscutcheon.markscutcheon.AdditionalSetMarkScutcheon; import com.lazycoder.uidatasourceedit.formatedit.additional.settype.AdditionalSetCodeEditPane; import com.lazycoder.uiutils.htmlstyte.HTMLText; import com.lazycoder.uiutils.htmlstyte.HtmlPar; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JMenuItem; import javax.swing.text.BadLocationException; import lombok.Getter; import lombok.Setter;
12,620
package com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.format.code; //import com.lazycoder.uiutils.utils.StyteString; public class AdditionalDeafaultFormatCodePane extends AbstractFormatCodeInputPane implements BaseModel { /** * */ private static final long serialVersionUID = 2216185688720500317L; /** * 是否写入了默认文件名 */ @Getter @Setter private int defaultFilenameSetting = FALSE_; /** * 可选模板业务方法的标识编号 */ @Getter private int additionalSerialNumber = 0; private JMenuItem additionalSetMenuItem, setDeafaultCodeFileNameMenuItem; public AdditionalDeafaultFormatCodePane(int sort, int additionalSerialNumber) { super(sort); this.additionalSerialNumber = additionalSerialNumber; CodeCondition codeCondition = new CodeCondition(false, true); this.menuInit(codeCondition); } @Override protected void setMenuItemText() { // TODO Auto-generated method stub super.setMenuItemText(); HTMLText htmlText = new HTMLText(); HtmlPar htmlPar = new HtmlPar(); htmlPar.addText("在此填写", false); htmlPar.addColorText("可选模板设置", HtmlPar.RED, false); htmlPar.addText("代码", false); htmlText.addPar(htmlPar); additionalSetMenuItem = new JMenuItem(htmlText.getHtmlContent()); } @Override public void menuInit(CodeCondition codeCondition) { super.menuInit(codeCondition); setDeafaultCodeFileNameMenuItem = new JMenuItem("设置默认文件名"); setDeafaultCodeFileNameMenuItem.setForeground(Color.BLUE); setDeafaultCodeFileNameMenuItem.addActionListener(menuItemActionListener); theMenu.add(setDeafaultCodeFileNameMenuItem, 3); addMarkmenu.add(additionalSetMenuItem); additionalSetMenuItem.addActionListener(menuItemActionListener); additionalSetMenuItem.addMouseListener(additionalSetMarkMenuItemMouseAdapter); } private ActionListener menuItemActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getSource() == additionalSetMenuItem) {
package com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.format.code; //import com.lazycoder.uiutils.utils.StyteString; public class AdditionalDeafaultFormatCodePane extends AbstractFormatCodeInputPane implements BaseModel { /** * */ private static final long serialVersionUID = 2216185688720500317L; /** * 是否写入了默认文件名 */ @Getter @Setter private int defaultFilenameSetting = FALSE_; /** * 可选模板业务方法的标识编号 */ @Getter private int additionalSerialNumber = 0; private JMenuItem additionalSetMenuItem, setDeafaultCodeFileNameMenuItem; public AdditionalDeafaultFormatCodePane(int sort, int additionalSerialNumber) { super(sort); this.additionalSerialNumber = additionalSerialNumber; CodeCondition codeCondition = new CodeCondition(false, true); this.menuInit(codeCondition); } @Override protected void setMenuItemText() { // TODO Auto-generated method stub super.setMenuItemText(); HTMLText htmlText = new HTMLText(); HtmlPar htmlPar = new HtmlPar(); htmlPar.addText("在此填写", false); htmlPar.addColorText("可选模板设置", HtmlPar.RED, false); htmlPar.addText("代码", false); htmlText.addPar(htmlPar); additionalSetMenuItem = new JMenuItem(htmlText.getHtmlContent()); } @Override public void menuInit(CodeCondition codeCondition) { super.menuInit(codeCondition); setDeafaultCodeFileNameMenuItem = new JMenuItem("设置默认文件名"); setDeafaultCodeFileNameMenuItem.setForeground(Color.BLUE); setDeafaultCodeFileNameMenuItem.addActionListener(menuItemActionListener); theMenu.add(setDeafaultCodeFileNameMenuItem, 3); addMarkmenu.add(additionalSetMenuItem); additionalSetMenuItem.addActionListener(menuItemActionListener); additionalSetMenuItem.addMouseListener(additionalSetMarkMenuItemMouseAdapter); } private ActionListener menuItemActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getSource() == additionalSetMenuItem) {
AdditionalSetMarkScutcheon scutcheon = new AdditionalSetMarkScutcheon();
5
2023-11-16 11:55:06+00:00
16k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/MainFragment.java
[ { "identifier": "PropertyMap", "path": "app/src/main/java/kr/or/kashi/hde/base/PropertyMap.java", "snippet": "public abstract class PropertyMap {\n /** Get the value of a property */\n public <E> E get(String name, Class<E> clazz) {\n return (E) get(name).getValue();\n }\n\n /** Put n...
import android.annotation.SuppressLint; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.Checkable; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.ToggleButton; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.RecyclerView; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import kr.or.kashi.hde.base.PropertyMap; import kr.or.kashi.hde.test.DeviceTestCallback; import kr.or.kashi.hde.util.DebugLog; import kr.or.kashi.hde.util.LocalPreferences; import kr.or.kashi.hde.util.LocalPreferences.Pref; import kr.or.kashi.hde.util.Utils; import kr.or.kashi.hde.widget.CheckableListAdapter; import kr.or.kashi.hde.widget.CustomLayoutManager; import kr.or.kashi.hde.widget.DebugLogView; import kr.or.kashi.hde.widget.DeviceInfoView; import kr.or.kashi.hde.widget.DeviceListAdapter; import kr.or.kashi.hde.widget.DeviceTestPartView; import kr.or.kashi.hde.widget.HomeDeviceView; import kr.or.kashi.hde.widget.NullRecyclerViewAdapter;
11,057
mDebugLogView.clear(); mAutoScrollToggle.setChecked(true); mDebugLogView.setAutoScroll(true); }); mEventLogCheck = (CheckBox) v.findViewById(R.id.event_log_check); mEventLogCheck.setChecked(LocalPreferences.getBoolean(Pref.DEBUG_LOG_EVENT_ENABLED, true)); mEventLogCheck.setOnClickListener(view -> updateLogFilter()); mTxRxLogCheck = (CheckBox) v.findViewById(R.id.txrx_log_check); mTxRxLogCheck.setChecked(LocalPreferences.getBoolean(Pref.DEBUG_LOG_TXRX_ENABLED, true)); mTxRxLogCheck.setOnClickListener(view -> updateLogFilter()); mAutoScrollToggle = (ToggleButton) v.findViewById(R.id.auto_scroll_toggle);; mAutoScrollToggle.setOnClickListener(view -> mDebugLogView.setAutoScroll(((Checkable)view).isChecked())); mDebugLogView = (DebugLogView) v.findViewById(R.id.debug_log_view); DebugLog.setLogger(mDebugLogView); mDebugLogView.setOnRawTouchListener((view, e) -> { if (e.getAction() == MotionEvent.ACTION_DOWN) { mAutoScrollToggle.setChecked(false); mDebugLogView.setAutoScroll(false); } return false; }); ((Button)v.findViewById(R.id.select_all_button)).setOnClickListener(view -> selectAllTypes()); ((Button)v.findViewById(R.id.deselect_all_button)).setOnClickListener(view -> deselectAllTypes()); ((Button)v.findViewById(R.id.reset_range_button)).setOnClickListener(view -> resetRanges()); mDiscoveryToggle = (ToggleButton) v.findViewById(R.id.discovery_toggle); mDiscoveryToggle.setEnabled(!mNetwork.isSlaveMode()); mDiscoveryToggle.setOnClickListener(view -> setDiscoveryOn(((Checkable)view).isChecked())); final CheckableListAdapter<String> deviceTypeListAdapter = new CheckableListAdapter<>( mContext, new ArrayList(mDeviceToKsIdMap.keySet()), mSelectedDeviceTypes); deviceTypeListAdapter.setChangeRunnable(() -> { LocalPreferences.putSelectedDeviceTypes(mSelectedDeviceTypes); }); mDeviceTypeListView = (ListView) v.findViewById(R.id.device_types_list); mDeviceTypeListView.setAdapter(deviceTypeListAdapter); final SeekBar.OnSeekBarChangeListener seekBarListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { onRangeChanged(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { onRangeChanged(); } @Override public void onStopTrackingTouch(SeekBar seekBar) { onRangeChanged(true); } }; mGroupIdCheckBox = (CheckBox) v.findViewById(R.id.group_id_check); mGroupIdCheckBox.setOnClickListener(view -> onRangeChanged(true)); mGroupIdSeekBar = (SeekBar) v.findViewById(R.id.group_id_seek); mGroupIdSeekBar.setMin(0x1); mGroupIdSeekBar.setMax(0xE); mGroupIdSeekBar.setOnSeekBarChangeListener(seekBarListener); mGroupIdTextView = (TextView) v.findViewById(R.id.group_id_text); mGroupFullToggle = (ToggleButton) v.findViewById(R.id.group_full_toggle); mGroupFullToggle.setOnClickListener(view -> onRangeChanged(true)); mSingleIdCheckBox = (CheckBox) v.findViewById(R.id.single_id_check); mSingleIdCheckBox.setOnClickListener(view -> onRangeChanged(true)); mSingleIdSeekBar = (SeekBar) v.findViewById(R.id.single_id_seek); mSingleIdSeekBar.setMin(0x1); mSingleIdSeekBar.setMax(0xE); mSingleIdSeekBar.setOnSeekBarChangeListener(seekBarListener); mSingleIdTextView = (TextView) v.findViewById(R.id.single_id_text); mSingleFullToggle = (ToggleButton) v.findViewById(R.id.single_full_toggle); mSingleFullToggle.setOnClickListener(view -> onRangeChanged(true)); mRangeTextView = (TextView) v.findViewById(R.id.range_text); ((Button)v.findViewById(R.id.add_selected_button)).setOnClickListener(view -> addSelectedDevices()); ((Button)v.findViewById(R.id.add_range_button)).setOnClickListener(view -> addAllDevicesInRange()); ((Button)v.findViewById(R.id.remove_all_button)).setOnClickListener(view -> removeAllDevices()); ((Button)v.findViewById(R.id.load_button)).setOnClickListener(view -> loadDeviceList()); ((Button)v.findViewById(R.id.save_button)).setOnClickListener(view -> saveDeviceList()); final List<String> intervalTexts = new ArrayList<>(); intervalTexts.add("0"); intervalTexts.add("500"); intervalTexts.add("1000"); intervalTexts.add("2000"); intervalTexts.add("3000"); mPollingIntervalsSpinner = (Spinner) v.findViewById(R.id.polling_intervals_spinner); mPollingIntervalsSpinner.setEnabled(!mNetwork.isSlaveMode()); mPollingIntervalsSpinner.setAdapter(new ArrayAdapter<>(mContext, R.layout.spinner_item, intervalTexts)); mPollingIntervalsSpinner.setSelection(LocalPreferences.getInt(Pref.POLLING_INTERVAL_INDEX, 2)); mPollingIntervalsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Object selectedItem = mPollingIntervalsSpinner.getSelectedItem(); if (selectedItem != null) { long pollingIntervalMs = Long.valueOf(selectedItem.toString()).longValue(); mNetwork.getDeviceStatePoller().setPollIntervalMs(pollingIntervalMs); LocalPreferences.putInt(Pref.POLLING_INTERVAL_INDEX, position); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); mAutoTestToggle = (ToggleButton) v.findViewById(R.id.auto_test_toggle); mAutoTestToggle.setEnabled(!mNetwork.isSlaveMode()); mAutoTestToggle.setOnClickListener(view -> setAutoTestOn(((Checkable)view).isChecked())); mAutoTestToggle.setOnCheckedChangeListener((view, isChecked) -> { if (isChecked) { mNetwork.getDeviceStatePoller().setPaused(true); mDeviceTestPart.startTest(getCurrentDevices()); } else { mDeviceTestPart.stopTest(); mNetwork.getDeviceStatePoller().setPaused(false); } }); mDeviceCountText = v.findViewById(R.id.device_count_text); mDeviceListView = (RecyclerView) v.findViewById(R.id.device_list); mDeviceListView.setLayoutManager(new CustomLayoutManager(mContext)); mDeviceListView.setAdapter(new NullRecyclerViewAdapter()); mDiscoveryProgress = (ProgressBar) v.findViewById(R.id.discovery_progress); mDeviceDetailPart = (ViewGroup) v.findViewById(R.id.device_detail_part); mDeviceInfoView = (DeviceInfoView) v.findViewById(R.id.device_info_view); mDeviceControlArea = (ViewGroup) v.findViewById(R.id.device_control_area); mDeviceTestPart = (DeviceTestPartView) v.findViewById(R.id.device_test_part);
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde; public class MainFragment extends Fragment { private static final String TAG = "HomeTestFragment"; private static final String SAVED_DEVICES_FILENAME = "saved_devices"; private final Context mContext; private final HomeNetwork mNetwork; private HomeDevice mSelectedDevice; private CheckBox mEventLogCheck; private CheckBox mTxRxLogCheck; private ToggleButton mAutoScrollToggle; private DebugLogView mDebugLogView; private ToggleButton mDiscoveryToggle; private ListView mDeviceTypeListView; private CheckBox mGroupIdCheckBox; private SeekBar mGroupIdSeekBar; private TextView mGroupIdTextView; private ToggleButton mGroupFullToggle; private CheckBox mSingleIdCheckBox; private SeekBar mSingleIdSeekBar; private TextView mSingleIdTextView; private ToggleButton mSingleFullToggle; private TextView mRangeTextView; private Spinner mPollingIntervalsSpinner; private ToggleButton mAutoTestToggle; private TextView mDeviceCountText; private RecyclerView mDeviceListView; private ProgressBar mDiscoveryProgress; private ViewGroup mDeviceDetailPart; private DeviceInfoView mDeviceInfoView; private ViewGroup mDeviceControlArea; private DeviceTestPartView mDeviceTestPart; private Map<String, Integer> mDeviceToKsIdMap = new TreeMap<>(); private Set<String> mSelectedDeviceTypes = new HashSet<>(); private DeviceDiscovery.Callback mDiscoveryCallback = new DeviceDiscovery.Callback() { List<HomeDevice> mStagedDevices = new ArrayList<>(); @Override public void onDiscoveryStarted() { debug("onDiscoveryStarted "); mDiscoveryProgress.setVisibility(View.VISIBLE); mStagedDevices.clear(); } @Override public void onDiscoveryFinished() { debug("onDiscoveryFinished "); if (mStagedDevices.size() > 0) { for (HomeDevice device: mStagedDevices) { mNetwork.addDevice(device); } mStagedDevices.clear(); } // Wait for a while until new devices are up to date by polling its state new Handler().postDelayed(() -> { updateDeviceList(); mDiscoveryProgress.setVisibility(View.GONE); mDiscoveryToggle.setChecked(false); }, 1000); } @Override public void onDeviceDiscovered(HomeDevice device) { final String clsName = device.getClass().getSimpleName(); debug("onDeviceDiscovered " + clsName + " " + device.getAddress()); mStagedDevices.add(device); } }; private HomeDevice.Callback mDeviceCallback = new HomeDevice.Callback() { public void onPropertyChanged(HomeDevice device, PropertyMap props) { for (String name : props.toMap().keySet()) { debug("onPropertyChanged - " + name + " : " + device.dc().getProperty(name).getValue()); } } public void onErrorOccurred(HomeDevice device, int error) { debug("onErrorOccurred:" + error); } }; public MainFragment(Context context, HomeNetwork network) { mContext = context; mNetwork = network; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNetwork.getDeviceDiscovery().addCallback(mDiscoveryCallback); mDeviceToKsIdMap.put("AirConditioner", 0x02); mDeviceToKsIdMap.put("BatchSwitch", 0x33); mDeviceToKsIdMap.put("Curtain", 0x13); mDeviceToKsIdMap.put("DoorLock", 0x31); mDeviceToKsIdMap.put("GasValve", 0x12); mDeviceToKsIdMap.put("HouseMeter", 0x30); mDeviceToKsIdMap.put("Light", 0x0E); mDeviceToKsIdMap.put("PowerSaver", 0x39); mDeviceToKsIdMap.put("Thermostat", 0x36); mDeviceToKsIdMap.put("Ventilation", 0x32); mSelectedDeviceTypes = LocalPreferences.getSelectedDeviceTypes(); } @SuppressLint("ClickableViewAccessibility") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance) { final View v = inflater.inflate(R.layout.main, container, false); v.findViewById(R.id.clear_log_button).setOnClickListener(view -> { mDebugLogView.clear(); mAutoScrollToggle.setChecked(true); mDebugLogView.setAutoScroll(true); }); mEventLogCheck = (CheckBox) v.findViewById(R.id.event_log_check); mEventLogCheck.setChecked(LocalPreferences.getBoolean(Pref.DEBUG_LOG_EVENT_ENABLED, true)); mEventLogCheck.setOnClickListener(view -> updateLogFilter()); mTxRxLogCheck = (CheckBox) v.findViewById(R.id.txrx_log_check); mTxRxLogCheck.setChecked(LocalPreferences.getBoolean(Pref.DEBUG_LOG_TXRX_ENABLED, true)); mTxRxLogCheck.setOnClickListener(view -> updateLogFilter()); mAutoScrollToggle = (ToggleButton) v.findViewById(R.id.auto_scroll_toggle);; mAutoScrollToggle.setOnClickListener(view -> mDebugLogView.setAutoScroll(((Checkable)view).isChecked())); mDebugLogView = (DebugLogView) v.findViewById(R.id.debug_log_view); DebugLog.setLogger(mDebugLogView); mDebugLogView.setOnRawTouchListener((view, e) -> { if (e.getAction() == MotionEvent.ACTION_DOWN) { mAutoScrollToggle.setChecked(false); mDebugLogView.setAutoScroll(false); } return false; }); ((Button)v.findViewById(R.id.select_all_button)).setOnClickListener(view -> selectAllTypes()); ((Button)v.findViewById(R.id.deselect_all_button)).setOnClickListener(view -> deselectAllTypes()); ((Button)v.findViewById(R.id.reset_range_button)).setOnClickListener(view -> resetRanges()); mDiscoveryToggle = (ToggleButton) v.findViewById(R.id.discovery_toggle); mDiscoveryToggle.setEnabled(!mNetwork.isSlaveMode()); mDiscoveryToggle.setOnClickListener(view -> setDiscoveryOn(((Checkable)view).isChecked())); final CheckableListAdapter<String> deviceTypeListAdapter = new CheckableListAdapter<>( mContext, new ArrayList(mDeviceToKsIdMap.keySet()), mSelectedDeviceTypes); deviceTypeListAdapter.setChangeRunnable(() -> { LocalPreferences.putSelectedDeviceTypes(mSelectedDeviceTypes); }); mDeviceTypeListView = (ListView) v.findViewById(R.id.device_types_list); mDeviceTypeListView.setAdapter(deviceTypeListAdapter); final SeekBar.OnSeekBarChangeListener seekBarListener = new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { onRangeChanged(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { onRangeChanged(); } @Override public void onStopTrackingTouch(SeekBar seekBar) { onRangeChanged(true); } }; mGroupIdCheckBox = (CheckBox) v.findViewById(R.id.group_id_check); mGroupIdCheckBox.setOnClickListener(view -> onRangeChanged(true)); mGroupIdSeekBar = (SeekBar) v.findViewById(R.id.group_id_seek); mGroupIdSeekBar.setMin(0x1); mGroupIdSeekBar.setMax(0xE); mGroupIdSeekBar.setOnSeekBarChangeListener(seekBarListener); mGroupIdTextView = (TextView) v.findViewById(R.id.group_id_text); mGroupFullToggle = (ToggleButton) v.findViewById(R.id.group_full_toggle); mGroupFullToggle.setOnClickListener(view -> onRangeChanged(true)); mSingleIdCheckBox = (CheckBox) v.findViewById(R.id.single_id_check); mSingleIdCheckBox.setOnClickListener(view -> onRangeChanged(true)); mSingleIdSeekBar = (SeekBar) v.findViewById(R.id.single_id_seek); mSingleIdSeekBar.setMin(0x1); mSingleIdSeekBar.setMax(0xE); mSingleIdSeekBar.setOnSeekBarChangeListener(seekBarListener); mSingleIdTextView = (TextView) v.findViewById(R.id.single_id_text); mSingleFullToggle = (ToggleButton) v.findViewById(R.id.single_full_toggle); mSingleFullToggle.setOnClickListener(view -> onRangeChanged(true)); mRangeTextView = (TextView) v.findViewById(R.id.range_text); ((Button)v.findViewById(R.id.add_selected_button)).setOnClickListener(view -> addSelectedDevices()); ((Button)v.findViewById(R.id.add_range_button)).setOnClickListener(view -> addAllDevicesInRange()); ((Button)v.findViewById(R.id.remove_all_button)).setOnClickListener(view -> removeAllDevices()); ((Button)v.findViewById(R.id.load_button)).setOnClickListener(view -> loadDeviceList()); ((Button)v.findViewById(R.id.save_button)).setOnClickListener(view -> saveDeviceList()); final List<String> intervalTexts = new ArrayList<>(); intervalTexts.add("0"); intervalTexts.add("500"); intervalTexts.add("1000"); intervalTexts.add("2000"); intervalTexts.add("3000"); mPollingIntervalsSpinner = (Spinner) v.findViewById(R.id.polling_intervals_spinner); mPollingIntervalsSpinner.setEnabled(!mNetwork.isSlaveMode()); mPollingIntervalsSpinner.setAdapter(new ArrayAdapter<>(mContext, R.layout.spinner_item, intervalTexts)); mPollingIntervalsSpinner.setSelection(LocalPreferences.getInt(Pref.POLLING_INTERVAL_INDEX, 2)); mPollingIntervalsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Object selectedItem = mPollingIntervalsSpinner.getSelectedItem(); if (selectedItem != null) { long pollingIntervalMs = Long.valueOf(selectedItem.toString()).longValue(); mNetwork.getDeviceStatePoller().setPollIntervalMs(pollingIntervalMs); LocalPreferences.putInt(Pref.POLLING_INTERVAL_INDEX, position); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); mAutoTestToggle = (ToggleButton) v.findViewById(R.id.auto_test_toggle); mAutoTestToggle.setEnabled(!mNetwork.isSlaveMode()); mAutoTestToggle.setOnClickListener(view -> setAutoTestOn(((Checkable)view).isChecked())); mAutoTestToggle.setOnCheckedChangeListener((view, isChecked) -> { if (isChecked) { mNetwork.getDeviceStatePoller().setPaused(true); mDeviceTestPart.startTest(getCurrentDevices()); } else { mDeviceTestPart.stopTest(); mNetwork.getDeviceStatePoller().setPaused(false); } }); mDeviceCountText = v.findViewById(R.id.device_count_text); mDeviceListView = (RecyclerView) v.findViewById(R.id.device_list); mDeviceListView.setLayoutManager(new CustomLayoutManager(mContext)); mDeviceListView.setAdapter(new NullRecyclerViewAdapter()); mDiscoveryProgress = (ProgressBar) v.findViewById(R.id.discovery_progress); mDeviceDetailPart = (ViewGroup) v.findViewById(R.id.device_detail_part); mDeviceInfoView = (DeviceInfoView) v.findViewById(R.id.device_info_view); mDeviceControlArea = (ViewGroup) v.findViewById(R.id.device_control_area); mDeviceTestPart = (DeviceTestPartView) v.findViewById(R.id.device_test_part);
mDeviceTestPart.getTestRunner().addCallback(new DeviceTestCallback() {
1
2023-11-10 01:19:44+00:00
16k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/client/core/StateManager.java
[ { "identifier": "FluxLogoState", "path": "src/main/java/io/xlorey/FluxLoader/client/states/FluxLogoState.java", "snippet": "public class FluxLogoState extends GameState {\n\n /**\n * Current transparency value\n */\n private float alpha = 0.0f;\n\n /**\n * Logo display time\n */...
import io.xlorey.FluxLoader.client.states.FluxLogoState; import io.xlorey.FluxLoader.utils.Logger; import zombie.GameWindow; import zombie.gameStates.GameState; import zombie.gameStates.TISLogoState; import java.util.List;
13,062
package io.xlorey.FluxLoader.client.core; /** * Game state manager */ public class StateManager { /** * Initializing and adding the FluxLoader logo to display when loading the game */ private static void initLogoState() { List<GameState> states = GameWindow.states.States; GameState tisLogoState = states.get(0); if (tisLogoState instanceof TISLogoState) { GameWindow.states.States.add(1, new FluxLogoState()); GameWindow.states.LoopToState = 2; } else {
package io.xlorey.FluxLoader.client.core; /** * Game state manager */ public class StateManager { /** * Initializing and adding the FluxLoader logo to display when loading the game */ private static void initLogoState() { List<GameState> states = GameWindow.states.States; GameState tisLogoState = states.get(0); if (tisLogoState instanceof TISLogoState) { GameWindow.states.States.add(1, new FluxLogoState()); GameWindow.states.LoopToState = 2; } else {
Logger.printLog(String.format(
1
2023-11-16 09:05:44+00:00
16k
EmonerRobotics/2023Robot
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "IntakeConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class IntakeConstants{\n\n public static final double kEncoderTick2Meter = 1.0 / 4096.0 * 0.1 * Math.PI;\n\n //üst sistem joystick sabitleri\n public static final int Joystick2 = 1; //usb por...
import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab; import edu.wpi.first.wpilibj.smartdashboard.Field2d; import edu.wpi.first.wpilibj.smartdashboard.FieldObject2d; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.RunCommand; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import edu.wpi.first.wpilibj2.command.button.JoystickButton; import frc.robot.Constants.IntakeConstants; import frc.robot.commands.AutoElevator; import frc.robot.commands.AutoIntake; import frc.robot.commands.DriveWithJoysticks; import frc.robot.commands.GetInRange; import frc.robot.commands.IntakeCommand; import frc.robot.commands.LiftCommand; import frc.robot.commands.PneumaticCommand; import frc.robot.commands.AutoElevator.ElevatorPosition; import frc.robot.commands.AutoIntake.IntakePosition; import frc.robot.commands.GetInRange.LimelightPositionCheck; import frc.robot.commands.autonomous.AutoBalance; import frc.robot.commands.autonomous.AutoCommand; import frc.robot.commands.autonomous.OnePieceCharge; import frc.robot.poseestimation.PoseEstimation; import frc.robot.subsystems.IntakeSubsystem; import frc.robot.subsystems.LiftSubsystem; import frc.robot.subsystems.LimelightSubsystem; import frc.robot.subsystems.PneumaticSubsystem; import frc.robot.subsystems.drivetrain.Drivetrain; import frc.robot.utils.AllianceUtils; import com.pathplanner.lib.server.PathPlannerServer;
10,808
// 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 trigger mappings) should be declared here. */ public class RobotContainer { //Limelight public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem(); //Intake public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); //Pneumatic public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem(); //Lift public static final LiftSubsystem liftSubsystem = new LiftSubsystem(); public static final ShuffleboardTab driveSettingsTab = Shuffleboard.getTab("Drive Settings"); public static final ShuffleboardTab autoTab = Shuffleboard.getTab("Auto"); public static final ShuffleboardTab swerveTab = Shuffleboard.getTab("Swerve"); public static final Joystick joystick1 = new Joystick(0); public static final Joystick joystick2 = new Joystick(IntakeConstants.AngleController); public static final Drivetrain drivetrain = new Drivetrain(); public static final PoseEstimation poseEstimation = new PoseEstimation(); public static final SendableChooser<String> drivePresetsChooser = new SendableChooser<>(); public static Field2d field = new Field2d(); public static Field2d nodeSelector = new Field2d(); private final FieldObject2d startingPosition = field.getObject("Starting Position"); private final FieldObject2d autoBalanceStartingPosition = field.getObject("Auto Balance Starting Position"); private DriveWithJoysticks driveCommand = new DriveWithJoysticks(drivetrain, poseEstimation, joystick1); private AutoBalance autoBalanceCommand = new AutoBalance(drivetrain); public static SendableChooser<String> autoSelector; //private static AutoElevator autoElevator; /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { //autoElevator = new AutoElevator(liftSubsystem, 0); //Intake intakeSubsystem.setDefaultCommand(new IntakeCommand(intakeSubsystem, () -> -joystick2.getRawAxis(IntakeConstants.AngleController))); //Pneumatic //pneumaticSubsystem.setDefaultCommand(new PneumaticCommand(pneumaticSubsystem, false, true)); //Lift
// 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 trigger mappings) should be declared here. */ public class RobotContainer { //Limelight public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem(); //Intake public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); //Pneumatic public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem(); //Lift public static final LiftSubsystem liftSubsystem = new LiftSubsystem(); public static final ShuffleboardTab driveSettingsTab = Shuffleboard.getTab("Drive Settings"); public static final ShuffleboardTab autoTab = Shuffleboard.getTab("Auto"); public static final ShuffleboardTab swerveTab = Shuffleboard.getTab("Swerve"); public static final Joystick joystick1 = new Joystick(0); public static final Joystick joystick2 = new Joystick(IntakeConstants.AngleController); public static final Drivetrain drivetrain = new Drivetrain(); public static final PoseEstimation poseEstimation = new PoseEstimation(); public static final SendableChooser<String> drivePresetsChooser = new SendableChooser<>(); public static Field2d field = new Field2d(); public static Field2d nodeSelector = new Field2d(); private final FieldObject2d startingPosition = field.getObject("Starting Position"); private final FieldObject2d autoBalanceStartingPosition = field.getObject("Auto Balance Starting Position"); private DriveWithJoysticks driveCommand = new DriveWithJoysticks(drivetrain, poseEstimation, joystick1); private AutoBalance autoBalanceCommand = new AutoBalance(drivetrain); public static SendableChooser<String> autoSelector; //private static AutoElevator autoElevator; /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { //autoElevator = new AutoElevator(liftSubsystem, 0); //Intake intakeSubsystem.setDefaultCommand(new IntakeCommand(intakeSubsystem, () -> -joystick2.getRawAxis(IntakeConstants.AngleController))); //Pneumatic //pneumaticSubsystem.setDefaultCommand(new PneumaticCommand(pneumaticSubsystem, false, true)); //Lift
liftSubsystem.setDefaultCommand(new LiftCommand(liftSubsystem, () -> -joystick2.getRawAxis(5)));
6
2023-11-18 14:02:20+00:00
16k